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>
46 #include <mono/metadata/gc-internal.h>
48 #ifdef PLATFORM_ANDROID
51 extern int tkill (pid_t tid, int signal);
54 /*#define THREAD_DEBUG(a) do { a; } while (0)*/
55 #define THREAD_DEBUG(a)
56 /*#define THREAD_WAIT_DEBUG(a) do { a; } while (0)*/
57 #define THREAD_WAIT_DEBUG(a)
58 /*#define LIBGC_DEBUG(a) do { a; } while (0)*/
59 #define LIBGC_DEBUG(a)
61 #define SPIN_TRYLOCK(i) (InterlockedCompareExchange (&(i), 1, 0) == 0)
62 #define SPIN_LOCK(i) do { \
63 if (SPIN_TRYLOCK (i)) \
67 #define SPIN_UNLOCK(i) i = 0
69 /* Provide this for systems with glib < 2.6 */
70 #ifndef G_GSIZE_FORMAT
71 # if GLIB_SIZEOF_LONG == 8
72 # define G_GSIZE_FORMAT "lu"
74 # define G_GSIZE_FORMAT "u"
80 guint32 (*func)(void *);
96 typedef struct _MonoThreadDomainTls MonoThreadDomainTls;
97 struct _MonoThreadDomainTls {
98 MonoThreadDomainTls *next;
106 MonoThreadDomainTls *freelist;
111 MonoHazardousFreeFunc free_func;
114 /* Number of cached culture objects in the MonoThread->cached_culture_info array
115 * (per-type): we use the first NUM entries for CultureInfo and the last for
116 * UICultureInfo. So the size of the array is really NUM_CACHED_CULTURES * 2.
118 #define NUM_CACHED_CULTURES 4
119 #define CULTURES_START_IDX 0
120 #define UICULTURES_START_IDX NUM_CACHED_CULTURES
122 /* Controls access to the 'threads' hash table */
123 #define mono_threads_lock() EnterCriticalSection (&threads_mutex)
124 #define mono_threads_unlock() LeaveCriticalSection (&threads_mutex)
125 static CRITICAL_SECTION threads_mutex;
127 /* Controls access to context static data */
128 #define mono_contexts_lock() EnterCriticalSection (&contexts_mutex)
129 #define mono_contexts_unlock() LeaveCriticalSection (&contexts_mutex)
130 static CRITICAL_SECTION contexts_mutex;
132 /* Holds current status of static data heap */
133 static StaticDataInfo thread_static_info;
134 static StaticDataInfo context_static_info;
136 /* The hash of existing threads (key is thread ID, value is
137 * MonoInternalThread*) that need joining before exit
139 static MonoGHashTable *threads=NULL;
142 * Threads which are starting up and they are not in the 'threads' hash yet.
143 * When handle_store is called for a thread, it will be removed from this hash table.
144 * Protected by mono_threads_lock ().
146 static MonoGHashTable *threads_starting_up = NULL;
148 /* Maps a MonoThread to its start argument */
149 /* Protected by mono_threads_lock () */
150 static MonoGHashTable *thread_start_args = NULL;
152 /* The TLS key that holds the MonoObject assigned to each thread */
153 static guint32 current_object_key = -1;
155 #ifdef HAVE_KW_THREAD
156 /* we need to use both the Tls* functions and __thread because
157 * the gc needs to see all the threads
159 static __thread MonoInternalThread * tls_current_object MONO_TLS_FAST;
160 #define SET_CURRENT_OBJECT(x) do { \
161 tls_current_object = x; \
162 TlsSetValue (current_object_key, x); \
164 #define GET_CURRENT_OBJECT() tls_current_object
166 #define SET_CURRENT_OBJECT(x) TlsSetValue (current_object_key, x)
167 #define GET_CURRENT_OBJECT() (MonoThread*) TlsGetValue (current_object_key)
170 /* function called at thread start */
171 static MonoThreadStartCB mono_thread_start_cb = NULL;
173 /* function called at thread attach */
174 static MonoThreadAttachCB mono_thread_attach_cb = NULL;
176 /* function called at thread cleanup */
177 static MonoThreadCleanupFunc mono_thread_cleanup_fn = NULL;
179 /* function called to notify the runtime about a pending exception on the current thread */
180 static MonoThreadNotifyPendingExcFunc mono_thread_notify_pending_exc_fn = NULL;
182 /* The default stack size for each thread */
183 static guint32 default_stacksize = 0;
184 #define default_stacksize_for_thread(thread) ((thread)->stack_size? (thread)->stack_size: default_stacksize)
186 static void thread_adjust_static_data (MonoInternalThread *thread);
187 static void mono_free_static_data (gpointer* static_data, gboolean threadlocal);
188 static void mono_init_static_data_info (StaticDataInfo *static_data);
189 static guint32 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align);
190 static gboolean mono_thread_resume (MonoInternalThread* thread);
191 static void mono_thread_start (MonoThread *thread);
192 static void signal_thread_state_change (MonoInternalThread *thread);
194 static MonoException* mono_thread_execute_interruption (MonoInternalThread *thread);
196 /* Spin lock for InterlockedXXX 64 bit functions */
197 #define mono_interlocked_lock() EnterCriticalSection (&interlocked_mutex)
198 #define mono_interlocked_unlock() LeaveCriticalSection (&interlocked_mutex)
199 static CRITICAL_SECTION interlocked_mutex;
201 /* global count of thread interruptions requested */
202 static gint32 thread_interruption_requested = 0;
204 /* Event signaled when a thread changes its background mode */
205 static HANDLE background_change_event;
207 /* The table for small ID assignment */
208 static CRITICAL_SECTION small_id_mutex;
209 static int small_id_table_size = 0;
210 static int small_id_next = 0;
211 static int highest_small_id = -1;
212 static MonoInternalThread **small_id_table = NULL;
214 /* The hazard table */
215 #if MONO_SMALL_CONFIG
216 #define HAZARD_TABLE_MAX_SIZE 256
218 #define HAZARD_TABLE_MAX_SIZE 16384 /* There cannot be more threads than this number. */
220 static volatile int hazard_table_size = 0;
221 static MonoThreadHazardPointers * volatile hazard_table = NULL;
223 /* The table where we keep pointers to blocks to be freed but that
224 have to wait because they're guarded by a hazard pointer. */
225 static CRITICAL_SECTION delayed_free_table_mutex;
226 static GArray *delayed_free_table = NULL;
228 static gboolean shutting_down = FALSE;
231 mono_thread_get_tls_key (void)
233 return current_object_key;
237 mono_thread_get_tls_offset (void)
240 MONO_THREAD_VAR_OFFSET (tls_current_object,offset);
244 /* handle_store() and handle_remove() manage the array of threads that
245 * still need to be waited for when the main thread exits.
247 * If handle_store() returns FALSE the thread must not be started
248 * because Mono is shutting down.
250 static gboolean handle_store(MonoThread *thread)
252 mono_threads_lock ();
254 THREAD_DEBUG (g_message ("%s: thread %p ID %"G_GSIZE_FORMAT, __func__, thread, (gsize)thread->tid));
256 if (threads_starting_up)
257 mono_g_hash_table_remove (threads_starting_up, thread);
260 mono_threads_unlock ();
265 MONO_GC_REGISTER_ROOT_FIXED (threads);
266 threads=mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
269 /* We don't need to duplicate thread->handle, because it is
270 * only closed when the thread object is finalized by the GC.
272 g_assert (thread->internal_thread);
273 mono_g_hash_table_insert(threads, (gpointer)(gsize)(thread->internal_thread->tid),
274 thread->internal_thread);
276 mono_threads_unlock ();
281 static gboolean handle_remove(MonoInternalThread *thread)
284 gsize tid = thread->tid;
286 THREAD_DEBUG (g_message ("%s: thread ID %"G_GSIZE_FORMAT, __func__, tid));
288 mono_threads_lock ();
291 /* We have to check whether the thread object for the
292 * tid is still the same in the table because the
293 * thread might have been destroyed and the tid reused
294 * in the meantime, in which case the tid would be in
295 * the table, but with another thread object.
297 if (mono_g_hash_table_lookup (threads, (gpointer)tid) == thread) {
298 mono_g_hash_table_remove (threads, (gpointer)tid);
307 mono_threads_unlock ();
309 /* Don't close the handle here, wait for the object finalizer
310 * to do it. Otherwise, the following race condition applies:
312 * 1) Thread exits (and handle_remove() closes the handle)
314 * 2) Some other handle is reassigned the same slot
316 * 3) Another thread tries to join the first thread, and
317 * blocks waiting for the reassigned handle to be signalled
318 * (which might never happen). This is possible, because the
319 * thread calling Join() still has a reference to the first
326 * Allocate a small thread id.
328 * FIXME: The biggest part of this function is very similar to
329 * domain_id_alloc() in domain.c and should be merged.
332 small_id_alloc (MonoInternalThread *thread)
336 EnterCriticalSection (&small_id_mutex);
338 if (!small_id_table) {
339 small_id_table_size = 2;
341 * Enabling this causes problems, because SGEN doesn't track/update the TLS slot holding
342 * the current thread.
344 //small_id_table = mono_gc_alloc_fixed (small_id_table_size * sizeof (MonoInternalThread*), mono_gc_make_root_descr_all_refs (small_id_table_size));
345 small_id_table = mono_gc_alloc_fixed (small_id_table_size * sizeof (MonoInternalThread*), NULL);
347 for (i = small_id_next; i < small_id_table_size; ++i) {
348 if (!small_id_table [i]) {
354 for (i = 0; i < small_id_next; ++i) {
355 if (!small_id_table [i]) {
362 MonoInternalThread **new_table;
363 int new_size = small_id_table_size * 2;
364 if (new_size >= (1 << 16))
365 g_assert_not_reached ();
366 id = small_id_table_size;
367 //new_table = mono_gc_alloc_fixed (new_size * sizeof (MonoInternalThread*), mono_gc_make_root_descr_all_refs (new_size));
368 new_table = mono_gc_alloc_fixed (new_size * sizeof (MonoInternalThread*), NULL);
369 memcpy (new_table, small_id_table, small_id_table_size * sizeof (void*));
370 mono_gc_free_fixed (small_id_table);
371 small_id_table = new_table;
372 small_id_table_size = new_size;
374 thread->small_id = id;
375 g_assert (small_id_table [id] == NULL);
376 small_id_table [id] = thread;
378 if (small_id_next > small_id_table_size)
381 g_assert (id < HAZARD_TABLE_MAX_SIZE);
382 if (id >= hazard_table_size) {
383 #if MONO_SMALL_CONFIG
384 hazard_table = g_malloc0 (sizeof (MonoThreadHazardPointers) * HAZARD_TABLE_MAX_SIZE);
385 hazard_table_size = HAZARD_TABLE_MAX_SIZE;
388 int pagesize = mono_pagesize ();
389 int num_pages = (hazard_table_size * sizeof (MonoThreadHazardPointers) + pagesize - 1) / pagesize;
391 if (hazard_table == NULL) {
392 hazard_table = mono_valloc (NULL,
393 sizeof (MonoThreadHazardPointers) * HAZARD_TABLE_MAX_SIZE,
397 g_assert (hazard_table != NULL);
398 page_addr = (guint8*)hazard_table + num_pages * pagesize;
400 mono_mprotect (page_addr, pagesize, MONO_MMAP_READ | MONO_MMAP_WRITE);
403 hazard_table_size = num_pages * pagesize / sizeof (MonoThreadHazardPointers);
406 g_assert (id < hazard_table_size);
407 hazard_table [id].hazard_pointers [0] = NULL;
408 hazard_table [id].hazard_pointers [1] = NULL;
411 if (id > highest_small_id) {
412 highest_small_id = id;
413 mono_memory_write_barrier ();
416 LeaveCriticalSection (&small_id_mutex);
422 small_id_free (int id)
424 g_assert (id >= 0 && id < small_id_table_size);
425 g_assert (small_id_table [id] != NULL);
427 small_id_table [id] = NULL;
431 is_pointer_hazardous (gpointer p)
434 int highest = highest_small_id;
436 g_assert (highest < hazard_table_size);
438 for (i = 0; i <= highest; ++i) {
439 if (hazard_table [i].hazard_pointers [0] == p
440 || hazard_table [i].hazard_pointers [1] == p)
447 MonoThreadHazardPointers*
448 mono_hazard_pointer_get (void)
450 MonoInternalThread *current_thread = mono_thread_internal_current ();
452 if (!(current_thread && current_thread->small_id >= 0)) {
453 static MonoThreadHazardPointers emerg_hazard_table;
454 g_warning ("Thread %p may have been prematurely finalized", current_thread);
455 return &emerg_hazard_table;
458 return &hazard_table [current_thread->small_id];
462 try_free_delayed_free_item (int index)
464 if (delayed_free_table->len > index) {
465 DelayedFreeItem item = { NULL, NULL };
467 EnterCriticalSection (&delayed_free_table_mutex);
468 /* We have to check the length again because another
469 thread might have freed an item before we acquired
471 if (delayed_free_table->len > index) {
472 item = g_array_index (delayed_free_table, DelayedFreeItem, index);
474 if (!is_pointer_hazardous (item.p))
475 g_array_remove_index_fast (delayed_free_table, index);
479 LeaveCriticalSection (&delayed_free_table_mutex);
482 item.free_func (item.p);
487 mono_thread_hazardous_free_or_queue (gpointer p, MonoHazardousFreeFunc free_func)
491 /* First try to free a few entries in the delayed free
493 for (i = 2; i >= 0; --i)
494 try_free_delayed_free_item (i);
496 /* Now see if the pointer we're freeing is hazardous. If it
497 isn't, free it. Otherwise put it in the delay list. */
498 if (is_pointer_hazardous (p)) {
499 DelayedFreeItem item = { p, free_func };
501 ++mono_stats.hazardous_pointer_count;
503 EnterCriticalSection (&delayed_free_table_mutex);
504 g_array_append_val (delayed_free_table, item);
505 LeaveCriticalSection (&delayed_free_table_mutex);
511 mono_thread_hazardous_try_free_all (void)
516 if (!delayed_free_table)
519 len = delayed_free_table->len;
521 for (i = len - 1; i >= 0; --i)
522 try_free_delayed_free_item (i);
525 static void ensure_synch_cs_set (MonoInternalThread *thread)
527 CRITICAL_SECTION *synch_cs;
529 if (thread->synch_cs != NULL) {
533 synch_cs = g_new0 (CRITICAL_SECTION, 1);
534 InitializeCriticalSection (synch_cs);
536 if (InterlockedCompareExchangePointer ((gpointer *)&thread->synch_cs,
537 synch_cs, NULL) != NULL) {
538 /* Another thread must have installed this CS */
539 DeleteCriticalSection (synch_cs);
545 * NOTE: this function can be called also for threads different from the current one:
546 * make sure no code called from it will ever assume it is run on the thread that is
547 * getting cleaned up.
549 static void thread_cleanup (MonoInternalThread *thread)
551 g_assert (thread != NULL);
553 if (thread->abort_state_handle) {
554 mono_gchandle_free (thread->abort_state_handle);
555 thread->abort_state_handle = 0;
557 thread->abort_exc = NULL;
558 thread->current_appcontext = NULL;
561 * This is necessary because otherwise we might have
562 * cross-domain references which will not get cleaned up when
563 * the target domain is unloaded.
565 if (thread->cached_culture_info) {
567 for (i = 0; i < NUM_CACHED_CULTURES * 2; ++i)
568 mono_array_set (thread->cached_culture_info, MonoObject*, i, NULL);
571 /* if the thread is not in the hash it has been removed already */
572 if (!handle_remove (thread)) {
573 /* This needs to be called even if handle_remove () fails */
574 if (mono_thread_cleanup_fn)
575 mono_thread_cleanup_fn (thread);
578 mono_release_type_locks (thread);
580 EnterCriticalSection (thread->synch_cs);
582 thread->state |= ThreadState_Stopped;
583 thread->state &= ~ThreadState_Background;
585 LeaveCriticalSection (thread->synch_cs);
587 mono_profiler_thread_end (thread->tid);
589 if (thread == mono_thread_internal_current ())
590 mono_thread_pop_appdomain_ref ();
592 thread->cached_culture_info = NULL;
594 mono_free_static_data (thread->static_data, TRUE);
595 thread->static_data = NULL;
597 if (mono_thread_cleanup_fn)
598 mono_thread_cleanup_fn (thread);
600 small_id_free (thread->small_id);
601 thread->small_id = -2;
606 get_thread_static_data (MonoInternalThread *thread, guint32 offset)
609 g_assert ((offset & 0x80000000) == 0);
610 offset &= 0x7fffffff;
611 idx = (offset >> 24) - 1;
612 return ((char*) thread->static_data [idx]) + (offset & 0xffffff);
616 get_current_thread_ptr_for_domain (MonoDomain *domain, MonoInternalThread *thread)
618 static MonoClassField *current_thread_field = NULL;
622 if (!current_thread_field) {
623 current_thread_field = mono_class_get_field_from_name (mono_defaults.thread_class, "current_thread");
624 g_assert (current_thread_field);
627 mono_class_vtable (domain, mono_defaults.thread_class);
628 mono_domain_lock (domain);
629 offset = GPOINTER_TO_UINT (g_hash_table_lookup (domain->special_static_fields, current_thread_field));
630 mono_domain_unlock (domain);
633 return get_thread_static_data (thread, offset);
637 set_current_thread_for_domain (MonoDomain *domain, MonoInternalThread *thread, MonoThread *current)
639 MonoThread **current_thread_ptr = get_current_thread_ptr_for_domain (domain, thread);
641 g_assert (current->obj.vtable->domain == domain);
643 g_assert (!*current_thread_ptr);
644 *current_thread_ptr = current;
647 static MonoInternalThread*
648 create_internal_thread_object (void)
652 * These objects are long living, and they will become pinned by the thread startup code
653 * anyway, so allocate them from oldspace.
655 MonoVTable *vt = mono_class_vtable (mono_get_root_domain (), mono_defaults.internal_thread_class);
656 return (MonoInternalThread*)mono_gc_alloc_pinned_obj (vt, vt->klass->instance_size);
658 return (MonoInternalThread*)mono_object_new (mono_get_root_domain (), mono_defaults.internal_thread_class);
663 create_thread_object (MonoDomain *domain)
666 MonoVTable *vt = mono_class_vtable (mono_get_root_domain (), mono_defaults.thread_class);
667 return (MonoThread*)mono_gc_alloc_pinned_obj (vt, vt->klass->instance_size);
669 return (MonoThread*)mono_object_new (domain, mono_defaults.thread_class);
674 new_thread_with_internal (MonoDomain *domain, MonoInternalThread *internal)
676 MonoThread *thread = create_thread_object (domain);
677 MONO_OBJECT_SETREF (thread, internal_thread, internal);
682 init_root_domain_thread (MonoInternalThread *thread, MonoThread *candidate)
684 MonoDomain *domain = mono_get_root_domain ();
686 if (!candidate || candidate->obj.vtable->domain != domain)
687 candidate = new_thread_with_internal (domain, thread);
688 set_current_thread_for_domain (domain, thread, candidate);
689 g_assert (!thread->root_domain_thread);
690 MONO_OBJECT_SETREF (thread, root_domain_thread, candidate);
693 static guint32 WINAPI start_wrapper(void *data)
695 struct StartInfo *start_info=(struct StartInfo *)data;
696 guint32 (*start_func)(void *);
699 MonoThread *thread=start_info->obj;
700 MonoInternalThread *internal = thread->internal_thread;
701 MonoObject *start_delegate = start_info->delegate;
703 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Start wrapper", __func__, GetCurrentThreadId ()));
705 /* We can be sure start_info->obj->tid and
706 * start_info->obj->handle have been set, because the thread
707 * was created suspended, and these values were set before the
713 SET_CURRENT_OBJECT (internal);
715 mono_monitor_init_tls ();
717 /* Every thread references the appdomain which created it */
718 mono_thread_push_appdomain_ref (thread->obj.vtable->domain);
720 if (!mono_domain_set (thread->obj.vtable->domain, FALSE)) {
721 /* No point in raising an appdomain_unloaded exception here */
722 /* FIXME: Cleanup here */
723 mono_thread_pop_appdomain_ref ();
727 start_func = start_info->func;
728 start_arg = start_info->start_arg;
730 /* We have to do this here because mono_thread_new_init()
731 requires that root_domain_thread is set up. */
732 thread_adjust_static_data (internal);
733 init_root_domain_thread (internal, thread);
735 /* This MUST be called before any managed code can be
736 * executed, as it calls the callback function that (for the
737 * jit) sets the lmf marker.
739 mono_thread_new_init (tid, &tid, start_func);
740 internal->stack_ptr = &tid;
742 LIBGC_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT",%d) Setting thread stack to %p", __func__, GetCurrentThreadId (), getpid (), thread->stack_ptr));
744 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Setting current_object_key to %p", __func__, GetCurrentThreadId (), thread));
746 /* On 2.0 profile (and higher), set explicitly since state might have been
748 if (internal->apartment_state == ThreadApartmentState_Unknown)
749 internal->apartment_state = ThreadApartmentState_MTA;
751 mono_thread_init_apartment_state ();
753 if(internal->start_notify!=NULL) {
754 /* Let the thread that called Start() know we're
757 ReleaseSemaphore (internal->start_notify, 1, NULL);
760 mono_threads_lock ();
761 mono_g_hash_table_remove (thread_start_args, thread);
762 mono_threads_unlock ();
766 g_message ("%s: start_wrapper for %"G_GSIZE_FORMAT, __func__,
770 mono_thread_set_execution_context (thread->ec_to_set);
771 thread->ec_to_set = NULL;
774 * Call this after calling start_notify, since the profiler callback might want
775 * to lock the thread, and the lock is held by thread_start () which waits for
778 mono_profiler_thread_start (tid);
780 /* start_func is set only for unmanaged start functions */
782 start_func (start_arg);
785 g_assert (start_delegate != NULL);
786 args [0] = start_arg;
787 /* we may want to handle the exception here. See comment below on unhandled exceptions */
788 mono_runtime_delegate_invoke (start_delegate, args, NULL);
791 /* If the thread calls ExitThread at all, this remaining code
792 * will not be executed, but the main thread will eventually
793 * call thread_cleanup() on this thread's behalf.
796 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Start wrapper terminating", __func__, GetCurrentThreadId ()));
798 thread_cleanup (internal);
800 /* Do any cleanup needed for apartment state. This
801 * cannot be done in thread_cleanup since thread_cleanup could be
802 * called for a thread other than the current thread.
803 * mono_thread_cleanup_apartment_state cleans up apartment
804 * for the current thead */
805 mono_thread_cleanup_apartment_state ();
807 /* Remove the reference to the thread object in the TLS data,
808 * so the thread object can be finalized. This won't be
809 * reached if the thread threw an uncaught exception, so those
810 * thread handles will stay referenced :-( (This is due to
811 * missing support for scanning thread-specific data in the
812 * Boehm GC - the io-layer keeps a GC-visible hash of pointers
815 SET_CURRENT_OBJECT (NULL);
816 mono_domain_unset ();
821 void mono_thread_new_init (intptr_t tid, gpointer stack_start, gpointer func)
823 if (mono_thread_start_cb) {
824 mono_thread_start_cb (tid, stack_start, func);
828 void mono_threads_set_default_stacksize (guint32 stacksize)
830 default_stacksize = stacksize;
833 guint32 mono_threads_get_default_stacksize (void)
835 return default_stacksize;
839 * mono_create_thread:
841 * This is a wrapper around CreateThread which handles differences in the type of
842 * the the 'tid' argument.
844 gpointer mono_create_thread (WapiSecurityAttributes *security,
845 guint32 stacksize, WapiThreadStart start,
846 gpointer param, guint32 create, gsize *tid)
853 res = CreateThread (security, stacksize, start, param, create, &real_tid);
857 res = CreateThread (security, stacksize, start, param, create, tid);
864 * The thread start argument may be an object reference, and there is
865 * no ref to keep it alive when the new thread is started but not yet
866 * registered with the collector. So we store it in a GC tracked hash
869 * LOCKING: Assumes the threads lock is held.
872 register_thread_start_argument (MonoThread *thread, struct StartInfo *start_info)
874 if (thread_start_args == NULL) {
875 MONO_GC_REGISTER_ROOT_FIXED (thread_start_args);
876 thread_start_args = mono_g_hash_table_new (NULL, NULL);
878 mono_g_hash_table_insert (thread_start_args, thread, start_info->start_arg);
881 MonoInternalThread* mono_thread_create_internal (MonoDomain *domain, gpointer func, gpointer arg, gboolean threadpool_thread)
884 MonoInternalThread *internal;
885 HANDLE thread_handle;
886 struct StartInfo *start_info;
889 thread = create_thread_object (domain);
890 internal = create_internal_thread_object ();
891 MONO_OBJECT_SETREF (thread, internal_thread, internal);
893 start_info=g_new0 (struct StartInfo, 1);
894 start_info->func = func;
895 start_info->obj = thread;
896 start_info->start_arg = arg;
898 mono_threads_lock ();
900 mono_threads_unlock ();
904 if (threads_starting_up == NULL) {
905 MONO_GC_REGISTER_ROOT_FIXED (threads_starting_up);
906 threads_starting_up = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_VALUE_GC);
909 register_thread_start_argument (thread, start_info);
910 mono_g_hash_table_insert (threads_starting_up, thread, thread);
911 mono_threads_unlock ();
913 /* Create suspended, so we can do some housekeeping before the thread
916 thread_handle = mono_create_thread (NULL, default_stacksize_for_thread (internal), (LPTHREAD_START_ROUTINE)start_wrapper, start_info,
917 CREATE_SUSPENDED, &tid);
918 THREAD_DEBUG (g_message ("%s: Started thread ID %"G_GSIZE_FORMAT" (handle %p)", __func__, tid, thread_handle));
919 if (thread_handle == NULL) {
920 /* The thread couldn't be created, so throw an exception */
921 mono_threads_lock ();
922 mono_g_hash_table_remove (threads_starting_up, thread);
923 mono_threads_unlock ();
925 mono_raise_exception (mono_get_exception_execution_engine ("Couldn't create thread"));
929 internal->handle=thread_handle;
931 internal->apartment_state=ThreadApartmentState_Unknown;
932 small_id_alloc (internal);
934 internal->synch_cs = g_new0 (CRITICAL_SECTION, 1);
935 InitializeCriticalSection (internal->synch_cs);
937 internal->threadpool_thread = threadpool_thread;
938 if (threadpool_thread)
939 mono_thread_set_state (internal, ThreadState_Background);
941 if (handle_store (thread))
942 ResumeThread (thread_handle);
948 mono_thread_create (MonoDomain *domain, gpointer func, gpointer arg)
950 mono_thread_create_internal (domain, func, arg, FALSE);
954 * mono_thread_get_stack_bounds:
956 * Return the address and size of the current threads stack. Return NULL as the
957 * stack address if the stack address cannot be determined.
960 mono_thread_get_stack_bounds (guint8 **staddr, size_t *stsize)
962 #if defined(HAVE_PTHREAD_GET_STACKSIZE_NP) && defined(HAVE_PTHREAD_GET_STACKADDR_NP)
963 *staddr = (guint8*)pthread_get_stackaddr_np (pthread_self ());
964 *stsize = pthread_get_stacksize_np (pthread_self ());
965 *staddr = (guint8*)((gssize)*staddr & ~(mono_pagesize () - 1));
967 /* FIXME: simplify the mess below */
968 #elif !defined(HOST_WIN32)
970 guint8 *current = (guint8*)&attr;
972 pthread_attr_init (&attr);
973 # ifdef HAVE_PTHREAD_GETATTR_NP
974 pthread_getattr_np (pthread_self(), &attr);
976 # ifdef HAVE_PTHREAD_ATTR_GET_NP
977 pthread_attr_get_np (pthread_self(), &attr);
980 pthread_attr_getstacksize (&attr, &stsize);
981 # elif defined(__OpenBSD__)
985 rslt = pthread_stackseg_np(pthread_self(), &ss);
986 g_assert (rslt == 0);
988 *staddr = (guint8*)((size_t)ss.ss_sp - ss.ss_size);
989 *stsize = ss.ss_size;
998 # if !defined(__OpenBSD__)
999 pthread_attr_getstack (&attr, (void**)staddr, stsize);
1002 g_assert ((current > *staddr) && (current < *staddr + *stsize));
1005 pthread_attr_destroy (&attr);
1008 *stsize = (size_t)-1;
1011 /* When running under emacs, sometimes staddr is not aligned to a page size */
1012 *staddr = (guint8*)((gssize)*staddr & ~(mono_pagesize () - 1));
1016 mono_thread_attach (MonoDomain *domain)
1018 MonoInternalThread *thread;
1019 MonoThread *current_thread;
1020 HANDLE thread_handle;
1023 if ((thread = mono_thread_internal_current ())) {
1024 if (domain != mono_domain_get ())
1025 mono_domain_set (domain, TRUE);
1026 /* Already attached */
1027 return mono_thread_current ();
1030 if (!mono_gc_register_thread (&domain)) {
1031 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 ());
1034 thread = create_internal_thread_object ();
1036 thread_handle = GetCurrentThread ();
1037 g_assert (thread_handle);
1039 tid=GetCurrentThreadId ();
1042 * The handle returned by GetCurrentThread () is a pseudo handle, so it can't be used to
1043 * refer to the thread from other threads for things like aborting.
1045 DuplicateHandle (GetCurrentProcess (), thread_handle, GetCurrentProcess (), &thread_handle,
1046 THREAD_ALL_ACCESS, TRUE, 0);
1048 thread->handle=thread_handle;
1050 #ifdef PLATFORM_ANDROID
1051 thread->android_tid = (gpointer) gettid ();
1053 thread->apartment_state=ThreadApartmentState_Unknown;
1054 small_id_alloc (thread);
1055 thread->stack_ptr = &tid;
1057 thread->synch_cs = g_new0 (CRITICAL_SECTION, 1);
1058 InitializeCriticalSection (thread->synch_cs);
1060 THREAD_DEBUG (g_message ("%s: Attached thread ID %"G_GSIZE_FORMAT" (handle %p)", __func__, tid, thread_handle));
1062 current_thread = new_thread_with_internal (domain, thread);
1064 if (!handle_store (current_thread)) {
1065 /* Mono is shutting down, so just wait for the end */
1070 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Setting current_object_key to %p", __func__, GetCurrentThreadId (), thread));
1072 SET_CURRENT_OBJECT (thread);
1073 mono_domain_set (domain, TRUE);
1075 mono_monitor_init_tls ();
1077 thread_adjust_static_data (thread);
1079 init_root_domain_thread (thread, current_thread);
1080 if (domain != mono_get_root_domain ())
1081 set_current_thread_for_domain (domain, thread, current_thread);
1084 if (mono_thread_attach_cb) {
1088 mono_thread_get_stack_bounds (&staddr, &stsize);
1091 mono_thread_attach_cb (tid, &tid);
1093 mono_thread_attach_cb (tid, staddr + stsize);
1096 // FIXME: Need a separate callback
1097 mono_profiler_thread_start (tid);
1099 return current_thread;
1103 mono_thread_detach (MonoThread *thread)
1105 g_return_if_fail (thread != NULL);
1107 THREAD_DEBUG (g_message ("%s: mono_thread_detach for %p (%"G_GSIZE_FORMAT")", __func__, thread, (gsize)thread->tid));
1109 thread_cleanup (thread->internal_thread);
1111 SET_CURRENT_OBJECT (NULL);
1112 mono_domain_unset ();
1114 /* Don't need to CloseHandle this thread, even though we took a
1115 * reference in mono_thread_attach (), because the GC will do it
1116 * when the Thread object is finalised.
1123 MonoInternalThread *thread = mono_thread_internal_current ();
1125 THREAD_DEBUG (g_message ("%s: mono_thread_exit for %p (%"G_GSIZE_FORMAT")", __func__, thread, (gsize)thread->tid));
1127 thread_cleanup (thread);
1128 SET_CURRENT_OBJECT (NULL);
1129 mono_domain_unset ();
1131 /* we could add a callback here for embedders to use. */
1132 if (mono_thread_get_main () && (thread == mono_thread_get_main ()->internal_thread))
1133 exit (mono_environment_exitcode_get ());
1138 ves_icall_System_Threading_Thread_ConstructInternalThread (MonoThread *this)
1140 MonoInternalThread *internal = create_internal_thread_object ();
1142 internal->state = ThreadState_Unstarted;
1143 internal->apartment_state = ThreadApartmentState_Unknown;
1145 InterlockedCompareExchangePointer ((gpointer)&this->internal_thread, internal, NULL);
1148 HANDLE ves_icall_System_Threading_Thread_Thread_internal(MonoThread *this,
1151 guint32 (*start_func)(void *);
1152 struct StartInfo *start_info;
1155 MonoInternalThread *internal;
1157 THREAD_DEBUG (g_message("%s: Trying to start a new thread: this (%p) start (%p)", __func__, this, start));
1159 if (!this->internal_thread)
1160 ves_icall_System_Threading_Thread_ConstructInternalThread (this);
1161 internal = this->internal_thread;
1163 ensure_synch_cs_set (internal);
1165 EnterCriticalSection (internal->synch_cs);
1167 if ((internal->state & ThreadState_Unstarted) == 0) {
1168 LeaveCriticalSection (internal->synch_cs);
1169 mono_raise_exception (mono_get_exception_thread_state ("Thread has already been started."));
1173 internal->small_id = -1;
1175 if ((internal->state & ThreadState_Aborted) != 0) {
1176 LeaveCriticalSection (internal->synch_cs);
1181 /* This is freed in start_wrapper */
1182 start_info = g_new0 (struct StartInfo, 1);
1183 start_info->func = start_func;
1184 start_info->start_arg = this->start_obj; /* FIXME: GC object stored in unmanaged memory */
1185 start_info->delegate = start;
1186 start_info->obj = this;
1187 g_assert (this->obj.vtable->domain == mono_domain_get ());
1189 internal->start_notify=CreateSemaphore (NULL, 0, 0x7fffffff, NULL);
1190 if (internal->start_notify==NULL) {
1191 LeaveCriticalSection (internal->synch_cs);
1192 g_warning ("%s: CreateSemaphore error 0x%x", __func__, GetLastError ());
1193 g_free (start_info);
1197 mono_threads_lock ();
1198 register_thread_start_argument (this, start_info);
1199 if (threads_starting_up == NULL) {
1200 MONO_GC_REGISTER_ROOT_FIXED (threads_starting_up);
1201 threads_starting_up = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_VALUE_GC);
1203 mono_g_hash_table_insert (threads_starting_up, this, this);
1204 mono_threads_unlock ();
1206 thread=mono_create_thread(NULL, default_stacksize_for_thread (internal), (LPTHREAD_START_ROUTINE)start_wrapper, start_info,
1207 CREATE_SUSPENDED, &tid);
1209 LeaveCriticalSection (internal->synch_cs);
1210 mono_threads_lock ();
1211 mono_g_hash_table_remove (threads_starting_up, this);
1212 mono_threads_unlock ();
1213 g_warning("%s: CreateThread error 0x%x", __func__, GetLastError());
1217 internal->handle=thread;
1219 small_id_alloc (internal);
1221 /* Don't call handle_store() here, delay it to Start.
1222 * We can't join a thread (trying to will just block
1223 * forever) until it actually starts running, so don't
1224 * store the handle till then.
1227 mono_thread_start (this);
1229 internal->state &= ~ThreadState_Unstarted;
1231 THREAD_DEBUG (g_message ("%s: Started thread ID %"G_GSIZE_FORMAT" (handle %p)", __func__, tid, thread));
1233 LeaveCriticalSection (internal->synch_cs);
1238 void ves_icall_System_Threading_InternalThread_Thread_free_internal (MonoInternalThread *this, HANDLE thread)
1240 MONO_ARCH_SAVE_REGS;
1242 THREAD_DEBUG (g_message ("%s: Closing thread %p, handle %p", __func__, this, thread));
1245 CloseHandle (thread);
1247 if (this->synch_cs) {
1248 DeleteCriticalSection (this->synch_cs);
1249 g_free (this->synch_cs);
1250 this->synch_cs = NULL;
1253 g_free (this->name);
1256 static void mono_thread_start (MonoThread *thread)
1258 MonoInternalThread *internal = thread->internal_thread;
1260 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Launching thread %p (%"G_GSIZE_FORMAT")", __func__, GetCurrentThreadId (), thread, (gsize)thread->tid));
1262 /* Only store the handle when the thread is about to be
1263 * launched, to avoid the main thread deadlocking while trying
1264 * to clean up a thread that will never be signalled.
1266 if (!handle_store (thread))
1269 ResumeThread (internal->handle);
1271 if(internal->start_notify!=NULL) {
1272 /* Wait for the thread to set up its TLS data etc, so
1273 * theres no potential race condition if someone tries
1274 * to look up the data believing the thread has
1278 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") waiting for thread %p (%"G_GSIZE_FORMAT") to start", __func__, GetCurrentThreadId (), thread, (gsize)thread->tid));
1280 WaitForSingleObjectEx (internal->start_notify, INFINITE, FALSE);
1281 CloseHandle (internal->start_notify);
1282 internal->start_notify = NULL;
1285 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Done launching thread %p (%"G_GSIZE_FORMAT")", __func__, GetCurrentThreadId (), thread, (gsize)thread->tid));
1288 void ves_icall_System_Threading_Thread_Sleep_internal(gint32 ms)
1291 MonoInternalThread *thread = mono_thread_internal_current ();
1293 THREAD_DEBUG (g_message ("%s: Sleeping for %d ms", __func__, ms));
1295 mono_thread_current_check_pending_interrupt ();
1297 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1299 res = SleepEx(ms,TRUE);
1301 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1303 if (res == WAIT_IO_COMPLETION) { /* we might have been interrupted */
1304 MonoException* exc = mono_thread_execute_interruption (thread);
1305 if (exc) mono_raise_exception (exc);
1309 void ves_icall_System_Threading_Thread_SpinWait_nop (void)
1314 ves_icall_System_Threading_Thread_GetDomainID (void)
1316 MONO_ARCH_SAVE_REGS;
1318 return mono_domain_get()->domain_id;
1322 ves_icall_System_Threading_Thread_Yield (void)
1325 return SwitchToThread ();
1327 return sched_yield () == 0;
1332 * mono_thread_get_name:
1334 * Return the name of the thread. NAME_LEN is set to the length of the name.
1335 * Return NULL if the thread has no name. The returned memory is owned by the
1339 mono_thread_get_name (MonoInternalThread *this_obj, guint32 *name_len)
1343 ensure_synch_cs_set (this_obj);
1345 EnterCriticalSection (this_obj->synch_cs);
1347 if (!this_obj->name) {
1351 *name_len = this_obj->name_len;
1352 res = g_new (gunichar2, this_obj->name_len);
1353 memcpy (res, this_obj->name, sizeof (gunichar2) * this_obj->name_len);
1356 LeaveCriticalSection (this_obj->synch_cs);
1362 ves_icall_System_Threading_Thread_GetName_internal (MonoInternalThread *this_obj)
1366 ensure_synch_cs_set (this_obj);
1368 EnterCriticalSection (this_obj->synch_cs);
1370 if (!this_obj->name)
1373 str = mono_string_new_utf16 (mono_domain_get (), this_obj->name, this_obj->name_len);
1375 LeaveCriticalSection (this_obj->synch_cs);
1381 ves_icall_System_Threading_Thread_SetName_internal (MonoInternalThread *this_obj, MonoString *name)
1383 ensure_synch_cs_set (this_obj);
1385 EnterCriticalSection (this_obj->synch_cs);
1387 if (this_obj->name) {
1388 LeaveCriticalSection (this_obj->synch_cs);
1390 mono_raise_exception (mono_get_exception_invalid_operation ("Thread.Name can only be set once."));
1394 this_obj->name = g_new (gunichar2, mono_string_length (name));
1395 memcpy (this_obj->name, mono_string_chars (name), mono_string_length (name) * 2);
1396 this_obj->name_len = mono_string_length (name);
1399 this_obj->name = NULL;
1401 LeaveCriticalSection (this_obj->synch_cs);
1402 if (this_obj->name) {
1403 char *tname = mono_string_to_utf8 (name);
1404 mono_profiler_thread_name (this_obj->tid, tname);
1410 lookup_cached_culture (MonoInternalThread *this, MonoDomain *domain, int start_idx)
1415 if (this->cached_culture_info) {
1416 domain = mono_domain_get ();
1417 for (i = start_idx; i < start_idx + NUM_CACHED_CULTURES; ++i) {
1418 res = mono_array_get (this->cached_culture_info, MonoObject*, i);
1419 if (res && res->vtable->domain == domain)
1427 /* If the array is already in the requested domain, we just return it,
1428 otherwise we return a copy in that domain. */
1430 byte_array_to_domain (MonoArray *arr, MonoDomain *domain)
1437 if (mono_object_domain (arr) == domain)
1440 copy = mono_array_new (domain, mono_defaults.byte_class, arr->max_length);
1441 memcpy (mono_array_addr (copy, guint8, 0), mono_array_addr (arr, guint8, 0), arr->max_length);
1446 ves_icall_System_Threading_Thread_ByteArrayToRootDomain (MonoArray *arr)
1448 return byte_array_to_domain (arr, mono_get_root_domain ());
1452 ves_icall_System_Threading_Thread_ByteArrayToCurrentDomain (MonoArray *arr)
1454 return byte_array_to_domain (arr, mono_domain_get ());
1458 ves_icall_System_Threading_Thread_GetCachedCurrentCulture (MonoInternalThread *this)
1460 return lookup_cached_culture (this, mono_domain_get (), CULTURES_START_IDX);
1464 cache_culture (MonoInternalThread *this, MonoObject *culture, int start_idx)
1467 MonoDomain *domain = mono_domain_get ();
1470 int same_domain_slot = -1;
1472 ensure_synch_cs_set (this);
1474 EnterCriticalSection (this->synch_cs);
1476 if (!this->cached_culture_info)
1477 MONO_OBJECT_SETREF (this, cached_culture_info, mono_array_new_cached (mono_get_root_domain (), mono_defaults.object_class, NUM_CACHED_CULTURES * 2));
1479 for (i = start_idx; i < start_idx + NUM_CACHED_CULTURES; ++i) {
1480 obj = mono_array_get (this->cached_culture_info, MonoObject*, i);
1484 /* we continue, because there may be a slot used with the same domain */
1488 if (obj->vtable->domain == domain) {
1489 same_domain_slot = i;
1493 if (same_domain_slot >= 0)
1494 mono_array_setref (this->cached_culture_info, same_domain_slot, culture);
1495 else if (free_slot >= 0)
1496 mono_array_setref (this->cached_culture_info, free_slot, culture);
1497 /* we may want to replace an existing entry here, even when no suitable slot is found */
1499 LeaveCriticalSection (this->synch_cs);
1503 ves_icall_System_Threading_Thread_SetCachedCurrentCulture (MonoThread *this, MonoObject *culture)
1505 MonoDomain *domain = mono_object_get_domain (&this->obj);
1506 g_assert (domain == mono_domain_get ());
1507 cache_culture (this->internal_thread, culture, CULTURES_START_IDX);
1511 ves_icall_System_Threading_Thread_GetCachedCurrentUICulture (MonoInternalThread *this)
1513 return lookup_cached_culture (this, mono_domain_get (), UICULTURES_START_IDX);
1517 ves_icall_System_Threading_Thread_SetCachedCurrentUICulture (MonoThread *this, MonoObject *culture)
1519 MonoDomain *domain = mono_object_get_domain (&this->obj);
1520 g_assert (domain == mono_domain_get ());
1521 cache_culture (this->internal_thread, culture, UICULTURES_START_IDX);
1525 mono_thread_current (void)
1527 MonoDomain *domain = mono_domain_get ();
1528 MonoInternalThread *internal = mono_thread_internal_current ();
1529 MonoThread **current_thread_ptr;
1531 g_assert (internal);
1532 current_thread_ptr = get_current_thread_ptr_for_domain (domain, internal);
1534 if (!*current_thread_ptr) {
1535 g_assert (domain != mono_get_root_domain ());
1536 *current_thread_ptr = new_thread_with_internal (domain, internal);
1538 return *current_thread_ptr;
1542 mono_thread_internal_current (void)
1544 MonoInternalThread *res = GET_CURRENT_OBJECT ();
1545 THREAD_DEBUG (g_message ("%s: returning %p", __func__, res));
1549 gboolean ves_icall_System_Threading_Thread_Join_internal(MonoInternalThread *this,
1550 int ms, HANDLE thread)
1552 MonoInternalThread *cur_thread = mono_thread_internal_current ();
1555 mono_thread_current_check_pending_interrupt ();
1557 ensure_synch_cs_set (this);
1559 EnterCriticalSection (this->synch_cs);
1561 if ((this->state & ThreadState_Unstarted) != 0) {
1562 LeaveCriticalSection (this->synch_cs);
1564 mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started."));
1568 LeaveCriticalSection (this->synch_cs);
1573 THREAD_DEBUG (g_message ("%s: joining thread handle %p, %d ms", __func__, thread, ms));
1575 mono_thread_set_state (cur_thread, ThreadState_WaitSleepJoin);
1577 ret=WaitForSingleObjectEx (thread, ms, TRUE);
1579 mono_thread_clr_state (cur_thread, ThreadState_WaitSleepJoin);
1581 if(ret==WAIT_OBJECT_0) {
1582 THREAD_DEBUG (g_message ("%s: join successful", __func__));
1587 THREAD_DEBUG (g_message ("%s: join failed", __func__));
1592 /* FIXME: exitContext isnt documented */
1593 gboolean ves_icall_System_Threading_WaitHandle_WaitAll_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext)
1599 MonoObject *waitHandle;
1600 MonoInternalThread *thread = mono_thread_internal_current ();
1602 /* Do this WaitSleepJoin check before creating objects */
1603 mono_thread_current_check_pending_interrupt ();
1605 numhandles = mono_array_length(mono_handles);
1606 handles = g_new0(HANDLE, numhandles);
1608 for(i = 0; i < numhandles; i++) {
1609 waitHandle = mono_array_get(mono_handles, MonoObject*, i);
1610 handles [i] = mono_wait_handle_get_handle ((MonoWaitHandle *) waitHandle);
1617 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1619 ret=WaitForMultipleObjectsEx(numhandles, handles, TRUE, ms, TRUE);
1621 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1625 if(ret==WAIT_FAILED) {
1626 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait failed", __func__, GetCurrentThreadId ()));
1628 } else if(ret==WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION) {
1629 /* Do we want to try again if we get
1630 * WAIT_IO_COMPLETION? The documentation for
1631 * WaitHandle doesn't give any clues. (We'd have to
1632 * fiddle with the timeout if we retry.)
1634 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait timed out", __func__, GetCurrentThreadId ()));
1641 /* FIXME: exitContext isnt documented */
1642 gint32 ves_icall_System_Threading_WaitHandle_WaitAny_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext)
1648 MonoObject *waitHandle;
1649 MonoInternalThread *thread = mono_thread_internal_current ();
1652 /* Do this WaitSleepJoin check before creating objects */
1653 mono_thread_current_check_pending_interrupt ();
1655 numhandles = mono_array_length(mono_handles);
1656 handles = g_new0(HANDLE, numhandles);
1658 for(i = 0; i < numhandles; i++) {
1659 waitHandle = mono_array_get(mono_handles, MonoObject*, i);
1660 handles [i] = mono_wait_handle_get_handle ((MonoWaitHandle *) waitHandle);
1667 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1669 start = (ms == -1) ? 0 : mono_msec_ticks ();
1671 ret = WaitForMultipleObjectsEx (numhandles, handles, FALSE, ms, TRUE);
1672 if (ret != WAIT_IO_COMPLETION)
1677 diff = mono_msec_ticks () - start;
1682 } while (ms == -1 || ms > 0);
1684 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1688 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") returning %d", __func__, GetCurrentThreadId (), ret));
1691 * These need to be here. See MSDN dos on WaitForMultipleObjects.
1693 if (ret >= WAIT_OBJECT_0 && ret <= WAIT_OBJECT_0 + numhandles - 1) {
1694 return ret - WAIT_OBJECT_0;
1696 else if (ret >= WAIT_ABANDONED_0 && ret <= WAIT_ABANDONED_0 + numhandles - 1) {
1697 return ret - WAIT_ABANDONED_0;
1704 /* FIXME: exitContext isnt documented */
1705 gboolean ves_icall_System_Threading_WaitHandle_WaitOne_internal(MonoObject *this, HANDLE handle, gint32 ms, gboolean exitContext)
1708 MonoInternalThread *thread = mono_thread_internal_current ();
1710 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") waiting for %p, %d ms", __func__, GetCurrentThreadId (), handle, ms));
1716 mono_thread_current_check_pending_interrupt ();
1718 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1720 ret=WaitForSingleObjectEx (handle, ms, TRUE);
1722 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1724 if(ret==WAIT_FAILED) {
1725 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait failed", __func__, GetCurrentThreadId ()));
1727 } else if(ret==WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION) {
1728 /* Do we want to try again if we get
1729 * WAIT_IO_COMPLETION? The documentation for
1730 * WaitHandle doesn't give any clues. (We'd have to
1731 * fiddle with the timeout if we retry.)
1733 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait timed out", __func__, GetCurrentThreadId ()));
1741 ves_icall_System_Threading_WaitHandle_SignalAndWait_Internal (HANDLE toSignal, HANDLE toWait, gint32 ms, gboolean exitContext)
1744 MonoInternalThread *thread = mono_thread_internal_current ();
1746 MONO_ARCH_SAVE_REGS;
1751 mono_thread_current_check_pending_interrupt ();
1753 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1755 ret = SignalObjectAndWait (toSignal, toWait, ms, TRUE);
1757 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1759 return (!(ret == WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION || ret == WAIT_FAILED));
1762 HANDLE ves_icall_System_Threading_Mutex_CreateMutex_internal (MonoBoolean owned, MonoString *name, MonoBoolean *created)
1766 MONO_ARCH_SAVE_REGS;
1771 mutex = CreateMutex (NULL, owned, NULL);
1773 mutex = CreateMutex (NULL, owned, mono_string_chars (name));
1775 if (GetLastError () == ERROR_ALREADY_EXISTS) {
1783 MonoBoolean ves_icall_System_Threading_Mutex_ReleaseMutex_internal (HANDLE handle ) {
1784 MONO_ARCH_SAVE_REGS;
1786 return(ReleaseMutex (handle));
1789 HANDLE ves_icall_System_Threading_Mutex_OpenMutex_internal (MonoString *name,
1795 MONO_ARCH_SAVE_REGS;
1797 *error = ERROR_SUCCESS;
1799 ret = OpenMutex (rights, FALSE, mono_string_chars (name));
1801 *error = GetLastError ();
1808 HANDLE ves_icall_System_Threading_Semaphore_CreateSemaphore_internal (gint32 initialCount, gint32 maximumCount, MonoString *name, MonoBoolean *created)
1812 MONO_ARCH_SAVE_REGS;
1817 sem = CreateSemaphore (NULL, initialCount, maximumCount, NULL);
1819 sem = CreateSemaphore (NULL, initialCount, maximumCount,
1820 mono_string_chars (name));
1822 if (GetLastError () == ERROR_ALREADY_EXISTS) {
1830 gint32 ves_icall_System_Threading_Semaphore_ReleaseSemaphore_internal (HANDLE handle, gint32 releaseCount, MonoBoolean *fail)
1834 MONO_ARCH_SAVE_REGS;
1836 *fail = !ReleaseSemaphore (handle, releaseCount, &prevcount);
1841 HANDLE ves_icall_System_Threading_Semaphore_OpenSemaphore_internal (MonoString *name, gint32 rights, gint32 *error)
1845 MONO_ARCH_SAVE_REGS;
1847 *error = ERROR_SUCCESS;
1849 ret = OpenSemaphore (rights, FALSE, mono_string_chars (name));
1851 *error = GetLastError ();
1857 HANDLE ves_icall_System_Threading_Events_CreateEvent_internal (MonoBoolean manual, MonoBoolean initial, MonoString *name, MonoBoolean *created)
1861 MONO_ARCH_SAVE_REGS;
1866 event = CreateEvent (NULL, manual, initial, NULL);
1868 event = CreateEvent (NULL, manual, initial,
1869 mono_string_chars (name));
1871 if (GetLastError () == ERROR_ALREADY_EXISTS) {
1879 gboolean ves_icall_System_Threading_Events_SetEvent_internal (HANDLE handle) {
1880 MONO_ARCH_SAVE_REGS;
1882 return (SetEvent(handle));
1885 gboolean ves_icall_System_Threading_Events_ResetEvent_internal (HANDLE handle) {
1886 MONO_ARCH_SAVE_REGS;
1888 return (ResetEvent(handle));
1892 ves_icall_System_Threading_Events_CloseEvent_internal (HANDLE handle) {
1893 MONO_ARCH_SAVE_REGS;
1895 CloseHandle (handle);
1898 HANDLE ves_icall_System_Threading_Events_OpenEvent_internal (MonoString *name,
1904 MONO_ARCH_SAVE_REGS;
1906 *error = ERROR_SUCCESS;
1908 ret = OpenEvent (rights, FALSE, mono_string_chars (name));
1910 *error = GetLastError ();
1916 gint32 ves_icall_System_Threading_Interlocked_Increment_Int (gint32 *location)
1918 MONO_ARCH_SAVE_REGS;
1920 return InterlockedIncrement (location);
1923 gint64 ves_icall_System_Threading_Interlocked_Increment_Long (gint64 *location)
1927 MONO_ARCH_SAVE_REGS;
1929 mono_interlocked_lock ();
1933 mono_interlocked_unlock ();
1939 gint32 ves_icall_System_Threading_Interlocked_Decrement_Int (gint32 *location)
1941 MONO_ARCH_SAVE_REGS;
1943 return InterlockedDecrement(location);
1946 gint64 ves_icall_System_Threading_Interlocked_Decrement_Long (gint64 * location)
1950 MONO_ARCH_SAVE_REGS;
1952 mono_interlocked_lock ();
1956 mono_interlocked_unlock ();
1961 gint32 ves_icall_System_Threading_Interlocked_Exchange_Int (gint32 *location, gint32 value)
1963 MONO_ARCH_SAVE_REGS;
1965 return InterlockedExchange(location, value);
1968 MonoObject * ves_icall_System_Threading_Interlocked_Exchange_Object (MonoObject **location, MonoObject *value)
1971 res = (MonoObject *) InterlockedExchangePointer((gpointer *) location, value);
1972 mono_gc_wbarrier_generic_nostore (location);
1976 gpointer ves_icall_System_Threading_Interlocked_Exchange_IntPtr (gpointer *location, gpointer value)
1978 return InterlockedExchangePointer(location, value);
1981 gfloat ves_icall_System_Threading_Interlocked_Exchange_Single (gfloat *location, gfloat value)
1983 IntFloatUnion val, ret;
1985 MONO_ARCH_SAVE_REGS;
1988 ret.ival = InterlockedExchange((gint32 *) location, val.ival);
1994 ves_icall_System_Threading_Interlocked_Exchange_Long (gint64 *location, gint64 value)
1996 #if SIZEOF_VOID_P == 8
1997 return (gint64) InterlockedExchangePointer((gpointer *) location, (gpointer)value);
2002 * According to MSDN, this function is only atomic with regards to the
2003 * other Interlocked functions on 32 bit platforms.
2005 mono_interlocked_lock ();
2008 mono_interlocked_unlock ();
2015 ves_icall_System_Threading_Interlocked_Exchange_Double (gdouble *location, gdouble value)
2017 #if SIZEOF_VOID_P == 8
2018 LongDoubleUnion val, ret;
2021 ret.ival = (gint64)InterlockedExchangePointer((gpointer *) location, (gpointer)val.ival);
2028 * According to MSDN, this function is only atomic with regards to the
2029 * other Interlocked functions on 32 bit platforms.
2031 mono_interlocked_lock ();
2034 mono_interlocked_unlock ();
2040 gint32 ves_icall_System_Threading_Interlocked_CompareExchange_Int(gint32 *location, gint32 value, gint32 comparand)
2042 MONO_ARCH_SAVE_REGS;
2044 return InterlockedCompareExchange(location, value, comparand);
2047 MonoObject * ves_icall_System_Threading_Interlocked_CompareExchange_Object (MonoObject **location, MonoObject *value, MonoObject *comparand)
2050 res = (MonoObject *) InterlockedCompareExchangePointer((gpointer *) location, value, comparand);
2051 mono_gc_wbarrier_generic_nostore (location);
2055 gpointer ves_icall_System_Threading_Interlocked_CompareExchange_IntPtr(gpointer *location, gpointer value, gpointer comparand)
2057 return InterlockedCompareExchangePointer(location, value, comparand);
2060 gfloat ves_icall_System_Threading_Interlocked_CompareExchange_Single (gfloat *location, gfloat value, gfloat comparand)
2062 IntFloatUnion val, ret, cmp;
2064 MONO_ARCH_SAVE_REGS;
2067 cmp.fval = comparand;
2068 ret.ival = InterlockedCompareExchange((gint32 *) location, val.ival, cmp.ival);
2074 ves_icall_System_Threading_Interlocked_CompareExchange_Double (gdouble *location, gdouble value, gdouble comparand)
2076 #if SIZEOF_VOID_P == 8
2077 LongDoubleUnion val, comp, ret;
2080 comp.fval = comparand;
2081 ret.ival = (gint64)InterlockedCompareExchangePointer((gpointer *) location, (gpointer)val.ival, (gpointer)comp.ival);
2087 mono_interlocked_lock ();
2089 if (old == comparand)
2091 mono_interlocked_unlock ();
2098 ves_icall_System_Threading_Interlocked_CompareExchange_Long (gint64 *location, gint64 value, gint64 comparand)
2100 #if SIZEOF_VOID_P == 8
2101 return (gint64)InterlockedCompareExchangePointer((gpointer *) location, (gpointer)value, (gpointer)comparand);
2105 mono_interlocked_lock ();
2107 if (old == comparand)
2109 mono_interlocked_unlock ();
2116 ves_icall_System_Threading_Interlocked_CompareExchange_T (MonoObject **location, MonoObject *value, MonoObject *comparand)
2119 res = InterlockedCompareExchangePointer ((gpointer *)location, value, comparand);
2120 mono_gc_wbarrier_generic_nostore (location);
2125 ves_icall_System_Threading_Interlocked_Exchange_T (MonoObject **location, MonoObject *value)
2128 res = InterlockedExchangePointer ((gpointer *)location, value);
2129 mono_gc_wbarrier_generic_nostore (location);
2134 ves_icall_System_Threading_Interlocked_Add_Int (gint32 *location, gint32 value)
2136 #if SIZEOF_VOID_P == 8
2137 /* Should be implemented as a JIT intrinsic */
2138 mono_raise_exception (mono_get_exception_not_implemented (NULL));
2143 mono_interlocked_lock ();
2145 *location = orig + value;
2146 mono_interlocked_unlock ();
2148 return orig + value;
2153 ves_icall_System_Threading_Interlocked_Add_Long (gint64 *location, gint64 value)
2155 #if SIZEOF_VOID_P == 8
2156 /* Should be implemented as a JIT intrinsic */
2157 mono_raise_exception (mono_get_exception_not_implemented (NULL));
2162 mono_interlocked_lock ();
2164 *location = orig + value;
2165 mono_interlocked_unlock ();
2167 return orig + value;
2172 ves_icall_System_Threading_Interlocked_Read_Long (gint64 *location)
2174 #if SIZEOF_VOID_P == 8
2175 /* 64 bit reads are already atomic */
2180 mono_interlocked_lock ();
2182 mono_interlocked_unlock ();
2189 ves_icall_System_Threading_Thread_MemoryBarrier (void)
2191 mono_threads_lock ();
2192 mono_threads_unlock ();
2196 ves_icall_System_Threading_Thread_ClrState (MonoInternalThread* this, guint32 state)
2198 mono_thread_clr_state (this, state);
2200 if (state & ThreadState_Background) {
2201 /* If the thread changes the background mode, the main thread has to
2202 * be notified, since it has to rebuild the list of threads to
2205 SetEvent (background_change_event);
2210 ves_icall_System_Threading_Thread_SetState (MonoInternalThread* this, guint32 state)
2212 mono_thread_set_state (this, state);
2214 if (state & ThreadState_Background) {
2215 /* If the thread changes the background mode, the main thread has to
2216 * be notified, since it has to rebuild the list of threads to
2219 SetEvent (background_change_event);
2224 ves_icall_System_Threading_Thread_GetState (MonoInternalThread* this)
2228 ensure_synch_cs_set (this);
2230 EnterCriticalSection (this->synch_cs);
2232 state = this->state;
2234 LeaveCriticalSection (this->synch_cs);
2239 void ves_icall_System_Threading_Thread_Interrupt_internal (MonoInternalThread *this)
2241 gboolean throw = FALSE;
2243 ensure_synch_cs_set (this);
2245 if (this == mono_thread_internal_current ())
2248 EnterCriticalSection (this->synch_cs);
2250 this->thread_interrupt_requested = TRUE;
2252 if (this->state & ThreadState_WaitSleepJoin) {
2256 LeaveCriticalSection (this->synch_cs);
2259 signal_thread_state_change (this);
2263 void mono_thread_current_check_pending_interrupt ()
2265 MonoInternalThread *thread = mono_thread_internal_current ();
2266 gboolean throw = FALSE;
2268 mono_debugger_check_interruption ();
2270 ensure_synch_cs_set (thread);
2272 EnterCriticalSection (thread->synch_cs);
2274 if (thread->thread_interrupt_requested) {
2276 thread->thread_interrupt_requested = FALSE;
2279 LeaveCriticalSection (thread->synch_cs);
2282 mono_raise_exception (mono_get_exception_thread_interrupted ());
2287 mono_thread_get_abort_signal (void)
2299 static int abort_signum = -1;
2301 if (abort_signum != -1)
2302 return abort_signum;
2303 /* we try to avoid SIGRTMIN and any one that might have been set already, see bug #75387 */
2304 for (i = SIGRTMIN + 1; i < SIGRTMAX; ++i) {
2305 struct sigaction sinfo;
2306 sigaction (i, NULL, &sinfo);
2307 if (sinfo.sa_handler == SIG_DFL && (void*)sinfo.sa_sigaction == (void*)SIG_DFL) {
2312 /* fallback to the old way */
2315 #endif /* HOST_WIN32 */
2319 static void CALLBACK interruption_request_apc (ULONG_PTR param)
2321 MonoException* exc = mono_thread_request_interruption (FALSE);
2322 if (exc) mono_raise_exception (exc);
2324 #endif /* HOST_WIN32 */
2327 * signal_thread_state_change
2329 * Tells the thread that his state has changed and it has to enter the new
2330 * state as soon as possible.
2332 static void signal_thread_state_change (MonoInternalThread *thread)
2334 if (thread == mono_thread_internal_current ()) {
2335 /* Do it synchronously */
2336 MonoException *exc = mono_thread_request_interruption (FALSE);
2338 mono_raise_exception (exc);
2342 QueueUserAPC ((PAPCFUNC)interruption_request_apc, thread->handle, NULL);
2344 /* fixme: store the state somewhere */
2345 mono_thread_kill (thread, mono_thread_get_abort_signal ());
2348 * This will cause waits to be broken.
2349 * It will also prevent the thread from entering a wait, so if the thread returns
2350 * from the wait before it receives the abort signal, it will just spin in the wait
2351 * functions in the io-layer until the signal handler calls QueueUserAPC which will
2354 wapi_interrupt_thread (thread->handle);
2355 #endif /* HOST_WIN32 */
2359 ves_icall_System_Threading_Thread_Abort (MonoInternalThread *thread, MonoObject *state)
2361 ensure_synch_cs_set (thread);
2363 EnterCriticalSection (thread->synch_cs);
2365 if ((thread->state & ThreadState_AbortRequested) != 0 ||
2366 (thread->state & ThreadState_StopRequested) != 0 ||
2367 (thread->state & ThreadState_Stopped) != 0)
2369 LeaveCriticalSection (thread->synch_cs);
2373 if ((thread->state & ThreadState_Unstarted) != 0) {
2374 thread->state |= ThreadState_Aborted;
2375 LeaveCriticalSection (thread->synch_cs);
2379 thread->state |= ThreadState_AbortRequested;
2380 if (thread->abort_state_handle)
2381 mono_gchandle_free (thread->abort_state_handle);
2383 thread->abort_state_handle = mono_gchandle_new (state, FALSE);
2384 g_assert (thread->abort_state_handle);
2386 thread->abort_state_handle = 0;
2388 thread->abort_exc = NULL;
2391 * abort_exc is set in mono_thread_execute_interruption(),
2392 * triggered by the call to signal_thread_state_change(),
2393 * below. There's a point between where we have
2394 * abort_state_handle set, but abort_exc NULL, but that's not
2398 LeaveCriticalSection (thread->synch_cs);
2400 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Abort requested for %p (%"G_GSIZE_FORMAT")", __func__, GetCurrentThreadId (), thread, (gsize)thread->tid));
2402 /* During shutdown, we can't wait for other threads */
2404 /* Make sure the thread is awake */
2405 mono_thread_resume (thread);
2407 signal_thread_state_change (thread);
2411 ves_icall_System_Threading_Thread_ResetAbort (void)
2413 MonoInternalThread *thread = mono_thread_internal_current ();
2414 gboolean was_aborting;
2416 ensure_synch_cs_set (thread);
2418 EnterCriticalSection (thread->synch_cs);
2419 was_aborting = thread->state & ThreadState_AbortRequested;
2420 thread->state &= ~ThreadState_AbortRequested;
2421 LeaveCriticalSection (thread->synch_cs);
2423 if (!was_aborting) {
2424 const char *msg = "Unable to reset abort because no abort was requested";
2425 mono_raise_exception (mono_get_exception_thread_state (msg));
2427 thread->abort_exc = NULL;
2428 if (thread->abort_state_handle) {
2429 mono_gchandle_free (thread->abort_state_handle);
2430 /* This is actually not necessary - the handle
2431 only counts if the exception is set */
2432 thread->abort_state_handle = 0;
2437 mono_thread_internal_reset_abort (MonoInternalThread *thread)
2439 ensure_synch_cs_set (thread);
2441 EnterCriticalSection (thread->synch_cs);
2443 thread->state &= ~ThreadState_AbortRequested;
2445 if (thread->abort_exc) {
2446 thread->abort_exc = NULL;
2447 if (thread->abort_state_handle) {
2448 mono_gchandle_free (thread->abort_state_handle);
2449 /* This is actually not necessary - the handle
2450 only counts if the exception is set */
2451 thread->abort_state_handle = 0;
2455 LeaveCriticalSection (thread->synch_cs);
2459 ves_icall_System_Threading_Thread_GetAbortExceptionState (MonoThread *this)
2461 MonoInternalThread *thread = this->internal_thread;
2462 MonoObject *state, *deserialized = NULL, *exc;
2465 if (!thread->abort_state_handle)
2468 state = mono_gchandle_get_target (thread->abort_state_handle);
2471 domain = mono_domain_get ();
2472 if (mono_object_domain (state) == domain)
2475 deserialized = mono_object_xdomain_representation (state, domain, &exc);
2477 if (!deserialized) {
2478 MonoException *invalid_op_exc = mono_get_exception_invalid_operation ("Thread.ExceptionState cannot access an ExceptionState from a different AppDomain");
2480 MONO_OBJECT_SETREF (invalid_op_exc, inner_ex, exc);
2481 mono_raise_exception (invalid_op_exc);
2484 return deserialized;
2488 mono_thread_suspend (MonoInternalThread *thread)
2490 ensure_synch_cs_set (thread);
2492 EnterCriticalSection (thread->synch_cs);
2494 if ((thread->state & ThreadState_Unstarted) != 0 ||
2495 (thread->state & ThreadState_Aborted) != 0 ||
2496 (thread->state & ThreadState_Stopped) != 0)
2498 LeaveCriticalSection (thread->synch_cs);
2502 if ((thread->state & ThreadState_Suspended) != 0 ||
2503 (thread->state & ThreadState_SuspendRequested) != 0 ||
2504 (thread->state & ThreadState_StopRequested) != 0)
2506 LeaveCriticalSection (thread->synch_cs);
2510 thread->state |= ThreadState_SuspendRequested;
2512 LeaveCriticalSection (thread->synch_cs);
2514 signal_thread_state_change (thread);
2519 ves_icall_System_Threading_Thread_Suspend (MonoInternalThread *thread)
2521 if (!mono_thread_suspend (thread))
2522 mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started, or is dead."));
2526 mono_thread_resume (MonoInternalThread *thread)
2528 ensure_synch_cs_set (thread);
2530 EnterCriticalSection (thread->synch_cs);
2532 if ((thread->state & ThreadState_SuspendRequested) != 0) {
2533 thread->state &= ~ThreadState_SuspendRequested;
2534 LeaveCriticalSection (thread->synch_cs);
2538 if ((thread->state & ThreadState_Suspended) == 0 ||
2539 (thread->state & ThreadState_Unstarted) != 0 ||
2540 (thread->state & ThreadState_Aborted) != 0 ||
2541 (thread->state & ThreadState_Stopped) != 0)
2543 LeaveCriticalSection (thread->synch_cs);
2547 thread->resume_event = CreateEvent (NULL, TRUE, FALSE, NULL);
2548 if (thread->resume_event == NULL) {
2549 LeaveCriticalSection (thread->synch_cs);
2553 /* Awake the thread */
2554 SetEvent (thread->suspend_event);
2556 LeaveCriticalSection (thread->synch_cs);
2558 /* Wait for the thread to awake */
2559 WaitForSingleObject (thread->resume_event, INFINITE);
2560 CloseHandle (thread->resume_event);
2561 thread->resume_event = NULL;
2567 ves_icall_System_Threading_Thread_Resume (MonoThread *thread)
2569 if (!thread->internal_thread || !mono_thread_resume (thread->internal_thread))
2570 mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started, or is dead."));
2574 find_wrapper (MonoMethod *m, gint no, gint ilo, gboolean managed, gpointer data)
2579 if (m->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE ||
2580 m->wrapper_type == MONO_WRAPPER_XDOMAIN_INVOKE ||
2581 m->wrapper_type == MONO_WRAPPER_XDOMAIN_DISPATCH)
2583 *((gboolean*)data) = TRUE;
2590 is_running_protected_wrapper (void)
2592 gboolean found = FALSE;
2593 mono_stack_walk (find_wrapper, &found);
2597 void mono_thread_internal_stop (MonoInternalThread *thread)
2599 ensure_synch_cs_set (thread);
2601 EnterCriticalSection (thread->synch_cs);
2603 if ((thread->state & ThreadState_StopRequested) != 0 ||
2604 (thread->state & ThreadState_Stopped) != 0)
2606 LeaveCriticalSection (thread->synch_cs);
2610 /* Make sure the thread is awake */
2611 mono_thread_resume (thread);
2613 thread->state |= ThreadState_StopRequested;
2614 thread->state &= ~ThreadState_AbortRequested;
2616 LeaveCriticalSection (thread->synch_cs);
2618 signal_thread_state_change (thread);
2621 void mono_thread_stop (MonoThread *thread)
2623 mono_thread_internal_stop (thread->internal_thread);
2627 ves_icall_System_Threading_Thread_VolatileRead1 (void *ptr)
2629 return *((volatile gint8 *) (ptr));
2633 ves_icall_System_Threading_Thread_VolatileRead2 (void *ptr)
2635 return *((volatile gint16 *) (ptr));
2639 ves_icall_System_Threading_Thread_VolatileRead4 (void *ptr)
2641 return *((volatile gint32 *) (ptr));
2645 ves_icall_System_Threading_Thread_VolatileRead8 (void *ptr)
2647 return *((volatile gint64 *) (ptr));
2651 ves_icall_System_Threading_Thread_VolatileReadIntPtr (void *ptr)
2653 return (void *) *((volatile void **) ptr);
2657 ves_icall_System_Threading_Thread_VolatileWrite1 (void *ptr, gint8 value)
2659 *((volatile gint8 *) ptr) = value;
2663 ves_icall_System_Threading_Thread_VolatileWrite2 (void *ptr, gint16 value)
2665 *((volatile gint16 *) ptr) = value;
2669 ves_icall_System_Threading_Thread_VolatileWrite4 (void *ptr, gint32 value)
2671 *((volatile gint32 *) ptr) = value;
2675 ves_icall_System_Threading_Thread_VolatileWrite8 (void *ptr, gint64 value)
2677 *((volatile gint64 *) ptr) = value;
2681 ves_icall_System_Threading_Thread_VolatileWriteIntPtr (void *ptr, void *value)
2683 *((volatile void **) ptr) = value;
2687 ves_icall_System_Threading_Thread_VolatileWriteObject (void *ptr, void *value)
2689 mono_gc_wbarrier_generic_store (ptr, value);
2692 void mono_thread_init (MonoThreadStartCB start_cb,
2693 MonoThreadAttachCB attach_cb)
2695 MONO_GC_REGISTER_ROOT_FIXED (small_id_table);
2696 InitializeCriticalSection(&threads_mutex);
2697 InitializeCriticalSection(&interlocked_mutex);
2698 InitializeCriticalSection(&contexts_mutex);
2699 InitializeCriticalSection(&delayed_free_table_mutex);
2700 InitializeCriticalSection(&small_id_mutex);
2702 background_change_event = CreateEvent (NULL, TRUE, FALSE, NULL);
2703 g_assert(background_change_event != NULL);
2705 mono_init_static_data_info (&thread_static_info);
2706 mono_init_static_data_info (&context_static_info);
2708 current_object_key=TlsAlloc();
2709 THREAD_DEBUG (g_message ("%s: Allocated current_object_key %d", __func__, current_object_key));
2711 mono_thread_start_cb = start_cb;
2712 mono_thread_attach_cb = attach_cb;
2714 delayed_free_table = g_array_new (FALSE, FALSE, sizeof (DelayedFreeItem));
2716 /* Get a pseudo handle to the current process. This is just a
2717 * kludge so that wapi can build a process handle if needed.
2718 * As a pseudo handle is returned, we don't need to clean
2721 GetCurrentProcess ();
2724 void mono_thread_cleanup (void)
2726 mono_thread_hazardous_try_free_all ();
2728 #if !defined(HOST_WIN32) && !defined(RUN_IN_SUBTHREAD)
2729 /* The main thread must abandon any held mutexes (particularly
2730 * important for named mutexes as they are shared across
2731 * processes, see bug 74680.) This will happen when the
2732 * thread exits, but if it's not running in a subthread it
2733 * won't exit in time.
2735 /* Using non-w32 API is a nasty kludge, but I couldn't find
2736 * anything in the documentation that would let me do this
2737 * here yet still be safe to call on windows.
2739 _wapi_thread_signal_self (mono_environment_exitcode_get ());
2743 /* This stuff needs more testing, it seems one of these
2744 * critical sections can be locked when mono_thread_cleanup is
2747 DeleteCriticalSection (&threads_mutex);
2748 DeleteCriticalSection (&interlocked_mutex);
2749 DeleteCriticalSection (&contexts_mutex);
2750 DeleteCriticalSection (&delayed_free_table_mutex);
2751 DeleteCriticalSection (&small_id_mutex);
2752 CloseHandle (background_change_event);
2755 g_array_free (delayed_free_table, TRUE);
2756 delayed_free_table = NULL;
2758 TlsFree (current_object_key);
2762 mono_threads_install_cleanup (MonoThreadCleanupFunc func)
2764 mono_thread_cleanup_fn = func;
2768 mono_thread_set_manage_callback (MonoThread *thread, MonoThreadManageCallback func)
2770 thread->internal_thread->manage_callback = func;
2773 void mono_threads_install_notify_pending_exc (MonoThreadNotifyPendingExcFunc func)
2775 mono_thread_notify_pending_exc_fn = func;
2779 static void print_tids (gpointer key, gpointer value, gpointer user)
2781 /* GPOINTER_TO_UINT breaks horribly if sizeof(void *) >
2782 * sizeof(uint) and a cast to uint would overflow
2784 /* Older versions of glib don't have G_GSIZE_FORMAT, so just
2785 * print this as a pointer.
2787 g_message ("Waiting for: %p", key);
2792 HANDLE handles[MAXIMUM_WAIT_OBJECTS];
2793 MonoInternalThread *threads[MAXIMUM_WAIT_OBJECTS];
2797 static void wait_for_tids (struct wait_data *wait, guint32 timeout)
2801 THREAD_DEBUG (g_message("%s: %d threads to wait for in this batch", __func__, wait->num));
2803 ret=WaitForMultipleObjectsEx(wait->num, wait->handles, TRUE, timeout, TRUE);
2805 if(ret==WAIT_FAILED) {
2806 /* See the comment in build_wait_tids() */
2807 THREAD_DEBUG (g_message ("%s: Wait failed", __func__));
2811 for(i=0; i<wait->num; i++)
2812 CloseHandle (wait->handles[i]);
2814 if (ret == WAIT_TIMEOUT)
2817 for(i=0; i<wait->num; i++) {
2818 gsize tid = wait->threads[i]->tid;
2820 mono_threads_lock ();
2821 if(mono_g_hash_table_lookup (threads, (gpointer)tid)!=NULL) {
2822 /* This thread must have been killed, because
2823 * it hasn't cleaned itself up. (It's just
2824 * possible that the thread exited before the
2825 * parent thread had a chance to store the
2826 * handle, and now there is another pointer to
2827 * the already-exited thread stored. In this
2828 * case, we'll just get two
2829 * mono_profiler_thread_end() calls for the
2833 mono_threads_unlock ();
2834 THREAD_DEBUG (g_message ("%s: cleaning up after thread %p (%"G_GSIZE_FORMAT")", __func__, wait->threads[i], tid));
2835 thread_cleanup (wait->threads[i]);
2837 mono_threads_unlock ();
2842 static void wait_for_tids_or_state_change (struct wait_data *wait, guint32 timeout)
2844 guint32 i, ret, count;
2846 THREAD_DEBUG (g_message("%s: %d threads to wait for in this batch", __func__, wait->num));
2848 /* Add the thread state change event, so it wakes up if a thread changes
2849 * to background mode.
2852 if (count < MAXIMUM_WAIT_OBJECTS) {
2853 wait->handles [count] = background_change_event;
2857 ret=WaitForMultipleObjectsEx (count, wait->handles, FALSE, timeout, TRUE);
2859 if(ret==WAIT_FAILED) {
2860 /* See the comment in build_wait_tids() */
2861 THREAD_DEBUG (g_message ("%s: Wait failed", __func__));
2865 for(i=0; i<wait->num; i++)
2866 CloseHandle (wait->handles[i]);
2868 if (ret == WAIT_TIMEOUT)
2871 if (ret < wait->num) {
2872 gsize tid = wait->threads[ret]->tid;
2873 mono_threads_lock ();
2874 if (mono_g_hash_table_lookup (threads, (gpointer)tid)!=NULL) {
2875 /* See comment in wait_for_tids about thread cleanup */
2876 mono_threads_unlock ();
2877 THREAD_DEBUG (g_message ("%s: cleaning up after thread %"G_GSIZE_FORMAT, __func__, tid));
2878 thread_cleanup (wait->threads [ret]);
2880 mono_threads_unlock ();
2884 static void build_wait_tids (gpointer key, gpointer value, gpointer user)
2886 struct wait_data *wait=(struct wait_data *)user;
2888 if(wait->num<MAXIMUM_WAIT_OBJECTS) {
2890 MonoInternalThread *thread=(MonoInternalThread *)value;
2892 /* Ignore background threads, we abort them later */
2893 /* Do not lock here since it is not needed and the caller holds threads_lock */
2894 if (thread->state & ThreadState_Background) {
2895 THREAD_DEBUG (g_message ("%s: ignoring background thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2896 return; /* just leave, ignore */
2899 if (mono_gc_is_finalizer_internal_thread (thread)) {
2900 THREAD_DEBUG (g_message ("%s: ignoring finalizer thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2904 if (thread == mono_thread_internal_current ()) {
2905 THREAD_DEBUG (g_message ("%s: ignoring current thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2909 if (mono_thread_get_main () && (thread == mono_thread_get_main ()->internal_thread)) {
2910 THREAD_DEBUG (g_message ("%s: ignoring main thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2914 if (thread->flags & MONO_THREAD_FLAG_DONT_MANAGE) {
2915 THREAD_DEBUG (g_message ("%s: ignoring thread %" G_GSIZE_FORMAT "with DONT_MANAGE flag set.", __func__, (gsize)thread->tid));
2919 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
2920 if (handle == NULL) {
2921 THREAD_DEBUG (g_message ("%s: ignoring unopenable thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2925 THREAD_DEBUG (g_message ("%s: Invoking mono_thread_manage callback on thread %p", __func__, thread));
2926 if ((thread->manage_callback == NULL) || (thread->manage_callback (thread->root_domain_thread) == TRUE)) {
2927 wait->handles[wait->num]=handle;
2928 wait->threads[wait->num]=thread;
2931 THREAD_DEBUG (g_message ("%s: adding thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2933 THREAD_DEBUG (g_message ("%s: ignoring (because of callback) thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2938 /* Just ignore the rest, we can't do anything with
2945 remove_and_abort_threads (gpointer key, gpointer value, gpointer user)
2947 struct wait_data *wait=(struct wait_data *)user;
2948 gsize self = GetCurrentThreadId ();
2949 MonoInternalThread *thread = value;
2952 if (wait->num >= MAXIMUM_WAIT_OBJECTS)
2955 /* The finalizer thread is not a background thread */
2956 if (thread->tid != self && (thread->state & ThreadState_Background) != 0 &&
2957 !(thread->flags & MONO_THREAD_FLAG_DONT_MANAGE)) {
2959 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
2963 /* printf ("A: %d\n", wait->num); */
2964 wait->handles[wait->num]=thread->handle;
2965 wait->threads[wait->num]=thread;
2968 THREAD_DEBUG (g_print ("%s: Aborting id: %"G_GSIZE_FORMAT"\n", __func__, (gsize)thread->tid));
2969 mono_thread_internal_stop (thread);
2973 return (thread->tid != self && !mono_gc_is_finalizer_internal_thread (thread));
2977 * mono_threads_set_shutting_down:
2979 * Is called by a thread that wants to shut down Mono. If the runtime is already
2980 * shutting down, the calling thread is suspended/stopped, and this function never
2984 mono_threads_set_shutting_down (void)
2986 MonoInternalThread *current_thread = mono_thread_internal_current ();
2988 mono_threads_lock ();
2990 if (shutting_down) {
2991 mono_threads_unlock ();
2993 /* Make sure we're properly suspended/stopped */
2995 EnterCriticalSection (current_thread->synch_cs);
2997 if ((current_thread->state & ThreadState_SuspendRequested) ||
2998 (current_thread->state & ThreadState_AbortRequested) ||
2999 (current_thread->state & ThreadState_StopRequested)) {
3000 LeaveCriticalSection (current_thread->synch_cs);
3001 mono_thread_execute_interruption (current_thread);
3003 current_thread->state |= ThreadState_Stopped;
3004 LeaveCriticalSection (current_thread->synch_cs);
3007 /* Wake up other threads potentially waiting for us */
3010 shutting_down = TRUE;
3012 /* Not really a background state change, but this will
3013 * interrupt the main thread if it is waiting for all
3014 * the other threads.
3016 SetEvent (background_change_event);
3018 mono_threads_unlock ();
3023 * mono_threads_is_shutting_down:
3025 * Returns whether a thread has commenced shutdown of Mono. Note that
3026 * if the function returns FALSE the caller must not assume that
3027 * shutdown is not in progress, because the situation might have
3028 * changed since the function returned. For that reason this function
3029 * is of very limited utility.
3032 mono_threads_is_shutting_down (void)
3034 return shutting_down;
3037 void mono_thread_manage (void)
3039 struct wait_data wait_data;
3040 struct wait_data *wait = &wait_data;
3042 memset (wait, 0, sizeof (struct wait_data));
3043 /* join each thread that's still running */
3044 THREAD_DEBUG (g_message ("%s: Joining each running thread...", __func__));
3046 mono_threads_lock ();
3048 THREAD_DEBUG (g_message("%s: No threads", __func__));
3049 mono_threads_unlock ();
3052 mono_threads_unlock ();
3055 mono_threads_lock ();
3056 if (shutting_down) {
3057 /* somebody else is shutting down */
3058 mono_threads_unlock ();
3061 THREAD_DEBUG (g_message ("%s: There are %d threads to join", __func__, mono_g_hash_table_size (threads));
3062 mono_g_hash_table_foreach (threads, print_tids, NULL));
3064 ResetEvent (background_change_event);
3066 /*We must zero all InternalThread pointers to avoid making the GC unhappy.*/
3067 memset (wait->threads, 0, MAXIMUM_WAIT_OBJECTS * SIZEOF_VOID_P);
3068 mono_g_hash_table_foreach (threads, build_wait_tids, wait);
3069 mono_threads_unlock ();
3071 /* Something to wait for */
3072 wait_for_tids_or_state_change (wait, INFINITE);
3074 THREAD_DEBUG (g_message ("%s: I have %d threads after waiting.", __func__, wait->num));
3075 } while(wait->num>0);
3077 mono_threads_set_shutting_down ();
3079 /* No new threads will be created after this point */
3081 mono_runtime_set_shutting_down ();
3083 THREAD_DEBUG (g_message ("%s: threadpool cleanup", __func__));
3084 mono_thread_pool_cleanup ();
3087 * Remove everything but the finalizer thread and self.
3088 * Also abort all the background threads
3091 mono_threads_lock ();
3094 /*We must zero all InternalThread pointers to avoid making the GC unhappy.*/
3095 memset (wait->threads, 0, MAXIMUM_WAIT_OBJECTS * SIZEOF_VOID_P);
3096 mono_g_hash_table_foreach_remove (threads, remove_and_abort_threads, wait);
3098 mono_threads_unlock ();
3100 THREAD_DEBUG (g_message ("%s: wait->num is now %d", __func__, wait->num));
3102 /* Something to wait for */
3103 wait_for_tids (wait, INFINITE);
3105 } while (wait->num > 0);
3108 * give the subthreads a chance to really quit (this is mainly needed
3109 * to get correct user and system times from getrusage/wait/time(1)).
3110 * This could be removed if we avoid pthread_detach() and use pthread_join().
3117 static void terminate_thread (gpointer key, gpointer value, gpointer user)
3119 MonoInternalThread *thread=(MonoInternalThread *)value;
3121 if(thread->tid != (gsize)user) {
3122 /*TerminateThread (thread->handle, -1);*/
3126 void mono_thread_abort_all_other_threads (void)
3128 gsize self = GetCurrentThreadId ();
3130 mono_threads_lock ();
3131 THREAD_DEBUG (g_message ("%s: There are %d threads to abort", __func__,
3132 mono_g_hash_table_size (threads));
3133 mono_g_hash_table_foreach (threads, print_tids, NULL));
3135 mono_g_hash_table_foreach (threads, terminate_thread, (gpointer)self);
3137 mono_threads_unlock ();
3141 collect_threads_for_suspend (gpointer key, gpointer value, gpointer user_data)
3143 MonoInternalThread *thread = (MonoInternalThread*)value;
3144 struct wait_data *wait = (struct wait_data*)user_data;
3148 * We try to exclude threads early, to avoid running into the MAXIMUM_WAIT_OBJECTS
3150 * This needs no locking.
3152 if ((thread->state & ThreadState_Suspended) != 0 ||
3153 (thread->state & ThreadState_Stopped) != 0)
3156 if (wait->num<MAXIMUM_WAIT_OBJECTS) {
3157 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
3161 wait->handles [wait->num] = handle;
3162 wait->threads [wait->num] = thread;
3168 * mono_thread_suspend_all_other_threads:
3170 * Suspend all managed threads except the finalizer thread and this thread. It is
3171 * not possible to resume them later.
3173 void mono_thread_suspend_all_other_threads (void)
3175 struct wait_data wait_data;
3176 struct wait_data *wait = &wait_data;
3178 gsize self = GetCurrentThreadId ();
3180 guint32 eventidx = 0;
3181 gboolean starting, finished;
3183 memset (wait, 0, sizeof (struct wait_data));
3185 * The other threads could be in an arbitrary state at this point, i.e.
3186 * they could be starting up, shutting down etc. This means that there could be
3187 * threads which are not even in the threads hash table yet.
3191 * First we set a barrier which will be checked by all threads before they
3192 * are added to the threads hash table, and they will exit if the flag is set.
3193 * This ensures that no threads could be added to the hash later.
3194 * We will use shutting_down as the barrier for now.
3196 g_assert (shutting_down);
3199 * We make multiple calls to WaitForMultipleObjects since:
3200 * - we can only wait for MAXIMUM_WAIT_OBJECTS threads
3201 * - some threads could exit without becoming suspended
3206 * Make a copy of the hashtable since we can't do anything with
3207 * threads while threads_mutex is held.
3210 /*We must zero all InternalThread pointers to avoid making the GC unhappy.*/
3211 memset (wait->threads, 0, MAXIMUM_WAIT_OBJECTS * SIZEOF_VOID_P);
3212 mono_threads_lock ();
3213 mono_g_hash_table_foreach (threads, collect_threads_for_suspend, wait);
3214 mono_threads_unlock ();
3216 events = g_new0 (gpointer, wait->num);
3218 /* Get the suspended events that we'll be waiting for */
3219 for (i = 0; i < wait->num; ++i) {
3220 MonoInternalThread *thread = wait->threads [i];
3221 gboolean signal_suspend = FALSE;
3223 if ((thread->tid == self) || mono_gc_is_finalizer_internal_thread (thread) || (thread->flags & MONO_THREAD_FLAG_DONT_MANAGE)) {
3224 //CloseHandle (wait->handles [i]);
3225 wait->threads [i] = NULL; /* ignore this thread in next loop */
3229 ensure_synch_cs_set (thread);
3231 EnterCriticalSection (thread->synch_cs);
3233 if (thread->suspended_event == NULL) {
3234 thread->suspended_event = CreateEvent (NULL, TRUE, FALSE, NULL);
3235 if (thread->suspended_event == NULL) {
3236 /* Forget this one and go on to the next */
3237 LeaveCriticalSection (thread->synch_cs);
3242 if ((thread->state & ThreadState_Suspended) != 0 ||
3243 (thread->state & ThreadState_StopRequested) != 0 ||
3244 (thread->state & ThreadState_Stopped) != 0) {
3245 LeaveCriticalSection (thread->synch_cs);
3246 CloseHandle (wait->handles [i]);
3247 wait->threads [i] = NULL; /* ignore this thread in next loop */
3251 if ((thread->state & ThreadState_SuspendRequested) == 0)
3252 signal_suspend = TRUE;
3254 events [eventidx++] = thread->suspended_event;
3256 /* Convert abort requests into suspend requests */
3257 if ((thread->state & ThreadState_AbortRequested) != 0)
3258 thread->state &= ~ThreadState_AbortRequested;
3260 thread->state |= ThreadState_SuspendRequested;
3262 LeaveCriticalSection (thread->synch_cs);
3264 /* Signal the thread to suspend */
3266 signal_thread_state_change (thread);
3270 WaitForMultipleObjectsEx (eventidx, events, TRUE, 100, FALSE);
3271 for (i = 0; i < wait->num; ++i) {
3272 MonoInternalThread *thread = wait->threads [i];
3277 ensure_synch_cs_set (thread);
3279 EnterCriticalSection (thread->synch_cs);
3280 if ((thread->state & ThreadState_Suspended) != 0) {
3281 CloseHandle (thread->suspended_event);
3282 thread->suspended_event = NULL;
3284 LeaveCriticalSection (thread->synch_cs);
3288 * If there are threads which are starting up, we wait until they
3289 * are suspended when they try to register in the threads hash.
3290 * This is guaranteed to finish, since the threads which can create new
3291 * threads get suspended after a while.
3292 * FIXME: The finalizer thread can still create new threads.
3294 mono_threads_lock ();
3295 if (threads_starting_up)
3296 starting = mono_g_hash_table_size (threads_starting_up) > 0;
3299 mono_threads_unlock ();
3311 collect_threads (gpointer key, gpointer value, gpointer user_data)
3313 MonoInternalThread *thread = (MonoInternalThread*)value;
3314 struct wait_data *wait = (struct wait_data*)user_data;
3317 if (wait->num<MAXIMUM_WAIT_OBJECTS) {
3318 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
3322 wait->handles [wait->num] = handle;
3323 wait->threads [wait->num] = thread;
3329 * mono_threads_request_thread_dump:
3331 * Ask all threads except the current to print their stacktrace to stdout.
3334 mono_threads_request_thread_dump (void)
3336 struct wait_data wait_data;
3337 struct wait_data *wait = &wait_data;
3340 memset (wait, 0, sizeof (struct wait_data));
3343 * Make a copy of the hashtable since we can't do anything with
3344 * threads while threads_mutex is held.
3346 mono_threads_lock ();
3347 mono_g_hash_table_foreach (threads, collect_threads, wait);
3348 mono_threads_unlock ();
3350 for (i = 0; i < wait->num; ++i) {
3351 MonoInternalThread *thread = wait->threads [i];
3353 if (!mono_gc_is_finalizer_internal_thread (thread) &&
3354 (thread != mono_thread_internal_current ()) &&
3355 !thread->thread_dump_requested) {
3356 thread->thread_dump_requested = TRUE;
3358 signal_thread_state_change (thread);
3361 CloseHandle (wait->handles [i]);
3366 * mono_thread_push_appdomain_ref:
3368 * Register that the current thread may have references to objects in domain
3369 * @domain on its stack. Each call to this function should be paired with a
3370 * call to pop_appdomain_ref.
3373 mono_thread_push_appdomain_ref (MonoDomain *domain)
3375 MonoInternalThread *thread = mono_thread_internal_current ();
3378 /* printf ("PUSH REF: %"G_GSIZE_FORMAT" -> %s.\n", (gsize)thread->tid, domain->friendly_name); */
3379 SPIN_LOCK (thread->lock_thread_id);
3380 thread->appdomain_refs = g_slist_prepend (thread->appdomain_refs, domain);
3381 SPIN_UNLOCK (thread->lock_thread_id);
3386 mono_thread_pop_appdomain_ref (void)
3388 MonoInternalThread *thread = mono_thread_internal_current ();
3391 /* printf ("POP REF: %"G_GSIZE_FORMAT" -> %s.\n", (gsize)thread->tid, ((MonoDomain*)(thread->appdomain_refs->data))->friendly_name); */
3392 /* FIXME: How can the list be empty ? */
3393 SPIN_LOCK (thread->lock_thread_id);
3394 if (thread->appdomain_refs)
3395 thread->appdomain_refs = g_slist_remove (thread->appdomain_refs, thread->appdomain_refs->data);
3396 SPIN_UNLOCK (thread->lock_thread_id);
3401 mono_thread_internal_has_appdomain_ref (MonoInternalThread *thread, MonoDomain *domain)
3404 SPIN_LOCK (thread->lock_thread_id);
3405 res = g_slist_find (thread->appdomain_refs, domain) != NULL;
3406 SPIN_UNLOCK (thread->lock_thread_id);
3411 mono_thread_has_appdomain_ref (MonoThread *thread, MonoDomain *domain)
3413 return mono_thread_internal_has_appdomain_ref (thread->internal_thread, domain);
3416 typedef struct abort_appdomain_data {
3417 struct wait_data wait;
3419 } abort_appdomain_data;
3422 collect_appdomain_thread (gpointer key, gpointer value, gpointer user_data)
3424 MonoInternalThread *thread = (MonoInternalThread*)value;
3425 abort_appdomain_data *data = (abort_appdomain_data*)user_data;
3426 MonoDomain *domain = data->domain;
3428 if (mono_thread_internal_has_appdomain_ref (thread, domain)) {
3429 /* printf ("ABORTING THREAD %p BECAUSE IT REFERENCES DOMAIN %s.\n", thread->tid, domain->friendly_name); */
3431 if(data->wait.num<MAXIMUM_WAIT_OBJECTS) {
3432 HANDLE handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
3435 data->wait.handles [data->wait.num] = handle;
3436 data->wait.threads [data->wait.num] = thread;
3439 /* Just ignore the rest, we can't do anything with
3447 * mono_threads_abort_appdomain_threads:
3449 * Abort threads which has references to the given appdomain.
3452 mono_threads_abort_appdomain_threads (MonoDomain *domain, int timeout)
3454 abort_appdomain_data user_data;
3456 int orig_timeout = timeout;
3459 THREAD_DEBUG (g_message ("%s: starting abort", __func__));
3461 start_time = mono_msec_ticks ();
3463 mono_threads_lock ();
3465 user_data.domain = domain;
3466 user_data.wait.num = 0;
3467 /* This shouldn't take any locks */
3468 mono_g_hash_table_foreach (threads, collect_appdomain_thread, &user_data);
3469 mono_threads_unlock ();
3471 if (user_data.wait.num > 0) {
3472 /* Abort the threads outside the threads lock */
3473 for (i = 0; i < user_data.wait.num; ++i)
3474 ves_icall_System_Threading_Thread_Abort (user_data.wait.threads [i], NULL);
3477 * We should wait for the threads either to abort, or to leave the
3478 * domain. We can't do the latter, so we wait with a timeout.
3480 wait_for_tids (&user_data.wait, 100);
3483 /* Update remaining time */
3484 timeout -= mono_msec_ticks () - start_time;
3485 start_time = mono_msec_ticks ();
3487 if (orig_timeout != -1 && timeout < 0)
3490 while (user_data.wait.num > 0);
3492 THREAD_DEBUG (g_message ("%s: abort done", __func__));
3498 clear_cached_culture (gpointer key, gpointer value, gpointer user_data)
3500 MonoInternalThread *thread = (MonoInternalThread*)value;
3501 MonoDomain *domain = (MonoDomain*)user_data;
3504 /* No locking needed here */
3505 /* FIXME: why no locking? writes to the cache are protected with synch_cs above */
3507 if (thread->cached_culture_info) {
3508 for (i = 0; i < NUM_CACHED_CULTURES * 2; ++i) {
3509 MonoObject *obj = mono_array_get (thread->cached_culture_info, MonoObject*, i);
3510 if (obj && obj->vtable->domain == domain)
3511 mono_array_set (thread->cached_culture_info, MonoObject*, i, NULL);
3517 * mono_threads_clear_cached_culture:
3519 * Clear the cached_current_culture from all threads if it is in the
3523 mono_threads_clear_cached_culture (MonoDomain *domain)
3525 mono_threads_lock ();
3526 mono_g_hash_table_foreach (threads, clear_cached_culture, domain);
3527 mono_threads_unlock ();
3531 * mono_thread_get_undeniable_exception:
3533 * Return an exception which needs to be raised when leaving a catch clause.
3534 * This is used for undeniable exception propagation.
3537 mono_thread_get_undeniable_exception (void)
3539 MonoInternalThread *thread = mono_thread_internal_current ();
3541 if (thread && thread->abort_exc && !is_running_protected_wrapper ()) {
3543 * FIXME: Clear the abort exception and return an AppDomainUnloaded
3544 * exception if the thread no longer references a dying appdomain.
3546 thread->abort_exc->trace_ips = NULL;
3547 thread->abort_exc->stack_trace = NULL;
3548 return thread->abort_exc;
3554 #if MONO_SMALL_CONFIG
3555 #define NUM_STATIC_DATA_IDX 4
3556 static const int static_data_size [NUM_STATIC_DATA_IDX] = {
3560 #define NUM_STATIC_DATA_IDX 8
3561 static const int static_data_size [NUM_STATIC_DATA_IDX] = {
3562 1024, 4096, 16384, 65536, 262144, 1048576, 4194304, 16777216
3566 static uintptr_t* static_reference_bitmaps [NUM_STATIC_DATA_IDX];
3570 mark_tls_slots (void *addr, MonoGCMarkFunc mark_func)
3573 gpointer *static_data = addr;
3574 for (i = 0; i < NUM_STATIC_DATA_IDX; ++i) {
3577 if (!static_data [i])
3579 numwords = 1 + static_data_size [i] / sizeof (gpointer) / (sizeof(uintptr_t) * 8);
3580 ptr = static_data [i];
3581 for (j = 0; j < numwords; ++j, ptr += sizeof (uintptr_t) * 8) {
3582 uintptr_t bmap = static_reference_bitmaps [i][j];
3585 if ((bmap & 1) && *p) {
3597 * mono_alloc_static_data
3599 * Allocate memory blocks for storing threads or context static data
3602 mono_alloc_static_data (gpointer **static_data_ptr, guint32 offset, gboolean threadlocal)
3604 guint idx = (offset >> 24) - 1;
3607 gpointer* static_data = *static_data_ptr;
3609 static void* tls_desc = NULL;
3612 tls_desc = mono_gc_make_root_descr_user (mark_tls_slots);
3614 static_data = mono_gc_alloc_fixed (static_data_size [0], threadlocal?tls_desc:NULL);
3615 *static_data_ptr = static_data;
3616 static_data [0] = static_data;
3619 for (i = 1; i <= idx; ++i) {
3620 if (static_data [i])
3623 static_data [i] = threadlocal?g_malloc0 (static_data_size [i]):mono_gc_alloc_fixed (static_data_size [i], NULL);
3625 static_data [i] = mono_gc_alloc_fixed (static_data_size [i], NULL);
3631 mono_free_static_data (gpointer* static_data, gboolean threadlocal)
3634 for (i = 1; i < NUM_STATIC_DATA_IDX; ++i) {
3635 if (!static_data [i])
3639 g_free (static_data [i]);
3641 mono_gc_free_fixed (static_data [i]);
3643 mono_gc_free_fixed (static_data [i]);
3646 mono_gc_free_fixed (static_data);
3650 * mono_init_static_data_info
3652 * Initializes static data counters
3654 static void mono_init_static_data_info (StaticDataInfo *static_data)
3656 static_data->idx = 0;
3657 static_data->offset = 0;
3658 static_data->freelist = NULL;
3662 * mono_alloc_static_data_slot
3664 * Generates an offset for static data. static_data contains the counters
3665 * used to generate it.
3668 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align)
3672 if (!static_data->idx && !static_data->offset) {
3674 * we use the first chunk of the first allocation also as
3675 * an array for the rest of the data
3677 static_data->offset = sizeof (gpointer) * NUM_STATIC_DATA_IDX;
3679 static_data->offset += align - 1;
3680 static_data->offset &= ~(align - 1);
3681 if (static_data->offset + size >= static_data_size [static_data->idx]) {
3682 static_data->idx ++;
3683 g_assert (size <= static_data_size [static_data->idx]);
3684 g_assert (static_data->idx < NUM_STATIC_DATA_IDX);
3685 static_data->offset = 0;
3687 offset = static_data->offset | ((static_data->idx + 1) << 24);
3688 static_data->offset += size;
3693 * ensure thread static fields already allocated are valid for thread
3694 * This function is called when a thread is created or on thread attach.
3697 thread_adjust_static_data (MonoInternalThread *thread)
3701 mono_threads_lock ();
3702 if (thread_static_info.offset || thread_static_info.idx > 0) {
3703 /* get the current allocated size */
3704 offset = thread_static_info.offset | ((thread_static_info.idx + 1) << 24);
3705 mono_alloc_static_data (&(thread->static_data), offset, TRUE);
3707 mono_threads_unlock ();
3711 alloc_thread_static_data_helper (gpointer key, gpointer value, gpointer user)
3713 MonoInternalThread *thread = value;
3714 guint32 offset = GPOINTER_TO_UINT (user);
3716 mono_alloc_static_data (&(thread->static_data), offset, TRUE);
3719 static MonoThreadDomainTls*
3720 search_tls_slot_in_freelist (StaticDataInfo *static_data, guint32 size, guint32 align)
3722 MonoThreadDomainTls* prev = NULL;
3723 MonoThreadDomainTls* tmp = static_data->freelist;
3725 if (tmp->size == size) {
3727 prev->next = tmp->next;
3729 static_data->freelist = tmp->next;
3738 update_tls_reference_bitmap (guint32 offset, uintptr_t *bitmap, int max_set)
3741 int idx = (offset >> 24) - 1;
3743 if (!static_reference_bitmaps [idx])
3744 static_reference_bitmaps [idx] = g_new0 (uintptr_t, 1 + static_data_size [idx] / sizeof(gpointer) / (sizeof(uintptr_t) * 8));
3745 rb = static_reference_bitmaps [idx];
3747 offset /= sizeof (gpointer);
3748 /* offset is now the bitmap offset */
3749 for (i = 0; i < max_set; ++i) {
3750 if (bitmap [i / sizeof (uintptr_t)] & (1L << (i & (sizeof (uintptr_t) * 8 -1))))
3751 rb [(offset + i) / (sizeof (uintptr_t) * 8)] |= (1L << ((offset + i) & (sizeof (uintptr_t) * 8 -1)));
3756 clear_reference_bitmap (guint32 offset, guint32 size)
3758 int idx = (offset >> 24) - 1;
3760 rb = static_reference_bitmaps [idx];
3762 offset /= sizeof (gpointer);
3763 size /= sizeof (gpointer);
3765 /* offset is now the bitmap offset */
3766 for (; offset < size; ++offset)
3767 rb [offset / (sizeof (uintptr_t) * 8)] &= ~(1L << (offset & (sizeof (uintptr_t) * 8 -1)));
3771 * The offset for a special static variable is composed of three parts:
3772 * a bit that indicates the type of static data (0:thread, 1:context),
3773 * an index in the array of chunks of memory for the thread (thread->static_data)
3774 * and an offset in that chunk of mem. This allows allocating less memory in the
3779 mono_alloc_special_static_data (guint32 static_type, guint32 size, guint32 align, uintptr_t *bitmap, int max_set)
3782 if (static_type == SPECIAL_STATIC_THREAD) {
3783 MonoThreadDomainTls *item;
3784 mono_threads_lock ();
3785 item = search_tls_slot_in_freelist (&thread_static_info, size, align);
3786 /*g_print ("TLS alloc: %d in domain %p (total: %d), cached: %p\n", size, mono_domain_get (), thread_static_info.offset, item);*/
3788 offset = item->offset;
3791 offset = mono_alloc_static_data_slot (&thread_static_info, size, align);
3793 update_tls_reference_bitmap (offset, bitmap, max_set);
3794 /* This can be called during startup */
3795 if (threads != NULL)
3796 mono_g_hash_table_foreach (threads, alloc_thread_static_data_helper, GUINT_TO_POINTER (offset));
3797 mono_threads_unlock ();
3799 g_assert (static_type == SPECIAL_STATIC_CONTEXT);
3800 mono_contexts_lock ();
3801 offset = mono_alloc_static_data_slot (&context_static_info, size, align);
3802 mono_contexts_unlock ();
3803 offset |= 0x80000000; /* Set the high bit to indicate context static data */
3809 mono_get_special_static_data (guint32 offset)
3811 /* The high bit means either thread (0) or static (1) data. */
3813 guint32 static_type = (offset & 0x80000000);
3816 offset &= 0x7fffffff;
3817 idx = (offset >> 24) - 1;
3819 if (static_type == 0) {
3820 return get_thread_static_data (mono_thread_internal_current (), offset);
3822 /* Allocate static data block under demand, since we don't have a list
3825 MonoAppContext *context = mono_context_get ();
3826 if (!context->static_data || !context->static_data [idx]) {
3827 mono_contexts_lock ();
3828 mono_alloc_static_data (&(context->static_data), offset, FALSE);
3829 mono_contexts_unlock ();
3831 return ((char*) context->static_data [idx]) + (offset & 0xffffff);
3841 free_thread_static_data_helper (gpointer key, gpointer value, gpointer user)
3843 MonoInternalThread *thread = value;
3844 TlsOffsetSize *data = user;
3845 int idx = (data->offset >> 24) - 1;
3848 if (!thread->static_data || !thread->static_data [idx])
3850 ptr = ((char*) thread->static_data [idx]) + (data->offset & 0xffffff);
3851 memset (ptr, 0, data->size);
3855 do_free_special (gpointer key, gpointer value, gpointer data)
3857 MonoClassField *field = key;
3858 guint32 offset = GPOINTER_TO_UINT (value);
3859 guint32 static_type = (offset & 0x80000000);
3862 size = mono_type_size (field->type, &align);
3863 /*g_print ("free %s , size: %d, offset: %x\n", field->name, size, offset);*/
3864 if (static_type == 0) {
3866 MonoThreadDomainTls *item = g_new0 (MonoThreadDomainTls, 1);
3867 data.offset = offset & 0x7fffffff;
3869 clear_reference_bitmap (data.offset, data.size);
3870 if (threads != NULL)
3871 mono_g_hash_table_foreach (threads, free_thread_static_data_helper, &data);
3872 item->offset = offset;
3875 if (!mono_runtime_is_shutting_down ()) {
3876 item->next = thread_static_info.freelist;
3877 thread_static_info.freelist = item;
3879 /* We could be called during shutdown after mono_thread_cleanup () is called */
3883 /* FIXME: free context static data as well */
3888 mono_alloc_special_static_data_free (GHashTable *special_static_fields)
3890 mono_threads_lock ();
3891 g_hash_table_foreach (special_static_fields, do_free_special, NULL);
3892 mono_threads_unlock ();
3895 static MonoClassField *local_slots = NULL;
3898 /* local tls data to get locals_slot from a thread */
3901 /* index in the locals_slot array */
3906 clear_local_slot (gpointer key, gpointer value, gpointer user_data)
3908 LocalSlotID *sid = user_data;
3909 MonoInternalThread *thread = (MonoInternalThread*)value;
3910 MonoArray *slots_array;
3912 * the static field is stored at: ((char*) thread->static_data [idx]) + (offset & 0xffffff);
3913 * it is for the right domain, so we need to check if it is allocated an initialized
3914 * for the current thread.
3916 /*g_print ("handling thread %p\n", thread);*/
3917 if (!thread->static_data || !thread->static_data [sid->idx])
3919 slots_array = *(MonoArray **)(((char*) thread->static_data [sid->idx]) + (sid->offset & 0xffffff));
3920 if (!slots_array || sid->slot >= mono_array_length (slots_array))
3922 mono_array_set (slots_array, MonoObject*, sid->slot, NULL);
3926 mono_thread_free_local_slot_values (int slot, MonoBoolean thread_local)
3934 local_slots = mono_class_get_field_from_name (mono_defaults.thread_class, "local_slots");
3936 g_warning ("local_slots field not found in Thread class");
3940 domain = mono_domain_get ();
3941 mono_domain_lock (domain);
3942 if (domain->special_static_fields)
3943 addr = g_hash_table_lookup (domain->special_static_fields, local_slots);
3944 mono_domain_unlock (domain);
3947 /*g_print ("freeing slot %d at %p\n", slot, addr);*/
3948 sid.offset = GPOINTER_TO_UINT (addr);
3949 sid.offset &= 0x7fffffff;
3950 sid.idx = (sid.offset >> 24) - 1;
3951 mono_threads_lock ();
3952 mono_g_hash_table_foreach (threads, clear_local_slot, &sid);
3953 mono_threads_unlock ();
3955 /* FIXME: clear the slot for MonoAppContexts, too */
3960 static void CALLBACK dummy_apc (ULONG_PTR param)
3964 static guint32 dummy_apc (gpointer param)
3971 * mono_thread_execute_interruption
3973 * Performs the operation that the requested thread state requires (abort,
3976 static MonoException* mono_thread_execute_interruption (MonoInternalThread *thread)
3978 ensure_synch_cs_set (thread);
3980 EnterCriticalSection (thread->synch_cs);
3982 /* MonoThread::interruption_requested can only be changed with atomics */
3983 if (InterlockedCompareExchange (&thread->interruption_requested, FALSE, TRUE)) {
3984 /* this will consume pending APC calls */
3985 WaitForSingleObjectEx (GetCurrentThread(), 0, TRUE);
3986 InterlockedDecrement (&thread_interruption_requested);
3988 /* Clear the interrupted flag of the thread so it can wait again */
3989 wapi_clear_interruption ();
3993 if ((thread->state & ThreadState_AbortRequested) != 0) {
3994 LeaveCriticalSection (thread->synch_cs);
3995 if (thread->abort_exc == NULL) {
3997 * This might be racy, but it has to be called outside the lock
3998 * since it calls managed code.
4000 MONO_OBJECT_SETREF (thread, abort_exc, mono_get_exception_thread_abort ());
4002 return thread->abort_exc;
4004 else if ((thread->state & ThreadState_SuspendRequested) != 0) {
4005 thread->state &= ~ThreadState_SuspendRequested;
4006 thread->state |= ThreadState_Suspended;
4007 thread->suspend_event = CreateEvent (NULL, TRUE, FALSE, NULL);
4008 if (thread->suspend_event == NULL) {
4009 LeaveCriticalSection (thread->synch_cs);
4012 if (thread->suspended_event)
4013 SetEvent (thread->suspended_event);
4015 LeaveCriticalSection (thread->synch_cs);
4017 if (shutting_down) {
4018 /* After we left the lock, the runtime might shut down so everything becomes invalid */
4023 WaitForSingleObject (thread->suspend_event, INFINITE);
4025 EnterCriticalSection (thread->synch_cs);
4027 CloseHandle (thread->suspend_event);
4028 thread->suspend_event = NULL;
4029 thread->state &= ~ThreadState_Suspended;
4031 /* The thread that requested the resume will have replaced this event
4032 * and will be waiting for it
4034 SetEvent (thread->resume_event);
4036 LeaveCriticalSection (thread->synch_cs);
4040 else if ((thread->state & ThreadState_StopRequested) != 0) {
4041 /* FIXME: do this through the JIT? */
4043 LeaveCriticalSection (thread->synch_cs);
4045 mono_thread_exit ();
4047 } else if (thread->thread_interrupt_requested) {
4049 thread->thread_interrupt_requested = FALSE;
4050 LeaveCriticalSection (thread->synch_cs);
4052 return(mono_get_exception_thread_interrupted ());
4055 LeaveCriticalSection (thread->synch_cs);
4061 * mono_thread_request_interruption
4063 * A signal handler can call this method to request the interruption of a
4064 * thread. The result of the interruption will depend on the current state of
4065 * the thread. If the result is an exception that needs to be throw, it is
4066 * provided as return value.
4069 mono_thread_request_interruption (gboolean running_managed)
4071 MonoInternalThread *thread = mono_thread_internal_current ();
4073 /* The thread may already be stopping */
4078 if (thread->interrupt_on_stop &&
4079 thread->state & ThreadState_StopRequested &&
4080 thread->state & ThreadState_Background)
4084 if (InterlockedCompareExchange (&thread->interruption_requested, 1, 0) == 1)
4087 if (!running_managed || is_running_protected_wrapper ()) {
4088 /* Can't stop while in unmanaged code. Increase the global interruption
4089 request count. When exiting the unmanaged method the count will be
4090 checked and the thread will be interrupted. */
4092 InterlockedIncrement (&thread_interruption_requested);
4094 if (mono_thread_notify_pending_exc_fn && !running_managed)
4095 /* The JIT will notify the thread about the interruption */
4096 /* This shouldn't take any locks */
4097 mono_thread_notify_pending_exc_fn ();
4099 /* this will awake the thread if it is in WaitForSingleObject
4101 /* Our implementation of this function ignores the func argument */
4102 QueueUserAPC ((PAPCFUNC)dummy_apc, thread->handle, NULL);
4106 return mono_thread_execute_interruption (thread);
4110 /*This function should be called by a thread after it has exited all of
4111 * its handle blocks at interruption time.*/
4113 mono_thread_resume_interruption (void)
4115 MonoInternalThread *thread = mono_thread_internal_current ();
4116 gboolean still_aborting;
4118 /* The thread may already be stopping */
4122 ensure_synch_cs_set (thread);
4123 EnterCriticalSection (thread->synch_cs);
4124 still_aborting = (thread->state & ThreadState_AbortRequested) != 0;
4125 LeaveCriticalSection (thread->synch_cs);
4127 /*This can happen if the protected block called Thread::ResetAbort*/
4128 if (!still_aborting)
4131 if (InterlockedCompareExchange (&thread->interruption_requested, 1, 0) == 1)
4133 InterlockedIncrement (&thread_interruption_requested);
4136 wapi_self_interrupt ();
4138 return mono_thread_execute_interruption (thread);
4141 gboolean mono_thread_interruption_requested ()
4143 if (thread_interruption_requested) {
4144 MonoInternalThread *thread = mono_thread_internal_current ();
4145 /* The thread may already be stopping */
4147 return (thread->interruption_requested);
4152 static void mono_thread_interruption_checkpoint_request (gboolean bypass_abort_protection)
4154 MonoInternalThread *thread = mono_thread_internal_current ();
4156 /* The thread may already be stopping */
4160 mono_debugger_check_interruption ();
4162 if (thread->interruption_requested && (bypass_abort_protection || !is_running_protected_wrapper ())) {
4163 MonoException* exc = mono_thread_execute_interruption (thread);
4164 if (exc) mono_raise_exception (exc);
4169 * Performs the interruption of the current thread, if one has been requested,
4170 * and the thread is not running a protected wrapper.
4172 void mono_thread_interruption_checkpoint ()
4174 mono_thread_interruption_checkpoint_request (FALSE);
4178 * Performs the interruption of the current thread, if one has been requested.
4180 void mono_thread_force_interruption_checkpoint ()
4182 mono_thread_interruption_checkpoint_request (TRUE);
4186 * mono_thread_get_and_clear_pending_exception:
4188 * Return any pending exceptions for the current thread and clear it as a side effect.
4191 mono_thread_get_and_clear_pending_exception (void)
4193 MonoInternalThread *thread = mono_thread_internal_current ();
4195 /* The thread may already be stopping */
4199 if (thread->interruption_requested && !is_running_protected_wrapper ()) {
4200 return mono_thread_execute_interruption (thread);
4203 if (thread->pending_exception) {
4204 MonoException *exc = thread->pending_exception;
4206 thread->pending_exception = NULL;
4214 * mono_set_pending_exception:
4216 * Set the pending exception of the current thread to EXC. On platforms which
4217 * support it, the exception will be thrown when execution returns to managed code.
4218 * On other platforms, this function is equivalent to mono_raise_exception ().
4219 * Internal calls which report exceptions using this function instead of
4220 * raise_exception () might be called by JITted code using a more efficient calling
4224 mono_set_pending_exception (MonoException *exc)
4226 MonoInternalThread *thread = mono_thread_internal_current ();
4228 /* The thread may already be stopping */
4232 if (mono_thread_notify_pending_exc_fn) {
4233 MONO_OBJECT_SETREF (thread, pending_exception, exc);
4235 mono_thread_notify_pending_exc_fn ();
4237 /* No way to notify the JIT about the exception, have to throw it now */
4238 mono_raise_exception (exc);
4243 * mono_thread_interruption_request_flag:
4245 * Returns the address of a flag that will be non-zero if an interruption has
4246 * been requested for a thread. The thread to interrupt may not be the current
4247 * thread, so an additional call to mono_thread_interruption_requested() or
4248 * mono_thread_interruption_checkpoint() is allways needed if the flag is not
4251 gint32* mono_thread_interruption_request_flag ()
4253 return &thread_interruption_requested;
4257 mono_thread_init_apartment_state (void)
4260 MonoInternalThread* thread = mono_thread_internal_current ();
4262 /* Positive return value indicates success, either
4263 * S_OK if this is first CoInitialize call, or
4264 * S_FALSE if CoInitialize already called, but with same
4265 * threading model. A negative value indicates failure,
4266 * probably due to trying to change the threading model.
4268 if (CoInitializeEx(NULL, (thread->apartment_state == ThreadApartmentState_STA)
4269 ? COINIT_APARTMENTTHREADED
4270 : COINIT_MULTITHREADED) < 0) {
4271 thread->apartment_state = ThreadApartmentState_Unknown;
4277 mono_thread_cleanup_apartment_state (void)
4280 MonoInternalThread* thread = mono_thread_internal_current ();
4282 if (thread && thread->apartment_state != ThreadApartmentState_Unknown) {
4289 mono_thread_set_state (MonoInternalThread *thread, MonoThreadState state)
4291 ensure_synch_cs_set (thread);
4293 EnterCriticalSection (thread->synch_cs);
4294 thread->state |= state;
4295 LeaveCriticalSection (thread->synch_cs);
4299 mono_thread_clr_state (MonoInternalThread *thread, MonoThreadState state)
4301 ensure_synch_cs_set (thread);
4303 EnterCriticalSection (thread->synch_cs);
4304 thread->state &= ~state;
4305 LeaveCriticalSection (thread->synch_cs);
4309 mono_thread_test_state (MonoInternalThread *thread, MonoThreadState test)
4311 gboolean ret = FALSE;
4313 ensure_synch_cs_set (thread);
4315 EnterCriticalSection (thread->synch_cs);
4317 if ((thread->state & test) != 0) {
4321 LeaveCriticalSection (thread->synch_cs);
4326 static MonoClassField *execution_context_field;
4329 get_execution_context_addr (void)
4331 MonoDomain *domain = mono_domain_get ();
4334 if (!execution_context_field) {
4335 execution_context_field = mono_class_get_field_from_name (mono_defaults.thread_class,
4337 g_assert (execution_context_field);
4340 g_assert (mono_class_try_get_vtable (domain, mono_defaults.appdomain_class));
4342 mono_domain_lock (domain);
4343 offset = GPOINTER_TO_UINT (g_hash_table_lookup (domain->special_static_fields, execution_context_field));
4344 mono_domain_unlock (domain);
4347 return (MonoObject**) mono_get_special_static_data (offset);
4351 mono_thread_get_execution_context (void)
4353 return *get_execution_context_addr ();
4357 mono_thread_set_execution_context (MonoObject *ec)
4359 *get_execution_context_addr () = ec;
4362 static gboolean has_tls_get = FALSE;
4365 mono_runtime_set_has_tls_get (gboolean val)
4371 mono_runtime_has_tls_get (void)
4377 mono_thread_kill (MonoInternalThread *thread, int signal)
4380 /* Win32 uses QueueUserAPC and callers of this are guarded */
4381 g_assert_not_reached ();
4383 # ifdef PTHREAD_POINTER_ID
4384 return pthread_kill ((gpointer)(gsize)(thread->tid), mono_thread_get_abort_signal ());
4386 # ifdef PLATFORM_ANDROID
4387 if (thread->android_tid != 0) {
4389 int old_errno = errno;
4391 ret = tkill ((pid_t) thread->android_tid, signal);
4400 return pthread_kill (thread->tid, mono_thread_get_abort_signal ());
4402 return pthread_kill (thread->tid, mono_thread_get_abort_signal ());