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 #if defined(__OpenBSD__)
21 #include <pthread_np.h>
24 #include <mono/metadata/object.h>
25 #include <mono/metadata/domain-internals.h>
26 #include <mono/metadata/profiler-private.h>
27 #include <mono/metadata/threads.h>
28 #include <mono/metadata/threadpool.h>
29 #include <mono/metadata/threads-types.h>
30 #include <mono/metadata/exception.h>
31 #include <mono/metadata/environment.h>
32 #include <mono/metadata/monitor.h>
33 #include <mono/metadata/gc-internal.h>
34 #include <mono/metadata/marshal.h>
35 #include <mono/io-layer/io-layer.h>
37 #include <mono/io-layer/threads.h>
39 #include <mono/metadata/object-internals.h>
40 #include <mono/metadata/mono-debug-debugger.h>
41 #include <mono/utils/mono-compiler.h>
42 #include <mono/utils/mono-mmap.h>
43 #include <mono/utils/mono-membar.h>
44 #include <mono/utils/mono-time.h>
45 #include <mono/utils/hazard-pointer.h>
47 #include <mono/metadata/gc-internal.h>
49 #ifdef PLATFORM_ANDROID
52 extern int tkill (pid_t tid, int signal);
55 /*#define THREAD_DEBUG(a) do { a; } while (0)*/
56 #define THREAD_DEBUG(a)
57 /*#define THREAD_WAIT_DEBUG(a) do { a; } while (0)*/
58 #define THREAD_WAIT_DEBUG(a)
59 /*#define LIBGC_DEBUG(a) do { a; } while (0)*/
60 #define LIBGC_DEBUG(a)
62 #define SPIN_TRYLOCK(i) (InterlockedCompareExchange (&(i), 1, 0) == 0)
63 #define SPIN_LOCK(i) do { \
64 if (SPIN_TRYLOCK (i)) \
68 #define SPIN_UNLOCK(i) i = 0
70 /* Provide this for systems with glib < 2.6 */
71 #ifndef G_GSIZE_FORMAT
72 # if GLIB_SIZEOF_LONG == 8
73 # define G_GSIZE_FORMAT "lu"
75 # define G_GSIZE_FORMAT "u"
81 guint32 (*func)(void *);
97 typedef struct _MonoThreadDomainTls MonoThreadDomainTls;
98 struct _MonoThreadDomainTls {
99 MonoThreadDomainTls *next;
107 MonoThreadDomainTls *freelist;
110 /* Number of cached culture objects in the MonoThread->cached_culture_info array
111 * (per-type): we use the first NUM entries for CultureInfo and the last for
112 * UICultureInfo. So the size of the array is really NUM_CACHED_CULTURES * 2.
114 #define NUM_CACHED_CULTURES 4
115 #define CULTURES_START_IDX 0
116 #define UICULTURES_START_IDX NUM_CACHED_CULTURES
118 /* Controls access to the 'threads' hash table */
119 #define mono_threads_lock() EnterCriticalSection (&threads_mutex)
120 #define mono_threads_unlock() LeaveCriticalSection (&threads_mutex)
121 static CRITICAL_SECTION threads_mutex;
123 /* Controls access to context static data */
124 #define mono_contexts_lock() EnterCriticalSection (&contexts_mutex)
125 #define mono_contexts_unlock() LeaveCriticalSection (&contexts_mutex)
126 static CRITICAL_SECTION contexts_mutex;
128 /* Holds current status of static data heap */
129 static StaticDataInfo thread_static_info;
130 static StaticDataInfo context_static_info;
132 /* The hash of existing threads (key is thread ID, value is
133 * MonoInternalThread*) that need joining before exit
135 static MonoGHashTable *threads=NULL;
138 * Threads which are starting up and they are not in the 'threads' hash yet.
139 * When handle_store is called for a thread, it will be removed from this hash table.
140 * Protected by mono_threads_lock ().
142 static MonoGHashTable *threads_starting_up = NULL;
144 /* Maps a MonoThread to its start argument */
145 /* Protected by mono_threads_lock () */
146 static MonoGHashTable *thread_start_args = NULL;
148 /* The TLS key that holds the MonoObject assigned to each thread */
149 static guint32 current_object_key = -1;
151 #ifdef MONO_HAVE_FAST_TLS
152 /* we need to use both the Tls* functions and __thread because
153 * the gc needs to see all the threads
155 MONO_FAST_TLS_DECLARE(tls_current_object);
156 #define SET_CURRENT_OBJECT(x) do { \
157 MONO_FAST_TLS_SET (tls_current_object, x); \
158 TlsSetValue (current_object_key, x); \
160 #define GET_CURRENT_OBJECT() ((MonoInternalThread*) MONO_FAST_TLS_GET (tls_current_object))
162 #define SET_CURRENT_OBJECT(x) TlsSetValue (current_object_key, x)
163 #define GET_CURRENT_OBJECT() (MonoInternalThread*) TlsGetValue (current_object_key)
166 /* function called at thread start */
167 static MonoThreadStartCB mono_thread_start_cb = NULL;
169 /* function called at thread attach */
170 static MonoThreadAttachCB mono_thread_attach_cb = NULL;
172 /* function called at thread cleanup */
173 static MonoThreadCleanupFunc mono_thread_cleanup_fn = NULL;
175 /* function called to notify the runtime about a pending exception on the current thread */
176 static MonoThreadNotifyPendingExcFunc mono_thread_notify_pending_exc_fn = NULL;
178 /* The default stack size for each thread */
179 static guint32 default_stacksize = 0;
180 #define default_stacksize_for_thread(thread) ((thread)->stack_size? (thread)->stack_size: default_stacksize)
182 static void thread_adjust_static_data (MonoInternalThread *thread);
183 static void mono_free_static_data (gpointer* static_data, gboolean threadlocal);
184 static void mono_init_static_data_info (StaticDataInfo *static_data);
185 static guint32 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align);
186 static gboolean mono_thread_resume (MonoInternalThread* thread);
187 static void mono_thread_start (MonoThread *thread);
188 static void signal_thread_state_change (MonoInternalThread *thread);
190 static MonoException* mono_thread_execute_interruption (MonoInternalThread *thread);
191 static void ref_stack_destroy (gpointer rs);
193 /* Spin lock for InterlockedXXX 64 bit functions */
194 #define mono_interlocked_lock() EnterCriticalSection (&interlocked_mutex)
195 #define mono_interlocked_unlock() LeaveCriticalSection (&interlocked_mutex)
196 static CRITICAL_SECTION interlocked_mutex;
198 /* global count of thread interruptions requested */
199 static gint32 thread_interruption_requested = 0;
201 /* Event signaled when a thread changes its background mode */
202 static HANDLE background_change_event;
204 static gboolean shutting_down = FALSE;
207 mono_thread_get_tls_key (void)
209 return current_object_key;
213 mono_thread_get_tls_offset (void)
216 MONO_THREAD_VAR_OFFSET (tls_current_object,offset);
220 /* handle_store() and handle_remove() manage the array of threads that
221 * still need to be waited for when the main thread exits.
223 * If handle_store() returns FALSE the thread must not be started
224 * because Mono is shutting down.
226 static gboolean handle_store(MonoThread *thread)
228 mono_threads_lock ();
230 THREAD_DEBUG (g_message ("%s: thread %p ID %"G_GSIZE_FORMAT, __func__, thread, (gsize)thread->internal_thread->tid));
232 if (threads_starting_up)
233 mono_g_hash_table_remove (threads_starting_up, thread);
236 mono_threads_unlock ();
241 MONO_GC_REGISTER_ROOT_FIXED (threads);
242 threads=mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
245 /* We don't need to duplicate thread->handle, because it is
246 * only closed when the thread object is finalized by the GC.
248 g_assert (thread->internal_thread);
249 mono_g_hash_table_insert(threads, (gpointer)(gsize)(thread->internal_thread->tid),
250 thread->internal_thread);
252 mono_threads_unlock ();
257 static gboolean handle_remove(MonoInternalThread *thread)
260 gsize tid = thread->tid;
262 THREAD_DEBUG (g_message ("%s: thread ID %"G_GSIZE_FORMAT, __func__, tid));
264 mono_threads_lock ();
267 /* We have to check whether the thread object for the
268 * tid is still the same in the table because the
269 * thread might have been destroyed and the tid reused
270 * in the meantime, in which case the tid would be in
271 * the table, but with another thread object.
273 if (mono_g_hash_table_lookup (threads, (gpointer)tid) == thread) {
274 mono_g_hash_table_remove (threads, (gpointer)tid);
283 mono_threads_unlock ();
285 /* Don't close the handle here, wait for the object finalizer
286 * to do it. Otherwise, the following race condition applies:
288 * 1) Thread exits (and handle_remove() closes the handle)
290 * 2) Some other handle is reassigned the same slot
292 * 3) Another thread tries to join the first thread, and
293 * blocks waiting for the reassigned handle to be signalled
294 * (which might never happen). This is possible, because the
295 * thread calling Join() still has a reference to the first
301 static void ensure_synch_cs_set (MonoInternalThread *thread)
303 CRITICAL_SECTION *synch_cs;
305 if (thread->synch_cs != NULL) {
309 synch_cs = g_new0 (CRITICAL_SECTION, 1);
310 InitializeCriticalSection (synch_cs);
312 if (InterlockedCompareExchangePointer ((gpointer *)&thread->synch_cs,
313 synch_cs, NULL) != NULL) {
314 /* Another thread must have installed this CS */
315 DeleteCriticalSection (synch_cs);
321 * NOTE: this function can be called also for threads different from the current one:
322 * make sure no code called from it will ever assume it is run on the thread that is
323 * getting cleaned up.
325 static void thread_cleanup (MonoInternalThread *thread)
327 g_assert (thread != NULL);
329 if (thread->abort_state_handle) {
330 mono_gchandle_free (thread->abort_state_handle);
331 thread->abort_state_handle = 0;
333 thread->abort_exc = NULL;
334 thread->current_appcontext = NULL;
337 * This is necessary because otherwise we might have
338 * cross-domain references which will not get cleaned up when
339 * the target domain is unloaded.
341 if (thread->cached_culture_info) {
343 for (i = 0; i < NUM_CACHED_CULTURES * 2; ++i)
344 mono_array_set (thread->cached_culture_info, MonoObject*, i, NULL);
347 /* if the thread is not in the hash it has been removed already */
348 if (!handle_remove (thread)) {
349 /* This needs to be called even if handle_remove () fails */
350 if (mono_thread_cleanup_fn)
351 mono_thread_cleanup_fn (thread);
354 mono_release_type_locks (thread);
356 EnterCriticalSection (thread->synch_cs);
358 thread->state |= ThreadState_Stopped;
359 thread->state &= ~ThreadState_Background;
361 LeaveCriticalSection (thread->synch_cs);
363 mono_profiler_thread_end (thread->tid);
365 if (thread == mono_thread_internal_current ())
366 mono_thread_pop_appdomain_ref ();
368 thread->cached_culture_info = NULL;
370 mono_free_static_data (thread->static_data, TRUE);
371 thread->static_data = NULL;
372 ref_stack_destroy (thread->appdomain_refs);
373 thread->appdomain_refs = NULL;
375 if (mono_thread_cleanup_fn)
376 mono_thread_cleanup_fn (thread);
378 mono_thread_small_id_free (thread->small_id);
379 thread->small_id = -2;
383 get_thread_static_data (MonoInternalThread *thread, guint32 offset)
386 g_assert ((offset & 0x80000000) == 0);
387 offset &= 0x7fffffff;
388 idx = (offset >> 24) - 1;
389 return ((char*) thread->static_data [idx]) + (offset & 0xffffff);
393 get_current_thread_ptr_for_domain (MonoDomain *domain, MonoInternalThread *thread)
395 static MonoClassField *current_thread_field = NULL;
399 if (!current_thread_field) {
400 current_thread_field = mono_class_get_field_from_name (mono_defaults.thread_class, "current_thread");
401 g_assert (current_thread_field);
404 mono_class_vtable (domain, mono_defaults.thread_class);
405 mono_domain_lock (domain);
406 offset = GPOINTER_TO_UINT (g_hash_table_lookup (domain->special_static_fields, current_thread_field));
407 mono_domain_unlock (domain);
410 return get_thread_static_data (thread, offset);
414 set_current_thread_for_domain (MonoDomain *domain, MonoInternalThread *thread, MonoThread *current)
416 MonoThread **current_thread_ptr = get_current_thread_ptr_for_domain (domain, thread);
418 g_assert (current->obj.vtable->domain == domain);
420 g_assert (!*current_thread_ptr);
421 *current_thread_ptr = current;
424 static MonoInternalThread*
425 create_internal_thread_object (void)
427 MonoVTable *vt = mono_class_vtable (mono_get_root_domain (), mono_defaults.internal_thread_class);
428 return (MonoInternalThread*)mono_gc_alloc_mature (vt);
432 create_thread_object (MonoDomain *domain)
434 MonoVTable *vt = mono_class_vtable (domain, mono_defaults.thread_class);
435 return (MonoThread*)mono_gc_alloc_mature (vt);
439 new_thread_with_internal (MonoDomain *domain, MonoInternalThread *internal)
441 MonoThread *thread = create_thread_object (domain);
442 MONO_OBJECT_SETREF (thread, internal_thread, internal);
447 init_root_domain_thread (MonoInternalThread *thread, MonoThread *candidate)
449 MonoDomain *domain = mono_get_root_domain ();
451 if (!candidate || candidate->obj.vtable->domain != domain)
452 candidate = new_thread_with_internal (domain, thread);
453 set_current_thread_for_domain (domain, thread, candidate);
454 g_assert (!thread->root_domain_thread);
455 MONO_OBJECT_SETREF (thread, root_domain_thread, candidate);
458 static guint32 WINAPI start_wrapper_internal(void *data)
460 struct StartInfo *start_info=(struct StartInfo *)data;
461 guint32 (*start_func)(void *);
465 * We don't create a local to hold start_info->obj, so hopefully it won't get pinned during a
468 MonoInternalThread *internal = start_info->obj->internal_thread;
469 MonoObject *start_delegate = start_info->delegate;
470 MonoDomain *domain = start_info->obj->obj.vtable->domain;
472 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Start wrapper", __func__, GetCurrentThreadId ()));
474 /* We can be sure start_info->obj->tid and
475 * start_info->obj->handle have been set, because the thread
476 * was created suspended, and these values were set before the
482 SET_CURRENT_OBJECT (internal);
484 mono_monitor_init_tls ();
486 /* Every thread references the appdomain which created it */
487 mono_thread_push_appdomain_ref (domain);
489 if (!mono_domain_set (domain, FALSE)) {
490 /* No point in raising an appdomain_unloaded exception here */
491 /* FIXME: Cleanup here */
492 mono_thread_pop_appdomain_ref ();
496 start_func = start_info->func;
497 start_arg = start_info->start_arg;
499 /* We have to do this here because mono_thread_new_init()
500 requires that root_domain_thread is set up. */
501 thread_adjust_static_data (internal);
502 init_root_domain_thread (internal, start_info->obj);
504 /* This MUST be called before any managed code can be
505 * executed, as it calls the callback function that (for the
506 * jit) sets the lmf marker.
508 mono_thread_new_init (tid, &tid, start_func);
509 internal->stack_ptr = &tid;
511 LIBGC_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT",%d) Setting thread stack to %p", __func__, GetCurrentThreadId (), getpid (), thread->stack_ptr));
513 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Setting current_object_key to %p", __func__, GetCurrentThreadId (), internal));
515 /* On 2.0 profile (and higher), set explicitly since state might have been
517 if (internal->apartment_state == ThreadApartmentState_Unknown)
518 internal->apartment_state = ThreadApartmentState_MTA;
520 mono_thread_init_apartment_state ();
522 if(internal->start_notify!=NULL) {
523 /* Let the thread that called Start() know we're
526 ReleaseSemaphore (internal->start_notify, 1, NULL);
529 mono_threads_lock ();
530 mono_g_hash_table_remove (thread_start_args, start_info->obj);
531 mono_threads_unlock ();
533 mono_thread_set_execution_context (start_info->obj->ec_to_set);
534 start_info->obj->ec_to_set = NULL;
537 THREAD_DEBUG (g_message ("%s: start_wrapper for %"G_GSIZE_FORMAT, __func__,
541 * Call this after calling start_notify, since the profiler callback might want
542 * to lock the thread, and the lock is held by thread_start () which waits for
545 mono_profiler_thread_start (tid);
547 /* start_func is set only for unmanaged start functions */
549 start_func (start_arg);
552 g_assert (start_delegate != NULL);
553 args [0] = start_arg;
554 /* we may want to handle the exception here. See comment below on unhandled exceptions */
555 mono_runtime_delegate_invoke (start_delegate, args, NULL);
558 /* If the thread calls ExitThread at all, this remaining code
559 * will not be executed, but the main thread will eventually
560 * call thread_cleanup() on this thread's behalf.
563 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Start wrapper terminating", __func__, GetCurrentThreadId ()));
565 thread_cleanup (internal);
567 /* Do any cleanup needed for apartment state. This
568 * cannot be done in thread_cleanup since thread_cleanup could be
569 * called for a thread other than the current thread.
570 * mono_thread_cleanup_apartment_state cleans up apartment
571 * for the current thead */
572 mono_thread_cleanup_apartment_state ();
574 /* Remove the reference to the thread object in the TLS data,
575 * so the thread object can be finalized. This won't be
576 * reached if the thread threw an uncaught exception, so those
577 * thread handles will stay referenced :-( (This is due to
578 * missing support for scanning thread-specific data in the
579 * Boehm GC - the io-layer keeps a GC-visible hash of pointers
582 SET_CURRENT_OBJECT (NULL);
583 mono_domain_unset ();
588 static guint32 WINAPI start_wrapper(void *data)
593 /* Avoid scanning the frames above this frame during a GC */
594 mono_gc_set_stack_end ((void*)&dummy);
597 return start_wrapper_internal (data);
600 void mono_thread_new_init (intptr_t tid, gpointer stack_start, gpointer func)
602 if (mono_thread_start_cb) {
603 mono_thread_start_cb (tid, stack_start, func);
607 void mono_threads_set_default_stacksize (guint32 stacksize)
609 default_stacksize = stacksize;
612 guint32 mono_threads_get_default_stacksize (void)
614 return default_stacksize;
618 * mono_create_thread:
620 * This is a wrapper around CreateThread which handles differences in the type of
621 * the the 'tid' argument.
623 gpointer mono_create_thread (WapiSecurityAttributes *security,
624 guint32 stacksize, WapiThreadStart start,
625 gpointer param, guint32 create, gsize *tid)
632 res = CreateThread (security, stacksize, start, param, create, &real_tid);
636 res = CreateThread (security, stacksize, start, param, create, tid);
643 * The thread start argument may be an object reference, and there is
644 * no ref to keep it alive when the new thread is started but not yet
645 * registered with the collector. So we store it in a GC tracked hash
648 * LOCKING: Assumes the threads lock is held.
651 register_thread_start_argument (MonoThread *thread, struct StartInfo *start_info)
653 if (thread_start_args == NULL) {
654 MONO_GC_REGISTER_ROOT_FIXED (thread_start_args);
655 thread_start_args = mono_g_hash_table_new (NULL, NULL);
657 mono_g_hash_table_insert (thread_start_args, thread, start_info->start_arg);
660 MonoInternalThread* mono_thread_create_internal (MonoDomain *domain, gpointer func, gpointer arg, gboolean threadpool_thread, guint32 stack_size)
663 MonoInternalThread *internal;
664 HANDLE thread_handle;
665 struct StartInfo *start_info;
668 thread = create_thread_object (domain);
669 internal = create_internal_thread_object ();
670 MONO_OBJECT_SETREF (thread, internal_thread, internal);
672 start_info=g_new0 (struct StartInfo, 1);
673 start_info->func = func;
674 start_info->obj = thread;
675 start_info->start_arg = arg;
677 mono_threads_lock ();
679 mono_threads_unlock ();
683 if (threads_starting_up == NULL) {
684 MONO_GC_REGISTER_ROOT_FIXED (threads_starting_up);
685 threads_starting_up = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_VALUE_GC);
688 register_thread_start_argument (thread, start_info);
689 mono_g_hash_table_insert (threads_starting_up, thread, thread);
690 mono_threads_unlock ();
693 stack_size = default_stacksize_for_thread (internal);
695 /* Create suspended, so we can do some housekeeping before the thread
698 thread_handle = mono_create_thread (NULL, stack_size, (LPTHREAD_START_ROUTINE)start_wrapper, start_info,
699 CREATE_SUSPENDED, &tid);
700 THREAD_DEBUG (g_message ("%s: Started thread ID %"G_GSIZE_FORMAT" (handle %p)", __func__, tid, thread_handle));
701 if (thread_handle == NULL) {
702 /* The thread couldn't be created, so throw an exception */
703 mono_threads_lock ();
704 mono_g_hash_table_remove (threads_starting_up, thread);
705 mono_threads_unlock ();
707 mono_raise_exception (mono_get_exception_execution_engine ("Couldn't create thread"));
711 internal->handle=thread_handle;
713 internal->apartment_state=ThreadApartmentState_Unknown;
714 mono_thread_small_id_alloc (internal);
716 internal->synch_cs = g_new0 (CRITICAL_SECTION, 1);
717 InitializeCriticalSection (internal->synch_cs);
719 internal->threadpool_thread = threadpool_thread;
720 if (threadpool_thread)
721 mono_thread_set_state (internal, ThreadState_Background);
723 if (handle_store (thread))
724 ResumeThread (thread_handle);
730 mono_thread_create (MonoDomain *domain, gpointer func, gpointer arg)
732 mono_thread_create_internal (domain, func, arg, FALSE, 0);
736 * mono_thread_get_stack_bounds:
738 * Return the address and size of the current threads stack. Return NULL as the
739 * stack address if the stack address cannot be determined.
742 mono_thread_get_stack_bounds (guint8 **staddr, size_t *stsize)
744 #if defined(HAVE_PTHREAD_GET_STACKSIZE_NP) && defined(HAVE_PTHREAD_GET_STACKADDR_NP)
745 *staddr = (guint8*)pthread_get_stackaddr_np (pthread_self ());
746 *stsize = pthread_get_stacksize_np (pthread_self ());
747 *staddr = (guint8*)((gssize)*staddr & ~(mono_pagesize () - 1));
749 /* FIXME: simplify the mess below */
750 #elif !defined(HOST_WIN32)
752 guint8 *current = (guint8*)&attr;
754 pthread_attr_init (&attr);
755 # ifdef HAVE_PTHREAD_GETATTR_NP
756 pthread_getattr_np (pthread_self(), &attr);
758 # ifdef HAVE_PTHREAD_ATTR_GET_NP
759 pthread_attr_get_np (pthread_self(), &attr);
762 pthread_attr_getstacksize (&attr, &stsize);
763 # elif defined(__OpenBSD__)
767 rslt = pthread_stackseg_np(pthread_self(), &ss);
768 g_assert (rslt == 0);
770 *staddr = (guint8*)((size_t)ss.ss_sp - ss.ss_size);
771 *stsize = ss.ss_size;
780 # if !defined(__OpenBSD__)
781 pthread_attr_getstack (&attr, (void**)staddr, stsize);
784 g_assert ((current > *staddr) && (current < *staddr + *stsize));
787 pthread_attr_destroy (&attr);
790 *stsize = (size_t)-1;
793 /* When running under emacs, sometimes staddr is not aligned to a page size */
794 *staddr = (guint8*)((gssize)*staddr & ~(mono_pagesize () - 1));
798 mono_thread_attach (MonoDomain *domain)
800 MonoInternalThread *thread;
801 MonoThread *current_thread;
802 HANDLE thread_handle;
805 if ((thread = mono_thread_internal_current ())) {
806 if (domain != mono_domain_get ())
807 mono_domain_set (domain, TRUE);
808 /* Already attached */
809 return mono_thread_current ();
812 if (!mono_gc_register_thread (&domain)) {
813 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 ());
816 thread = create_internal_thread_object ();
818 thread_handle = GetCurrentThread ();
819 g_assert (thread_handle);
821 tid=GetCurrentThreadId ();
824 * The handle returned by GetCurrentThread () is a pseudo handle, so it can't be used to
825 * refer to the thread from other threads for things like aborting.
827 DuplicateHandle (GetCurrentProcess (), thread_handle, GetCurrentProcess (), &thread_handle,
828 THREAD_ALL_ACCESS, TRUE, 0);
830 thread->handle=thread_handle;
832 #ifdef PLATFORM_ANDROID
833 thread->android_tid = (gpointer) gettid ();
835 thread->apartment_state=ThreadApartmentState_Unknown;
836 mono_thread_small_id_alloc (thread);
837 thread->stack_ptr = &tid;
839 thread->synch_cs = g_new0 (CRITICAL_SECTION, 1);
840 InitializeCriticalSection (thread->synch_cs);
842 THREAD_DEBUG (g_message ("%s: Attached thread ID %"G_GSIZE_FORMAT" (handle %p)", __func__, tid, thread_handle));
844 current_thread = new_thread_with_internal (domain, thread);
846 if (!handle_store (current_thread)) {
847 /* Mono is shutting down, so just wait for the end */
852 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Setting current_object_key to %p", __func__, GetCurrentThreadId (), thread));
854 SET_CURRENT_OBJECT (thread);
855 mono_domain_set (domain, TRUE);
857 mono_monitor_init_tls ();
859 thread_adjust_static_data (thread);
861 init_root_domain_thread (thread, current_thread);
862 if (domain != mono_get_root_domain ())
863 set_current_thread_for_domain (domain, thread, current_thread);
866 if (mono_thread_attach_cb) {
870 mono_thread_get_stack_bounds (&staddr, &stsize);
873 mono_thread_attach_cb (tid, &tid);
875 mono_thread_attach_cb (tid, staddr + stsize);
878 // FIXME: Need a separate callback
879 mono_profiler_thread_start (tid);
881 return current_thread;
885 mono_thread_detach (MonoThread *thread)
887 g_return_if_fail (thread != NULL);
889 THREAD_DEBUG (g_message ("%s: mono_thread_detach for %p (%"G_GSIZE_FORMAT")", __func__, thread, (gsize)thread->internal_thread->tid));
891 thread_cleanup (thread->internal_thread);
893 SET_CURRENT_OBJECT (NULL);
894 mono_domain_unset ();
896 /* Don't need to CloseHandle this thread, even though we took a
897 * reference in mono_thread_attach (), because the GC will do it
898 * when the Thread object is finalised.
905 MonoInternalThread *thread = mono_thread_internal_current ();
907 THREAD_DEBUG (g_message ("%s: mono_thread_exit for %p (%"G_GSIZE_FORMAT")", __func__, thread, (gsize)thread->tid));
909 thread_cleanup (thread);
910 SET_CURRENT_OBJECT (NULL);
911 mono_domain_unset ();
913 /* we could add a callback here for embedders to use. */
914 if (mono_thread_get_main () && (thread == mono_thread_get_main ()->internal_thread))
915 exit (mono_environment_exitcode_get ());
920 ves_icall_System_Threading_Thread_ConstructInternalThread (MonoThread *this)
922 MonoInternalThread *internal = create_internal_thread_object ();
924 internal->state = ThreadState_Unstarted;
925 internal->apartment_state = ThreadApartmentState_Unknown;
927 InterlockedCompareExchangePointer ((gpointer)&this->internal_thread, internal, NULL);
930 HANDLE ves_icall_System_Threading_Thread_Thread_internal(MonoThread *this,
933 guint32 (*start_func)(void *);
934 struct StartInfo *start_info;
937 MonoInternalThread *internal;
939 THREAD_DEBUG (g_message("%s: Trying to start a new thread: this (%p) start (%p)", __func__, this, start));
941 if (!this->internal_thread)
942 ves_icall_System_Threading_Thread_ConstructInternalThread (this);
943 internal = this->internal_thread;
945 ensure_synch_cs_set (internal);
947 EnterCriticalSection (internal->synch_cs);
949 if ((internal->state & ThreadState_Unstarted) == 0) {
950 LeaveCriticalSection (internal->synch_cs);
951 mono_raise_exception (mono_get_exception_thread_state ("Thread has already been started."));
955 internal->small_id = -1;
957 if ((internal->state & ThreadState_Aborted) != 0) {
958 LeaveCriticalSection (internal->synch_cs);
963 /* This is freed in start_wrapper */
964 start_info = g_new0 (struct StartInfo, 1);
965 start_info->func = start_func;
966 start_info->start_arg = this->start_obj; /* FIXME: GC object stored in unmanaged memory */
967 start_info->delegate = start;
968 start_info->obj = this;
969 g_assert (this->obj.vtable->domain == mono_domain_get ());
971 internal->start_notify=CreateSemaphore (NULL, 0, 0x7fffffff, NULL);
972 if (internal->start_notify==NULL) {
973 LeaveCriticalSection (internal->synch_cs);
974 g_warning ("%s: CreateSemaphore error 0x%x", __func__, GetLastError ());
979 mono_threads_lock ();
980 register_thread_start_argument (this, start_info);
981 if (threads_starting_up == NULL) {
982 MONO_GC_REGISTER_ROOT_FIXED (threads_starting_up);
983 threads_starting_up = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_VALUE_GC);
985 mono_g_hash_table_insert (threads_starting_up, this, this);
986 mono_threads_unlock ();
988 thread=mono_create_thread(NULL, default_stacksize_for_thread (internal), (LPTHREAD_START_ROUTINE)start_wrapper, start_info,
989 CREATE_SUSPENDED, &tid);
991 LeaveCriticalSection (internal->synch_cs);
992 mono_threads_lock ();
993 mono_g_hash_table_remove (threads_starting_up, this);
994 mono_threads_unlock ();
995 g_warning("%s: CreateThread error 0x%x", __func__, GetLastError());
999 internal->handle=thread;
1001 mono_thread_small_id_alloc (internal);
1003 /* Don't call handle_store() here, delay it to Start.
1004 * We can't join a thread (trying to will just block
1005 * forever) until it actually starts running, so don't
1006 * store the handle till then.
1009 mono_thread_start (this);
1011 internal->state &= ~ThreadState_Unstarted;
1013 THREAD_DEBUG (g_message ("%s: Started thread ID %"G_GSIZE_FORMAT" (handle %p)", __func__, tid, thread));
1015 LeaveCriticalSection (internal->synch_cs);
1020 void ves_icall_System_Threading_InternalThread_Thread_free_internal (MonoInternalThread *this, HANDLE thread)
1022 MONO_ARCH_SAVE_REGS;
1024 THREAD_DEBUG (g_message ("%s: Closing thread %p, handle %p", __func__, this, thread));
1027 CloseHandle (thread);
1029 if (this->synch_cs) {
1030 DeleteCriticalSection (this->synch_cs);
1031 g_free (this->synch_cs);
1032 this->synch_cs = NULL;
1035 g_free (this->name);
1038 static void mono_thread_start (MonoThread *thread)
1040 MonoInternalThread *internal = thread->internal_thread;
1042 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Launching thread %p (%"G_GSIZE_FORMAT")", __func__, GetCurrentThreadId (), internal, (gsize)internal->tid));
1044 /* Only store the handle when the thread is about to be
1045 * launched, to avoid the main thread deadlocking while trying
1046 * to clean up a thread that will never be signalled.
1048 if (!handle_store (thread))
1051 ResumeThread (internal->handle);
1053 if(internal->start_notify!=NULL) {
1054 /* Wait for the thread to set up its TLS data etc, so
1055 * theres no potential race condition if someone tries
1056 * to look up the data believing the thread has
1060 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") waiting for thread %p (%"G_GSIZE_FORMAT") to start", __func__, GetCurrentThreadId (), internal, (gsize)internal->tid));
1062 WaitForSingleObjectEx (internal->start_notify, INFINITE, FALSE);
1063 CloseHandle (internal->start_notify);
1064 internal->start_notify = NULL;
1067 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Done launching thread %p (%"G_GSIZE_FORMAT")", __func__, GetCurrentThreadId (), internal, (gsize)internal->tid));
1070 void ves_icall_System_Threading_Thread_Sleep_internal(gint32 ms)
1073 MonoInternalThread *thread = mono_thread_internal_current ();
1075 THREAD_DEBUG (g_message ("%s: Sleeping for %d ms", __func__, ms));
1077 mono_thread_current_check_pending_interrupt ();
1079 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1081 res = SleepEx(ms,TRUE);
1083 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1085 if (res == WAIT_IO_COMPLETION) { /* we might have been interrupted */
1086 MonoException* exc = mono_thread_execute_interruption (thread);
1087 if (exc) mono_raise_exception (exc);
1091 void ves_icall_System_Threading_Thread_SpinWait_nop (void)
1096 ves_icall_System_Threading_Thread_GetDomainID (void)
1098 MONO_ARCH_SAVE_REGS;
1100 return mono_domain_get()->domain_id;
1104 ves_icall_System_Threading_Thread_Yield (void)
1107 return SwitchToThread ();
1109 return sched_yield () == 0;
1114 * mono_thread_get_name:
1116 * Return the name of the thread. NAME_LEN is set to the length of the name.
1117 * Return NULL if the thread has no name. The returned memory is owned by the
1121 mono_thread_get_name (MonoInternalThread *this_obj, guint32 *name_len)
1125 ensure_synch_cs_set (this_obj);
1127 EnterCriticalSection (this_obj->synch_cs);
1129 if (!this_obj->name) {
1133 *name_len = this_obj->name_len;
1134 res = g_new (gunichar2, this_obj->name_len);
1135 memcpy (res, this_obj->name, sizeof (gunichar2) * this_obj->name_len);
1138 LeaveCriticalSection (this_obj->synch_cs);
1144 ves_icall_System_Threading_Thread_GetName_internal (MonoInternalThread *this_obj)
1148 ensure_synch_cs_set (this_obj);
1150 EnterCriticalSection (this_obj->synch_cs);
1152 if (!this_obj->name)
1155 str = mono_string_new_utf16 (mono_domain_get (), this_obj->name, this_obj->name_len);
1157 LeaveCriticalSection (this_obj->synch_cs);
1163 ves_icall_System_Threading_Thread_SetName_internal (MonoInternalThread *this_obj, MonoString *name)
1165 ensure_synch_cs_set (this_obj);
1167 EnterCriticalSection (this_obj->synch_cs);
1169 if (this_obj->name) {
1170 LeaveCriticalSection (this_obj->synch_cs);
1172 mono_raise_exception (mono_get_exception_invalid_operation ("Thread.Name can only be set once."));
1176 this_obj->name = g_new (gunichar2, mono_string_length (name));
1177 memcpy (this_obj->name, mono_string_chars (name), mono_string_length (name) * 2);
1178 this_obj->name_len = mono_string_length (name);
1181 this_obj->name = NULL;
1183 LeaveCriticalSection (this_obj->synch_cs);
1184 if (this_obj->name) {
1185 char *tname = mono_string_to_utf8 (name);
1186 mono_profiler_thread_name (this_obj->tid, tname);
1191 /* If the array is already in the requested domain, we just return it,
1192 otherwise we return a copy in that domain. */
1194 byte_array_to_domain (MonoArray *arr, MonoDomain *domain)
1201 if (mono_object_domain (arr) == domain)
1204 copy = mono_array_new (domain, mono_defaults.byte_class, arr->max_length);
1205 memcpy (mono_array_addr (copy, guint8, 0), mono_array_addr (arr, guint8, 0), arr->max_length);
1210 ves_icall_System_Threading_Thread_ByteArrayToRootDomain (MonoArray *arr)
1212 return byte_array_to_domain (arr, mono_get_root_domain ());
1216 ves_icall_System_Threading_Thread_ByteArrayToCurrentDomain (MonoArray *arr)
1218 return byte_array_to_domain (arr, mono_domain_get ());
1222 mono_thread_current (void)
1224 MonoDomain *domain = mono_domain_get ();
1225 MonoInternalThread *internal = mono_thread_internal_current ();
1226 MonoThread **current_thread_ptr;
1228 g_assert (internal);
1229 current_thread_ptr = get_current_thread_ptr_for_domain (domain, internal);
1231 if (!*current_thread_ptr) {
1232 g_assert (domain != mono_get_root_domain ());
1233 *current_thread_ptr = new_thread_with_internal (domain, internal);
1235 return *current_thread_ptr;
1239 mono_thread_internal_current (void)
1241 MonoInternalThread *res = GET_CURRENT_OBJECT ();
1242 THREAD_DEBUG (g_message ("%s: returning %p", __func__, res));
1246 gboolean ves_icall_System_Threading_Thread_Join_internal(MonoInternalThread *this,
1247 int ms, HANDLE thread)
1249 MonoInternalThread *cur_thread = mono_thread_internal_current ();
1252 mono_thread_current_check_pending_interrupt ();
1254 ensure_synch_cs_set (this);
1256 EnterCriticalSection (this->synch_cs);
1258 if ((this->state & ThreadState_Unstarted) != 0) {
1259 LeaveCriticalSection (this->synch_cs);
1261 mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started."));
1265 LeaveCriticalSection (this->synch_cs);
1270 THREAD_DEBUG (g_message ("%s: joining thread handle %p, %d ms", __func__, thread, ms));
1272 mono_thread_set_state (cur_thread, ThreadState_WaitSleepJoin);
1274 ret=WaitForSingleObjectEx (thread, ms, TRUE);
1276 mono_thread_clr_state (cur_thread, ThreadState_WaitSleepJoin);
1278 if(ret==WAIT_OBJECT_0) {
1279 THREAD_DEBUG (g_message ("%s: join successful", __func__));
1284 THREAD_DEBUG (g_message ("%s: join failed", __func__));
1289 /* FIXME: exitContext isnt documented */
1290 gboolean ves_icall_System_Threading_WaitHandle_WaitAll_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext)
1296 MonoObject *waitHandle;
1297 MonoInternalThread *thread = mono_thread_internal_current ();
1299 /* Do this WaitSleepJoin check before creating objects */
1300 mono_thread_current_check_pending_interrupt ();
1302 numhandles = mono_array_length(mono_handles);
1303 handles = g_new0(HANDLE, numhandles);
1305 for(i = 0; i < numhandles; i++) {
1306 waitHandle = mono_array_get(mono_handles, MonoObject*, i);
1307 handles [i] = mono_wait_handle_get_handle ((MonoWaitHandle *) waitHandle);
1314 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1316 ret=WaitForMultipleObjectsEx(numhandles, handles, TRUE, ms, TRUE);
1318 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1322 if(ret==WAIT_FAILED) {
1323 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait failed", __func__, GetCurrentThreadId ()));
1325 } else if(ret==WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION) {
1326 /* Do we want to try again if we get
1327 * WAIT_IO_COMPLETION? The documentation for
1328 * WaitHandle doesn't give any clues. (We'd have to
1329 * fiddle with the timeout if we retry.)
1331 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait timed out", __func__, GetCurrentThreadId ()));
1338 /* FIXME: exitContext isnt documented */
1339 gint32 ves_icall_System_Threading_WaitHandle_WaitAny_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext)
1341 HANDLE handles [MAXIMUM_WAIT_OBJECTS];
1345 MonoObject *waitHandle;
1346 MonoInternalThread *thread = mono_thread_internal_current ();
1349 /* Do this WaitSleepJoin check before creating objects */
1350 mono_thread_current_check_pending_interrupt ();
1352 numhandles = mono_array_length(mono_handles);
1353 if (numhandles > MAXIMUM_WAIT_OBJECTS)
1356 for(i = 0; i < numhandles; i++) {
1357 waitHandle = mono_array_get(mono_handles, MonoObject*, i);
1358 handles [i] = mono_wait_handle_get_handle ((MonoWaitHandle *) waitHandle);
1365 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1367 start = (ms == -1) ? 0 : mono_msec_ticks ();
1369 ret = WaitForMultipleObjectsEx (numhandles, handles, FALSE, ms, TRUE);
1370 if (ret != WAIT_IO_COMPLETION)
1375 diff = mono_msec_ticks () - start;
1380 } while (ms == -1 || ms > 0);
1382 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1384 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") returning %d", __func__, GetCurrentThreadId (), ret));
1387 * These need to be here. See MSDN dos on WaitForMultipleObjects.
1389 if (ret >= WAIT_OBJECT_0 && ret <= WAIT_OBJECT_0 + numhandles - 1) {
1390 return ret - WAIT_OBJECT_0;
1392 else if (ret >= WAIT_ABANDONED_0 && ret <= WAIT_ABANDONED_0 + numhandles - 1) {
1393 return ret - WAIT_ABANDONED_0;
1400 /* FIXME: exitContext isnt documented */
1401 gboolean ves_icall_System_Threading_WaitHandle_WaitOne_internal(MonoObject *this, HANDLE handle, gint32 ms, gboolean exitContext)
1404 MonoInternalThread *thread = mono_thread_internal_current ();
1406 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") waiting for %p, %d ms", __func__, GetCurrentThreadId (), handle, ms));
1412 mono_thread_current_check_pending_interrupt ();
1414 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1416 ret=WaitForSingleObjectEx (handle, ms, TRUE);
1418 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1420 if(ret==WAIT_FAILED) {
1421 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait failed", __func__, GetCurrentThreadId ()));
1423 } else if(ret==WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION) {
1424 /* Do we want to try again if we get
1425 * WAIT_IO_COMPLETION? The documentation for
1426 * WaitHandle doesn't give any clues. (We'd have to
1427 * fiddle with the timeout if we retry.)
1429 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait timed out", __func__, GetCurrentThreadId ()));
1437 ves_icall_System_Threading_WaitHandle_SignalAndWait_Internal (HANDLE toSignal, HANDLE toWait, gint32 ms, gboolean exitContext)
1440 MonoInternalThread *thread = mono_thread_internal_current ();
1442 MONO_ARCH_SAVE_REGS;
1447 mono_thread_current_check_pending_interrupt ();
1449 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1451 ret = SignalObjectAndWait (toSignal, toWait, ms, TRUE);
1453 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1455 return (!(ret == WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION || ret == WAIT_FAILED));
1458 HANDLE ves_icall_System_Threading_Mutex_CreateMutex_internal (MonoBoolean owned, MonoString *name, MonoBoolean *created)
1462 MONO_ARCH_SAVE_REGS;
1467 mutex = CreateMutex (NULL, owned, NULL);
1469 mutex = CreateMutex (NULL, owned, mono_string_chars (name));
1471 if (GetLastError () == ERROR_ALREADY_EXISTS) {
1479 MonoBoolean ves_icall_System_Threading_Mutex_ReleaseMutex_internal (HANDLE handle ) {
1480 MONO_ARCH_SAVE_REGS;
1482 return(ReleaseMutex (handle));
1485 HANDLE ves_icall_System_Threading_Mutex_OpenMutex_internal (MonoString *name,
1491 MONO_ARCH_SAVE_REGS;
1493 *error = ERROR_SUCCESS;
1495 ret = OpenMutex (rights, FALSE, mono_string_chars (name));
1497 *error = GetLastError ();
1504 HANDLE ves_icall_System_Threading_Semaphore_CreateSemaphore_internal (gint32 initialCount, gint32 maximumCount, MonoString *name, MonoBoolean *created)
1508 MONO_ARCH_SAVE_REGS;
1513 sem = CreateSemaphore (NULL, initialCount, maximumCount, NULL);
1515 sem = CreateSemaphore (NULL, initialCount, maximumCount,
1516 mono_string_chars (name));
1518 if (GetLastError () == ERROR_ALREADY_EXISTS) {
1526 gint32 ves_icall_System_Threading_Semaphore_ReleaseSemaphore_internal (HANDLE handle, gint32 releaseCount, MonoBoolean *fail)
1530 MONO_ARCH_SAVE_REGS;
1532 *fail = !ReleaseSemaphore (handle, releaseCount, &prevcount);
1537 HANDLE ves_icall_System_Threading_Semaphore_OpenSemaphore_internal (MonoString *name, gint32 rights, gint32 *error)
1541 MONO_ARCH_SAVE_REGS;
1543 *error = ERROR_SUCCESS;
1545 ret = OpenSemaphore (rights, FALSE, mono_string_chars (name));
1547 *error = GetLastError ();
1553 HANDLE ves_icall_System_Threading_Events_CreateEvent_internal (MonoBoolean manual, MonoBoolean initial, MonoString *name, MonoBoolean *created)
1557 MONO_ARCH_SAVE_REGS;
1562 event = CreateEvent (NULL, manual, initial, NULL);
1564 event = CreateEvent (NULL, manual, initial,
1565 mono_string_chars (name));
1567 if (GetLastError () == ERROR_ALREADY_EXISTS) {
1575 gboolean ves_icall_System_Threading_Events_SetEvent_internal (HANDLE handle) {
1576 MONO_ARCH_SAVE_REGS;
1578 return (SetEvent(handle));
1581 gboolean ves_icall_System_Threading_Events_ResetEvent_internal (HANDLE handle) {
1582 MONO_ARCH_SAVE_REGS;
1584 return (ResetEvent(handle));
1588 ves_icall_System_Threading_Events_CloseEvent_internal (HANDLE handle) {
1589 MONO_ARCH_SAVE_REGS;
1591 CloseHandle (handle);
1594 HANDLE ves_icall_System_Threading_Events_OpenEvent_internal (MonoString *name,
1600 MONO_ARCH_SAVE_REGS;
1602 *error = ERROR_SUCCESS;
1604 ret = OpenEvent (rights, FALSE, mono_string_chars (name));
1606 *error = GetLastError ();
1612 gint32 ves_icall_System_Threading_Interlocked_Increment_Int (gint32 *location)
1614 MONO_ARCH_SAVE_REGS;
1616 return InterlockedIncrement (location);
1619 gint64 ves_icall_System_Threading_Interlocked_Increment_Long (gint64 *location)
1623 MONO_ARCH_SAVE_REGS;
1625 mono_interlocked_lock ();
1629 mono_interlocked_unlock ();
1635 gint32 ves_icall_System_Threading_Interlocked_Decrement_Int (gint32 *location)
1637 MONO_ARCH_SAVE_REGS;
1639 return InterlockedDecrement(location);
1642 gint64 ves_icall_System_Threading_Interlocked_Decrement_Long (gint64 * location)
1646 MONO_ARCH_SAVE_REGS;
1648 mono_interlocked_lock ();
1652 mono_interlocked_unlock ();
1657 gint32 ves_icall_System_Threading_Interlocked_Exchange_Int (gint32 *location, gint32 value)
1659 MONO_ARCH_SAVE_REGS;
1661 return InterlockedExchange(location, value);
1664 MonoObject * ves_icall_System_Threading_Interlocked_Exchange_Object (MonoObject **location, MonoObject *value)
1667 res = (MonoObject *) InterlockedExchangePointer((gpointer *) location, value);
1668 mono_gc_wbarrier_generic_nostore (location);
1672 gpointer ves_icall_System_Threading_Interlocked_Exchange_IntPtr (gpointer *location, gpointer value)
1674 return InterlockedExchangePointer(location, value);
1677 gfloat ves_icall_System_Threading_Interlocked_Exchange_Single (gfloat *location, gfloat value)
1679 IntFloatUnion val, ret;
1681 MONO_ARCH_SAVE_REGS;
1684 ret.ival = InterlockedExchange((gint32 *) location, val.ival);
1690 ves_icall_System_Threading_Interlocked_Exchange_Long (gint64 *location, gint64 value)
1692 #if SIZEOF_VOID_P == 8
1693 return (gint64) InterlockedExchangePointer((gpointer *) location, (gpointer)value);
1698 * According to MSDN, this function is only atomic with regards to the
1699 * other Interlocked functions on 32 bit platforms.
1701 mono_interlocked_lock ();
1704 mono_interlocked_unlock ();
1711 ves_icall_System_Threading_Interlocked_Exchange_Double (gdouble *location, gdouble value)
1713 #if SIZEOF_VOID_P == 8
1714 LongDoubleUnion val, ret;
1717 ret.ival = (gint64)InterlockedExchangePointer((gpointer *) location, (gpointer)val.ival);
1724 * According to MSDN, this function is only atomic with regards to the
1725 * other Interlocked functions on 32 bit platforms.
1727 mono_interlocked_lock ();
1730 mono_interlocked_unlock ();
1736 gint32 ves_icall_System_Threading_Interlocked_CompareExchange_Int(gint32 *location, gint32 value, gint32 comparand)
1738 MONO_ARCH_SAVE_REGS;
1740 return InterlockedCompareExchange(location, value, comparand);
1743 MonoObject * ves_icall_System_Threading_Interlocked_CompareExchange_Object (MonoObject **location, MonoObject *value, MonoObject *comparand)
1746 res = (MonoObject *) InterlockedCompareExchangePointer((gpointer *) location, value, comparand);
1747 mono_gc_wbarrier_generic_nostore (location);
1751 gpointer ves_icall_System_Threading_Interlocked_CompareExchange_IntPtr(gpointer *location, gpointer value, gpointer comparand)
1753 return InterlockedCompareExchangePointer(location, value, comparand);
1756 gfloat ves_icall_System_Threading_Interlocked_CompareExchange_Single (gfloat *location, gfloat value, gfloat comparand)
1758 IntFloatUnion val, ret, cmp;
1760 MONO_ARCH_SAVE_REGS;
1763 cmp.fval = comparand;
1764 ret.ival = InterlockedCompareExchange((gint32 *) location, val.ival, cmp.ival);
1770 ves_icall_System_Threading_Interlocked_CompareExchange_Double (gdouble *location, gdouble value, gdouble comparand)
1772 #if SIZEOF_VOID_P == 8
1773 LongDoubleUnion val, comp, ret;
1776 comp.fval = comparand;
1777 ret.ival = (gint64)InterlockedCompareExchangePointer((gpointer *) location, (gpointer)val.ival, (gpointer)comp.ival);
1783 mono_interlocked_lock ();
1785 if (old == comparand)
1787 mono_interlocked_unlock ();
1794 ves_icall_System_Threading_Interlocked_CompareExchange_Long (gint64 *location, gint64 value, gint64 comparand)
1796 #if SIZEOF_VOID_P == 8
1797 return (gint64)InterlockedCompareExchangePointer((gpointer *) location, (gpointer)value, (gpointer)comparand);
1801 mono_interlocked_lock ();
1803 if (old == comparand)
1805 mono_interlocked_unlock ();
1812 ves_icall_System_Threading_Interlocked_CompareExchange_T (MonoObject **location, MonoObject *value, MonoObject *comparand)
1815 res = InterlockedCompareExchangePointer ((gpointer *)location, value, comparand);
1816 mono_gc_wbarrier_generic_nostore (location);
1821 ves_icall_System_Threading_Interlocked_Exchange_T (MonoObject **location, MonoObject *value)
1824 res = InterlockedExchangePointer ((gpointer *)location, value);
1825 mono_gc_wbarrier_generic_nostore (location);
1830 ves_icall_System_Threading_Interlocked_Add_Int (gint32 *location, gint32 value)
1832 #if SIZEOF_VOID_P == 8
1833 /* Should be implemented as a JIT intrinsic */
1834 mono_raise_exception (mono_get_exception_not_implemented (NULL));
1839 mono_interlocked_lock ();
1841 *location = orig + value;
1842 mono_interlocked_unlock ();
1844 return orig + value;
1849 ves_icall_System_Threading_Interlocked_Add_Long (gint64 *location, gint64 value)
1851 #if SIZEOF_VOID_P == 8
1852 /* Should be implemented as a JIT intrinsic */
1853 mono_raise_exception (mono_get_exception_not_implemented (NULL));
1858 mono_interlocked_lock ();
1860 *location = orig + value;
1861 mono_interlocked_unlock ();
1863 return orig + value;
1868 ves_icall_System_Threading_Interlocked_Read_Long (gint64 *location)
1870 #if SIZEOF_VOID_P == 8
1871 /* 64 bit reads are already atomic */
1876 mono_interlocked_lock ();
1878 mono_interlocked_unlock ();
1885 ves_icall_System_Threading_Thread_MemoryBarrier (void)
1887 mono_threads_lock ();
1888 mono_threads_unlock ();
1892 ves_icall_System_Threading_Thread_ClrState (MonoInternalThread* this, guint32 state)
1894 mono_thread_clr_state (this, state);
1896 if (state & ThreadState_Background) {
1897 /* If the thread changes the background mode, the main thread has to
1898 * be notified, since it has to rebuild the list of threads to
1901 SetEvent (background_change_event);
1906 ves_icall_System_Threading_Thread_SetState (MonoInternalThread* this, guint32 state)
1908 mono_thread_set_state (this, state);
1910 if (state & ThreadState_Background) {
1911 /* If the thread changes the background mode, the main thread has to
1912 * be notified, since it has to rebuild the list of threads to
1915 SetEvent (background_change_event);
1920 ves_icall_System_Threading_Thread_GetState (MonoInternalThread* this)
1924 ensure_synch_cs_set (this);
1926 EnterCriticalSection (this->synch_cs);
1928 state = this->state;
1930 LeaveCriticalSection (this->synch_cs);
1935 void ves_icall_System_Threading_Thread_Interrupt_internal (MonoInternalThread *this)
1937 gboolean throw = FALSE;
1939 ensure_synch_cs_set (this);
1941 if (this == mono_thread_internal_current ())
1944 EnterCriticalSection (this->synch_cs);
1946 this->thread_interrupt_requested = TRUE;
1948 if (this->state & ThreadState_WaitSleepJoin) {
1952 LeaveCriticalSection (this->synch_cs);
1955 signal_thread_state_change (this);
1959 void mono_thread_current_check_pending_interrupt ()
1961 MonoInternalThread *thread = mono_thread_internal_current ();
1962 gboolean throw = FALSE;
1964 mono_debugger_check_interruption ();
1966 ensure_synch_cs_set (thread);
1968 EnterCriticalSection (thread->synch_cs);
1970 if (thread->thread_interrupt_requested) {
1972 thread->thread_interrupt_requested = FALSE;
1975 LeaveCriticalSection (thread->synch_cs);
1978 mono_raise_exception (mono_get_exception_thread_interrupted ());
1983 mono_thread_get_abort_signal (void)
1995 static int abort_signum = -1;
1997 if (abort_signum != -1)
1998 return abort_signum;
1999 /* we try to avoid SIGRTMIN and any one that might have been set already, see bug #75387 */
2000 for (i = SIGRTMIN + 1; i < SIGRTMAX; ++i) {
2001 struct sigaction sinfo;
2002 sigaction (i, NULL, &sinfo);
2003 if (sinfo.sa_handler == SIG_DFL && (void*)sinfo.sa_sigaction == (void*)SIG_DFL) {
2008 /* fallback to the old way */
2011 #endif /* HOST_WIN32 */
2015 static void CALLBACK interruption_request_apc (ULONG_PTR param)
2017 MonoException* exc = mono_thread_request_interruption (FALSE);
2018 if (exc) mono_raise_exception (exc);
2020 #endif /* HOST_WIN32 */
2023 * signal_thread_state_change
2025 * Tells the thread that his state has changed and it has to enter the new
2026 * state as soon as possible.
2028 static void signal_thread_state_change (MonoInternalThread *thread)
2030 if (thread == mono_thread_internal_current ()) {
2031 /* Do it synchronously */
2032 MonoException *exc = mono_thread_request_interruption (FALSE);
2034 mono_raise_exception (exc);
2038 QueueUserAPC ((PAPCFUNC)interruption_request_apc, thread->handle, NULL);
2040 /* fixme: store the state somewhere */
2041 mono_thread_kill (thread, mono_thread_get_abort_signal ());
2044 * This will cause waits to be broken.
2045 * It will also prevent the thread from entering a wait, so if the thread returns
2046 * from the wait before it receives the abort signal, it will just spin in the wait
2047 * functions in the io-layer until the signal handler calls QueueUserAPC which will
2050 wapi_interrupt_thread (thread->handle);
2051 #endif /* HOST_WIN32 */
2055 ves_icall_System_Threading_Thread_Abort (MonoInternalThread *thread, MonoObject *state)
2057 ensure_synch_cs_set (thread);
2059 EnterCriticalSection (thread->synch_cs);
2061 if ((thread->state & ThreadState_AbortRequested) != 0 ||
2062 (thread->state & ThreadState_StopRequested) != 0 ||
2063 (thread->state & ThreadState_Stopped) != 0)
2065 LeaveCriticalSection (thread->synch_cs);
2069 if ((thread->state & ThreadState_Unstarted) != 0) {
2070 thread->state |= ThreadState_Aborted;
2071 LeaveCriticalSection (thread->synch_cs);
2075 thread->state |= ThreadState_AbortRequested;
2076 if (thread->abort_state_handle)
2077 mono_gchandle_free (thread->abort_state_handle);
2079 thread->abort_state_handle = mono_gchandle_new (state, FALSE);
2080 g_assert (thread->abort_state_handle);
2082 thread->abort_state_handle = 0;
2084 thread->abort_exc = NULL;
2087 * abort_exc is set in mono_thread_execute_interruption(),
2088 * triggered by the call to signal_thread_state_change(),
2089 * below. There's a point between where we have
2090 * abort_state_handle set, but abort_exc NULL, but that's not
2094 LeaveCriticalSection (thread->synch_cs);
2096 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Abort requested for %p (%"G_GSIZE_FORMAT")", __func__, GetCurrentThreadId (), thread, (gsize)thread->tid));
2098 /* During shutdown, we can't wait for other threads */
2100 /* Make sure the thread is awake */
2101 mono_thread_resume (thread);
2103 signal_thread_state_change (thread);
2107 ves_icall_System_Threading_Thread_ResetAbort (void)
2109 MonoInternalThread *thread = mono_thread_internal_current ();
2110 gboolean was_aborting;
2112 ensure_synch_cs_set (thread);
2114 EnterCriticalSection (thread->synch_cs);
2115 was_aborting = thread->state & ThreadState_AbortRequested;
2116 thread->state &= ~ThreadState_AbortRequested;
2117 LeaveCriticalSection (thread->synch_cs);
2119 if (!was_aborting) {
2120 const char *msg = "Unable to reset abort because no abort was requested";
2121 mono_raise_exception (mono_get_exception_thread_state (msg));
2123 thread->abort_exc = NULL;
2124 if (thread->abort_state_handle) {
2125 mono_gchandle_free (thread->abort_state_handle);
2126 /* This is actually not necessary - the handle
2127 only counts if the exception is set */
2128 thread->abort_state_handle = 0;
2133 mono_thread_internal_reset_abort (MonoInternalThread *thread)
2135 ensure_synch_cs_set (thread);
2137 EnterCriticalSection (thread->synch_cs);
2139 thread->state &= ~ThreadState_AbortRequested;
2141 if (thread->abort_exc) {
2142 thread->abort_exc = NULL;
2143 if (thread->abort_state_handle) {
2144 mono_gchandle_free (thread->abort_state_handle);
2145 /* This is actually not necessary - the handle
2146 only counts if the exception is set */
2147 thread->abort_state_handle = 0;
2151 LeaveCriticalSection (thread->synch_cs);
2155 ves_icall_System_Threading_Thread_GetAbortExceptionState (MonoThread *this)
2157 MonoInternalThread *thread = this->internal_thread;
2158 MonoObject *state, *deserialized = NULL, *exc;
2161 if (!thread->abort_state_handle)
2164 state = mono_gchandle_get_target (thread->abort_state_handle);
2167 domain = mono_domain_get ();
2168 if (mono_object_domain (state) == domain)
2171 deserialized = mono_object_xdomain_representation (state, domain, &exc);
2173 if (!deserialized) {
2174 MonoException *invalid_op_exc = mono_get_exception_invalid_operation ("Thread.ExceptionState cannot access an ExceptionState from a different AppDomain");
2176 MONO_OBJECT_SETREF (invalid_op_exc, inner_ex, exc);
2177 mono_raise_exception (invalid_op_exc);
2180 return deserialized;
2184 mono_thread_suspend (MonoInternalThread *thread)
2186 ensure_synch_cs_set (thread);
2188 EnterCriticalSection (thread->synch_cs);
2190 if ((thread->state & ThreadState_Unstarted) != 0 ||
2191 (thread->state & ThreadState_Aborted) != 0 ||
2192 (thread->state & ThreadState_Stopped) != 0)
2194 LeaveCriticalSection (thread->synch_cs);
2198 if ((thread->state & ThreadState_Suspended) != 0 ||
2199 (thread->state & ThreadState_SuspendRequested) != 0 ||
2200 (thread->state & ThreadState_StopRequested) != 0)
2202 LeaveCriticalSection (thread->synch_cs);
2206 thread->state |= ThreadState_SuspendRequested;
2208 LeaveCriticalSection (thread->synch_cs);
2210 signal_thread_state_change (thread);
2215 ves_icall_System_Threading_Thread_Suspend (MonoInternalThread *thread)
2217 if (!mono_thread_suspend (thread))
2218 mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started, or is dead."));
2222 mono_thread_resume (MonoInternalThread *thread)
2224 ensure_synch_cs_set (thread);
2226 EnterCriticalSection (thread->synch_cs);
2228 if ((thread->state & ThreadState_SuspendRequested) != 0) {
2229 thread->state &= ~ThreadState_SuspendRequested;
2230 LeaveCriticalSection (thread->synch_cs);
2234 if ((thread->state & ThreadState_Suspended) == 0 ||
2235 (thread->state & ThreadState_Unstarted) != 0 ||
2236 (thread->state & ThreadState_Aborted) != 0 ||
2237 (thread->state & ThreadState_Stopped) != 0)
2239 LeaveCriticalSection (thread->synch_cs);
2243 thread->resume_event = CreateEvent (NULL, TRUE, FALSE, NULL);
2244 if (thread->resume_event == NULL) {
2245 LeaveCriticalSection (thread->synch_cs);
2249 /* Awake the thread */
2250 SetEvent (thread->suspend_event);
2252 LeaveCriticalSection (thread->synch_cs);
2254 /* Wait for the thread to awake */
2255 WaitForSingleObject (thread->resume_event, INFINITE);
2256 CloseHandle (thread->resume_event);
2257 thread->resume_event = NULL;
2263 ves_icall_System_Threading_Thread_Resume (MonoThread *thread)
2265 if (!thread->internal_thread || !mono_thread_resume (thread->internal_thread))
2266 mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started, or is dead."));
2270 find_wrapper (MonoMethod *m, gint no, gint ilo, gboolean managed, gpointer data)
2275 if (m->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE ||
2276 m->wrapper_type == MONO_WRAPPER_XDOMAIN_INVOKE ||
2277 m->wrapper_type == MONO_WRAPPER_XDOMAIN_DISPATCH)
2279 *((gboolean*)data) = TRUE;
2286 is_running_protected_wrapper (void)
2288 gboolean found = FALSE;
2289 mono_stack_walk (find_wrapper, &found);
2293 void mono_thread_internal_stop (MonoInternalThread *thread)
2295 ensure_synch_cs_set (thread);
2297 EnterCriticalSection (thread->synch_cs);
2299 if ((thread->state & ThreadState_StopRequested) != 0 ||
2300 (thread->state & ThreadState_Stopped) != 0)
2302 LeaveCriticalSection (thread->synch_cs);
2306 /* Make sure the thread is awake */
2307 mono_thread_resume (thread);
2309 thread->state |= ThreadState_StopRequested;
2310 thread->state &= ~ThreadState_AbortRequested;
2312 LeaveCriticalSection (thread->synch_cs);
2314 signal_thread_state_change (thread);
2317 void mono_thread_stop (MonoThread *thread)
2319 mono_thread_internal_stop (thread->internal_thread);
2323 ves_icall_System_Threading_Thread_VolatileRead1 (void *ptr)
2325 return *((volatile gint8 *) (ptr));
2329 ves_icall_System_Threading_Thread_VolatileRead2 (void *ptr)
2331 return *((volatile gint16 *) (ptr));
2335 ves_icall_System_Threading_Thread_VolatileRead4 (void *ptr)
2337 return *((volatile gint32 *) (ptr));
2341 ves_icall_System_Threading_Thread_VolatileRead8 (void *ptr)
2343 return *((volatile gint64 *) (ptr));
2347 ves_icall_System_Threading_Thread_VolatileReadIntPtr (void *ptr)
2349 return (void *) *((volatile void **) ptr);
2353 ves_icall_System_Threading_Thread_VolatileWrite1 (void *ptr, gint8 value)
2355 *((volatile gint8 *) ptr) = value;
2359 ves_icall_System_Threading_Thread_VolatileWrite2 (void *ptr, gint16 value)
2361 *((volatile gint16 *) ptr) = value;
2365 ves_icall_System_Threading_Thread_VolatileWrite4 (void *ptr, gint32 value)
2367 *((volatile gint32 *) ptr) = value;
2371 ves_icall_System_Threading_Thread_VolatileWrite8 (void *ptr, gint64 value)
2373 *((volatile gint64 *) ptr) = value;
2377 ves_icall_System_Threading_Thread_VolatileWriteIntPtr (void *ptr, void *value)
2379 *((volatile void **) ptr) = value;
2383 ves_icall_System_Threading_Thread_VolatileWriteObject (void *ptr, void *value)
2385 mono_gc_wbarrier_generic_store (ptr, value);
2388 void mono_thread_init (MonoThreadStartCB start_cb,
2389 MonoThreadAttachCB attach_cb)
2391 mono_thread_smr_init ();
2393 InitializeCriticalSection(&threads_mutex);
2394 InitializeCriticalSection(&interlocked_mutex);
2395 InitializeCriticalSection(&contexts_mutex);
2397 background_change_event = CreateEvent (NULL, TRUE, FALSE, NULL);
2398 g_assert(background_change_event != NULL);
2400 mono_init_static_data_info (&thread_static_info);
2401 mono_init_static_data_info (&context_static_info);
2403 MONO_FAST_TLS_INIT (tls_current_object);
2404 current_object_key=TlsAlloc();
2405 THREAD_DEBUG (g_message ("%s: Allocated current_object_key %d", __func__, current_object_key));
2407 mono_thread_start_cb = start_cb;
2408 mono_thread_attach_cb = attach_cb;
2410 /* Get a pseudo handle to the current process. This is just a
2411 * kludge so that wapi can build a process handle if needed.
2412 * As a pseudo handle is returned, we don't need to clean
2415 GetCurrentProcess ();
2418 void mono_thread_cleanup (void)
2420 #if !defined(HOST_WIN32) && !defined(RUN_IN_SUBTHREAD)
2421 /* The main thread must abandon any held mutexes (particularly
2422 * important for named mutexes as they are shared across
2423 * processes, see bug 74680.) This will happen when the
2424 * thread exits, but if it's not running in a subthread it
2425 * won't exit in time.
2427 /* Using non-w32 API is a nasty kludge, but I couldn't find
2428 * anything in the documentation that would let me do this
2429 * here yet still be safe to call on windows.
2431 _wapi_thread_signal_self (mono_environment_exitcode_get ());
2435 /* This stuff needs more testing, it seems one of these
2436 * critical sections can be locked when mono_thread_cleanup is
2439 DeleteCriticalSection (&threads_mutex);
2440 DeleteCriticalSection (&interlocked_mutex);
2441 DeleteCriticalSection (&contexts_mutex);
2442 DeleteCriticalSection (&delayed_free_table_mutex);
2443 DeleteCriticalSection (&small_id_mutex);
2444 CloseHandle (background_change_event);
2447 TlsFree (current_object_key);
2451 mono_threads_install_cleanup (MonoThreadCleanupFunc func)
2453 mono_thread_cleanup_fn = func;
2457 mono_thread_set_manage_callback (MonoThread *thread, MonoThreadManageCallback func)
2459 thread->internal_thread->manage_callback = func;
2462 void mono_threads_install_notify_pending_exc (MonoThreadNotifyPendingExcFunc func)
2464 mono_thread_notify_pending_exc_fn = func;
2468 static void print_tids (gpointer key, gpointer value, gpointer user)
2470 /* GPOINTER_TO_UINT breaks horribly if sizeof(void *) >
2471 * sizeof(uint) and a cast to uint would overflow
2473 /* Older versions of glib don't have G_GSIZE_FORMAT, so just
2474 * print this as a pointer.
2476 g_message ("Waiting for: %p", key);
2481 HANDLE handles[MAXIMUM_WAIT_OBJECTS];
2482 MonoInternalThread *threads[MAXIMUM_WAIT_OBJECTS];
2486 static void wait_for_tids (struct wait_data *wait, guint32 timeout)
2490 THREAD_DEBUG (g_message("%s: %d threads to wait for in this batch", __func__, wait->num));
2492 ret=WaitForMultipleObjectsEx(wait->num, wait->handles, TRUE, timeout, TRUE);
2494 if(ret==WAIT_FAILED) {
2495 /* See the comment in build_wait_tids() */
2496 THREAD_DEBUG (g_message ("%s: Wait failed", __func__));
2500 for(i=0; i<wait->num; i++)
2501 CloseHandle (wait->handles[i]);
2503 if (ret == WAIT_TIMEOUT)
2506 for(i=0; i<wait->num; i++) {
2507 gsize tid = wait->threads[i]->tid;
2509 mono_threads_lock ();
2510 if(mono_g_hash_table_lookup (threads, (gpointer)tid)!=NULL) {
2511 /* This thread must have been killed, because
2512 * it hasn't cleaned itself up. (It's just
2513 * possible that the thread exited before the
2514 * parent thread had a chance to store the
2515 * handle, and now there is another pointer to
2516 * the already-exited thread stored. In this
2517 * case, we'll just get two
2518 * mono_profiler_thread_end() calls for the
2522 mono_threads_unlock ();
2523 THREAD_DEBUG (g_message ("%s: cleaning up after thread %p (%"G_GSIZE_FORMAT")", __func__, wait->threads[i], tid));
2524 thread_cleanup (wait->threads[i]);
2526 mono_threads_unlock ();
2531 static void wait_for_tids_or_state_change (struct wait_data *wait, guint32 timeout)
2533 guint32 i, ret, count;
2535 THREAD_DEBUG (g_message("%s: %d threads to wait for in this batch", __func__, wait->num));
2537 /* Add the thread state change event, so it wakes up if a thread changes
2538 * to background mode.
2541 if (count < MAXIMUM_WAIT_OBJECTS) {
2542 wait->handles [count] = background_change_event;
2546 ret=WaitForMultipleObjectsEx (count, wait->handles, FALSE, timeout, TRUE);
2548 if(ret==WAIT_FAILED) {
2549 /* See the comment in build_wait_tids() */
2550 THREAD_DEBUG (g_message ("%s: Wait failed", __func__));
2554 for(i=0; i<wait->num; i++)
2555 CloseHandle (wait->handles[i]);
2557 if (ret == WAIT_TIMEOUT)
2560 if (ret < wait->num) {
2561 gsize tid = wait->threads[ret]->tid;
2562 mono_threads_lock ();
2563 if (mono_g_hash_table_lookup (threads, (gpointer)tid)!=NULL) {
2564 /* See comment in wait_for_tids about thread cleanup */
2565 mono_threads_unlock ();
2566 THREAD_DEBUG (g_message ("%s: cleaning up after thread %"G_GSIZE_FORMAT, __func__, tid));
2567 thread_cleanup (wait->threads [ret]);
2569 mono_threads_unlock ();
2573 static void build_wait_tids (gpointer key, gpointer value, gpointer user)
2575 struct wait_data *wait=(struct wait_data *)user;
2577 if(wait->num<MAXIMUM_WAIT_OBJECTS) {
2579 MonoInternalThread *thread=(MonoInternalThread *)value;
2581 /* Ignore background threads, we abort them later */
2582 /* Do not lock here since it is not needed and the caller holds threads_lock */
2583 if (thread->state & ThreadState_Background) {
2584 THREAD_DEBUG (g_message ("%s: ignoring background thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2585 return; /* just leave, ignore */
2588 if (mono_gc_is_finalizer_internal_thread (thread)) {
2589 THREAD_DEBUG (g_message ("%s: ignoring finalizer thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2593 if (thread == mono_thread_internal_current ()) {
2594 THREAD_DEBUG (g_message ("%s: ignoring current thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2598 if (mono_thread_get_main () && (thread == mono_thread_get_main ()->internal_thread)) {
2599 THREAD_DEBUG (g_message ("%s: ignoring main thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2603 if (thread->flags & MONO_THREAD_FLAG_DONT_MANAGE) {
2604 THREAD_DEBUG (g_message ("%s: ignoring thread %" G_GSIZE_FORMAT "with DONT_MANAGE flag set.", __func__, (gsize)thread->tid));
2608 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
2609 if (handle == NULL) {
2610 THREAD_DEBUG (g_message ("%s: ignoring unopenable thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2614 THREAD_DEBUG (g_message ("%s: Invoking mono_thread_manage callback on thread %p", __func__, thread));
2615 if ((thread->manage_callback == NULL) || (thread->manage_callback (thread->root_domain_thread) == TRUE)) {
2616 wait->handles[wait->num]=handle;
2617 wait->threads[wait->num]=thread;
2620 THREAD_DEBUG (g_message ("%s: adding thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2622 THREAD_DEBUG (g_message ("%s: ignoring (because of callback) thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2627 /* Just ignore the rest, we can't do anything with
2634 remove_and_abort_threads (gpointer key, gpointer value, gpointer user)
2636 struct wait_data *wait=(struct wait_data *)user;
2637 gsize self = GetCurrentThreadId ();
2638 MonoInternalThread *thread = value;
2641 if (wait->num >= MAXIMUM_WAIT_OBJECTS)
2644 /* The finalizer thread is not a background thread */
2645 if (thread->tid != self && (thread->state & ThreadState_Background) != 0 &&
2646 !(thread->flags & MONO_THREAD_FLAG_DONT_MANAGE)) {
2648 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
2652 /* printf ("A: %d\n", wait->num); */
2653 wait->handles[wait->num]=thread->handle;
2654 wait->threads[wait->num]=thread;
2657 THREAD_DEBUG (g_print ("%s: Aborting id: %"G_GSIZE_FORMAT"\n", __func__, (gsize)thread->tid));
2658 mono_thread_internal_stop (thread);
2662 return (thread->tid != self && !mono_gc_is_finalizer_internal_thread (thread));
2666 * mono_threads_set_shutting_down:
2668 * Is called by a thread that wants to shut down Mono. If the runtime is already
2669 * shutting down, the calling thread is suspended/stopped, and this function never
2673 mono_threads_set_shutting_down (void)
2675 MonoInternalThread *current_thread = mono_thread_internal_current ();
2677 mono_threads_lock ();
2679 if (shutting_down) {
2680 mono_threads_unlock ();
2682 /* Make sure we're properly suspended/stopped */
2684 EnterCriticalSection (current_thread->synch_cs);
2686 if ((current_thread->state & ThreadState_SuspendRequested) ||
2687 (current_thread->state & ThreadState_AbortRequested) ||
2688 (current_thread->state & ThreadState_StopRequested)) {
2689 LeaveCriticalSection (current_thread->synch_cs);
2690 mono_thread_execute_interruption (current_thread);
2692 current_thread->state |= ThreadState_Stopped;
2693 LeaveCriticalSection (current_thread->synch_cs);
2696 /*since we're killing the thread, unset the current domain.*/
2697 mono_domain_unset ();
2699 /* Wake up other threads potentially waiting for us */
2702 shutting_down = TRUE;
2704 /* Not really a background state change, but this will
2705 * interrupt the main thread if it is waiting for all
2706 * the other threads.
2708 SetEvent (background_change_event);
2710 mono_threads_unlock ();
2715 * mono_threads_is_shutting_down:
2717 * Returns whether a thread has commenced shutdown of Mono. Note that
2718 * if the function returns FALSE the caller must not assume that
2719 * shutdown is not in progress, because the situation might have
2720 * changed since the function returned. For that reason this function
2721 * is of very limited utility.
2724 mono_threads_is_shutting_down (void)
2726 return shutting_down;
2729 void mono_thread_manage (void)
2731 struct wait_data wait_data;
2732 struct wait_data *wait = &wait_data;
2734 memset (wait, 0, sizeof (struct wait_data));
2735 /* join each thread that's still running */
2736 THREAD_DEBUG (g_message ("%s: Joining each running thread...", __func__));
2738 mono_threads_lock ();
2740 THREAD_DEBUG (g_message("%s: No threads", __func__));
2741 mono_threads_unlock ();
2744 mono_threads_unlock ();
2747 mono_threads_lock ();
2748 if (shutting_down) {
2749 /* somebody else is shutting down */
2750 mono_threads_unlock ();
2753 THREAD_DEBUG (g_message ("%s: There are %d threads to join", __func__, mono_g_hash_table_size (threads));
2754 mono_g_hash_table_foreach (threads, print_tids, NULL));
2756 ResetEvent (background_change_event);
2758 /*We must zero all InternalThread pointers to avoid making the GC unhappy.*/
2759 memset (wait->threads, 0, MAXIMUM_WAIT_OBJECTS * SIZEOF_VOID_P);
2760 mono_g_hash_table_foreach (threads, build_wait_tids, wait);
2761 mono_threads_unlock ();
2763 /* Something to wait for */
2764 wait_for_tids_or_state_change (wait, INFINITE);
2766 THREAD_DEBUG (g_message ("%s: I have %d threads after waiting.", __func__, wait->num));
2767 } while(wait->num>0);
2769 mono_threads_set_shutting_down ();
2771 /* No new threads will be created after this point */
2773 mono_runtime_set_shutting_down ();
2775 THREAD_DEBUG (g_message ("%s: threadpool cleanup", __func__));
2776 mono_thread_pool_cleanup ();
2779 * Remove everything but the finalizer thread and self.
2780 * Also abort all the background threads
2783 mono_threads_lock ();
2786 /*We must zero all InternalThread pointers to avoid making the GC unhappy.*/
2787 memset (wait->threads, 0, MAXIMUM_WAIT_OBJECTS * SIZEOF_VOID_P);
2788 mono_g_hash_table_foreach_remove (threads, remove_and_abort_threads, wait);
2790 mono_threads_unlock ();
2792 THREAD_DEBUG (g_message ("%s: wait->num is now %d", __func__, wait->num));
2794 /* Something to wait for */
2795 wait_for_tids (wait, INFINITE);
2797 } while (wait->num > 0);
2800 * give the subthreads a chance to really quit (this is mainly needed
2801 * to get correct user and system times from getrusage/wait/time(1)).
2802 * This could be removed if we avoid pthread_detach() and use pthread_join().
2809 static void terminate_thread (gpointer key, gpointer value, gpointer user)
2811 MonoInternalThread *thread=(MonoInternalThread *)value;
2813 if(thread->tid != (gsize)user) {
2814 /*TerminateThread (thread->handle, -1);*/
2818 void mono_thread_abort_all_other_threads (void)
2820 gsize self = GetCurrentThreadId ();
2822 mono_threads_lock ();
2823 THREAD_DEBUG (g_message ("%s: There are %d threads to abort", __func__,
2824 mono_g_hash_table_size (threads));
2825 mono_g_hash_table_foreach (threads, print_tids, NULL));
2827 mono_g_hash_table_foreach (threads, terminate_thread, (gpointer)self);
2829 mono_threads_unlock ();
2833 collect_threads_for_suspend (gpointer key, gpointer value, gpointer user_data)
2835 MonoInternalThread *thread = (MonoInternalThread*)value;
2836 struct wait_data *wait = (struct wait_data*)user_data;
2840 * We try to exclude threads early, to avoid running into the MAXIMUM_WAIT_OBJECTS
2842 * This needs no locking.
2844 if ((thread->state & ThreadState_Suspended) != 0 ||
2845 (thread->state & ThreadState_Stopped) != 0)
2848 if (wait->num<MAXIMUM_WAIT_OBJECTS) {
2849 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
2853 wait->handles [wait->num] = handle;
2854 wait->threads [wait->num] = thread;
2860 * mono_thread_suspend_all_other_threads:
2862 * Suspend all managed threads except the finalizer thread and this thread. It is
2863 * not possible to resume them later.
2865 void mono_thread_suspend_all_other_threads (void)
2867 struct wait_data wait_data;
2868 struct wait_data *wait = &wait_data;
2870 gsize self = GetCurrentThreadId ();
2872 guint32 eventidx = 0;
2873 gboolean starting, finished;
2875 memset (wait, 0, sizeof (struct wait_data));
2877 * The other threads could be in an arbitrary state at this point, i.e.
2878 * they could be starting up, shutting down etc. This means that there could be
2879 * threads which are not even in the threads hash table yet.
2883 * First we set a barrier which will be checked by all threads before they
2884 * are added to the threads hash table, and they will exit if the flag is set.
2885 * This ensures that no threads could be added to the hash later.
2886 * We will use shutting_down as the barrier for now.
2888 g_assert (shutting_down);
2891 * We make multiple calls to WaitForMultipleObjects since:
2892 * - we can only wait for MAXIMUM_WAIT_OBJECTS threads
2893 * - some threads could exit without becoming suspended
2898 * Make a copy of the hashtable since we can't do anything with
2899 * threads while threads_mutex is held.
2902 /*We must zero all InternalThread pointers to avoid making the GC unhappy.*/
2903 memset (wait->threads, 0, MAXIMUM_WAIT_OBJECTS * SIZEOF_VOID_P);
2904 mono_threads_lock ();
2905 mono_g_hash_table_foreach (threads, collect_threads_for_suspend, wait);
2906 mono_threads_unlock ();
2908 events = g_new0 (gpointer, wait->num);
2910 /* Get the suspended events that we'll be waiting for */
2911 for (i = 0; i < wait->num; ++i) {
2912 MonoInternalThread *thread = wait->threads [i];
2913 gboolean signal_suspend = FALSE;
2915 if ((thread->tid == self) || mono_gc_is_finalizer_internal_thread (thread) || (thread->flags & MONO_THREAD_FLAG_DONT_MANAGE)) {
2916 //CloseHandle (wait->handles [i]);
2917 wait->threads [i] = NULL; /* ignore this thread in next loop */
2921 ensure_synch_cs_set (thread);
2923 EnterCriticalSection (thread->synch_cs);
2925 if (thread->suspended_event == NULL) {
2926 thread->suspended_event = CreateEvent (NULL, TRUE, FALSE, NULL);
2927 if (thread->suspended_event == NULL) {
2928 /* Forget this one and go on to the next */
2929 LeaveCriticalSection (thread->synch_cs);
2934 if ((thread->state & ThreadState_Suspended) != 0 ||
2935 (thread->state & ThreadState_StopRequested) != 0 ||
2936 (thread->state & ThreadState_Stopped) != 0) {
2937 LeaveCriticalSection (thread->synch_cs);
2938 CloseHandle (wait->handles [i]);
2939 wait->threads [i] = NULL; /* ignore this thread in next loop */
2943 if ((thread->state & ThreadState_SuspendRequested) == 0)
2944 signal_suspend = TRUE;
2946 events [eventidx++] = thread->suspended_event;
2948 /* Convert abort requests into suspend requests */
2949 if ((thread->state & ThreadState_AbortRequested) != 0)
2950 thread->state &= ~ThreadState_AbortRequested;
2952 thread->state |= ThreadState_SuspendRequested;
2954 LeaveCriticalSection (thread->synch_cs);
2956 /* Signal the thread to suspend */
2958 signal_thread_state_change (thread);
2962 WaitForMultipleObjectsEx (eventidx, events, TRUE, 100, FALSE);
2963 for (i = 0; i < wait->num; ++i) {
2964 MonoInternalThread *thread = wait->threads [i];
2969 ensure_synch_cs_set (thread);
2971 EnterCriticalSection (thread->synch_cs);
2972 if ((thread->state & ThreadState_Suspended) != 0) {
2973 CloseHandle (thread->suspended_event);
2974 thread->suspended_event = NULL;
2976 LeaveCriticalSection (thread->synch_cs);
2980 * If there are threads which are starting up, we wait until they
2981 * are suspended when they try to register in the threads hash.
2982 * This is guaranteed to finish, since the threads which can create new
2983 * threads get suspended after a while.
2984 * FIXME: The finalizer thread can still create new threads.
2986 mono_threads_lock ();
2987 if (threads_starting_up)
2988 starting = mono_g_hash_table_size (threads_starting_up) > 0;
2991 mono_threads_unlock ();
3003 collect_threads (gpointer key, gpointer value, gpointer user_data)
3005 MonoInternalThread *thread = (MonoInternalThread*)value;
3006 struct wait_data *wait = (struct wait_data*)user_data;
3009 if (wait->num<MAXIMUM_WAIT_OBJECTS) {
3010 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
3014 wait->handles [wait->num] = handle;
3015 wait->threads [wait->num] = thread;
3021 * mono_threads_request_thread_dump:
3023 * Ask all threads except the current to print their stacktrace to stdout.
3026 mono_threads_request_thread_dump (void)
3028 struct wait_data wait_data;
3029 struct wait_data *wait = &wait_data;
3032 memset (wait, 0, sizeof (struct wait_data));
3035 * Make a copy of the hashtable since we can't do anything with
3036 * threads while threads_mutex is held.
3038 mono_threads_lock ();
3039 mono_g_hash_table_foreach (threads, collect_threads, wait);
3040 mono_threads_unlock ();
3042 for (i = 0; i < wait->num; ++i) {
3043 MonoInternalThread *thread = wait->threads [i];
3045 if (!mono_gc_is_finalizer_internal_thread (thread) &&
3046 (thread != mono_thread_internal_current ()) &&
3047 !thread->thread_dump_requested) {
3048 thread->thread_dump_requested = TRUE;
3050 signal_thread_state_change (thread);
3053 CloseHandle (wait->handles [i]);
3059 gint allocated; /* +1 so that refs [allocated] == NULL */
3063 typedef struct ref_stack RefStack;
3066 ref_stack_new (gint initial_size)
3070 initial_size = MAX (initial_size, 16) + 1;
3071 rs = g_new0 (RefStack, 1);
3072 rs->refs = g_new0 (gpointer, initial_size);
3073 rs->allocated = initial_size;
3078 ref_stack_destroy (gpointer ptr)
3089 ref_stack_push (RefStack *rs, gpointer ptr)
3091 g_assert (rs != NULL);
3093 if (rs->bottom >= rs->allocated) {
3094 rs->refs = g_realloc (rs->refs, rs->allocated * 2 * sizeof (gpointer) + 1);
3095 rs->allocated <<= 1;
3096 rs->refs [rs->allocated] = NULL;
3098 rs->refs [rs->bottom++] = ptr;
3102 ref_stack_pop (RefStack *rs)
3104 if (rs == NULL || rs->bottom == 0)
3108 rs->refs [rs->bottom] = NULL;
3112 ref_stack_find (RefStack *rs, gpointer ptr)
3119 for (refs = rs->refs; refs && *refs; refs++) {
3127 * mono_thread_push_appdomain_ref:
3129 * Register that the current thread may have references to objects in domain
3130 * @domain on its stack. Each call to this function should be paired with a
3131 * call to pop_appdomain_ref.
3134 mono_thread_push_appdomain_ref (MonoDomain *domain)
3136 MonoInternalThread *thread = mono_thread_internal_current ();
3139 /* printf ("PUSH REF: %"G_GSIZE_FORMAT" -> %s.\n", (gsize)thread->tid, domain->friendly_name); */
3140 SPIN_LOCK (thread->lock_thread_id);
3141 if (thread->appdomain_refs == NULL)
3142 thread->appdomain_refs = ref_stack_new (16);
3143 ref_stack_push (thread->appdomain_refs, domain);
3144 SPIN_UNLOCK (thread->lock_thread_id);
3149 mono_thread_pop_appdomain_ref (void)
3151 MonoInternalThread *thread = mono_thread_internal_current ();
3154 /* printf ("POP REF: %"G_GSIZE_FORMAT" -> %s.\n", (gsize)thread->tid, ((MonoDomain*)(thread->appdomain_refs->data))->friendly_name); */
3155 SPIN_LOCK (thread->lock_thread_id);
3156 ref_stack_pop (thread->appdomain_refs);
3157 SPIN_UNLOCK (thread->lock_thread_id);
3162 mono_thread_internal_has_appdomain_ref (MonoInternalThread *thread, MonoDomain *domain)
3165 SPIN_LOCK (thread->lock_thread_id);
3166 res = ref_stack_find (thread->appdomain_refs, domain);
3167 SPIN_UNLOCK (thread->lock_thread_id);
3172 mono_thread_has_appdomain_ref (MonoThread *thread, MonoDomain *domain)
3174 return mono_thread_internal_has_appdomain_ref (thread->internal_thread, domain);
3177 typedef struct abort_appdomain_data {
3178 struct wait_data wait;
3180 } abort_appdomain_data;
3183 collect_appdomain_thread (gpointer key, gpointer value, gpointer user_data)
3185 MonoInternalThread *thread = (MonoInternalThread*)value;
3186 abort_appdomain_data *data = (abort_appdomain_data*)user_data;
3187 MonoDomain *domain = data->domain;
3189 if (mono_thread_internal_has_appdomain_ref (thread, domain)) {
3190 /* printf ("ABORTING THREAD %p BECAUSE IT REFERENCES DOMAIN %s.\n", thread->tid, domain->friendly_name); */
3192 if(data->wait.num<MAXIMUM_WAIT_OBJECTS) {
3193 HANDLE handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
3196 data->wait.handles [data->wait.num] = handle;
3197 data->wait.threads [data->wait.num] = thread;
3200 /* Just ignore the rest, we can't do anything with
3208 * mono_threads_abort_appdomain_threads:
3210 * Abort threads which has references to the given appdomain.
3213 mono_threads_abort_appdomain_threads (MonoDomain *domain, int timeout)
3215 abort_appdomain_data user_data;
3217 int orig_timeout = timeout;
3220 THREAD_DEBUG (g_message ("%s: starting abort", __func__));
3222 start_time = mono_msec_ticks ();
3224 mono_threads_lock ();
3226 user_data.domain = domain;
3227 user_data.wait.num = 0;
3228 /* This shouldn't take any locks */
3229 mono_g_hash_table_foreach (threads, collect_appdomain_thread, &user_data);
3230 mono_threads_unlock ();
3232 if (user_data.wait.num > 0) {
3233 /* Abort the threads outside the threads lock */
3234 for (i = 0; i < user_data.wait.num; ++i)
3235 ves_icall_System_Threading_Thread_Abort (user_data.wait.threads [i], NULL);
3238 * We should wait for the threads either to abort, or to leave the
3239 * domain. We can't do the latter, so we wait with a timeout.
3241 wait_for_tids (&user_data.wait, 100);
3244 /* Update remaining time */
3245 timeout -= mono_msec_ticks () - start_time;
3246 start_time = mono_msec_ticks ();
3248 if (orig_timeout != -1 && timeout < 0)
3251 while (user_data.wait.num > 0);
3253 THREAD_DEBUG (g_message ("%s: abort done", __func__));
3259 clear_cached_culture (gpointer key, gpointer value, gpointer user_data)
3261 MonoInternalThread *thread = (MonoInternalThread*)value;
3262 MonoDomain *domain = (MonoDomain*)user_data;
3265 /* No locking needed here */
3266 /* FIXME: why no locking? writes to the cache are protected with synch_cs above */
3268 if (thread->cached_culture_info) {
3269 for (i = 0; i < NUM_CACHED_CULTURES * 2; ++i) {
3270 MonoObject *obj = mono_array_get (thread->cached_culture_info, MonoObject*, i);
3271 if (obj && obj->vtable->domain == domain)
3272 mono_array_set (thread->cached_culture_info, MonoObject*, i, NULL);
3278 * mono_threads_clear_cached_culture:
3280 * Clear the cached_current_culture from all threads if it is in the
3284 mono_threads_clear_cached_culture (MonoDomain *domain)
3286 mono_threads_lock ();
3287 mono_g_hash_table_foreach (threads, clear_cached_culture, domain);
3288 mono_threads_unlock ();
3292 * mono_thread_get_undeniable_exception:
3294 * Return an exception which needs to be raised when leaving a catch clause.
3295 * This is used for undeniable exception propagation.
3298 mono_thread_get_undeniable_exception (void)
3300 MonoInternalThread *thread = mono_thread_internal_current ();
3302 if (thread && thread->abort_exc && !is_running_protected_wrapper ()) {
3304 * FIXME: Clear the abort exception and return an AppDomainUnloaded
3305 * exception if the thread no longer references a dying appdomain.
3307 thread->abort_exc->trace_ips = NULL;
3308 thread->abort_exc->stack_trace = NULL;
3309 return thread->abort_exc;
3315 #if MONO_SMALL_CONFIG
3316 #define NUM_STATIC_DATA_IDX 4
3317 static const int static_data_size [NUM_STATIC_DATA_IDX] = {
3321 #define NUM_STATIC_DATA_IDX 8
3322 static const int static_data_size [NUM_STATIC_DATA_IDX] = {
3323 1024, 4096, 16384, 65536, 262144, 1048576, 4194304, 16777216
3327 static uintptr_t* static_reference_bitmaps [NUM_STATIC_DATA_IDX];
3331 mark_tls_slots (void *addr, MonoGCMarkFunc mark_func)
3334 gpointer *static_data = addr;
3335 for (i = 0; i < NUM_STATIC_DATA_IDX; ++i) {
3338 if (!static_data [i])
3340 numwords = 1 + static_data_size [i] / sizeof (gpointer) / (sizeof(uintptr_t) * 8);
3341 ptr = static_data [i];
3342 for (j = 0; j < numwords; ++j, ptr += sizeof (uintptr_t) * 8) {
3343 uintptr_t bmap = static_reference_bitmaps [i][j];
3346 if ((bmap & 1) && *p) {
3358 * mono_alloc_static_data
3360 * Allocate memory blocks for storing threads or context static data
3363 mono_alloc_static_data (gpointer **static_data_ptr, guint32 offset, gboolean threadlocal)
3365 guint idx = (offset >> 24) - 1;
3368 gpointer* static_data = *static_data_ptr;
3370 static void* tls_desc = NULL;
3373 tls_desc = mono_gc_make_root_descr_user (mark_tls_slots);
3375 static_data = mono_gc_alloc_fixed (static_data_size [0], threadlocal?tls_desc:NULL);
3376 *static_data_ptr = static_data;
3377 static_data [0] = static_data;
3380 for (i = 1; i <= idx; ++i) {
3381 if (static_data [i])
3384 static_data [i] = threadlocal?g_malloc0 (static_data_size [i]):mono_gc_alloc_fixed (static_data_size [i], NULL);
3386 static_data [i] = mono_gc_alloc_fixed (static_data_size [i], NULL);
3392 mono_free_static_data (gpointer* static_data, gboolean threadlocal)
3395 for (i = 1; i < NUM_STATIC_DATA_IDX; ++i) {
3396 if (!static_data [i])
3400 g_free (static_data [i]);
3402 mono_gc_free_fixed (static_data [i]);
3404 mono_gc_free_fixed (static_data [i]);
3407 mono_gc_free_fixed (static_data);
3411 * mono_init_static_data_info
3413 * Initializes static data counters
3415 static void mono_init_static_data_info (StaticDataInfo *static_data)
3417 static_data->idx = 0;
3418 static_data->offset = 0;
3419 static_data->freelist = NULL;
3423 * mono_alloc_static_data_slot
3425 * Generates an offset for static data. static_data contains the counters
3426 * used to generate it.
3429 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align)
3433 if (!static_data->idx && !static_data->offset) {
3435 * we use the first chunk of the first allocation also as
3436 * an array for the rest of the data
3438 static_data->offset = sizeof (gpointer) * NUM_STATIC_DATA_IDX;
3440 static_data->offset += align - 1;
3441 static_data->offset &= ~(align - 1);
3442 if (static_data->offset + size >= static_data_size [static_data->idx]) {
3443 static_data->idx ++;
3444 g_assert (size <= static_data_size [static_data->idx]);
3445 g_assert (static_data->idx < NUM_STATIC_DATA_IDX);
3446 static_data->offset = 0;
3448 offset = static_data->offset | ((static_data->idx + 1) << 24);
3449 static_data->offset += size;
3454 * ensure thread static fields already allocated are valid for thread
3455 * This function is called when a thread is created or on thread attach.
3458 thread_adjust_static_data (MonoInternalThread *thread)
3462 mono_threads_lock ();
3463 if (thread_static_info.offset || thread_static_info.idx > 0) {
3464 /* get the current allocated size */
3465 offset = thread_static_info.offset | ((thread_static_info.idx + 1) << 24);
3466 mono_alloc_static_data (&(thread->static_data), offset, TRUE);
3468 mono_threads_unlock ();
3472 alloc_thread_static_data_helper (gpointer key, gpointer value, gpointer user)
3474 MonoInternalThread *thread = value;
3475 guint32 offset = GPOINTER_TO_UINT (user);
3477 mono_alloc_static_data (&(thread->static_data), offset, TRUE);
3480 static MonoThreadDomainTls*
3481 search_tls_slot_in_freelist (StaticDataInfo *static_data, guint32 size, guint32 align)
3483 MonoThreadDomainTls* prev = NULL;
3484 MonoThreadDomainTls* tmp = static_data->freelist;
3486 if (tmp->size == size) {
3488 prev->next = tmp->next;
3490 static_data->freelist = tmp->next;
3499 update_tls_reference_bitmap (guint32 offset, uintptr_t *bitmap, int max_set)
3502 int idx = (offset >> 24) - 1;
3504 if (!static_reference_bitmaps [idx])
3505 static_reference_bitmaps [idx] = g_new0 (uintptr_t, 1 + static_data_size [idx] / sizeof(gpointer) / (sizeof(uintptr_t) * 8));
3506 rb = static_reference_bitmaps [idx];
3508 offset /= sizeof (gpointer);
3509 /* offset is now the bitmap offset */
3510 for (i = 0; i < max_set; ++i) {
3511 if (bitmap [i / sizeof (uintptr_t)] & (1L << (i & (sizeof (uintptr_t) * 8 -1))))
3512 rb [(offset + i) / (sizeof (uintptr_t) * 8)] |= (1L << ((offset + i) & (sizeof (uintptr_t) * 8 -1)));
3517 clear_reference_bitmap (guint32 offset, guint32 size)
3519 int idx = (offset >> 24) - 1;
3521 rb = static_reference_bitmaps [idx];
3523 offset /= sizeof (gpointer);
3524 size /= sizeof (gpointer);
3526 /* offset is now the bitmap offset */
3527 for (; offset < size; ++offset)
3528 rb [offset / (sizeof (uintptr_t) * 8)] &= ~(1L << (offset & (sizeof (uintptr_t) * 8 -1)));
3532 * The offset for a special static variable is composed of three parts:
3533 * a bit that indicates the type of static data (0:thread, 1:context),
3534 * an index in the array of chunks of memory for the thread (thread->static_data)
3535 * and an offset in that chunk of mem. This allows allocating less memory in the
3540 mono_alloc_special_static_data (guint32 static_type, guint32 size, guint32 align, uintptr_t *bitmap, int max_set)
3543 if (static_type == SPECIAL_STATIC_THREAD) {
3544 MonoThreadDomainTls *item;
3545 mono_threads_lock ();
3546 item = search_tls_slot_in_freelist (&thread_static_info, size, align);
3547 /*g_print ("TLS alloc: %d in domain %p (total: %d), cached: %p\n", size, mono_domain_get (), thread_static_info.offset, item);*/
3549 offset = item->offset;
3552 offset = mono_alloc_static_data_slot (&thread_static_info, size, align);
3554 update_tls_reference_bitmap (offset, bitmap, max_set);
3555 /* This can be called during startup */
3556 if (threads != NULL)
3557 mono_g_hash_table_foreach (threads, alloc_thread_static_data_helper, GUINT_TO_POINTER (offset));
3558 mono_threads_unlock ();
3560 g_assert (static_type == SPECIAL_STATIC_CONTEXT);
3561 mono_contexts_lock ();
3562 offset = mono_alloc_static_data_slot (&context_static_info, size, align);
3563 mono_contexts_unlock ();
3564 offset |= 0x80000000; /* Set the high bit to indicate context static data */
3570 mono_get_special_static_data_for_thread (MonoInternalThread *thread, guint32 offset)
3572 /* The high bit means either thread (0) or static (1) data. */
3574 guint32 static_type = (offset & 0x80000000);
3577 offset &= 0x7fffffff;
3578 idx = (offset >> 24) - 1;
3580 if (static_type == 0) {
3581 return get_thread_static_data (thread, offset);
3583 /* Allocate static data block under demand, since we don't have a list
3586 MonoAppContext *context = mono_context_get ();
3587 if (!context->static_data || !context->static_data [idx]) {
3588 mono_contexts_lock ();
3589 mono_alloc_static_data (&(context->static_data), offset, FALSE);
3590 mono_contexts_unlock ();
3592 return ((char*) context->static_data [idx]) + (offset & 0xffffff);
3597 mono_get_special_static_data (guint32 offset)
3599 return mono_get_special_static_data_for_thread (mono_thread_internal_current (), offset);
3608 free_thread_static_data_helper (gpointer key, gpointer value, gpointer user)
3610 MonoInternalThread *thread = value;
3611 TlsOffsetSize *data = user;
3612 int idx = (data->offset >> 24) - 1;
3615 if (!thread->static_data || !thread->static_data [idx])
3617 ptr = ((char*) thread->static_data [idx]) + (data->offset & 0xffffff);
3618 memset (ptr, 0, data->size);
3622 do_free_special_slot (guint32 offset, guint32 size)
3624 guint32 static_type = (offset & 0x80000000);
3625 /*g_print ("free %s , size: %d, offset: %x\n", field->name, size, offset);*/
3626 if (static_type == 0) {
3628 MonoThreadDomainTls *item = g_new0 (MonoThreadDomainTls, 1);
3629 data.offset = offset & 0x7fffffff;
3631 clear_reference_bitmap (data.offset, data.size);
3632 if (threads != NULL)
3633 mono_g_hash_table_foreach (threads, free_thread_static_data_helper, &data);
3634 item->offset = offset;
3637 if (!mono_runtime_is_shutting_down ()) {
3638 item->next = thread_static_info.freelist;
3639 thread_static_info.freelist = item;
3641 /* We could be called during shutdown after mono_thread_cleanup () is called */
3645 /* FIXME: free context static data as well */
3650 do_free_special (gpointer key, gpointer value, gpointer data)
3652 MonoClassField *field = key;
3653 guint32 offset = GPOINTER_TO_UINT (value);
3656 size = mono_type_size (field->type, &align);
3657 do_free_special_slot (offset, size);
3661 mono_alloc_special_static_data_free (GHashTable *special_static_fields)
3663 mono_threads_lock ();
3664 g_hash_table_foreach (special_static_fields, do_free_special, NULL);
3665 mono_threads_unlock ();
3669 mono_special_static_data_free_slot (guint32 offset, guint32 size)
3671 mono_threads_lock ();
3672 do_free_special_slot (offset, size);
3673 mono_threads_unlock ();
3677 * allocates room in the thread local area for storing an instance of the struct type
3678 * the allocation is kept track of in domain->tlsrec_list.
3681 mono_thread_alloc_tls (MonoReflectionType *type)
3683 MonoDomain *domain = mono_domain_get ();
3685 MonoTlsDataRecord *tlsrec;
3688 gsize default_bitmap [4] = {0};
3689 uint32_t tls_offset;
3693 klass = mono_class_from_mono_type (type->type);
3694 /* TlsDatum is a struct, so we subtract the object header size offset */
3695 bitmap = mono_class_compute_bitmap (klass, default_bitmap, sizeof (default_bitmap) * 8, - (int)(sizeof (MonoObject) / sizeof (gpointer)), &max_set, FALSE);
3696 size = mono_type_size (type->type, &align);
3697 tls_offset = mono_alloc_special_static_data (SPECIAL_STATIC_THREAD, size, align, bitmap, max_set);
3698 if (bitmap != default_bitmap)
3700 tlsrec = g_new0 (MonoTlsDataRecord, 1);
3701 tlsrec->tls_offset = tls_offset;
3702 tlsrec->size = size;
3703 mono_domain_lock (domain);
3704 tlsrec->next = domain->tlsrec_list;
3705 domain->tlsrec_list = tlsrec;
3706 mono_domain_unlock (domain);
3711 mono_thread_destroy_tls (uint32_t tls_offset)
3713 MonoTlsDataRecord *prev = NULL;
3714 MonoTlsDataRecord *cur;
3716 MonoDomain *domain = mono_domain_get ();
3717 mono_domain_lock (domain);
3718 cur = domain->tlsrec_list;
3720 if (cur->tls_offset == tls_offset) {
3722 prev->next = cur->next;
3724 domain->tlsrec_list = cur->next;
3732 mono_domain_unlock (domain);
3734 mono_special_static_data_free_slot (tls_offset, size);
3738 * This is just to ensure cleanup: the finalizers should have taken care, so this is not perf-critical.
3741 mono_thread_destroy_domain_tls (MonoDomain *domain)
3743 while (domain->tlsrec_list)
3744 mono_thread_destroy_tls (domain->tlsrec_list->tls_offset);
3747 static MonoClassField *local_slots = NULL;
3750 /* local tls data to get locals_slot from a thread */
3753 /* index in the locals_slot array */
3758 clear_local_slot (gpointer key, gpointer value, gpointer user_data)
3760 LocalSlotID *sid = user_data;
3761 MonoInternalThread *thread = (MonoInternalThread*)value;
3762 MonoArray *slots_array;
3764 * the static field is stored at: ((char*) thread->static_data [idx]) + (offset & 0xffffff);
3765 * it is for the right domain, so we need to check if it is allocated an initialized
3766 * for the current thread.
3768 /*g_print ("handling thread %p\n", thread);*/
3769 if (!thread->static_data || !thread->static_data [sid->idx])
3771 slots_array = *(MonoArray **)(((char*) thread->static_data [sid->idx]) + (sid->offset & 0xffffff));
3772 if (!slots_array || sid->slot >= mono_array_length (slots_array))
3774 mono_array_set (slots_array, MonoObject*, sid->slot, NULL);
3778 mono_thread_free_local_slot_values (int slot, MonoBoolean thread_local)
3786 local_slots = mono_class_get_field_from_name (mono_defaults.thread_class, "local_slots");
3788 g_warning ("local_slots field not found in Thread class");
3792 domain = mono_domain_get ();
3793 mono_domain_lock (domain);
3794 if (domain->special_static_fields)
3795 addr = g_hash_table_lookup (domain->special_static_fields, local_slots);
3796 mono_domain_unlock (domain);
3799 /*g_print ("freeing slot %d at %p\n", slot, addr);*/
3800 sid.offset = GPOINTER_TO_UINT (addr);
3801 sid.offset &= 0x7fffffff;
3802 sid.idx = (sid.offset >> 24) - 1;
3803 mono_threads_lock ();
3804 mono_g_hash_table_foreach (threads, clear_local_slot, &sid);
3805 mono_threads_unlock ();
3807 /* FIXME: clear the slot for MonoAppContexts, too */
3812 static void CALLBACK dummy_apc (ULONG_PTR param)
3816 static guint32 dummy_apc (gpointer param)
3823 * mono_thread_execute_interruption
3825 * Performs the operation that the requested thread state requires (abort,
3828 static MonoException* mono_thread_execute_interruption (MonoInternalThread *thread)
3830 ensure_synch_cs_set (thread);
3832 EnterCriticalSection (thread->synch_cs);
3834 /* MonoThread::interruption_requested can only be changed with atomics */
3835 if (InterlockedCompareExchange (&thread->interruption_requested, FALSE, TRUE)) {
3836 /* this will consume pending APC calls */
3837 WaitForSingleObjectEx (GetCurrentThread(), 0, TRUE);
3838 InterlockedDecrement (&thread_interruption_requested);
3840 /* Clear the interrupted flag of the thread so it can wait again */
3841 wapi_clear_interruption ();
3845 if ((thread->state & ThreadState_AbortRequested) != 0) {
3846 LeaveCriticalSection (thread->synch_cs);
3847 if (thread->abort_exc == NULL) {
3849 * This might be racy, but it has to be called outside the lock
3850 * since it calls managed code.
3852 MONO_OBJECT_SETREF (thread, abort_exc, mono_get_exception_thread_abort ());
3854 return thread->abort_exc;
3856 else if ((thread->state & ThreadState_SuspendRequested) != 0) {
3857 thread->state &= ~ThreadState_SuspendRequested;
3858 thread->state |= ThreadState_Suspended;
3859 thread->suspend_event = CreateEvent (NULL, TRUE, FALSE, NULL);
3860 if (thread->suspend_event == NULL) {
3861 LeaveCriticalSection (thread->synch_cs);
3864 if (thread->suspended_event)
3865 SetEvent (thread->suspended_event);
3867 LeaveCriticalSection (thread->synch_cs);
3869 if (shutting_down) {
3870 /* After we left the lock, the runtime might shut down so everything becomes invalid */
3875 WaitForSingleObject (thread->suspend_event, INFINITE);
3877 EnterCriticalSection (thread->synch_cs);
3879 CloseHandle (thread->suspend_event);
3880 thread->suspend_event = NULL;
3881 thread->state &= ~ThreadState_Suspended;
3883 /* The thread that requested the resume will have replaced this event
3884 * and will be waiting for it
3886 SetEvent (thread->resume_event);
3888 LeaveCriticalSection (thread->synch_cs);
3892 else if ((thread->state & ThreadState_StopRequested) != 0) {
3893 /* FIXME: do this through the JIT? */
3895 LeaveCriticalSection (thread->synch_cs);
3897 mono_thread_exit ();
3899 } else if (thread->thread_interrupt_requested) {
3901 thread->thread_interrupt_requested = FALSE;
3902 LeaveCriticalSection (thread->synch_cs);
3904 return(mono_get_exception_thread_interrupted ());
3907 LeaveCriticalSection (thread->synch_cs);
3913 * mono_thread_request_interruption
3915 * A signal handler can call this method to request the interruption of a
3916 * thread. The result of the interruption will depend on the current state of
3917 * the thread. If the result is an exception that needs to be throw, it is
3918 * provided as return value.
3921 mono_thread_request_interruption (gboolean running_managed)
3923 MonoInternalThread *thread = mono_thread_internal_current ();
3925 /* The thread may already be stopping */
3930 if (thread->interrupt_on_stop &&
3931 thread->state & ThreadState_StopRequested &&
3932 thread->state & ThreadState_Background)
3936 if (InterlockedCompareExchange (&thread->interruption_requested, 1, 0) == 1)
3939 if (!running_managed || is_running_protected_wrapper ()) {
3940 /* Can't stop while in unmanaged code. Increase the global interruption
3941 request count. When exiting the unmanaged method the count will be
3942 checked and the thread will be interrupted. */
3944 InterlockedIncrement (&thread_interruption_requested);
3946 if (mono_thread_notify_pending_exc_fn && !running_managed)
3947 /* The JIT will notify the thread about the interruption */
3948 /* This shouldn't take any locks */
3949 mono_thread_notify_pending_exc_fn ();
3951 /* this will awake the thread if it is in WaitForSingleObject
3953 /* Our implementation of this function ignores the func argument */
3954 QueueUserAPC ((PAPCFUNC)dummy_apc, thread->handle, NULL);
3958 return mono_thread_execute_interruption (thread);
3962 /*This function should be called by a thread after it has exited all of
3963 * its handle blocks at interruption time.*/
3965 mono_thread_resume_interruption (void)
3967 MonoInternalThread *thread = mono_thread_internal_current ();
3968 gboolean still_aborting;
3970 /* The thread may already be stopping */
3974 ensure_synch_cs_set (thread);
3975 EnterCriticalSection (thread->synch_cs);
3976 still_aborting = (thread->state & ThreadState_AbortRequested) != 0;
3977 LeaveCriticalSection (thread->synch_cs);
3979 /*This can happen if the protected block called Thread::ResetAbort*/
3980 if (!still_aborting)
3983 if (InterlockedCompareExchange (&thread->interruption_requested, 1, 0) == 1)
3985 InterlockedIncrement (&thread_interruption_requested);
3988 wapi_self_interrupt ();
3990 return mono_thread_execute_interruption (thread);
3993 gboolean mono_thread_interruption_requested ()
3995 if (thread_interruption_requested) {
3996 MonoInternalThread *thread = mono_thread_internal_current ();
3997 /* The thread may already be stopping */
3999 return (thread->interruption_requested);
4004 static void mono_thread_interruption_checkpoint_request (gboolean bypass_abort_protection)
4006 MonoInternalThread *thread = mono_thread_internal_current ();
4008 /* The thread may already be stopping */
4012 mono_debugger_check_interruption ();
4014 if (thread->interruption_requested && (bypass_abort_protection || !is_running_protected_wrapper ())) {
4015 MonoException* exc = mono_thread_execute_interruption (thread);
4016 if (exc) mono_raise_exception (exc);
4021 * Performs the interruption of the current thread, if one has been requested,
4022 * and the thread is not running a protected wrapper.
4024 void mono_thread_interruption_checkpoint ()
4026 mono_thread_interruption_checkpoint_request (FALSE);
4030 * Performs the interruption of the current thread, if one has been requested.
4032 void mono_thread_force_interruption_checkpoint ()
4034 mono_thread_interruption_checkpoint_request (TRUE);
4038 * mono_thread_get_and_clear_pending_exception:
4040 * Return any pending exceptions for the current thread and clear it as a side effect.
4043 mono_thread_get_and_clear_pending_exception (void)
4045 MonoInternalThread *thread = mono_thread_internal_current ();
4047 /* The thread may already be stopping */
4051 if (thread->interruption_requested && !is_running_protected_wrapper ()) {
4052 return mono_thread_execute_interruption (thread);
4055 if (thread->pending_exception) {
4056 MonoException *exc = thread->pending_exception;
4058 thread->pending_exception = NULL;
4066 * mono_set_pending_exception:
4068 * Set the pending exception of the current thread to EXC. On platforms which
4069 * support it, the exception will be thrown when execution returns to managed code.
4070 * On other platforms, this function is equivalent to mono_raise_exception ().
4071 * Internal calls which report exceptions using this function instead of
4072 * raise_exception () might be called by JITted code using a more efficient calling
4076 mono_set_pending_exception (MonoException *exc)
4078 MonoInternalThread *thread = mono_thread_internal_current ();
4080 /* The thread may already be stopping */
4084 if (mono_thread_notify_pending_exc_fn) {
4085 MONO_OBJECT_SETREF (thread, pending_exception, exc);
4087 mono_thread_notify_pending_exc_fn ();
4089 /* No way to notify the JIT about the exception, have to throw it now */
4090 mono_raise_exception (exc);
4095 * mono_thread_interruption_request_flag:
4097 * Returns the address of a flag that will be non-zero if an interruption has
4098 * been requested for a thread. The thread to interrupt may not be the current
4099 * thread, so an additional call to mono_thread_interruption_requested() or
4100 * mono_thread_interruption_checkpoint() is allways needed if the flag is not
4103 gint32* mono_thread_interruption_request_flag ()
4105 return &thread_interruption_requested;
4109 mono_thread_init_apartment_state (void)
4112 MonoInternalThread* thread = mono_thread_internal_current ();
4114 /* Positive return value indicates success, either
4115 * S_OK if this is first CoInitialize call, or
4116 * S_FALSE if CoInitialize already called, but with same
4117 * threading model. A negative value indicates failure,
4118 * probably due to trying to change the threading model.
4120 if (CoInitializeEx(NULL, (thread->apartment_state == ThreadApartmentState_STA)
4121 ? COINIT_APARTMENTTHREADED
4122 : COINIT_MULTITHREADED) < 0) {
4123 thread->apartment_state = ThreadApartmentState_Unknown;
4129 mono_thread_cleanup_apartment_state (void)
4132 MonoInternalThread* thread = mono_thread_internal_current ();
4134 if (thread && thread->apartment_state != ThreadApartmentState_Unknown) {
4141 mono_thread_set_state (MonoInternalThread *thread, MonoThreadState state)
4143 ensure_synch_cs_set (thread);
4145 EnterCriticalSection (thread->synch_cs);
4146 thread->state |= state;
4147 LeaveCriticalSection (thread->synch_cs);
4151 mono_thread_clr_state (MonoInternalThread *thread, MonoThreadState state)
4153 ensure_synch_cs_set (thread);
4155 EnterCriticalSection (thread->synch_cs);
4156 thread->state &= ~state;
4157 LeaveCriticalSection (thread->synch_cs);
4161 mono_thread_test_state (MonoInternalThread *thread, MonoThreadState test)
4163 gboolean ret = FALSE;
4165 ensure_synch_cs_set (thread);
4167 EnterCriticalSection (thread->synch_cs);
4169 if ((thread->state & test) != 0) {
4173 LeaveCriticalSection (thread->synch_cs);
4178 static MonoClassField *execution_context_field;
4181 get_execution_context_addr (void)
4183 MonoDomain *domain = mono_domain_get ();
4186 if (!execution_context_field) {
4187 execution_context_field = mono_class_get_field_from_name (mono_defaults.thread_class,
4189 g_assert (execution_context_field);
4192 g_assert (mono_class_try_get_vtable (domain, mono_defaults.appdomain_class));
4194 mono_domain_lock (domain);
4195 offset = GPOINTER_TO_UINT (g_hash_table_lookup (domain->special_static_fields, execution_context_field));
4196 mono_domain_unlock (domain);
4199 return (MonoObject**) mono_get_special_static_data (offset);
4203 mono_thread_get_execution_context (void)
4205 return *get_execution_context_addr ();
4209 mono_thread_set_execution_context (MonoObject *ec)
4211 *get_execution_context_addr () = ec;
4214 static gboolean has_tls_get = FALSE;
4217 mono_runtime_set_has_tls_get (gboolean val)
4223 mono_runtime_has_tls_get (void)
4229 mono_thread_kill (MonoInternalThread *thread, int signal)
4232 /* Win32 uses QueueUserAPC and callers of this are guarded */
4233 g_assert_not_reached ();
4235 # ifdef PTHREAD_POINTER_ID
4236 return pthread_kill ((gpointer)(gsize)(thread->tid), mono_thread_get_abort_signal ());
4238 # ifdef PLATFORM_ANDROID
4239 if (thread->android_tid != 0) {
4241 int old_errno = errno;
4243 ret = tkill ((pid_t) thread->android_tid, signal);
4252 return pthread_kill (thread->tid, mono_thread_get_abort_signal ());
4254 return pthread_kill (thread->tid, mono_thread_get_abort_signal ());