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 * (C) 2001 Ximian, Inc.
14 #define _WIN32_WINNT 0x0500
21 #include <mono/metadata/object.h>
22 #include <mono/metadata/domain-internals.h>
23 #include <mono/metadata/profiler-private.h>
24 #include <mono/metadata/threads.h>
25 #include <mono/metadata/threadpool.h>
26 #include <mono/metadata/threads-types.h>
27 #include <mono/metadata/exception.h>
28 #include <mono/metadata/environment.h>
29 #include <mono/metadata/monitor.h>
30 #include <mono/metadata/gc-internal.h>
31 #include <mono/metadata/marshal.h>
32 #include <mono/io-layer/io-layer.h>
33 #include <mono/metadata/object-internals.h>
34 #include <mono/metadata/mono-debug-debugger.h>
35 #include <mono/utils/mono-compiler.h>
36 #include <mono/utils/mono-mmap.h>
37 #include <mono/utils/mono-membar.h>
39 #include <mono/os/gc_wrapper.h>
41 /*#define THREAD_DEBUG(a) do { a; } while (0)*/
42 #define THREAD_DEBUG(a)
43 /*#define THREAD_WAIT_DEBUG(a) do { a; } while (0)*/
44 #define THREAD_WAIT_DEBUG(a)
45 /*#define LIBGC_DEBUG(a) do { a; } while (0)*/
46 #define LIBGC_DEBUG(a)
48 /* Provide this for systems with glib < 2.6 */
49 #ifndef G_GSIZE_FORMAT
50 # if GLIB_SIZEOF_LONG == 8
51 # define G_GSIZE_FORMAT "lu"
53 # define G_GSIZE_FORMAT "u"
59 guint32 (*func)(void *);
76 typedef struct _MonoThreadDomainTls MonoThreadDomainTls;
77 struct _MonoThreadDomainTls {
78 MonoThreadDomainTls *next;
86 MonoThreadDomainTls *freelist;
91 MonoHazardousFreeFunc free_func;
94 /* Number of cached culture objects in the MonoThread->cached_culture_info array
95 * (per-type): we use the first NUM entries for CultureInfo and the last for
96 * UICultureInfo. So the size of the array is really NUM_CACHED_CULTURES * 2.
98 #define NUM_CACHED_CULTURES 4
99 #define CULTURES_START_IDX 0
100 #define UICULTURES_START_IDX NUM_CACHED_CULTURES
102 /* Controls access to the 'threads' hash table */
103 #define mono_threads_lock() EnterCriticalSection (&threads_mutex)
104 #define mono_threads_unlock() LeaveCriticalSection (&threads_mutex)
105 static CRITICAL_SECTION threads_mutex;
107 /* Controls access to context static data */
108 #define mono_contexts_lock() EnterCriticalSection (&contexts_mutex)
109 #define mono_contexts_unlock() LeaveCriticalSection (&contexts_mutex)
110 static CRITICAL_SECTION contexts_mutex;
112 /* Holds current status of static data heap */
113 static StaticDataInfo thread_static_info;
114 static StaticDataInfo context_static_info;
116 /* The hash of existing threads (key is thread ID) that need joining
119 static MonoGHashTable *threads=NULL;
121 /* The TLS key that holds the MonoObject assigned to each thread */
122 static guint32 current_object_key = -1;
124 #ifdef HAVE_KW_THREAD
125 /* we need to use both the Tls* functions and __thread because
126 * the gc needs to see all the threads
128 static __thread MonoThread * tls_current_object MONO_TLS_FAST;
129 #define SET_CURRENT_OBJECT(x) do { \
130 tls_current_object = x; \
131 TlsSetValue (current_object_key, x); \
133 #define GET_CURRENT_OBJECT() tls_current_object
135 #define SET_CURRENT_OBJECT(x) TlsSetValue (current_object_key, x);
136 #define GET_CURRENT_OBJECT() (MonoThread*) TlsGetValue (current_object_key);
139 /* function called at thread start */
140 static MonoThreadStartCB mono_thread_start_cb = NULL;
142 /* function called at thread attach */
143 static MonoThreadAttachCB mono_thread_attach_cb = NULL;
145 /* function called at thread cleanup */
146 static MonoThreadCleanupFunc mono_thread_cleanup_fn = NULL;
148 /* The default stack size for each thread */
149 static guint32 default_stacksize = 0;
150 #define default_stacksize_for_thread(thread) ((thread)->stack_size? (thread)->stack_size: default_stacksize)
152 static void thread_adjust_static_data (MonoThread *thread);
153 static void mono_init_static_data_info (StaticDataInfo *static_data);
154 static guint32 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align);
155 static gboolean mono_thread_resume (MonoThread* thread);
156 static void mono_thread_start (MonoThread *thread);
157 static void signal_thread_state_change (MonoThread *thread);
159 /* Spin lock for InterlockedXXX 64 bit functions */
160 #define mono_interlocked_lock() EnterCriticalSection (&interlocked_mutex)
161 #define mono_interlocked_unlock() LeaveCriticalSection (&interlocked_mutex)
162 static CRITICAL_SECTION interlocked_mutex;
164 /* global count of thread interruptions requested */
165 static gint32 thread_interruption_requested = 0;
167 /* Event signaled when a thread changes its background mode */
168 static HANDLE background_change_event;
170 /* The table for small ID assignment */
171 static CRITICAL_SECTION small_id_mutex;
172 static int small_id_table_size = 0;
173 static int small_id_next = 0;
174 static int highest_small_id = -1;
175 static MonoThread **small_id_table = NULL;
177 /* The hazard table */
178 #define HAZARD_TABLE_MAX_SIZE 16384 /* There cannot be more threads than this number. */
179 static volatile int hazard_table_size = 0;
180 static MonoThreadHazardPointers * volatile hazard_table = NULL;
182 /* The table where we keep pointers to blocks to be freed but that
183 have to wait because they're guarded by a hazard pointer. */
184 static CRITICAL_SECTION delayed_free_table_mutex;
185 static GArray *delayed_free_table = NULL;
188 mono_thread_get_tls_key (void)
190 return current_object_key;
194 mono_thread_get_tls_offset (void)
197 MONO_THREAD_VAR_OFFSET (tls_current_object,offset);
201 /* handle_store() and handle_remove() manage the array of threads that
202 * still need to be waited for when the main thread exits.
204 static void handle_store(MonoThread *thread)
206 mono_threads_lock ();
208 THREAD_DEBUG (g_message ("%s: thread %p ID %"G_GSIZE_FORMAT, __func__, thread, (gsize)thread->tid));
211 MONO_GC_REGISTER_ROOT (threads);
212 threads=mono_g_hash_table_new(NULL, NULL);
215 /* We don't need to duplicate thread->handle, because it is
216 * only closed when the thread object is finalized by the GC.
218 mono_g_hash_table_insert(threads, (gpointer)(gsize)(thread->tid),
221 mono_threads_unlock ();
224 static gboolean handle_remove(MonoThread *thread)
227 gsize tid = thread->tid;
229 THREAD_DEBUG (g_message ("%s: thread ID %"G_GSIZE_FORMAT, __func__, tid));
231 mono_threads_lock ();
234 /* We have to check whether the thread object for the
235 * tid is still the same in the table because the
236 * thread might have been destroyed and the tid reused
237 * in the meantime, in which case the tid would be in
238 * the table, but with another thread object.
240 if (mono_g_hash_table_lookup (threads, (gpointer)tid) == thread) {
241 mono_g_hash_table_remove (threads, (gpointer)tid);
250 mono_threads_unlock ();
252 /* Don't close the handle here, wait for the object finalizer
253 * to do it. Otherwise, the following race condition applies:
255 * 1) Thread exits (and handle_remove() closes the handle)
257 * 2) Some other handle is reassigned the same slot
259 * 3) Another thread tries to join the first thread, and
260 * blocks waiting for the reassigned handle to be signalled
261 * (which might never happen). This is possible, because the
262 * thread calling Join() still has a reference to the first
269 * Allocate a small thread id.
271 * FIXME: The biggest part of this function is very similar to
272 * domain_id_alloc() in domain.c and should be merged.
275 small_id_alloc (MonoThread *thread)
279 EnterCriticalSection (&small_id_mutex);
281 if (!small_id_table) {
282 small_id_table_size = 2;
283 small_id_table = mono_gc_alloc_fixed (small_id_table_size * sizeof (MonoThread*), NULL);
285 for (i = small_id_next; i < small_id_table_size; ++i) {
286 if (!small_id_table [i]) {
292 for (i = 0; i < small_id_next; ++i) {
293 if (!small_id_table [i]) {
300 MonoThread **new_table;
301 int new_size = small_id_table_size * 2;
302 if (new_size >= (1 << 16))
303 g_assert_not_reached ();
304 id = small_id_table_size;
305 new_table = mono_gc_alloc_fixed (new_size * sizeof (MonoThread*), NULL);
306 memcpy (new_table, small_id_table, small_id_table_size * sizeof (void*));
307 mono_gc_free_fixed (small_id_table);
308 small_id_table = new_table;
309 small_id_table_size = new_size;
311 thread->small_id = id;
312 g_assert (small_id_table [id] == NULL);
313 small_id_table [id] = thread;
315 if (small_id_next > small_id_table_size)
318 if (id >= hazard_table_size) {
320 int pagesize = mono_pagesize ();
321 int num_pages = (hazard_table_size * sizeof (MonoThreadHazardPointers) + pagesize - 1) / pagesize;
323 if (hazard_table == NULL) {
324 hazard_table = mono_valloc (NULL,
325 sizeof (MonoThreadHazardPointers) * HAZARD_TABLE_MAX_SIZE,
329 g_assert (hazard_table != NULL);
330 page_addr = (guint8*)hazard_table + num_pages * pagesize;
332 g_assert (id < HAZARD_TABLE_MAX_SIZE);
334 mono_mprotect (page_addr, pagesize, MONO_MMAP_READ | MONO_MMAP_WRITE);
337 hazard_table_size = num_pages * pagesize / sizeof (MonoThreadHazardPointers);
339 g_assert (id < hazard_table_size);
341 hazard_table [id].hazard_pointers [0] = NULL;
342 hazard_table [id].hazard_pointers [1] = NULL;
345 if (id > highest_small_id) {
346 highest_small_id = id;
347 mono_memory_write_barrier ();
350 LeaveCriticalSection (&small_id_mutex);
356 small_id_free (int id)
358 g_assert (id >= 0 && id < small_id_table_size);
359 g_assert (small_id_table [id] != NULL);
361 small_id_table [id] = NULL;
365 is_pointer_hazardous (gpointer p)
368 int highest = highest_small_id;
370 g_assert (highest < hazard_table_size);
372 for (i = 0; i <= highest; ++i) {
373 if (hazard_table [i].hazard_pointers [0] == p
374 || hazard_table [i].hazard_pointers [1] == p)
381 MonoThreadHazardPointers*
382 mono_hazard_pointer_get (void)
384 MonoThread *current_thread = mono_thread_current ();
386 if (!(current_thread && current_thread->small_id >= 0)) {
387 static MonoThreadHazardPointers emerg_hazard_table;
388 g_warning ("Thread %p may have been prematurely finalized", current_thread);
389 return &emerg_hazard_table;
392 return &hazard_table [current_thread->small_id];
396 mono_thread_hazardous_free_or_queue (gpointer p, MonoHazardousFreeFunc free_func)
400 /* First try to free a few entries in the delayed free
402 for (i = 2; i >= 0; --i) {
403 if (delayed_free_table->len > i) {
404 DelayedFreeItem item;
407 EnterCriticalSection (&delayed_free_table_mutex);
408 /* We have to check the length again because another
409 thread might have freed an item before we acquired
411 if (delayed_free_table->len > i) {
412 item = g_array_index (delayed_free_table, DelayedFreeItem, i);
414 if (!is_pointer_hazardous (item.p))
415 g_array_remove_index_fast (delayed_free_table, i);
419 LeaveCriticalSection (&delayed_free_table_mutex);
422 item.free_func (item.p);
426 /* Now see if the pointer we're freeing is hazardous. If it
427 isn't, free it. Otherwise put it in the delay list. */
428 if (is_pointer_hazardous (p)) {
429 DelayedFreeItem item = { p, free_func };
431 ++mono_stats.hazardous_pointer_count;
433 EnterCriticalSection (&delayed_free_table_mutex);
434 g_array_append_val (delayed_free_table, item);
435 LeaveCriticalSection (&delayed_free_table_mutex);
440 static void ensure_synch_cs_set (MonoThread *thread)
442 CRITICAL_SECTION *synch_cs;
444 if (thread->synch_cs != NULL) {
448 synch_cs = g_new0 (CRITICAL_SECTION, 1);
449 InitializeCriticalSection (synch_cs);
451 if (InterlockedCompareExchangePointer ((gpointer *)&thread->synch_cs,
452 synch_cs, NULL) != NULL) {
453 /* Another thread must have installed this CS */
454 DeleteCriticalSection (synch_cs);
460 * NOTE: this function can be called also for threads different from the current one:
461 * make sure no code called from it will ever assume it is run on the thread that is
462 * getting cleaned up.
464 static void thread_cleanup (MonoThread *thread)
466 g_assert (thread != NULL);
468 /* if the thread is not in the hash it has been removed already */
469 if (!handle_remove (thread))
471 mono_release_type_locks (thread);
473 EnterCriticalSection (thread->synch_cs);
475 thread->state |= ThreadState_Stopped;
476 thread->state &= ~ThreadState_Background;
478 LeaveCriticalSection (thread->synch_cs);
480 mono_profiler_thread_end (thread->tid);
482 if (thread == mono_thread_current ())
483 mono_thread_pop_appdomain_ref ();
485 if (thread->serialized_culture_info)
486 g_free (thread->serialized_culture_info);
488 thread->cached_culture_info = NULL;
490 mono_gc_free_fixed (thread->static_data);
491 thread->static_data = NULL;
493 if (mono_thread_cleanup_fn)
494 mono_thread_cleanup_fn (thread);
496 small_id_free (thread->small_id);
497 thread->small_id = -2;
500 static guint32 WINAPI start_wrapper(void *data)
502 struct StartInfo *start_info=(struct StartInfo *)data;
503 guint32 (*start_func)(void *);
506 MonoThread *thread=start_info->obj;
507 MonoObject *start_delegate = start_info->delegate;
509 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Start wrapper", __func__, GetCurrentThreadId ()));
511 /* We can be sure start_info->obj->tid and
512 * start_info->obj->handle have been set, because the thread
513 * was created suspended, and these values were set before the
519 SET_CURRENT_OBJECT (thread);
521 /* Every thread references the appdomain which created it */
522 mono_thread_push_appdomain_ref (start_info->domain);
524 if (!mono_domain_set (start_info->domain, FALSE)) {
525 /* No point in raising an appdomain_unloaded exception here */
526 /* FIXME: Cleanup here */
527 mono_thread_pop_appdomain_ref ();
531 start_func = start_info->func;
532 start_arg = start_info->start_arg;
534 /* This MUST be called before any managed code can be
535 * executed, as it calls the callback function that (for the
536 * jit) sets the lmf marker.
538 mono_thread_new_init (tid, &tid, start_func);
539 thread->stack_ptr = &tid;
541 LIBGC_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT",%d) Setting thread stack to %p", __func__, GetCurrentThreadId (), getpid (), thread->stack_ptr));
543 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Setting current_object_key to %p", __func__, GetCurrentThreadId (), thread));
545 mono_profiler_thread_start (tid);
547 /* On 2.0 profile (and higher), set explicitly since state might have been
549 if (mono_get_runtime_info ()->framework_version [0] != '1') {
550 if (thread->apartment_state == ThreadApartmentState_Unknown)
551 thread->apartment_state = ThreadApartmentState_MTA;
554 mono_thread_init_apartment_state ();
556 if(thread->start_notify!=NULL) {
557 /* Let the thread that called Start() know we're
560 ReleaseSemaphore (thread->start_notify, 1, NULL);
565 thread_adjust_static_data (thread);
567 g_message ("%s: start_wrapper for %"G_GSIZE_FORMAT, __func__,
571 /* start_func is set only for unmanaged start functions */
573 start_func (start_arg);
576 g_assert (start_delegate != NULL);
577 args [0] = start_arg;
578 /* we may want to handle the exception here. See comment below on unhandled exceptions */
579 mono_runtime_delegate_invoke (start_delegate, args, NULL);
582 /* If the thread calls ExitThread at all, this remaining code
583 * will not be executed, but the main thread will eventually
584 * call thread_cleanup() on this thread's behalf.
587 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Start wrapper terminating", __func__, GetCurrentThreadId ()));
589 thread_cleanup (thread);
591 /* Do any cleanup needed for apartment state. This
592 * cannot be done in thread_cleanup since thread_cleanup could be
593 * called for a thread other than the current thread.
594 * mono_thread_cleanup_apartment_state cleans up apartment
595 * for the current thead */
596 mono_thread_cleanup_apartment_state ();
598 /* Remove the reference to the thread object in the TLS data,
599 * so the thread object can be finalized. This won't be
600 * reached if the thread threw an uncaught exception, so those
601 * thread handles will stay referenced :-( (This is due to
602 * missing support for scanning thread-specific data in the
603 * Boehm GC - the io-layer keeps a GC-visible hash of pointers
606 SET_CURRENT_OBJECT (NULL);
611 void mono_thread_new_init (gsize tid, gpointer stack_start, gpointer func)
613 if (mono_thread_start_cb) {
614 mono_thread_start_cb (tid, stack_start, func);
618 void mono_threads_set_default_stacksize (guint32 stacksize)
620 default_stacksize = stacksize;
623 guint32 mono_threads_get_default_stacksize (void)
625 return default_stacksize;
628 void mono_thread_create_internal (MonoDomain *domain, gpointer func, gpointer arg, gboolean threadpool_thread)
631 HANDLE thread_handle;
632 struct StartInfo *start_info;
635 thread=(MonoThread *)mono_object_new (domain,
636 mono_defaults.thread_class);
638 start_info=g_new0 (struct StartInfo, 1);
639 start_info->func = func;
640 start_info->obj = thread;
641 start_info->domain = domain;
642 start_info->start_arg = arg;
644 /* Create suspended, so we can do some housekeeping before the thread
647 thread_handle = CreateThread(NULL, default_stacksize_for_thread (thread), (LPTHREAD_START_ROUTINE)start_wrapper, start_info,
648 CREATE_SUSPENDED, &tid);
649 THREAD_DEBUG (g_message ("%s: Started thread ID %"G_GSIZE_FORMAT" (handle %p)", __func__, tid, thread_handle));
650 if (thread_handle == NULL) {
651 /* The thread couldn't be created, so throw an exception */
652 mono_raise_exception (mono_get_exception_execution_engine ("Couldn't create thread"));
656 thread->handle=thread_handle;
658 thread->apartment_state=ThreadApartmentState_Unknown;
659 small_id_alloc (thread);
661 thread->synch_cs = g_new0 (CRITICAL_SECTION, 1);
662 InitializeCriticalSection (thread->synch_cs);
664 thread->threadpool_thread = threadpool_thread;
666 handle_store(thread);
668 ResumeThread (thread_handle);
672 mono_thread_create (MonoDomain *domain, gpointer func, gpointer arg)
674 mono_thread_create_internal (domain, func, arg, FALSE);
678 * mono_thread_get_stack_bounds:
680 * Return the address and size of the current threads stack. Return NULL as the stack
681 * address if the stack address cannot be determined.
684 mono_thread_get_stack_bounds (guint8 **staddr, size_t *stsize)
686 #if defined(HAVE_PTHREAD_GET_STACKSIZE_NP) && defined(HAVE_PTHREAD_GET_STACKADDR_NP)
687 *staddr = (guint8*)pthread_get_stackaddr_np (pthread_self ());
688 *stsize = pthread_get_stacksize_np (pthread_self ());
690 /* FIXME: simplify the mess below */
691 #elif !defined(PLATFORM_WIN32)
693 guint8 *current = (guint8*)&attr;
695 pthread_attr_init (&attr);
696 #ifdef HAVE_PTHREAD_GETATTR_NP
697 pthread_getattr_np (pthread_self(), &attr);
699 #ifdef HAVE_PTHREAD_ATTR_GET_NP
700 pthread_attr_get_np (pthread_self(), &attr);
703 pthread_attr_getstacksize (&attr, &stsize);
712 pthread_attr_getstack (&attr, (void**)staddr, stsize);
714 g_assert ((current > *staddr) && (current < *staddr + *stsize));
717 pthread_attr_destroy (&attr);
722 mono_thread_attach (MonoDomain *domain)
725 HANDLE thread_handle;
728 if ((thread = mono_thread_current ())) {
729 if (domain != mono_domain_get ())
730 mono_domain_set (domain, TRUE);
731 /* Already attached */
735 if (!mono_gc_register_thread (&domain)) {
736 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 ());
739 thread = (MonoThread *)mono_object_new (domain,
740 mono_defaults.thread_class);
742 thread_handle = GetCurrentThread ();
743 g_assert (thread_handle);
745 tid=GetCurrentThreadId ();
748 * The handle returned by GetCurrentThread () is a pseudo handle, so it can't be used to
749 * refer to the thread from other threads for things like aborting.
751 DuplicateHandle (GetCurrentProcess (), thread_handle, GetCurrentProcess (), &thread_handle,
752 THREAD_ALL_ACCESS, TRUE, 0);
754 thread->handle=thread_handle;
756 thread->apartment_state=ThreadApartmentState_Unknown;
757 small_id_alloc (thread);
758 thread->stack_ptr = &tid;
760 thread->synch_cs = g_new0 (CRITICAL_SECTION, 1);
761 InitializeCriticalSection (thread->synch_cs);
763 THREAD_DEBUG (g_message ("%s: Attached thread ID %"G_GSIZE_FORMAT" (handle %p)", __func__, tid, thread_handle));
765 handle_store(thread);
767 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Setting current_object_key to %p", __func__, GetCurrentThreadId (), thread));
769 SET_CURRENT_OBJECT (thread);
770 mono_domain_set (domain, TRUE);
772 thread_adjust_static_data (thread);
774 if (mono_thread_attach_cb) {
778 mono_thread_get_stack_bounds (&staddr, &stsize);
781 mono_thread_attach_cb (tid, &tid);
783 mono_thread_attach_cb (tid, staddr + stsize);
790 mono_thread_detach (MonoThread *thread)
792 g_return_if_fail (thread != NULL);
794 THREAD_DEBUG (g_message ("%s: mono_thread_detach for %p (%"G_GSIZE_FORMAT")", __func__, thread, (gsize)thread->tid));
796 thread_cleanup (thread);
798 SET_CURRENT_OBJECT (NULL);
800 /* Don't need to CloseHandle this thread, even though we took a
801 * reference in mono_thread_attach (), because the GC will do it
802 * when the Thread object is finalised.
809 MonoThread *thread = mono_thread_current ();
811 THREAD_DEBUG (g_message ("%s: mono_thread_exit for %p (%"G_GSIZE_FORMAT")", __func__, thread, (gsize)thread->tid));
813 thread_cleanup (thread);
814 SET_CURRENT_OBJECT (NULL);
816 /* we could add a callback here for embedders to use. */
817 if (thread == mono_thread_get_main ())
818 exit (mono_environment_exitcode_get ());
822 HANDLE ves_icall_System_Threading_Thread_Thread_internal(MonoThread *this,
825 guint32 (*start_func)(void *);
826 struct StartInfo *start_info;
832 THREAD_DEBUG (g_message("%s: Trying to start a new thread: this (%p) start (%p)", __func__, this, start));
834 ensure_synch_cs_set (this);
836 EnterCriticalSection (this->synch_cs);
838 if ((this->state & ThreadState_Unstarted) == 0) {
839 LeaveCriticalSection (this->synch_cs);
840 mono_raise_exception (mono_get_exception_thread_state ("Thread has already been started."));
846 if ((this->state & ThreadState_Aborted) != 0) {
847 LeaveCriticalSection (this->synch_cs);
852 /* This is freed in start_wrapper */
853 start_info = g_new0 (struct StartInfo, 1);
854 start_info->func = start_func;
855 start_info->start_arg = this->start_obj; /* FIXME: GC object stored in unmanaged memory */
856 start_info->delegate = start;
857 start_info->obj = this;
858 start_info->domain = mono_domain_get ();
860 this->start_notify=CreateSemaphore (NULL, 0, 0x7fffffff, NULL);
861 if(this->start_notify==NULL) {
862 LeaveCriticalSection (this->synch_cs);
863 g_warning ("%s: CreateSemaphore error 0x%x", __func__, GetLastError ());
867 thread=CreateThread(NULL, default_stacksize_for_thread (this), (LPTHREAD_START_ROUTINE)start_wrapper, start_info,
868 CREATE_SUSPENDED, &tid);
870 LeaveCriticalSection (this->synch_cs);
871 g_warning("%s: CreateThread error 0x%x", __func__, GetLastError());
877 small_id_alloc (this);
879 /* Don't call handle_store() here, delay it to Start.
880 * We can't join a thread (trying to will just block
881 * forever) until it actually starts running, so don't
882 * store the handle till then.
885 mono_thread_start (this);
887 this->state &= ~ThreadState_Unstarted;
889 THREAD_DEBUG (g_message ("%s: Started thread ID %"G_GSIZE_FORMAT" (handle %p)", __func__, tid, thread));
891 LeaveCriticalSection (this->synch_cs);
896 void ves_icall_System_Threading_Thread_Thread_init (MonoThread *this)
900 ensure_synch_cs_set (this);
903 void ves_icall_System_Threading_Thread_Thread_free_internal (MonoThread *this,
908 THREAD_DEBUG (g_message ("%s: Closing thread %p, handle %p", __func__, this, thread));
910 CloseHandle (thread);
912 DeleteCriticalSection (this->synch_cs);
913 g_free (this->synch_cs);
914 this->synch_cs = NULL;
917 static void mono_thread_start (MonoThread *thread)
921 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Launching thread %p (%"G_GSIZE_FORMAT")", __func__, GetCurrentThreadId (), thread, (gsize)thread->tid));
923 /* Only store the handle when the thread is about to be
924 * launched, to avoid the main thread deadlocking while trying
925 * to clean up a thread that will never be signalled.
927 handle_store (thread);
929 ResumeThread (thread->handle);
931 if(thread->start_notify!=NULL) {
932 /* Wait for the thread to set up its TLS data etc, so
933 * theres no potential race condition if someone tries
934 * to look up the data believing the thread has
938 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") waiting for thread %p (%"G_GSIZE_FORMAT") to start", __func__, GetCurrentThreadId (), thread, (gsize)thread->tid));
940 WaitForSingleObjectEx (thread->start_notify, INFINITE, FALSE);
941 CloseHandle (thread->start_notify);
942 thread->start_notify = NULL;
945 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Done launching thread %p (%"G_GSIZE_FORMAT")", __func__, GetCurrentThreadId (), thread, (gsize)thread->tid));
948 void ves_icall_System_Threading_Thread_Sleep_internal(gint32 ms)
950 MonoThread *thread = mono_thread_current ();
954 THREAD_DEBUG (g_message ("%s: Sleeping for %d ms", __func__, ms));
956 mono_thread_current_check_pending_interrupt ();
958 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
962 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
965 void ves_icall_System_Threading_Thread_SpinWait_internal (gint32 iterations)
969 for(i = 0; i < iterations; i++) {
970 /* We're busy waiting, but at least we can tell the
971 * scheduler to let someone else have a go...
978 ves_icall_System_Threading_Thread_GetDomainID (void)
982 return mono_domain_get()->domain_id;
986 ves_icall_System_Threading_Thread_GetName_internal (MonoThread *this_obj)
990 ensure_synch_cs_set (this_obj);
992 EnterCriticalSection (this_obj->synch_cs);
997 str = mono_string_new_utf16 (mono_domain_get (), this_obj->name, this_obj->name_len);
999 LeaveCriticalSection (this_obj->synch_cs);
1005 ves_icall_System_Threading_Thread_SetName_internal (MonoThread *this_obj, MonoString *name)
1007 ensure_synch_cs_set (this_obj);
1009 EnterCriticalSection (this_obj->synch_cs);
1011 if (this_obj->name) {
1012 LeaveCriticalSection (this_obj->synch_cs);
1014 mono_raise_exception (mono_get_exception_invalid_operation ("Thread.Name can only be set once."));
1018 this_obj->name = g_new (gunichar2, mono_string_length (name));
1019 memcpy (this_obj->name, mono_string_chars (name), mono_string_length (name) * 2);
1020 this_obj->name_len = mono_string_length (name);
1023 this_obj->name = NULL;
1025 LeaveCriticalSection (this_obj->synch_cs);
1029 lookup_cached_culture (MonoThread *this, MonoDomain *domain, int start_idx)
1034 if (this->cached_culture_info) {
1035 domain = mono_domain_get ();
1036 for (i = start_idx; i < start_idx + NUM_CACHED_CULTURES; ++i) {
1037 res = mono_array_get (this->cached_culture_info, MonoObject*, i);
1038 if (res && res->vtable->domain == domain)
1047 ves_icall_System_Threading_Thread_GetCachedCurrentCulture (MonoThread *this)
1049 return lookup_cached_culture (this, mono_domain_get (), CULTURES_START_IDX);
1053 ves_icall_System_Threading_Thread_GetSerializedCurrentCulture (MonoThread *this)
1057 ensure_synch_cs_set (this);
1059 EnterCriticalSection (this->synch_cs);
1061 if (this->serialized_culture_info) {
1062 res = mono_array_new (mono_domain_get (), mono_defaults.byte_class, this->serialized_culture_info_len);
1063 memcpy (mono_array_addr (res, guint8, 0), this->serialized_culture_info, this->serialized_culture_info_len);
1068 LeaveCriticalSection (this->synch_cs);
1074 cache_culture (MonoThread *this, MonoObject *culture, int start_idx)
1077 MonoDomain *domain = mono_domain_get ();
1080 int same_domain_slot = -1;
1082 ensure_synch_cs_set (this);
1084 EnterCriticalSection (this->synch_cs);
1086 if (!this->cached_culture_info)
1087 this->cached_culture_info = mono_array_new (mono_object_domain (this), mono_defaults.object_class, NUM_CACHED_CULTURES * 2);
1089 for (i = start_idx; i < start_idx + NUM_CACHED_CULTURES; ++i) {
1090 obj = mono_array_get (this->cached_culture_info, MonoObject*, i);
1094 /* we continue, because there may be a slot used with the same domain */
1098 if (obj->vtable->domain == domain) {
1099 same_domain_slot = i;
1103 if (same_domain_slot >= 0)
1104 mono_array_setref (this->cached_culture_info, same_domain_slot, culture);
1105 else if (free_slot >= 0)
1106 mono_array_setref (this->cached_culture_info, free_slot, culture);
1107 /* we may want to replace an existing entry here, even when no suitable slot is found */
1109 LeaveCriticalSection (this->synch_cs);
1113 ves_icall_System_Threading_Thread_SetCachedCurrentCulture (MonoThread *this, MonoObject *culture)
1115 cache_culture (this, culture, CULTURES_START_IDX);
1119 ves_icall_System_Threading_Thread_SetSerializedCurrentCulture (MonoThread *this, MonoArray *arr)
1121 ensure_synch_cs_set (this);
1123 EnterCriticalSection (this->synch_cs);
1125 if (this->serialized_culture_info)
1126 g_free (this->serialized_culture_info);
1127 this->serialized_culture_info = g_new0 (guint8, mono_array_length (arr));
1128 this->serialized_culture_info_len = mono_array_length (arr);
1129 memcpy (this->serialized_culture_info, mono_array_addr (arr, guint8, 0), mono_array_length (arr));
1131 LeaveCriticalSection (this->synch_cs);
1136 ves_icall_System_Threading_Thread_GetCachedCurrentUICulture (MonoThread *this)
1138 return lookup_cached_culture (this, mono_domain_get (), UICULTURES_START_IDX);
1142 ves_icall_System_Threading_Thread_GetSerializedCurrentUICulture (MonoThread *this)
1146 ensure_synch_cs_set (this);
1148 EnterCriticalSection (this->synch_cs);
1150 if (this->serialized_ui_culture_info) {
1151 res = mono_array_new (mono_domain_get (), mono_defaults.byte_class, this->serialized_ui_culture_info_len);
1152 memcpy (mono_array_addr (res, guint8, 0), this->serialized_ui_culture_info, this->serialized_ui_culture_info_len);
1157 LeaveCriticalSection (this->synch_cs);
1163 ves_icall_System_Threading_Thread_SetCachedCurrentUICulture (MonoThread *this, MonoObject *culture)
1165 cache_culture (this, culture, UICULTURES_START_IDX);
1169 ves_icall_System_Threading_Thread_SetSerializedCurrentUICulture (MonoThread *this, MonoArray *arr)
1171 ensure_synch_cs_set (this);
1173 EnterCriticalSection (this->synch_cs);
1175 if (this->serialized_ui_culture_info)
1176 g_free (this->serialized_ui_culture_info);
1177 this->serialized_ui_culture_info = g_new0 (guint8, mono_array_length (arr));
1178 this->serialized_ui_culture_info_len = mono_array_length (arr);
1179 memcpy (this->serialized_ui_culture_info, mono_array_addr (arr, guint8, 0), mono_array_length (arr));
1181 LeaveCriticalSection (this->synch_cs);
1184 /* the jit may read the compiled code of this function */
1186 mono_thread_current (void)
1188 THREAD_DEBUG (g_message ("%s: returning %p", __func__, GET_CURRENT_OBJECT ()));
1189 return GET_CURRENT_OBJECT ();
1192 gboolean ves_icall_System_Threading_Thread_Join_internal(MonoThread *this,
1193 int ms, HANDLE thread)
1195 MonoThread *cur_thread = mono_thread_current ();
1198 MONO_ARCH_SAVE_REGS;
1200 mono_thread_current_check_pending_interrupt ();
1202 ensure_synch_cs_set (this);
1204 EnterCriticalSection (this->synch_cs);
1206 if ((this->state & ThreadState_Unstarted) != 0) {
1207 LeaveCriticalSection (this->synch_cs);
1209 mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started."));
1213 LeaveCriticalSection (this->synch_cs);
1218 THREAD_DEBUG (g_message ("%s: joining thread handle %p, %d ms", __func__, thread, ms));
1220 mono_thread_set_state (cur_thread, ThreadState_WaitSleepJoin);
1222 ret=WaitForSingleObjectEx (thread, ms, TRUE);
1224 mono_thread_clr_state (cur_thread, ThreadState_WaitSleepJoin);
1226 if(ret==WAIT_OBJECT_0) {
1227 THREAD_DEBUG (g_message ("%s: join successful", __func__));
1232 THREAD_DEBUG (g_message ("%s: join failed", __func__));
1237 /* FIXME: exitContext isnt documented */
1238 gboolean ves_icall_System_Threading_WaitHandle_WaitAll_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext)
1244 MonoObject *waitHandle;
1245 MonoThread *thread = mono_thread_current ();
1247 MONO_ARCH_SAVE_REGS;
1249 /* Do this WaitSleepJoin check before creating objects */
1250 mono_thread_current_check_pending_interrupt ();
1252 numhandles = mono_array_length(mono_handles);
1253 handles = g_new0(HANDLE, numhandles);
1255 for(i = 0; i < numhandles; i++) {
1256 waitHandle = mono_array_get(mono_handles, MonoObject*, i);
1257 handles [i] = mono_wait_handle_get_handle ((MonoWaitHandle *) waitHandle);
1264 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1266 ret=WaitForMultipleObjectsEx(numhandles, handles, TRUE, ms, TRUE);
1268 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1272 if(ret==WAIT_FAILED) {
1273 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait failed", __func__, GetCurrentThreadId ()));
1275 } else if(ret==WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION) {
1276 /* Do we want to try again if we get
1277 * WAIT_IO_COMPLETION? The documentation for
1278 * WaitHandle doesn't give any clues. (We'd have to
1279 * fiddle with the timeout if we retry.)
1281 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait timed out", __func__, GetCurrentThreadId ()));
1288 /* FIXME: exitContext isnt documented */
1289 gint32 ves_icall_System_Threading_WaitHandle_WaitAny_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext)
1295 MonoObject *waitHandle;
1296 MonoThread *thread = mono_thread_current ();
1298 MONO_ARCH_SAVE_REGS;
1300 /* Do this WaitSleepJoin check before creating objects */
1301 mono_thread_current_check_pending_interrupt ();
1303 numhandles = mono_array_length(mono_handles);
1304 handles = g_new0(HANDLE, numhandles);
1306 for(i = 0; i < numhandles; i++) {
1307 waitHandle = mono_array_get(mono_handles, MonoObject*, i);
1308 handles [i] = mono_wait_handle_get_handle ((MonoWaitHandle *) waitHandle);
1315 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1317 ret=WaitForMultipleObjectsEx(numhandles, handles, FALSE, ms, TRUE);
1319 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1323 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") returning %d", __func__, GetCurrentThreadId (), ret));
1326 * These need to be here. See MSDN dos on WaitForMultipleObjects.
1328 if (ret >= WAIT_OBJECT_0 && ret <= WAIT_OBJECT_0 + numhandles - 1) {
1329 return ret - WAIT_OBJECT_0;
1331 else if (ret >= WAIT_ABANDONED_0 && ret <= WAIT_ABANDONED_0 + numhandles - 1) {
1332 return ret - WAIT_ABANDONED_0;
1339 /* FIXME: exitContext isnt documented */
1340 gboolean ves_icall_System_Threading_WaitHandle_WaitOne_internal(MonoObject *this, HANDLE handle, gint32 ms, gboolean exitContext)
1343 MonoThread *thread = mono_thread_current ();
1345 MONO_ARCH_SAVE_REGS;
1347 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") waiting for %p, %d ms", __func__, GetCurrentThreadId (), handle, ms));
1353 mono_thread_current_check_pending_interrupt ();
1355 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1357 ret=WaitForSingleObjectEx (handle, ms, TRUE);
1359 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1361 if(ret==WAIT_FAILED) {
1362 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait failed", __func__, GetCurrentThreadId ()));
1364 } else if(ret==WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION) {
1365 /* Do we want to try again if we get
1366 * WAIT_IO_COMPLETION? The documentation for
1367 * WaitHandle doesn't give any clues. (We'd have to
1368 * fiddle with the timeout if we retry.)
1370 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait timed out", __func__, GetCurrentThreadId ()));
1377 HANDLE ves_icall_System_Threading_Mutex_CreateMutex_internal (MonoBoolean owned, MonoString *name, MonoBoolean *created)
1381 MONO_ARCH_SAVE_REGS;
1386 mutex = CreateMutex (NULL, owned, NULL);
1388 mutex = CreateMutex (NULL, owned, mono_string_chars (name));
1390 if (GetLastError () == ERROR_ALREADY_EXISTS) {
1398 MonoBoolean ves_icall_System_Threading_Mutex_ReleaseMutex_internal (HANDLE handle ) {
1399 MONO_ARCH_SAVE_REGS;
1401 return(ReleaseMutex (handle));
1404 HANDLE ves_icall_System_Threading_Mutex_OpenMutex_internal (MonoString *name,
1410 MONO_ARCH_SAVE_REGS;
1412 *error = ERROR_SUCCESS;
1414 ret = OpenMutex (rights, FALSE, mono_string_chars (name));
1416 *error = GetLastError ();
1423 HANDLE ves_icall_System_Threading_Semaphore_CreateSemaphore_internal (gint32 initialCount, gint32 maximumCount, MonoString *name, MonoBoolean *created)
1427 MONO_ARCH_SAVE_REGS;
1432 sem = CreateSemaphore (NULL, initialCount, maximumCount, NULL);
1434 sem = CreateSemaphore (NULL, initialCount, maximumCount,
1435 mono_string_chars (name));
1437 if (GetLastError () == ERROR_ALREADY_EXISTS) {
1445 gint32 ves_icall_System_Threading_Semaphore_ReleaseSemaphore_internal (HANDLE handle, gint32 releaseCount, MonoBoolean *fail)
1449 MONO_ARCH_SAVE_REGS;
1451 *fail = !ReleaseSemaphore (handle, releaseCount, &prevcount);
1456 HANDLE ves_icall_System_Threading_Semaphore_OpenSemaphore_internal (MonoString *name, gint32 rights, gint32 *error)
1460 MONO_ARCH_SAVE_REGS;
1462 *error = ERROR_SUCCESS;
1464 ret = OpenSemaphore (rights, FALSE, mono_string_chars (name));
1466 *error = GetLastError ();
1472 HANDLE ves_icall_System_Threading_Events_CreateEvent_internal (MonoBoolean manual, MonoBoolean initial, MonoString *name, MonoBoolean *created)
1476 MONO_ARCH_SAVE_REGS;
1481 event = CreateEvent (NULL, manual, initial, NULL);
1483 event = CreateEvent (NULL, manual, initial,
1484 mono_string_chars (name));
1486 if (GetLastError () == ERROR_ALREADY_EXISTS) {
1494 gboolean ves_icall_System_Threading_Events_SetEvent_internal (HANDLE handle) {
1495 MONO_ARCH_SAVE_REGS;
1497 return (SetEvent(handle));
1500 gboolean ves_icall_System_Threading_Events_ResetEvent_internal (HANDLE handle) {
1501 MONO_ARCH_SAVE_REGS;
1503 return (ResetEvent(handle));
1507 ves_icall_System_Threading_Events_CloseEvent_internal (HANDLE handle) {
1508 MONO_ARCH_SAVE_REGS;
1510 CloseHandle (handle);
1513 HANDLE ves_icall_System_Threading_Events_OpenEvent_internal (MonoString *name,
1519 MONO_ARCH_SAVE_REGS;
1521 *error = ERROR_SUCCESS;
1523 ret = OpenEvent (rights, FALSE, mono_string_chars (name));
1525 *error = GetLastError ();
1531 gint32 ves_icall_System_Threading_Interlocked_Increment_Int (gint32 *location)
1533 MONO_ARCH_SAVE_REGS;
1535 return InterlockedIncrement (location);
1538 gint64 ves_icall_System_Threading_Interlocked_Increment_Long (gint64 *location)
1542 MONO_ARCH_SAVE_REGS;
1544 mono_interlocked_lock ();
1548 mono_interlocked_unlock ();
1554 gint32 ves_icall_System_Threading_Interlocked_Decrement_Int (gint32 *location)
1556 MONO_ARCH_SAVE_REGS;
1558 return InterlockedDecrement(location);
1561 gint64 ves_icall_System_Threading_Interlocked_Decrement_Long (gint64 * location)
1565 MONO_ARCH_SAVE_REGS;
1567 mono_interlocked_lock ();
1571 mono_interlocked_unlock ();
1576 gint32 ves_icall_System_Threading_Interlocked_Exchange_Int (gint32 *location, gint32 value)
1578 MONO_ARCH_SAVE_REGS;
1580 return InterlockedExchange(location, value);
1583 MonoObject * ves_icall_System_Threading_Interlocked_Exchange_Object (MonoObject **location, MonoObject *value)
1585 MONO_ARCH_SAVE_REGS;
1587 return (MonoObject *) InterlockedExchangePointer((gpointer *) location, value);
1590 gfloat ves_icall_System_Threading_Interlocked_Exchange_Single (gfloat *location, gfloat value)
1592 IntFloatUnion val, ret;
1594 MONO_ARCH_SAVE_REGS;
1597 ret.ival = InterlockedExchange((gint32 *) location, val.ival);
1603 ves_icall_System_Threading_Interlocked_Exchange_Long (gint64 *location, gint64 value)
1605 #if SIZEOF_VOID_P == 8
1606 return (gint64) InterlockedExchangePointer((gpointer *) location, (gpointer)value);
1611 * According to MSDN, this function is only atomic with regards to the
1612 * other Interlocked functions on 32 bit platforms.
1614 mono_interlocked_lock ();
1617 mono_interlocked_unlock ();
1624 ves_icall_System_Threading_Interlocked_Exchange_Double (gdouble *location, gdouble value)
1626 #if SIZEOF_VOID_P == 8
1627 LongDoubleUnion val, ret;
1630 ret.ival = (gint64)InterlockedExchangePointer((gpointer *) location, (gpointer)val.ival);
1637 * According to MSDN, this function is only atomic with regards to the
1638 * other Interlocked functions on 32 bit platforms.
1640 mono_interlocked_lock ();
1643 mono_interlocked_unlock ();
1649 gint32 ves_icall_System_Threading_Interlocked_CompareExchange_Int(gint32 *location, gint32 value, gint32 comparand)
1651 MONO_ARCH_SAVE_REGS;
1653 return InterlockedCompareExchange(location, value, comparand);
1656 MonoObject * ves_icall_System_Threading_Interlocked_CompareExchange_Object (MonoObject **location, MonoObject *value, MonoObject *comparand)
1658 MONO_ARCH_SAVE_REGS;
1660 return (MonoObject *) InterlockedCompareExchangePointer((gpointer *) location, value, comparand);
1663 gfloat ves_icall_System_Threading_Interlocked_CompareExchange_Single (gfloat *location, gfloat value, gfloat comparand)
1665 IntFloatUnion val, ret, cmp;
1667 MONO_ARCH_SAVE_REGS;
1670 cmp.fval = comparand;
1671 ret.ival = InterlockedCompareExchange((gint32 *) location, val.ival, cmp.ival);
1677 ves_icall_System_Threading_Interlocked_CompareExchange_Double (gdouble *location, gdouble value, gdouble comparand)
1679 #if SIZEOF_VOID_P == 8
1680 LongDoubleUnion val, comp, ret;
1683 comp.fval = comparand;
1684 ret.ival = (gint64)InterlockedCompareExchangePointer((gpointer *) location, (gpointer)val.ival, (gpointer)comp.ival);
1690 mono_interlocked_lock ();
1692 if (old == comparand)
1694 mono_interlocked_unlock ();
1701 ves_icall_System_Threading_Interlocked_CompareExchange_Long (gint64 *location, gint64 value, gint64 comparand)
1703 #if SIZEOF_VOID_P == 8
1704 return (gint64)InterlockedCompareExchangePointer((gpointer *) location, (gpointer)value, (gpointer)comparand);
1708 mono_interlocked_lock ();
1710 if (old == comparand)
1712 mono_interlocked_unlock ();
1719 ves_icall_System_Threading_Interlocked_CompareExchange_T (MonoObject **location, MonoObject *value, MonoObject *comparand)
1721 MONO_ARCH_SAVE_REGS;
1723 return InterlockedCompareExchangePointer ((gpointer *)location, value, comparand);
1727 ves_icall_System_Threading_Interlocked_Exchange_T (MonoObject **location, MonoObject *value)
1729 MONO_ARCH_SAVE_REGS;
1731 return InterlockedExchangePointer ((gpointer *)location, value);
1735 ves_icall_System_Threading_Interlocked_Add_Int (gint32 *location, gint32 value)
1737 #if SIZEOF_VOID_P == 8
1738 /* Should be implemented as a JIT intrinsic */
1739 mono_raise_exception (mono_get_exception_not_implemented (NULL));
1744 mono_interlocked_lock ();
1746 *location = orig + value;
1747 mono_interlocked_unlock ();
1749 return orig + value;
1754 ves_icall_System_Threading_Interlocked_Add_Long (gint64 *location, gint64 value)
1756 #if SIZEOF_VOID_P == 8
1757 /* Should be implemented as a JIT intrinsic */
1758 mono_raise_exception (mono_get_exception_not_implemented (NULL));
1763 mono_interlocked_lock ();
1765 *location = orig + value;
1766 mono_interlocked_unlock ();
1768 return orig + value;
1773 ves_icall_System_Threading_Interlocked_Read_Long (gint64 *location)
1775 #if SIZEOF_VOID_P == 8
1776 /* 64 bit reads are already atomic */
1781 mono_interlocked_lock ();
1783 mono_interlocked_unlock ();
1790 ves_icall_System_Threading_Thread_MemoryBarrier (void)
1792 mono_threads_lock ();
1793 mono_threads_unlock ();
1797 ves_icall_System_Threading_Thread_ClrState (MonoThread* this, guint32 state)
1799 mono_thread_clr_state (this, state);
1801 if (state & ThreadState_Background) {
1802 /* If the thread changes the background mode, the main thread has to
1803 * be notified, since it has to rebuild the list of threads to
1806 SetEvent (background_change_event);
1811 ves_icall_System_Threading_Thread_SetState (MonoThread* this, guint32 state)
1813 mono_thread_set_state (this, state);
1815 if (state & ThreadState_Background) {
1816 /* If the thread changes the background mode, the main thread has to
1817 * be notified, since it has to rebuild the list of threads to
1820 SetEvent (background_change_event);
1825 ves_icall_System_Threading_Thread_GetState (MonoThread* this)
1829 ensure_synch_cs_set (this);
1831 EnterCriticalSection (this->synch_cs);
1833 state = this->state;
1835 LeaveCriticalSection (this->synch_cs);
1840 void ves_icall_System_Threading_Thread_Interrupt_internal (MonoThread *this)
1842 gboolean throw = FALSE;
1844 ensure_synch_cs_set (this);
1846 EnterCriticalSection (this->synch_cs);
1848 this->thread_interrupt_requested = TRUE;
1850 if (this->state & ThreadState_WaitSleepJoin) {
1854 LeaveCriticalSection (this->synch_cs);
1857 signal_thread_state_change (this);
1861 void mono_thread_current_check_pending_interrupt ()
1863 MonoThread *thread = mono_thread_current ();
1864 gboolean throw = FALSE;
1866 ensure_synch_cs_set (thread);
1868 EnterCriticalSection (thread->synch_cs);
1870 if (thread->thread_interrupt_requested) {
1872 thread->thread_interrupt_requested = FALSE;
1875 LeaveCriticalSection (thread->synch_cs);
1878 mono_raise_exception (mono_get_exception_thread_interrupted ());
1883 mono_thread_get_abort_signal (void)
1885 #ifdef PLATFORM_WIN32
1891 static int abort_signum = -1;
1893 if (abort_signum != -1)
1894 return abort_signum;
1895 /* we try to avoid SIGRTMIN and any one that might have been set already, see bug #75387 */
1896 for (i = SIGRTMIN + 1; i < SIGRTMAX; ++i) {
1897 struct sigaction sinfo;
1898 sigaction (i, NULL, &sinfo);
1899 if (sinfo.sa_handler == SIG_DFL && (void*)sinfo.sa_sigaction == (void*)SIG_DFL) {
1904 /* fallback to the old way */
1907 #endif /* PLATFORM_WIN32 */
1910 #ifdef PLATFORM_WIN32
1911 static void CALLBACK interruption_request_apc (ULONG_PTR param)
1913 MonoException* exc = mono_thread_request_interruption (FALSE);
1914 if (exc) mono_raise_exception (exc);
1916 #endif /* PLATFORM_WIN32 */
1919 * signal_thread_state_change
1921 * Tells the thread that his state has changed and it has to enter the new
1922 * state as soon as possible.
1924 static void signal_thread_state_change (MonoThread *thread)
1926 if (thread == mono_thread_current ()) {
1927 /* Do it synchronously */
1928 MonoException *exc = mono_thread_request_interruption (FALSE);
1930 mono_raise_exception (exc);
1933 #ifdef PLATFORM_WIN32
1934 QueueUserAPC ((PAPCFUNC)interruption_request_apc, thread->handle, NULL);
1936 /* fixme: store the state somewhere */
1937 #ifdef PTHREAD_POINTER_ID
1938 pthread_kill ((gpointer)(gsize)(thread->tid), mono_thread_get_abort_signal ());
1940 pthread_kill (thread->tid, mono_thread_get_abort_signal ());
1942 #endif /* PLATFORM_WIN32 */
1946 ves_icall_System_Threading_Thread_Abort (MonoThread *thread, MonoObject *state)
1948 MONO_ARCH_SAVE_REGS;
1950 ensure_synch_cs_set (thread);
1952 EnterCriticalSection (thread->synch_cs);
1954 if ((thread->state & ThreadState_AbortRequested) != 0 ||
1955 (thread->state & ThreadState_StopRequested) != 0 ||
1956 (thread->state & ThreadState_Stopped) != 0)
1958 LeaveCriticalSection (thread->synch_cs);
1962 if ((thread->state & ThreadState_Unstarted) != 0) {
1963 thread->state |= ThreadState_Aborted;
1964 LeaveCriticalSection (thread->synch_cs);
1968 thread->state |= ThreadState_AbortRequested;
1969 MONO_OBJECT_SETREF (thread, abort_state, state);
1970 thread->abort_exc = NULL;
1972 LeaveCriticalSection (thread->synch_cs);
1974 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Abort requested for %p (%"G_GSIZE_FORMAT")", __func__, GetCurrentThreadId (), thread, (gsize)thread->tid));
1976 /* Make sure the thread is awake */
1977 mono_thread_resume (thread);
1979 signal_thread_state_change (thread);
1983 ves_icall_System_Threading_Thread_ResetAbort (void)
1985 MonoThread *thread = mono_thread_current ();
1987 MONO_ARCH_SAVE_REGS;
1989 ensure_synch_cs_set (thread);
1991 EnterCriticalSection (thread->synch_cs);
1993 thread->state &= ~ThreadState_AbortRequested;
1995 if (!thread->abort_exc) {
1996 const char *msg = "Unable to reset abort because no abort was requested";
1997 LeaveCriticalSection (thread->synch_cs);
1998 mono_raise_exception (mono_get_exception_thread_state (msg));
2000 thread->abort_exc = NULL;
2001 thread->abort_state = NULL;
2004 LeaveCriticalSection (thread->synch_cs);
2008 mono_thread_suspend (MonoThread *thread)
2010 MONO_ARCH_SAVE_REGS;
2012 ensure_synch_cs_set (thread);
2014 EnterCriticalSection (thread->synch_cs);
2016 if ((thread->state & ThreadState_Unstarted) != 0 ||
2017 (thread->state & ThreadState_Aborted) != 0 ||
2018 (thread->state & ThreadState_Stopped) != 0)
2020 LeaveCriticalSection (thread->synch_cs);
2024 if ((thread->state & ThreadState_Suspended) != 0 ||
2025 (thread->state & ThreadState_SuspendRequested) != 0 ||
2026 (thread->state & ThreadState_StopRequested) != 0)
2028 LeaveCriticalSection (thread->synch_cs);
2032 thread->state |= ThreadState_SuspendRequested;
2034 LeaveCriticalSection (thread->synch_cs);
2036 signal_thread_state_change (thread);
2041 ves_icall_System_Threading_Thread_Suspend (MonoThread *thread)
2043 if (!mono_thread_suspend (thread))
2044 mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started, or is dead."));
2048 mono_thread_resume (MonoThread *thread)
2050 MONO_ARCH_SAVE_REGS;
2052 ensure_synch_cs_set (thread);
2054 EnterCriticalSection (thread->synch_cs);
2056 if ((thread->state & ThreadState_SuspendRequested) != 0) {
2057 thread->state &= ~ThreadState_SuspendRequested;
2058 LeaveCriticalSection (thread->synch_cs);
2062 if ((thread->state & ThreadState_Suspended) == 0 ||
2063 (thread->state & ThreadState_Unstarted) != 0 ||
2064 (thread->state & ThreadState_Aborted) != 0 ||
2065 (thread->state & ThreadState_Stopped) != 0)
2067 LeaveCriticalSection (thread->synch_cs);
2071 thread->resume_event = CreateEvent (NULL, TRUE, FALSE, NULL);
2072 if (thread->resume_event == NULL) {
2073 LeaveCriticalSection (thread->synch_cs);
2077 /* Awake the thread */
2078 SetEvent (thread->suspend_event);
2080 LeaveCriticalSection (thread->synch_cs);
2082 /* Wait for the thread to awake */
2083 WaitForSingleObject (thread->resume_event, INFINITE);
2084 CloseHandle (thread->resume_event);
2085 thread->resume_event = NULL;
2091 ves_icall_System_Threading_Thread_Resume (MonoThread *thread)
2093 if (!mono_thread_resume (thread))
2094 mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started, or is dead."));
2098 find_wrapper (MonoMethod *m, gint no, gint ilo, gboolean managed, gpointer data)
2103 if (m->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE ||
2104 m->wrapper_type == MONO_WRAPPER_XDOMAIN_INVOKE ||
2105 m->wrapper_type == MONO_WRAPPER_XDOMAIN_DISPATCH)
2107 *((gboolean*)data) = TRUE;
2114 is_running_protected_wrapper (void)
2116 gboolean found = FALSE;
2117 mono_stack_walk (find_wrapper, &found);
2121 void mono_thread_stop (MonoThread *thread)
2123 ensure_synch_cs_set (thread);
2125 EnterCriticalSection (thread->synch_cs);
2127 if ((thread->state & ThreadState_StopRequested) != 0 ||
2128 (thread->state & ThreadState_Stopped) != 0)
2130 LeaveCriticalSection (thread->synch_cs);
2134 /* Make sure the thread is awake */
2135 mono_thread_resume (thread);
2137 thread->state |= ThreadState_StopRequested;
2138 thread->state &= ~ThreadState_AbortRequested;
2140 LeaveCriticalSection (thread->synch_cs);
2142 signal_thread_state_change (thread);
2146 ves_icall_System_Threading_Thread_VolatileRead1 (void *ptr)
2148 return *((volatile gint8 *) (ptr));
2152 ves_icall_System_Threading_Thread_VolatileRead2 (void *ptr)
2154 return *((volatile gint16 *) (ptr));
2158 ves_icall_System_Threading_Thread_VolatileRead4 (void *ptr)
2160 return *((volatile gint32 *) (ptr));
2164 ves_icall_System_Threading_Thread_VolatileRead8 (void *ptr)
2166 return *((volatile gint64 *) (ptr));
2170 ves_icall_System_Threading_Thread_VolatileReadIntPtr (void *ptr)
2172 return (void *) *((volatile void **) ptr);
2176 ves_icall_System_Threading_Thread_VolatileWrite1 (void *ptr, gint8 value)
2178 *((volatile gint8 *) ptr) = value;
2182 ves_icall_System_Threading_Thread_VolatileWrite2 (void *ptr, gint16 value)
2184 *((volatile gint16 *) ptr) = value;
2188 ves_icall_System_Threading_Thread_VolatileWrite4 (void *ptr, gint32 value)
2190 *((volatile gint32 *) ptr) = value;
2194 ves_icall_System_Threading_Thread_VolatileWrite8 (void *ptr, gint64 value)
2196 *((volatile gint64 *) ptr) = value;
2200 ves_icall_System_Threading_Thread_VolatileWriteIntPtr (void *ptr, void *value)
2202 *((volatile void **) ptr) = value;
2205 void mono_thread_init (MonoThreadStartCB start_cb,
2206 MonoThreadAttachCB attach_cb)
2208 MONO_GC_REGISTER_ROOT (small_id_table);
2209 InitializeCriticalSection(&threads_mutex);
2210 InitializeCriticalSection(&interlocked_mutex);
2211 InitializeCriticalSection(&contexts_mutex);
2212 InitializeCriticalSection(&delayed_free_table_mutex);
2213 InitializeCriticalSection(&small_id_mutex);
2215 background_change_event = CreateEvent (NULL, TRUE, FALSE, NULL);
2216 g_assert(background_change_event != NULL);
2218 mono_init_static_data_info (&thread_static_info);
2219 mono_init_static_data_info (&context_static_info);
2221 current_object_key=TlsAlloc();
2222 THREAD_DEBUG (g_message ("%s: Allocated current_object_key %d", __func__, current_object_key));
2224 mono_thread_start_cb = start_cb;
2225 mono_thread_attach_cb = attach_cb;
2227 delayed_free_table = g_array_new (FALSE, FALSE, sizeof (DelayedFreeItem));
2229 /* Get a pseudo handle to the current process. This is just a
2230 * kludge so that wapi can build a process handle if needed.
2231 * As a pseudo handle is returned, we don't need to clean
2234 GetCurrentProcess ();
2237 void mono_thread_cleanup (void)
2239 #if !defined(PLATFORM_WIN32) && !defined(RUN_IN_SUBTHREAD)
2240 /* The main thread must abandon any held mutexes (particularly
2241 * important for named mutexes as they are shared across
2242 * processes, see bug 74680.) This will happen when the
2243 * thread exits, but if it's not running in a subthread it
2244 * won't exit in time.
2246 /* Using non-w32 API is a nasty kludge, but I couldn't find
2247 * anything in the documentation that would let me do this
2248 * here yet still be safe to call on windows.
2250 _wapi_thread_signal_self (mono_environment_exitcode_get ());
2254 /* This stuff needs more testing, it seems one of these
2255 * critical sections can be locked when mono_thread_cleanup is
2258 DeleteCriticalSection (&threads_mutex);
2259 DeleteCriticalSection (&interlocked_mutex);
2260 DeleteCriticalSection (&contexts_mutex);
2261 DeleteCriticalSection (&delayed_free_table_mutex);
2262 DeleteCriticalSection (&small_id_mutex);
2263 CloseHandle (background_change_event);
2266 g_array_free (delayed_free_table, TRUE);
2268 TlsFree (current_object_key);
2272 mono_threads_install_cleanup (MonoThreadCleanupFunc func)
2274 mono_thread_cleanup_fn = func;
2278 static void print_tids (gpointer key, gpointer value, gpointer user)
2280 /* GPOINTER_TO_UINT breaks horribly if sizeof(void *) >
2281 * sizeof(uint) and a cast to uint would overflow
2283 /* Older versions of glib don't have G_GSIZE_FORMAT, so just
2284 * print this as a pointer.
2286 g_message ("Waiting for: %p", key);
2291 HANDLE handles[MAXIMUM_WAIT_OBJECTS];
2292 MonoThread *threads[MAXIMUM_WAIT_OBJECTS];
2296 static void wait_for_tids (struct wait_data *wait, guint32 timeout)
2300 THREAD_DEBUG (g_message("%s: %d threads to wait for in this batch", __func__, wait->num));
2302 ret=WaitForMultipleObjectsEx(wait->num, wait->handles, TRUE, timeout, FALSE);
2304 if(ret==WAIT_FAILED) {
2305 /* See the comment in build_wait_tids() */
2306 THREAD_DEBUG (g_message ("%s: Wait failed", __func__));
2310 for(i=0; i<wait->num; i++)
2311 CloseHandle (wait->handles[i]);
2313 if (ret == WAIT_TIMEOUT)
2316 for(i=0; i<wait->num; i++) {
2317 gsize tid = wait->threads[i]->tid;
2319 mono_threads_lock ();
2320 if(mono_g_hash_table_lookup (threads, (gpointer)tid)!=NULL) {
2321 /* This thread must have been killed, because
2322 * it hasn't cleaned itself up. (It's just
2323 * possible that the thread exited before the
2324 * parent thread had a chance to store the
2325 * handle, and now there is another pointer to
2326 * the already-exited thread stored. In this
2327 * case, we'll just get two
2328 * mono_profiler_thread_end() calls for the
2332 mono_threads_unlock ();
2333 THREAD_DEBUG (g_message ("%s: cleaning up after thread %p (%"G_GSIZE_FORMAT")", __func__, wait->threads[i], tid));
2334 thread_cleanup (wait->threads[i]);
2336 mono_threads_unlock ();
2341 static void wait_for_tids_or_state_change (struct wait_data *wait, guint32 timeout)
2343 guint32 i, ret, count;
2345 THREAD_DEBUG (g_message("%s: %d threads to wait for in this batch", __func__, wait->num));
2347 /* Add the thread state change event, so it wakes up if a thread changes
2348 * to background mode.
2351 if (count < MAXIMUM_WAIT_OBJECTS) {
2352 wait->handles [count] = background_change_event;
2356 ret=WaitForMultipleObjectsEx (count, wait->handles, FALSE, timeout, FALSE);
2358 if(ret==WAIT_FAILED) {
2359 /* See the comment in build_wait_tids() */
2360 THREAD_DEBUG (g_message ("%s: Wait failed", __func__));
2364 for(i=0; i<wait->num; i++)
2365 CloseHandle (wait->handles[i]);
2367 if (ret == WAIT_TIMEOUT)
2370 if (ret < wait->num) {
2371 gsize tid = wait->threads[ret]->tid;
2372 mono_threads_lock ();
2373 if (mono_g_hash_table_lookup (threads, (gpointer)tid)!=NULL) {
2374 /* See comment in wait_for_tids about thread cleanup */
2375 mono_threads_unlock ();
2376 THREAD_DEBUG (g_message ("%s: cleaning up after thread %"G_GSIZE_FORMAT, __func__, tid));
2377 thread_cleanup (wait->threads [ret]);
2379 mono_threads_unlock ();
2383 static void build_wait_tids (gpointer key, gpointer value, gpointer user)
2385 struct wait_data *wait=(struct wait_data *)user;
2387 if(wait->num<MAXIMUM_WAIT_OBJECTS) {
2389 MonoThread *thread=(MonoThread *)value;
2391 /* Ignore background threads, we abort them later */
2392 /* Do not lock here since it is not needed and the caller holds threads_lock */
2393 if (thread->state & ThreadState_Background) {
2394 THREAD_DEBUG (g_message ("%s: ignoring background thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2395 return; /* just leave, ignore */
2398 if (mono_gc_is_finalizer_thread (thread)) {
2399 THREAD_DEBUG (g_message ("%s: ignoring finalizer thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2403 if (thread == mono_thread_current ()) {
2404 THREAD_DEBUG (g_message ("%s: ignoring current thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2408 if (thread == mono_thread_get_main ()) {
2409 THREAD_DEBUG (g_message ("%s: ignoring main thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2413 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
2414 if (handle == NULL) {
2415 THREAD_DEBUG (g_message ("%s: ignoring unopenable thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2419 wait->handles[wait->num]=handle;
2420 wait->threads[wait->num]=thread;
2423 THREAD_DEBUG (g_message ("%s: adding thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2425 /* Just ignore the rest, we can't do anything with
2432 remove_and_abort_threads (gpointer key, gpointer value, gpointer user)
2434 struct wait_data *wait=(struct wait_data *)user;
2435 gsize self = GetCurrentThreadId ();
2436 MonoThread *thread = (MonoThread *) value;
2439 if (wait->num >= MAXIMUM_WAIT_OBJECTS)
2442 /* The finalizer thread is not a background thread */
2443 if (thread->tid != self && (thread->state & ThreadState_Background) != 0) {
2445 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
2449 if(thread->state & ThreadState_AbortRequested ||
2450 thread->state & ThreadState_Aborted) {
2451 THREAD_DEBUG (g_message ("%s: Thread id %"G_GSIZE_FORMAT" already aborting", __func__, (gsize)thread->tid));
2455 /* printf ("A: %d\n", wait->num); */
2456 wait->handles[wait->num]=thread->handle;
2457 wait->threads[wait->num]=thread;
2460 THREAD_DEBUG (g_print ("%s: Aborting id: %"G_GSIZE_FORMAT"\n", __func__, (gsize)thread->tid));
2461 mono_thread_stop (thread);
2465 return (thread->tid != self && !mono_gc_is_finalizer_thread (thread));
2468 void mono_thread_manage (void)
2470 struct wait_data *wait=g_new0 (struct wait_data, 1);
2472 /* join each thread that's still running */
2473 THREAD_DEBUG (g_message ("%s: Joining each running thread...", __func__));
2475 mono_threads_lock ();
2477 THREAD_DEBUG (g_message("%s: No threads", __func__));
2478 mono_threads_unlock ();
2481 mono_threads_unlock ();
2484 mono_threads_lock ();
2485 THREAD_DEBUG (g_message ("%s: There are %d threads to join", __func__, mono_g_hash_table_size (threads));
2486 mono_g_hash_table_foreach (threads, print_tids, NULL));
2488 ResetEvent (background_change_event);
2490 mono_g_hash_table_foreach (threads, build_wait_tids, wait);
2491 mono_threads_unlock ();
2493 /* Something to wait for */
2494 wait_for_tids_or_state_change (wait, INFINITE);
2496 THREAD_DEBUG (g_message ("%s: I have %d threads after waiting.", __func__, wait->num));
2497 } while(wait->num>0);
2499 mono_runtime_set_shutting_down ();
2501 THREAD_DEBUG (g_message ("%s: threadpool cleanup", __func__));
2502 mono_thread_pool_cleanup ();
2505 * Remove everything but the finalizer thread and self.
2506 * Also abort all the background threads
2509 mono_threads_lock ();
2512 mono_g_hash_table_foreach_remove (threads, remove_and_abort_threads, wait);
2514 mono_threads_unlock ();
2516 THREAD_DEBUG (g_message ("%s: wait->num is now %d", __func__, wait->num));
2518 /* Something to wait for */
2519 wait_for_tids (wait, INFINITE);
2521 } while (wait->num > 0);
2524 * give the subthreads a chance to really quit (this is mainly needed
2525 * to get correct user and system times from getrusage/wait/time(1)).
2526 * This could be removed if we avoid pthread_detach() and use pthread_join().
2528 #ifndef PLATFORM_WIN32
2535 static void terminate_thread (gpointer key, gpointer value, gpointer user)
2537 MonoThread *thread=(MonoThread *)value;
2539 if(thread->tid != (gsize)user) {
2540 /*TerminateThread (thread->handle, -1);*/
2544 void mono_thread_abort_all_other_threads (void)
2546 gsize self = GetCurrentThreadId ();
2548 mono_threads_lock ();
2549 THREAD_DEBUG (g_message ("%s: There are %d threads to abort", __func__,
2550 mono_g_hash_table_size (threads));
2551 mono_g_hash_table_foreach (threads, print_tids, NULL));
2553 mono_g_hash_table_foreach (threads, terminate_thread, (gpointer)self);
2555 mono_threads_unlock ();
2559 collect_threads (gpointer key, gpointer value, gpointer user_data)
2561 MonoThread *thread = (MonoThread*)value;
2562 struct wait_data *wait = (struct wait_data*)user_data;
2565 if (wait->num<MAXIMUM_WAIT_OBJECTS) {
2566 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
2570 wait->handles [wait->num] = handle;
2571 wait->threads [wait->num] = thread;
2577 * mono_thread_suspend_all_other_threads:
2579 * Suspend all managed threads except the finalizer thread and this thread.
2581 void mono_thread_suspend_all_other_threads (void)
2583 struct wait_data *wait = g_new0 (struct wait_data, 1);
2585 gsize self = GetCurrentThreadId ();
2587 guint32 eventidx = 0;
2590 * Make a copy of the hashtable since we can't do anything with
2591 * threads while threads_mutex is held.
2593 mono_threads_lock ();
2594 mono_g_hash_table_foreach (threads, collect_threads, wait);
2595 mono_threads_unlock ();
2597 events = g_new0 (gpointer, wait->num);
2599 /* Get the suspended events that we'll be waiting for */
2600 for (i = 0; i < wait->num; ++i) {
2601 MonoThread *thread = wait->threads [i];
2603 if ((thread->tid == self) || mono_gc_is_finalizer_thread (thread)) {
2604 //CloseHandle (wait->handles [i]);
2605 wait->threads [i] = NULL; /* ignore this thread in next loop */
2609 ensure_synch_cs_set (thread);
2611 EnterCriticalSection (thread->synch_cs);
2613 if ((thread->state & ThreadState_Suspended) != 0 ||
2614 (thread->state & ThreadState_SuspendRequested) != 0 ||
2615 (thread->state & ThreadState_StopRequested) != 0 ||
2616 (thread->state & ThreadState_Stopped) != 0) {
2617 LeaveCriticalSection (thread->synch_cs);
2618 CloseHandle (wait->handles [i]);
2619 wait->threads [i] = NULL; /* ignore this thread in next loop */
2623 /* Convert abort requests into suspend requests */
2624 if ((thread->state & ThreadState_AbortRequested) != 0)
2625 thread->state &= ~ThreadState_AbortRequested;
2627 thread->state |= ThreadState_SuspendRequested;
2629 if (thread->suspended_event == NULL) {
2630 thread->suspended_event = CreateEvent (NULL, TRUE, FALSE, NULL);
2631 if (thread->suspended_event == NULL) {
2632 /* Forget this one and go on to the next */
2633 LeaveCriticalSection (thread->synch_cs);
2638 events [eventidx++] = thread->suspended_event;
2639 LeaveCriticalSection (thread->synch_cs);
2641 /* Signal the thread to suspend */
2642 signal_thread_state_change (thread);
2645 WaitForMultipleObjectsEx (eventidx, events, TRUE, INFINITE, FALSE);
2646 for (i = 0; i < wait->num; ++i) {
2647 MonoThread *thread = wait->threads [i];
2652 EnterCriticalSection (thread->synch_cs);
2653 CloseHandle (thread->suspended_event);
2654 thread->suspended_event = NULL;
2655 LeaveCriticalSection (thread->synch_cs);
2663 * mono_threads_request_thread_dump:
2665 * Ask all threads except the current to print their stacktrace to stdout.
2668 mono_threads_request_thread_dump (void)
2670 struct wait_data *wait = g_new0 (struct wait_data, 1);
2674 * Make a copy of the hashtable since we can't do anything with
2675 * threads while threads_mutex is held.
2677 mono_threads_lock ();
2678 mono_g_hash_table_foreach (threads, collect_threads, wait);
2679 mono_threads_unlock ();
2681 for (i = 0; i < wait->num; ++i) {
2682 MonoThread *thread = wait->threads [i];
2684 if (!mono_gc_is_finalizer_thread (thread) && (thread != mono_thread_current ()) && !thread->thread_dump_requested) {
2685 thread->thread_dump_requested = TRUE;
2687 signal_thread_state_change (thread);
2690 CloseHandle (wait->handles [i]);
2695 * mono_thread_push_appdomain_ref:
2697 * Register that the current thread may have references to objects in domain
2698 * @domain on its stack. Each call to this function should be paired with a
2699 * call to pop_appdomain_ref.
2702 mono_thread_push_appdomain_ref (MonoDomain *domain)
2704 MonoThread *thread = mono_thread_current ();
2707 /* printf ("PUSH REF: %"G_GSIZE_FORMAT" -> %s.\n", (gsize)thread->tid, domain->friendly_name); */
2708 mono_threads_lock ();
2709 thread->appdomain_refs = g_slist_prepend (thread->appdomain_refs, domain);
2710 mono_threads_unlock ();
2715 mono_thread_pop_appdomain_ref (void)
2717 MonoThread *thread = mono_thread_current ();
2720 /* printf ("POP REF: %"G_GSIZE_FORMAT" -> %s.\n", (gsize)thread->tid, ((MonoDomain*)(thread->appdomain_refs->data))->friendly_name); */
2721 mono_threads_lock ();
2722 /* FIXME: How can the list be empty ? */
2723 if (thread->appdomain_refs)
2724 thread->appdomain_refs = g_slist_remove (thread->appdomain_refs, thread->appdomain_refs->data);
2725 mono_threads_unlock ();
2730 mono_thread_has_appdomain_ref (MonoThread *thread, MonoDomain *domain)
2733 mono_threads_lock ();
2734 res = g_slist_find (thread->appdomain_refs, domain) != NULL;
2735 mono_threads_unlock ();
2739 typedef struct abort_appdomain_data {
2740 struct wait_data wait;
2742 } abort_appdomain_data;
2745 abort_appdomain_thread (gpointer key, gpointer value, gpointer user_data)
2747 MonoThread *thread = (MonoThread*)value;
2748 abort_appdomain_data *data = (abort_appdomain_data*)user_data;
2749 MonoDomain *domain = data->domain;
2751 if (mono_thread_has_appdomain_ref (thread, domain)) {
2752 /* printf ("ABORTING THREAD %p BECAUSE IT REFERENCES DOMAIN %s.\n", thread->tid, domain->friendly_name); */
2754 ves_icall_System_Threading_Thread_Abort (thread, NULL);
2756 if(data->wait.num<MAXIMUM_WAIT_OBJECTS) {
2757 HANDLE handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
2760 data->wait.handles [data->wait.num] = handle;
2761 data->wait.threads [data->wait.num] = thread;
2764 /* Just ignore the rest, we can't do anything with
2772 * mono_threads_abort_appdomain_threads:
2774 * Abort threads which has references to the given appdomain.
2777 mono_threads_abort_appdomain_threads (MonoDomain *domain, int timeout)
2779 abort_appdomain_data user_data;
2782 THREAD_DEBUG (g_message ("%s: starting abort", __func__));
2784 start_time = GetTickCount ();
2786 mono_threads_lock ();
2788 user_data.domain = domain;
2789 user_data.wait.num = 0;
2790 mono_g_hash_table_foreach (threads, abort_appdomain_thread, &user_data);
2791 mono_threads_unlock ();
2793 if (user_data.wait.num > 0)
2795 * We should wait for the threads either to abort, or to leave the
2796 * domain. We can't do the latter, so we wait with a timeout.
2798 wait_for_tids (&user_data.wait, 100);
2800 /* Update remaining time */
2801 timeout -= GetTickCount () - start_time;
2802 start_time = GetTickCount ();
2807 while (user_data.wait.num > 0);
2809 THREAD_DEBUG (g_message ("%s: abort done", __func__));
2815 clear_cached_culture (gpointer key, gpointer value, gpointer user_data)
2817 MonoThread *thread = (MonoThread*)value;
2818 MonoDomain *domain = (MonoDomain*)user_data;
2821 /* No locking needed here */
2822 /* FIXME: why no locking? writes to the cache are protected with synch_cs above */
2824 if (thread->cached_culture_info) {
2825 for (i = 0; i < NUM_CACHED_CULTURES * 2; ++i) {
2826 MonoObject *obj = mono_array_get (thread->cached_culture_info, MonoObject*, i);
2827 if (obj && obj->vtable->domain == domain)
2828 mono_array_set (thread->cached_culture_info, MonoObject*, i, NULL);
2834 * mono_threads_clear_cached_culture:
2836 * Clear the cached_current_culture from all threads if it is in the
2840 mono_threads_clear_cached_culture (MonoDomain *domain)
2842 mono_threads_lock ();
2843 mono_g_hash_table_foreach (threads, clear_cached_culture, domain);
2844 mono_threads_unlock ();
2848 * mono_thread_get_pending_exception:
2850 * Return an exception which needs to be raised when leaving a catch clause.
2851 * This is used for undeniable exception propagation.
2854 mono_thread_get_pending_exception (void)
2856 MonoThread *thread = mono_thread_current ();
2858 MONO_ARCH_SAVE_REGS;
2860 if (thread && thread->abort_exc && !is_running_protected_wrapper ()) {
2862 * FIXME: Clear the abort exception and return an AppDomainUnloaded
2863 * exception if the thread no longer references a dying appdomain.
2865 thread->abort_exc->trace_ips = NULL;
2866 thread->abort_exc->stack_trace = NULL;
2867 return thread->abort_exc;
2873 #define NUM_STATIC_DATA_IDX 8
2874 static const int static_data_size [NUM_STATIC_DATA_IDX] = {
2875 1024, 4096, 16384, 65536, 262144, 1048576, 4194304, 16777216
2880 * mono_alloc_static_data
2882 * Allocate memory blocks for storing threads or context static data
2885 mono_alloc_static_data (gpointer **static_data_ptr, guint32 offset)
2887 guint idx = (offset >> 24) - 1;
2890 gpointer* static_data = *static_data_ptr;
2892 static_data = mono_gc_alloc_fixed (static_data_size [0], NULL);
2893 *static_data_ptr = static_data;
2894 static_data [0] = static_data;
2897 for (i = 1; i <= idx; ++i) {
2898 if (static_data [i])
2900 static_data [i] = mono_gc_alloc_fixed (static_data_size [i], NULL);
2905 * mono_init_static_data_info
2907 * Initializes static data counters
2909 static void mono_init_static_data_info (StaticDataInfo *static_data)
2911 static_data->idx = 0;
2912 static_data->offset = 0;
2913 static_data->freelist = NULL;
2917 * mono_alloc_static_data_slot
2919 * Generates an offset for static data. static_data contains the counters
2920 * used to generate it.
2923 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align)
2927 if (!static_data->idx && !static_data->offset) {
2929 * we use the first chunk of the first allocation also as
2930 * an array for the rest of the data
2932 static_data->offset = sizeof (gpointer) * NUM_STATIC_DATA_IDX;
2934 static_data->offset += align - 1;
2935 static_data->offset &= ~(align - 1);
2936 if (static_data->offset + size >= static_data_size [static_data->idx]) {
2937 static_data->idx ++;
2938 g_assert (size <= static_data_size [static_data->idx]);
2939 g_assert (static_data->idx < NUM_STATIC_DATA_IDX);
2940 static_data->offset = 0;
2942 offset = static_data->offset | ((static_data->idx + 1) << 24);
2943 static_data->offset += size;
2948 * ensure thread static fields already allocated are valid for thread
2949 * This function is called when a thread is created or on thread attach.
2952 thread_adjust_static_data (MonoThread *thread)
2956 mono_threads_lock ();
2957 if (thread_static_info.offset || thread_static_info.idx > 0) {
2958 /* get the current allocated size */
2959 offset = thread_static_info.offset | ((thread_static_info.idx + 1) << 24);
2960 mono_alloc_static_data (&(thread->static_data), offset);
2962 mono_threads_unlock ();
2966 alloc_thread_static_data_helper (gpointer key, gpointer value, gpointer user)
2968 MonoThread *thread = value;
2969 guint32 offset = GPOINTER_TO_UINT (user);
2971 mono_alloc_static_data (&(thread->static_data), offset);
2974 static MonoThreadDomainTls*
2975 search_tls_slot_in_freelist (StaticDataInfo *static_data, guint32 size, guint32 align)
2977 MonoThreadDomainTls* prev = NULL;
2978 MonoThreadDomainTls* tmp = static_data->freelist;
2980 if (tmp->size == size) {
2982 prev->next = tmp->next;
2984 static_data->freelist = tmp->next;
2993 * The offset for a special static variable is composed of three parts:
2994 * a bit that indicates the type of static data (0:thread, 1:context),
2995 * an index in the array of chunks of memory for the thread (thread->static_data)
2996 * and an offset in that chunk of mem. This allows allocating less memory in the
3001 mono_alloc_special_static_data (guint32 static_type, guint32 size, guint32 align)
3004 if (static_type == SPECIAL_STATIC_THREAD)
3006 MonoThreadDomainTls *item;
3007 mono_threads_lock ();
3008 item = search_tls_slot_in_freelist (&thread_static_info, size, align);
3009 /*g_print ("TLS alloc: %d in domain %p (total: %d), cached: %p\n", size, mono_domain_get (), thread_static_info.offset, item);*/
3011 offset = item->offset;
3014 offset = mono_alloc_static_data_slot (&thread_static_info, size, align);
3016 /* This can be called during startup */
3017 if (threads != NULL)
3018 mono_g_hash_table_foreach (threads, alloc_thread_static_data_helper, GUINT_TO_POINTER (offset));
3019 mono_threads_unlock ();
3023 g_assert (static_type == SPECIAL_STATIC_CONTEXT);
3024 mono_contexts_lock ();
3025 offset = mono_alloc_static_data_slot (&context_static_info, size, align);
3026 mono_contexts_unlock ();
3027 offset |= 0x80000000; /* Set the high bit to indicate context static data */
3033 mono_get_special_static_data (guint32 offset)
3035 /* The high bit means either thread (0) or static (1) data. */
3037 guint32 static_type = (offset & 0x80000000);
3040 offset &= 0x7fffffff;
3041 idx = (offset >> 24) - 1;
3043 if (static_type == 0)
3045 MonoThread *thread = mono_thread_current ();
3046 return ((char*) thread->static_data [idx]) + (offset & 0xffffff);
3050 /* Allocate static data block under demand, since we don't have a list
3053 MonoAppContext *context = mono_context_get ();
3054 if (!context->static_data || !context->static_data [idx]) {
3055 mono_contexts_lock ();
3056 mono_alloc_static_data (&(context->static_data), offset);
3057 mono_contexts_unlock ();
3059 return ((char*) context->static_data [idx]) + (offset & 0xffffff);
3069 free_thread_static_data_helper (gpointer key, gpointer value, gpointer user)
3071 MonoThread *thread = value;
3072 TlsOffsetSize *data = user;
3073 int idx = (data->offset >> 24) - 1;
3076 if (!thread->static_data || !thread->static_data [idx])
3078 ptr = ((char*) thread->static_data [idx]) + (data->offset & 0xffffff);
3079 memset (ptr, 0, data->size);
3083 do_free_special (gpointer key, gpointer value, gpointer data)
3085 MonoClassField *field = key;
3086 guint32 offset = GPOINTER_TO_UINT (value);
3087 guint32 static_type = (offset & 0x80000000);
3090 size = mono_type_size (field->type, &align);
3091 /*g_print ("free %s , size: %d, offset: %x\n", field->name, size, offset);*/
3092 if (static_type == 0) {
3094 MonoThreadDomainTls *item = g_new0 (MonoThreadDomainTls, 1);
3095 data.offset = offset & 0x7fffffff;
3097 if (threads != NULL)
3098 mono_g_hash_table_foreach (threads, free_thread_static_data_helper, &data);
3099 item->offset = offset;
3101 item->next = thread_static_info.freelist;
3102 thread_static_info.freelist = item;
3104 /* FIXME: free context static data as well */
3109 mono_alloc_special_static_data_free (GHashTable *special_static_fields)
3111 mono_threads_lock ();
3112 g_hash_table_foreach (special_static_fields, do_free_special, NULL);
3113 mono_threads_unlock ();
3116 static MonoClassField *local_slots = NULL;
3119 /* local tls data to get locals_slot from a thread */
3122 /* index in the locals_slot array */
3127 clear_local_slot (gpointer key, gpointer value, gpointer user_data)
3129 LocalSlotID *sid = user_data;
3130 MonoThread *thread = (MonoThread*)value;
3131 MonoArray *slots_array;
3133 * the static field is stored at: ((char*) thread->static_data [idx]) + (offset & 0xffffff);
3134 * it is for the right domain, so we need to check if it is allocated an initialized
3135 * for the current thread.
3137 /*g_print ("handling thread %p\n", thread);*/
3138 if (!thread->static_data || !thread->static_data [sid->idx])
3140 slots_array = *(MonoArray **)(((char*) thread->static_data [sid->idx]) + (sid->offset & 0xffffff));
3141 if (!slots_array || sid->slot >= mono_array_length (slots_array))
3143 mono_array_set (slots_array, MonoObject*, sid->slot, NULL);
3147 mono_thread_free_local_slot_values (int slot, MonoBoolean thread_local)
3155 local_slots = mono_class_get_field_from_name (mono_defaults.thread_class, "local_slots");
3157 g_warning ("local_slots field not found in Thread class");
3161 domain = mono_domain_get ();
3162 mono_domain_lock (domain);
3163 if (domain->special_static_fields)
3164 addr = g_hash_table_lookup (domain->special_static_fields, local_slots);
3165 mono_domain_unlock (domain);
3168 /*g_print ("freeing slot %d at %p\n", slot, addr);*/
3169 sid.offset = GPOINTER_TO_UINT (addr);
3170 sid.offset &= 0x7fffffff;
3171 sid.idx = (sid.offset >> 24) - 1;
3172 mono_threads_lock ();
3173 mono_g_hash_table_foreach (threads, clear_local_slot, &sid);
3174 mono_threads_unlock ();
3176 /* FIXME: clear the slot for MonoAppContexts, too */
3180 #ifdef PLATFORM_WIN32
3181 static void CALLBACK dummy_apc (ULONG_PTR param)
3185 static guint32 dummy_apc (gpointer param)
3192 * mono_thread_execute_interruption
3194 * Performs the operation that the requested thread state requires (abort,
3197 static MonoException* mono_thread_execute_interruption (MonoThread *thread)
3199 ensure_synch_cs_set (thread);
3201 EnterCriticalSection (thread->synch_cs);
3203 if (thread->interruption_requested) {
3204 /* this will consume pending APC calls */
3205 WaitForSingleObjectEx (GetCurrentThread(), 0, TRUE);
3206 InterlockedDecrement (&thread_interruption_requested);
3207 thread->interruption_requested = FALSE;
3210 if ((thread->state & ThreadState_AbortRequested) != 0) {
3211 if (thread->abort_exc == NULL)
3212 MONO_OBJECT_SETREF (thread, abort_exc, mono_get_exception_thread_abort ());
3213 LeaveCriticalSection (thread->synch_cs);
3214 return thread->abort_exc;
3216 else if ((thread->state & ThreadState_SuspendRequested) != 0) {
3217 thread->state &= ~ThreadState_SuspendRequested;
3218 thread->state |= ThreadState_Suspended;
3219 thread->suspend_event = CreateEvent (NULL, TRUE, FALSE, NULL);
3220 if (thread->suspend_event == NULL) {
3221 LeaveCriticalSection (thread->synch_cs);
3224 if (thread->suspended_event)
3225 SetEvent (thread->suspended_event);
3227 LeaveCriticalSection (thread->synch_cs);
3229 WaitForSingleObject (thread->suspend_event, INFINITE);
3231 EnterCriticalSection (thread->synch_cs);
3233 CloseHandle (thread->suspend_event);
3234 thread->suspend_event = NULL;
3235 thread->state &= ~ThreadState_Suspended;
3237 /* The thread that requested the resume will have replaced this event
3238 * and will be waiting for it
3240 SetEvent (thread->resume_event);
3242 LeaveCriticalSection (thread->synch_cs);
3246 else if ((thread->state & ThreadState_StopRequested) != 0) {
3247 /* FIXME: do this through the JIT? */
3249 LeaveCriticalSection (thread->synch_cs);
3251 mono_thread_exit ();
3253 } else if (thread->thread_interrupt_requested) {
3255 LeaveCriticalSection (thread->synch_cs);
3257 return(mono_get_exception_thread_interrupted ());
3260 LeaveCriticalSection (thread->synch_cs);
3266 * mono_thread_request_interruption
3268 * A signal handler can call this method to request the interruption of a
3269 * thread. The result of the interruption will depend on the current state of
3270 * the thread. If the result is an exception that needs to be throw, it is
3271 * provided as return value.
3273 MonoException* mono_thread_request_interruption (gboolean running_managed)
3275 MonoThread *thread = mono_thread_current ();
3277 /* The thread may already be stopping */
3281 ensure_synch_cs_set (thread);
3283 EnterCriticalSection (thread->synch_cs);
3285 if (thread->interruption_requested) {
3286 LeaveCriticalSection (thread->synch_cs);
3291 if (!running_managed || is_running_protected_wrapper ()) {
3292 /* Can't stop while in unmanaged code. Increase the global interruption
3293 request count. When exiting the unmanaged method the count will be
3294 checked and the thread will be interrupted. */
3296 InterlockedIncrement (&thread_interruption_requested);
3297 thread->interruption_requested = TRUE;
3299 LeaveCriticalSection (thread->synch_cs);
3301 /* this will awake the thread if it is in WaitForSingleObject
3303 QueueUserAPC ((PAPCFUNC)dummy_apc, thread->handle, NULL);
3307 LeaveCriticalSection (thread->synch_cs);
3309 return mono_thread_execute_interruption (thread);
3313 gboolean mono_thread_interruption_requested ()
3315 if (thread_interruption_requested) {
3316 MonoThread *thread = mono_thread_current ();
3317 /* The thread may already be stopping */
3319 return (thread->interruption_requested);
3324 static void mono_thread_interruption_checkpoint_request (gboolean bypass_abort_protection)
3326 MonoThread *thread = mono_thread_current ();
3328 /* The thread may already be stopping */
3332 if (thread->interruption_requested && (bypass_abort_protection || !is_running_protected_wrapper ())) {
3333 MonoException* exc = mono_thread_execute_interruption (thread);
3334 if (exc) mono_raise_exception (exc);
3339 * Performs the interruption of the current thread, if one has been requested,
3340 * and the thread is not running a protected wrapper.
3342 void mono_thread_interruption_checkpoint ()
3344 mono_thread_interruption_checkpoint_request (FALSE);
3348 * Performs the interruption of the current thread, if one has been requested.
3350 void mono_thread_force_interruption_checkpoint ()
3352 mono_thread_interruption_checkpoint_request (TRUE);
3356 * mono_thread_interruption_request_flag:
3358 * Returns the address of a flag that will be non-zero if an interruption has
3359 * been requested for a thread. The thread to interrupt may not be the current
3360 * thread, so an additional call to mono_thread_interruption_requested() or
3361 * mono_thread_interruption_checkpoint() is allways needed if the flag is not
3364 gint32* mono_thread_interruption_request_flag ()
3366 return &thread_interruption_requested;
3370 mono_thread_init_apartment_state (void)
3373 thread = mono_thread_current ();
3375 #ifdef PLATFORM_WIN32
3376 /* Positive return value indicates success, either
3377 * S_OK if this is first CoInitialize call, or
3378 * S_FALSE if CoInitialize already called, but with same
3379 * threading model. A negative value indicates failure,
3380 * probably due to trying to change the threading model.
3382 if (CoInitializeEx(NULL, (thread->apartment_state == ThreadApartmentState_STA)
3383 ? COINIT_APARTMENTTHREADED
3384 : COINIT_MULTITHREADED) < 0) {
3385 thread->apartment_state = ThreadApartmentState_Unknown;
3391 mono_thread_cleanup_apartment_state (void)
3393 #ifdef PLATFORM_WIN32
3395 thread = mono_thread_current ();
3397 if (thread && thread->apartment_state != ThreadApartmentState_Unknown) {
3404 mono_thread_set_state (MonoThread *thread, MonoThreadState state)
3406 ensure_synch_cs_set (thread);
3408 EnterCriticalSection (thread->synch_cs);
3409 thread->state |= state;
3410 LeaveCriticalSection (thread->synch_cs);
3414 mono_thread_clr_state (MonoThread *thread, MonoThreadState state)
3416 ensure_synch_cs_set (thread);
3418 EnterCriticalSection (thread->synch_cs);
3419 thread->state &= ~state;
3420 LeaveCriticalSection (thread->synch_cs);
3424 mono_thread_test_state (MonoThread *thread, MonoThreadState test)
3426 gboolean ret = FALSE;
3428 ensure_synch_cs_set (thread);
3430 EnterCriticalSection (thread->synch_cs);
3432 if ((thread->state & test) != 0) {
3436 LeaveCriticalSection (thread->synch_cs);