2 * threads.c: Thread support internal calls
5 * Dick Porter (dick@ximian.com)
6 * Paolo Molaro (lupus@ximian.com)
7 * Patrik Torstensson (patrik.torstensson@labs2.com)
9 * Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
10 * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
19 #include <mono/metadata/object.h>
20 #include <mono/metadata/domain-internals.h>
21 #include <mono/metadata/profiler-private.h>
22 #include <mono/metadata/threads.h>
23 #include <mono/metadata/threadpool.h>
24 #include <mono/metadata/threads-types.h>
25 #include <mono/metadata/exception.h>
26 #include <mono/metadata/environment.h>
27 #include <mono/metadata/monitor.h>
28 #include <mono/metadata/gc-internal.h>
29 #include <mono/metadata/marshal.h>
30 #include <mono/io-layer/io-layer.h>
31 #ifndef PLATFORM_WIN32
32 #include <mono/io-layer/threads.h>
34 #include <mono/metadata/object-internals.h>
35 #include <mono/metadata/mono-debug-debugger.h>
36 #include <mono/utils/mono-compiler.h>
37 #include <mono/utils/mono-mmap.h>
38 #include <mono/utils/mono-membar.h>
39 #include <mono/utils/mono-time.h>
41 #include <mono/metadata/gc-internal.h>
43 /*#define THREAD_DEBUG(a) do { a; } while (0)*/
44 #define THREAD_DEBUG(a)
45 /*#define THREAD_WAIT_DEBUG(a) do { a; } while (0)*/
46 #define THREAD_WAIT_DEBUG(a)
47 /*#define LIBGC_DEBUG(a) do { a; } while (0)*/
48 #define LIBGC_DEBUG(a)
50 /* Provide this for systems with glib < 2.6 */
51 #ifndef G_GSIZE_FORMAT
52 # if GLIB_SIZEOF_LONG == 8
53 # define G_GSIZE_FORMAT "lu"
55 # define G_GSIZE_FORMAT "u"
61 guint32 (*func)(void *);
78 typedef struct _MonoThreadDomainTls MonoThreadDomainTls;
79 struct _MonoThreadDomainTls {
80 MonoThreadDomainTls *next;
88 MonoThreadDomainTls *freelist;
93 MonoHazardousFreeFunc free_func;
96 /* Number of cached culture objects in the MonoThread->cached_culture_info array
97 * (per-type): we use the first NUM entries for CultureInfo and the last for
98 * UICultureInfo. So the size of the array is really NUM_CACHED_CULTURES * 2.
100 #define NUM_CACHED_CULTURES 4
101 #define CULTURES_START_IDX 0
102 #define UICULTURES_START_IDX NUM_CACHED_CULTURES
104 /* Controls access to the 'threads' hash table */
105 #define mono_threads_lock() EnterCriticalSection (&threads_mutex)
106 #define mono_threads_unlock() LeaveCriticalSection (&threads_mutex)
107 static CRITICAL_SECTION threads_mutex;
109 /* Controls access to context static data */
110 #define mono_contexts_lock() EnterCriticalSection (&contexts_mutex)
111 #define mono_contexts_unlock() LeaveCriticalSection (&contexts_mutex)
112 static CRITICAL_SECTION contexts_mutex;
114 /* Holds current status of static data heap */
115 static StaticDataInfo thread_static_info;
116 static StaticDataInfo context_static_info;
118 /* The hash of existing threads (key is thread ID) that need joining
121 static MonoGHashTable *threads=NULL;
124 * Threads which are starting up and they are not in the 'threads' hash yet.
125 * When handle_store is called for a thread, it will be removed from this hash table.
126 * Protected by mono_threads_lock ().
128 static MonoGHashTable *threads_starting_up = NULL;
130 /* Maps a MonoThread to its start argument */
131 /* Protected by mono_threads_lock () */
132 static MonoGHashTable *thread_start_args = NULL;
134 /* The TLS key that holds the MonoObject assigned to each thread */
135 static guint32 current_object_key = -1;
137 #ifdef HAVE_KW_THREAD
138 /* we need to use both the Tls* functions and __thread because
139 * the gc needs to see all the threads
141 static __thread MonoThread * tls_current_object MONO_TLS_FAST;
142 #define SET_CURRENT_OBJECT(x) do { \
143 tls_current_object = x; \
144 TlsSetValue (current_object_key, x); \
146 #define GET_CURRENT_OBJECT() tls_current_object
148 #define SET_CURRENT_OBJECT(x) TlsSetValue (current_object_key, x)
149 #define GET_CURRENT_OBJECT() (MonoThread*) TlsGetValue (current_object_key)
152 /* function called at thread start */
153 static MonoThreadStartCB mono_thread_start_cb = NULL;
155 /* function called at thread attach */
156 static MonoThreadAttachCB mono_thread_attach_cb = NULL;
158 /* function called at thread cleanup */
159 static MonoThreadCleanupFunc mono_thread_cleanup_fn = NULL;
161 /* function called to notify the runtime about a pending exception on the current thread */
162 static MonoThreadNotifyPendingExcFunc mono_thread_notify_pending_exc_fn = NULL;
164 /* The default stack size for each thread */
165 static guint32 default_stacksize = 0;
166 #define default_stacksize_for_thread(thread) ((thread)->stack_size? (thread)->stack_size: default_stacksize)
168 static void thread_adjust_static_data (MonoThread *thread);
169 static void mono_init_static_data_info (StaticDataInfo *static_data);
170 static guint32 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align);
171 static gboolean mono_thread_resume (MonoThread* thread);
172 static void mono_thread_start (MonoThread *thread);
173 static void signal_thread_state_change (MonoThread *thread);
175 static MonoException* mono_thread_execute_interruption (MonoThread *thread);
177 /* Spin lock for InterlockedXXX 64 bit functions */
178 #define mono_interlocked_lock() EnterCriticalSection (&interlocked_mutex)
179 #define mono_interlocked_unlock() LeaveCriticalSection (&interlocked_mutex)
180 static CRITICAL_SECTION interlocked_mutex;
182 /* global count of thread interruptions requested */
183 static gint32 thread_interruption_requested = 0;
185 /* Event signaled when a thread changes its background mode */
186 static HANDLE background_change_event;
188 /* The table for small ID assignment */
189 static CRITICAL_SECTION small_id_mutex;
190 static int small_id_table_size = 0;
191 static int small_id_next = 0;
192 static int highest_small_id = -1;
193 static MonoThread **small_id_table = NULL;
195 /* The hazard table */
196 #define HAZARD_TABLE_MAX_SIZE 16384 /* There cannot be more threads than this number. */
197 static volatile int hazard_table_size = 0;
198 static MonoThreadHazardPointers * volatile hazard_table = NULL;
200 /* The table where we keep pointers to blocks to be freed but that
201 have to wait because they're guarded by a hazard pointer. */
202 static CRITICAL_SECTION delayed_free_table_mutex;
203 static GArray *delayed_free_table = NULL;
205 static gboolean shutting_down = FALSE;
208 mono_thread_get_tls_key (void)
210 return current_object_key;
214 mono_thread_get_tls_offset (void)
217 MONO_THREAD_VAR_OFFSET (tls_current_object,offset);
221 /* handle_store() and handle_remove() manage the array of threads that
222 * still need to be waited for when the main thread exits.
224 * If handle_store() returns FALSE the thread must not be started
225 * because Mono is shutting down.
227 static gboolean handle_store(MonoThread *thread)
229 mono_threads_lock ();
231 THREAD_DEBUG (g_message ("%s: thread %p ID %"G_GSIZE_FORMAT, __func__, thread, (gsize)thread->tid));
233 if (threads_starting_up)
234 mono_g_hash_table_remove (threads_starting_up, thread);
237 mono_threads_unlock ();
242 MONO_GC_REGISTER_ROOT (threads);
243 threads=mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
246 /* We don't need to duplicate thread->handle, because it is
247 * only closed when the thread object is finalized by the GC.
249 mono_g_hash_table_insert(threads, (gpointer)(gsize)(thread->tid),
252 mono_threads_unlock ();
257 static gboolean handle_remove(MonoThread *thread)
260 gsize tid = thread->tid;
262 THREAD_DEBUG (g_message ("%s: thread ID %"G_GSIZE_FORMAT, __func__, tid));
264 mono_threads_lock ();
267 /* We have to check whether the thread object for the
268 * tid is still the same in the table because the
269 * thread might have been destroyed and the tid reused
270 * in the meantime, in which case the tid would be in
271 * the table, but with another thread object.
273 if (mono_g_hash_table_lookup (threads, (gpointer)tid) == thread) {
274 mono_g_hash_table_remove (threads, (gpointer)tid);
283 mono_threads_unlock ();
285 /* Don't close the handle here, wait for the object finalizer
286 * to do it. Otherwise, the following race condition applies:
288 * 1) Thread exits (and handle_remove() closes the handle)
290 * 2) Some other handle is reassigned the same slot
292 * 3) Another thread tries to join the first thread, and
293 * blocks waiting for the reassigned handle to be signalled
294 * (which might never happen). This is possible, because the
295 * thread calling Join() still has a reference to the first
302 * Allocate a small thread id.
304 * FIXME: The biggest part of this function is very similar to
305 * domain_id_alloc() in domain.c and should be merged.
308 small_id_alloc (MonoThread *thread)
312 EnterCriticalSection (&small_id_mutex);
314 if (!small_id_table) {
315 small_id_table_size = 2;
316 small_id_table = mono_gc_alloc_fixed (small_id_table_size * sizeof (MonoThread*), NULL);
318 for (i = small_id_next; i < small_id_table_size; ++i) {
319 if (!small_id_table [i]) {
325 for (i = 0; i < small_id_next; ++i) {
326 if (!small_id_table [i]) {
333 MonoThread **new_table;
334 int new_size = small_id_table_size * 2;
335 if (new_size >= (1 << 16))
336 g_assert_not_reached ();
337 id = small_id_table_size;
338 new_table = mono_gc_alloc_fixed (new_size * sizeof (MonoThread*), NULL);
339 memcpy (new_table, small_id_table, small_id_table_size * sizeof (void*));
340 mono_gc_free_fixed (small_id_table);
341 small_id_table = new_table;
342 small_id_table_size = new_size;
344 thread->small_id = id;
345 g_assert (small_id_table [id] == NULL);
346 small_id_table [id] = thread;
348 if (small_id_next > small_id_table_size)
351 if (id >= hazard_table_size) {
353 int pagesize = mono_pagesize ();
354 int num_pages = (hazard_table_size * sizeof (MonoThreadHazardPointers) + pagesize - 1) / pagesize;
356 if (hazard_table == NULL) {
357 hazard_table = mono_valloc (NULL,
358 sizeof (MonoThreadHazardPointers) * HAZARD_TABLE_MAX_SIZE,
362 g_assert (hazard_table != NULL);
363 page_addr = (guint8*)hazard_table + num_pages * pagesize;
365 g_assert (id < HAZARD_TABLE_MAX_SIZE);
367 mono_mprotect (page_addr, pagesize, MONO_MMAP_READ | MONO_MMAP_WRITE);
370 hazard_table_size = num_pages * pagesize / sizeof (MonoThreadHazardPointers);
372 g_assert (id < hazard_table_size);
374 hazard_table [id].hazard_pointers [0] = NULL;
375 hazard_table [id].hazard_pointers [1] = NULL;
378 if (id > highest_small_id) {
379 highest_small_id = id;
380 mono_memory_write_barrier ();
383 LeaveCriticalSection (&small_id_mutex);
389 small_id_free (int id)
391 g_assert (id >= 0 && id < small_id_table_size);
392 g_assert (small_id_table [id] != NULL);
394 small_id_table [id] = NULL;
398 is_pointer_hazardous (gpointer p)
401 int highest = highest_small_id;
403 g_assert (highest < hazard_table_size);
405 for (i = 0; i <= highest; ++i) {
406 if (hazard_table [i].hazard_pointers [0] == p
407 || hazard_table [i].hazard_pointers [1] == p)
414 MonoThreadHazardPointers*
415 mono_hazard_pointer_get (void)
417 MonoThread *current_thread = mono_thread_current ();
419 if (!(current_thread && current_thread->small_id >= 0)) {
420 static MonoThreadHazardPointers emerg_hazard_table;
421 g_warning ("Thread %p may have been prematurely finalized", current_thread);
422 return &emerg_hazard_table;
425 return &hazard_table [current_thread->small_id];
429 try_free_delayed_free_item (int index)
431 if (delayed_free_table->len > index) {
432 DelayedFreeItem item = { NULL, NULL };
434 EnterCriticalSection (&delayed_free_table_mutex);
435 /* We have to check the length again because another
436 thread might have freed an item before we acquired
438 if (delayed_free_table->len > index) {
439 item = g_array_index (delayed_free_table, DelayedFreeItem, index);
441 if (!is_pointer_hazardous (item.p))
442 g_array_remove_index_fast (delayed_free_table, index);
446 LeaveCriticalSection (&delayed_free_table_mutex);
449 item.free_func (item.p);
454 mono_thread_hazardous_free_or_queue (gpointer p, MonoHazardousFreeFunc free_func)
458 /* First try to free a few entries in the delayed free
460 for (i = 2; i >= 0; --i)
461 try_free_delayed_free_item (i);
463 /* Now see if the pointer we're freeing is hazardous. If it
464 isn't, free it. Otherwise put it in the delay list. */
465 if (is_pointer_hazardous (p)) {
466 DelayedFreeItem item = { p, free_func };
468 ++mono_stats.hazardous_pointer_count;
470 EnterCriticalSection (&delayed_free_table_mutex);
471 g_array_append_val (delayed_free_table, item);
472 LeaveCriticalSection (&delayed_free_table_mutex);
478 mono_thread_hazardous_try_free_all (void)
483 if (!delayed_free_table)
486 len = delayed_free_table->len;
488 for (i = len - 1; i >= 0; --i)
489 try_free_delayed_free_item (i);
492 static void ensure_synch_cs_set (MonoThread *thread)
494 CRITICAL_SECTION *synch_cs;
496 if (thread->synch_cs != NULL) {
500 synch_cs = g_new0 (CRITICAL_SECTION, 1);
501 InitializeCriticalSection (synch_cs);
503 if (InterlockedCompareExchangePointer ((gpointer *)&thread->synch_cs,
504 synch_cs, NULL) != NULL) {
505 /* Another thread must have installed this CS */
506 DeleteCriticalSection (synch_cs);
512 * NOTE: this function can be called also for threads different from the current one:
513 * make sure no code called from it will ever assume it is run on the thread that is
514 * getting cleaned up.
516 static void thread_cleanup (MonoThread *thread)
518 g_assert (thread != NULL);
520 if (thread->abort_state_handle) {
521 g_assert (thread->abort_exc);
522 mono_gchandle_free (thread->abort_state_handle);
523 thread->abort_state_handle = 0;
525 thread->abort_exc = NULL;
526 thread->current_appcontext = NULL;
528 /* if the thread is not in the hash it has been removed already */
529 if (!handle_remove (thread))
531 mono_release_type_locks (thread);
533 EnterCriticalSection (thread->synch_cs);
535 thread->state |= ThreadState_Stopped;
536 thread->state &= ~ThreadState_Background;
538 LeaveCriticalSection (thread->synch_cs);
540 mono_profiler_thread_end (thread->tid);
542 if (thread == mono_thread_current ())
543 mono_thread_pop_appdomain_ref ();
545 if (thread->serialized_culture_info)
546 g_free (thread->serialized_culture_info);
548 g_free (thread->name);
550 thread->cached_culture_info = NULL;
552 mono_gc_free_fixed (thread->static_data);
553 thread->static_data = NULL;
555 if (mono_thread_cleanup_fn)
556 mono_thread_cleanup_fn (thread);
558 small_id_free (thread->small_id);
559 thread->small_id = -2;
562 static guint32 WINAPI start_wrapper(void *data)
564 struct StartInfo *start_info=(struct StartInfo *)data;
565 guint32 (*start_func)(void *);
568 MonoThread *thread=start_info->obj;
569 MonoObject *start_delegate = start_info->delegate;
571 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Start wrapper", __func__, GetCurrentThreadId ()));
573 /* We can be sure start_info->obj->tid and
574 * start_info->obj->handle have been set, because the thread
575 * was created suspended, and these values were set before the
581 SET_CURRENT_OBJECT (thread);
583 mono_monitor_init_tls ();
585 /* Every thread references the appdomain which created it */
586 mono_thread_push_appdomain_ref (start_info->domain);
588 if (!mono_domain_set (start_info->domain, FALSE)) {
589 /* No point in raising an appdomain_unloaded exception here */
590 /* FIXME: Cleanup here */
591 mono_thread_pop_appdomain_ref ();
595 start_func = start_info->func;
596 start_arg = start_info->start_arg;
598 /* This MUST be called before any managed code can be
599 * executed, as it calls the callback function that (for the
600 * jit) sets the lmf marker.
602 mono_thread_new_init (tid, &tid, start_func);
603 thread->stack_ptr = &tid;
605 LIBGC_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT",%d) Setting thread stack to %p", __func__, GetCurrentThreadId (), getpid (), thread->stack_ptr));
607 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Setting current_object_key to %p", __func__, GetCurrentThreadId (), thread));
609 mono_profiler_thread_start (tid);
611 /* On 2.0 profile (and higher), set explicitly since state might have been
613 if (mono_framework_version () != 1) {
614 if (thread->apartment_state == ThreadApartmentState_Unknown)
615 thread->apartment_state = ThreadApartmentState_MTA;
618 mono_thread_init_apartment_state ();
620 if(thread->start_notify!=NULL) {
621 /* Let the thread that called Start() know we're
624 ReleaseSemaphore (thread->start_notify, 1, NULL);
627 mono_threads_lock ();
628 mono_g_hash_table_remove (thread_start_args, thread);
629 mono_threads_unlock ();
633 thread_adjust_static_data (thread);
635 g_message ("%s: start_wrapper for %"G_GSIZE_FORMAT, __func__,
639 mono_thread_set_execution_context (thread->ec_to_set);
641 /* start_func is set only for unmanaged start functions */
643 start_func (start_arg);
646 g_assert (start_delegate != NULL);
647 args [0] = start_arg;
648 /* we may want to handle the exception here. See comment below on unhandled exceptions */
649 mono_runtime_delegate_invoke (start_delegate, args, NULL);
652 /* If the thread calls ExitThread at all, this remaining code
653 * will not be executed, but the main thread will eventually
654 * call thread_cleanup() on this thread's behalf.
657 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Start wrapper terminating", __func__, GetCurrentThreadId ()));
659 thread_cleanup (thread);
661 /* Do any cleanup needed for apartment state. This
662 * cannot be done in thread_cleanup since thread_cleanup could be
663 * called for a thread other than the current thread.
664 * mono_thread_cleanup_apartment_state cleans up apartment
665 * for the current thead */
666 mono_thread_cleanup_apartment_state ();
668 /* Remove the reference to the thread object in the TLS data,
669 * so the thread object can be finalized. This won't be
670 * reached if the thread threw an uncaught exception, so those
671 * thread handles will stay referenced :-( (This is due to
672 * missing support for scanning thread-specific data in the
673 * Boehm GC - the io-layer keeps a GC-visible hash of pointers
676 SET_CURRENT_OBJECT (NULL);
681 void mono_thread_new_init (gsize tid, gpointer stack_start, gpointer func)
683 if (mono_thread_start_cb) {
684 mono_thread_start_cb (tid, stack_start, func);
688 void mono_threads_set_default_stacksize (guint32 stacksize)
690 default_stacksize = stacksize;
693 guint32 mono_threads_get_default_stacksize (void)
695 return default_stacksize;
699 * mono_create_thread:
701 * This is a wrapper around CreateThread which handles differences in the type of
702 * the the 'tid' argument.
704 gpointer mono_create_thread (WapiSecurityAttributes *security,
705 guint32 stacksize, WapiThreadStart start,
706 gpointer param, guint32 create, gsize *tid)
710 #ifdef PLATFORM_WIN32
713 res = CreateThread (security, stacksize, start, param, create, &real_tid);
717 res = CreateThread (security, stacksize, start, param, create, tid);
723 MonoThread* mono_thread_create_internal (MonoDomain *domain, gpointer func, gpointer arg, gboolean threadpool_thread)
726 HANDLE thread_handle;
727 struct StartInfo *start_info;
730 thread=(MonoThread *)mono_object_new (domain,
731 mono_defaults.thread_class);
733 start_info=g_new0 (struct StartInfo, 1);
734 start_info->func = func;
735 start_info->obj = thread;
736 start_info->domain = domain;
737 start_info->start_arg = arg;
739 mono_threads_lock ();
741 mono_threads_unlock ();
744 if (threads_starting_up == NULL) {
745 MONO_GC_REGISTER_ROOT (threads_starting_up);
746 threads_starting_up = mono_g_hash_table_new (NULL, NULL);
748 if (thread_start_args == NULL) {
749 MONO_GC_REGISTER_ROOT (thread_start_args);
750 thread_start_args = mono_g_hash_table_new (NULL, NULL);
752 mono_g_hash_table_insert (threads_starting_up, thread, thread);
754 * The argument may be an object reference, and there is no ref to keep it alive
755 * when the new thread is started but not yet registered with the collector. So
756 * we store it in a GC tracked hash table.
758 mono_g_hash_table_insert (thread_start_args, thread, start_info->start_arg);
759 mono_threads_unlock ();
761 /* Create suspended, so we can do some housekeeping before the thread
764 thread_handle = mono_create_thread (NULL, default_stacksize_for_thread (thread), (LPTHREAD_START_ROUTINE)start_wrapper, start_info,
765 CREATE_SUSPENDED, &tid);
766 THREAD_DEBUG (g_message ("%s: Started thread ID %"G_GSIZE_FORMAT" (handle %p)", __func__, tid, thread_handle));
767 if (thread_handle == NULL) {
768 /* The thread couldn't be created, so throw an exception */
769 mono_threads_lock ();
770 mono_g_hash_table_remove (threads_starting_up, thread);
771 mono_threads_unlock ();
773 mono_raise_exception (mono_get_exception_execution_engine ("Couldn't create thread"));
777 thread->handle=thread_handle;
779 thread->apartment_state=ThreadApartmentState_Unknown;
780 small_id_alloc (thread);
782 thread->synch_cs = g_new0 (CRITICAL_SECTION, 1);
783 InitializeCriticalSection (thread->synch_cs);
785 thread->threadpool_thread = threadpool_thread;
786 if (threadpool_thread)
787 mono_thread_set_state (thread, ThreadState_Background);
789 if (handle_store (thread))
790 ResumeThread (thread_handle);
796 mono_thread_create (MonoDomain *domain, gpointer func, gpointer arg)
798 mono_thread_create_internal (domain, func, arg, FALSE);
802 * mono_thread_get_stack_bounds:
804 * Return the address and size of the current threads stack. Return NULL as the
805 * stack address if the stack address cannot be determined.
808 mono_thread_get_stack_bounds (guint8 **staddr, size_t *stsize)
810 #if defined(HAVE_PTHREAD_GET_STACKSIZE_NP) && defined(HAVE_PTHREAD_GET_STACKADDR_NP)
811 *staddr = (guint8*)pthread_get_stackaddr_np (pthread_self ());
812 *stsize = pthread_get_stacksize_np (pthread_self ());
813 *staddr = (guint8*)((gssize)*staddr & ~(mono_pagesize () - 1));
815 /* FIXME: simplify the mess below */
816 #elif !defined(PLATFORM_WIN32)
818 guint8 *current = (guint8*)&attr;
820 pthread_attr_init (&attr);
821 # ifdef HAVE_PTHREAD_GETATTR_NP
822 pthread_getattr_np (pthread_self(), &attr);
824 # ifdef HAVE_PTHREAD_ATTR_GET_NP
825 pthread_attr_get_np (pthread_self(), &attr);
828 pthread_attr_getstacksize (&attr, &stsize);
837 pthread_attr_getstack (&attr, (void**)staddr, stsize);
839 g_assert ((current > *staddr) && (current < *staddr + *stsize));
842 pthread_attr_destroy (&attr);
845 /* When running under emacs, sometimes staddr is not aligned to a page size */
846 *staddr = (guint8*)((gssize)*staddr & ~(mono_pagesize () - 1));
850 mono_thread_attach (MonoDomain *domain)
853 HANDLE thread_handle;
856 if ((thread = mono_thread_current ())) {
857 if (domain != mono_domain_get ())
858 mono_domain_set (domain, TRUE);
859 /* Already attached */
863 if (!mono_gc_register_thread (&domain)) {
864 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 ());
867 thread = (MonoThread *)mono_object_new (domain,
868 mono_defaults.thread_class);
870 thread_handle = GetCurrentThread ();
871 g_assert (thread_handle);
873 tid=GetCurrentThreadId ();
876 * The handle returned by GetCurrentThread () is a pseudo handle, so it can't be used to
877 * refer to the thread from other threads for things like aborting.
879 DuplicateHandle (GetCurrentProcess (), thread_handle, GetCurrentProcess (), &thread_handle,
880 THREAD_ALL_ACCESS, TRUE, 0);
882 thread->handle=thread_handle;
884 thread->apartment_state=ThreadApartmentState_Unknown;
885 small_id_alloc (thread);
886 thread->stack_ptr = &tid;
888 thread->synch_cs = g_new0 (CRITICAL_SECTION, 1);
889 InitializeCriticalSection (thread->synch_cs);
891 THREAD_DEBUG (g_message ("%s: Attached thread ID %"G_GSIZE_FORMAT" (handle %p)", __func__, tid, thread_handle));
893 if (!handle_store (thread)) {
894 /* Mono is shutting down, so just wait for the end */
899 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Setting current_object_key to %p", __func__, GetCurrentThreadId (), thread));
901 SET_CURRENT_OBJECT (thread);
902 mono_domain_set (domain, TRUE);
904 mono_monitor_init_tls ();
906 thread_adjust_static_data (thread);
908 if (mono_thread_attach_cb) {
912 mono_thread_get_stack_bounds (&staddr, &stsize);
915 mono_thread_attach_cb (tid, &tid);
917 mono_thread_attach_cb (tid, staddr + stsize);
924 mono_thread_detach (MonoThread *thread)
926 g_return_if_fail (thread != NULL);
928 THREAD_DEBUG (g_message ("%s: mono_thread_detach for %p (%"G_GSIZE_FORMAT")", __func__, thread, (gsize)thread->tid));
930 thread_cleanup (thread);
932 SET_CURRENT_OBJECT (NULL);
934 /* Don't need to CloseHandle this thread, even though we took a
935 * reference in mono_thread_attach (), because the GC will do it
936 * when the Thread object is finalised.
943 MonoThread *thread = mono_thread_current ();
945 THREAD_DEBUG (g_message ("%s: mono_thread_exit for %p (%"G_GSIZE_FORMAT")", __func__, thread, (gsize)thread->tid));
947 thread_cleanup (thread);
948 SET_CURRENT_OBJECT (NULL);
950 /* we could add a callback here for embedders to use. */
951 if (thread == mono_thread_get_main ())
952 exit (mono_environment_exitcode_get ());
956 HANDLE ves_icall_System_Threading_Thread_Thread_internal(MonoThread *this,
959 guint32 (*start_func)(void *);
960 struct StartInfo *start_info;
966 THREAD_DEBUG (g_message("%s: Trying to start a new thread: this (%p) start (%p)", __func__, this, start));
968 ensure_synch_cs_set (this);
970 EnterCriticalSection (this->synch_cs);
972 if ((this->state & ThreadState_Unstarted) == 0) {
973 LeaveCriticalSection (this->synch_cs);
974 mono_raise_exception (mono_get_exception_thread_state ("Thread has already been started."));
980 if ((this->state & ThreadState_Aborted) != 0) {
981 LeaveCriticalSection (this->synch_cs);
986 /* This is freed in start_wrapper */
987 start_info = g_new0 (struct StartInfo, 1);
988 start_info->func = start_func;
989 start_info->start_arg = this->start_obj; /* FIXME: GC object stored in unmanaged memory */
990 start_info->delegate = start;
991 start_info->obj = this;
992 start_info->domain = mono_domain_get ();
994 this->start_notify=CreateSemaphore (NULL, 0, 0x7fffffff, NULL);
995 if(this->start_notify==NULL) {
996 LeaveCriticalSection (this->synch_cs);
997 g_warning ("%s: CreateSemaphore error 0x%x", __func__, GetLastError ());
1001 mono_threads_lock ();
1002 if (threads_starting_up == NULL) {
1003 MONO_GC_REGISTER_ROOT (threads_starting_up);
1004 threads_starting_up = mono_g_hash_table_new (NULL, NULL);
1006 mono_g_hash_table_insert (threads_starting_up, this, this);
1007 mono_threads_unlock ();
1009 thread=mono_create_thread(NULL, default_stacksize_for_thread (this), (LPTHREAD_START_ROUTINE)start_wrapper, start_info,
1010 CREATE_SUSPENDED, &tid);
1012 LeaveCriticalSection (this->synch_cs);
1013 mono_threads_lock ();
1014 mono_g_hash_table_remove (threads_starting_up, this);
1015 mono_threads_unlock ();
1016 g_warning("%s: CreateThread error 0x%x", __func__, GetLastError());
1020 this->handle=thread;
1022 small_id_alloc (this);
1024 /* Don't call handle_store() here, delay it to Start.
1025 * We can't join a thread (trying to will just block
1026 * forever) until it actually starts running, so don't
1027 * store the handle till then.
1030 mono_thread_start (this);
1032 this->state &= ~ThreadState_Unstarted;
1034 THREAD_DEBUG (g_message ("%s: Started thread ID %"G_GSIZE_FORMAT" (handle %p)", __func__, tid, thread));
1036 LeaveCriticalSection (this->synch_cs);
1041 void ves_icall_System_Threading_Thread_Thread_init (MonoThread *this)
1043 MONO_ARCH_SAVE_REGS;
1045 ensure_synch_cs_set (this);
1048 void ves_icall_System_Threading_Thread_Thread_free_internal (MonoThread *this,
1051 MONO_ARCH_SAVE_REGS;
1053 THREAD_DEBUG (g_message ("%s: Closing thread %p, handle %p", __func__, this, thread));
1055 CloseHandle (thread);
1057 DeleteCriticalSection (this->synch_cs);
1058 g_free (this->synch_cs);
1059 this->synch_cs = NULL;
1061 g_assert (!this->abort_exc && !this->abort_state_handle);
1064 static void mono_thread_start (MonoThread *thread)
1066 MONO_ARCH_SAVE_REGS;
1068 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Launching thread %p (%"G_GSIZE_FORMAT")", __func__, GetCurrentThreadId (), thread, (gsize)thread->tid));
1070 /* Only store the handle when the thread is about to be
1071 * launched, to avoid the main thread deadlocking while trying
1072 * to clean up a thread that will never be signalled.
1074 if (!handle_store (thread))
1077 ResumeThread (thread->handle);
1079 if(thread->start_notify!=NULL) {
1080 /* Wait for the thread to set up its TLS data etc, so
1081 * theres no potential race condition if someone tries
1082 * to look up the data believing the thread has
1086 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") waiting for thread %p (%"G_GSIZE_FORMAT") to start", __func__, GetCurrentThreadId (), thread, (gsize)thread->tid));
1088 WaitForSingleObjectEx (thread->start_notify, INFINITE, FALSE);
1089 CloseHandle (thread->start_notify);
1090 thread->start_notify = NULL;
1093 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Done launching thread %p (%"G_GSIZE_FORMAT")", __func__, GetCurrentThreadId (), thread, (gsize)thread->tid));
1096 void ves_icall_System_Threading_Thread_Sleep_internal(gint32 ms)
1099 MonoThread *thread = mono_thread_current ();
1101 MONO_ARCH_SAVE_REGS;
1103 THREAD_DEBUG (g_message ("%s: Sleeping for %d ms", __func__, ms));
1105 mono_thread_current_check_pending_interrupt ();
1107 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1109 res = SleepEx(ms,TRUE);
1111 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1113 if (res == WAIT_IO_COMPLETION) { /* we might have been interrupted */
1114 MonoException* exc = mono_thread_execute_interruption (thread);
1115 if (exc) mono_raise_exception (exc);
1119 void ves_icall_System_Threading_Thread_SpinWait_nop (void)
1124 ves_icall_System_Threading_Thread_GetDomainID (void)
1126 MONO_ARCH_SAVE_REGS;
1128 return mono_domain_get()->domain_id;
1132 ves_icall_System_Threading_Thread_GetName_internal (MonoThread *this_obj)
1136 ensure_synch_cs_set (this_obj);
1138 EnterCriticalSection (this_obj->synch_cs);
1140 if (!this_obj->name)
1143 str = mono_string_new_utf16 (mono_domain_get (), this_obj->name, this_obj->name_len);
1145 LeaveCriticalSection (this_obj->synch_cs);
1151 ves_icall_System_Threading_Thread_SetName_internal (MonoThread *this_obj, MonoString *name)
1153 ensure_synch_cs_set (this_obj);
1155 EnterCriticalSection (this_obj->synch_cs);
1157 if (this_obj->name) {
1158 LeaveCriticalSection (this_obj->synch_cs);
1160 mono_raise_exception (mono_get_exception_invalid_operation ("Thread.Name can only be set once."));
1164 this_obj->name = g_new (gunichar2, mono_string_length (name));
1165 memcpy (this_obj->name, mono_string_chars (name), mono_string_length (name) * 2);
1166 this_obj->name_len = mono_string_length (name);
1169 this_obj->name = NULL;
1171 LeaveCriticalSection (this_obj->synch_cs);
1175 lookup_cached_culture (MonoThread *this, MonoDomain *domain, int start_idx)
1180 if (this->cached_culture_info) {
1181 domain = mono_domain_get ();
1182 for (i = start_idx; i < start_idx + NUM_CACHED_CULTURES; ++i) {
1183 res = mono_array_get (this->cached_culture_info, MonoObject*, i);
1184 if (res && res->vtable->domain == domain)
1193 ves_icall_System_Threading_Thread_GetCachedCurrentCulture (MonoThread *this)
1195 return lookup_cached_culture (this, mono_domain_get (), CULTURES_START_IDX);
1199 ves_icall_System_Threading_Thread_GetSerializedCurrentCulture (MonoThread *this)
1203 ensure_synch_cs_set (this);
1205 EnterCriticalSection (this->synch_cs);
1207 if (this->serialized_culture_info) {
1208 res = mono_array_new (mono_domain_get (), mono_defaults.byte_class, this->serialized_culture_info_len);
1209 memcpy (mono_array_addr (res, guint8, 0), this->serialized_culture_info, this->serialized_culture_info_len);
1214 LeaveCriticalSection (this->synch_cs);
1220 cache_culture (MonoThread *this, MonoObject *culture, int start_idx)
1223 MonoDomain *domain = mono_domain_get ();
1226 int same_domain_slot = -1;
1228 ensure_synch_cs_set (this);
1230 EnterCriticalSection (this->synch_cs);
1232 if (!this->cached_culture_info)
1233 MONO_OBJECT_SETREF (this, cached_culture_info, mono_array_new_cached (mono_object_domain (this), mono_defaults.object_class, NUM_CACHED_CULTURES * 2));
1235 for (i = start_idx; i < start_idx + NUM_CACHED_CULTURES; ++i) {
1236 obj = mono_array_get (this->cached_culture_info, MonoObject*, i);
1240 /* we continue, because there may be a slot used with the same domain */
1244 if (obj->vtable->domain == domain) {
1245 same_domain_slot = i;
1249 if (same_domain_slot >= 0)
1250 mono_array_setref (this->cached_culture_info, same_domain_slot, culture);
1251 else if (free_slot >= 0)
1252 mono_array_setref (this->cached_culture_info, free_slot, culture);
1253 /* we may want to replace an existing entry here, even when no suitable slot is found */
1255 LeaveCriticalSection (this->synch_cs);
1259 ves_icall_System_Threading_Thread_SetCachedCurrentCulture (MonoThread *this, MonoObject *culture)
1261 cache_culture (this, culture, CULTURES_START_IDX);
1265 ves_icall_System_Threading_Thread_SetSerializedCurrentCulture (MonoThread *this, MonoArray *arr)
1267 ensure_synch_cs_set (this);
1269 EnterCriticalSection (this->synch_cs);
1271 if (this->serialized_culture_info)
1272 g_free (this->serialized_culture_info);
1273 this->serialized_culture_info = g_new0 (guint8, mono_array_length (arr));
1274 this->serialized_culture_info_len = mono_array_length (arr);
1275 memcpy (this->serialized_culture_info, mono_array_addr (arr, guint8, 0), mono_array_length (arr));
1277 LeaveCriticalSection (this->synch_cs);
1282 ves_icall_System_Threading_Thread_GetCachedCurrentUICulture (MonoThread *this)
1284 return lookup_cached_culture (this, mono_domain_get (), UICULTURES_START_IDX);
1288 ves_icall_System_Threading_Thread_GetSerializedCurrentUICulture (MonoThread *this)
1292 ensure_synch_cs_set (this);
1294 EnterCriticalSection (this->synch_cs);
1296 if (this->serialized_ui_culture_info) {
1297 res = mono_array_new (mono_domain_get (), mono_defaults.byte_class, this->serialized_ui_culture_info_len);
1298 memcpy (mono_array_addr (res, guint8, 0), this->serialized_ui_culture_info, this->serialized_ui_culture_info_len);
1303 LeaveCriticalSection (this->synch_cs);
1309 ves_icall_System_Threading_Thread_SetCachedCurrentUICulture (MonoThread *this, MonoObject *culture)
1311 cache_culture (this, culture, UICULTURES_START_IDX);
1315 ves_icall_System_Threading_Thread_SetSerializedCurrentUICulture (MonoThread *this, MonoArray *arr)
1317 ensure_synch_cs_set (this);
1319 EnterCriticalSection (this->synch_cs);
1321 if (this->serialized_ui_culture_info)
1322 g_free (this->serialized_ui_culture_info);
1323 this->serialized_ui_culture_info = g_new0 (guint8, mono_array_length (arr));
1324 this->serialized_ui_culture_info_len = mono_array_length (arr);
1325 memcpy (this->serialized_ui_culture_info, mono_array_addr (arr, guint8, 0), mono_array_length (arr));
1327 LeaveCriticalSection (this->synch_cs);
1330 /* the jit may read the compiled code of this function */
1332 mono_thread_current (void)
1334 MonoThread *res = GET_CURRENT_OBJECT ();
1335 THREAD_DEBUG (g_message ("%s: returning %p", __func__, res));
1339 gboolean ves_icall_System_Threading_Thread_Join_internal(MonoThread *this,
1340 int ms, HANDLE thread)
1342 MonoThread *cur_thread = mono_thread_current ();
1345 MONO_ARCH_SAVE_REGS;
1347 mono_thread_current_check_pending_interrupt ();
1349 ensure_synch_cs_set (this);
1351 EnterCriticalSection (this->synch_cs);
1353 if ((this->state & ThreadState_Unstarted) != 0) {
1354 LeaveCriticalSection (this->synch_cs);
1356 mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started."));
1360 LeaveCriticalSection (this->synch_cs);
1365 THREAD_DEBUG (g_message ("%s: joining thread handle %p, %d ms", __func__, thread, ms));
1367 mono_thread_set_state (cur_thread, ThreadState_WaitSleepJoin);
1369 ret=WaitForSingleObjectEx (thread, ms, TRUE);
1371 mono_thread_clr_state (cur_thread, ThreadState_WaitSleepJoin);
1373 if(ret==WAIT_OBJECT_0) {
1374 THREAD_DEBUG (g_message ("%s: join successful", __func__));
1379 THREAD_DEBUG (g_message ("%s: join failed", __func__));
1384 /* FIXME: exitContext isnt documented */
1385 gboolean ves_icall_System_Threading_WaitHandle_WaitAll_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext)
1391 MonoObject *waitHandle;
1392 MonoThread *thread = mono_thread_current ();
1394 MONO_ARCH_SAVE_REGS;
1396 /* Do this WaitSleepJoin check before creating objects */
1397 mono_thread_current_check_pending_interrupt ();
1399 numhandles = mono_array_length(mono_handles);
1400 handles = g_new0(HANDLE, numhandles);
1402 for(i = 0; i < numhandles; i++) {
1403 waitHandle = mono_array_get(mono_handles, MonoObject*, i);
1404 handles [i] = mono_wait_handle_get_handle ((MonoWaitHandle *) waitHandle);
1411 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1413 ret=WaitForMultipleObjectsEx(numhandles, handles, TRUE, ms, TRUE);
1415 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1419 if(ret==WAIT_FAILED) {
1420 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait failed", __func__, GetCurrentThreadId ()));
1422 } else if(ret==WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION) {
1423 /* Do we want to try again if we get
1424 * WAIT_IO_COMPLETION? The documentation for
1425 * WaitHandle doesn't give any clues. (We'd have to
1426 * fiddle with the timeout if we retry.)
1428 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait timed out", __func__, GetCurrentThreadId ()));
1435 /* FIXME: exitContext isnt documented */
1436 gint32 ves_icall_System_Threading_WaitHandle_WaitAny_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext)
1442 MonoObject *waitHandle;
1443 MonoThread *thread = mono_thread_current ();
1445 MONO_ARCH_SAVE_REGS;
1447 /* Do this WaitSleepJoin check before creating objects */
1448 mono_thread_current_check_pending_interrupt ();
1450 numhandles = mono_array_length(mono_handles);
1451 handles = g_new0(HANDLE, numhandles);
1453 for(i = 0; i < numhandles; i++) {
1454 waitHandle = mono_array_get(mono_handles, MonoObject*, i);
1455 handles [i] = mono_wait_handle_get_handle ((MonoWaitHandle *) waitHandle);
1462 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1464 ret=WaitForMultipleObjectsEx(numhandles, handles, FALSE, ms, TRUE);
1466 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1470 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") returning %d", __func__, GetCurrentThreadId (), ret));
1473 * These need to be here. See MSDN dos on WaitForMultipleObjects.
1475 if (ret >= WAIT_OBJECT_0 && ret <= WAIT_OBJECT_0 + numhandles - 1) {
1476 return ret - WAIT_OBJECT_0;
1478 else if (ret >= WAIT_ABANDONED_0 && ret <= WAIT_ABANDONED_0 + numhandles - 1) {
1479 return ret - WAIT_ABANDONED_0;
1486 /* FIXME: exitContext isnt documented */
1487 gboolean ves_icall_System_Threading_WaitHandle_WaitOne_internal(MonoObject *this, HANDLE handle, gint32 ms, gboolean exitContext)
1490 MonoThread *thread = mono_thread_current ();
1492 MONO_ARCH_SAVE_REGS;
1494 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") waiting for %p, %d ms", __func__, GetCurrentThreadId (), handle, ms));
1500 mono_thread_current_check_pending_interrupt ();
1502 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1504 ret=WaitForSingleObjectEx (handle, ms, TRUE);
1506 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1508 if(ret==WAIT_FAILED) {
1509 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait failed", __func__, GetCurrentThreadId ()));
1511 } else if(ret==WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION) {
1512 /* Do we want to try again if we get
1513 * WAIT_IO_COMPLETION? The documentation for
1514 * WaitHandle doesn't give any clues. (We'd have to
1515 * fiddle with the timeout if we retry.)
1517 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait timed out", __func__, GetCurrentThreadId ()));
1525 ves_icall_System_Threading_WaitHandle_SignalAndWait_Internal (HANDLE toSignal, HANDLE toWait, gint32 ms, gboolean exitContext)
1528 MonoThread *thread = mono_thread_current ();
1530 MONO_ARCH_SAVE_REGS;
1535 mono_thread_current_check_pending_interrupt ();
1537 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1539 ret = SignalObjectAndWait (toSignal, toWait, ms, TRUE);
1541 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1543 return (!(ret == WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION || ret == WAIT_FAILED));
1546 HANDLE ves_icall_System_Threading_Mutex_CreateMutex_internal (MonoBoolean owned, MonoString *name, MonoBoolean *created)
1550 MONO_ARCH_SAVE_REGS;
1555 mutex = CreateMutex (NULL, owned, NULL);
1557 mutex = CreateMutex (NULL, owned, mono_string_chars (name));
1559 if (GetLastError () == ERROR_ALREADY_EXISTS) {
1567 MonoBoolean ves_icall_System_Threading_Mutex_ReleaseMutex_internal (HANDLE handle ) {
1568 MONO_ARCH_SAVE_REGS;
1570 return(ReleaseMutex (handle));
1573 HANDLE ves_icall_System_Threading_Mutex_OpenMutex_internal (MonoString *name,
1579 MONO_ARCH_SAVE_REGS;
1581 *error = ERROR_SUCCESS;
1583 ret = OpenMutex (rights, FALSE, mono_string_chars (name));
1585 *error = GetLastError ();
1592 HANDLE ves_icall_System_Threading_Semaphore_CreateSemaphore_internal (gint32 initialCount, gint32 maximumCount, MonoString *name, MonoBoolean *created)
1596 MONO_ARCH_SAVE_REGS;
1601 sem = CreateSemaphore (NULL, initialCount, maximumCount, NULL);
1603 sem = CreateSemaphore (NULL, initialCount, maximumCount,
1604 mono_string_chars (name));
1606 if (GetLastError () == ERROR_ALREADY_EXISTS) {
1614 gint32 ves_icall_System_Threading_Semaphore_ReleaseSemaphore_internal (HANDLE handle, gint32 releaseCount, MonoBoolean *fail)
1618 MONO_ARCH_SAVE_REGS;
1620 *fail = !ReleaseSemaphore (handle, releaseCount, &prevcount);
1625 HANDLE ves_icall_System_Threading_Semaphore_OpenSemaphore_internal (MonoString *name, gint32 rights, gint32 *error)
1629 MONO_ARCH_SAVE_REGS;
1631 *error = ERROR_SUCCESS;
1633 ret = OpenSemaphore (rights, FALSE, mono_string_chars (name));
1635 *error = GetLastError ();
1641 HANDLE ves_icall_System_Threading_Events_CreateEvent_internal (MonoBoolean manual, MonoBoolean initial, MonoString *name, MonoBoolean *created)
1645 MONO_ARCH_SAVE_REGS;
1650 event = CreateEvent (NULL, manual, initial, NULL);
1652 event = CreateEvent (NULL, manual, initial,
1653 mono_string_chars (name));
1655 if (GetLastError () == ERROR_ALREADY_EXISTS) {
1663 gboolean ves_icall_System_Threading_Events_SetEvent_internal (HANDLE handle) {
1664 MONO_ARCH_SAVE_REGS;
1666 return (SetEvent(handle));
1669 gboolean ves_icall_System_Threading_Events_ResetEvent_internal (HANDLE handle) {
1670 MONO_ARCH_SAVE_REGS;
1672 return (ResetEvent(handle));
1676 ves_icall_System_Threading_Events_CloseEvent_internal (HANDLE handle) {
1677 MONO_ARCH_SAVE_REGS;
1679 CloseHandle (handle);
1682 HANDLE ves_icall_System_Threading_Events_OpenEvent_internal (MonoString *name,
1688 MONO_ARCH_SAVE_REGS;
1690 *error = ERROR_SUCCESS;
1692 ret = OpenEvent (rights, FALSE, mono_string_chars (name));
1694 *error = GetLastError ();
1700 gint32 ves_icall_System_Threading_Interlocked_Increment_Int (gint32 *location)
1702 MONO_ARCH_SAVE_REGS;
1704 return InterlockedIncrement (location);
1707 gint64 ves_icall_System_Threading_Interlocked_Increment_Long (gint64 *location)
1711 MONO_ARCH_SAVE_REGS;
1713 mono_interlocked_lock ();
1717 mono_interlocked_unlock ();
1723 gint32 ves_icall_System_Threading_Interlocked_Decrement_Int (gint32 *location)
1725 MONO_ARCH_SAVE_REGS;
1727 return InterlockedDecrement(location);
1730 gint64 ves_icall_System_Threading_Interlocked_Decrement_Long (gint64 * location)
1734 MONO_ARCH_SAVE_REGS;
1736 mono_interlocked_lock ();
1740 mono_interlocked_unlock ();
1745 gint32 ves_icall_System_Threading_Interlocked_Exchange_Int (gint32 *location, gint32 value)
1747 MONO_ARCH_SAVE_REGS;
1749 return InterlockedExchange(location, value);
1752 MonoObject * ves_icall_System_Threading_Interlocked_Exchange_Object (MonoObject **location, MonoObject *value)
1754 MONO_ARCH_SAVE_REGS;
1756 return (MonoObject *) InterlockedExchangePointer((gpointer *) location, value);
1759 gfloat ves_icall_System_Threading_Interlocked_Exchange_Single (gfloat *location, gfloat value)
1761 IntFloatUnion val, ret;
1763 MONO_ARCH_SAVE_REGS;
1766 ret.ival = InterlockedExchange((gint32 *) location, val.ival);
1772 ves_icall_System_Threading_Interlocked_Exchange_Long (gint64 *location, gint64 value)
1774 #if SIZEOF_VOID_P == 8
1775 return (gint64) InterlockedExchangePointer((gpointer *) location, (gpointer)value);
1780 * According to MSDN, this function is only atomic with regards to the
1781 * other Interlocked functions on 32 bit platforms.
1783 mono_interlocked_lock ();
1786 mono_interlocked_unlock ();
1793 ves_icall_System_Threading_Interlocked_Exchange_Double (gdouble *location, gdouble value)
1795 #if SIZEOF_VOID_P == 8
1796 LongDoubleUnion val, ret;
1799 ret.ival = (gint64)InterlockedExchangePointer((gpointer *) location, (gpointer)val.ival);
1806 * According to MSDN, this function is only atomic with regards to the
1807 * other Interlocked functions on 32 bit platforms.
1809 mono_interlocked_lock ();
1812 mono_interlocked_unlock ();
1818 gint32 ves_icall_System_Threading_Interlocked_CompareExchange_Int(gint32 *location, gint32 value, gint32 comparand)
1820 MONO_ARCH_SAVE_REGS;
1822 return InterlockedCompareExchange(location, value, comparand);
1825 MonoObject * ves_icall_System_Threading_Interlocked_CompareExchange_Object (MonoObject **location, MonoObject *value, MonoObject *comparand)
1827 MONO_ARCH_SAVE_REGS;
1829 return (MonoObject *) InterlockedCompareExchangePointer((gpointer *) location, value, comparand);
1832 gfloat ves_icall_System_Threading_Interlocked_CompareExchange_Single (gfloat *location, gfloat value, gfloat comparand)
1834 IntFloatUnion val, ret, cmp;
1836 MONO_ARCH_SAVE_REGS;
1839 cmp.fval = comparand;
1840 ret.ival = InterlockedCompareExchange((gint32 *) location, val.ival, cmp.ival);
1846 ves_icall_System_Threading_Interlocked_CompareExchange_Double (gdouble *location, gdouble value, gdouble comparand)
1848 #if SIZEOF_VOID_P == 8
1849 LongDoubleUnion val, comp, ret;
1852 comp.fval = comparand;
1853 ret.ival = (gint64)InterlockedCompareExchangePointer((gpointer *) location, (gpointer)val.ival, (gpointer)comp.ival);
1859 mono_interlocked_lock ();
1861 if (old == comparand)
1863 mono_interlocked_unlock ();
1870 ves_icall_System_Threading_Interlocked_CompareExchange_Long (gint64 *location, gint64 value, gint64 comparand)
1872 #if SIZEOF_VOID_P == 8
1873 return (gint64)InterlockedCompareExchangePointer((gpointer *) location, (gpointer)value, (gpointer)comparand);
1877 mono_interlocked_lock ();
1879 if (old == comparand)
1881 mono_interlocked_unlock ();
1888 ves_icall_System_Threading_Interlocked_CompareExchange_T (MonoObject **location, MonoObject *value, MonoObject *comparand)
1890 MONO_ARCH_SAVE_REGS;
1892 return InterlockedCompareExchangePointer ((gpointer *)location, value, comparand);
1896 ves_icall_System_Threading_Interlocked_Exchange_T (MonoObject **location, MonoObject *value)
1898 MONO_ARCH_SAVE_REGS;
1900 return InterlockedExchangePointer ((gpointer *)location, value);
1904 ves_icall_System_Threading_Interlocked_Add_Int (gint32 *location, gint32 value)
1906 #if SIZEOF_VOID_P == 8
1907 /* Should be implemented as a JIT intrinsic */
1908 mono_raise_exception (mono_get_exception_not_implemented (NULL));
1913 mono_interlocked_lock ();
1915 *location = orig + value;
1916 mono_interlocked_unlock ();
1918 return orig + value;
1923 ves_icall_System_Threading_Interlocked_Add_Long (gint64 *location, gint64 value)
1925 #if SIZEOF_VOID_P == 8
1926 /* Should be implemented as a JIT intrinsic */
1927 mono_raise_exception (mono_get_exception_not_implemented (NULL));
1932 mono_interlocked_lock ();
1934 *location = orig + value;
1935 mono_interlocked_unlock ();
1937 return orig + value;
1942 ves_icall_System_Threading_Interlocked_Read_Long (gint64 *location)
1944 #if SIZEOF_VOID_P == 8
1945 /* 64 bit reads are already atomic */
1950 mono_interlocked_lock ();
1952 mono_interlocked_unlock ();
1959 ves_icall_System_Threading_Thread_MemoryBarrier (void)
1961 mono_threads_lock ();
1962 mono_threads_unlock ();
1966 ves_icall_System_Threading_Thread_ClrState (MonoThread* this, guint32 state)
1968 mono_thread_clr_state (this, state);
1970 if (state & ThreadState_Background) {
1971 /* If the thread changes the background mode, the main thread has to
1972 * be notified, since it has to rebuild the list of threads to
1975 SetEvent (background_change_event);
1980 ves_icall_System_Threading_Thread_SetState (MonoThread* this, guint32 state)
1982 mono_thread_set_state (this, state);
1984 if (state & ThreadState_Background) {
1985 /* If the thread changes the background mode, the main thread has to
1986 * be notified, since it has to rebuild the list of threads to
1989 SetEvent (background_change_event);
1994 ves_icall_System_Threading_Thread_GetState (MonoThread* this)
1998 ensure_synch_cs_set (this);
2000 EnterCriticalSection (this->synch_cs);
2002 state = this->state;
2004 LeaveCriticalSection (this->synch_cs);
2009 void ves_icall_System_Threading_Thread_Interrupt_internal (MonoThread *this)
2011 gboolean throw = FALSE;
2013 ensure_synch_cs_set (this);
2015 if (this == mono_thread_current ())
2018 EnterCriticalSection (this->synch_cs);
2020 this->thread_interrupt_requested = TRUE;
2022 if (this->state & ThreadState_WaitSleepJoin) {
2026 LeaveCriticalSection (this->synch_cs);
2029 signal_thread_state_change (this);
2033 void mono_thread_current_check_pending_interrupt ()
2035 MonoThread *thread = mono_thread_current ();
2036 gboolean throw = FALSE;
2038 mono_debugger_check_interruption ();
2040 ensure_synch_cs_set (thread);
2042 EnterCriticalSection (thread->synch_cs);
2044 if (thread->thread_interrupt_requested) {
2046 thread->thread_interrupt_requested = FALSE;
2049 LeaveCriticalSection (thread->synch_cs);
2052 mono_raise_exception (mono_get_exception_thread_interrupted ());
2057 mono_thread_get_abort_signal (void)
2059 #ifdef PLATFORM_WIN32
2069 static int abort_signum = -1;
2071 if (abort_signum != -1)
2072 return abort_signum;
2073 /* we try to avoid SIGRTMIN and any one that might have been set already, see bug #75387 */
2074 for (i = SIGRTMIN + 1; i < SIGRTMAX; ++i) {
2075 struct sigaction sinfo;
2076 sigaction (i, NULL, &sinfo);
2077 if (sinfo.sa_handler == SIG_DFL && (void*)sinfo.sa_sigaction == (void*)SIG_DFL) {
2082 /* fallback to the old way */
2085 #endif /* PLATFORM_WIN32 */
2088 #ifdef PLATFORM_WIN32
2089 static void CALLBACK interruption_request_apc (ULONG_PTR param)
2091 MonoException* exc = mono_thread_request_interruption (FALSE);
2092 if (exc) mono_raise_exception (exc);
2094 #endif /* PLATFORM_WIN32 */
2097 * signal_thread_state_change
2099 * Tells the thread that his state has changed and it has to enter the new
2100 * state as soon as possible.
2102 static void signal_thread_state_change (MonoThread *thread)
2104 if (thread == mono_thread_current ()) {
2105 /* Do it synchronously */
2106 MonoException *exc = mono_thread_request_interruption (FALSE);
2108 mono_raise_exception (exc);
2111 #ifdef PLATFORM_WIN32
2112 QueueUserAPC ((PAPCFUNC)interruption_request_apc, thread->handle, NULL);
2114 /* fixme: store the state somewhere */
2115 #ifdef PTHREAD_POINTER_ID
2116 pthread_kill ((gpointer)(gsize)(thread->tid), mono_thread_get_abort_signal ());
2118 pthread_kill (thread->tid, mono_thread_get_abort_signal ());
2122 * This will cause waits to be broken.
2123 * It will also prevent the thread from entering a wait, so if the thread returns
2124 * from the wait before it receives the abort signal, it will just spin in the wait
2125 * functions in the io-layer until the signal handler calls QueueUserAPC which will
2128 wapi_interrupt_thread (thread->handle);
2129 #endif /* PLATFORM_WIN32 */
2133 ves_icall_System_Threading_Thread_Abort (MonoThread *thread, MonoObject *state)
2135 MONO_ARCH_SAVE_REGS;
2137 ensure_synch_cs_set (thread);
2139 EnterCriticalSection (thread->synch_cs);
2141 if ((thread->state & ThreadState_AbortRequested) != 0 ||
2142 (thread->state & ThreadState_StopRequested) != 0 ||
2143 (thread->state & ThreadState_Stopped) != 0)
2145 LeaveCriticalSection (thread->synch_cs);
2149 if ((thread->state & ThreadState_Unstarted) != 0) {
2150 thread->state |= ThreadState_Aborted;
2151 LeaveCriticalSection (thread->synch_cs);
2155 thread->state |= ThreadState_AbortRequested;
2156 if (thread->abort_state_handle)
2157 mono_gchandle_free (thread->abort_state_handle);
2159 thread->abort_state_handle = mono_gchandle_new (state, FALSE);
2160 g_assert (thread->abort_state_handle);
2162 thread->abort_state_handle = 0;
2164 thread->abort_exc = NULL;
2166 LeaveCriticalSection (thread->synch_cs);
2168 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Abort requested for %p (%"G_GSIZE_FORMAT")", __func__, GetCurrentThreadId (), thread, (gsize)thread->tid));
2170 /* During shutdown, we can't wait for other threads */
2172 /* Make sure the thread is awake */
2173 mono_thread_resume (thread);
2175 signal_thread_state_change (thread);
2179 ves_icall_System_Threading_Thread_ResetAbort (void)
2181 MonoThread *thread = mono_thread_current ();
2183 MONO_ARCH_SAVE_REGS;
2185 ensure_synch_cs_set (thread);
2187 EnterCriticalSection (thread->synch_cs);
2189 thread->state &= ~ThreadState_AbortRequested;
2191 if (!thread->abort_exc) {
2192 const char *msg = "Unable to reset abort because no abort was requested";
2193 LeaveCriticalSection (thread->synch_cs);
2194 mono_raise_exception (mono_get_exception_thread_state (msg));
2196 thread->abort_exc = NULL;
2197 if (thread->abort_state_handle) {
2198 mono_gchandle_free (thread->abort_state_handle);
2199 /* This is actually not necessary - the handle
2200 only counts if the exception is set */
2201 thread->abort_state_handle = 0;
2205 LeaveCriticalSection (thread->synch_cs);
2209 serialize_object (MonoObject *obj, gboolean *failure, MonoObject **exc)
2211 static MonoMethod *serialize_method;
2216 if (!serialize_method) {
2217 MonoClass *klass = mono_class_from_name (mono_defaults.corlib, "System.Runtime.Remoting", "RemotingServices");
2218 serialize_method = mono_class_get_method_from_name (klass, "SerializeCallData", -1);
2221 if (!serialize_method) {
2226 g_assert (!obj->vtable->klass->marshalbyref);
2230 array = mono_runtime_invoke (serialize_method, NULL, params, exc);
2238 deserialize_object (MonoObject *obj, gboolean *failure, MonoObject **exc)
2240 static MonoMethod *deserialize_method;
2245 if (!deserialize_method) {
2246 MonoClass *klass = mono_class_from_name (mono_defaults.corlib, "System.Runtime.Remoting", "RemotingServices");
2247 deserialize_method = mono_class_get_method_from_name (klass, "DeserializeCallData", -1);
2249 if (!deserialize_method) {
2256 result = mono_runtime_invoke (deserialize_method, NULL, params, exc);
2264 make_transparent_proxy (MonoObject *obj, gboolean *failure, MonoObject **exc)
2266 static MonoMethod *get_proxy_method;
2268 MonoDomain *domain = mono_domain_get ();
2269 MonoRealProxy *real_proxy;
2270 MonoReflectionType *reflection_type;
2271 MonoTransparentProxy *transparent_proxy;
2273 if (!get_proxy_method)
2274 get_proxy_method = mono_class_get_method_from_name (mono_defaults.real_proxy_class, "GetTransparentProxy", 0);
2276 g_assert (obj->vtable->klass->marshalbyref);
2278 real_proxy = (MonoRealProxy*) mono_object_new (domain, mono_defaults.real_proxy_class);
2279 reflection_type = mono_type_get_object (domain, &obj->vtable->klass->byval_arg);
2281 real_proxy->class_to_proxy = reflection_type;
2282 real_proxy->unwrapped_server = obj;
2285 transparent_proxy = (MonoTransparentProxy*) mono_runtime_invoke (get_proxy_method, real_proxy, NULL, exc);
2289 return (MonoObject*) transparent_proxy;
2293 ves_icall_System_Threading_Thread_GetAbortExceptionState (MonoThread *thread)
2295 MonoObject *state, *serialized, *deserialized = NULL, *exc;
2297 gboolean failure = FALSE;
2299 if (!thread->abort_state_handle)
2302 state = mono_gchandle_get_target (thread->abort_state_handle);
2305 domain = mono_domain_get ();
2306 if (state->vtable->domain == domain)
2309 if (state->vtable->klass->marshalbyref) {
2310 deserialized = make_transparent_proxy (state, &failure, &exc);
2312 mono_domain_set_internal_with_options (state->vtable->domain, FALSE);
2313 serialized = serialize_object (state, &failure, &exc);
2314 mono_domain_set_internal_with_options (domain, FALSE);
2316 deserialized = deserialize_object (serialized, &failure, &exc);
2320 MonoException *invalid_op_exc = mono_get_exception_invalid_operation ("Thread.ExceptionState cannot access an ExceptionState from a different AppDomain");
2322 MONO_OBJECT_SETREF (invalid_op_exc, inner_ex, exc);
2323 mono_raise_exception (invalid_op_exc);
2326 return deserialized;
2330 mono_thread_suspend (MonoThread *thread)
2332 MONO_ARCH_SAVE_REGS;
2334 ensure_synch_cs_set (thread);
2336 EnterCriticalSection (thread->synch_cs);
2338 if ((thread->state & ThreadState_Unstarted) != 0 ||
2339 (thread->state & ThreadState_Aborted) != 0 ||
2340 (thread->state & ThreadState_Stopped) != 0)
2342 LeaveCriticalSection (thread->synch_cs);
2346 if ((thread->state & ThreadState_Suspended) != 0 ||
2347 (thread->state & ThreadState_SuspendRequested) != 0 ||
2348 (thread->state & ThreadState_StopRequested) != 0)
2350 LeaveCriticalSection (thread->synch_cs);
2354 thread->state |= ThreadState_SuspendRequested;
2356 LeaveCriticalSection (thread->synch_cs);
2358 signal_thread_state_change (thread);
2363 ves_icall_System_Threading_Thread_Suspend (MonoThread *thread)
2365 if (!mono_thread_suspend (thread))
2366 mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started, or is dead."));
2370 mono_thread_resume (MonoThread *thread)
2372 MONO_ARCH_SAVE_REGS;
2374 ensure_synch_cs_set (thread);
2376 EnterCriticalSection (thread->synch_cs);
2378 if ((thread->state & ThreadState_SuspendRequested) != 0) {
2379 thread->state &= ~ThreadState_SuspendRequested;
2380 LeaveCriticalSection (thread->synch_cs);
2384 if ((thread->state & ThreadState_Suspended) == 0 ||
2385 (thread->state & ThreadState_Unstarted) != 0 ||
2386 (thread->state & ThreadState_Aborted) != 0 ||
2387 (thread->state & ThreadState_Stopped) != 0)
2389 LeaveCriticalSection (thread->synch_cs);
2393 thread->resume_event = CreateEvent (NULL, TRUE, FALSE, NULL);
2394 if (thread->resume_event == NULL) {
2395 LeaveCriticalSection (thread->synch_cs);
2399 /* Awake the thread */
2400 SetEvent (thread->suspend_event);
2402 LeaveCriticalSection (thread->synch_cs);
2404 /* Wait for the thread to awake */
2405 WaitForSingleObject (thread->resume_event, INFINITE);
2406 CloseHandle (thread->resume_event);
2407 thread->resume_event = NULL;
2413 ves_icall_System_Threading_Thread_Resume (MonoThread *thread)
2415 if (!mono_thread_resume (thread))
2416 mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started, or is dead."));
2420 find_wrapper (MonoMethod *m, gint no, gint ilo, gboolean managed, gpointer data)
2425 if (m->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE ||
2426 m->wrapper_type == MONO_WRAPPER_XDOMAIN_INVOKE ||
2427 m->wrapper_type == MONO_WRAPPER_XDOMAIN_DISPATCH)
2429 *((gboolean*)data) = TRUE;
2436 is_running_protected_wrapper (void)
2438 gboolean found = FALSE;
2439 mono_stack_walk (find_wrapper, &found);
2443 void mono_thread_stop (MonoThread *thread)
2445 ensure_synch_cs_set (thread);
2447 EnterCriticalSection (thread->synch_cs);
2449 if ((thread->state & ThreadState_StopRequested) != 0 ||
2450 (thread->state & ThreadState_Stopped) != 0)
2452 LeaveCriticalSection (thread->synch_cs);
2456 /* Make sure the thread is awake */
2457 mono_thread_resume (thread);
2459 thread->state |= ThreadState_StopRequested;
2460 thread->state &= ~ThreadState_AbortRequested;
2462 LeaveCriticalSection (thread->synch_cs);
2464 signal_thread_state_change (thread);
2468 ves_icall_System_Threading_Thread_VolatileRead1 (void *ptr)
2470 return *((volatile gint8 *) (ptr));
2474 ves_icall_System_Threading_Thread_VolatileRead2 (void *ptr)
2476 return *((volatile gint16 *) (ptr));
2480 ves_icall_System_Threading_Thread_VolatileRead4 (void *ptr)
2482 return *((volatile gint32 *) (ptr));
2486 ves_icall_System_Threading_Thread_VolatileRead8 (void *ptr)
2488 return *((volatile gint64 *) (ptr));
2492 ves_icall_System_Threading_Thread_VolatileReadIntPtr (void *ptr)
2494 return (void *) *((volatile void **) ptr);
2498 ves_icall_System_Threading_Thread_VolatileWrite1 (void *ptr, gint8 value)
2500 *((volatile gint8 *) ptr) = value;
2504 ves_icall_System_Threading_Thread_VolatileWrite2 (void *ptr, gint16 value)
2506 *((volatile gint16 *) ptr) = value;
2510 ves_icall_System_Threading_Thread_VolatileWrite4 (void *ptr, gint32 value)
2512 *((volatile gint32 *) ptr) = value;
2516 ves_icall_System_Threading_Thread_VolatileWrite8 (void *ptr, gint64 value)
2518 *((volatile gint64 *) ptr) = value;
2522 ves_icall_System_Threading_Thread_VolatileWriteIntPtr (void *ptr, void *value)
2524 *((volatile void **) ptr) = value;
2528 ves_icall_System_Threading_Thread_VolatileWriteObject (void *ptr, void *value)
2530 mono_gc_wbarrier_generic_store (ptr, value);
2533 void mono_thread_init (MonoThreadStartCB start_cb,
2534 MonoThreadAttachCB attach_cb)
2536 MONO_GC_REGISTER_ROOT (small_id_table);
2537 InitializeCriticalSection(&threads_mutex);
2538 InitializeCriticalSection(&interlocked_mutex);
2539 InitializeCriticalSection(&contexts_mutex);
2540 InitializeCriticalSection(&delayed_free_table_mutex);
2541 InitializeCriticalSection(&small_id_mutex);
2543 background_change_event = CreateEvent (NULL, TRUE, FALSE, NULL);
2544 g_assert(background_change_event != NULL);
2546 mono_init_static_data_info (&thread_static_info);
2547 mono_init_static_data_info (&context_static_info);
2549 current_object_key=TlsAlloc();
2550 THREAD_DEBUG (g_message ("%s: Allocated current_object_key %d", __func__, current_object_key));
2552 mono_thread_start_cb = start_cb;
2553 mono_thread_attach_cb = attach_cb;
2555 delayed_free_table = g_array_new (FALSE, FALSE, sizeof (DelayedFreeItem));
2557 /* Get a pseudo handle to the current process. This is just a
2558 * kludge so that wapi can build a process handle if needed.
2559 * As a pseudo handle is returned, we don't need to clean
2562 GetCurrentProcess ();
2565 void mono_thread_cleanup (void)
2567 mono_thread_hazardous_try_free_all ();
2569 #if !defined(PLATFORM_WIN32) && !defined(RUN_IN_SUBTHREAD)
2570 /* The main thread must abandon any held mutexes (particularly
2571 * important for named mutexes as they are shared across
2572 * processes, see bug 74680.) This will happen when the
2573 * thread exits, but if it's not running in a subthread it
2574 * won't exit in time.
2576 /* Using non-w32 API is a nasty kludge, but I couldn't find
2577 * anything in the documentation that would let me do this
2578 * here yet still be safe to call on windows.
2580 _wapi_thread_signal_self (mono_environment_exitcode_get ());
2584 /* This stuff needs more testing, it seems one of these
2585 * critical sections can be locked when mono_thread_cleanup is
2588 DeleteCriticalSection (&threads_mutex);
2589 DeleteCriticalSection (&interlocked_mutex);
2590 DeleteCriticalSection (&contexts_mutex);
2591 DeleteCriticalSection (&delayed_free_table_mutex);
2592 DeleteCriticalSection (&small_id_mutex);
2593 CloseHandle (background_change_event);
2596 g_array_free (delayed_free_table, TRUE);
2597 delayed_free_table = NULL;
2599 TlsFree (current_object_key);
2603 mono_threads_install_cleanup (MonoThreadCleanupFunc func)
2605 mono_thread_cleanup_fn = func;
2609 mono_thread_set_manage_callback (MonoThread *thread, MonoThreadManageCallback func)
2611 thread->manage_callback = func;
2614 void mono_threads_install_notify_pending_exc (MonoThreadNotifyPendingExcFunc func)
2616 mono_thread_notify_pending_exc_fn = func;
2620 static void print_tids (gpointer key, gpointer value, gpointer user)
2622 /* GPOINTER_TO_UINT breaks horribly if sizeof(void *) >
2623 * sizeof(uint) and a cast to uint would overflow
2625 /* Older versions of glib don't have G_GSIZE_FORMAT, so just
2626 * print this as a pointer.
2628 g_message ("Waiting for: %p", key);
2633 HANDLE handles[MAXIMUM_WAIT_OBJECTS];
2634 MonoThread *threads[MAXIMUM_WAIT_OBJECTS];
2638 static void wait_for_tids (struct wait_data *wait, guint32 timeout)
2642 THREAD_DEBUG (g_message("%s: %d threads to wait for in this batch", __func__, wait->num));
2644 ret=WaitForMultipleObjectsEx(wait->num, wait->handles, TRUE, timeout, FALSE);
2646 if(ret==WAIT_FAILED) {
2647 /* See the comment in build_wait_tids() */
2648 THREAD_DEBUG (g_message ("%s: Wait failed", __func__));
2652 for(i=0; i<wait->num; i++)
2653 CloseHandle (wait->handles[i]);
2655 if (ret == WAIT_TIMEOUT)
2658 for(i=0; i<wait->num; i++) {
2659 gsize tid = wait->threads[i]->tid;
2661 mono_threads_lock ();
2662 if(mono_g_hash_table_lookup (threads, (gpointer)tid)!=NULL) {
2663 /* This thread must have been killed, because
2664 * it hasn't cleaned itself up. (It's just
2665 * possible that the thread exited before the
2666 * parent thread had a chance to store the
2667 * handle, and now there is another pointer to
2668 * the already-exited thread stored. In this
2669 * case, we'll just get two
2670 * mono_profiler_thread_end() calls for the
2674 mono_threads_unlock ();
2675 THREAD_DEBUG (g_message ("%s: cleaning up after thread %p (%"G_GSIZE_FORMAT")", __func__, wait->threads[i], tid));
2676 thread_cleanup (wait->threads[i]);
2678 mono_threads_unlock ();
2683 static void wait_for_tids_or_state_change (struct wait_data *wait, guint32 timeout)
2685 guint32 i, ret, count;
2687 THREAD_DEBUG (g_message("%s: %d threads to wait for in this batch", __func__, wait->num));
2689 /* Add the thread state change event, so it wakes up if a thread changes
2690 * to background mode.
2693 if (count < MAXIMUM_WAIT_OBJECTS) {
2694 wait->handles [count] = background_change_event;
2698 ret=WaitForMultipleObjectsEx (count, wait->handles, FALSE, timeout, FALSE);
2700 if(ret==WAIT_FAILED) {
2701 /* See the comment in build_wait_tids() */
2702 THREAD_DEBUG (g_message ("%s: Wait failed", __func__));
2706 for(i=0; i<wait->num; i++)
2707 CloseHandle (wait->handles[i]);
2709 if (ret == WAIT_TIMEOUT)
2712 if (ret < wait->num) {
2713 gsize tid = wait->threads[ret]->tid;
2714 mono_threads_lock ();
2715 if (mono_g_hash_table_lookup (threads, (gpointer)tid)!=NULL) {
2716 /* See comment in wait_for_tids about thread cleanup */
2717 mono_threads_unlock ();
2718 THREAD_DEBUG (g_message ("%s: cleaning up after thread %"G_GSIZE_FORMAT, __func__, tid));
2719 thread_cleanup (wait->threads [ret]);
2721 mono_threads_unlock ();
2725 static void build_wait_tids (gpointer key, gpointer value, gpointer user)
2727 struct wait_data *wait=(struct wait_data *)user;
2729 if(wait->num<MAXIMUM_WAIT_OBJECTS) {
2731 MonoThread *thread=(MonoThread *)value;
2733 /* Ignore background threads, we abort them later */
2734 /* Do not lock here since it is not needed and the caller holds threads_lock */
2735 if (thread->state & ThreadState_Background) {
2736 THREAD_DEBUG (g_message ("%s: ignoring background thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2737 return; /* just leave, ignore */
2740 if (mono_gc_is_finalizer_thread (thread)) {
2741 THREAD_DEBUG (g_message ("%s: ignoring finalizer thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2745 if (thread == mono_thread_current ()) {
2746 THREAD_DEBUG (g_message ("%s: ignoring current thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2750 if (thread == mono_thread_get_main ()) {
2751 THREAD_DEBUG (g_message ("%s: ignoring main thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2755 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
2756 if (handle == NULL) {
2757 THREAD_DEBUG (g_message ("%s: ignoring unopenable thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2761 THREAD_DEBUG (g_message ("%s: Invoking mono_thread_manage callback on thread %p", __func__, thread));
2762 if ((thread->manage_callback == NULL) || (thread->manage_callback (thread) == TRUE)) {
2763 wait->handles[wait->num]=handle;
2764 wait->threads[wait->num]=thread;
2767 THREAD_DEBUG (g_message ("%s: adding thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2769 THREAD_DEBUG (g_message ("%s: ignoring (because of callback) thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2774 /* Just ignore the rest, we can't do anything with
2781 remove_and_abort_threads (gpointer key, gpointer value, gpointer user)
2783 struct wait_data *wait=(struct wait_data *)user;
2784 gsize self = GetCurrentThreadId ();
2785 MonoThread *thread = (MonoThread *) value;
2788 if (wait->num >= MAXIMUM_WAIT_OBJECTS)
2791 /* The finalizer thread is not a background thread */
2792 if (thread->tid != self && (thread->state & ThreadState_Background) != 0) {
2794 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
2798 /* printf ("A: %d\n", wait->num); */
2799 wait->handles[wait->num]=thread->handle;
2800 wait->threads[wait->num]=thread;
2803 THREAD_DEBUG (g_print ("%s: Aborting id: %"G_GSIZE_FORMAT"\n", __func__, (gsize)thread->tid));
2804 mono_thread_stop (thread);
2808 return (thread->tid != self && !mono_gc_is_finalizer_thread (thread));
2812 * mono_threads_set_shutting_down:
2814 * Is called by a thread that wants to shut down Mono. If the runtime is already
2815 * shutting down, the calling thread is suspended/stopped, and this function never
2819 mono_threads_set_shutting_down (void)
2821 MonoThread *current_thread = mono_thread_current ();
2823 mono_threads_lock ();
2825 if (shutting_down) {
2826 mono_threads_unlock ();
2828 /* Make sure we're properly suspended/stopped */
2830 EnterCriticalSection (current_thread->synch_cs);
2832 if ((current_thread->state & ThreadState_SuspendRequested) ||
2833 (current_thread->state & ThreadState_AbortRequested) ||
2834 (current_thread->state & ThreadState_StopRequested)) {
2835 LeaveCriticalSection (current_thread->synch_cs);
2836 mono_thread_execute_interruption (current_thread);
2838 current_thread->state |= ThreadState_Stopped;
2839 LeaveCriticalSection (current_thread->synch_cs);
2842 /* Wake up other threads potentially waiting for us */
2845 shutting_down = TRUE;
2847 /* Not really a background state change, but this will
2848 * interrupt the main thread if it is waiting for all
2849 * the other threads.
2851 SetEvent (background_change_event);
2853 mono_threads_unlock ();
2858 * mono_threads_is_shutting_down:
2860 * Returns whether a thread has commenced shutdown of Mono. Note that
2861 * if the function returns FALSE the caller must not assume that
2862 * shutdown is not in progress, because the situation might have
2863 * changed since the function returned. For that reason this function
2864 * is of very limited utility.
2867 mono_threads_is_shutting_down (void)
2869 return shutting_down;
2872 void mono_thread_manage (void)
2874 struct wait_data *wait=g_new0 (struct wait_data, 1);
2876 /* join each thread that's still running */
2877 THREAD_DEBUG (g_message ("%s: Joining each running thread...", __func__));
2879 mono_threads_lock ();
2881 THREAD_DEBUG (g_message("%s: No threads", __func__));
2882 mono_threads_unlock ();
2885 mono_threads_unlock ();
2888 mono_threads_lock ();
2889 if (shutting_down) {
2890 /* somebody else is shutting down */
2891 mono_threads_unlock ();
2894 THREAD_DEBUG (g_message ("%s: There are %d threads to join", __func__, mono_g_hash_table_size (threads));
2895 mono_g_hash_table_foreach (threads, print_tids, NULL));
2897 ResetEvent (background_change_event);
2899 mono_g_hash_table_foreach (threads, build_wait_tids, wait);
2900 mono_threads_unlock ();
2902 /* Something to wait for */
2903 wait_for_tids_or_state_change (wait, INFINITE);
2905 THREAD_DEBUG (g_message ("%s: I have %d threads after waiting.", __func__, wait->num));
2906 } while(wait->num>0);
2908 mono_threads_set_shutting_down ();
2910 /* No new threads will be created after this point */
2912 mono_runtime_set_shutting_down ();
2914 THREAD_DEBUG (g_message ("%s: threadpool cleanup", __func__));
2915 mono_thread_pool_cleanup ();
2918 * Remove everything but the finalizer thread and self.
2919 * Also abort all the background threads
2922 mono_threads_lock ();
2925 mono_g_hash_table_foreach_remove (threads, remove_and_abort_threads, wait);
2927 mono_threads_unlock ();
2929 THREAD_DEBUG (g_message ("%s: wait->num is now %d", __func__, wait->num));
2931 /* Something to wait for */
2932 wait_for_tids (wait, INFINITE);
2934 } while (wait->num > 0);
2937 * give the subthreads a chance to really quit (this is mainly needed
2938 * to get correct user and system times from getrusage/wait/time(1)).
2939 * This could be removed if we avoid pthread_detach() and use pthread_join().
2941 #ifndef PLATFORM_WIN32
2948 static void terminate_thread (gpointer key, gpointer value, gpointer user)
2950 MonoThread *thread=(MonoThread *)value;
2952 if(thread->tid != (gsize)user) {
2953 /*TerminateThread (thread->handle, -1);*/
2957 void mono_thread_abort_all_other_threads (void)
2959 gsize self = GetCurrentThreadId ();
2961 mono_threads_lock ();
2962 THREAD_DEBUG (g_message ("%s: There are %d threads to abort", __func__,
2963 mono_g_hash_table_size (threads));
2964 mono_g_hash_table_foreach (threads, print_tids, NULL));
2966 mono_g_hash_table_foreach (threads, terminate_thread, (gpointer)self);
2968 mono_threads_unlock ();
2972 collect_threads_for_suspend (gpointer key, gpointer value, gpointer user_data)
2974 MonoThread *thread = (MonoThread*)value;
2975 struct wait_data *wait = (struct wait_data*)user_data;
2979 * We try to exclude threads early, to avoid running into the MAXIMUM_WAIT_OBJECTS
2981 * This needs no locking.
2983 if ((thread->state & ThreadState_Suspended) != 0 ||
2984 (thread->state & ThreadState_Stopped) != 0)
2987 if (wait->num<MAXIMUM_WAIT_OBJECTS) {
2988 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
2992 wait->handles [wait->num] = handle;
2993 wait->threads [wait->num] = thread;
2999 * mono_thread_suspend_all_other_threads:
3001 * Suspend all managed threads except the finalizer thread and this thread. It is
3002 * not possible to resume them later.
3004 void mono_thread_suspend_all_other_threads (void)
3006 struct wait_data *wait = g_new0 (struct wait_data, 1);
3008 gsize self = GetCurrentThreadId ();
3010 guint32 eventidx = 0;
3011 gboolean starting, finished;
3014 * The other threads could be in an arbitrary state at this point, i.e.
3015 * they could be starting up, shutting down etc. This means that there could be
3016 * threads which are not even in the threads hash table yet.
3020 * First we set a barrier which will be checked by all threads before they
3021 * are added to the threads hash table, and they will exit if the flag is set.
3022 * This ensures that no threads could be added to the hash later.
3023 * We will use shutting_down as the barrier for now.
3025 g_assert (shutting_down);
3028 * We make multiple calls to WaitForMultipleObjects since:
3029 * - we can only wait for MAXIMUM_WAIT_OBJECTS threads
3030 * - some threads could exit without becoming suspended
3035 * Make a copy of the hashtable since we can't do anything with
3036 * threads while threads_mutex is held.
3039 mono_threads_lock ();
3040 mono_g_hash_table_foreach (threads, collect_threads_for_suspend, wait);
3041 mono_threads_unlock ();
3043 events = g_new0 (gpointer, wait->num);
3045 /* Get the suspended events that we'll be waiting for */
3046 for (i = 0; i < wait->num; ++i) {
3047 MonoThread *thread = wait->threads [i];
3048 gboolean signal_suspend = FALSE;
3050 if ((thread->tid == self) || mono_gc_is_finalizer_thread (thread)) {
3051 //CloseHandle (wait->handles [i]);
3052 wait->threads [i] = NULL; /* ignore this thread in next loop */
3056 ensure_synch_cs_set (thread);
3058 EnterCriticalSection (thread->synch_cs);
3060 if (thread->suspended_event == NULL) {
3061 thread->suspended_event = CreateEvent (NULL, TRUE, FALSE, NULL);
3062 if (thread->suspended_event == NULL) {
3063 /* Forget this one and go on to the next */
3064 LeaveCriticalSection (thread->synch_cs);
3069 if ((thread->state & ThreadState_Suspended) != 0 ||
3070 (thread->state & ThreadState_StopRequested) != 0 ||
3071 (thread->state & ThreadState_Stopped) != 0) {
3072 LeaveCriticalSection (thread->synch_cs);
3073 CloseHandle (wait->handles [i]);
3074 wait->threads [i] = NULL; /* ignore this thread in next loop */
3078 if ((thread->state & ThreadState_SuspendRequested) == 0)
3079 signal_suspend = TRUE;
3081 events [eventidx++] = thread->suspended_event;
3083 /* Convert abort requests into suspend requests */
3084 if ((thread->state & ThreadState_AbortRequested) != 0)
3085 thread->state &= ~ThreadState_AbortRequested;
3087 thread->state |= ThreadState_SuspendRequested;
3089 LeaveCriticalSection (thread->synch_cs);
3091 /* Signal the thread to suspend */
3093 signal_thread_state_change (thread);
3097 WaitForMultipleObjectsEx (eventidx, events, TRUE, 100, FALSE);
3098 for (i = 0; i < wait->num; ++i) {
3099 MonoThread *thread = wait->threads [i];
3104 EnterCriticalSection (thread->synch_cs);
3105 if ((thread->state & ThreadState_Suspended) != 0) {
3106 CloseHandle (thread->suspended_event);
3107 thread->suspended_event = NULL;
3109 LeaveCriticalSection (thread->synch_cs);
3113 * If there are threads which are starting up, we wait until they
3114 * are suspended when they try to register in the threads hash.
3115 * This is guaranteed to finish, since the threads which can create new
3116 * threads get suspended after a while.
3117 * FIXME: The finalizer thread can still create new threads.
3119 mono_threads_lock ();
3120 starting = mono_g_hash_table_size (threads_starting_up) > 0;
3121 mono_threads_unlock ();
3135 collect_threads (gpointer key, gpointer value, gpointer user_data)
3137 MonoThread *thread = (MonoThread*)value;
3138 struct wait_data *wait = (struct wait_data*)user_data;
3141 if (wait->num<MAXIMUM_WAIT_OBJECTS) {
3142 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
3146 wait->handles [wait->num] = handle;
3147 wait->threads [wait->num] = thread;
3153 * mono_threads_request_thread_dump:
3155 * Ask all threads except the current to print their stacktrace to stdout.
3158 mono_threads_request_thread_dump (void)
3160 struct wait_data *wait = g_new0 (struct wait_data, 1);
3164 * Make a copy of the hashtable since we can't do anything with
3165 * threads while threads_mutex is held.
3167 mono_threads_lock ();
3168 mono_g_hash_table_foreach (threads, collect_threads, wait);
3169 mono_threads_unlock ();
3171 for (i = 0; i < wait->num; ++i) {
3172 MonoThread *thread = wait->threads [i];
3174 if (!mono_gc_is_finalizer_thread (thread) && (thread != mono_thread_current ()) && !thread->thread_dump_requested) {
3175 thread->thread_dump_requested = TRUE;
3177 signal_thread_state_change (thread);
3180 CloseHandle (wait->handles [i]);
3185 * mono_thread_push_appdomain_ref:
3187 * Register that the current thread may have references to objects in domain
3188 * @domain on its stack. Each call to this function should be paired with a
3189 * call to pop_appdomain_ref.
3192 mono_thread_push_appdomain_ref (MonoDomain *domain)
3194 MonoThread *thread = mono_thread_current ();
3197 /* printf ("PUSH REF: %"G_GSIZE_FORMAT" -> %s.\n", (gsize)thread->tid, domain->friendly_name); */
3198 mono_threads_lock ();
3199 thread->appdomain_refs = g_slist_prepend (thread->appdomain_refs, domain);
3200 mono_threads_unlock ();
3205 mono_thread_pop_appdomain_ref (void)
3207 MonoThread *thread = mono_thread_current ();
3210 /* printf ("POP REF: %"G_GSIZE_FORMAT" -> %s.\n", (gsize)thread->tid, ((MonoDomain*)(thread->appdomain_refs->data))->friendly_name); */
3211 mono_threads_lock ();
3212 /* FIXME: How can the list be empty ? */
3213 if (thread->appdomain_refs)
3214 thread->appdomain_refs = g_slist_remove (thread->appdomain_refs, thread->appdomain_refs->data);
3215 mono_threads_unlock ();
3220 mono_thread_has_appdomain_ref (MonoThread *thread, MonoDomain *domain)
3223 mono_threads_lock ();
3224 res = g_slist_find (thread->appdomain_refs, domain) != NULL;
3225 mono_threads_unlock ();
3229 typedef struct abort_appdomain_data {
3230 struct wait_data wait;
3232 } abort_appdomain_data;
3235 collect_appdomain_thread (gpointer key, gpointer value, gpointer user_data)
3237 MonoThread *thread = (MonoThread*)value;
3238 abort_appdomain_data *data = (abort_appdomain_data*)user_data;
3239 MonoDomain *domain = data->domain;
3241 if (mono_thread_has_appdomain_ref (thread, domain)) {
3242 /* printf ("ABORTING THREAD %p BECAUSE IT REFERENCES DOMAIN %s.\n", thread->tid, domain->friendly_name); */
3244 if(data->wait.num<MAXIMUM_WAIT_OBJECTS) {
3245 HANDLE handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
3248 data->wait.handles [data->wait.num] = handle;
3249 data->wait.threads [data->wait.num] = thread;
3252 /* Just ignore the rest, we can't do anything with
3260 * mono_threads_abort_appdomain_threads:
3262 * Abort threads which has references to the given appdomain.
3265 mono_threads_abort_appdomain_threads (MonoDomain *domain, int timeout)
3267 abort_appdomain_data user_data;
3269 int orig_timeout = timeout;
3272 THREAD_DEBUG (g_message ("%s: starting abort", __func__));
3274 start_time = mono_msec_ticks ();
3276 mono_threads_lock ();
3278 user_data.domain = domain;
3279 user_data.wait.num = 0;
3280 /* This shouldn't take any locks */
3281 mono_g_hash_table_foreach (threads, collect_appdomain_thread, &user_data);
3282 mono_threads_unlock ();
3284 if (user_data.wait.num > 0) {
3285 /* Abort the threads outside the threads lock */
3286 for (i = 0; i < user_data.wait.num; ++i)
3287 ves_icall_System_Threading_Thread_Abort (user_data.wait.threads [i], NULL);
3290 * We should wait for the threads either to abort, or to leave the
3291 * domain. We can't do the latter, so we wait with a timeout.
3293 wait_for_tids (&user_data.wait, 100);
3296 /* Update remaining time */
3297 timeout -= mono_msec_ticks () - start_time;
3298 start_time = mono_msec_ticks ();
3300 if (orig_timeout != -1 && timeout < 0)
3303 while (user_data.wait.num > 0);
3305 THREAD_DEBUG (g_message ("%s: abort done", __func__));
3311 clear_cached_culture (gpointer key, gpointer value, gpointer user_data)
3313 MonoThread *thread = (MonoThread*)value;
3314 MonoDomain *domain = (MonoDomain*)user_data;
3317 /* No locking needed here */
3318 /* FIXME: why no locking? writes to the cache are protected with synch_cs above */
3320 if (thread->cached_culture_info) {
3321 for (i = 0; i < NUM_CACHED_CULTURES * 2; ++i) {
3322 MonoObject *obj = mono_array_get (thread->cached_culture_info, MonoObject*, i);
3323 if (obj && obj->vtable->domain == domain)
3324 mono_array_set (thread->cached_culture_info, MonoObject*, i, NULL);
3330 * mono_threads_clear_cached_culture:
3332 * Clear the cached_current_culture from all threads if it is in the
3336 mono_threads_clear_cached_culture (MonoDomain *domain)
3338 mono_threads_lock ();
3339 mono_g_hash_table_foreach (threads, clear_cached_culture, domain);
3340 mono_threads_unlock ();
3344 * mono_thread_get_undeniable_exception:
3346 * Return an exception which needs to be raised when leaving a catch clause.
3347 * This is used for undeniable exception propagation.
3350 mono_thread_get_undeniable_exception (void)
3352 MonoThread *thread = mono_thread_current ();
3354 MONO_ARCH_SAVE_REGS;
3356 if (thread && thread->abort_exc && !is_running_protected_wrapper ()) {
3358 * FIXME: Clear the abort exception and return an AppDomainUnloaded
3359 * exception if the thread no longer references a dying appdomain.
3361 thread->abort_exc->trace_ips = NULL;
3362 thread->abort_exc->stack_trace = NULL;
3363 return thread->abort_exc;
3369 #define NUM_STATIC_DATA_IDX 8
3370 static const int static_data_size [NUM_STATIC_DATA_IDX] = {
3371 1024, 4096, 16384, 65536, 262144, 1048576, 4194304, 16777216
3376 * mono_alloc_static_data
3378 * Allocate memory blocks for storing threads or context static data
3381 mono_alloc_static_data (gpointer **static_data_ptr, guint32 offset)
3383 guint idx = (offset >> 24) - 1;
3386 gpointer* static_data = *static_data_ptr;
3388 static_data = mono_gc_alloc_fixed (static_data_size [0], NULL);
3389 *static_data_ptr = static_data;
3390 static_data [0] = static_data;
3393 for (i = 1; i <= idx; ++i) {
3394 if (static_data [i])
3396 static_data [i] = mono_gc_alloc_fixed (static_data_size [i], NULL);
3401 * mono_init_static_data_info
3403 * Initializes static data counters
3405 static void mono_init_static_data_info (StaticDataInfo *static_data)
3407 static_data->idx = 0;
3408 static_data->offset = 0;
3409 static_data->freelist = NULL;
3413 * mono_alloc_static_data_slot
3415 * Generates an offset for static data. static_data contains the counters
3416 * used to generate it.
3419 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align)
3423 if (!static_data->idx && !static_data->offset) {
3425 * we use the first chunk of the first allocation also as
3426 * an array for the rest of the data
3428 static_data->offset = sizeof (gpointer) * NUM_STATIC_DATA_IDX;
3430 static_data->offset += align - 1;
3431 static_data->offset &= ~(align - 1);
3432 if (static_data->offset + size >= static_data_size [static_data->idx]) {
3433 static_data->idx ++;
3434 g_assert (size <= static_data_size [static_data->idx]);
3435 g_assert (static_data->idx < NUM_STATIC_DATA_IDX);
3436 static_data->offset = 0;
3438 offset = static_data->offset | ((static_data->idx + 1) << 24);
3439 static_data->offset += size;
3444 * ensure thread static fields already allocated are valid for thread
3445 * This function is called when a thread is created or on thread attach.
3448 thread_adjust_static_data (MonoThread *thread)
3452 mono_threads_lock ();
3453 if (thread_static_info.offset || thread_static_info.idx > 0) {
3454 /* get the current allocated size */
3455 offset = thread_static_info.offset | ((thread_static_info.idx + 1) << 24);
3456 mono_alloc_static_data (&(thread->static_data), offset);
3458 mono_threads_unlock ();
3462 alloc_thread_static_data_helper (gpointer key, gpointer value, gpointer user)
3464 MonoThread *thread = value;
3465 guint32 offset = GPOINTER_TO_UINT (user);
3467 mono_alloc_static_data (&(thread->static_data), offset);
3470 static MonoThreadDomainTls*
3471 search_tls_slot_in_freelist (StaticDataInfo *static_data, guint32 size, guint32 align)
3473 MonoThreadDomainTls* prev = NULL;
3474 MonoThreadDomainTls* tmp = static_data->freelist;
3476 if (tmp->size == size) {
3478 prev->next = tmp->next;
3480 static_data->freelist = tmp->next;
3489 * The offset for a special static variable is composed of three parts:
3490 * a bit that indicates the type of static data (0:thread, 1:context),
3491 * an index in the array of chunks of memory for the thread (thread->static_data)
3492 * and an offset in that chunk of mem. This allows allocating less memory in the
3497 mono_alloc_special_static_data (guint32 static_type, guint32 size, guint32 align)
3500 if (static_type == SPECIAL_STATIC_THREAD)
3502 MonoThreadDomainTls *item;
3503 mono_threads_lock ();
3504 item = search_tls_slot_in_freelist (&thread_static_info, size, align);
3505 /*g_print ("TLS alloc: %d in domain %p (total: %d), cached: %p\n", size, mono_domain_get (), thread_static_info.offset, item);*/
3507 offset = item->offset;
3510 offset = mono_alloc_static_data_slot (&thread_static_info, size, align);
3512 /* This can be called during startup */
3513 if (threads != NULL)
3514 mono_g_hash_table_foreach (threads, alloc_thread_static_data_helper, GUINT_TO_POINTER (offset));
3515 mono_threads_unlock ();
3519 g_assert (static_type == SPECIAL_STATIC_CONTEXT);
3520 mono_contexts_lock ();
3521 offset = mono_alloc_static_data_slot (&context_static_info, size, align);
3522 mono_contexts_unlock ();
3523 offset |= 0x80000000; /* Set the high bit to indicate context static data */
3529 mono_get_special_static_data (guint32 offset)
3531 /* The high bit means either thread (0) or static (1) data. */
3533 guint32 static_type = (offset & 0x80000000);
3536 offset &= 0x7fffffff;
3537 idx = (offset >> 24) - 1;
3539 if (static_type == 0)
3541 MonoThread *thread = mono_thread_current ();
3542 return ((char*) thread->static_data [idx]) + (offset & 0xffffff);
3546 /* Allocate static data block under demand, since we don't have a list
3549 MonoAppContext *context = mono_context_get ();
3550 if (!context->static_data || !context->static_data [idx]) {
3551 mono_contexts_lock ();
3552 mono_alloc_static_data (&(context->static_data), offset);
3553 mono_contexts_unlock ();
3555 return ((char*) context->static_data [idx]) + (offset & 0xffffff);
3565 free_thread_static_data_helper (gpointer key, gpointer value, gpointer user)
3567 MonoThread *thread = value;
3568 TlsOffsetSize *data = user;
3569 int idx = (data->offset >> 24) - 1;
3572 if (!thread->static_data || !thread->static_data [idx])
3574 ptr = ((char*) thread->static_data [idx]) + (data->offset & 0xffffff);
3575 memset (ptr, 0, data->size);
3579 do_free_special (gpointer key, gpointer value, gpointer data)
3581 MonoClassField *field = key;
3582 guint32 offset = GPOINTER_TO_UINT (value);
3583 guint32 static_type = (offset & 0x80000000);
3586 size = mono_type_size (field->type, &align);
3587 /*g_print ("free %s , size: %d, offset: %x\n", field->name, size, offset);*/
3588 if (static_type == 0) {
3590 MonoThreadDomainTls *item = g_new0 (MonoThreadDomainTls, 1);
3591 data.offset = offset & 0x7fffffff;
3593 if (threads != NULL)
3594 mono_g_hash_table_foreach (threads, free_thread_static_data_helper, &data);
3595 item->offset = offset;
3597 item->next = thread_static_info.freelist;
3598 thread_static_info.freelist = item;
3600 /* FIXME: free context static data as well */
3605 mono_alloc_special_static_data_free (GHashTable *special_static_fields)
3607 mono_threads_lock ();
3608 g_hash_table_foreach (special_static_fields, do_free_special, NULL);
3609 mono_threads_unlock ();
3612 static MonoClassField *local_slots = NULL;
3615 /* local tls data to get locals_slot from a thread */
3618 /* index in the locals_slot array */
3623 clear_local_slot (gpointer key, gpointer value, gpointer user_data)
3625 LocalSlotID *sid = user_data;
3626 MonoThread *thread = (MonoThread*)value;
3627 MonoArray *slots_array;
3629 * the static field is stored at: ((char*) thread->static_data [idx]) + (offset & 0xffffff);
3630 * it is for the right domain, so we need to check if it is allocated an initialized
3631 * for the current thread.
3633 /*g_print ("handling thread %p\n", thread);*/
3634 if (!thread->static_data || !thread->static_data [sid->idx])
3636 slots_array = *(MonoArray **)(((char*) thread->static_data [sid->idx]) + (sid->offset & 0xffffff));
3637 if (!slots_array || sid->slot >= mono_array_length (slots_array))
3639 mono_array_set (slots_array, MonoObject*, sid->slot, NULL);
3643 mono_thread_free_local_slot_values (int slot, MonoBoolean thread_local)
3651 local_slots = mono_class_get_field_from_name (mono_defaults.thread_class, "local_slots");
3653 g_warning ("local_slots field not found in Thread class");
3657 domain = mono_domain_get ();
3658 mono_domain_lock (domain);
3659 if (domain->special_static_fields)
3660 addr = g_hash_table_lookup (domain->special_static_fields, local_slots);
3661 mono_domain_unlock (domain);
3664 /*g_print ("freeing slot %d at %p\n", slot, addr);*/
3665 sid.offset = GPOINTER_TO_UINT (addr);
3666 sid.offset &= 0x7fffffff;
3667 sid.idx = (sid.offset >> 24) - 1;
3668 mono_threads_lock ();
3669 mono_g_hash_table_foreach (threads, clear_local_slot, &sid);
3670 mono_threads_unlock ();
3672 /* FIXME: clear the slot for MonoAppContexts, too */
3676 #ifdef PLATFORM_WIN32
3677 static void CALLBACK dummy_apc (ULONG_PTR param)
3681 static guint32 dummy_apc (gpointer param)
3688 * mono_thread_execute_interruption
3690 * Performs the operation that the requested thread state requires (abort,
3693 static MonoException* mono_thread_execute_interruption (MonoThread *thread)
3695 ensure_synch_cs_set (thread);
3697 EnterCriticalSection (thread->synch_cs);
3699 /* MonoThread::interruption_requested can only be changed with atomics */
3700 if (InterlockedCompareExchange (&thread->interruption_requested, FALSE, TRUE)) {
3701 /* this will consume pending APC calls */
3702 WaitForSingleObjectEx (GetCurrentThread(), 0, TRUE);
3703 InterlockedDecrement (&thread_interruption_requested);
3704 #ifndef PLATFORM_WIN32
3705 /* Clear the interrupted flag of the thread so it can wait again */
3706 wapi_clear_interruption ();
3710 if ((thread->state & ThreadState_AbortRequested) != 0) {
3711 LeaveCriticalSection (thread->synch_cs);
3712 if (thread->abort_exc == NULL) {
3714 * This might be racy, but it has to be called outside the lock
3715 * since it calls managed code.
3717 MONO_OBJECT_SETREF (thread, abort_exc, mono_get_exception_thread_abort ());
3719 return thread->abort_exc;
3721 else if ((thread->state & ThreadState_SuspendRequested) != 0) {
3722 thread->state &= ~ThreadState_SuspendRequested;
3723 thread->state |= ThreadState_Suspended;
3724 thread->suspend_event = CreateEvent (NULL, TRUE, FALSE, NULL);
3725 if (thread->suspend_event == NULL) {
3726 LeaveCriticalSection (thread->synch_cs);
3729 if (thread->suspended_event)
3730 SetEvent (thread->suspended_event);
3732 LeaveCriticalSection (thread->synch_cs);
3734 if (shutting_down) {
3735 /* After we left the lock, the runtime might shut down so everything becomes invalid */
3740 WaitForSingleObject (thread->suspend_event, INFINITE);
3742 EnterCriticalSection (thread->synch_cs);
3744 CloseHandle (thread->suspend_event);
3745 thread->suspend_event = NULL;
3746 thread->state &= ~ThreadState_Suspended;
3748 /* The thread that requested the resume will have replaced this event
3749 * and will be waiting for it
3751 SetEvent (thread->resume_event);
3753 LeaveCriticalSection (thread->synch_cs);
3757 else if ((thread->state & ThreadState_StopRequested) != 0) {
3758 /* FIXME: do this through the JIT? */
3760 LeaveCriticalSection (thread->synch_cs);
3762 mono_thread_exit ();
3764 } else if (thread->thread_interrupt_requested) {
3766 thread->thread_interrupt_requested = FALSE;
3767 LeaveCriticalSection (thread->synch_cs);
3769 return(mono_get_exception_thread_interrupted ());
3772 LeaveCriticalSection (thread->synch_cs);
3778 * mono_thread_request_interruption
3780 * A signal handler can call this method to request the interruption of a
3781 * thread. The result of the interruption will depend on the current state of
3782 * the thread. If the result is an exception that needs to be throw, it is
3783 * provided as return value.
3786 mono_thread_request_interruption (gboolean running_managed)
3788 MonoThread *thread = mono_thread_current ();
3790 /* The thread may already be stopping */
3794 #ifdef PLATFORM_WIN32
3795 if (thread->interrupt_on_stop &&
3796 thread->state & ThreadState_StopRequested &&
3797 thread->state & ThreadState_Background)
3801 if (InterlockedCompareExchange (&thread->interruption_requested, 1, 0) == 1)
3804 if (!running_managed || is_running_protected_wrapper ()) {
3805 /* Can't stop while in unmanaged code. Increase the global interruption
3806 request count. When exiting the unmanaged method the count will be
3807 checked and the thread will be interrupted. */
3809 InterlockedIncrement (&thread_interruption_requested);
3811 if (mono_thread_notify_pending_exc_fn && !running_managed)
3812 /* The JIT will notify the thread about the interruption */
3813 /* This shouldn't take any locks */
3814 mono_thread_notify_pending_exc_fn ();
3816 /* this will awake the thread if it is in WaitForSingleObject
3818 /* Our implementation of this function ignores the func argument */
3819 QueueUserAPC ((PAPCFUNC)dummy_apc, thread->handle, NULL);
3823 return mono_thread_execute_interruption (thread);
3827 gboolean mono_thread_interruption_requested ()
3829 if (thread_interruption_requested) {
3830 MonoThread *thread = mono_thread_current ();
3831 /* The thread may already be stopping */
3833 return (thread->interruption_requested);
3838 static void mono_thread_interruption_checkpoint_request (gboolean bypass_abort_protection)
3840 MonoThread *thread = mono_thread_current ();
3842 /* The thread may already be stopping */
3846 mono_debugger_check_interruption ();
3848 if (thread->interruption_requested && (bypass_abort_protection || !is_running_protected_wrapper ())) {
3849 MonoException* exc = mono_thread_execute_interruption (thread);
3850 if (exc) mono_raise_exception (exc);
3855 * Performs the interruption of the current thread, if one has been requested,
3856 * and the thread is not running a protected wrapper.
3858 void mono_thread_interruption_checkpoint ()
3860 mono_thread_interruption_checkpoint_request (FALSE);
3864 * Performs the interruption of the current thread, if one has been requested.
3866 void mono_thread_force_interruption_checkpoint ()
3868 mono_thread_interruption_checkpoint_request (TRUE);
3872 * mono_thread_get_and_clear_pending_exception:
3874 * Return any pending exceptions for the current thread and clear it as a side effect.
3877 mono_thread_get_and_clear_pending_exception (void)
3879 MonoThread *thread = mono_thread_current ();
3881 /* The thread may already be stopping */
3885 if (thread->interruption_requested && !is_running_protected_wrapper ()) {
3886 return mono_thread_execute_interruption (thread);
3889 if (thread->pending_exception) {
3890 MonoException *exc = thread->pending_exception;
3892 thread->pending_exception = NULL;
3900 * mono_set_pending_exception:
3902 * Set the pending exception of the current thread to EXC. On platforms which
3903 * support it, the exception will be thrown when execution returns to managed code.
3904 * On other platforms, this function is equivalent to mono_raise_exception ().
3905 * Internal calls which report exceptions using this function instead of
3906 * raise_exception () might be called by JITted code using a more efficient calling
3910 mono_set_pending_exception (MonoException *exc)
3912 MonoThread *thread = mono_thread_current ();
3914 /* The thread may already be stopping */
3918 if (mono_thread_notify_pending_exc_fn) {
3919 MONO_OBJECT_SETREF (thread, pending_exception, exc);
3921 mono_thread_notify_pending_exc_fn ();
3923 /* No way to notify the JIT about the exception, have to throw it now */
3924 mono_raise_exception (exc);
3929 * mono_thread_interruption_request_flag:
3931 * Returns the address of a flag that will be non-zero if an interruption has
3932 * been requested for a thread. The thread to interrupt may not be the current
3933 * thread, so an additional call to mono_thread_interruption_requested() or
3934 * mono_thread_interruption_checkpoint() is allways needed if the flag is not
3937 gint32* mono_thread_interruption_request_flag ()
3939 return &thread_interruption_requested;
3943 mono_thread_init_apartment_state (void)
3946 thread = mono_thread_current ();
3948 #ifdef PLATFORM_WIN32
3949 /* Positive return value indicates success, either
3950 * S_OK if this is first CoInitialize call, or
3951 * S_FALSE if CoInitialize already called, but with same
3952 * threading model. A negative value indicates failure,
3953 * probably due to trying to change the threading model.
3955 if (CoInitializeEx(NULL, (thread->apartment_state == ThreadApartmentState_STA)
3956 ? COINIT_APARTMENTTHREADED
3957 : COINIT_MULTITHREADED) < 0) {
3958 thread->apartment_state = ThreadApartmentState_Unknown;
3964 mono_thread_cleanup_apartment_state (void)
3966 #ifdef PLATFORM_WIN32
3968 thread = mono_thread_current ();
3970 if (thread && thread->apartment_state != ThreadApartmentState_Unknown) {
3977 mono_thread_set_state (MonoThread *thread, MonoThreadState state)
3979 ensure_synch_cs_set (thread);
3981 EnterCriticalSection (thread->synch_cs);
3982 thread->state |= state;
3983 LeaveCriticalSection (thread->synch_cs);
3987 mono_thread_clr_state (MonoThread *thread, MonoThreadState state)
3989 ensure_synch_cs_set (thread);
3991 EnterCriticalSection (thread->synch_cs);
3992 thread->state &= ~state;
3993 LeaveCriticalSection (thread->synch_cs);
3997 mono_thread_test_state (MonoThread *thread, MonoThreadState test)
3999 gboolean ret = FALSE;
4001 ensure_synch_cs_set (thread);
4003 EnterCriticalSection (thread->synch_cs);
4005 if ((thread->state & test) != 0) {
4009 LeaveCriticalSection (thread->synch_cs);
4014 static MonoClassField *execution_context_field;
4017 get_execution_context_addr (void)
4019 MonoDomain *domain = mono_domain_get ();
4022 if (!execution_context_field) {
4023 execution_context_field = mono_class_get_field_from_name (mono_defaults.thread_class,
4025 g_assert (execution_context_field);
4028 g_assert (mono_class_try_get_vtable (domain, mono_defaults.appdomain_class));
4030 mono_domain_lock (domain);
4031 offset = GPOINTER_TO_UINT (g_hash_table_lookup (domain->special_static_fields, execution_context_field));
4032 mono_domain_unlock (domain);
4035 return (MonoObject**) mono_get_special_static_data (offset);
4039 mono_thread_get_execution_context (void)
4041 return *get_execution_context_addr ();
4045 mono_thread_set_execution_context (MonoObject *ec)
4047 *get_execution_context_addr () = ec;
4050 static gboolean has_tls_get = FALSE;
4053 mono_runtime_set_has_tls_get (gboolean val)
4059 mono_runtime_has_tls_get (void)