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;
2527 void mono_thread_init (MonoThreadStartCB start_cb,
2528 MonoThreadAttachCB attach_cb)
2530 MONO_GC_REGISTER_ROOT (small_id_table);
2531 InitializeCriticalSection(&threads_mutex);
2532 InitializeCriticalSection(&interlocked_mutex);
2533 InitializeCriticalSection(&contexts_mutex);
2534 InitializeCriticalSection(&delayed_free_table_mutex);
2535 InitializeCriticalSection(&small_id_mutex);
2537 background_change_event = CreateEvent (NULL, TRUE, FALSE, NULL);
2538 g_assert(background_change_event != NULL);
2540 mono_init_static_data_info (&thread_static_info);
2541 mono_init_static_data_info (&context_static_info);
2543 current_object_key=TlsAlloc();
2544 THREAD_DEBUG (g_message ("%s: Allocated current_object_key %d", __func__, current_object_key));
2546 mono_thread_start_cb = start_cb;
2547 mono_thread_attach_cb = attach_cb;
2549 delayed_free_table = g_array_new (FALSE, FALSE, sizeof (DelayedFreeItem));
2551 /* Get a pseudo handle to the current process. This is just a
2552 * kludge so that wapi can build a process handle if needed.
2553 * As a pseudo handle is returned, we don't need to clean
2556 GetCurrentProcess ();
2559 void mono_thread_cleanup (void)
2561 mono_thread_hazardous_try_free_all ();
2563 #if !defined(PLATFORM_WIN32) && !defined(RUN_IN_SUBTHREAD)
2564 /* The main thread must abandon any held mutexes (particularly
2565 * important for named mutexes as they are shared across
2566 * processes, see bug 74680.) This will happen when the
2567 * thread exits, but if it's not running in a subthread it
2568 * won't exit in time.
2570 /* Using non-w32 API is a nasty kludge, but I couldn't find
2571 * anything in the documentation that would let me do this
2572 * here yet still be safe to call on windows.
2574 _wapi_thread_signal_self (mono_environment_exitcode_get ());
2578 /* This stuff needs more testing, it seems one of these
2579 * critical sections can be locked when mono_thread_cleanup is
2582 DeleteCriticalSection (&threads_mutex);
2583 DeleteCriticalSection (&interlocked_mutex);
2584 DeleteCriticalSection (&contexts_mutex);
2585 DeleteCriticalSection (&delayed_free_table_mutex);
2586 DeleteCriticalSection (&small_id_mutex);
2587 CloseHandle (background_change_event);
2590 g_array_free (delayed_free_table, TRUE);
2591 delayed_free_table = NULL;
2593 TlsFree (current_object_key);
2597 mono_threads_install_cleanup (MonoThreadCleanupFunc func)
2599 mono_thread_cleanup_fn = func;
2603 mono_thread_set_manage_callback (MonoThread *thread, MonoThreadManageCallback func)
2605 thread->manage_callback = func;
2608 void mono_threads_install_notify_pending_exc (MonoThreadNotifyPendingExcFunc func)
2610 mono_thread_notify_pending_exc_fn = func;
2614 static void print_tids (gpointer key, gpointer value, gpointer user)
2616 /* GPOINTER_TO_UINT breaks horribly if sizeof(void *) >
2617 * sizeof(uint) and a cast to uint would overflow
2619 /* Older versions of glib don't have G_GSIZE_FORMAT, so just
2620 * print this as a pointer.
2622 g_message ("Waiting for: %p", key);
2627 HANDLE handles[MAXIMUM_WAIT_OBJECTS];
2628 MonoThread *threads[MAXIMUM_WAIT_OBJECTS];
2632 static void wait_for_tids (struct wait_data *wait, guint32 timeout)
2636 THREAD_DEBUG (g_message("%s: %d threads to wait for in this batch", __func__, wait->num));
2638 ret=WaitForMultipleObjectsEx(wait->num, wait->handles, TRUE, timeout, FALSE);
2640 if(ret==WAIT_FAILED) {
2641 /* See the comment in build_wait_tids() */
2642 THREAD_DEBUG (g_message ("%s: Wait failed", __func__));
2646 for(i=0; i<wait->num; i++)
2647 CloseHandle (wait->handles[i]);
2649 if (ret == WAIT_TIMEOUT)
2652 for(i=0; i<wait->num; i++) {
2653 gsize tid = wait->threads[i]->tid;
2655 mono_threads_lock ();
2656 if(mono_g_hash_table_lookup (threads, (gpointer)tid)!=NULL) {
2657 /* This thread must have been killed, because
2658 * it hasn't cleaned itself up. (It's just
2659 * possible that the thread exited before the
2660 * parent thread had a chance to store the
2661 * handle, and now there is another pointer to
2662 * the already-exited thread stored. In this
2663 * case, we'll just get two
2664 * mono_profiler_thread_end() calls for the
2668 mono_threads_unlock ();
2669 THREAD_DEBUG (g_message ("%s: cleaning up after thread %p (%"G_GSIZE_FORMAT")", __func__, wait->threads[i], tid));
2670 thread_cleanup (wait->threads[i]);
2672 mono_threads_unlock ();
2677 static void wait_for_tids_or_state_change (struct wait_data *wait, guint32 timeout)
2679 guint32 i, ret, count;
2681 THREAD_DEBUG (g_message("%s: %d threads to wait for in this batch", __func__, wait->num));
2683 /* Add the thread state change event, so it wakes up if a thread changes
2684 * to background mode.
2687 if (count < MAXIMUM_WAIT_OBJECTS) {
2688 wait->handles [count] = background_change_event;
2692 ret=WaitForMultipleObjectsEx (count, wait->handles, FALSE, timeout, FALSE);
2694 if(ret==WAIT_FAILED) {
2695 /* See the comment in build_wait_tids() */
2696 THREAD_DEBUG (g_message ("%s: Wait failed", __func__));
2700 for(i=0; i<wait->num; i++)
2701 CloseHandle (wait->handles[i]);
2703 if (ret == WAIT_TIMEOUT)
2706 if (ret < wait->num) {
2707 gsize tid = wait->threads[ret]->tid;
2708 mono_threads_lock ();
2709 if (mono_g_hash_table_lookup (threads, (gpointer)tid)!=NULL) {
2710 /* See comment in wait_for_tids about thread cleanup */
2711 mono_threads_unlock ();
2712 THREAD_DEBUG (g_message ("%s: cleaning up after thread %"G_GSIZE_FORMAT, __func__, tid));
2713 thread_cleanup (wait->threads [ret]);
2715 mono_threads_unlock ();
2719 static void build_wait_tids (gpointer key, gpointer value, gpointer user)
2721 struct wait_data *wait=(struct wait_data *)user;
2723 if(wait->num<MAXIMUM_WAIT_OBJECTS) {
2725 MonoThread *thread=(MonoThread *)value;
2727 /* Ignore background threads, we abort them later */
2728 /* Do not lock here since it is not needed and the caller holds threads_lock */
2729 if (thread->state & ThreadState_Background) {
2730 THREAD_DEBUG (g_message ("%s: ignoring background thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2731 return; /* just leave, ignore */
2734 if (mono_gc_is_finalizer_thread (thread)) {
2735 THREAD_DEBUG (g_message ("%s: ignoring finalizer thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2739 if (thread == mono_thread_current ()) {
2740 THREAD_DEBUG (g_message ("%s: ignoring current thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2744 if (thread == mono_thread_get_main ()) {
2745 THREAD_DEBUG (g_message ("%s: ignoring main thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2749 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
2750 if (handle == NULL) {
2751 THREAD_DEBUG (g_message ("%s: ignoring unopenable thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2755 THREAD_DEBUG (g_message ("%s: Invoking mono_thread_manage callback on thread %p", __func__, thread));
2756 if ((thread->manage_callback == NULL) || (thread->manage_callback (thread) == TRUE)) {
2757 wait->handles[wait->num]=handle;
2758 wait->threads[wait->num]=thread;
2761 THREAD_DEBUG (g_message ("%s: adding thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2763 THREAD_DEBUG (g_message ("%s: ignoring (because of callback) thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2768 /* Just ignore the rest, we can't do anything with
2775 remove_and_abort_threads (gpointer key, gpointer value, gpointer user)
2777 struct wait_data *wait=(struct wait_data *)user;
2778 gsize self = GetCurrentThreadId ();
2779 MonoThread *thread = (MonoThread *) value;
2782 if (wait->num >= MAXIMUM_WAIT_OBJECTS)
2785 /* The finalizer thread is not a background thread */
2786 if (thread->tid != self && (thread->state & ThreadState_Background) != 0) {
2788 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
2792 /* printf ("A: %d\n", wait->num); */
2793 wait->handles[wait->num]=thread->handle;
2794 wait->threads[wait->num]=thread;
2797 THREAD_DEBUG (g_print ("%s: Aborting id: %"G_GSIZE_FORMAT"\n", __func__, (gsize)thread->tid));
2798 mono_thread_stop (thread);
2802 return (thread->tid != self && !mono_gc_is_finalizer_thread (thread));
2806 * mono_threads_set_shutting_down:
2808 * Is called by a thread that wants to shut down Mono. If the runtime is already
2809 * shutting down, the calling thread is suspended/stopped, and this function never
2813 mono_threads_set_shutting_down (void)
2815 MonoThread *current_thread = mono_thread_current ();
2817 mono_threads_lock ();
2819 if (shutting_down) {
2820 mono_threads_unlock ();
2822 /* Make sure we're properly suspended/stopped */
2824 EnterCriticalSection (current_thread->synch_cs);
2826 if ((current_thread->state & ThreadState_SuspendRequested) ||
2827 (current_thread->state & ThreadState_AbortRequested) ||
2828 (current_thread->state & ThreadState_StopRequested)) {
2829 LeaveCriticalSection (current_thread->synch_cs);
2830 mono_thread_execute_interruption (current_thread);
2832 current_thread->state |= ThreadState_Stopped;
2833 LeaveCriticalSection (current_thread->synch_cs);
2836 /* Wake up other threads potentially waiting for us */
2839 shutting_down = TRUE;
2841 /* Not really a background state change, but this will
2842 * interrupt the main thread if it is waiting for all
2843 * the other threads.
2845 SetEvent (background_change_event);
2847 mono_threads_unlock ();
2852 * mono_threads_is_shutting_down:
2854 * Returns whether a thread has commenced shutdown of Mono. Note that
2855 * if the function returns FALSE the caller must not assume that
2856 * shutdown is not in progress, because the situation might have
2857 * changed since the function returned. For that reason this function
2858 * is of very limited utility.
2861 mono_threads_is_shutting_down (void)
2863 return shutting_down;
2866 void mono_thread_manage (void)
2868 struct wait_data *wait=g_new0 (struct wait_data, 1);
2870 /* join each thread that's still running */
2871 THREAD_DEBUG (g_message ("%s: Joining each running thread...", __func__));
2873 mono_threads_lock ();
2875 THREAD_DEBUG (g_message("%s: No threads", __func__));
2876 mono_threads_unlock ();
2879 mono_threads_unlock ();
2882 mono_threads_lock ();
2883 if (shutting_down) {
2884 /* somebody else is shutting down */
2885 mono_threads_unlock ();
2888 THREAD_DEBUG (g_message ("%s: There are %d threads to join", __func__, mono_g_hash_table_size (threads));
2889 mono_g_hash_table_foreach (threads, print_tids, NULL));
2891 ResetEvent (background_change_event);
2893 mono_g_hash_table_foreach (threads, build_wait_tids, wait);
2894 mono_threads_unlock ();
2896 /* Something to wait for */
2897 wait_for_tids_or_state_change (wait, INFINITE);
2899 THREAD_DEBUG (g_message ("%s: I have %d threads after waiting.", __func__, wait->num));
2900 } while(wait->num>0);
2902 mono_threads_set_shutting_down ();
2904 /* No new threads will be created after this point */
2906 mono_runtime_set_shutting_down ();
2908 THREAD_DEBUG (g_message ("%s: threadpool cleanup", __func__));
2909 mono_thread_pool_cleanup ();
2912 * Remove everything but the finalizer thread and self.
2913 * Also abort all the background threads
2916 mono_threads_lock ();
2919 mono_g_hash_table_foreach_remove (threads, remove_and_abort_threads, wait);
2921 mono_threads_unlock ();
2923 THREAD_DEBUG (g_message ("%s: wait->num is now %d", __func__, wait->num));
2925 /* Something to wait for */
2926 wait_for_tids (wait, INFINITE);
2928 } while (wait->num > 0);
2931 * give the subthreads a chance to really quit (this is mainly needed
2932 * to get correct user and system times from getrusage/wait/time(1)).
2933 * This could be removed if we avoid pthread_detach() and use pthread_join().
2935 #ifndef PLATFORM_WIN32
2942 static void terminate_thread (gpointer key, gpointer value, gpointer user)
2944 MonoThread *thread=(MonoThread *)value;
2946 if(thread->tid != (gsize)user) {
2947 /*TerminateThread (thread->handle, -1);*/
2951 void mono_thread_abort_all_other_threads (void)
2953 gsize self = GetCurrentThreadId ();
2955 mono_threads_lock ();
2956 THREAD_DEBUG (g_message ("%s: There are %d threads to abort", __func__,
2957 mono_g_hash_table_size (threads));
2958 mono_g_hash_table_foreach (threads, print_tids, NULL));
2960 mono_g_hash_table_foreach (threads, terminate_thread, (gpointer)self);
2962 mono_threads_unlock ();
2966 collect_threads_for_suspend (gpointer key, gpointer value, gpointer user_data)
2968 MonoThread *thread = (MonoThread*)value;
2969 struct wait_data *wait = (struct wait_data*)user_data;
2973 * We try to exclude threads early, to avoid running into the MAXIMUM_WAIT_OBJECTS
2975 * This needs no locking.
2977 if ((thread->state & ThreadState_Suspended) != 0 ||
2978 (thread->state & ThreadState_Stopped) != 0)
2981 if (wait->num<MAXIMUM_WAIT_OBJECTS) {
2982 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
2986 wait->handles [wait->num] = handle;
2987 wait->threads [wait->num] = thread;
2993 * mono_thread_suspend_all_other_threads:
2995 * Suspend all managed threads except the finalizer thread and this thread. It is
2996 * not possible to resume them later.
2998 void mono_thread_suspend_all_other_threads (void)
3000 struct wait_data *wait = g_new0 (struct wait_data, 1);
3002 gsize self = GetCurrentThreadId ();
3004 guint32 eventidx = 0;
3005 gboolean starting, finished;
3008 * The other threads could be in an arbitrary state at this point, i.e.
3009 * they could be starting up, shutting down etc. This means that there could be
3010 * threads which are not even in the threads hash table yet.
3014 * First we set a barrier which will be checked by all threads before they
3015 * are added to the threads hash table, and they will exit if the flag is set.
3016 * This ensures that no threads could be added to the hash later.
3017 * We will use shutting_down as the barrier for now.
3019 g_assert (shutting_down);
3022 * We make multiple calls to WaitForMultipleObjects since:
3023 * - we can only wait for MAXIMUM_WAIT_OBJECTS threads
3024 * - some threads could exit without becoming suspended
3029 * Make a copy of the hashtable since we can't do anything with
3030 * threads while threads_mutex is held.
3033 mono_threads_lock ();
3034 mono_g_hash_table_foreach (threads, collect_threads_for_suspend, wait);
3035 mono_threads_unlock ();
3037 events = g_new0 (gpointer, wait->num);
3039 /* Get the suspended events that we'll be waiting for */
3040 for (i = 0; i < wait->num; ++i) {
3041 MonoThread *thread = wait->threads [i];
3042 gboolean signal_suspend = FALSE;
3044 if ((thread->tid == self) || mono_gc_is_finalizer_thread (thread)) {
3045 //CloseHandle (wait->handles [i]);
3046 wait->threads [i] = NULL; /* ignore this thread in next loop */
3050 ensure_synch_cs_set (thread);
3052 EnterCriticalSection (thread->synch_cs);
3054 if (thread->suspended_event == NULL) {
3055 thread->suspended_event = CreateEvent (NULL, TRUE, FALSE, NULL);
3056 if (thread->suspended_event == NULL) {
3057 /* Forget this one and go on to the next */
3058 LeaveCriticalSection (thread->synch_cs);
3063 if ((thread->state & ThreadState_Suspended) != 0 ||
3064 (thread->state & ThreadState_StopRequested) != 0 ||
3065 (thread->state & ThreadState_Stopped) != 0) {
3066 LeaveCriticalSection (thread->synch_cs);
3067 CloseHandle (wait->handles [i]);
3068 wait->threads [i] = NULL; /* ignore this thread in next loop */
3072 if ((thread->state & ThreadState_SuspendRequested) == 0)
3073 signal_suspend = TRUE;
3075 events [eventidx++] = thread->suspended_event;
3077 /* Convert abort requests into suspend requests */
3078 if ((thread->state & ThreadState_AbortRequested) != 0)
3079 thread->state &= ~ThreadState_AbortRequested;
3081 thread->state |= ThreadState_SuspendRequested;
3083 LeaveCriticalSection (thread->synch_cs);
3085 /* Signal the thread to suspend */
3087 signal_thread_state_change (thread);
3091 WaitForMultipleObjectsEx (eventidx, events, TRUE, 100, FALSE);
3092 for (i = 0; i < wait->num; ++i) {
3093 MonoThread *thread = wait->threads [i];
3098 EnterCriticalSection (thread->synch_cs);
3099 if ((thread->state & ThreadState_Suspended) != 0) {
3100 CloseHandle (thread->suspended_event);
3101 thread->suspended_event = NULL;
3103 LeaveCriticalSection (thread->synch_cs);
3107 * If there are threads which are starting up, we wait until they
3108 * are suspended when they try to register in the threads hash.
3109 * This is guaranteed to finish, since the threads which can create new
3110 * threads get suspended after a while.
3111 * FIXME: The finalizer thread can still create new threads.
3113 mono_threads_lock ();
3114 starting = mono_g_hash_table_size (threads_starting_up) > 0;
3115 mono_threads_unlock ();
3129 collect_threads (gpointer key, gpointer value, gpointer user_data)
3131 MonoThread *thread = (MonoThread*)value;
3132 struct wait_data *wait = (struct wait_data*)user_data;
3135 if (wait->num<MAXIMUM_WAIT_OBJECTS) {
3136 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
3140 wait->handles [wait->num] = handle;
3141 wait->threads [wait->num] = thread;
3147 * mono_threads_request_thread_dump:
3149 * Ask all threads except the current to print their stacktrace to stdout.
3152 mono_threads_request_thread_dump (void)
3154 struct wait_data *wait = g_new0 (struct wait_data, 1);
3158 * Make a copy of the hashtable since we can't do anything with
3159 * threads while threads_mutex is held.
3161 mono_threads_lock ();
3162 mono_g_hash_table_foreach (threads, collect_threads, wait);
3163 mono_threads_unlock ();
3165 for (i = 0; i < wait->num; ++i) {
3166 MonoThread *thread = wait->threads [i];
3168 if (!mono_gc_is_finalizer_thread (thread) && (thread != mono_thread_current ()) && !thread->thread_dump_requested) {
3169 thread->thread_dump_requested = TRUE;
3171 signal_thread_state_change (thread);
3174 CloseHandle (wait->handles [i]);
3179 * mono_thread_push_appdomain_ref:
3181 * Register that the current thread may have references to objects in domain
3182 * @domain on its stack. Each call to this function should be paired with a
3183 * call to pop_appdomain_ref.
3186 mono_thread_push_appdomain_ref (MonoDomain *domain)
3188 MonoThread *thread = mono_thread_current ();
3191 /* printf ("PUSH REF: %"G_GSIZE_FORMAT" -> %s.\n", (gsize)thread->tid, domain->friendly_name); */
3192 mono_threads_lock ();
3193 thread->appdomain_refs = g_slist_prepend (thread->appdomain_refs, domain);
3194 mono_threads_unlock ();
3199 mono_thread_pop_appdomain_ref (void)
3201 MonoThread *thread = mono_thread_current ();
3204 /* printf ("POP REF: %"G_GSIZE_FORMAT" -> %s.\n", (gsize)thread->tid, ((MonoDomain*)(thread->appdomain_refs->data))->friendly_name); */
3205 mono_threads_lock ();
3206 /* FIXME: How can the list be empty ? */
3207 if (thread->appdomain_refs)
3208 thread->appdomain_refs = g_slist_remove (thread->appdomain_refs, thread->appdomain_refs->data);
3209 mono_threads_unlock ();
3214 mono_thread_has_appdomain_ref (MonoThread *thread, MonoDomain *domain)
3217 mono_threads_lock ();
3218 res = g_slist_find (thread->appdomain_refs, domain) != NULL;
3219 mono_threads_unlock ();
3223 typedef struct abort_appdomain_data {
3224 struct wait_data wait;
3226 } abort_appdomain_data;
3229 collect_appdomain_thread (gpointer key, gpointer value, gpointer user_data)
3231 MonoThread *thread = (MonoThread*)value;
3232 abort_appdomain_data *data = (abort_appdomain_data*)user_data;
3233 MonoDomain *domain = data->domain;
3235 if (mono_thread_has_appdomain_ref (thread, domain)) {
3236 /* printf ("ABORTING THREAD %p BECAUSE IT REFERENCES DOMAIN %s.\n", thread->tid, domain->friendly_name); */
3238 if(data->wait.num<MAXIMUM_WAIT_OBJECTS) {
3239 HANDLE handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
3242 data->wait.handles [data->wait.num] = handle;
3243 data->wait.threads [data->wait.num] = thread;
3246 /* Just ignore the rest, we can't do anything with
3254 * mono_threads_abort_appdomain_threads:
3256 * Abort threads which has references to the given appdomain.
3259 mono_threads_abort_appdomain_threads (MonoDomain *domain, int timeout)
3261 abort_appdomain_data user_data;
3263 int orig_timeout = timeout;
3266 THREAD_DEBUG (g_message ("%s: starting abort", __func__));
3268 start_time = mono_msec_ticks ();
3270 mono_threads_lock ();
3272 user_data.domain = domain;
3273 user_data.wait.num = 0;
3274 /* This shouldn't take any locks */
3275 mono_g_hash_table_foreach (threads, collect_appdomain_thread, &user_data);
3276 mono_threads_unlock ();
3278 if (user_data.wait.num > 0) {
3279 /* Abort the threads outside the threads lock */
3280 for (i = 0; i < user_data.wait.num; ++i)
3281 ves_icall_System_Threading_Thread_Abort (user_data.wait.threads [i], NULL);
3284 * We should wait for the threads either to abort, or to leave the
3285 * domain. We can't do the latter, so we wait with a timeout.
3287 wait_for_tids (&user_data.wait, 100);
3290 /* Update remaining time */
3291 timeout -= mono_msec_ticks () - start_time;
3292 start_time = mono_msec_ticks ();
3294 if (orig_timeout != -1 && timeout < 0)
3297 while (user_data.wait.num > 0);
3299 THREAD_DEBUG (g_message ("%s: abort done", __func__));
3305 clear_cached_culture (gpointer key, gpointer value, gpointer user_data)
3307 MonoThread *thread = (MonoThread*)value;
3308 MonoDomain *domain = (MonoDomain*)user_data;
3311 /* No locking needed here */
3312 /* FIXME: why no locking? writes to the cache are protected with synch_cs above */
3314 if (thread->cached_culture_info) {
3315 for (i = 0; i < NUM_CACHED_CULTURES * 2; ++i) {
3316 MonoObject *obj = mono_array_get (thread->cached_culture_info, MonoObject*, i);
3317 if (obj && obj->vtable->domain == domain)
3318 mono_array_set (thread->cached_culture_info, MonoObject*, i, NULL);
3324 * mono_threads_clear_cached_culture:
3326 * Clear the cached_current_culture from all threads if it is in the
3330 mono_threads_clear_cached_culture (MonoDomain *domain)
3332 mono_threads_lock ();
3333 mono_g_hash_table_foreach (threads, clear_cached_culture, domain);
3334 mono_threads_unlock ();
3338 * mono_thread_get_undeniable_exception:
3340 * Return an exception which needs to be raised when leaving a catch clause.
3341 * This is used for undeniable exception propagation.
3344 mono_thread_get_undeniable_exception (void)
3346 MonoThread *thread = mono_thread_current ();
3348 MONO_ARCH_SAVE_REGS;
3350 if (thread && thread->abort_exc && !is_running_protected_wrapper ()) {
3352 * FIXME: Clear the abort exception and return an AppDomainUnloaded
3353 * exception if the thread no longer references a dying appdomain.
3355 thread->abort_exc->trace_ips = NULL;
3356 thread->abort_exc->stack_trace = NULL;
3357 return thread->abort_exc;
3363 #define NUM_STATIC_DATA_IDX 8
3364 static const int static_data_size [NUM_STATIC_DATA_IDX] = {
3365 1024, 4096, 16384, 65536, 262144, 1048576, 4194304, 16777216
3370 * mono_alloc_static_data
3372 * Allocate memory blocks for storing threads or context static data
3375 mono_alloc_static_data (gpointer **static_data_ptr, guint32 offset)
3377 guint idx = (offset >> 24) - 1;
3380 gpointer* static_data = *static_data_ptr;
3382 static_data = mono_gc_alloc_fixed (static_data_size [0], NULL);
3383 *static_data_ptr = static_data;
3384 static_data [0] = static_data;
3387 for (i = 1; i <= idx; ++i) {
3388 if (static_data [i])
3390 static_data [i] = mono_gc_alloc_fixed (static_data_size [i], NULL);
3395 * mono_init_static_data_info
3397 * Initializes static data counters
3399 static void mono_init_static_data_info (StaticDataInfo *static_data)
3401 static_data->idx = 0;
3402 static_data->offset = 0;
3403 static_data->freelist = NULL;
3407 * mono_alloc_static_data_slot
3409 * Generates an offset for static data. static_data contains the counters
3410 * used to generate it.
3413 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align)
3417 if (!static_data->idx && !static_data->offset) {
3419 * we use the first chunk of the first allocation also as
3420 * an array for the rest of the data
3422 static_data->offset = sizeof (gpointer) * NUM_STATIC_DATA_IDX;
3424 static_data->offset += align - 1;
3425 static_data->offset &= ~(align - 1);
3426 if (static_data->offset + size >= static_data_size [static_data->idx]) {
3427 static_data->idx ++;
3428 g_assert (size <= static_data_size [static_data->idx]);
3429 g_assert (static_data->idx < NUM_STATIC_DATA_IDX);
3430 static_data->offset = 0;
3432 offset = static_data->offset | ((static_data->idx + 1) << 24);
3433 static_data->offset += size;
3438 * ensure thread static fields already allocated are valid for thread
3439 * This function is called when a thread is created or on thread attach.
3442 thread_adjust_static_data (MonoThread *thread)
3446 mono_threads_lock ();
3447 if (thread_static_info.offset || thread_static_info.idx > 0) {
3448 /* get the current allocated size */
3449 offset = thread_static_info.offset | ((thread_static_info.idx + 1) << 24);
3450 mono_alloc_static_data (&(thread->static_data), offset);
3452 mono_threads_unlock ();
3456 alloc_thread_static_data_helper (gpointer key, gpointer value, gpointer user)
3458 MonoThread *thread = value;
3459 guint32 offset = GPOINTER_TO_UINT (user);
3461 mono_alloc_static_data (&(thread->static_data), offset);
3464 static MonoThreadDomainTls*
3465 search_tls_slot_in_freelist (StaticDataInfo *static_data, guint32 size, guint32 align)
3467 MonoThreadDomainTls* prev = NULL;
3468 MonoThreadDomainTls* tmp = static_data->freelist;
3470 if (tmp->size == size) {
3472 prev->next = tmp->next;
3474 static_data->freelist = tmp->next;
3483 * The offset for a special static variable is composed of three parts:
3484 * a bit that indicates the type of static data (0:thread, 1:context),
3485 * an index in the array of chunks of memory for the thread (thread->static_data)
3486 * and an offset in that chunk of mem. This allows allocating less memory in the
3491 mono_alloc_special_static_data (guint32 static_type, guint32 size, guint32 align)
3494 if (static_type == SPECIAL_STATIC_THREAD)
3496 MonoThreadDomainTls *item;
3497 mono_threads_lock ();
3498 item = search_tls_slot_in_freelist (&thread_static_info, size, align);
3499 /*g_print ("TLS alloc: %d in domain %p (total: %d), cached: %p\n", size, mono_domain_get (), thread_static_info.offset, item);*/
3501 offset = item->offset;
3504 offset = mono_alloc_static_data_slot (&thread_static_info, size, align);
3506 /* This can be called during startup */
3507 if (threads != NULL)
3508 mono_g_hash_table_foreach (threads, alloc_thread_static_data_helper, GUINT_TO_POINTER (offset));
3509 mono_threads_unlock ();
3513 g_assert (static_type == SPECIAL_STATIC_CONTEXT);
3514 mono_contexts_lock ();
3515 offset = mono_alloc_static_data_slot (&context_static_info, size, align);
3516 mono_contexts_unlock ();
3517 offset |= 0x80000000; /* Set the high bit to indicate context static data */
3523 mono_get_special_static_data (guint32 offset)
3525 /* The high bit means either thread (0) or static (1) data. */
3527 guint32 static_type = (offset & 0x80000000);
3530 offset &= 0x7fffffff;
3531 idx = (offset >> 24) - 1;
3533 if (static_type == 0)
3535 MonoThread *thread = mono_thread_current ();
3536 return ((char*) thread->static_data [idx]) + (offset & 0xffffff);
3540 /* Allocate static data block under demand, since we don't have a list
3543 MonoAppContext *context = mono_context_get ();
3544 if (!context->static_data || !context->static_data [idx]) {
3545 mono_contexts_lock ();
3546 mono_alloc_static_data (&(context->static_data), offset);
3547 mono_contexts_unlock ();
3549 return ((char*) context->static_data [idx]) + (offset & 0xffffff);
3559 free_thread_static_data_helper (gpointer key, gpointer value, gpointer user)
3561 MonoThread *thread = value;
3562 TlsOffsetSize *data = user;
3563 int idx = (data->offset >> 24) - 1;
3566 if (!thread->static_data || !thread->static_data [idx])
3568 ptr = ((char*) thread->static_data [idx]) + (data->offset & 0xffffff);
3569 memset (ptr, 0, data->size);
3573 do_free_special (gpointer key, gpointer value, gpointer data)
3575 MonoClassField *field = key;
3576 guint32 offset = GPOINTER_TO_UINT (value);
3577 guint32 static_type = (offset & 0x80000000);
3580 size = mono_type_size (field->type, &align);
3581 /*g_print ("free %s , size: %d, offset: %x\n", field->name, size, offset);*/
3582 if (static_type == 0) {
3584 MonoThreadDomainTls *item = g_new0 (MonoThreadDomainTls, 1);
3585 data.offset = offset & 0x7fffffff;
3587 if (threads != NULL)
3588 mono_g_hash_table_foreach (threads, free_thread_static_data_helper, &data);
3589 item->offset = offset;
3591 item->next = thread_static_info.freelist;
3592 thread_static_info.freelist = item;
3594 /* FIXME: free context static data as well */
3599 mono_alloc_special_static_data_free (GHashTable *special_static_fields)
3601 mono_threads_lock ();
3602 g_hash_table_foreach (special_static_fields, do_free_special, NULL);
3603 mono_threads_unlock ();
3606 static MonoClassField *local_slots = NULL;
3609 /* local tls data to get locals_slot from a thread */
3612 /* index in the locals_slot array */
3617 clear_local_slot (gpointer key, gpointer value, gpointer user_data)
3619 LocalSlotID *sid = user_data;
3620 MonoThread *thread = (MonoThread*)value;
3621 MonoArray *slots_array;
3623 * the static field is stored at: ((char*) thread->static_data [idx]) + (offset & 0xffffff);
3624 * it is for the right domain, so we need to check if it is allocated an initialized
3625 * for the current thread.
3627 /*g_print ("handling thread %p\n", thread);*/
3628 if (!thread->static_data || !thread->static_data [sid->idx])
3630 slots_array = *(MonoArray **)(((char*) thread->static_data [sid->idx]) + (sid->offset & 0xffffff));
3631 if (!slots_array || sid->slot >= mono_array_length (slots_array))
3633 mono_array_set (slots_array, MonoObject*, sid->slot, NULL);
3637 mono_thread_free_local_slot_values (int slot, MonoBoolean thread_local)
3645 local_slots = mono_class_get_field_from_name (mono_defaults.thread_class, "local_slots");
3647 g_warning ("local_slots field not found in Thread class");
3651 domain = mono_domain_get ();
3652 mono_domain_lock (domain);
3653 if (domain->special_static_fields)
3654 addr = g_hash_table_lookup (domain->special_static_fields, local_slots);
3655 mono_domain_unlock (domain);
3658 /*g_print ("freeing slot %d at %p\n", slot, addr);*/
3659 sid.offset = GPOINTER_TO_UINT (addr);
3660 sid.offset &= 0x7fffffff;
3661 sid.idx = (sid.offset >> 24) - 1;
3662 mono_threads_lock ();
3663 mono_g_hash_table_foreach (threads, clear_local_slot, &sid);
3664 mono_threads_unlock ();
3666 /* FIXME: clear the slot for MonoAppContexts, too */
3670 #ifdef PLATFORM_WIN32
3671 static void CALLBACK dummy_apc (ULONG_PTR param)
3675 static guint32 dummy_apc (gpointer param)
3682 * mono_thread_execute_interruption
3684 * Performs the operation that the requested thread state requires (abort,
3687 static MonoException* mono_thread_execute_interruption (MonoThread *thread)
3689 ensure_synch_cs_set (thread);
3691 EnterCriticalSection (thread->synch_cs);
3693 /* MonoThread::interruption_requested can only be changed with atomics */
3694 if (InterlockedCompareExchange (&thread->interruption_requested, FALSE, TRUE)) {
3695 /* this will consume pending APC calls */
3696 WaitForSingleObjectEx (GetCurrentThread(), 0, TRUE);
3697 InterlockedDecrement (&thread_interruption_requested);
3698 #ifndef PLATFORM_WIN32
3699 /* Clear the interrupted flag of the thread so it can wait again */
3700 wapi_clear_interruption ();
3704 if ((thread->state & ThreadState_AbortRequested) != 0) {
3705 LeaveCriticalSection (thread->synch_cs);
3706 if (thread->abort_exc == NULL) {
3708 * This might be racy, but it has to be called outside the lock
3709 * since it calls managed code.
3711 MONO_OBJECT_SETREF (thread, abort_exc, mono_get_exception_thread_abort ());
3713 return thread->abort_exc;
3715 else if ((thread->state & ThreadState_SuspendRequested) != 0) {
3716 thread->state &= ~ThreadState_SuspendRequested;
3717 thread->state |= ThreadState_Suspended;
3718 thread->suspend_event = CreateEvent (NULL, TRUE, FALSE, NULL);
3719 if (thread->suspend_event == NULL) {
3720 LeaveCriticalSection (thread->synch_cs);
3723 if (thread->suspended_event)
3724 SetEvent (thread->suspended_event);
3726 LeaveCriticalSection (thread->synch_cs);
3728 if (shutting_down) {
3729 /* After we left the lock, the runtime might shut down so everything becomes invalid */
3734 WaitForSingleObject (thread->suspend_event, INFINITE);
3736 EnterCriticalSection (thread->synch_cs);
3738 CloseHandle (thread->suspend_event);
3739 thread->suspend_event = NULL;
3740 thread->state &= ~ThreadState_Suspended;
3742 /* The thread that requested the resume will have replaced this event
3743 * and will be waiting for it
3745 SetEvent (thread->resume_event);
3747 LeaveCriticalSection (thread->synch_cs);
3751 else if ((thread->state & ThreadState_StopRequested) != 0) {
3752 /* FIXME: do this through the JIT? */
3754 LeaveCriticalSection (thread->synch_cs);
3756 mono_thread_exit ();
3758 } else if (thread->thread_interrupt_requested) {
3760 thread->thread_interrupt_requested = FALSE;
3761 LeaveCriticalSection (thread->synch_cs);
3763 return(mono_get_exception_thread_interrupted ());
3766 LeaveCriticalSection (thread->synch_cs);
3772 * mono_thread_request_interruption
3774 * A signal handler can call this method to request the interruption of a
3775 * thread. The result of the interruption will depend on the current state of
3776 * the thread. If the result is an exception that needs to be throw, it is
3777 * provided as return value.
3780 mono_thread_request_interruption (gboolean running_managed)
3782 MonoThread *thread = mono_thread_current ();
3784 /* The thread may already be stopping */
3788 #ifdef PLATFORM_WIN32
3789 if (thread->interrupt_on_stop &&
3790 thread->state & ThreadState_StopRequested &&
3791 thread->state & ThreadState_Background)
3795 if (InterlockedCompareExchange (&thread->interruption_requested, 1, 0) == 1)
3798 if (!running_managed || is_running_protected_wrapper ()) {
3799 /* Can't stop while in unmanaged code. Increase the global interruption
3800 request count. When exiting the unmanaged method the count will be
3801 checked and the thread will be interrupted. */
3803 InterlockedIncrement (&thread_interruption_requested);
3805 if (mono_thread_notify_pending_exc_fn && !running_managed)
3806 /* The JIT will notify the thread about the interruption */
3807 /* This shouldn't take any locks */
3808 mono_thread_notify_pending_exc_fn ();
3810 /* this will awake the thread if it is in WaitForSingleObject
3812 /* Our implementation of this function ignores the func argument */
3813 QueueUserAPC ((PAPCFUNC)dummy_apc, thread->handle, NULL);
3817 return mono_thread_execute_interruption (thread);
3821 gboolean mono_thread_interruption_requested ()
3823 if (thread_interruption_requested) {
3824 MonoThread *thread = mono_thread_current ();
3825 /* The thread may already be stopping */
3827 return (thread->interruption_requested);
3832 static void mono_thread_interruption_checkpoint_request (gboolean bypass_abort_protection)
3834 MonoThread *thread = mono_thread_current ();
3836 /* The thread may already be stopping */
3840 mono_debugger_check_interruption ();
3842 if (thread->interruption_requested && (bypass_abort_protection || !is_running_protected_wrapper ())) {
3843 MonoException* exc = mono_thread_execute_interruption (thread);
3844 if (exc) mono_raise_exception (exc);
3849 * Performs the interruption of the current thread, if one has been requested,
3850 * and the thread is not running a protected wrapper.
3852 void mono_thread_interruption_checkpoint ()
3854 mono_thread_interruption_checkpoint_request (FALSE);
3858 * Performs the interruption of the current thread, if one has been requested.
3860 void mono_thread_force_interruption_checkpoint ()
3862 mono_thread_interruption_checkpoint_request (TRUE);
3866 * mono_thread_get_and_clear_pending_exception:
3868 * Return any pending exceptions for the current thread and clear it as a side effect.
3871 mono_thread_get_and_clear_pending_exception (void)
3873 MonoThread *thread = mono_thread_current ();
3875 /* The thread may already be stopping */
3879 if (thread->interruption_requested && !is_running_protected_wrapper ()) {
3880 return mono_thread_execute_interruption (thread);
3883 if (thread->pending_exception) {
3884 MonoException *exc = thread->pending_exception;
3886 thread->pending_exception = NULL;
3894 * mono_set_pending_exception:
3896 * Set the pending exception of the current thread to EXC. On platforms which
3897 * support it, the exception will be thrown when execution returns to managed code.
3898 * On other platforms, this function is equivalent to mono_raise_exception ().
3899 * Internal calls which report exceptions using this function instead of
3900 * raise_exception () might be called by JITted code using a more efficient calling
3904 mono_set_pending_exception (MonoException *exc)
3906 MonoThread *thread = mono_thread_current ();
3908 /* The thread may already be stopping */
3912 if (mono_thread_notify_pending_exc_fn) {
3913 MONO_OBJECT_SETREF (thread, pending_exception, exc);
3915 mono_thread_notify_pending_exc_fn ();
3917 /* No way to notify the JIT about the exception, have to throw it now */
3918 mono_raise_exception (exc);
3923 * mono_thread_interruption_request_flag:
3925 * Returns the address of a flag that will be non-zero if an interruption has
3926 * been requested for a thread. The thread to interrupt may not be the current
3927 * thread, so an additional call to mono_thread_interruption_requested() or
3928 * mono_thread_interruption_checkpoint() is allways needed if the flag is not
3931 gint32* mono_thread_interruption_request_flag ()
3933 return &thread_interruption_requested;
3937 mono_thread_init_apartment_state (void)
3940 thread = mono_thread_current ();
3942 #ifdef PLATFORM_WIN32
3943 /* Positive return value indicates success, either
3944 * S_OK if this is first CoInitialize call, or
3945 * S_FALSE if CoInitialize already called, but with same
3946 * threading model. A negative value indicates failure,
3947 * probably due to trying to change the threading model.
3949 if (CoInitializeEx(NULL, (thread->apartment_state == ThreadApartmentState_STA)
3950 ? COINIT_APARTMENTTHREADED
3951 : COINIT_MULTITHREADED) < 0) {
3952 thread->apartment_state = ThreadApartmentState_Unknown;
3958 mono_thread_cleanup_apartment_state (void)
3960 #ifdef PLATFORM_WIN32
3962 thread = mono_thread_current ();
3964 if (thread && thread->apartment_state != ThreadApartmentState_Unknown) {
3971 mono_thread_set_state (MonoThread *thread, MonoThreadState state)
3973 ensure_synch_cs_set (thread);
3975 EnterCriticalSection (thread->synch_cs);
3976 thread->state |= state;
3977 LeaveCriticalSection (thread->synch_cs);
3981 mono_thread_clr_state (MonoThread *thread, MonoThreadState state)
3983 ensure_synch_cs_set (thread);
3985 EnterCriticalSection (thread->synch_cs);
3986 thread->state &= ~state;
3987 LeaveCriticalSection (thread->synch_cs);
3991 mono_thread_test_state (MonoThread *thread, MonoThreadState test)
3993 gboolean ret = FALSE;
3995 ensure_synch_cs_set (thread);
3997 EnterCriticalSection (thread->synch_cs);
3999 if ((thread->state & test) != 0) {
4003 LeaveCriticalSection (thread->synch_cs);
4008 static MonoClassField *execution_context_field;
4011 get_execution_context_addr (void)
4013 MonoDomain *domain = mono_domain_get ();
4016 if (!execution_context_field) {
4017 execution_context_field = mono_class_get_field_from_name (mono_defaults.thread_class,
4019 g_assert (execution_context_field);
4022 g_assert (mono_class_try_get_vtable (domain, mono_defaults.appdomain_class));
4024 mono_domain_lock (domain);
4025 offset = GPOINTER_TO_UINT (g_hash_table_lookup (domain->special_static_fields, execution_context_field));
4026 mono_domain_unlock (domain);
4029 return (MonoObject**) mono_get_special_static_data (offset);
4033 mono_thread_get_execution_context (void)
4035 return *get_execution_context_addr ();
4039 mono_thread_set_execution_context (MonoObject *ec)
4041 *get_execution_context_addr () = ec;
4044 static gboolean has_tls_get = FALSE;
4047 mono_runtime_set_has_tls_get (gboolean val)
4053 mono_runtime_has_tls_get (void)