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 /*#define THREAD_DEBUG(a) do { a; } while (0)*/
49 #define THREAD_DEBUG(a)
50 /*#define THREAD_WAIT_DEBUG(a) do { a; } while (0)*/
51 #define THREAD_WAIT_DEBUG(a)
52 /*#define LIBGC_DEBUG(a) do { a; } while (0)*/
53 #define LIBGC_DEBUG(a)
55 #define SPIN_TRYLOCK(i) (InterlockedCompareExchange (&(i), 1, 0) == 0)
56 #define SPIN_LOCK(i) do { \
57 if (SPIN_TRYLOCK (i)) \
61 #define SPIN_UNLOCK(i) i = 0
63 /* Provide this for systems with glib < 2.6 */
64 #ifndef G_GSIZE_FORMAT
65 # if GLIB_SIZEOF_LONG == 8
66 # define G_GSIZE_FORMAT "lu"
68 # define G_GSIZE_FORMAT "u"
74 guint32 (*func)(void *);
90 typedef struct _MonoThreadDomainTls MonoThreadDomainTls;
91 struct _MonoThreadDomainTls {
92 MonoThreadDomainTls *next;
100 MonoThreadDomainTls *freelist;
105 MonoHazardousFreeFunc free_func;
108 /* Number of cached culture objects in the MonoThread->cached_culture_info array
109 * (per-type): we use the first NUM entries for CultureInfo and the last for
110 * UICultureInfo. So the size of the array is really NUM_CACHED_CULTURES * 2.
112 #define NUM_CACHED_CULTURES 4
113 #define CULTURES_START_IDX 0
114 #define UICULTURES_START_IDX NUM_CACHED_CULTURES
116 /* Controls access to the 'threads' hash table */
117 #define mono_threads_lock() EnterCriticalSection (&threads_mutex)
118 #define mono_threads_unlock() LeaveCriticalSection (&threads_mutex)
119 static CRITICAL_SECTION threads_mutex;
121 /* Controls access to context static data */
122 #define mono_contexts_lock() EnterCriticalSection (&contexts_mutex)
123 #define mono_contexts_unlock() LeaveCriticalSection (&contexts_mutex)
124 static CRITICAL_SECTION contexts_mutex;
126 /* Holds current status of static data heap */
127 static StaticDataInfo thread_static_info;
128 static StaticDataInfo context_static_info;
130 /* The hash of existing threads (key is thread ID, value is
131 * MonoInternalThread*) that need joining before exit
133 static MonoGHashTable *threads=NULL;
136 * Threads which are starting up and they are not in the 'threads' hash yet.
137 * When handle_store is called for a thread, it will be removed from this hash table.
138 * Protected by mono_threads_lock ().
140 static MonoGHashTable *threads_starting_up = NULL;
142 /* Maps a MonoThread to its start argument */
143 /* Protected by mono_threads_lock () */
144 static MonoGHashTable *thread_start_args = NULL;
146 /* The TLS key that holds the MonoObject assigned to each thread */
147 static guint32 current_object_key = -1;
149 #ifdef HAVE_KW_THREAD
150 /* we need to use both the Tls* functions and __thread because
151 * the gc needs to see all the threads
153 static __thread MonoInternalThread * tls_current_object MONO_TLS_FAST;
154 #define SET_CURRENT_OBJECT(x) do { \
155 tls_current_object = x; \
156 TlsSetValue (current_object_key, x); \
158 #define GET_CURRENT_OBJECT() tls_current_object
160 #define SET_CURRENT_OBJECT(x) TlsSetValue (current_object_key, x)
161 #define GET_CURRENT_OBJECT() (MonoThread*) TlsGetValue (current_object_key)
164 /* function called at thread start */
165 static MonoThreadStartCB mono_thread_start_cb = NULL;
167 /* function called at thread attach */
168 static MonoThreadAttachCB mono_thread_attach_cb = NULL;
170 /* function called at thread cleanup */
171 static MonoThreadCleanupFunc mono_thread_cleanup_fn = NULL;
173 /* function called to notify the runtime about a pending exception on the current thread */
174 static MonoThreadNotifyPendingExcFunc mono_thread_notify_pending_exc_fn = NULL;
176 /* The default stack size for each thread */
177 static guint32 default_stacksize = 0;
178 #define default_stacksize_for_thread(thread) ((thread)->stack_size? (thread)->stack_size: default_stacksize)
180 static void thread_adjust_static_data (MonoInternalThread *thread);
181 static void mono_free_static_data (gpointer* static_data, gboolean threadlocal);
182 static void mono_init_static_data_info (StaticDataInfo *static_data);
183 static guint32 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align);
184 static gboolean mono_thread_resume (MonoInternalThread* thread);
185 static void mono_thread_start (MonoThread *thread);
186 static void signal_thread_state_change (MonoInternalThread *thread);
188 static MonoException* mono_thread_execute_interruption (MonoInternalThread *thread);
190 /* Spin lock for InterlockedXXX 64 bit functions */
191 #define mono_interlocked_lock() EnterCriticalSection (&interlocked_mutex)
192 #define mono_interlocked_unlock() LeaveCriticalSection (&interlocked_mutex)
193 static CRITICAL_SECTION interlocked_mutex;
195 /* global count of thread interruptions requested */
196 static gint32 thread_interruption_requested = 0;
198 /* Event signaled when a thread changes its background mode */
199 static HANDLE background_change_event;
201 /* The table for small ID assignment */
202 static CRITICAL_SECTION small_id_mutex;
203 static int small_id_table_size = 0;
204 static int small_id_next = 0;
205 static int highest_small_id = -1;
206 static MonoInternalThread **small_id_table = NULL;
208 /* The hazard table */
209 #if MONO_SMALL_CONFIG
210 #define HAZARD_TABLE_MAX_SIZE 256
212 #define HAZARD_TABLE_MAX_SIZE 16384 /* There cannot be more threads than this number. */
214 static volatile int hazard_table_size = 0;
215 static MonoThreadHazardPointers * volatile hazard_table = NULL;
217 /* The table where we keep pointers to blocks to be freed but that
218 have to wait because they're guarded by a hazard pointer. */
219 static CRITICAL_SECTION delayed_free_table_mutex;
220 static GArray *delayed_free_table = NULL;
222 static gboolean shutting_down = FALSE;
225 mono_thread_get_tls_key (void)
227 return current_object_key;
231 mono_thread_get_tls_offset (void)
234 MONO_THREAD_VAR_OFFSET (tls_current_object,offset);
238 /* handle_store() and handle_remove() manage the array of threads that
239 * still need to be waited for when the main thread exits.
241 * If handle_store() returns FALSE the thread must not be started
242 * because Mono is shutting down.
244 static gboolean handle_store(MonoThread *thread)
246 mono_threads_lock ();
248 THREAD_DEBUG (g_message ("%s: thread %p ID %"G_GSIZE_FORMAT, __func__, thread, (gsize)thread->tid));
250 if (threads_starting_up)
251 mono_g_hash_table_remove (threads_starting_up, thread);
254 mono_threads_unlock ();
259 MONO_GC_REGISTER_ROOT (threads);
260 threads=mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
263 /* We don't need to duplicate thread->handle, because it is
264 * only closed when the thread object is finalized by the GC.
266 g_assert (thread->internal_thread);
267 mono_g_hash_table_insert(threads, (gpointer)(gsize)(thread->internal_thread->tid),
268 thread->internal_thread);
270 mono_threads_unlock ();
275 static gboolean handle_remove(MonoInternalThread *thread)
278 gsize tid = thread->tid;
280 THREAD_DEBUG (g_message ("%s: thread ID %"G_GSIZE_FORMAT, __func__, tid));
282 mono_threads_lock ();
285 /* We have to check whether the thread object for the
286 * tid is still the same in the table because the
287 * thread might have been destroyed and the tid reused
288 * in the meantime, in which case the tid would be in
289 * the table, but with another thread object.
291 if (mono_g_hash_table_lookup (threads, (gpointer)tid) == thread) {
292 mono_g_hash_table_remove (threads, (gpointer)tid);
301 mono_threads_unlock ();
303 /* Don't close the handle here, wait for the object finalizer
304 * to do it. Otherwise, the following race condition applies:
306 * 1) Thread exits (and handle_remove() closes the handle)
308 * 2) Some other handle is reassigned the same slot
310 * 3) Another thread tries to join the first thread, and
311 * blocks waiting for the reassigned handle to be signalled
312 * (which might never happen). This is possible, because the
313 * thread calling Join() still has a reference to the first
320 * Allocate a small thread id.
322 * FIXME: The biggest part of this function is very similar to
323 * domain_id_alloc() in domain.c and should be merged.
326 small_id_alloc (MonoInternalThread *thread)
330 EnterCriticalSection (&small_id_mutex);
332 if (!small_id_table) {
333 small_id_table_size = 2;
334 small_id_table = mono_gc_alloc_fixed (small_id_table_size * sizeof (MonoInternalThread*), NULL);
336 for (i = small_id_next; i < small_id_table_size; ++i) {
337 if (!small_id_table [i]) {
343 for (i = 0; i < small_id_next; ++i) {
344 if (!small_id_table [i]) {
351 MonoInternalThread **new_table;
352 int new_size = small_id_table_size * 2;
353 if (new_size >= (1 << 16))
354 g_assert_not_reached ();
355 id = small_id_table_size;
356 new_table = mono_gc_alloc_fixed (new_size * sizeof (MonoInternalThread*), NULL);
357 memcpy (new_table, small_id_table, small_id_table_size * sizeof (void*));
358 mono_gc_free_fixed (small_id_table);
359 small_id_table = new_table;
360 small_id_table_size = new_size;
362 thread->small_id = id;
363 g_assert (small_id_table [id] == NULL);
364 small_id_table [id] = thread;
366 if (small_id_next > small_id_table_size)
369 g_assert (id < HAZARD_TABLE_MAX_SIZE);
370 if (id >= hazard_table_size) {
371 #if MONO_SMALL_CONFIG
372 hazard_table = g_malloc0 (sizeof (MonoThreadHazardPointers) * HAZARD_TABLE_MAX_SIZE);
373 hazard_table_size = HAZARD_TABLE_MAX_SIZE;
376 int pagesize = mono_pagesize ();
377 int num_pages = (hazard_table_size * sizeof (MonoThreadHazardPointers) + pagesize - 1) / pagesize;
379 if (hazard_table == NULL) {
380 hazard_table = mono_valloc (NULL,
381 sizeof (MonoThreadHazardPointers) * HAZARD_TABLE_MAX_SIZE,
385 g_assert (hazard_table != NULL);
386 page_addr = (guint8*)hazard_table + num_pages * pagesize;
388 mono_mprotect (page_addr, pagesize, MONO_MMAP_READ | MONO_MMAP_WRITE);
391 hazard_table_size = num_pages * pagesize / sizeof (MonoThreadHazardPointers);
394 g_assert (id < hazard_table_size);
395 hazard_table [id].hazard_pointers [0] = NULL;
396 hazard_table [id].hazard_pointers [1] = NULL;
399 if (id > highest_small_id) {
400 highest_small_id = id;
401 mono_memory_write_barrier ();
404 LeaveCriticalSection (&small_id_mutex);
410 small_id_free (int id)
412 g_assert (id >= 0 && id < small_id_table_size);
413 g_assert (small_id_table [id] != NULL);
415 small_id_table [id] = NULL;
419 is_pointer_hazardous (gpointer p)
422 int highest = highest_small_id;
424 g_assert (highest < hazard_table_size);
426 for (i = 0; i <= highest; ++i) {
427 if (hazard_table [i].hazard_pointers [0] == p
428 || hazard_table [i].hazard_pointers [1] == p)
435 MonoThreadHazardPointers*
436 mono_hazard_pointer_get (void)
438 MonoInternalThread *current_thread = mono_thread_internal_current ();
440 if (!(current_thread && current_thread->small_id >= 0)) {
441 static MonoThreadHazardPointers emerg_hazard_table;
442 g_warning ("Thread %p may have been prematurely finalized", current_thread);
443 return &emerg_hazard_table;
446 return &hazard_table [current_thread->small_id];
450 try_free_delayed_free_item (int index)
452 if (delayed_free_table->len > index) {
453 DelayedFreeItem item = { NULL, NULL };
455 EnterCriticalSection (&delayed_free_table_mutex);
456 /* We have to check the length again because another
457 thread might have freed an item before we acquired
459 if (delayed_free_table->len > index) {
460 item = g_array_index (delayed_free_table, DelayedFreeItem, index);
462 if (!is_pointer_hazardous (item.p))
463 g_array_remove_index_fast (delayed_free_table, index);
467 LeaveCriticalSection (&delayed_free_table_mutex);
470 item.free_func (item.p);
475 mono_thread_hazardous_free_or_queue (gpointer p, MonoHazardousFreeFunc free_func)
479 /* First try to free a few entries in the delayed free
481 for (i = 2; i >= 0; --i)
482 try_free_delayed_free_item (i);
484 /* Now see if the pointer we're freeing is hazardous. If it
485 isn't, free it. Otherwise put it in the delay list. */
486 if (is_pointer_hazardous (p)) {
487 DelayedFreeItem item = { p, free_func };
489 ++mono_stats.hazardous_pointer_count;
491 EnterCriticalSection (&delayed_free_table_mutex);
492 g_array_append_val (delayed_free_table, item);
493 LeaveCriticalSection (&delayed_free_table_mutex);
499 mono_thread_hazardous_try_free_all (void)
504 if (!delayed_free_table)
507 len = delayed_free_table->len;
509 for (i = len - 1; i >= 0; --i)
510 try_free_delayed_free_item (i);
513 static void ensure_synch_cs_set (MonoInternalThread *thread)
515 CRITICAL_SECTION *synch_cs;
517 if (thread->synch_cs != NULL) {
521 synch_cs = g_new0 (CRITICAL_SECTION, 1);
522 InitializeCriticalSection (synch_cs);
524 if (InterlockedCompareExchangePointer ((gpointer *)&thread->synch_cs,
525 synch_cs, NULL) != NULL) {
526 /* Another thread must have installed this CS */
527 DeleteCriticalSection (synch_cs);
533 * NOTE: this function can be called also for threads different from the current one:
534 * make sure no code called from it will ever assume it is run on the thread that is
535 * getting cleaned up.
537 static void thread_cleanup (MonoInternalThread *thread)
539 g_assert (thread != NULL);
541 if (thread->abort_state_handle) {
542 mono_gchandle_free (thread->abort_state_handle);
543 thread->abort_state_handle = 0;
545 thread->abort_exc = NULL;
546 thread->current_appcontext = NULL;
549 * This is necessary because otherwise we might have
550 * cross-domain references which will not get cleaned up when
551 * the target domain is unloaded.
553 if (thread->cached_culture_info) {
555 for (i = 0; i < NUM_CACHED_CULTURES * 2; ++i)
556 mono_array_set (thread->cached_culture_info, MonoObject*, i, NULL);
559 if (mono_thread_cleanup_fn)
560 mono_thread_cleanup_fn (thread);
562 /* if the thread is not in the hash it has been removed already */
563 if (!handle_remove (thread))
565 mono_release_type_locks (thread);
567 EnterCriticalSection (thread->synch_cs);
569 thread->state |= ThreadState_Stopped;
570 thread->state &= ~ThreadState_Background;
572 LeaveCriticalSection (thread->synch_cs);
574 mono_profiler_thread_end (thread->tid);
576 if (thread == mono_thread_internal_current ())
577 mono_thread_pop_appdomain_ref ();
579 thread->cached_culture_info = NULL;
581 mono_free_static_data (thread->static_data, TRUE);
582 thread->static_data = NULL;
584 small_id_free (thread->small_id);
585 thread->small_id = -2;
589 get_thread_static_data (MonoInternalThread *thread, guint32 offset)
592 g_assert ((offset & 0x80000000) == 0);
593 offset &= 0x7fffffff;
594 idx = (offset >> 24) - 1;
595 return ((char*) thread->static_data [idx]) + (offset & 0xffffff);
599 get_current_thread_ptr_for_domain (MonoDomain *domain, MonoInternalThread *thread)
601 static MonoClassField *current_thread_field = NULL;
605 if (!current_thread_field) {
606 current_thread_field = mono_class_get_field_from_name (mono_defaults.thread_class, "current_thread");
607 g_assert (current_thread_field);
610 mono_class_vtable (domain, mono_defaults.thread_class);
611 mono_domain_lock (domain);
612 offset = GPOINTER_TO_UINT (g_hash_table_lookup (domain->special_static_fields, current_thread_field));
613 mono_domain_unlock (domain);
616 return get_thread_static_data (thread, offset);
620 set_current_thread_for_domain (MonoDomain *domain, MonoInternalThread *thread, MonoThread *current)
622 MonoThread **current_thread_ptr = get_current_thread_ptr_for_domain (domain, thread);
624 g_assert (current->obj.vtable->domain == domain);
626 g_assert (!*current_thread_ptr);
627 *current_thread_ptr = current;
631 new_thread_with_internal (MonoDomain *domain, MonoInternalThread *internal)
633 MonoThread *thread = (MonoThread*) mono_object_new (domain, mono_defaults.thread_class);
634 MONO_OBJECT_SETREF (thread, internal_thread, internal);
639 init_root_domain_thread (MonoInternalThread *thread, MonoThread *candidate)
641 MonoDomain *domain = mono_get_root_domain ();
643 if (!candidate || candidate->obj.vtable->domain != domain)
644 candidate = new_thread_with_internal (domain, thread);
645 set_current_thread_for_domain (domain, thread, candidate);
646 g_assert (!thread->root_domain_thread);
647 MONO_OBJECT_SETREF (thread, root_domain_thread, candidate);
650 static guint32 WINAPI start_wrapper(void *data)
652 struct StartInfo *start_info=(struct StartInfo *)data;
653 guint32 (*start_func)(void *);
656 MonoThread *thread=start_info->obj;
657 MonoInternalThread *internal = thread->internal_thread;
658 MonoObject *start_delegate = start_info->delegate;
660 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Start wrapper", __func__, GetCurrentThreadId ()));
662 /* We can be sure start_info->obj->tid and
663 * start_info->obj->handle have been set, because the thread
664 * was created suspended, and these values were set before the
670 SET_CURRENT_OBJECT (internal);
672 mono_monitor_init_tls ();
674 /* Every thread references the appdomain which created it */
675 mono_thread_push_appdomain_ref (thread->obj.vtable->domain);
677 if (!mono_domain_set (thread->obj.vtable->domain, FALSE)) {
678 /* No point in raising an appdomain_unloaded exception here */
679 /* FIXME: Cleanup here */
680 mono_thread_pop_appdomain_ref ();
684 start_func = start_info->func;
685 start_arg = start_info->start_arg;
687 /* We have to do this here because mono_thread_new_init()
688 requires that root_domain_thread is set up. */
689 thread_adjust_static_data (internal);
690 init_root_domain_thread (internal, thread);
692 /* This MUST be called before any managed code can be
693 * executed, as it calls the callback function that (for the
694 * jit) sets the lmf marker.
696 mono_thread_new_init (tid, &tid, start_func);
697 internal->stack_ptr = &tid;
699 LIBGC_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT",%d) Setting thread stack to %p", __func__, GetCurrentThreadId (), getpid (), thread->stack_ptr));
701 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Setting current_object_key to %p", __func__, GetCurrentThreadId (), thread));
703 /* On 2.0 profile (and higher), set explicitly since state might have been
705 if (internal->apartment_state == ThreadApartmentState_Unknown)
706 internal->apartment_state = ThreadApartmentState_MTA;
708 mono_thread_init_apartment_state ();
710 if(internal->start_notify!=NULL) {
711 /* Let the thread that called Start() know we're
714 ReleaseSemaphore (internal->start_notify, 1, NULL);
717 mono_threads_lock ();
718 mono_g_hash_table_remove (thread_start_args, thread);
719 mono_threads_unlock ();
723 g_message ("%s: start_wrapper for %"G_GSIZE_FORMAT, __func__,
727 mono_thread_set_execution_context (thread->ec_to_set);
728 thread->ec_to_set = NULL;
731 * Call this after calling start_notify, since the profiler callback might want
732 * to lock the thread, and the lock is held by thread_start () which waits for
735 mono_profiler_thread_start (tid);
737 /* start_func is set only for unmanaged start functions */
739 start_func (start_arg);
742 g_assert (start_delegate != NULL);
743 args [0] = start_arg;
744 /* we may want to handle the exception here. See comment below on unhandled exceptions */
745 mono_runtime_delegate_invoke (start_delegate, args, NULL);
748 /* If the thread calls ExitThread at all, this remaining code
749 * will not be executed, but the main thread will eventually
750 * call thread_cleanup() on this thread's behalf.
753 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Start wrapper terminating", __func__, GetCurrentThreadId ()));
755 thread_cleanup (internal);
757 /* Do any cleanup needed for apartment state. This
758 * cannot be done in thread_cleanup since thread_cleanup could be
759 * called for a thread other than the current thread.
760 * mono_thread_cleanup_apartment_state cleans up apartment
761 * for the current thead */
762 mono_thread_cleanup_apartment_state ();
764 /* Remove the reference to the thread object in the TLS data,
765 * so the thread object can be finalized. This won't be
766 * reached if the thread threw an uncaught exception, so those
767 * thread handles will stay referenced :-( (This is due to
768 * missing support for scanning thread-specific data in the
769 * Boehm GC - the io-layer keeps a GC-visible hash of pointers
772 SET_CURRENT_OBJECT (NULL);
773 mono_domain_unset ();
778 void mono_thread_new_init (intptr_t tid, gpointer stack_start, gpointer func)
780 if (mono_thread_start_cb) {
781 mono_thread_start_cb (tid, stack_start, func);
785 void mono_threads_set_default_stacksize (guint32 stacksize)
787 default_stacksize = stacksize;
790 guint32 mono_threads_get_default_stacksize (void)
792 return default_stacksize;
796 * mono_create_thread:
798 * This is a wrapper around CreateThread which handles differences in the type of
799 * the the 'tid' argument.
801 gpointer mono_create_thread (WapiSecurityAttributes *security,
802 guint32 stacksize, WapiThreadStart start,
803 gpointer param, guint32 create, gsize *tid)
810 res = CreateThread (security, stacksize, start, param, create, &real_tid);
814 res = CreateThread (security, stacksize, start, param, create, tid);
821 * The thread start argument may be an object reference, and there is
822 * no ref to keep it alive when the new thread is started but not yet
823 * registered with the collector. So we store it in a GC tracked hash
826 * LOCKING: Assumes the threads lock is held.
829 register_thread_start_argument (MonoThread *thread, struct StartInfo *start_info)
831 if (thread_start_args == NULL) {
832 MONO_GC_REGISTER_ROOT (thread_start_args);
833 thread_start_args = mono_g_hash_table_new (NULL, NULL);
835 mono_g_hash_table_insert (thread_start_args, thread, start_info->start_arg);
838 MonoInternalThread* mono_thread_create_internal (MonoDomain *domain, gpointer func, gpointer arg, gboolean threadpool_thread)
841 MonoInternalThread *internal;
842 HANDLE thread_handle;
843 struct StartInfo *start_info;
846 thread=(MonoThread *)mono_object_new (domain,
847 mono_defaults.thread_class);
848 internal = (MonoInternalThread*)mono_object_new (mono_get_root_domain (),
849 mono_defaults.internal_thread_class);
850 MONO_OBJECT_SETREF (thread, internal_thread, internal);
852 start_info=g_new0 (struct StartInfo, 1);
853 start_info->func = func;
854 start_info->obj = thread;
855 start_info->start_arg = arg;
857 mono_threads_lock ();
859 mono_threads_unlock ();
863 if (threads_starting_up == NULL) {
864 MONO_GC_REGISTER_ROOT (threads_starting_up);
865 threads_starting_up = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_VALUE_GC);
868 register_thread_start_argument (thread, start_info);
869 mono_g_hash_table_insert (threads_starting_up, thread, thread);
870 mono_threads_unlock ();
872 /* Create suspended, so we can do some housekeeping before the thread
875 thread_handle = mono_create_thread (NULL, default_stacksize_for_thread (internal), (LPTHREAD_START_ROUTINE)start_wrapper, start_info,
876 CREATE_SUSPENDED, &tid);
877 THREAD_DEBUG (g_message ("%s: Started thread ID %"G_GSIZE_FORMAT" (handle %p)", __func__, tid, thread_handle));
878 if (thread_handle == NULL) {
879 /* The thread couldn't be created, so throw an exception */
880 mono_threads_lock ();
881 mono_g_hash_table_remove (threads_starting_up, thread);
882 mono_threads_unlock ();
884 mono_raise_exception (mono_get_exception_execution_engine ("Couldn't create thread"));
888 internal->handle=thread_handle;
890 internal->apartment_state=ThreadApartmentState_Unknown;
891 small_id_alloc (internal);
893 internal->synch_cs = g_new0 (CRITICAL_SECTION, 1);
894 InitializeCriticalSection (internal->synch_cs);
896 internal->threadpool_thread = threadpool_thread;
897 if (threadpool_thread)
898 mono_thread_set_state (internal, ThreadState_Background);
900 if (handle_store (thread))
901 ResumeThread (thread_handle);
907 mono_thread_create (MonoDomain *domain, gpointer func, gpointer arg)
909 mono_thread_create_internal (domain, func, arg, FALSE);
913 * mono_thread_get_stack_bounds:
915 * Return the address and size of the current threads stack. Return NULL as the
916 * stack address if the stack address cannot be determined.
919 mono_thread_get_stack_bounds (guint8 **staddr, size_t *stsize)
921 #if defined(HAVE_PTHREAD_GET_STACKSIZE_NP) && defined(HAVE_PTHREAD_GET_STACKADDR_NP)
922 *staddr = (guint8*)pthread_get_stackaddr_np (pthread_self ());
923 *stsize = pthread_get_stacksize_np (pthread_self ());
924 *staddr = (guint8*)((gssize)*staddr & ~(mono_pagesize () - 1));
926 /* FIXME: simplify the mess below */
927 #elif !defined(HOST_WIN32)
929 guint8 *current = (guint8*)&attr;
931 pthread_attr_init (&attr);
932 # ifdef HAVE_PTHREAD_GETATTR_NP
933 pthread_getattr_np (pthread_self(), &attr);
935 # ifdef HAVE_PTHREAD_ATTR_GET_NP
936 pthread_attr_get_np (pthread_self(), &attr);
939 pthread_attr_getstacksize (&attr, &stsize);
940 # elif defined(__OpenBSD__)
944 rslt = pthread_stackseg_np(pthread_self(), &ss);
945 g_assert (rslt == 0);
947 *staddr = (guint8*)((size_t)ss.ss_sp - ss.ss_size);
948 *stsize = ss.ss_size;
957 # if !defined(__OpenBSD__)
958 pthread_attr_getstack (&attr, (void**)staddr, stsize);
961 g_assert ((current > *staddr) && (current < *staddr + *stsize));
964 pthread_attr_destroy (&attr);
967 /* When running under emacs, sometimes staddr is not aligned to a page size */
968 *staddr = (guint8*)((gssize)*staddr & ~(mono_pagesize () - 1));
972 mono_thread_attach (MonoDomain *domain)
974 MonoInternalThread *thread;
975 MonoThread *current_thread;
976 HANDLE thread_handle;
979 if ((thread = mono_thread_internal_current ())) {
980 if (domain != mono_domain_get ())
981 mono_domain_set (domain, TRUE);
982 /* Already attached */
983 return mono_thread_current ();
986 if (!mono_gc_register_thread (&domain)) {
987 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 ());
990 thread = (MonoInternalThread *)mono_object_new (domain, mono_defaults.internal_thread_class);
992 thread_handle = GetCurrentThread ();
993 g_assert (thread_handle);
995 tid=GetCurrentThreadId ();
998 * The handle returned by GetCurrentThread () is a pseudo handle, so it can't be used to
999 * refer to the thread from other threads for things like aborting.
1001 DuplicateHandle (GetCurrentProcess (), thread_handle, GetCurrentProcess (), &thread_handle,
1002 THREAD_ALL_ACCESS, TRUE, 0);
1004 thread->handle=thread_handle;
1006 thread->apartment_state=ThreadApartmentState_Unknown;
1007 small_id_alloc (thread);
1008 thread->stack_ptr = &tid;
1010 thread->synch_cs = g_new0 (CRITICAL_SECTION, 1);
1011 InitializeCriticalSection (thread->synch_cs);
1013 THREAD_DEBUG (g_message ("%s: Attached thread ID %"G_GSIZE_FORMAT" (handle %p)", __func__, tid, thread_handle));
1015 current_thread = new_thread_with_internal (domain, thread);
1017 if (!handle_store (current_thread)) {
1018 /* Mono is shutting down, so just wait for the end */
1023 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Setting current_object_key to %p", __func__, GetCurrentThreadId (), thread));
1025 SET_CURRENT_OBJECT (thread);
1026 mono_domain_set (domain, TRUE);
1028 mono_monitor_init_tls ();
1030 thread_adjust_static_data (thread);
1032 init_root_domain_thread (thread, current_thread);
1033 if (domain != mono_get_root_domain ())
1034 set_current_thread_for_domain (domain, thread, current_thread);
1037 if (mono_thread_attach_cb) {
1041 mono_thread_get_stack_bounds (&staddr, &stsize);
1044 mono_thread_attach_cb (tid, &tid);
1046 mono_thread_attach_cb (tid, staddr + stsize);
1049 // FIXME: Need a separate callback
1050 mono_profiler_thread_start (tid);
1052 return current_thread;
1056 mono_thread_detach (MonoThread *thread)
1058 g_return_if_fail (thread != NULL);
1060 THREAD_DEBUG (g_message ("%s: mono_thread_detach for %p (%"G_GSIZE_FORMAT")", __func__, thread, (gsize)thread->tid));
1062 thread_cleanup (thread->internal_thread);
1064 SET_CURRENT_OBJECT (NULL);
1065 mono_domain_unset ();
1067 /* Don't need to CloseHandle this thread, even though we took a
1068 * reference in mono_thread_attach (), because the GC will do it
1069 * when the Thread object is finalised.
1076 MonoInternalThread *thread = mono_thread_internal_current ();
1078 THREAD_DEBUG (g_message ("%s: mono_thread_exit for %p (%"G_GSIZE_FORMAT")", __func__, thread, (gsize)thread->tid));
1080 thread_cleanup (thread);
1081 SET_CURRENT_OBJECT (NULL);
1082 mono_domain_unset ();
1084 /* we could add a callback here for embedders to use. */
1085 if (mono_thread_get_main () && (thread == mono_thread_get_main ()->internal_thread))
1086 exit (mono_environment_exitcode_get ());
1091 ves_icall_System_Threading_Thread_ConstructInternalThread (MonoThread *this)
1093 MonoInternalThread *internal = (MonoInternalThread*)mono_object_new (mono_get_root_domain (), mono_defaults.internal_thread_class);
1094 internal->state = ThreadState_Unstarted;
1095 internal->apartment_state = ThreadApartmentState_Unknown;
1097 InterlockedCompareExchangePointer ((gpointer)&this->internal_thread, internal, NULL);
1100 HANDLE ves_icall_System_Threading_Thread_Thread_internal(MonoThread *this,
1103 guint32 (*start_func)(void *);
1104 struct StartInfo *start_info;
1107 MonoInternalThread *internal;
1109 THREAD_DEBUG (g_message("%s: Trying to start a new thread: this (%p) start (%p)", __func__, this, start));
1111 if (!this->internal_thread)
1112 ves_icall_System_Threading_Thread_ConstructInternalThread (this);
1113 internal = this->internal_thread;
1115 ensure_synch_cs_set (internal);
1117 EnterCriticalSection (internal->synch_cs);
1119 if ((internal->state & ThreadState_Unstarted) == 0) {
1120 LeaveCriticalSection (internal->synch_cs);
1121 mono_raise_exception (mono_get_exception_thread_state ("Thread has already been started."));
1125 internal->small_id = -1;
1127 if ((internal->state & ThreadState_Aborted) != 0) {
1128 LeaveCriticalSection (internal->synch_cs);
1133 /* This is freed in start_wrapper */
1134 start_info = g_new0 (struct StartInfo, 1);
1135 start_info->func = start_func;
1136 start_info->start_arg = this->start_obj; /* FIXME: GC object stored in unmanaged memory */
1137 start_info->delegate = start;
1138 start_info->obj = this;
1139 g_assert (this->obj.vtable->domain == mono_domain_get ());
1141 internal->start_notify=CreateSemaphore (NULL, 0, 0x7fffffff, NULL);
1142 if (internal->start_notify==NULL) {
1143 LeaveCriticalSection (internal->synch_cs);
1144 g_warning ("%s: CreateSemaphore error 0x%x", __func__, GetLastError ());
1145 g_free (start_info);
1149 mono_threads_lock ();
1150 register_thread_start_argument (this, start_info);
1151 if (threads_starting_up == NULL) {
1152 MONO_GC_REGISTER_ROOT (threads_starting_up);
1153 threads_starting_up = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_VALUE_GC);
1155 mono_g_hash_table_insert (threads_starting_up, this, this);
1156 mono_threads_unlock ();
1158 thread=mono_create_thread(NULL, default_stacksize_for_thread (internal), (LPTHREAD_START_ROUTINE)start_wrapper, start_info,
1159 CREATE_SUSPENDED, &tid);
1161 LeaveCriticalSection (internal->synch_cs);
1162 mono_threads_lock ();
1163 mono_g_hash_table_remove (threads_starting_up, this);
1164 mono_threads_unlock ();
1165 g_warning("%s: CreateThread error 0x%x", __func__, GetLastError());
1169 internal->handle=thread;
1171 small_id_alloc (internal);
1173 /* Don't call handle_store() here, delay it to Start.
1174 * We can't join a thread (trying to will just block
1175 * forever) until it actually starts running, so don't
1176 * store the handle till then.
1179 mono_thread_start (this);
1181 internal->state &= ~ThreadState_Unstarted;
1183 THREAD_DEBUG (g_message ("%s: Started thread ID %"G_GSIZE_FORMAT" (handle %p)", __func__, tid, thread));
1185 LeaveCriticalSection (internal->synch_cs);
1190 void ves_icall_System_Threading_InternalThread_Thread_free_internal (MonoInternalThread *this, HANDLE thread)
1192 MONO_ARCH_SAVE_REGS;
1194 THREAD_DEBUG (g_message ("%s: Closing thread %p, handle %p", __func__, this, thread));
1197 CloseHandle (thread);
1199 if (this->synch_cs) {
1200 DeleteCriticalSection (this->synch_cs);
1201 g_free (this->synch_cs);
1202 this->synch_cs = NULL;
1205 g_free (this->name);
1208 static void mono_thread_start (MonoThread *thread)
1210 MonoInternalThread *internal = thread->internal_thread;
1212 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Launching thread %p (%"G_GSIZE_FORMAT")", __func__, GetCurrentThreadId (), thread, (gsize)thread->tid));
1214 /* Only store the handle when the thread is about to be
1215 * launched, to avoid the main thread deadlocking while trying
1216 * to clean up a thread that will never be signalled.
1218 if (!handle_store (thread))
1221 ResumeThread (internal->handle);
1223 if(internal->start_notify!=NULL) {
1224 /* Wait for the thread to set up its TLS data etc, so
1225 * theres no potential race condition if someone tries
1226 * to look up the data believing the thread has
1230 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") waiting for thread %p (%"G_GSIZE_FORMAT") to start", __func__, GetCurrentThreadId (), thread, (gsize)thread->tid));
1232 WaitForSingleObjectEx (internal->start_notify, INFINITE, FALSE);
1233 CloseHandle (internal->start_notify);
1234 internal->start_notify = NULL;
1237 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Done launching thread %p (%"G_GSIZE_FORMAT")", __func__, GetCurrentThreadId (), thread, (gsize)thread->tid));
1240 void ves_icall_System_Threading_Thread_Sleep_internal(gint32 ms)
1243 MonoInternalThread *thread = mono_thread_internal_current ();
1245 THREAD_DEBUG (g_message ("%s: Sleeping for %d ms", __func__, ms));
1247 mono_thread_current_check_pending_interrupt ();
1249 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1251 res = SleepEx(ms,TRUE);
1253 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1255 if (res == WAIT_IO_COMPLETION) { /* we might have been interrupted */
1256 MonoException* exc = mono_thread_execute_interruption (thread);
1257 if (exc) mono_raise_exception (exc);
1261 void ves_icall_System_Threading_Thread_SpinWait_nop (void)
1266 ves_icall_System_Threading_Thread_GetDomainID (void)
1268 MONO_ARCH_SAVE_REGS;
1270 return mono_domain_get()->domain_id;
1274 ves_icall_System_Threading_Thread_Yield (void)
1277 return SwitchToThread ();
1279 return sched_yield () == 0;
1284 * mono_thread_get_name:
1286 * Return the name of the thread. NAME_LEN is set to the length of the name.
1287 * Return NULL if the thread has no name. The returned memory is owned by the
1291 mono_thread_get_name (MonoInternalThread *this_obj, guint32 *name_len)
1295 ensure_synch_cs_set (this_obj);
1297 EnterCriticalSection (this_obj->synch_cs);
1299 if (!this_obj->name) {
1303 *name_len = this_obj->name_len;
1304 res = g_new (gunichar2, this_obj->name_len);
1305 memcpy (res, this_obj->name, sizeof (gunichar2) * this_obj->name_len);
1308 LeaveCriticalSection (this_obj->synch_cs);
1314 ves_icall_System_Threading_Thread_GetName_internal (MonoInternalThread *this_obj)
1318 ensure_synch_cs_set (this_obj);
1320 EnterCriticalSection (this_obj->synch_cs);
1322 if (!this_obj->name)
1325 str = mono_string_new_utf16 (mono_domain_get (), this_obj->name, this_obj->name_len);
1327 LeaveCriticalSection (this_obj->synch_cs);
1333 ves_icall_System_Threading_Thread_SetName_internal (MonoInternalThread *this_obj, MonoString *name)
1335 ensure_synch_cs_set (this_obj);
1337 EnterCriticalSection (this_obj->synch_cs);
1339 if (this_obj->name) {
1340 LeaveCriticalSection (this_obj->synch_cs);
1342 mono_raise_exception (mono_get_exception_invalid_operation ("Thread.Name can only be set once."));
1346 this_obj->name = g_new (gunichar2, mono_string_length (name));
1347 memcpy (this_obj->name, mono_string_chars (name), mono_string_length (name) * 2);
1348 this_obj->name_len = mono_string_length (name);
1351 this_obj->name = NULL;
1353 LeaveCriticalSection (this_obj->synch_cs);
1357 lookup_cached_culture (MonoInternalThread *this, MonoDomain *domain, int start_idx)
1362 if (this->cached_culture_info) {
1363 domain = mono_domain_get ();
1364 for (i = start_idx; i < start_idx + NUM_CACHED_CULTURES; ++i) {
1365 res = mono_array_get (this->cached_culture_info, MonoObject*, i);
1366 if (res && res->vtable->domain == domain)
1374 /* If the array is already in the requested domain, we just return it,
1375 otherwise we return a copy in that domain. */
1377 byte_array_to_domain (MonoArray *arr, MonoDomain *domain)
1384 if (mono_object_domain (arr) == domain)
1387 copy = mono_array_new (domain, mono_defaults.byte_class, arr->max_length);
1388 memcpy (mono_array_addr (copy, guint8, 0), mono_array_addr (arr, guint8, 0), arr->max_length);
1393 ves_icall_System_Threading_Thread_ByteArrayToRootDomain (MonoArray *arr)
1395 return byte_array_to_domain (arr, mono_get_root_domain ());
1399 ves_icall_System_Threading_Thread_ByteArrayToCurrentDomain (MonoArray *arr)
1401 return byte_array_to_domain (arr, mono_domain_get ());
1405 ves_icall_System_Threading_Thread_GetCachedCurrentCulture (MonoInternalThread *this)
1407 return lookup_cached_culture (this, mono_domain_get (), CULTURES_START_IDX);
1411 cache_culture (MonoInternalThread *this, MonoObject *culture, int start_idx)
1414 MonoDomain *domain = mono_domain_get ();
1417 int same_domain_slot = -1;
1419 ensure_synch_cs_set (this);
1421 EnterCriticalSection (this->synch_cs);
1423 if (!this->cached_culture_info)
1424 MONO_OBJECT_SETREF (this, cached_culture_info, mono_array_new_cached (mono_get_root_domain (), mono_defaults.object_class, NUM_CACHED_CULTURES * 2));
1426 for (i = start_idx; i < start_idx + NUM_CACHED_CULTURES; ++i) {
1427 obj = mono_array_get (this->cached_culture_info, MonoObject*, i);
1431 /* we continue, because there may be a slot used with the same domain */
1435 if (obj->vtable->domain == domain) {
1436 same_domain_slot = i;
1440 if (same_domain_slot >= 0)
1441 mono_array_setref (this->cached_culture_info, same_domain_slot, culture);
1442 else if (free_slot >= 0)
1443 mono_array_setref (this->cached_culture_info, free_slot, culture);
1444 /* we may want to replace an existing entry here, even when no suitable slot is found */
1446 LeaveCriticalSection (this->synch_cs);
1450 ves_icall_System_Threading_Thread_SetCachedCurrentCulture (MonoThread *this, MonoObject *culture)
1452 MonoDomain *domain = mono_object_get_domain (&this->obj);
1453 g_assert (domain == mono_domain_get ());
1454 cache_culture (this->internal_thread, culture, CULTURES_START_IDX);
1458 ves_icall_System_Threading_Thread_GetCachedCurrentUICulture (MonoInternalThread *this)
1460 return lookup_cached_culture (this, mono_domain_get (), UICULTURES_START_IDX);
1464 ves_icall_System_Threading_Thread_SetCachedCurrentUICulture (MonoThread *this, MonoObject *culture)
1466 MonoDomain *domain = mono_object_get_domain (&this->obj);
1467 g_assert (domain == mono_domain_get ());
1468 cache_culture (this->internal_thread, culture, UICULTURES_START_IDX);
1472 mono_thread_current (void)
1474 MonoDomain *domain = mono_domain_get ();
1475 MonoInternalThread *internal = mono_thread_internal_current ();
1476 MonoThread **current_thread_ptr;
1478 g_assert (internal);
1479 current_thread_ptr = get_current_thread_ptr_for_domain (domain, internal);
1481 if (!*current_thread_ptr) {
1482 g_assert (domain != mono_get_root_domain ());
1483 *current_thread_ptr = new_thread_with_internal (domain, internal);
1485 return *current_thread_ptr;
1489 mono_thread_internal_current (void)
1491 MonoInternalThread *res = GET_CURRENT_OBJECT ();
1492 THREAD_DEBUG (g_message ("%s: returning %p", __func__, res));
1496 gboolean ves_icall_System_Threading_Thread_Join_internal(MonoInternalThread *this,
1497 int ms, HANDLE thread)
1499 MonoInternalThread *cur_thread = mono_thread_internal_current ();
1502 mono_thread_current_check_pending_interrupt ();
1504 ensure_synch_cs_set (this);
1506 EnterCriticalSection (this->synch_cs);
1508 if ((this->state & ThreadState_Unstarted) != 0) {
1509 LeaveCriticalSection (this->synch_cs);
1511 mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started."));
1515 LeaveCriticalSection (this->synch_cs);
1520 THREAD_DEBUG (g_message ("%s: joining thread handle %p, %d ms", __func__, thread, ms));
1522 mono_thread_set_state (cur_thread, ThreadState_WaitSleepJoin);
1524 ret=WaitForSingleObjectEx (thread, ms, TRUE);
1526 mono_thread_clr_state (cur_thread, ThreadState_WaitSleepJoin);
1528 if(ret==WAIT_OBJECT_0) {
1529 THREAD_DEBUG (g_message ("%s: join successful", __func__));
1534 THREAD_DEBUG (g_message ("%s: join failed", __func__));
1539 /* FIXME: exitContext isnt documented */
1540 gboolean ves_icall_System_Threading_WaitHandle_WaitAll_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext)
1546 MonoObject *waitHandle;
1547 MonoInternalThread *thread = mono_thread_internal_current ();
1549 /* Do this WaitSleepJoin check before creating objects */
1550 mono_thread_current_check_pending_interrupt ();
1552 numhandles = mono_array_length(mono_handles);
1553 handles = g_new0(HANDLE, numhandles);
1555 for(i = 0; i < numhandles; i++) {
1556 waitHandle = mono_array_get(mono_handles, MonoObject*, i);
1557 handles [i] = mono_wait_handle_get_handle ((MonoWaitHandle *) waitHandle);
1564 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1566 ret=WaitForMultipleObjectsEx(numhandles, handles, TRUE, ms, TRUE);
1568 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1572 if(ret==WAIT_FAILED) {
1573 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait failed", __func__, GetCurrentThreadId ()));
1575 } else if(ret==WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION) {
1576 /* Do we want to try again if we get
1577 * WAIT_IO_COMPLETION? The documentation for
1578 * WaitHandle doesn't give any clues. (We'd have to
1579 * fiddle with the timeout if we retry.)
1581 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait timed out", __func__, GetCurrentThreadId ()));
1588 /* FIXME: exitContext isnt documented */
1589 gint32 ves_icall_System_Threading_WaitHandle_WaitAny_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext)
1595 MonoObject *waitHandle;
1596 MonoInternalThread *thread = mono_thread_internal_current ();
1599 /* Do this WaitSleepJoin check before creating objects */
1600 mono_thread_current_check_pending_interrupt ();
1602 numhandles = mono_array_length(mono_handles);
1603 handles = g_new0(HANDLE, numhandles);
1605 for(i = 0; i < numhandles; i++) {
1606 waitHandle = mono_array_get(mono_handles, MonoObject*, i);
1607 handles [i] = mono_wait_handle_get_handle ((MonoWaitHandle *) waitHandle);
1614 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1616 start = (ms == -1) ? 0 : mono_msec_ticks ();
1618 ret = WaitForMultipleObjectsEx (numhandles, handles, FALSE, ms, TRUE);
1619 if (ret != WAIT_IO_COMPLETION)
1624 diff = mono_msec_ticks () - start;
1629 } while (ms == -1 || ms > 0);
1631 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1635 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") returning %d", __func__, GetCurrentThreadId (), ret));
1638 * These need to be here. See MSDN dos on WaitForMultipleObjects.
1640 if (ret >= WAIT_OBJECT_0 && ret <= WAIT_OBJECT_0 + numhandles - 1) {
1641 return ret - WAIT_OBJECT_0;
1643 else if (ret >= WAIT_ABANDONED_0 && ret <= WAIT_ABANDONED_0 + numhandles - 1) {
1644 return ret - WAIT_ABANDONED_0;
1651 /* FIXME: exitContext isnt documented */
1652 gboolean ves_icall_System_Threading_WaitHandle_WaitOne_internal(MonoObject *this, HANDLE handle, gint32 ms, gboolean exitContext)
1655 MonoInternalThread *thread = mono_thread_internal_current ();
1657 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") waiting for %p, %d ms", __func__, GetCurrentThreadId (), handle, ms));
1663 mono_thread_current_check_pending_interrupt ();
1665 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1667 ret=WaitForSingleObjectEx (handle, ms, TRUE);
1669 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1671 if(ret==WAIT_FAILED) {
1672 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait failed", __func__, GetCurrentThreadId ()));
1674 } else if(ret==WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION) {
1675 /* Do we want to try again if we get
1676 * WAIT_IO_COMPLETION? The documentation for
1677 * WaitHandle doesn't give any clues. (We'd have to
1678 * fiddle with the timeout if we retry.)
1680 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait timed out", __func__, GetCurrentThreadId ()));
1688 ves_icall_System_Threading_WaitHandle_SignalAndWait_Internal (HANDLE toSignal, HANDLE toWait, gint32 ms, gboolean exitContext)
1691 MonoInternalThread *thread = mono_thread_internal_current ();
1693 MONO_ARCH_SAVE_REGS;
1698 mono_thread_current_check_pending_interrupt ();
1700 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1702 ret = SignalObjectAndWait (toSignal, toWait, ms, TRUE);
1704 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1706 return (!(ret == WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION || ret == WAIT_FAILED));
1709 HANDLE ves_icall_System_Threading_Mutex_CreateMutex_internal (MonoBoolean owned, MonoString *name, MonoBoolean *created)
1713 MONO_ARCH_SAVE_REGS;
1718 mutex = CreateMutex (NULL, owned, NULL);
1720 mutex = CreateMutex (NULL, owned, mono_string_chars (name));
1722 if (GetLastError () == ERROR_ALREADY_EXISTS) {
1730 MonoBoolean ves_icall_System_Threading_Mutex_ReleaseMutex_internal (HANDLE handle ) {
1731 MONO_ARCH_SAVE_REGS;
1733 return(ReleaseMutex (handle));
1736 HANDLE ves_icall_System_Threading_Mutex_OpenMutex_internal (MonoString *name,
1742 MONO_ARCH_SAVE_REGS;
1744 *error = ERROR_SUCCESS;
1746 ret = OpenMutex (rights, FALSE, mono_string_chars (name));
1748 *error = GetLastError ();
1755 HANDLE ves_icall_System_Threading_Semaphore_CreateSemaphore_internal (gint32 initialCount, gint32 maximumCount, MonoString *name, MonoBoolean *created)
1759 MONO_ARCH_SAVE_REGS;
1764 sem = CreateSemaphore (NULL, initialCount, maximumCount, NULL);
1766 sem = CreateSemaphore (NULL, initialCount, maximumCount,
1767 mono_string_chars (name));
1769 if (GetLastError () == ERROR_ALREADY_EXISTS) {
1777 gint32 ves_icall_System_Threading_Semaphore_ReleaseSemaphore_internal (HANDLE handle, gint32 releaseCount, MonoBoolean *fail)
1781 MONO_ARCH_SAVE_REGS;
1783 *fail = !ReleaseSemaphore (handle, releaseCount, &prevcount);
1788 HANDLE ves_icall_System_Threading_Semaphore_OpenSemaphore_internal (MonoString *name, gint32 rights, gint32 *error)
1792 MONO_ARCH_SAVE_REGS;
1794 *error = ERROR_SUCCESS;
1796 ret = OpenSemaphore (rights, FALSE, mono_string_chars (name));
1798 *error = GetLastError ();
1804 HANDLE ves_icall_System_Threading_Events_CreateEvent_internal (MonoBoolean manual, MonoBoolean initial, MonoString *name, MonoBoolean *created)
1808 MONO_ARCH_SAVE_REGS;
1813 event = CreateEvent (NULL, manual, initial, NULL);
1815 event = CreateEvent (NULL, manual, initial,
1816 mono_string_chars (name));
1818 if (GetLastError () == ERROR_ALREADY_EXISTS) {
1826 gboolean ves_icall_System_Threading_Events_SetEvent_internal (HANDLE handle) {
1827 MONO_ARCH_SAVE_REGS;
1829 return (SetEvent(handle));
1832 gboolean ves_icall_System_Threading_Events_ResetEvent_internal (HANDLE handle) {
1833 MONO_ARCH_SAVE_REGS;
1835 return (ResetEvent(handle));
1839 ves_icall_System_Threading_Events_CloseEvent_internal (HANDLE handle) {
1840 MONO_ARCH_SAVE_REGS;
1842 CloseHandle (handle);
1845 HANDLE ves_icall_System_Threading_Events_OpenEvent_internal (MonoString *name,
1851 MONO_ARCH_SAVE_REGS;
1853 *error = ERROR_SUCCESS;
1855 ret = OpenEvent (rights, FALSE, mono_string_chars (name));
1857 *error = GetLastError ();
1863 gint32 ves_icall_System_Threading_Interlocked_Increment_Int (gint32 *location)
1865 MONO_ARCH_SAVE_REGS;
1867 return InterlockedIncrement (location);
1870 gint64 ves_icall_System_Threading_Interlocked_Increment_Long (gint64 *location)
1874 MONO_ARCH_SAVE_REGS;
1876 mono_interlocked_lock ();
1880 mono_interlocked_unlock ();
1886 gint32 ves_icall_System_Threading_Interlocked_Decrement_Int (gint32 *location)
1888 MONO_ARCH_SAVE_REGS;
1890 return InterlockedDecrement(location);
1893 gint64 ves_icall_System_Threading_Interlocked_Decrement_Long (gint64 * location)
1897 MONO_ARCH_SAVE_REGS;
1899 mono_interlocked_lock ();
1903 mono_interlocked_unlock ();
1908 gint32 ves_icall_System_Threading_Interlocked_Exchange_Int (gint32 *location, gint32 value)
1910 MONO_ARCH_SAVE_REGS;
1912 return InterlockedExchange(location, value);
1915 MonoObject * ves_icall_System_Threading_Interlocked_Exchange_Object (MonoObject **location, MonoObject *value)
1918 res = (MonoObject *) InterlockedExchangePointer((gpointer *) location, value);
1919 mono_gc_wbarrier_generic_nostore (location);
1923 gpointer ves_icall_System_Threading_Interlocked_Exchange_IntPtr (gpointer *location, gpointer value)
1925 return InterlockedExchangePointer(location, value);
1928 gfloat ves_icall_System_Threading_Interlocked_Exchange_Single (gfloat *location, gfloat value)
1930 IntFloatUnion val, ret;
1932 MONO_ARCH_SAVE_REGS;
1935 ret.ival = InterlockedExchange((gint32 *) location, val.ival);
1941 ves_icall_System_Threading_Interlocked_Exchange_Long (gint64 *location, gint64 value)
1943 #if SIZEOF_VOID_P == 8
1944 return (gint64) InterlockedExchangePointer((gpointer *) location, (gpointer)value);
1949 * According to MSDN, this function is only atomic with regards to the
1950 * other Interlocked functions on 32 bit platforms.
1952 mono_interlocked_lock ();
1955 mono_interlocked_unlock ();
1962 ves_icall_System_Threading_Interlocked_Exchange_Double (gdouble *location, gdouble value)
1964 #if SIZEOF_VOID_P == 8
1965 LongDoubleUnion val, ret;
1968 ret.ival = (gint64)InterlockedExchangePointer((gpointer *) location, (gpointer)val.ival);
1975 * According to MSDN, this function is only atomic with regards to the
1976 * other Interlocked functions on 32 bit platforms.
1978 mono_interlocked_lock ();
1981 mono_interlocked_unlock ();
1987 gint32 ves_icall_System_Threading_Interlocked_CompareExchange_Int(gint32 *location, gint32 value, gint32 comparand)
1989 MONO_ARCH_SAVE_REGS;
1991 return InterlockedCompareExchange(location, value, comparand);
1994 MonoObject * ves_icall_System_Threading_Interlocked_CompareExchange_Object (MonoObject **location, MonoObject *value, MonoObject *comparand)
1997 res = (MonoObject *) InterlockedCompareExchangePointer((gpointer *) location, value, comparand);
1998 mono_gc_wbarrier_generic_nostore (location);
2002 gpointer ves_icall_System_Threading_Interlocked_CompareExchange_IntPtr(gpointer *location, gpointer value, gpointer comparand)
2004 return InterlockedCompareExchangePointer(location, value, comparand);
2007 gfloat ves_icall_System_Threading_Interlocked_CompareExchange_Single (gfloat *location, gfloat value, gfloat comparand)
2009 IntFloatUnion val, ret, cmp;
2011 MONO_ARCH_SAVE_REGS;
2014 cmp.fval = comparand;
2015 ret.ival = InterlockedCompareExchange((gint32 *) location, val.ival, cmp.ival);
2021 ves_icall_System_Threading_Interlocked_CompareExchange_Double (gdouble *location, gdouble value, gdouble comparand)
2023 #if SIZEOF_VOID_P == 8
2024 LongDoubleUnion val, comp, ret;
2027 comp.fval = comparand;
2028 ret.ival = (gint64)InterlockedCompareExchangePointer((gpointer *) location, (gpointer)val.ival, (gpointer)comp.ival);
2034 mono_interlocked_lock ();
2036 if (old == comparand)
2038 mono_interlocked_unlock ();
2045 ves_icall_System_Threading_Interlocked_CompareExchange_Long (gint64 *location, gint64 value, gint64 comparand)
2047 #if SIZEOF_VOID_P == 8
2048 return (gint64)InterlockedCompareExchangePointer((gpointer *) location, (gpointer)value, (gpointer)comparand);
2052 mono_interlocked_lock ();
2054 if (old == comparand)
2056 mono_interlocked_unlock ();
2063 ves_icall_System_Threading_Interlocked_CompareExchange_T (MonoObject **location, MonoObject *value, MonoObject *comparand)
2066 res = InterlockedCompareExchangePointer ((gpointer *)location, value, comparand);
2067 mono_gc_wbarrier_generic_nostore (location);
2072 ves_icall_System_Threading_Interlocked_Exchange_T (MonoObject **location, MonoObject *value)
2075 res = InterlockedExchangePointer ((gpointer *)location, value);
2076 mono_gc_wbarrier_generic_nostore (location);
2081 ves_icall_System_Threading_Interlocked_Add_Int (gint32 *location, gint32 value)
2083 #if SIZEOF_VOID_P == 8
2084 /* Should be implemented as a JIT intrinsic */
2085 mono_raise_exception (mono_get_exception_not_implemented (NULL));
2090 mono_interlocked_lock ();
2092 *location = orig + value;
2093 mono_interlocked_unlock ();
2095 return orig + value;
2100 ves_icall_System_Threading_Interlocked_Add_Long (gint64 *location, gint64 value)
2102 #if SIZEOF_VOID_P == 8
2103 /* Should be implemented as a JIT intrinsic */
2104 mono_raise_exception (mono_get_exception_not_implemented (NULL));
2109 mono_interlocked_lock ();
2111 *location = orig + value;
2112 mono_interlocked_unlock ();
2114 return orig + value;
2119 ves_icall_System_Threading_Interlocked_Read_Long (gint64 *location)
2121 #if SIZEOF_VOID_P == 8
2122 /* 64 bit reads are already atomic */
2127 mono_interlocked_lock ();
2129 mono_interlocked_unlock ();
2136 ves_icall_System_Threading_Thread_MemoryBarrier (void)
2138 mono_threads_lock ();
2139 mono_threads_unlock ();
2143 ves_icall_System_Threading_Thread_ClrState (MonoInternalThread* this, guint32 state)
2145 mono_thread_clr_state (this, state);
2147 if (state & ThreadState_Background) {
2148 /* If the thread changes the background mode, the main thread has to
2149 * be notified, since it has to rebuild the list of threads to
2152 SetEvent (background_change_event);
2157 ves_icall_System_Threading_Thread_SetState (MonoInternalThread* this, guint32 state)
2159 mono_thread_set_state (this, state);
2161 if (state & ThreadState_Background) {
2162 /* If the thread changes the background mode, the main thread has to
2163 * be notified, since it has to rebuild the list of threads to
2166 SetEvent (background_change_event);
2171 ves_icall_System_Threading_Thread_GetState (MonoInternalThread* this)
2175 ensure_synch_cs_set (this);
2177 EnterCriticalSection (this->synch_cs);
2179 state = this->state;
2181 LeaveCriticalSection (this->synch_cs);
2186 void ves_icall_System_Threading_Thread_Interrupt_internal (MonoInternalThread *this)
2188 gboolean throw = FALSE;
2190 ensure_synch_cs_set (this);
2192 if (this == mono_thread_internal_current ())
2195 EnterCriticalSection (this->synch_cs);
2197 this->thread_interrupt_requested = TRUE;
2199 if (this->state & ThreadState_WaitSleepJoin) {
2203 LeaveCriticalSection (this->synch_cs);
2206 signal_thread_state_change (this);
2210 void mono_thread_current_check_pending_interrupt ()
2212 MonoInternalThread *thread = mono_thread_internal_current ();
2213 gboolean throw = FALSE;
2215 mono_debugger_check_interruption ();
2217 ensure_synch_cs_set (thread);
2219 EnterCriticalSection (thread->synch_cs);
2221 if (thread->thread_interrupt_requested) {
2223 thread->thread_interrupt_requested = FALSE;
2226 LeaveCriticalSection (thread->synch_cs);
2229 mono_raise_exception (mono_get_exception_thread_interrupted ());
2234 mono_thread_get_abort_signal (void)
2246 static int abort_signum = -1;
2248 if (abort_signum != -1)
2249 return abort_signum;
2250 /* we try to avoid SIGRTMIN and any one that might have been set already, see bug #75387 */
2251 for (i = SIGRTMIN + 1; i < SIGRTMAX; ++i) {
2252 struct sigaction sinfo;
2253 sigaction (i, NULL, &sinfo);
2254 if (sinfo.sa_handler == SIG_DFL && (void*)sinfo.sa_sigaction == (void*)SIG_DFL) {
2259 /* fallback to the old way */
2262 #endif /* HOST_WIN32 */
2266 static void CALLBACK interruption_request_apc (ULONG_PTR param)
2268 MonoException* exc = mono_thread_request_interruption (FALSE);
2269 if (exc) mono_raise_exception (exc);
2271 #endif /* HOST_WIN32 */
2274 * signal_thread_state_change
2276 * Tells the thread that his state has changed and it has to enter the new
2277 * state as soon as possible.
2279 static void signal_thread_state_change (MonoInternalThread *thread)
2281 if (thread == mono_thread_internal_current ()) {
2282 /* Do it synchronously */
2283 MonoException *exc = mono_thread_request_interruption (FALSE);
2285 mono_raise_exception (exc);
2289 QueueUserAPC ((PAPCFUNC)interruption_request_apc, thread->handle, NULL);
2291 /* fixme: store the state somewhere */
2292 #ifdef PTHREAD_POINTER_ID
2293 pthread_kill ((gpointer)(gsize)(thread->tid), mono_thread_get_abort_signal ());
2295 pthread_kill (thread->tid, mono_thread_get_abort_signal ());
2299 * This will cause waits to be broken.
2300 * It will also prevent the thread from entering a wait, so if the thread returns
2301 * from the wait before it receives the abort signal, it will just spin in the wait
2302 * functions in the io-layer until the signal handler calls QueueUserAPC which will
2305 wapi_interrupt_thread (thread->handle);
2306 #endif /* HOST_WIN32 */
2310 ves_icall_System_Threading_Thread_Abort (MonoInternalThread *thread, MonoObject *state)
2312 ensure_synch_cs_set (thread);
2314 EnterCriticalSection (thread->synch_cs);
2316 if ((thread->state & ThreadState_AbortRequested) != 0 ||
2317 (thread->state & ThreadState_StopRequested) != 0 ||
2318 (thread->state & ThreadState_Stopped) != 0)
2320 LeaveCriticalSection (thread->synch_cs);
2324 if ((thread->state & ThreadState_Unstarted) != 0) {
2325 thread->state |= ThreadState_Aborted;
2326 LeaveCriticalSection (thread->synch_cs);
2330 thread->state |= ThreadState_AbortRequested;
2331 if (thread->abort_state_handle)
2332 mono_gchandle_free (thread->abort_state_handle);
2334 thread->abort_state_handle = mono_gchandle_new (state, FALSE);
2335 g_assert (thread->abort_state_handle);
2337 thread->abort_state_handle = 0;
2339 thread->abort_exc = NULL;
2342 * abort_exc is set in mono_thread_execute_interruption(),
2343 * triggered by the call to signal_thread_state_change(),
2344 * below. There's a point between where we have
2345 * abort_state_handle set, but abort_exc NULL, but that's not
2349 LeaveCriticalSection (thread->synch_cs);
2351 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Abort requested for %p (%"G_GSIZE_FORMAT")", __func__, GetCurrentThreadId (), thread, (gsize)thread->tid));
2353 /* During shutdown, we can't wait for other threads */
2355 /* Make sure the thread is awake */
2356 mono_thread_resume (thread);
2358 signal_thread_state_change (thread);
2362 ves_icall_System_Threading_Thread_ResetAbort (void)
2364 MonoInternalThread *thread = mono_thread_internal_current ();
2365 gboolean was_aborting;
2367 ensure_synch_cs_set (thread);
2369 EnterCriticalSection (thread->synch_cs);
2370 was_aborting = thread->state & ThreadState_AbortRequested;
2371 thread->state &= ~ThreadState_AbortRequested;
2372 LeaveCriticalSection (thread->synch_cs);
2374 if (!was_aborting) {
2375 const char *msg = "Unable to reset abort because no abort was requested";
2376 mono_raise_exception (mono_get_exception_thread_state (msg));
2378 thread->abort_exc = NULL;
2379 if (thread->abort_state_handle) {
2380 mono_gchandle_free (thread->abort_state_handle);
2381 /* This is actually not necessary - the handle
2382 only counts if the exception is set */
2383 thread->abort_state_handle = 0;
2388 mono_thread_internal_reset_abort (MonoInternalThread *thread)
2390 ensure_synch_cs_set (thread);
2392 EnterCriticalSection (thread->synch_cs);
2394 thread->state &= ~ThreadState_AbortRequested;
2396 if (thread->abort_exc) {
2397 thread->abort_exc = NULL;
2398 if (thread->abort_state_handle) {
2399 mono_gchandle_free (thread->abort_state_handle);
2400 /* This is actually not necessary - the handle
2401 only counts if the exception is set */
2402 thread->abort_state_handle = 0;
2406 LeaveCriticalSection (thread->synch_cs);
2410 ves_icall_System_Threading_Thread_GetAbortExceptionState (MonoThread *this)
2412 MonoInternalThread *thread = this->internal_thread;
2413 MonoObject *state, *deserialized = NULL, *exc;
2416 if (!thread->abort_state_handle)
2419 state = mono_gchandle_get_target (thread->abort_state_handle);
2422 domain = mono_domain_get ();
2423 if (mono_object_domain (state) == domain)
2426 deserialized = mono_object_xdomain_representation (state, domain, &exc);
2428 if (!deserialized) {
2429 MonoException *invalid_op_exc = mono_get_exception_invalid_operation ("Thread.ExceptionState cannot access an ExceptionState from a different AppDomain");
2431 MONO_OBJECT_SETREF (invalid_op_exc, inner_ex, exc);
2432 mono_raise_exception (invalid_op_exc);
2435 return deserialized;
2439 mono_thread_suspend (MonoInternalThread *thread)
2441 ensure_synch_cs_set (thread);
2443 EnterCriticalSection (thread->synch_cs);
2445 if ((thread->state & ThreadState_Unstarted) != 0 ||
2446 (thread->state & ThreadState_Aborted) != 0 ||
2447 (thread->state & ThreadState_Stopped) != 0)
2449 LeaveCriticalSection (thread->synch_cs);
2453 if ((thread->state & ThreadState_Suspended) != 0 ||
2454 (thread->state & ThreadState_SuspendRequested) != 0 ||
2455 (thread->state & ThreadState_StopRequested) != 0)
2457 LeaveCriticalSection (thread->synch_cs);
2461 thread->state |= ThreadState_SuspendRequested;
2463 LeaveCriticalSection (thread->synch_cs);
2465 signal_thread_state_change (thread);
2470 ves_icall_System_Threading_Thread_Suspend (MonoInternalThread *thread)
2472 if (!mono_thread_suspend (thread))
2473 mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started, or is dead."));
2477 mono_thread_resume (MonoInternalThread *thread)
2479 ensure_synch_cs_set (thread);
2481 EnterCriticalSection (thread->synch_cs);
2483 if ((thread->state & ThreadState_SuspendRequested) != 0) {
2484 thread->state &= ~ThreadState_SuspendRequested;
2485 LeaveCriticalSection (thread->synch_cs);
2489 if ((thread->state & ThreadState_Suspended) == 0 ||
2490 (thread->state & ThreadState_Unstarted) != 0 ||
2491 (thread->state & ThreadState_Aborted) != 0 ||
2492 (thread->state & ThreadState_Stopped) != 0)
2494 LeaveCriticalSection (thread->synch_cs);
2498 thread->resume_event = CreateEvent (NULL, TRUE, FALSE, NULL);
2499 if (thread->resume_event == NULL) {
2500 LeaveCriticalSection (thread->synch_cs);
2504 /* Awake the thread */
2505 SetEvent (thread->suspend_event);
2507 LeaveCriticalSection (thread->synch_cs);
2509 /* Wait for the thread to awake */
2510 WaitForSingleObject (thread->resume_event, INFINITE);
2511 CloseHandle (thread->resume_event);
2512 thread->resume_event = NULL;
2518 ves_icall_System_Threading_Thread_Resume (MonoThread *thread)
2520 if (!thread->internal_thread || !mono_thread_resume (thread->internal_thread))
2521 mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started, or is dead."));
2525 find_wrapper (MonoMethod *m, gint no, gint ilo, gboolean managed, gpointer data)
2530 if (m->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE ||
2531 m->wrapper_type == MONO_WRAPPER_XDOMAIN_INVOKE ||
2532 m->wrapper_type == MONO_WRAPPER_XDOMAIN_DISPATCH)
2534 *((gboolean*)data) = TRUE;
2541 is_running_protected_wrapper (void)
2543 gboolean found = FALSE;
2544 mono_stack_walk (find_wrapper, &found);
2548 void mono_thread_internal_stop (MonoInternalThread *thread)
2550 ensure_synch_cs_set (thread);
2552 EnterCriticalSection (thread->synch_cs);
2554 if ((thread->state & ThreadState_StopRequested) != 0 ||
2555 (thread->state & ThreadState_Stopped) != 0)
2557 LeaveCriticalSection (thread->synch_cs);
2561 /* Make sure the thread is awake */
2562 mono_thread_resume (thread);
2564 thread->state |= ThreadState_StopRequested;
2565 thread->state &= ~ThreadState_AbortRequested;
2567 LeaveCriticalSection (thread->synch_cs);
2569 signal_thread_state_change (thread);
2572 void mono_thread_stop (MonoThread *thread)
2574 mono_thread_internal_stop (thread->internal_thread);
2578 ves_icall_System_Threading_Thread_VolatileRead1 (void *ptr)
2580 return *((volatile gint8 *) (ptr));
2584 ves_icall_System_Threading_Thread_VolatileRead2 (void *ptr)
2586 return *((volatile gint16 *) (ptr));
2590 ves_icall_System_Threading_Thread_VolatileRead4 (void *ptr)
2592 return *((volatile gint32 *) (ptr));
2596 ves_icall_System_Threading_Thread_VolatileRead8 (void *ptr)
2598 return *((volatile gint64 *) (ptr));
2602 ves_icall_System_Threading_Thread_VolatileReadIntPtr (void *ptr)
2604 return (void *) *((volatile void **) ptr);
2608 ves_icall_System_Threading_Thread_VolatileWrite1 (void *ptr, gint8 value)
2610 *((volatile gint8 *) ptr) = value;
2614 ves_icall_System_Threading_Thread_VolatileWrite2 (void *ptr, gint16 value)
2616 *((volatile gint16 *) ptr) = value;
2620 ves_icall_System_Threading_Thread_VolatileWrite4 (void *ptr, gint32 value)
2622 *((volatile gint32 *) ptr) = value;
2626 ves_icall_System_Threading_Thread_VolatileWrite8 (void *ptr, gint64 value)
2628 *((volatile gint64 *) ptr) = value;
2632 ves_icall_System_Threading_Thread_VolatileWriteIntPtr (void *ptr, void *value)
2634 *((volatile void **) ptr) = value;
2638 ves_icall_System_Threading_Thread_VolatileWriteObject (void *ptr, void *value)
2640 mono_gc_wbarrier_generic_store (ptr, value);
2643 void mono_thread_init (MonoThreadStartCB start_cb,
2644 MonoThreadAttachCB attach_cb)
2646 MONO_GC_REGISTER_ROOT (small_id_table);
2647 InitializeCriticalSection(&threads_mutex);
2648 InitializeCriticalSection(&interlocked_mutex);
2649 InitializeCriticalSection(&contexts_mutex);
2650 InitializeCriticalSection(&delayed_free_table_mutex);
2651 InitializeCriticalSection(&small_id_mutex);
2653 background_change_event = CreateEvent (NULL, TRUE, FALSE, NULL);
2654 g_assert(background_change_event != NULL);
2656 mono_init_static_data_info (&thread_static_info);
2657 mono_init_static_data_info (&context_static_info);
2659 current_object_key=TlsAlloc();
2660 THREAD_DEBUG (g_message ("%s: Allocated current_object_key %d", __func__, current_object_key));
2662 mono_thread_start_cb = start_cb;
2663 mono_thread_attach_cb = attach_cb;
2665 delayed_free_table = g_array_new (FALSE, FALSE, sizeof (DelayedFreeItem));
2667 /* Get a pseudo handle to the current process. This is just a
2668 * kludge so that wapi can build a process handle if needed.
2669 * As a pseudo handle is returned, we don't need to clean
2672 GetCurrentProcess ();
2675 void mono_thread_cleanup (void)
2677 mono_thread_hazardous_try_free_all ();
2679 #if !defined(HOST_WIN32) && !defined(RUN_IN_SUBTHREAD)
2680 /* The main thread must abandon any held mutexes (particularly
2681 * important for named mutexes as they are shared across
2682 * processes, see bug 74680.) This will happen when the
2683 * thread exits, but if it's not running in a subthread it
2684 * won't exit in time.
2686 /* Using non-w32 API is a nasty kludge, but I couldn't find
2687 * anything in the documentation that would let me do this
2688 * here yet still be safe to call on windows.
2690 _wapi_thread_signal_self (mono_environment_exitcode_get ());
2694 /* This stuff needs more testing, it seems one of these
2695 * critical sections can be locked when mono_thread_cleanup is
2698 DeleteCriticalSection (&threads_mutex);
2699 DeleteCriticalSection (&interlocked_mutex);
2700 DeleteCriticalSection (&contexts_mutex);
2701 DeleteCriticalSection (&delayed_free_table_mutex);
2702 DeleteCriticalSection (&small_id_mutex);
2703 CloseHandle (background_change_event);
2706 g_array_free (delayed_free_table, TRUE);
2707 delayed_free_table = NULL;
2709 TlsFree (current_object_key);
2713 mono_threads_install_cleanup (MonoThreadCleanupFunc func)
2715 mono_thread_cleanup_fn = func;
2719 mono_thread_set_manage_callback (MonoThread *thread, MonoThreadManageCallback func)
2721 thread->internal_thread->manage_callback = func;
2724 void mono_threads_install_notify_pending_exc (MonoThreadNotifyPendingExcFunc func)
2726 mono_thread_notify_pending_exc_fn = func;
2730 static void print_tids (gpointer key, gpointer value, gpointer user)
2732 /* GPOINTER_TO_UINT breaks horribly if sizeof(void *) >
2733 * sizeof(uint) and a cast to uint would overflow
2735 /* Older versions of glib don't have G_GSIZE_FORMAT, so just
2736 * print this as a pointer.
2738 g_message ("Waiting for: %p", key);
2743 HANDLE handles[MAXIMUM_WAIT_OBJECTS];
2744 MonoInternalThread *threads[MAXIMUM_WAIT_OBJECTS];
2748 static void wait_for_tids (struct wait_data *wait, guint32 timeout)
2752 THREAD_DEBUG (g_message("%s: %d threads to wait for in this batch", __func__, wait->num));
2754 ret=WaitForMultipleObjectsEx(wait->num, wait->handles, TRUE, timeout, TRUE);
2756 if(ret==WAIT_FAILED) {
2757 /* See the comment in build_wait_tids() */
2758 THREAD_DEBUG (g_message ("%s: Wait failed", __func__));
2762 for(i=0; i<wait->num; i++)
2763 CloseHandle (wait->handles[i]);
2765 if (ret == WAIT_TIMEOUT)
2768 for(i=0; i<wait->num; i++) {
2769 gsize tid = wait->threads[i]->tid;
2771 mono_threads_lock ();
2772 if(mono_g_hash_table_lookup (threads, (gpointer)tid)!=NULL) {
2773 /* This thread must have been killed, because
2774 * it hasn't cleaned itself up. (It's just
2775 * possible that the thread exited before the
2776 * parent thread had a chance to store the
2777 * handle, and now there is another pointer to
2778 * the already-exited thread stored. In this
2779 * case, we'll just get two
2780 * mono_profiler_thread_end() calls for the
2784 mono_threads_unlock ();
2785 THREAD_DEBUG (g_message ("%s: cleaning up after thread %p (%"G_GSIZE_FORMAT")", __func__, wait->threads[i], tid));
2786 thread_cleanup (wait->threads[i]);
2788 mono_threads_unlock ();
2793 static void wait_for_tids_or_state_change (struct wait_data *wait, guint32 timeout)
2795 guint32 i, ret, count;
2797 THREAD_DEBUG (g_message("%s: %d threads to wait for in this batch", __func__, wait->num));
2799 /* Add the thread state change event, so it wakes up if a thread changes
2800 * to background mode.
2803 if (count < MAXIMUM_WAIT_OBJECTS) {
2804 wait->handles [count] = background_change_event;
2808 ret=WaitForMultipleObjectsEx (count, wait->handles, FALSE, timeout, TRUE);
2810 if(ret==WAIT_FAILED) {
2811 /* See the comment in build_wait_tids() */
2812 THREAD_DEBUG (g_message ("%s: Wait failed", __func__));
2816 for(i=0; i<wait->num; i++)
2817 CloseHandle (wait->handles[i]);
2819 if (ret == WAIT_TIMEOUT)
2822 if (ret < wait->num) {
2823 gsize tid = wait->threads[ret]->tid;
2824 mono_threads_lock ();
2825 if (mono_g_hash_table_lookup (threads, (gpointer)tid)!=NULL) {
2826 /* See comment in wait_for_tids about thread cleanup */
2827 mono_threads_unlock ();
2828 THREAD_DEBUG (g_message ("%s: cleaning up after thread %"G_GSIZE_FORMAT, __func__, tid));
2829 thread_cleanup (wait->threads [ret]);
2831 mono_threads_unlock ();
2835 static void build_wait_tids (gpointer key, gpointer value, gpointer user)
2837 struct wait_data *wait=(struct wait_data *)user;
2839 if(wait->num<MAXIMUM_WAIT_OBJECTS) {
2841 MonoInternalThread *thread=(MonoInternalThread *)value;
2843 /* Ignore background threads, we abort them later */
2844 /* Do not lock here since it is not needed and the caller holds threads_lock */
2845 if (thread->state & ThreadState_Background) {
2846 THREAD_DEBUG (g_message ("%s: ignoring background thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2847 return; /* just leave, ignore */
2850 if (mono_gc_is_finalizer_internal_thread (thread)) {
2851 THREAD_DEBUG (g_message ("%s: ignoring finalizer thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2855 if (thread == mono_thread_internal_current ()) {
2856 THREAD_DEBUG (g_message ("%s: ignoring current thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2860 if (mono_thread_get_main () && (thread == mono_thread_get_main ()->internal_thread)) {
2861 THREAD_DEBUG (g_message ("%s: ignoring main thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2865 if (thread->flags & MONO_THREAD_FLAG_DONT_MANAGE) {
2866 THREAD_DEBUG (g_message ("%s: ignoring thread %" G_GSIZE_FORMAT "with DONT_MANAGE flag set.", __func__, (gsize)thread->tid));
2870 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
2871 if (handle == NULL) {
2872 THREAD_DEBUG (g_message ("%s: ignoring unopenable thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2876 THREAD_DEBUG (g_message ("%s: Invoking mono_thread_manage callback on thread %p", __func__, thread));
2877 if ((thread->manage_callback == NULL) || (thread->manage_callback (thread->root_domain_thread) == TRUE)) {
2878 wait->handles[wait->num]=handle;
2879 wait->threads[wait->num]=thread;
2882 THREAD_DEBUG (g_message ("%s: adding thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2884 THREAD_DEBUG (g_message ("%s: ignoring (because of callback) thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2889 /* Just ignore the rest, we can't do anything with
2896 remove_and_abort_threads (gpointer key, gpointer value, gpointer user)
2898 struct wait_data *wait=(struct wait_data *)user;
2899 gsize self = GetCurrentThreadId ();
2900 MonoInternalThread *thread = value;
2903 if (wait->num >= MAXIMUM_WAIT_OBJECTS)
2906 /* The finalizer thread is not a background thread */
2907 if (thread->tid != self && (thread->state & ThreadState_Background) != 0 &&
2908 !(thread->flags & MONO_THREAD_FLAG_DONT_MANAGE)) {
2910 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
2914 /* printf ("A: %d\n", wait->num); */
2915 wait->handles[wait->num]=thread->handle;
2916 wait->threads[wait->num]=thread;
2919 THREAD_DEBUG (g_print ("%s: Aborting id: %"G_GSIZE_FORMAT"\n", __func__, (gsize)thread->tid));
2920 mono_thread_internal_stop (thread);
2924 return (thread->tid != self && !mono_gc_is_finalizer_internal_thread (thread));
2928 * mono_threads_set_shutting_down:
2930 * Is called by a thread that wants to shut down Mono. If the runtime is already
2931 * shutting down, the calling thread is suspended/stopped, and this function never
2935 mono_threads_set_shutting_down (void)
2937 MonoInternalThread *current_thread = mono_thread_internal_current ();
2939 mono_threads_lock ();
2941 if (shutting_down) {
2942 mono_threads_unlock ();
2944 /* Make sure we're properly suspended/stopped */
2946 EnterCriticalSection (current_thread->synch_cs);
2948 if ((current_thread->state & ThreadState_SuspendRequested) ||
2949 (current_thread->state & ThreadState_AbortRequested) ||
2950 (current_thread->state & ThreadState_StopRequested)) {
2951 LeaveCriticalSection (current_thread->synch_cs);
2952 mono_thread_execute_interruption (current_thread);
2954 current_thread->state |= ThreadState_Stopped;
2955 LeaveCriticalSection (current_thread->synch_cs);
2958 /* Wake up other threads potentially waiting for us */
2961 shutting_down = TRUE;
2963 /* Not really a background state change, but this will
2964 * interrupt the main thread if it is waiting for all
2965 * the other threads.
2967 SetEvent (background_change_event);
2969 mono_threads_unlock ();
2974 * mono_threads_is_shutting_down:
2976 * Returns whether a thread has commenced shutdown of Mono. Note that
2977 * if the function returns FALSE the caller must not assume that
2978 * shutdown is not in progress, because the situation might have
2979 * changed since the function returned. For that reason this function
2980 * is of very limited utility.
2983 mono_threads_is_shutting_down (void)
2985 return shutting_down;
2988 void mono_thread_manage (void)
2990 struct wait_data wait_data;
2991 struct wait_data *wait = &wait_data;
2993 memset (wait, 0, sizeof (struct wait_data));
2994 /* join each thread that's still running */
2995 THREAD_DEBUG (g_message ("%s: Joining each running thread...", __func__));
2997 mono_threads_lock ();
2999 THREAD_DEBUG (g_message("%s: No threads", __func__));
3000 mono_threads_unlock ();
3003 mono_threads_unlock ();
3006 mono_threads_lock ();
3007 if (shutting_down) {
3008 /* somebody else is shutting down */
3009 mono_threads_unlock ();
3012 THREAD_DEBUG (g_message ("%s: There are %d threads to join", __func__, mono_g_hash_table_size (threads));
3013 mono_g_hash_table_foreach (threads, print_tids, NULL));
3015 ResetEvent (background_change_event);
3017 /*We must zero all InternalThread pointers to avoid making the GC unhappy.*/
3018 memset (wait->threads, 0, MAXIMUM_WAIT_OBJECTS * SIZEOF_VOID_P);
3019 mono_g_hash_table_foreach (threads, build_wait_tids, wait);
3020 mono_threads_unlock ();
3022 /* Something to wait for */
3023 wait_for_tids_or_state_change (wait, INFINITE);
3025 THREAD_DEBUG (g_message ("%s: I have %d threads after waiting.", __func__, wait->num));
3026 } while(wait->num>0);
3028 mono_threads_set_shutting_down ();
3030 /* No new threads will be created after this point */
3032 mono_runtime_set_shutting_down ();
3034 THREAD_DEBUG (g_message ("%s: threadpool cleanup", __func__));
3035 mono_thread_pool_cleanup ();
3038 * Remove everything but the finalizer thread and self.
3039 * Also abort all the background threads
3042 mono_threads_lock ();
3045 /*We must zero all InternalThread pointers to avoid making the GC unhappy.*/
3046 memset (wait->threads, 0, MAXIMUM_WAIT_OBJECTS * SIZEOF_VOID_P);
3047 mono_g_hash_table_foreach_remove (threads, remove_and_abort_threads, wait);
3049 mono_threads_unlock ();
3051 THREAD_DEBUG (g_message ("%s: wait->num is now %d", __func__, wait->num));
3053 /* Something to wait for */
3054 wait_for_tids (wait, INFINITE);
3056 } while (wait->num > 0);
3059 * give the subthreads a chance to really quit (this is mainly needed
3060 * to get correct user and system times from getrusage/wait/time(1)).
3061 * This could be removed if we avoid pthread_detach() and use pthread_join().
3068 static void terminate_thread (gpointer key, gpointer value, gpointer user)
3070 MonoInternalThread *thread=(MonoInternalThread *)value;
3072 if(thread->tid != (gsize)user) {
3073 /*TerminateThread (thread->handle, -1);*/
3077 void mono_thread_abort_all_other_threads (void)
3079 gsize self = GetCurrentThreadId ();
3081 mono_threads_lock ();
3082 THREAD_DEBUG (g_message ("%s: There are %d threads to abort", __func__,
3083 mono_g_hash_table_size (threads));
3084 mono_g_hash_table_foreach (threads, print_tids, NULL));
3086 mono_g_hash_table_foreach (threads, terminate_thread, (gpointer)self);
3088 mono_threads_unlock ();
3092 collect_threads_for_suspend (gpointer key, gpointer value, gpointer user_data)
3094 MonoInternalThread *thread = (MonoInternalThread*)value;
3095 struct wait_data *wait = (struct wait_data*)user_data;
3099 * We try to exclude threads early, to avoid running into the MAXIMUM_WAIT_OBJECTS
3101 * This needs no locking.
3103 if ((thread->state & ThreadState_Suspended) != 0 ||
3104 (thread->state & ThreadState_Stopped) != 0)
3107 if (wait->num<MAXIMUM_WAIT_OBJECTS) {
3108 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
3112 wait->handles [wait->num] = handle;
3113 wait->threads [wait->num] = thread;
3119 * mono_thread_suspend_all_other_threads:
3121 * Suspend all managed threads except the finalizer thread and this thread. It is
3122 * not possible to resume them later.
3124 void mono_thread_suspend_all_other_threads (void)
3126 struct wait_data wait_data;
3127 struct wait_data *wait = &wait_data;
3129 gsize self = GetCurrentThreadId ();
3131 guint32 eventidx = 0;
3132 gboolean starting, finished;
3134 memset (wait, 0, sizeof (struct wait_data));
3136 * The other threads could be in an arbitrary state at this point, i.e.
3137 * they could be starting up, shutting down etc. This means that there could be
3138 * threads which are not even in the threads hash table yet.
3142 * First we set a barrier which will be checked by all threads before they
3143 * are added to the threads hash table, and they will exit if the flag is set.
3144 * This ensures that no threads could be added to the hash later.
3145 * We will use shutting_down as the barrier for now.
3147 g_assert (shutting_down);
3150 * We make multiple calls to WaitForMultipleObjects since:
3151 * - we can only wait for MAXIMUM_WAIT_OBJECTS threads
3152 * - some threads could exit without becoming suspended
3157 * Make a copy of the hashtable since we can't do anything with
3158 * threads while threads_mutex is held.
3161 /*We must zero all InternalThread pointers to avoid making the GC unhappy.*/
3162 memset (wait->threads, 0, MAXIMUM_WAIT_OBJECTS * SIZEOF_VOID_P);
3163 mono_threads_lock ();
3164 mono_g_hash_table_foreach (threads, collect_threads_for_suspend, wait);
3165 mono_threads_unlock ();
3167 events = g_new0 (gpointer, wait->num);
3169 /* Get the suspended events that we'll be waiting for */
3170 for (i = 0; i < wait->num; ++i) {
3171 MonoInternalThread *thread = wait->threads [i];
3172 gboolean signal_suspend = FALSE;
3174 if ((thread->tid == self) || mono_gc_is_finalizer_internal_thread (thread) || (thread->flags & MONO_THREAD_FLAG_DONT_MANAGE)) {
3175 //CloseHandle (wait->handles [i]);
3176 wait->threads [i] = NULL; /* ignore this thread in next loop */
3180 ensure_synch_cs_set (thread);
3182 EnterCriticalSection (thread->synch_cs);
3184 if (thread->suspended_event == NULL) {
3185 thread->suspended_event = CreateEvent (NULL, TRUE, FALSE, NULL);
3186 if (thread->suspended_event == NULL) {
3187 /* Forget this one and go on to the next */
3188 LeaveCriticalSection (thread->synch_cs);
3193 if ((thread->state & ThreadState_Suspended) != 0 ||
3194 (thread->state & ThreadState_StopRequested) != 0 ||
3195 (thread->state & ThreadState_Stopped) != 0) {
3196 LeaveCriticalSection (thread->synch_cs);
3197 CloseHandle (wait->handles [i]);
3198 wait->threads [i] = NULL; /* ignore this thread in next loop */
3202 if ((thread->state & ThreadState_SuspendRequested) == 0)
3203 signal_suspend = TRUE;
3205 events [eventidx++] = thread->suspended_event;
3207 /* Convert abort requests into suspend requests */
3208 if ((thread->state & ThreadState_AbortRequested) != 0)
3209 thread->state &= ~ThreadState_AbortRequested;
3211 thread->state |= ThreadState_SuspendRequested;
3213 LeaveCriticalSection (thread->synch_cs);
3215 /* Signal the thread to suspend */
3217 signal_thread_state_change (thread);
3221 WaitForMultipleObjectsEx (eventidx, events, TRUE, 100, FALSE);
3222 for (i = 0; i < wait->num; ++i) {
3223 MonoInternalThread *thread = wait->threads [i];
3228 ensure_synch_cs_set (thread);
3230 EnterCriticalSection (thread->synch_cs);
3231 if ((thread->state & ThreadState_Suspended) != 0) {
3232 CloseHandle (thread->suspended_event);
3233 thread->suspended_event = NULL;
3235 LeaveCriticalSection (thread->synch_cs);
3239 * If there are threads which are starting up, we wait until they
3240 * are suspended when they try to register in the threads hash.
3241 * This is guaranteed to finish, since the threads which can create new
3242 * threads get suspended after a while.
3243 * FIXME: The finalizer thread can still create new threads.
3245 mono_threads_lock ();
3246 if (threads_starting_up)
3247 starting = mono_g_hash_table_size (threads_starting_up) > 0;
3250 mono_threads_unlock ();
3262 collect_threads (gpointer key, gpointer value, gpointer user_data)
3264 MonoInternalThread *thread = (MonoInternalThread*)value;
3265 struct wait_data *wait = (struct wait_data*)user_data;
3268 if (wait->num<MAXIMUM_WAIT_OBJECTS) {
3269 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
3273 wait->handles [wait->num] = handle;
3274 wait->threads [wait->num] = thread;
3280 * mono_threads_request_thread_dump:
3282 * Ask all threads except the current to print their stacktrace to stdout.
3285 mono_threads_request_thread_dump (void)
3287 struct wait_data wait_data;
3288 struct wait_data *wait = &wait_data;
3291 memset (wait, 0, sizeof (struct wait_data));
3294 * Make a copy of the hashtable since we can't do anything with
3295 * threads while threads_mutex is held.
3297 mono_threads_lock ();
3298 mono_g_hash_table_foreach (threads, collect_threads, wait);
3299 mono_threads_unlock ();
3301 for (i = 0; i < wait->num; ++i) {
3302 MonoInternalThread *thread = wait->threads [i];
3304 if (!mono_gc_is_finalizer_internal_thread (thread) &&
3305 (thread != mono_thread_internal_current ()) &&
3306 !thread->thread_dump_requested) {
3307 thread->thread_dump_requested = TRUE;
3309 signal_thread_state_change (thread);
3312 CloseHandle (wait->handles [i]);
3317 * mono_thread_push_appdomain_ref:
3319 * Register that the current thread may have references to objects in domain
3320 * @domain on its stack. Each call to this function should be paired with a
3321 * call to pop_appdomain_ref.
3324 mono_thread_push_appdomain_ref (MonoDomain *domain)
3326 MonoInternalThread *thread = mono_thread_internal_current ();
3329 /* printf ("PUSH REF: %"G_GSIZE_FORMAT" -> %s.\n", (gsize)thread->tid, domain->friendly_name); */
3330 SPIN_LOCK (thread->lock_thread_id);
3331 thread->appdomain_refs = g_slist_prepend (thread->appdomain_refs, domain);
3332 SPIN_UNLOCK (thread->lock_thread_id);
3337 mono_thread_pop_appdomain_ref (void)
3339 MonoInternalThread *thread = mono_thread_internal_current ();
3342 /* printf ("POP REF: %"G_GSIZE_FORMAT" -> %s.\n", (gsize)thread->tid, ((MonoDomain*)(thread->appdomain_refs->data))->friendly_name); */
3343 /* FIXME: How can the list be empty ? */
3344 SPIN_LOCK (thread->lock_thread_id);
3345 if (thread->appdomain_refs)
3346 thread->appdomain_refs = g_slist_remove (thread->appdomain_refs, thread->appdomain_refs->data);
3347 SPIN_UNLOCK (thread->lock_thread_id);
3352 mono_thread_internal_has_appdomain_ref (MonoInternalThread *thread, MonoDomain *domain)
3355 SPIN_LOCK (thread->lock_thread_id);
3356 res = g_slist_find (thread->appdomain_refs, domain) != NULL;
3357 SPIN_UNLOCK (thread->lock_thread_id);
3362 mono_thread_has_appdomain_ref (MonoThread *thread, MonoDomain *domain)
3364 return mono_thread_internal_has_appdomain_ref (thread->internal_thread, domain);
3367 typedef struct abort_appdomain_data {
3368 struct wait_data wait;
3370 } abort_appdomain_data;
3373 collect_appdomain_thread (gpointer key, gpointer value, gpointer user_data)
3375 MonoInternalThread *thread = (MonoInternalThread*)value;
3376 abort_appdomain_data *data = (abort_appdomain_data*)user_data;
3377 MonoDomain *domain = data->domain;
3379 if (mono_thread_internal_has_appdomain_ref (thread, domain)) {
3380 /* printf ("ABORTING THREAD %p BECAUSE IT REFERENCES DOMAIN %s.\n", thread->tid, domain->friendly_name); */
3382 if(data->wait.num<MAXIMUM_WAIT_OBJECTS) {
3383 HANDLE handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
3386 data->wait.handles [data->wait.num] = handle;
3387 data->wait.threads [data->wait.num] = thread;
3390 /* Just ignore the rest, we can't do anything with
3398 * mono_threads_abort_appdomain_threads:
3400 * Abort threads which has references to the given appdomain.
3403 mono_threads_abort_appdomain_threads (MonoDomain *domain, int timeout)
3405 abort_appdomain_data user_data;
3407 int orig_timeout = timeout;
3410 THREAD_DEBUG (g_message ("%s: starting abort", __func__));
3412 start_time = mono_msec_ticks ();
3414 mono_threads_lock ();
3416 user_data.domain = domain;
3417 user_data.wait.num = 0;
3418 /* This shouldn't take any locks */
3419 mono_g_hash_table_foreach (threads, collect_appdomain_thread, &user_data);
3420 mono_threads_unlock ();
3422 if (user_data.wait.num > 0) {
3423 /* Abort the threads outside the threads lock */
3424 for (i = 0; i < user_data.wait.num; ++i)
3425 ves_icall_System_Threading_Thread_Abort (user_data.wait.threads [i], NULL);
3428 * We should wait for the threads either to abort, or to leave the
3429 * domain. We can't do the latter, so we wait with a timeout.
3431 wait_for_tids (&user_data.wait, 100);
3434 /* Update remaining time */
3435 timeout -= mono_msec_ticks () - start_time;
3436 start_time = mono_msec_ticks ();
3438 if (orig_timeout != -1 && timeout < 0)
3441 while (user_data.wait.num > 0);
3443 THREAD_DEBUG (g_message ("%s: abort done", __func__));
3449 clear_cached_culture (gpointer key, gpointer value, gpointer user_data)
3451 MonoInternalThread *thread = (MonoInternalThread*)value;
3452 MonoDomain *domain = (MonoDomain*)user_data;
3455 /* No locking needed here */
3456 /* FIXME: why no locking? writes to the cache are protected with synch_cs above */
3458 if (thread->cached_culture_info) {
3459 for (i = 0; i < NUM_CACHED_CULTURES * 2; ++i) {
3460 MonoObject *obj = mono_array_get (thread->cached_culture_info, MonoObject*, i);
3461 if (obj && obj->vtable->domain == domain)
3462 mono_array_set (thread->cached_culture_info, MonoObject*, i, NULL);
3468 * mono_threads_clear_cached_culture:
3470 * Clear the cached_current_culture from all threads if it is in the
3474 mono_threads_clear_cached_culture (MonoDomain *domain)
3476 mono_threads_lock ();
3477 mono_g_hash_table_foreach (threads, clear_cached_culture, domain);
3478 mono_threads_unlock ();
3482 * mono_thread_get_undeniable_exception:
3484 * Return an exception which needs to be raised when leaving a catch clause.
3485 * This is used for undeniable exception propagation.
3488 mono_thread_get_undeniable_exception (void)
3490 MonoInternalThread *thread = mono_thread_internal_current ();
3492 if (thread && thread->abort_exc && !is_running_protected_wrapper ()) {
3494 * FIXME: Clear the abort exception and return an AppDomainUnloaded
3495 * exception if the thread no longer references a dying appdomain.
3497 thread->abort_exc->trace_ips = NULL;
3498 thread->abort_exc->stack_trace = NULL;
3499 return thread->abort_exc;
3505 #if MONO_SMALL_CONFIG
3506 #define NUM_STATIC_DATA_IDX 4
3507 static const int static_data_size [NUM_STATIC_DATA_IDX] = {
3511 #define NUM_STATIC_DATA_IDX 8
3512 static const int static_data_size [NUM_STATIC_DATA_IDX] = {
3513 1024, 4096, 16384, 65536, 262144, 1048576, 4194304, 16777216
3517 static uintptr_t* static_reference_bitmaps [NUM_STATIC_DATA_IDX];
3521 mark_tls_slots (void *addr, MonoGCMarkFunc mark_func)
3524 gpointer *static_data = addr;
3525 for (i = 0; i < NUM_STATIC_DATA_IDX; ++i) {
3528 if (!static_data [i])
3530 numwords = 1 + static_data_size [i] / sizeof (gpointer) / (sizeof(uintptr_t) * 8);
3531 ptr = static_data [i];
3532 for (j = 0; j < numwords; ++j, ptr += sizeof (uintptr_t) * 8) {
3533 uintptr_t bmap = static_reference_bitmaps [i][j];
3536 if ((bmap & 1) && *p) {
3548 * mono_alloc_static_data
3550 * Allocate memory blocks for storing threads or context static data
3553 mono_alloc_static_data (gpointer **static_data_ptr, guint32 offset, gboolean threadlocal)
3555 guint idx = (offset >> 24) - 1;
3558 gpointer* static_data = *static_data_ptr;
3560 static void* tls_desc = NULL;
3563 tls_desc = mono_gc_make_root_descr_user (mark_tls_slots);
3565 static_data = mono_gc_alloc_fixed (static_data_size [0], threadlocal?tls_desc:NULL);
3566 *static_data_ptr = static_data;
3567 static_data [0] = static_data;
3570 for (i = 1; i <= idx; ++i) {
3571 if (static_data [i])
3574 static_data [i] = threadlocal?g_malloc0 (static_data_size [i]):mono_gc_alloc_fixed (static_data_size [i], NULL);
3576 static_data [i] = mono_gc_alloc_fixed (static_data_size [i], NULL);
3582 mono_free_static_data (gpointer* static_data, gboolean threadlocal)
3585 for (i = 1; i < NUM_STATIC_DATA_IDX; ++i) {
3586 if (!static_data [i])
3590 g_free (static_data [i]);
3592 mono_gc_free_fixed (static_data [i]);
3594 mono_gc_free_fixed (static_data [i]);
3597 mono_gc_free_fixed (static_data);
3601 * mono_init_static_data_info
3603 * Initializes static data counters
3605 static void mono_init_static_data_info (StaticDataInfo *static_data)
3607 static_data->idx = 0;
3608 static_data->offset = 0;
3609 static_data->freelist = NULL;
3613 * mono_alloc_static_data_slot
3615 * Generates an offset for static data. static_data contains the counters
3616 * used to generate it.
3619 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align)
3623 if (!static_data->idx && !static_data->offset) {
3625 * we use the first chunk of the first allocation also as
3626 * an array for the rest of the data
3628 static_data->offset = sizeof (gpointer) * NUM_STATIC_DATA_IDX;
3630 static_data->offset += align - 1;
3631 static_data->offset &= ~(align - 1);
3632 if (static_data->offset + size >= static_data_size [static_data->idx]) {
3633 static_data->idx ++;
3634 g_assert (size <= static_data_size [static_data->idx]);
3635 g_assert (static_data->idx < NUM_STATIC_DATA_IDX);
3636 static_data->offset = 0;
3638 offset = static_data->offset | ((static_data->idx + 1) << 24);
3639 static_data->offset += size;
3644 * ensure thread static fields already allocated are valid for thread
3645 * This function is called when a thread is created or on thread attach.
3648 thread_adjust_static_data (MonoInternalThread *thread)
3652 mono_threads_lock ();
3653 if (thread_static_info.offset || thread_static_info.idx > 0) {
3654 /* get the current allocated size */
3655 offset = thread_static_info.offset | ((thread_static_info.idx + 1) << 24);
3656 mono_alloc_static_data (&(thread->static_data), offset, TRUE);
3658 mono_threads_unlock ();
3662 alloc_thread_static_data_helper (gpointer key, gpointer value, gpointer user)
3664 MonoInternalThread *thread = value;
3665 guint32 offset = GPOINTER_TO_UINT (user);
3667 mono_alloc_static_data (&(thread->static_data), offset, TRUE);
3670 static MonoThreadDomainTls*
3671 search_tls_slot_in_freelist (StaticDataInfo *static_data, guint32 size, guint32 align)
3673 MonoThreadDomainTls* prev = NULL;
3674 MonoThreadDomainTls* tmp = static_data->freelist;
3676 if (tmp->size == size) {
3678 prev->next = tmp->next;
3680 static_data->freelist = tmp->next;
3689 update_tls_reference_bitmap (guint32 offset, uintptr_t *bitmap, int max_set)
3692 int idx = (offset >> 24) - 1;
3694 if (!static_reference_bitmaps [idx])
3695 static_reference_bitmaps [idx] = g_new0 (uintptr_t, 1 + static_data_size [idx] / sizeof(gpointer) / (sizeof(uintptr_t) * 8));
3696 rb = static_reference_bitmaps [idx];
3698 offset /= sizeof (gpointer);
3699 /* offset is now the bitmap offset */
3700 for (i = 0; i < max_set; ++i) {
3701 if (bitmap [i / sizeof (uintptr_t)] & (1L << (i & (sizeof (uintptr_t) * 8 -1))))
3702 rb [(offset + i) / (sizeof (uintptr_t) * 8)] |= (1L << ((offset + i) & (sizeof (uintptr_t) * 8 -1)));
3707 clear_reference_bitmap (guint32 offset, guint32 size)
3709 int idx = (offset >> 24) - 1;
3711 rb = static_reference_bitmaps [idx];
3713 offset /= sizeof (gpointer);
3714 size /= sizeof (gpointer);
3716 /* offset is now the bitmap offset */
3717 for (; offset < size; ++offset)
3718 rb [offset / (sizeof (uintptr_t) * 8)] &= ~(1L << (offset & (sizeof (uintptr_t) * 8 -1)));
3722 * The offset for a special static variable is composed of three parts:
3723 * a bit that indicates the type of static data (0:thread, 1:context),
3724 * an index in the array of chunks of memory for the thread (thread->static_data)
3725 * and an offset in that chunk of mem. This allows allocating less memory in the
3730 mono_alloc_special_static_data (guint32 static_type, guint32 size, guint32 align, uintptr_t *bitmap, int max_set)
3733 if (static_type == SPECIAL_STATIC_THREAD) {
3734 MonoThreadDomainTls *item;
3735 mono_threads_lock ();
3736 item = search_tls_slot_in_freelist (&thread_static_info, size, align);
3737 /*g_print ("TLS alloc: %d in domain %p (total: %d), cached: %p\n", size, mono_domain_get (), thread_static_info.offset, item);*/
3739 offset = item->offset;
3742 offset = mono_alloc_static_data_slot (&thread_static_info, size, align);
3744 update_tls_reference_bitmap (offset, bitmap, max_set);
3745 /* This can be called during startup */
3746 if (threads != NULL)
3747 mono_g_hash_table_foreach (threads, alloc_thread_static_data_helper, GUINT_TO_POINTER (offset));
3748 mono_threads_unlock ();
3750 g_assert (static_type == SPECIAL_STATIC_CONTEXT);
3751 mono_contexts_lock ();
3752 offset = mono_alloc_static_data_slot (&context_static_info, size, align);
3753 mono_contexts_unlock ();
3754 offset |= 0x80000000; /* Set the high bit to indicate context static data */
3760 mono_get_special_static_data (guint32 offset)
3762 /* The high bit means either thread (0) or static (1) data. */
3764 guint32 static_type = (offset & 0x80000000);
3767 offset &= 0x7fffffff;
3768 idx = (offset >> 24) - 1;
3770 if (static_type == 0) {
3771 return get_thread_static_data (mono_thread_internal_current (), offset);
3773 /* Allocate static data block under demand, since we don't have a list
3776 MonoAppContext *context = mono_context_get ();
3777 if (!context->static_data || !context->static_data [idx]) {
3778 mono_contexts_lock ();
3779 mono_alloc_static_data (&(context->static_data), offset, FALSE);
3780 mono_contexts_unlock ();
3782 return ((char*) context->static_data [idx]) + (offset & 0xffffff);
3792 free_thread_static_data_helper (gpointer key, gpointer value, gpointer user)
3794 MonoInternalThread *thread = value;
3795 TlsOffsetSize *data = user;
3796 int idx = (data->offset >> 24) - 1;
3799 if (!thread->static_data || !thread->static_data [idx])
3801 ptr = ((char*) thread->static_data [idx]) + (data->offset & 0xffffff);
3802 memset (ptr, 0, data->size);
3806 do_free_special (gpointer key, gpointer value, gpointer data)
3808 MonoClassField *field = key;
3809 guint32 offset = GPOINTER_TO_UINT (value);
3810 guint32 static_type = (offset & 0x80000000);
3813 size = mono_type_size (field->type, &align);
3814 /*g_print ("free %s , size: %d, offset: %x\n", field->name, size, offset);*/
3815 if (static_type == 0) {
3817 MonoThreadDomainTls *item = g_new0 (MonoThreadDomainTls, 1);
3818 data.offset = offset & 0x7fffffff;
3820 clear_reference_bitmap (data.offset, data.size);
3821 if (threads != NULL)
3822 mono_g_hash_table_foreach (threads, free_thread_static_data_helper, &data);
3823 item->offset = offset;
3826 if (!mono_runtime_is_shutting_down ()) {
3827 item->next = thread_static_info.freelist;
3828 thread_static_info.freelist = item;
3830 /* We could be called during shutdown after mono_thread_cleanup () is called */
3834 /* FIXME: free context static data as well */
3839 mono_alloc_special_static_data_free (GHashTable *special_static_fields)
3841 mono_threads_lock ();
3842 g_hash_table_foreach (special_static_fields, do_free_special, NULL);
3843 mono_threads_unlock ();
3846 static MonoClassField *local_slots = NULL;
3849 /* local tls data to get locals_slot from a thread */
3852 /* index in the locals_slot array */
3857 clear_local_slot (gpointer key, gpointer value, gpointer user_data)
3859 LocalSlotID *sid = user_data;
3860 MonoInternalThread *thread = (MonoInternalThread*)value;
3861 MonoArray *slots_array;
3863 * the static field is stored at: ((char*) thread->static_data [idx]) + (offset & 0xffffff);
3864 * it is for the right domain, so we need to check if it is allocated an initialized
3865 * for the current thread.
3867 /*g_print ("handling thread %p\n", thread);*/
3868 if (!thread->static_data || !thread->static_data [sid->idx])
3870 slots_array = *(MonoArray **)(((char*) thread->static_data [sid->idx]) + (sid->offset & 0xffffff));
3871 if (!slots_array || sid->slot >= mono_array_length (slots_array))
3873 mono_array_set (slots_array, MonoObject*, sid->slot, NULL);
3877 mono_thread_free_local_slot_values (int slot, MonoBoolean thread_local)
3885 local_slots = mono_class_get_field_from_name (mono_defaults.thread_class, "local_slots");
3887 g_warning ("local_slots field not found in Thread class");
3891 domain = mono_domain_get ();
3892 mono_domain_lock (domain);
3893 if (domain->special_static_fields)
3894 addr = g_hash_table_lookup (domain->special_static_fields, local_slots);
3895 mono_domain_unlock (domain);
3898 /*g_print ("freeing slot %d at %p\n", slot, addr);*/
3899 sid.offset = GPOINTER_TO_UINT (addr);
3900 sid.offset &= 0x7fffffff;
3901 sid.idx = (sid.offset >> 24) - 1;
3902 mono_threads_lock ();
3903 mono_g_hash_table_foreach (threads, clear_local_slot, &sid);
3904 mono_threads_unlock ();
3906 /* FIXME: clear the slot for MonoAppContexts, too */
3911 static void CALLBACK dummy_apc (ULONG_PTR param)
3915 static guint32 dummy_apc (gpointer param)
3922 * mono_thread_execute_interruption
3924 * Performs the operation that the requested thread state requires (abort,
3927 static MonoException* mono_thread_execute_interruption (MonoInternalThread *thread)
3929 ensure_synch_cs_set (thread);
3931 EnterCriticalSection (thread->synch_cs);
3933 /* MonoThread::interruption_requested can only be changed with atomics */
3934 if (InterlockedCompareExchange (&thread->interruption_requested, FALSE, TRUE)) {
3935 /* this will consume pending APC calls */
3936 WaitForSingleObjectEx (GetCurrentThread(), 0, TRUE);
3937 InterlockedDecrement (&thread_interruption_requested);
3939 /* Clear the interrupted flag of the thread so it can wait again */
3940 wapi_clear_interruption ();
3944 if ((thread->state & ThreadState_AbortRequested) != 0) {
3945 LeaveCriticalSection (thread->synch_cs);
3946 if (thread->abort_exc == NULL) {
3948 * This might be racy, but it has to be called outside the lock
3949 * since it calls managed code.
3951 MONO_OBJECT_SETREF (thread, abort_exc, mono_get_exception_thread_abort ());
3953 return thread->abort_exc;
3955 else if ((thread->state & ThreadState_SuspendRequested) != 0) {
3956 thread->state &= ~ThreadState_SuspendRequested;
3957 thread->state |= ThreadState_Suspended;
3958 thread->suspend_event = CreateEvent (NULL, TRUE, FALSE, NULL);
3959 if (thread->suspend_event == NULL) {
3960 LeaveCriticalSection (thread->synch_cs);
3963 if (thread->suspended_event)
3964 SetEvent (thread->suspended_event);
3966 LeaveCriticalSection (thread->synch_cs);
3968 if (shutting_down) {
3969 /* After we left the lock, the runtime might shut down so everything becomes invalid */
3974 WaitForSingleObject (thread->suspend_event, INFINITE);
3976 EnterCriticalSection (thread->synch_cs);
3978 CloseHandle (thread->suspend_event);
3979 thread->suspend_event = NULL;
3980 thread->state &= ~ThreadState_Suspended;
3982 /* The thread that requested the resume will have replaced this event
3983 * and will be waiting for it
3985 SetEvent (thread->resume_event);
3987 LeaveCriticalSection (thread->synch_cs);
3991 else if ((thread->state & ThreadState_StopRequested) != 0) {
3992 /* FIXME: do this through the JIT? */
3994 LeaveCriticalSection (thread->synch_cs);
3996 mono_thread_exit ();
3998 } else if (thread->thread_interrupt_requested) {
4000 thread->thread_interrupt_requested = FALSE;
4001 LeaveCriticalSection (thread->synch_cs);
4003 return(mono_get_exception_thread_interrupted ());
4006 LeaveCriticalSection (thread->synch_cs);
4012 * mono_thread_request_interruption
4014 * A signal handler can call this method to request the interruption of a
4015 * thread. The result of the interruption will depend on the current state of
4016 * the thread. If the result is an exception that needs to be throw, it is
4017 * provided as return value.
4020 mono_thread_request_interruption (gboolean running_managed)
4022 MonoInternalThread *thread = mono_thread_internal_current ();
4024 /* The thread may already be stopping */
4029 if (thread->interrupt_on_stop &&
4030 thread->state & ThreadState_StopRequested &&
4031 thread->state & ThreadState_Background)
4035 if (InterlockedCompareExchange (&thread->interruption_requested, 1, 0) == 1)
4038 if (!running_managed || is_running_protected_wrapper ()) {
4039 /* Can't stop while in unmanaged code. Increase the global interruption
4040 request count. When exiting the unmanaged method the count will be
4041 checked and the thread will be interrupted. */
4043 InterlockedIncrement (&thread_interruption_requested);
4045 if (mono_thread_notify_pending_exc_fn && !running_managed)
4046 /* The JIT will notify the thread about the interruption */
4047 /* This shouldn't take any locks */
4048 mono_thread_notify_pending_exc_fn ();
4050 /* this will awake the thread if it is in WaitForSingleObject
4052 /* Our implementation of this function ignores the func argument */
4053 QueueUserAPC ((PAPCFUNC)dummy_apc, thread->handle, NULL);
4057 return mono_thread_execute_interruption (thread);
4061 /*This function should be called by a thread after it has exited all of
4062 * its handle blocks at interruption time.*/
4064 mono_thread_resume_interruption (void)
4066 MonoInternalThread *thread = mono_thread_internal_current ();
4067 gboolean still_aborting;
4069 /* The thread may already be stopping */
4073 ensure_synch_cs_set (thread);
4074 EnterCriticalSection (thread->synch_cs);
4075 still_aborting = (thread->state & ThreadState_AbortRequested) != 0;
4076 LeaveCriticalSection (thread->synch_cs);
4078 /*This can happen if the protected block called Thread::ResetAbort*/
4079 if (!still_aborting)
4082 if (InterlockedCompareExchange (&thread->interruption_requested, 1, 0) == 1)
4084 InterlockedIncrement (&thread_interruption_requested);
4087 wapi_self_interrupt ();
4089 return mono_thread_execute_interruption (thread);
4092 gboolean mono_thread_interruption_requested ()
4094 if (thread_interruption_requested) {
4095 MonoInternalThread *thread = mono_thread_internal_current ();
4096 /* The thread may already be stopping */
4098 return (thread->interruption_requested);
4103 static void mono_thread_interruption_checkpoint_request (gboolean bypass_abort_protection)
4105 MonoInternalThread *thread = mono_thread_internal_current ();
4107 /* The thread may already be stopping */
4111 mono_debugger_check_interruption ();
4113 if (thread->interruption_requested && (bypass_abort_protection || !is_running_protected_wrapper ())) {
4114 MonoException* exc = mono_thread_execute_interruption (thread);
4115 if (exc) mono_raise_exception (exc);
4120 * Performs the interruption of the current thread, if one has been requested,
4121 * and the thread is not running a protected wrapper.
4123 void mono_thread_interruption_checkpoint ()
4125 mono_thread_interruption_checkpoint_request (FALSE);
4129 * Performs the interruption of the current thread, if one has been requested.
4131 void mono_thread_force_interruption_checkpoint ()
4133 mono_thread_interruption_checkpoint_request (TRUE);
4137 * mono_thread_get_and_clear_pending_exception:
4139 * Return any pending exceptions for the current thread and clear it as a side effect.
4142 mono_thread_get_and_clear_pending_exception (void)
4144 MonoInternalThread *thread = mono_thread_internal_current ();
4146 /* The thread may already be stopping */
4150 if (thread->interruption_requested && !is_running_protected_wrapper ()) {
4151 return mono_thread_execute_interruption (thread);
4154 if (thread->pending_exception) {
4155 MonoException *exc = thread->pending_exception;
4157 thread->pending_exception = NULL;
4165 * mono_set_pending_exception:
4167 * Set the pending exception of the current thread to EXC. On platforms which
4168 * support it, the exception will be thrown when execution returns to managed code.
4169 * On other platforms, this function is equivalent to mono_raise_exception ().
4170 * Internal calls which report exceptions using this function instead of
4171 * raise_exception () might be called by JITted code using a more efficient calling
4175 mono_set_pending_exception (MonoException *exc)
4177 MonoInternalThread *thread = mono_thread_internal_current ();
4179 /* The thread may already be stopping */
4183 if (mono_thread_notify_pending_exc_fn) {
4184 MONO_OBJECT_SETREF (thread, pending_exception, exc);
4186 mono_thread_notify_pending_exc_fn ();
4188 /* No way to notify the JIT about the exception, have to throw it now */
4189 mono_raise_exception (exc);
4194 * mono_thread_interruption_request_flag:
4196 * Returns the address of a flag that will be non-zero if an interruption has
4197 * been requested for a thread. The thread to interrupt may not be the current
4198 * thread, so an additional call to mono_thread_interruption_requested() or
4199 * mono_thread_interruption_checkpoint() is allways needed if the flag is not
4202 gint32* mono_thread_interruption_request_flag ()
4204 return &thread_interruption_requested;
4208 mono_thread_init_apartment_state (void)
4211 MonoInternalThread* thread = mono_thread_internal_current ();
4213 /* Positive return value indicates success, either
4214 * S_OK if this is first CoInitialize call, or
4215 * S_FALSE if CoInitialize already called, but with same
4216 * threading model. A negative value indicates failure,
4217 * probably due to trying to change the threading model.
4219 if (CoInitializeEx(NULL, (thread->apartment_state == ThreadApartmentState_STA)
4220 ? COINIT_APARTMENTTHREADED
4221 : COINIT_MULTITHREADED) < 0) {
4222 thread->apartment_state = ThreadApartmentState_Unknown;
4228 mono_thread_cleanup_apartment_state (void)
4231 MonoInternalThread* thread = mono_thread_internal_current ();
4233 if (thread && thread->apartment_state != ThreadApartmentState_Unknown) {
4240 mono_thread_set_state (MonoInternalThread *thread, MonoThreadState state)
4242 ensure_synch_cs_set (thread);
4244 EnterCriticalSection (thread->synch_cs);
4245 thread->state |= state;
4246 LeaveCriticalSection (thread->synch_cs);
4250 mono_thread_clr_state (MonoInternalThread *thread, MonoThreadState state)
4252 ensure_synch_cs_set (thread);
4254 EnterCriticalSection (thread->synch_cs);
4255 thread->state &= ~state;
4256 LeaveCriticalSection (thread->synch_cs);
4260 mono_thread_test_state (MonoInternalThread *thread, MonoThreadState test)
4262 gboolean ret = FALSE;
4264 ensure_synch_cs_set (thread);
4266 EnterCriticalSection (thread->synch_cs);
4268 if ((thread->state & test) != 0) {
4272 LeaveCriticalSection (thread->synch_cs);
4277 static MonoClassField *execution_context_field;
4280 get_execution_context_addr (void)
4282 MonoDomain *domain = mono_domain_get ();
4285 if (!execution_context_field) {
4286 execution_context_field = mono_class_get_field_from_name (mono_defaults.thread_class,
4288 g_assert (execution_context_field);
4291 g_assert (mono_class_try_get_vtable (domain, mono_defaults.appdomain_class));
4293 mono_domain_lock (domain);
4294 offset = GPOINTER_TO_UINT (g_hash_table_lookup (domain->special_static_fields, execution_context_field));
4295 mono_domain_unlock (domain);
4298 return (MonoObject**) mono_get_special_static_data (offset);
4302 mono_thread_get_execution_context (void)
4304 return *get_execution_context_addr ();
4308 mono_thread_set_execution_context (MonoObject *ec)
4310 *get_execution_context_addr () = ec;
4313 static gboolean has_tls_get = FALSE;
4316 mono_runtime_set_has_tls_get (gboolean val)
4322 mono_runtime_has_tls_get (void)