2009-03-11 Zoltan Varga <vargaz@gmail.com>
[mono-debugger.git] / mono / metadata / threads.c
blob48fd620cdd32b7c65e8165ea7707ff7d01f91fe0
1 /*
2 * threads.c: Thread support internal calls
4 * Author:
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)
13 #include <config.h>
15 #include <glib.h>
16 #include <signal.h>
17 #include <string.h>
19 #include <mono/metadata/object.h>
20 #include <mono/metadata/domain-internals.h>
21 #include <mono/metadata/profiler-private.h>
22 #include <mono/metadata/threads.h>
23 #include <mono/metadata/threadpool.h>
24 #include <mono/metadata/threads-types.h>
25 #include <mono/metadata/exception.h>
26 #include <mono/metadata/environment.h>
27 #include <mono/metadata/monitor.h>
28 #include <mono/metadata/gc-internal.h>
29 #include <mono/metadata/marshal.h>
30 #include <mono/io-layer/io-layer.h>
31 #ifndef PLATFORM_WIN32
32 #include <mono/io-layer/threads.h>
33 #endif
34 #include <mono/metadata/object-internals.h>
35 #include <mono/metadata/mono-debug-debugger.h>
36 #include <mono/utils/mono-compiler.h>
37 #include <mono/utils/mono-mmap.h>
38 #include <mono/utils/mono-membar.h>
39 #include <mono/utils/mono-time.h>
41 #include <mono/metadata/gc-internal.h>
43 /*#define THREAD_DEBUG(a) do { a; } while (0)*/
44 #define THREAD_DEBUG(a)
45 /*#define THREAD_WAIT_DEBUG(a) do { a; } while (0)*/
46 #define THREAD_WAIT_DEBUG(a)
47 /*#define LIBGC_DEBUG(a) do { a; } while (0)*/
48 #define LIBGC_DEBUG(a)
50 /* Provide this for systems with glib < 2.6 */
51 #ifndef G_GSIZE_FORMAT
52 # if GLIB_SIZEOF_LONG == 8
53 # define G_GSIZE_FORMAT "lu"
54 # else
55 # define G_GSIZE_FORMAT "u"
56 # endif
57 #endif
59 struct StartInfo
61 guint32 (*func)(void *);
62 MonoThread *obj;
63 MonoObject *delegate;
64 void *start_arg;
65 MonoDomain *domain;
68 typedef union {
69 gint32 ival;
70 gfloat fval;
71 } IntFloatUnion;
73 typedef union {
74 gint64 ival;
75 gdouble fval;
76 } LongDoubleUnion;
78 typedef struct _MonoThreadDomainTls MonoThreadDomainTls;
79 struct _MonoThreadDomainTls {
80 MonoThreadDomainTls *next;
81 guint32 offset;
82 guint32 size;
85 typedef struct {
86 int idx;
87 int offset;
88 MonoThreadDomainTls *freelist;
89 } StaticDataInfo;
91 typedef struct {
92 gpointer p;
93 MonoHazardousFreeFunc free_func;
94 } DelayedFreeItem;
96 /* Number of cached culture objects in the MonoThread->cached_culture_info array
97 * (per-type): we use the first NUM entries for CultureInfo and the last for
98 * UICultureInfo. So the size of the array is really NUM_CACHED_CULTURES * 2.
100 #define NUM_CACHED_CULTURES 4
101 #define CULTURES_START_IDX 0
102 #define UICULTURES_START_IDX NUM_CACHED_CULTURES
104 /* Controls access to the 'threads' hash table */
105 #define mono_threads_lock() EnterCriticalSection (&threads_mutex)
106 #define mono_threads_unlock() LeaveCriticalSection (&threads_mutex)
107 static CRITICAL_SECTION threads_mutex;
109 /* Controls access to context static data */
110 #define mono_contexts_lock() EnterCriticalSection (&contexts_mutex)
111 #define mono_contexts_unlock() LeaveCriticalSection (&contexts_mutex)
112 static CRITICAL_SECTION contexts_mutex;
114 /* Holds current status of static data heap */
115 static StaticDataInfo thread_static_info;
116 static StaticDataInfo context_static_info;
118 /* The hash of existing threads (key is thread ID) that need joining
119 * before exit
121 static MonoGHashTable *threads=NULL;
124 * Threads which are starting up and they are not in the 'threads' hash yet.
125 * When handle_store is called for a thread, it will be removed from this hash table.
126 * Protected by mono_threads_lock ().
128 static MonoGHashTable *threads_starting_up = NULL;
130 /* The TLS key that holds the MonoObject assigned to each thread */
131 static guint32 current_object_key = -1;
133 #ifdef HAVE_KW_THREAD
134 /* we need to use both the Tls* functions and __thread because
135 * the gc needs to see all the threads
137 static __thread MonoThread * tls_current_object MONO_TLS_FAST;
138 #define SET_CURRENT_OBJECT(x) do { \
139 tls_current_object = x; \
140 TlsSetValue (current_object_key, x); \
141 } while (FALSE)
142 #define GET_CURRENT_OBJECT() tls_current_object
143 #else
144 #define SET_CURRENT_OBJECT(x) TlsSetValue (current_object_key, x);
145 #define GET_CURRENT_OBJECT() (MonoThread*) TlsGetValue (current_object_key);
146 #endif
148 /* function called at thread start */
149 static MonoThreadStartCB mono_thread_start_cb = NULL;
151 /* function called at thread attach */
152 static MonoThreadAttachCB mono_thread_attach_cb = NULL;
154 /* function called at thread cleanup */
155 static MonoThreadCleanupFunc mono_thread_cleanup_fn = NULL;
157 /* function called to notify the runtime about a pending exception on the current thread */
158 static MonoThreadNotifyPendingExcFunc mono_thread_notify_pending_exc_fn = NULL;
160 /* The default stack size for each thread */
161 static guint32 default_stacksize = 0;
162 #define default_stacksize_for_thread(thread) ((thread)->stack_size? (thread)->stack_size: default_stacksize)
164 static void thread_adjust_static_data (MonoThread *thread);
165 static void mono_init_static_data_info (StaticDataInfo *static_data);
166 static guint32 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align);
167 static gboolean mono_thread_resume (MonoThread* thread);
168 static void mono_thread_start (MonoThread *thread);
169 static void signal_thread_state_change (MonoThread *thread);
171 /* Spin lock for InterlockedXXX 64 bit functions */
172 #define mono_interlocked_lock() EnterCriticalSection (&interlocked_mutex)
173 #define mono_interlocked_unlock() LeaveCriticalSection (&interlocked_mutex)
174 static CRITICAL_SECTION interlocked_mutex;
176 /* global count of thread interruptions requested */
177 static gint32 thread_interruption_requested = 0;
179 /* Event signaled when a thread changes its background mode */
180 static HANDLE background_change_event;
182 /* The table for small ID assignment */
183 static CRITICAL_SECTION small_id_mutex;
184 static int small_id_table_size = 0;
185 static int small_id_next = 0;
186 static int highest_small_id = -1;
187 static MonoThread **small_id_table = NULL;
189 /* The hazard table */
190 #define HAZARD_TABLE_MAX_SIZE 16384 /* There cannot be more threads than this number. */
191 static volatile int hazard_table_size = 0;
192 static MonoThreadHazardPointers * volatile hazard_table = NULL;
194 /* The table where we keep pointers to blocks to be freed but that
195 have to wait because they're guarded by a hazard pointer. */
196 static CRITICAL_SECTION delayed_free_table_mutex;
197 static GArray *delayed_free_table = NULL;
199 static gboolean shutting_down = FALSE;
201 guint32
202 mono_thread_get_tls_key (void)
204 return current_object_key;
207 gint32
208 mono_thread_get_tls_offset (void)
210 int offset;
211 MONO_THREAD_VAR_OFFSET (tls_current_object,offset);
212 return offset;
215 /* handle_store() and handle_remove() manage the array of threads that
216 * still need to be waited for when the main thread exits.
218 * If handle_store() returns FALSE the thread must not be started
219 * because Mono is shutting down.
221 static gboolean handle_store(MonoThread *thread)
223 mono_threads_lock ();
225 THREAD_DEBUG (g_message ("%s: thread %p ID %"G_GSIZE_FORMAT, __func__, thread, (gsize)thread->tid));
227 if (threads_starting_up)
228 mono_g_hash_table_remove (threads_starting_up, thread);
230 if (shutting_down) {
231 mono_threads_unlock ();
232 return FALSE;
235 if(threads==NULL) {
236 MONO_GC_REGISTER_ROOT (threads);
237 threads=mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
240 /* We don't need to duplicate thread->handle, because it is
241 * only closed when the thread object is finalized by the GC.
243 mono_g_hash_table_insert(threads, (gpointer)(gsize)(thread->tid),
244 thread);
246 mono_threads_unlock ();
248 return TRUE;
251 static gboolean handle_remove(MonoThread *thread)
253 gboolean ret;
254 gsize tid = thread->tid;
256 THREAD_DEBUG (g_message ("%s: thread ID %"G_GSIZE_FORMAT, __func__, tid));
258 mono_threads_lock ();
260 if (threads) {
261 /* We have to check whether the thread object for the
262 * tid is still the same in the table because the
263 * thread might have been destroyed and the tid reused
264 * in the meantime, in which case the tid would be in
265 * the table, but with another thread object.
267 if (mono_g_hash_table_lookup (threads, (gpointer)tid) == thread) {
268 mono_g_hash_table_remove (threads, (gpointer)tid);
269 ret = TRUE;
270 } else {
271 ret = FALSE;
274 else
275 ret = FALSE;
277 mono_threads_unlock ();
279 /* Don't close the handle here, wait for the object finalizer
280 * to do it. Otherwise, the following race condition applies:
282 * 1) Thread exits (and handle_remove() closes the handle)
284 * 2) Some other handle is reassigned the same slot
286 * 3) Another thread tries to join the first thread, and
287 * blocks waiting for the reassigned handle to be signalled
288 * (which might never happen). This is possible, because the
289 * thread calling Join() still has a reference to the first
290 * thread's object.
292 return ret;
296 * Allocate a small thread id.
298 * FIXME: The biggest part of this function is very similar to
299 * domain_id_alloc() in domain.c and should be merged.
301 static int
302 small_id_alloc (MonoThread *thread)
304 int id = -1, i;
306 EnterCriticalSection (&small_id_mutex);
308 if (!small_id_table) {
309 small_id_table_size = 2;
310 small_id_table = mono_gc_alloc_fixed (small_id_table_size * sizeof (MonoThread*), NULL);
312 for (i = small_id_next; i < small_id_table_size; ++i) {
313 if (!small_id_table [i]) {
314 id = i;
315 break;
318 if (id == -1) {
319 for (i = 0; i < small_id_next; ++i) {
320 if (!small_id_table [i]) {
321 id = i;
322 break;
326 if (id == -1) {
327 MonoThread **new_table;
328 int new_size = small_id_table_size * 2;
329 if (new_size >= (1 << 16))
330 g_assert_not_reached ();
331 id = small_id_table_size;
332 new_table = mono_gc_alloc_fixed (new_size * sizeof (MonoThread*), NULL);
333 memcpy (new_table, small_id_table, small_id_table_size * sizeof (void*));
334 mono_gc_free_fixed (small_id_table);
335 small_id_table = new_table;
336 small_id_table_size = new_size;
338 thread->small_id = id;
339 g_assert (small_id_table [id] == NULL);
340 small_id_table [id] = thread;
341 small_id_next++;
342 if (small_id_next > small_id_table_size)
343 small_id_next = 0;
345 if (id >= hazard_table_size) {
346 gpointer page_addr;
347 int pagesize = mono_pagesize ();
348 int num_pages = (hazard_table_size * sizeof (MonoThreadHazardPointers) + pagesize - 1) / pagesize;
350 if (hazard_table == NULL) {
351 hazard_table = mono_valloc (NULL,
352 sizeof (MonoThreadHazardPointers) * HAZARD_TABLE_MAX_SIZE,
353 MONO_MMAP_NONE);
356 g_assert (hazard_table != NULL);
357 page_addr = (guint8*)hazard_table + num_pages * pagesize;
359 g_assert (id < HAZARD_TABLE_MAX_SIZE);
361 mono_mprotect (page_addr, pagesize, MONO_MMAP_READ | MONO_MMAP_WRITE);
363 ++num_pages;
364 hazard_table_size = num_pages * pagesize / sizeof (MonoThreadHazardPointers);
366 g_assert (id < hazard_table_size);
368 hazard_table [id].hazard_pointers [0] = NULL;
369 hazard_table [id].hazard_pointers [1] = NULL;
372 if (id > highest_small_id) {
373 highest_small_id = id;
374 mono_memory_write_barrier ();
377 LeaveCriticalSection (&small_id_mutex);
379 return id;
382 static void
383 small_id_free (int id)
385 g_assert (id >= 0 && id < small_id_table_size);
386 g_assert (small_id_table [id] != NULL);
388 small_id_table [id] = NULL;
391 static gboolean
392 is_pointer_hazardous (gpointer p)
394 int i;
395 int highest = highest_small_id;
397 g_assert (highest < hazard_table_size);
399 for (i = 0; i <= highest; ++i) {
400 if (hazard_table [i].hazard_pointers [0] == p
401 || hazard_table [i].hazard_pointers [1] == p)
402 return TRUE;
405 return FALSE;
408 MonoThreadHazardPointers*
409 mono_hazard_pointer_get (void)
411 MonoThread *current_thread = mono_thread_current ();
413 if (!(current_thread && current_thread->small_id >= 0)) {
414 static MonoThreadHazardPointers emerg_hazard_table;
415 g_warning ("Thread %p may have been prematurely finalized", current_thread);
416 return &emerg_hazard_table;
419 return &hazard_table [current_thread->small_id];
422 static void
423 try_free_delayed_free_item (int index)
425 if (delayed_free_table->len > index) {
426 DelayedFreeItem item = { NULL, NULL };
428 EnterCriticalSection (&delayed_free_table_mutex);
429 /* We have to check the length again because another
430 thread might have freed an item before we acquired
431 the lock. */
432 if (delayed_free_table->len > index) {
433 item = g_array_index (delayed_free_table, DelayedFreeItem, index);
435 if (!is_pointer_hazardous (item.p))
436 g_array_remove_index_fast (delayed_free_table, index);
437 else
438 item.p = NULL;
440 LeaveCriticalSection (&delayed_free_table_mutex);
442 if (item.p != NULL)
443 item.free_func (item.p);
447 void
448 mono_thread_hazardous_free_or_queue (gpointer p, MonoHazardousFreeFunc free_func)
450 int i;
452 /* First try to free a few entries in the delayed free
453 table. */
454 for (i = 2; i >= 0; --i)
455 try_free_delayed_free_item (i);
457 /* Now see if the pointer we're freeing is hazardous. If it
458 isn't, free it. Otherwise put it in the delay list. */
459 if (is_pointer_hazardous (p)) {
460 DelayedFreeItem item = { p, free_func };
462 ++mono_stats.hazardous_pointer_count;
464 EnterCriticalSection (&delayed_free_table_mutex);
465 g_array_append_val (delayed_free_table, item);
466 LeaveCriticalSection (&delayed_free_table_mutex);
467 } else
468 free_func (p);
471 void
472 mono_thread_hazardous_try_free_all (void)
474 int len;
475 int i;
477 if (!delayed_free_table)
478 return;
480 len = delayed_free_table->len;
482 for (i = len - 1; i >= 0; --i)
483 try_free_delayed_free_item (i);
486 static void ensure_synch_cs_set (MonoThread *thread)
488 CRITICAL_SECTION *synch_cs;
490 if (thread->synch_cs != NULL) {
491 return;
494 synch_cs = g_new0 (CRITICAL_SECTION, 1);
495 InitializeCriticalSection (synch_cs);
497 if (InterlockedCompareExchangePointer ((gpointer *)&thread->synch_cs,
498 synch_cs, NULL) != NULL) {
499 /* Another thread must have installed this CS */
500 DeleteCriticalSection (synch_cs);
501 g_free (synch_cs);
506 * NOTE: this function can be called also for threads different from the current one:
507 * make sure no code called from it will ever assume it is run on the thread that is
508 * getting cleaned up.
510 static void thread_cleanup (MonoThread *thread)
512 g_assert (thread != NULL);
514 /* if the thread is not in the hash it has been removed already */
515 if (!handle_remove (thread))
516 return;
517 mono_release_type_locks (thread);
519 EnterCriticalSection (thread->synch_cs);
521 thread->state |= ThreadState_Stopped;
522 thread->state &= ~ThreadState_Background;
524 LeaveCriticalSection (thread->synch_cs);
526 mono_profiler_thread_end (thread->tid);
528 if (thread == mono_thread_current ())
529 mono_thread_pop_appdomain_ref ();
531 if (thread->serialized_culture_info)
532 g_free (thread->serialized_culture_info);
534 g_free (thread->name);
536 thread->cached_culture_info = NULL;
538 mono_gc_free_fixed (thread->static_data);
539 thread->static_data = NULL;
541 if (mono_thread_cleanup_fn)
542 mono_thread_cleanup_fn (thread);
544 small_id_free (thread->small_id);
545 thread->small_id = -2;
548 static guint32 WINAPI start_wrapper(void *data)
550 struct StartInfo *start_info=(struct StartInfo *)data;
551 guint32 (*start_func)(void *);
552 void *start_arg;
553 gsize tid;
554 MonoThread *thread=start_info->obj;
555 MonoObject *start_delegate = start_info->delegate;
557 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Start wrapper", __func__, GetCurrentThreadId ()));
559 /* We can be sure start_info->obj->tid and
560 * start_info->obj->handle have been set, because the thread
561 * was created suspended, and these values were set before the
562 * thread resumed
565 tid=thread->tid;
567 SET_CURRENT_OBJECT (thread);
569 mono_monitor_init_tls ();
571 /* Every thread references the appdomain which created it */
572 mono_thread_push_appdomain_ref (start_info->domain);
574 if (!mono_domain_set (start_info->domain, FALSE)) {
575 /* No point in raising an appdomain_unloaded exception here */
576 /* FIXME: Cleanup here */
577 mono_thread_pop_appdomain_ref ();
578 return 0;
581 start_func = start_info->func;
582 start_arg = start_info->start_arg;
584 /* This MUST be called before any managed code can be
585 * executed, as it calls the callback function that (for the
586 * jit) sets the lmf marker.
588 mono_thread_new_init (tid, &tid, start_func);
589 thread->stack_ptr = &tid;
591 LIBGC_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT",%d) Setting thread stack to %p", __func__, GetCurrentThreadId (), getpid (), thread->stack_ptr));
593 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Setting current_object_key to %p", __func__, GetCurrentThreadId (), thread));
595 mono_profiler_thread_start (tid);
597 /* On 2.0 profile (and higher), set explicitly since state might have been
598 Unknown */
599 if (mono_framework_version () != 1) {
600 if (thread->apartment_state == ThreadApartmentState_Unknown)
601 thread->apartment_state = ThreadApartmentState_MTA;
604 mono_thread_init_apartment_state ();
606 if(thread->start_notify!=NULL) {
607 /* Let the thread that called Start() know we're
608 * ready
610 ReleaseSemaphore (thread->start_notify, 1, NULL);
613 MONO_GC_UNREGISTER_ROOT (start_info->start_arg);
614 g_free (start_info);
616 thread_adjust_static_data (thread);
617 #ifdef DEBUG
618 g_message ("%s: start_wrapper for %"G_GSIZE_FORMAT, __func__,
619 thread->tid);
620 #endif
622 /* start_func is set only for unmanaged start functions */
623 if (start_func) {
624 start_func (start_arg);
625 } else {
626 void *args [1];
627 g_assert (start_delegate != NULL);
628 args [0] = start_arg;
629 /* we may want to handle the exception here. See comment below on unhandled exceptions */
630 mono_runtime_delegate_invoke (start_delegate, args, NULL);
633 /* If the thread calls ExitThread at all, this remaining code
634 * will not be executed, but the main thread will eventually
635 * call thread_cleanup() on this thread's behalf.
638 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Start wrapper terminating", __func__, GetCurrentThreadId ()));
640 thread_cleanup (thread);
642 /* Do any cleanup needed for apartment state. This
643 * cannot be done in thread_cleanup since thread_cleanup could be
644 * called for a thread other than the current thread.
645 * mono_thread_cleanup_apartment_state cleans up apartment
646 * for the current thead */
647 mono_thread_cleanup_apartment_state ();
649 /* Remove the reference to the thread object in the TLS data,
650 * so the thread object can be finalized. This won't be
651 * reached if the thread threw an uncaught exception, so those
652 * thread handles will stay referenced :-( (This is due to
653 * missing support for scanning thread-specific data in the
654 * Boehm GC - the io-layer keeps a GC-visible hash of pointers
655 * to TLS data.)
657 SET_CURRENT_OBJECT (NULL);
659 return(0);
662 void mono_thread_new_init (gsize tid, gpointer stack_start, gpointer func)
664 if (mono_thread_start_cb) {
665 mono_thread_start_cb (tid, stack_start, func);
669 void mono_threads_set_default_stacksize (guint32 stacksize)
671 default_stacksize = stacksize;
674 guint32 mono_threads_get_default_stacksize (void)
676 return default_stacksize;
679 void mono_thread_create_internal (MonoDomain *domain, gpointer func, gpointer arg, gboolean threadpool_thread)
681 MonoThread *thread;
682 HANDLE thread_handle;
683 struct StartInfo *start_info;
684 gsize tid;
686 thread=(MonoThread *)mono_object_new (domain,
687 mono_defaults.thread_class);
689 start_info=g_new0 (struct StartInfo, 1);
690 start_info->func = func;
691 start_info->obj = thread;
692 start_info->domain = domain;
693 start_info->start_arg = arg;
696 * The argument may be an object reference, and there is no ref to keep it alive
697 * when the new thread is started but not yet registered with the collector.
699 MONO_GC_REGISTER_ROOT (start_info->start_arg);
701 mono_threads_lock ();
702 if (shutting_down) {
703 mono_threads_unlock ();
704 return;
706 if (threads_starting_up == NULL) {
707 MONO_GC_REGISTER_ROOT (threads_starting_up);
708 threads_starting_up = mono_g_hash_table_new (NULL, NULL);
710 mono_g_hash_table_insert (threads_starting_up, thread, thread);
711 mono_threads_unlock ();
713 /* Create suspended, so we can do some housekeeping before the thread
714 * starts
716 thread_handle = CreateThread(NULL, default_stacksize_for_thread (thread), (LPTHREAD_START_ROUTINE)start_wrapper, start_info,
717 CREATE_SUSPENDED, &tid);
718 THREAD_DEBUG (g_message ("%s: Started thread ID %"G_GSIZE_FORMAT" (handle %p)", __func__, tid, thread_handle));
719 if (thread_handle == NULL) {
720 /* The thread couldn't be created, so throw an exception */
721 MONO_GC_UNREGISTER_ROOT (start_info->start_arg);
722 mono_threads_lock ();
723 mono_g_hash_table_remove (threads_starting_up, thread);
724 mono_threads_unlock ();
725 g_free (start_info);
726 mono_raise_exception (mono_get_exception_execution_engine ("Couldn't create thread"));
727 return;
730 thread->handle=thread_handle;
731 thread->tid=tid;
732 thread->apartment_state=ThreadApartmentState_Unknown;
733 small_id_alloc (thread);
735 thread->synch_cs = g_new0 (CRITICAL_SECTION, 1);
736 InitializeCriticalSection (thread->synch_cs);
738 thread->threadpool_thread = threadpool_thread;
739 if (threadpool_thread)
740 mono_thread_set_state (thread, ThreadState_Background);
742 if (handle_store (thread))
743 ResumeThread (thread_handle);
746 void
747 mono_thread_create (MonoDomain *domain, gpointer func, gpointer arg)
749 mono_thread_create_internal (domain, func, arg, FALSE);
753 * mono_thread_get_stack_bounds:
755 * Return the address and size of the current threads stack. Return NULL as the
756 * stack address if the stack address cannot be determined.
758 void
759 mono_thread_get_stack_bounds (guint8 **staddr, size_t *stsize)
761 #if defined(HAVE_PTHREAD_GET_STACKSIZE_NP) && defined(HAVE_PTHREAD_GET_STACKADDR_NP)
762 *staddr = (guint8*)pthread_get_stackaddr_np (pthread_self ());
763 *stsize = pthread_get_stacksize_np (pthread_self ());
764 *staddr = (guint8*)((gssize)*staddr & ~(mono_pagesize () - 1));
765 return;
766 /* FIXME: simplify the mess below */
767 #elif !defined(PLATFORM_WIN32)
768 pthread_attr_t attr;
769 guint8 *current = (guint8*)&attr;
771 pthread_attr_init (&attr);
772 #ifdef HAVE_PTHREAD_GETATTR_NP
773 pthread_getattr_np (pthread_self(), &attr);
774 #else
775 #ifdef HAVE_PTHREAD_ATTR_GET_NP
776 pthread_attr_get_np (pthread_self(), &attr);
777 #elif defined(sun)
778 *staddr = NULL;
779 pthread_attr_getstacksize (&attr, &stsize);
780 #else
781 *staddr = NULL;
782 *stsize = 0;
783 return;
784 #endif
785 #endif
787 #ifndef sun
788 pthread_attr_getstack (&attr, (void**)staddr, stsize);
789 if (*staddr)
790 g_assert ((current > *staddr) && (current < *staddr + *stsize));
791 #endif
793 pthread_attr_destroy (&attr);
794 #endif
796 /* When running under emacs, sometimes staddr is not aligned to a page size */
797 *staddr = (guint8*)((gssize)*staddr & ~(mono_pagesize () - 1));
800 MonoThread *
801 mono_thread_attach (MonoDomain *domain)
803 MonoThread *thread;
804 HANDLE thread_handle;
805 gsize tid;
807 if ((thread = mono_thread_current ())) {
808 if (domain != mono_domain_get ())
809 mono_domain_set (domain, TRUE);
810 /* Already attached */
811 return thread;
814 if (!mono_gc_register_thread (&domain)) {
815 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 ());
818 thread = (MonoThread *)mono_object_new (domain,
819 mono_defaults.thread_class);
821 thread_handle = GetCurrentThread ();
822 g_assert (thread_handle);
824 tid=GetCurrentThreadId ();
827 * The handle returned by GetCurrentThread () is a pseudo handle, so it can't be used to
828 * refer to the thread from other threads for things like aborting.
830 DuplicateHandle (GetCurrentProcess (), thread_handle, GetCurrentProcess (), &thread_handle,
831 THREAD_ALL_ACCESS, TRUE, 0);
833 thread->handle=thread_handle;
834 thread->tid=tid;
835 thread->apartment_state=ThreadApartmentState_Unknown;
836 small_id_alloc (thread);
837 thread->stack_ptr = &tid;
839 thread->synch_cs = g_new0 (CRITICAL_SECTION, 1);
840 InitializeCriticalSection (thread->synch_cs);
842 THREAD_DEBUG (g_message ("%s: Attached thread ID %"G_GSIZE_FORMAT" (handle %p)", __func__, tid, thread_handle));
844 if (!handle_store (thread)) {
845 /* Mono is shutting down, so just wait for the end */
846 for (;;)
847 Sleep (10000);
850 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Setting current_object_key to %p", __func__, GetCurrentThreadId (), thread));
852 SET_CURRENT_OBJECT (thread);
853 mono_domain_set (domain, TRUE);
855 mono_monitor_init_tls ();
857 thread_adjust_static_data (thread);
859 if (mono_thread_attach_cb) {
860 guint8 *staddr;
861 size_t stsize;
863 mono_thread_get_stack_bounds (&staddr, &stsize);
865 if (staddr == NULL)
866 mono_thread_attach_cb (tid, &tid);
867 else
868 mono_thread_attach_cb (tid, staddr + stsize);
871 return(thread);
874 void
875 mono_thread_detach (MonoThread *thread)
877 g_return_if_fail (thread != NULL);
879 THREAD_DEBUG (g_message ("%s: mono_thread_detach for %p (%"G_GSIZE_FORMAT")", __func__, thread, (gsize)thread->tid));
881 thread_cleanup (thread);
883 SET_CURRENT_OBJECT (NULL);
885 /* Don't need to CloseHandle this thread, even though we took a
886 * reference in mono_thread_attach (), because the GC will do it
887 * when the Thread object is finalised.
891 void
892 mono_thread_exit ()
894 MonoThread *thread = mono_thread_current ();
896 THREAD_DEBUG (g_message ("%s: mono_thread_exit for %p (%"G_GSIZE_FORMAT")", __func__, thread, (gsize)thread->tid));
898 thread_cleanup (thread);
899 SET_CURRENT_OBJECT (NULL);
901 /* we could add a callback here for embedders to use. */
902 if (thread == mono_thread_get_main ())
903 exit (mono_environment_exitcode_get ());
904 ExitThread (-1);
907 HANDLE ves_icall_System_Threading_Thread_Thread_internal(MonoThread *this,
908 MonoObject *start)
910 guint32 (*start_func)(void *);
911 struct StartInfo *start_info;
912 HANDLE thread;
913 gsize tid;
915 MONO_ARCH_SAVE_REGS;
917 THREAD_DEBUG (g_message("%s: Trying to start a new thread: this (%p) start (%p)", __func__, this, start));
919 ensure_synch_cs_set (this);
921 EnterCriticalSection (this->synch_cs);
923 if ((this->state & ThreadState_Unstarted) == 0) {
924 LeaveCriticalSection (this->synch_cs);
925 mono_raise_exception (mono_get_exception_thread_state ("Thread has already been started."));
926 return NULL;
929 this->small_id = -1;
931 if ((this->state & ThreadState_Aborted) != 0) {
932 LeaveCriticalSection (this->synch_cs);
933 return this;
935 start_func = NULL;
937 /* This is freed in start_wrapper */
938 start_info = g_new0 (struct StartInfo, 1);
939 start_info->func = start_func;
940 start_info->start_arg = this->start_obj; /* FIXME: GC object stored in unmanaged memory */
941 start_info->delegate = start;
942 start_info->obj = this;
943 start_info->domain = mono_domain_get ();
945 this->start_notify=CreateSemaphore (NULL, 0, 0x7fffffff, NULL);
946 if(this->start_notify==NULL) {
947 LeaveCriticalSection (this->synch_cs);
948 g_warning ("%s: CreateSemaphore error 0x%x", __func__, GetLastError ());
949 return(NULL);
952 mono_threads_lock ();
953 if (threads_starting_up == NULL) {
954 MONO_GC_REGISTER_ROOT (threads_starting_up);
955 threads_starting_up = mono_g_hash_table_new (NULL, NULL);
957 mono_g_hash_table_insert (threads_starting_up, this, this);
958 mono_threads_unlock ();
960 thread=CreateThread(NULL, default_stacksize_for_thread (this), (LPTHREAD_START_ROUTINE)start_wrapper, start_info,
961 CREATE_SUSPENDED, &tid);
962 if(thread==NULL) {
963 LeaveCriticalSection (this->synch_cs);
964 mono_threads_lock ();
965 mono_g_hash_table_remove (threads_starting_up, this);
966 mono_threads_unlock ();
967 g_warning("%s: CreateThread error 0x%x", __func__, GetLastError());
968 return(NULL);
971 this->handle=thread;
972 this->tid=tid;
973 small_id_alloc (this);
975 /* Don't call handle_store() here, delay it to Start.
976 * We can't join a thread (trying to will just block
977 * forever) until it actually starts running, so don't
978 * store the handle till then.
981 mono_thread_start (this);
983 this->state &= ~ThreadState_Unstarted;
985 THREAD_DEBUG (g_message ("%s: Started thread ID %"G_GSIZE_FORMAT" (handle %p)", __func__, tid, thread));
987 LeaveCriticalSection (this->synch_cs);
988 return(thread);
992 void ves_icall_System_Threading_Thread_Thread_init (MonoThread *this)
994 MONO_ARCH_SAVE_REGS;
996 ensure_synch_cs_set (this);
999 void ves_icall_System_Threading_Thread_Thread_free_internal (MonoThread *this,
1000 HANDLE thread)
1002 MONO_ARCH_SAVE_REGS;
1004 THREAD_DEBUG (g_message ("%s: Closing thread %p, handle %p", __func__, this, thread));
1006 CloseHandle (thread);
1008 DeleteCriticalSection (this->synch_cs);
1009 g_free (this->synch_cs);
1010 this->synch_cs = NULL;
1013 static void mono_thread_start (MonoThread *thread)
1015 MONO_ARCH_SAVE_REGS;
1017 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Launching thread %p (%"G_GSIZE_FORMAT")", __func__, GetCurrentThreadId (), thread, (gsize)thread->tid));
1019 /* Only store the handle when the thread is about to be
1020 * launched, to avoid the main thread deadlocking while trying
1021 * to clean up a thread that will never be signalled.
1023 if (!handle_store (thread))
1024 return;
1026 ResumeThread (thread->handle);
1028 if(thread->start_notify!=NULL) {
1029 /* Wait for the thread to set up its TLS data etc, so
1030 * theres no potential race condition if someone tries
1031 * to look up the data believing the thread has
1032 * started
1035 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") waiting for thread %p (%"G_GSIZE_FORMAT") to start", __func__, GetCurrentThreadId (), thread, (gsize)thread->tid));
1037 WaitForSingleObjectEx (thread->start_notify, INFINITE, FALSE);
1038 CloseHandle (thread->start_notify);
1039 thread->start_notify = NULL;
1042 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Done launching thread %p (%"G_GSIZE_FORMAT")", __func__, GetCurrentThreadId (), thread, (gsize)thread->tid));
1045 void ves_icall_System_Threading_Thread_Sleep_internal(gint32 ms)
1047 MonoThread *thread = mono_thread_current ();
1049 MONO_ARCH_SAVE_REGS;
1051 THREAD_DEBUG (g_message ("%s: Sleeping for %d ms", __func__, ms));
1053 mono_thread_current_check_pending_interrupt ();
1055 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1057 SleepEx(ms,TRUE);
1059 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1062 void ves_icall_System_Threading_Thread_SpinWait_nop (void)
1066 gint32
1067 ves_icall_System_Threading_Thread_GetDomainID (void)
1069 MONO_ARCH_SAVE_REGS;
1071 return mono_domain_get()->domain_id;
1074 MonoString*
1075 ves_icall_System_Threading_Thread_GetName_internal (MonoThread *this_obj)
1077 MonoString* str;
1079 ensure_synch_cs_set (this_obj);
1081 EnterCriticalSection (this_obj->synch_cs);
1083 if (!this_obj->name)
1084 str = NULL;
1085 else
1086 str = mono_string_new_utf16 (mono_domain_get (), this_obj->name, this_obj->name_len);
1088 LeaveCriticalSection (this_obj->synch_cs);
1090 return str;
1093 void
1094 ves_icall_System_Threading_Thread_SetName_internal (MonoThread *this_obj, MonoString *name)
1096 ensure_synch_cs_set (this_obj);
1098 EnterCriticalSection (this_obj->synch_cs);
1100 if (this_obj->name) {
1101 LeaveCriticalSection (this_obj->synch_cs);
1103 mono_raise_exception (mono_get_exception_invalid_operation ("Thread.Name can only be set once."));
1104 return;
1106 if (name) {
1107 this_obj->name = g_new (gunichar2, mono_string_length (name));
1108 memcpy (this_obj->name, mono_string_chars (name), mono_string_length (name) * 2);
1109 this_obj->name_len = mono_string_length (name);
1111 else
1112 this_obj->name = NULL;
1114 LeaveCriticalSection (this_obj->synch_cs);
1117 static MonoObject*
1118 lookup_cached_culture (MonoThread *this, MonoDomain *domain, int start_idx)
1120 MonoObject *res;
1121 int i;
1123 if (this->cached_culture_info) {
1124 domain = mono_domain_get ();
1125 for (i = start_idx; i < start_idx + NUM_CACHED_CULTURES; ++i) {
1126 res = mono_array_get (this->cached_culture_info, MonoObject*, i);
1127 if (res && res->vtable->domain == domain)
1128 return res;
1132 return NULL;
1135 MonoObject*
1136 ves_icall_System_Threading_Thread_GetCachedCurrentCulture (MonoThread *this)
1138 return lookup_cached_culture (this, mono_domain_get (), CULTURES_START_IDX);
1141 MonoArray*
1142 ves_icall_System_Threading_Thread_GetSerializedCurrentCulture (MonoThread *this)
1144 MonoArray *res;
1146 ensure_synch_cs_set (this);
1148 EnterCriticalSection (this->synch_cs);
1150 if (this->serialized_culture_info) {
1151 res = mono_array_new (mono_domain_get (), mono_defaults.byte_class, this->serialized_culture_info_len);
1152 memcpy (mono_array_addr (res, guint8, 0), this->serialized_culture_info, this->serialized_culture_info_len);
1153 } else {
1154 res = NULL;
1157 LeaveCriticalSection (this->synch_cs);
1159 return res;
1162 static void
1163 cache_culture (MonoThread *this, MonoObject *culture, int start_idx)
1165 int i;
1166 MonoDomain *domain = mono_domain_get ();
1167 MonoObject *obj;
1168 int free_slot = -1;
1169 int same_domain_slot = -1;
1171 ensure_synch_cs_set (this);
1173 EnterCriticalSection (this->synch_cs);
1175 if (!this->cached_culture_info)
1176 MONO_OBJECT_SETREF (this, cached_culture_info, mono_array_new_cached (mono_object_domain (this), mono_defaults.object_class, NUM_CACHED_CULTURES * 2));
1178 for (i = start_idx; i < start_idx + NUM_CACHED_CULTURES; ++i) {
1179 obj = mono_array_get (this->cached_culture_info, MonoObject*, i);
1180 /* Free entry */
1181 if (!obj) {
1182 free_slot = i;
1183 /* we continue, because there may be a slot used with the same domain */
1184 continue;
1186 /* Replace */
1187 if (obj->vtable->domain == domain) {
1188 same_domain_slot = i;
1189 break;
1192 if (same_domain_slot >= 0)
1193 mono_array_setref (this->cached_culture_info, same_domain_slot, culture);
1194 else if (free_slot >= 0)
1195 mono_array_setref (this->cached_culture_info, free_slot, culture);
1196 /* we may want to replace an existing entry here, even when no suitable slot is found */
1198 LeaveCriticalSection (this->synch_cs);
1201 void
1202 ves_icall_System_Threading_Thread_SetCachedCurrentCulture (MonoThread *this, MonoObject *culture)
1204 cache_culture (this, culture, CULTURES_START_IDX);
1207 void
1208 ves_icall_System_Threading_Thread_SetSerializedCurrentCulture (MonoThread *this, MonoArray *arr)
1210 ensure_synch_cs_set (this);
1212 EnterCriticalSection (this->synch_cs);
1214 if (this->serialized_culture_info)
1215 g_free (this->serialized_culture_info);
1216 this->serialized_culture_info = g_new0 (guint8, mono_array_length (arr));
1217 this->serialized_culture_info_len = mono_array_length (arr);
1218 memcpy (this->serialized_culture_info, mono_array_addr (arr, guint8, 0), mono_array_length (arr));
1220 LeaveCriticalSection (this->synch_cs);
1224 MonoObject*
1225 ves_icall_System_Threading_Thread_GetCachedCurrentUICulture (MonoThread *this)
1227 return lookup_cached_culture (this, mono_domain_get (), UICULTURES_START_IDX);
1230 MonoArray*
1231 ves_icall_System_Threading_Thread_GetSerializedCurrentUICulture (MonoThread *this)
1233 MonoArray *res;
1235 ensure_synch_cs_set (this);
1237 EnterCriticalSection (this->synch_cs);
1239 if (this->serialized_ui_culture_info) {
1240 res = mono_array_new (mono_domain_get (), mono_defaults.byte_class, this->serialized_ui_culture_info_len);
1241 memcpy (mono_array_addr (res, guint8, 0), this->serialized_ui_culture_info, this->serialized_ui_culture_info_len);
1242 } else {
1243 res = NULL;
1246 LeaveCriticalSection (this->synch_cs);
1248 return res;
1251 void
1252 ves_icall_System_Threading_Thread_SetCachedCurrentUICulture (MonoThread *this, MonoObject *culture)
1254 cache_culture (this, culture, UICULTURES_START_IDX);
1257 void
1258 ves_icall_System_Threading_Thread_SetSerializedCurrentUICulture (MonoThread *this, MonoArray *arr)
1260 ensure_synch_cs_set (this);
1262 EnterCriticalSection (this->synch_cs);
1264 if (this->serialized_ui_culture_info)
1265 g_free (this->serialized_ui_culture_info);
1266 this->serialized_ui_culture_info = g_new0 (guint8, mono_array_length (arr));
1267 this->serialized_ui_culture_info_len = mono_array_length (arr);
1268 memcpy (this->serialized_ui_culture_info, mono_array_addr (arr, guint8, 0), mono_array_length (arr));
1270 LeaveCriticalSection (this->synch_cs);
1273 /* the jit may read the compiled code of this function */
1274 MonoThread *
1275 mono_thread_current (void)
1277 MonoThread *res = GET_CURRENT_OBJECT ()
1278 THREAD_DEBUG (g_message ("%s: returning %p", __func__, res));
1279 return res;
1282 gboolean ves_icall_System_Threading_Thread_Join_internal(MonoThread *this,
1283 int ms, HANDLE thread)
1285 MonoThread *cur_thread = mono_thread_current ();
1286 gboolean ret;
1288 MONO_ARCH_SAVE_REGS;
1290 mono_thread_current_check_pending_interrupt ();
1292 ensure_synch_cs_set (this);
1294 EnterCriticalSection (this->synch_cs);
1296 if ((this->state & ThreadState_Unstarted) != 0) {
1297 LeaveCriticalSection (this->synch_cs);
1299 mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started."));
1300 return FALSE;
1303 LeaveCriticalSection (this->synch_cs);
1305 if(ms== -1) {
1306 ms=INFINITE;
1308 THREAD_DEBUG (g_message ("%s: joining thread handle %p, %d ms", __func__, thread, ms));
1310 mono_thread_set_state (cur_thread, ThreadState_WaitSleepJoin);
1312 ret=WaitForSingleObjectEx (thread, ms, TRUE);
1314 mono_thread_clr_state (cur_thread, ThreadState_WaitSleepJoin);
1316 if(ret==WAIT_OBJECT_0) {
1317 THREAD_DEBUG (g_message ("%s: join successful", __func__));
1319 return(TRUE);
1322 THREAD_DEBUG (g_message ("%s: join failed", __func__));
1324 return(FALSE);
1327 /* FIXME: exitContext isnt documented */
1328 gboolean ves_icall_System_Threading_WaitHandle_WaitAll_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext)
1330 HANDLE *handles;
1331 guint32 numhandles;
1332 guint32 ret;
1333 guint32 i;
1334 MonoObject *waitHandle;
1335 MonoThread *thread = mono_thread_current ();
1337 MONO_ARCH_SAVE_REGS;
1339 /* Do this WaitSleepJoin check before creating objects */
1340 mono_thread_current_check_pending_interrupt ();
1342 numhandles = mono_array_length(mono_handles);
1343 handles = g_new0(HANDLE, numhandles);
1345 for(i = 0; i < numhandles; i++) {
1346 waitHandle = mono_array_get(mono_handles, MonoObject*, i);
1347 handles [i] = mono_wait_handle_get_handle ((MonoWaitHandle *) waitHandle);
1350 if(ms== -1) {
1351 ms=INFINITE;
1354 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1356 ret=WaitForMultipleObjectsEx(numhandles, handles, TRUE, ms, TRUE);
1358 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1360 g_free(handles);
1362 if(ret==WAIT_FAILED) {
1363 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait failed", __func__, GetCurrentThreadId ()));
1364 return(FALSE);
1365 } else if(ret==WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION) {
1366 /* Do we want to try again if we get
1367 * WAIT_IO_COMPLETION? The documentation for
1368 * WaitHandle doesn't give any clues. (We'd have to
1369 * fiddle with the timeout if we retry.)
1371 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait timed out", __func__, GetCurrentThreadId ()));
1372 return(FALSE);
1375 return(TRUE);
1378 /* FIXME: exitContext isnt documented */
1379 gint32 ves_icall_System_Threading_WaitHandle_WaitAny_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext)
1381 HANDLE *handles;
1382 guint32 numhandles;
1383 guint32 ret;
1384 guint32 i;
1385 MonoObject *waitHandle;
1386 MonoThread *thread = mono_thread_current ();
1388 MONO_ARCH_SAVE_REGS;
1390 /* Do this WaitSleepJoin check before creating objects */
1391 mono_thread_current_check_pending_interrupt ();
1393 numhandles = mono_array_length(mono_handles);
1394 handles = g_new0(HANDLE, numhandles);
1396 for(i = 0; i < numhandles; i++) {
1397 waitHandle = mono_array_get(mono_handles, MonoObject*, i);
1398 handles [i] = mono_wait_handle_get_handle ((MonoWaitHandle *) waitHandle);
1401 if(ms== -1) {
1402 ms=INFINITE;
1405 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1407 ret=WaitForMultipleObjectsEx(numhandles, handles, FALSE, ms, TRUE);
1409 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1411 g_free(handles);
1413 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") returning %d", __func__, GetCurrentThreadId (), ret));
1416 * These need to be here. See MSDN dos on WaitForMultipleObjects.
1418 if (ret >= WAIT_OBJECT_0 && ret <= WAIT_OBJECT_0 + numhandles - 1) {
1419 return ret - WAIT_OBJECT_0;
1421 else if (ret >= WAIT_ABANDONED_0 && ret <= WAIT_ABANDONED_0 + numhandles - 1) {
1422 return ret - WAIT_ABANDONED_0;
1424 else {
1425 return ret;
1429 /* FIXME: exitContext isnt documented */
1430 gboolean ves_icall_System_Threading_WaitHandle_WaitOne_internal(MonoObject *this, HANDLE handle, gint32 ms, gboolean exitContext)
1432 guint32 ret;
1433 MonoThread *thread = mono_thread_current ();
1435 MONO_ARCH_SAVE_REGS;
1437 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") waiting for %p, %d ms", __func__, GetCurrentThreadId (), handle, ms));
1439 if(ms== -1) {
1440 ms=INFINITE;
1443 mono_thread_current_check_pending_interrupt ();
1445 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1447 ret=WaitForSingleObjectEx (handle, ms, TRUE);
1449 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1451 if(ret==WAIT_FAILED) {
1452 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait failed", __func__, GetCurrentThreadId ()));
1453 return(FALSE);
1454 } else if(ret==WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION) {
1455 /* Do we want to try again if we get
1456 * WAIT_IO_COMPLETION? The documentation for
1457 * WaitHandle doesn't give any clues. (We'd have to
1458 * fiddle with the timeout if we retry.)
1460 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait timed out", __func__, GetCurrentThreadId ()));
1461 return(FALSE);
1464 return(TRUE);
1467 gboolean
1468 ves_icall_System_Threading_WaitHandle_SignalAndWait_Internal (HANDLE toSignal, HANDLE toWait, gint32 ms, gboolean exitContext)
1470 guint32 ret;
1471 MonoThread *thread = mono_thread_current ();
1473 MONO_ARCH_SAVE_REGS;
1475 if (ms == -1)
1476 ms = INFINITE;
1478 mono_thread_current_check_pending_interrupt ();
1480 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1482 ret = SignalObjectAndWait (toSignal, toWait, ms, TRUE);
1484 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1486 return (!(ret == WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION || ret == WAIT_FAILED));
1489 HANDLE ves_icall_System_Threading_Mutex_CreateMutex_internal (MonoBoolean owned, MonoString *name, MonoBoolean *created)
1491 HANDLE mutex;
1493 MONO_ARCH_SAVE_REGS;
1495 *created = TRUE;
1497 if (name == NULL) {
1498 mutex = CreateMutex (NULL, owned, NULL);
1499 } else {
1500 mutex = CreateMutex (NULL, owned, mono_string_chars (name));
1502 if (GetLastError () == ERROR_ALREADY_EXISTS) {
1503 *created = FALSE;
1507 return(mutex);
1510 MonoBoolean ves_icall_System_Threading_Mutex_ReleaseMutex_internal (HANDLE handle ) {
1511 MONO_ARCH_SAVE_REGS;
1513 return(ReleaseMutex (handle));
1516 HANDLE ves_icall_System_Threading_Mutex_OpenMutex_internal (MonoString *name,
1517 gint32 rights,
1518 gint32 *error)
1520 HANDLE ret;
1522 MONO_ARCH_SAVE_REGS;
1524 *error = ERROR_SUCCESS;
1526 ret = OpenMutex (rights, FALSE, mono_string_chars (name));
1527 if (ret == NULL) {
1528 *error = GetLastError ();
1531 return(ret);
1535 HANDLE ves_icall_System_Threading_Semaphore_CreateSemaphore_internal (gint32 initialCount, gint32 maximumCount, MonoString *name, MonoBoolean *created)
1537 HANDLE sem;
1539 MONO_ARCH_SAVE_REGS;
1541 *created = TRUE;
1543 if (name == NULL) {
1544 sem = CreateSemaphore (NULL, initialCount, maximumCount, NULL);
1545 } else {
1546 sem = CreateSemaphore (NULL, initialCount, maximumCount,
1547 mono_string_chars (name));
1549 if (GetLastError () == ERROR_ALREADY_EXISTS) {
1550 *created = FALSE;
1554 return(sem);
1557 gint32 ves_icall_System_Threading_Semaphore_ReleaseSemaphore_internal (HANDLE handle, gint32 releaseCount, MonoBoolean *fail)
1559 gint32 prevcount;
1561 MONO_ARCH_SAVE_REGS;
1563 *fail = !ReleaseSemaphore (handle, releaseCount, &prevcount);
1565 return (prevcount);
1568 HANDLE ves_icall_System_Threading_Semaphore_OpenSemaphore_internal (MonoString *name, gint32 rights, gint32 *error)
1570 HANDLE ret;
1572 MONO_ARCH_SAVE_REGS;
1574 *error = ERROR_SUCCESS;
1576 ret = OpenSemaphore (rights, FALSE, mono_string_chars (name));
1577 if (ret == NULL) {
1578 *error = GetLastError ();
1581 return(ret);
1584 HANDLE ves_icall_System_Threading_Events_CreateEvent_internal (MonoBoolean manual, MonoBoolean initial, MonoString *name, MonoBoolean *created)
1586 HANDLE event;
1588 MONO_ARCH_SAVE_REGS;
1590 *created = TRUE;
1592 if (name == NULL) {
1593 event = CreateEvent (NULL, manual, initial, NULL);
1594 } else {
1595 event = CreateEvent (NULL, manual, initial,
1596 mono_string_chars (name));
1598 if (GetLastError () == ERROR_ALREADY_EXISTS) {
1599 *created = FALSE;
1603 return(event);
1606 gboolean ves_icall_System_Threading_Events_SetEvent_internal (HANDLE handle) {
1607 MONO_ARCH_SAVE_REGS;
1609 return (SetEvent(handle));
1612 gboolean ves_icall_System_Threading_Events_ResetEvent_internal (HANDLE handle) {
1613 MONO_ARCH_SAVE_REGS;
1615 return (ResetEvent(handle));
1618 void
1619 ves_icall_System_Threading_Events_CloseEvent_internal (HANDLE handle) {
1620 MONO_ARCH_SAVE_REGS;
1622 CloseHandle (handle);
1625 HANDLE ves_icall_System_Threading_Events_OpenEvent_internal (MonoString *name,
1626 gint32 rights,
1627 gint32 *error)
1629 HANDLE ret;
1631 MONO_ARCH_SAVE_REGS;
1633 *error = ERROR_SUCCESS;
1635 ret = OpenEvent (rights, FALSE, mono_string_chars (name));
1636 if (ret == NULL) {
1637 *error = GetLastError ();
1640 return(ret);
1643 gint32 ves_icall_System_Threading_Interlocked_Increment_Int (gint32 *location)
1645 MONO_ARCH_SAVE_REGS;
1647 return InterlockedIncrement (location);
1650 gint64 ves_icall_System_Threading_Interlocked_Increment_Long (gint64 *location)
1652 gint64 ret;
1654 MONO_ARCH_SAVE_REGS;
1656 mono_interlocked_lock ();
1658 ret = ++ *location;
1660 mono_interlocked_unlock ();
1663 return ret;
1666 gint32 ves_icall_System_Threading_Interlocked_Decrement_Int (gint32 *location)
1668 MONO_ARCH_SAVE_REGS;
1670 return InterlockedDecrement(location);
1673 gint64 ves_icall_System_Threading_Interlocked_Decrement_Long (gint64 * location)
1675 gint64 ret;
1677 MONO_ARCH_SAVE_REGS;
1679 mono_interlocked_lock ();
1681 ret = -- *location;
1683 mono_interlocked_unlock ();
1685 return ret;
1688 gint32 ves_icall_System_Threading_Interlocked_Exchange_Int (gint32 *location, gint32 value)
1690 MONO_ARCH_SAVE_REGS;
1692 return InterlockedExchange(location, value);
1695 MonoObject * ves_icall_System_Threading_Interlocked_Exchange_Object (MonoObject **location, MonoObject *value)
1697 MONO_ARCH_SAVE_REGS;
1699 return (MonoObject *) InterlockedExchangePointer((gpointer *) location, value);
1702 gfloat ves_icall_System_Threading_Interlocked_Exchange_Single (gfloat *location, gfloat value)
1704 IntFloatUnion val, ret;
1706 MONO_ARCH_SAVE_REGS;
1708 val.fval = value;
1709 ret.ival = InterlockedExchange((gint32 *) location, val.ival);
1711 return ret.fval;
1714 gint64
1715 ves_icall_System_Threading_Interlocked_Exchange_Long (gint64 *location, gint64 value)
1717 #if SIZEOF_VOID_P == 8
1718 return (gint64) InterlockedExchangePointer((gpointer *) location, (gpointer)value);
1719 #else
1720 gint64 res;
1723 * According to MSDN, this function is only atomic with regards to the
1724 * other Interlocked functions on 32 bit platforms.
1726 mono_interlocked_lock ();
1727 res = *location;
1728 *location = value;
1729 mono_interlocked_unlock ();
1731 return res;
1732 #endif
1735 gdouble
1736 ves_icall_System_Threading_Interlocked_Exchange_Double (gdouble *location, gdouble value)
1738 #if SIZEOF_VOID_P == 8
1739 LongDoubleUnion val, ret;
1741 val.fval = value;
1742 ret.ival = (gint64)InterlockedExchangePointer((gpointer *) location, (gpointer)val.ival);
1744 return ret.fval;
1745 #else
1746 gdouble res;
1749 * According to MSDN, this function is only atomic with regards to the
1750 * other Interlocked functions on 32 bit platforms.
1752 mono_interlocked_lock ();
1753 res = *location;
1754 *location = value;
1755 mono_interlocked_unlock ();
1757 return res;
1758 #endif
1761 gint32 ves_icall_System_Threading_Interlocked_CompareExchange_Int(gint32 *location, gint32 value, gint32 comparand)
1763 MONO_ARCH_SAVE_REGS;
1765 return InterlockedCompareExchange(location, value, comparand);
1768 MonoObject * ves_icall_System_Threading_Interlocked_CompareExchange_Object (MonoObject **location, MonoObject *value, MonoObject *comparand)
1770 MONO_ARCH_SAVE_REGS;
1772 return (MonoObject *) InterlockedCompareExchangePointer((gpointer *) location, value, comparand);
1775 gfloat ves_icall_System_Threading_Interlocked_CompareExchange_Single (gfloat *location, gfloat value, gfloat comparand)
1777 IntFloatUnion val, ret, cmp;
1779 MONO_ARCH_SAVE_REGS;
1781 val.fval = value;
1782 cmp.fval = comparand;
1783 ret.ival = InterlockedCompareExchange((gint32 *) location, val.ival, cmp.ival);
1785 return ret.fval;
1788 gdouble
1789 ves_icall_System_Threading_Interlocked_CompareExchange_Double (gdouble *location, gdouble value, gdouble comparand)
1791 #if SIZEOF_VOID_P == 8
1792 LongDoubleUnion val, comp, ret;
1794 val.fval = value;
1795 comp.fval = comparand;
1796 ret.ival = (gint64)InterlockedCompareExchangePointer((gpointer *) location, (gpointer)val.ival, (gpointer)comp.ival);
1798 return ret.fval;
1799 #else
1800 gdouble old;
1802 mono_interlocked_lock ();
1803 old = *location;
1804 if (old == comparand)
1805 *location = value;
1806 mono_interlocked_unlock ();
1808 return old;
1809 #endif
1812 gint64
1813 ves_icall_System_Threading_Interlocked_CompareExchange_Long (gint64 *location, gint64 value, gint64 comparand)
1815 #if SIZEOF_VOID_P == 8
1816 return (gint64)InterlockedCompareExchangePointer((gpointer *) location, (gpointer)value, (gpointer)comparand);
1817 #else
1818 gint64 old;
1820 mono_interlocked_lock ();
1821 old = *location;
1822 if (old == comparand)
1823 *location = value;
1824 mono_interlocked_unlock ();
1826 return old;
1827 #endif
1830 MonoObject*
1831 ves_icall_System_Threading_Interlocked_CompareExchange_T (MonoObject **location, MonoObject *value, MonoObject *comparand)
1833 MONO_ARCH_SAVE_REGS;
1835 return InterlockedCompareExchangePointer ((gpointer *)location, value, comparand);
1838 MonoObject*
1839 ves_icall_System_Threading_Interlocked_Exchange_T (MonoObject **location, MonoObject *value)
1841 MONO_ARCH_SAVE_REGS;
1843 return InterlockedExchangePointer ((gpointer *)location, value);
1846 gint32
1847 ves_icall_System_Threading_Interlocked_Add_Int (gint32 *location, gint32 value)
1849 #if SIZEOF_VOID_P == 8
1850 /* Should be implemented as a JIT intrinsic */
1851 mono_raise_exception (mono_get_exception_not_implemented (NULL));
1852 return 0;
1853 #else
1854 gint32 orig;
1856 mono_interlocked_lock ();
1857 orig = *location;
1858 *location = orig + value;
1859 mono_interlocked_unlock ();
1861 return orig + value;
1862 #endif
1865 gint64
1866 ves_icall_System_Threading_Interlocked_Add_Long (gint64 *location, gint64 value)
1868 #if SIZEOF_VOID_P == 8
1869 /* Should be implemented as a JIT intrinsic */
1870 mono_raise_exception (mono_get_exception_not_implemented (NULL));
1871 return 0;
1872 #else
1873 gint64 orig;
1875 mono_interlocked_lock ();
1876 orig = *location;
1877 *location = orig + value;
1878 mono_interlocked_unlock ();
1880 return orig + value;
1881 #endif
1884 gint64
1885 ves_icall_System_Threading_Interlocked_Read_Long (gint64 *location)
1887 #if SIZEOF_VOID_P == 8
1888 /* 64 bit reads are already atomic */
1889 return *location;
1890 #else
1891 gint64 res;
1893 mono_interlocked_lock ();
1894 res = *location;
1895 mono_interlocked_unlock ();
1897 return res;
1898 #endif
1901 void
1902 ves_icall_System_Threading_Thread_MemoryBarrier (void)
1904 mono_threads_lock ();
1905 mono_threads_unlock ();
1908 void
1909 ves_icall_System_Threading_Thread_ClrState (MonoThread* this, guint32 state)
1911 mono_thread_clr_state (this, state);
1913 if (state & ThreadState_Background) {
1914 /* If the thread changes the background mode, the main thread has to
1915 * be notified, since it has to rebuild the list of threads to
1916 * wait for.
1918 SetEvent (background_change_event);
1922 void
1923 ves_icall_System_Threading_Thread_SetState (MonoThread* this, guint32 state)
1925 mono_thread_set_state (this, state);
1927 if (state & ThreadState_Background) {
1928 /* If the thread changes the background mode, the main thread has to
1929 * be notified, since it has to rebuild the list of threads to
1930 * wait for.
1932 SetEvent (background_change_event);
1936 guint32
1937 ves_icall_System_Threading_Thread_GetState (MonoThread* this)
1939 guint32 state;
1941 ensure_synch_cs_set (this);
1943 EnterCriticalSection (this->synch_cs);
1945 state = this->state;
1947 LeaveCriticalSection (this->synch_cs);
1949 return state;
1952 void ves_icall_System_Threading_Thread_Interrupt_internal (MonoThread *this)
1954 gboolean throw = FALSE;
1956 ensure_synch_cs_set (this);
1958 if (this == mono_thread_current ())
1959 return;
1961 EnterCriticalSection (this->synch_cs);
1963 this->thread_interrupt_requested = TRUE;
1965 if (this->state & ThreadState_WaitSleepJoin) {
1966 throw = TRUE;
1969 LeaveCriticalSection (this->synch_cs);
1971 if (throw) {
1972 signal_thread_state_change (this);
1976 void mono_thread_current_check_pending_interrupt ()
1978 MonoThread *thread = mono_thread_current ();
1979 gboolean throw = FALSE;
1981 mono_debugger_check_interruption ();
1983 ensure_synch_cs_set (thread);
1985 EnterCriticalSection (thread->synch_cs);
1987 if (thread->thread_interrupt_requested) {
1988 throw = TRUE;
1989 thread->thread_interrupt_requested = FALSE;
1992 LeaveCriticalSection (thread->synch_cs);
1994 if (throw) {
1995 mono_raise_exception (mono_get_exception_thread_interrupted ());
1999 int
2000 mono_thread_get_abort_signal (void)
2002 #ifdef PLATFORM_WIN32
2003 return -1;
2004 #else
2005 #ifndef SIGRTMIN
2006 #ifdef SIGUSR1
2007 return SIGUSR1;
2008 #else
2009 return -1;
2010 #endif
2011 #else
2012 static int abort_signum = -1;
2013 int i;
2014 if (abort_signum != -1)
2015 return abort_signum;
2016 /* we try to avoid SIGRTMIN and any one that might have been set already, see bug #75387 */
2017 for (i = SIGRTMIN + 1; i < SIGRTMAX; ++i) {
2018 struct sigaction sinfo;
2019 sigaction (i, NULL, &sinfo);
2020 if (sinfo.sa_handler == SIG_DFL && (void*)sinfo.sa_sigaction == (void*)SIG_DFL) {
2021 abort_signum = i;
2022 return i;
2025 /* fallback to the old way */
2026 return SIGRTMIN;
2027 #endif
2028 #endif /* PLATFORM_WIN32 */
2031 #ifdef PLATFORM_WIN32
2032 static void CALLBACK interruption_request_apc (ULONG_PTR param)
2034 MonoException* exc = mono_thread_request_interruption (FALSE);
2035 if (exc) mono_raise_exception (exc);
2037 #endif /* PLATFORM_WIN32 */
2040 * signal_thread_state_change
2042 * Tells the thread that his state has changed and it has to enter the new
2043 * state as soon as possible.
2045 static void signal_thread_state_change (MonoThread *thread)
2047 if (thread == mono_thread_current ()) {
2048 /* Do it synchronously */
2049 MonoException *exc = mono_thread_request_interruption (FALSE);
2050 if (exc)
2051 mono_raise_exception (exc);
2054 #ifdef PLATFORM_WIN32
2055 QueueUserAPC ((PAPCFUNC)interruption_request_apc, thread->handle, NULL);
2056 #else
2057 /* fixme: store the state somewhere */
2058 #ifdef PTHREAD_POINTER_ID
2059 pthread_kill ((gpointer)(gsize)(thread->tid), mono_thread_get_abort_signal ());
2060 #else
2061 pthread_kill (thread->tid, mono_thread_get_abort_signal ());
2062 #endif
2065 * This will cause waits to be broken.
2066 * It will also prevent the thread from entering a wait, so if the thread returns
2067 * from the wait before it receives the abort signal, it will just spin in the wait
2068 * functions in the io-layer until the signal handler calls QueueUserAPC which will
2069 * make it return.
2071 wapi_interrupt_thread (thread->handle);
2072 #endif /* PLATFORM_WIN32 */
2075 void
2076 ves_icall_System_Threading_Thread_Abort (MonoThread *thread, MonoObject *state)
2078 MONO_ARCH_SAVE_REGS;
2080 ensure_synch_cs_set (thread);
2082 EnterCriticalSection (thread->synch_cs);
2084 if ((thread->state & ThreadState_AbortRequested) != 0 ||
2085 (thread->state & ThreadState_StopRequested) != 0 ||
2086 (thread->state & ThreadState_Stopped) != 0)
2088 LeaveCriticalSection (thread->synch_cs);
2089 return;
2092 if ((thread->state & ThreadState_Unstarted) != 0) {
2093 thread->state |= ThreadState_Aborted;
2094 LeaveCriticalSection (thread->synch_cs);
2095 return;
2098 thread->state |= ThreadState_AbortRequested;
2099 MONO_OBJECT_SETREF (thread, abort_state, state);
2100 thread->abort_exc = NULL;
2102 LeaveCriticalSection (thread->synch_cs);
2104 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Abort requested for %p (%"G_GSIZE_FORMAT")", __func__, GetCurrentThreadId (), thread, (gsize)thread->tid));
2106 /* During shutdown, we can't wait for other threads */
2107 if (!shutting_down)
2108 /* Make sure the thread is awake */
2109 mono_thread_resume (thread);
2111 signal_thread_state_change (thread);
2114 void
2115 ves_icall_System_Threading_Thread_ResetAbort (void)
2117 MonoThread *thread = mono_thread_current ();
2119 MONO_ARCH_SAVE_REGS;
2121 ensure_synch_cs_set (thread);
2123 EnterCriticalSection (thread->synch_cs);
2125 thread->state &= ~ThreadState_AbortRequested;
2127 if (!thread->abort_exc) {
2128 const char *msg = "Unable to reset abort because no abort was requested";
2129 LeaveCriticalSection (thread->synch_cs);
2130 mono_raise_exception (mono_get_exception_thread_state (msg));
2131 } else {
2132 thread->abort_exc = NULL;
2133 thread->abort_state = NULL;
2136 LeaveCriticalSection (thread->synch_cs);
2139 static gboolean
2140 mono_thread_suspend (MonoThread *thread)
2142 MONO_ARCH_SAVE_REGS;
2144 ensure_synch_cs_set (thread);
2146 EnterCriticalSection (thread->synch_cs);
2148 if ((thread->state & ThreadState_Unstarted) != 0 ||
2149 (thread->state & ThreadState_Aborted) != 0 ||
2150 (thread->state & ThreadState_Stopped) != 0)
2152 LeaveCriticalSection (thread->synch_cs);
2153 return FALSE;
2156 if ((thread->state & ThreadState_Suspended) != 0 ||
2157 (thread->state & ThreadState_SuspendRequested) != 0 ||
2158 (thread->state & ThreadState_StopRequested) != 0)
2160 LeaveCriticalSection (thread->synch_cs);
2161 return TRUE;
2164 thread->state |= ThreadState_SuspendRequested;
2166 LeaveCriticalSection (thread->synch_cs);
2168 signal_thread_state_change (thread);
2169 return TRUE;
2172 void
2173 ves_icall_System_Threading_Thread_Suspend (MonoThread *thread)
2175 if (!mono_thread_suspend (thread))
2176 mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started, or is dead."));
2179 static gboolean
2180 mono_thread_resume (MonoThread *thread)
2182 MONO_ARCH_SAVE_REGS;
2184 ensure_synch_cs_set (thread);
2186 EnterCriticalSection (thread->synch_cs);
2188 if ((thread->state & ThreadState_SuspendRequested) != 0) {
2189 thread->state &= ~ThreadState_SuspendRequested;
2190 LeaveCriticalSection (thread->synch_cs);
2191 return TRUE;
2194 if ((thread->state & ThreadState_Suspended) == 0 ||
2195 (thread->state & ThreadState_Unstarted) != 0 ||
2196 (thread->state & ThreadState_Aborted) != 0 ||
2197 (thread->state & ThreadState_Stopped) != 0)
2199 LeaveCriticalSection (thread->synch_cs);
2200 return FALSE;
2203 thread->resume_event = CreateEvent (NULL, TRUE, FALSE, NULL);
2204 if (thread->resume_event == NULL) {
2205 LeaveCriticalSection (thread->synch_cs);
2206 return(FALSE);
2209 /* Awake the thread */
2210 SetEvent (thread->suspend_event);
2212 LeaveCriticalSection (thread->synch_cs);
2214 /* Wait for the thread to awake */
2215 WaitForSingleObject (thread->resume_event, INFINITE);
2216 CloseHandle (thread->resume_event);
2217 thread->resume_event = NULL;
2219 return TRUE;
2222 void
2223 ves_icall_System_Threading_Thread_Resume (MonoThread *thread)
2225 if (!mono_thread_resume (thread))
2226 mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started, or is dead."));
2229 static gboolean
2230 find_wrapper (MonoMethod *m, gint no, gint ilo, gboolean managed, gpointer data)
2232 if (managed)
2233 return TRUE;
2235 if (m->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE ||
2236 m->wrapper_type == MONO_WRAPPER_XDOMAIN_INVOKE ||
2237 m->wrapper_type == MONO_WRAPPER_XDOMAIN_DISPATCH)
2239 *((gboolean*)data) = TRUE;
2240 return TRUE;
2242 return FALSE;
2245 static gboolean
2246 is_running_protected_wrapper (void)
2248 gboolean found = FALSE;
2249 mono_stack_walk (find_wrapper, &found);
2250 return found;
2253 void mono_thread_stop (MonoThread *thread)
2255 ensure_synch_cs_set (thread);
2257 EnterCriticalSection (thread->synch_cs);
2259 if ((thread->state & ThreadState_StopRequested) != 0 ||
2260 (thread->state & ThreadState_Stopped) != 0)
2262 LeaveCriticalSection (thread->synch_cs);
2263 return;
2266 /* Make sure the thread is awake */
2267 mono_thread_resume (thread);
2269 thread->state |= ThreadState_StopRequested;
2270 thread->state &= ~ThreadState_AbortRequested;
2272 LeaveCriticalSection (thread->synch_cs);
2274 signal_thread_state_change (thread);
2277 gint8
2278 ves_icall_System_Threading_Thread_VolatileRead1 (void *ptr)
2280 return *((volatile gint8 *) (ptr));
2283 gint16
2284 ves_icall_System_Threading_Thread_VolatileRead2 (void *ptr)
2286 return *((volatile gint16 *) (ptr));
2289 gint32
2290 ves_icall_System_Threading_Thread_VolatileRead4 (void *ptr)
2292 return *((volatile gint32 *) (ptr));
2295 gint64
2296 ves_icall_System_Threading_Thread_VolatileRead8 (void *ptr)
2298 return *((volatile gint64 *) (ptr));
2301 void *
2302 ves_icall_System_Threading_Thread_VolatileReadIntPtr (void *ptr)
2304 return (void *) *((volatile void **) ptr);
2307 void
2308 ves_icall_System_Threading_Thread_VolatileWrite1 (void *ptr, gint8 value)
2310 *((volatile gint8 *) ptr) = value;
2313 void
2314 ves_icall_System_Threading_Thread_VolatileWrite2 (void *ptr, gint16 value)
2316 *((volatile gint16 *) ptr) = value;
2319 void
2320 ves_icall_System_Threading_Thread_VolatileWrite4 (void *ptr, gint32 value)
2322 *((volatile gint32 *) ptr) = value;
2325 void
2326 ves_icall_System_Threading_Thread_VolatileWrite8 (void *ptr, gint64 value)
2328 *((volatile gint64 *) ptr) = value;
2331 void
2332 ves_icall_System_Threading_Thread_VolatileWriteIntPtr (void *ptr, void *value)
2334 *((volatile void **) ptr) = value;
2337 void mono_thread_init (MonoThreadStartCB start_cb,
2338 MonoThreadAttachCB attach_cb)
2340 MONO_GC_REGISTER_ROOT (small_id_table);
2341 InitializeCriticalSection(&threads_mutex);
2342 InitializeCriticalSection(&interlocked_mutex);
2343 InitializeCriticalSection(&contexts_mutex);
2344 InitializeCriticalSection(&delayed_free_table_mutex);
2345 InitializeCriticalSection(&small_id_mutex);
2347 background_change_event = CreateEvent (NULL, TRUE, FALSE, NULL);
2348 g_assert(background_change_event != NULL);
2350 mono_init_static_data_info (&thread_static_info);
2351 mono_init_static_data_info (&context_static_info);
2353 current_object_key=TlsAlloc();
2354 THREAD_DEBUG (g_message ("%s: Allocated current_object_key %d", __func__, current_object_key));
2356 mono_thread_start_cb = start_cb;
2357 mono_thread_attach_cb = attach_cb;
2359 delayed_free_table = g_array_new (FALSE, FALSE, sizeof (DelayedFreeItem));
2361 /* Get a pseudo handle to the current process. This is just a
2362 * kludge so that wapi can build a process handle if needed.
2363 * As a pseudo handle is returned, we don't need to clean
2364 * anything up.
2366 GetCurrentProcess ();
2369 void mono_thread_cleanup (void)
2371 mono_thread_hazardous_try_free_all ();
2373 #if !defined(PLATFORM_WIN32) && !defined(RUN_IN_SUBTHREAD)
2374 /* The main thread must abandon any held mutexes (particularly
2375 * important for named mutexes as they are shared across
2376 * processes, see bug 74680.) This will happen when the
2377 * thread exits, but if it's not running in a subthread it
2378 * won't exit in time.
2380 /* Using non-w32 API is a nasty kludge, but I couldn't find
2381 * anything in the documentation that would let me do this
2382 * here yet still be safe to call on windows.
2384 _wapi_thread_signal_self (mono_environment_exitcode_get ());
2385 #endif
2387 #if 0
2388 /* This stuff needs more testing, it seems one of these
2389 * critical sections can be locked when mono_thread_cleanup is
2390 * called.
2392 DeleteCriticalSection (&threads_mutex);
2393 DeleteCriticalSection (&interlocked_mutex);
2394 DeleteCriticalSection (&contexts_mutex);
2395 DeleteCriticalSection (&delayed_free_table_mutex);
2396 DeleteCriticalSection (&small_id_mutex);
2397 CloseHandle (background_change_event);
2398 #endif
2400 g_array_free (delayed_free_table, TRUE);
2401 delayed_free_table = NULL;
2403 TlsFree (current_object_key);
2406 void
2407 mono_threads_install_cleanup (MonoThreadCleanupFunc func)
2409 mono_thread_cleanup_fn = func;
2412 void
2413 mono_thread_set_manage_callback (MonoThread *thread, MonoThreadManageCallback func)
2415 thread->manage_callback = func;
2418 void mono_threads_install_notify_pending_exc (MonoThreadNotifyPendingExcFunc func)
2420 mono_thread_notify_pending_exc_fn = func;
2423 G_GNUC_UNUSED
2424 static void print_tids (gpointer key, gpointer value, gpointer user)
2426 /* GPOINTER_TO_UINT breaks horribly if sizeof(void *) >
2427 * sizeof(uint) and a cast to uint would overflow
2429 /* Older versions of glib don't have G_GSIZE_FORMAT, so just
2430 * print this as a pointer.
2432 g_message ("Waiting for: %p", key);
2435 struct wait_data
2437 HANDLE handles[MAXIMUM_WAIT_OBJECTS];
2438 MonoThread *threads[MAXIMUM_WAIT_OBJECTS];
2439 guint32 num;
2442 static void wait_for_tids (struct wait_data *wait, guint32 timeout)
2444 guint32 i, ret;
2446 THREAD_DEBUG (g_message("%s: %d threads to wait for in this batch", __func__, wait->num));
2448 ret=WaitForMultipleObjectsEx(wait->num, wait->handles, TRUE, timeout, FALSE);
2450 if(ret==WAIT_FAILED) {
2451 /* See the comment in build_wait_tids() */
2452 THREAD_DEBUG (g_message ("%s: Wait failed", __func__));
2453 return;
2456 for(i=0; i<wait->num; i++)
2457 CloseHandle (wait->handles[i]);
2459 if (ret == WAIT_TIMEOUT)
2460 return;
2462 for(i=0; i<wait->num; i++) {
2463 gsize tid = wait->threads[i]->tid;
2465 mono_threads_lock ();
2466 if(mono_g_hash_table_lookup (threads, (gpointer)tid)!=NULL) {
2467 /* This thread must have been killed, because
2468 * it hasn't cleaned itself up. (It's just
2469 * possible that the thread exited before the
2470 * parent thread had a chance to store the
2471 * handle, and now there is another pointer to
2472 * the already-exited thread stored. In this
2473 * case, we'll just get two
2474 * mono_profiler_thread_end() calls for the
2475 * same thread.)
2478 mono_threads_unlock ();
2479 THREAD_DEBUG (g_message ("%s: cleaning up after thread %p (%"G_GSIZE_FORMAT")", __func__, wait->threads[i], tid));
2480 thread_cleanup (wait->threads[i]);
2481 } else {
2482 mono_threads_unlock ();
2487 static void wait_for_tids_or_state_change (struct wait_data *wait, guint32 timeout)
2489 guint32 i, ret, count;
2491 THREAD_DEBUG (g_message("%s: %d threads to wait for in this batch", __func__, wait->num));
2493 /* Add the thread state change event, so it wakes up if a thread changes
2494 * to background mode.
2496 count = wait->num;
2497 if (count < MAXIMUM_WAIT_OBJECTS) {
2498 wait->handles [count] = background_change_event;
2499 count++;
2502 ret=WaitForMultipleObjectsEx (count, wait->handles, FALSE, timeout, FALSE);
2504 if(ret==WAIT_FAILED) {
2505 /* See the comment in build_wait_tids() */
2506 THREAD_DEBUG (g_message ("%s: Wait failed", __func__));
2507 return;
2510 for(i=0; i<wait->num; i++)
2511 CloseHandle (wait->handles[i]);
2513 if (ret == WAIT_TIMEOUT)
2514 return;
2516 if (ret < wait->num) {
2517 gsize tid = wait->threads[ret]->tid;
2518 mono_threads_lock ();
2519 if (mono_g_hash_table_lookup (threads, (gpointer)tid)!=NULL) {
2520 /* See comment in wait_for_tids about thread cleanup */
2521 mono_threads_unlock ();
2522 THREAD_DEBUG (g_message ("%s: cleaning up after thread %"G_GSIZE_FORMAT, __func__, tid));
2523 thread_cleanup (wait->threads [ret]);
2524 } else
2525 mono_threads_unlock ();
2529 static void build_wait_tids (gpointer key, gpointer value, gpointer user)
2531 struct wait_data *wait=(struct wait_data *)user;
2533 if(wait->num<MAXIMUM_WAIT_OBJECTS) {
2534 HANDLE handle;
2535 MonoThread *thread=(MonoThread *)value;
2537 /* Ignore background threads, we abort them later */
2538 /* Do not lock here since it is not needed and the caller holds threads_lock */
2539 if (thread->state & ThreadState_Background) {
2540 THREAD_DEBUG (g_message ("%s: ignoring background thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2541 return; /* just leave, ignore */
2544 if (mono_gc_is_finalizer_thread (thread)) {
2545 THREAD_DEBUG (g_message ("%s: ignoring finalizer thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2546 return;
2549 if (thread == mono_thread_current ()) {
2550 THREAD_DEBUG (g_message ("%s: ignoring current thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2551 return;
2554 if (thread == mono_thread_get_main ()) {
2555 THREAD_DEBUG (g_message ("%s: ignoring main thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2556 return;
2559 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
2560 if (handle == NULL) {
2561 THREAD_DEBUG (g_message ("%s: ignoring unopenable thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2562 return;
2565 THREAD_DEBUG (g_message ("%s: Invoking mono_thread_manage callback on thread %p", __func__, thread));
2566 if ((thread->manage_callback == NULL) || (thread->manage_callback (thread) == TRUE)) {
2567 wait->handles[wait->num]=handle;
2568 wait->threads[wait->num]=thread;
2569 wait->num++;
2571 THREAD_DEBUG (g_message ("%s: adding thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2572 } else {
2573 THREAD_DEBUG (g_message ("%s: ignoring (because of callback) thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2577 } else {
2578 /* Just ignore the rest, we can't do anything with
2579 * them yet
2584 static gboolean
2585 remove_and_abort_threads (gpointer key, gpointer value, gpointer user)
2587 struct wait_data *wait=(struct wait_data *)user;
2588 gsize self = GetCurrentThreadId ();
2589 MonoThread *thread = (MonoThread *) value;
2590 HANDLE handle;
2592 if (wait->num >= MAXIMUM_WAIT_OBJECTS)
2593 return FALSE;
2595 /* The finalizer thread is not a background thread */
2596 if (thread->tid != self && (thread->state & ThreadState_Background) != 0) {
2598 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
2599 if (handle == NULL)
2600 return FALSE;
2602 /* printf ("A: %d\n", wait->num); */
2603 wait->handles[wait->num]=thread->handle;
2604 wait->threads[wait->num]=thread;
2605 wait->num++;
2607 THREAD_DEBUG (g_print ("%s: Aborting id: %"G_GSIZE_FORMAT"\n", __func__, (gsize)thread->tid));
2608 mono_thread_stop (thread);
2609 return TRUE;
2612 return (thread->tid != self && !mono_gc_is_finalizer_thread (thread));
2615 static MonoException* mono_thread_execute_interruption (MonoThread *thread);
2617 /**
2618 * mono_threads_set_shutting_down:
2620 * Is called by a thread that wants to shut down Mono. If the runtime is already
2621 * shutting down, the calling thread is suspended/stopped, and this function never
2622 * returns.
2624 void
2625 mono_threads_set_shutting_down (void)
2627 MonoThread *current_thread = mono_thread_current ();
2629 mono_threads_lock ();
2631 if (shutting_down) {
2632 mono_threads_unlock ();
2634 /* Make sure we're properly suspended/stopped */
2636 EnterCriticalSection (current_thread->synch_cs);
2638 if ((current_thread->state & ThreadState_SuspendRequested) ||
2639 (current_thread->state & ThreadState_AbortRequested) ||
2640 (current_thread->state & ThreadState_StopRequested)) {
2641 LeaveCriticalSection (current_thread->synch_cs);
2642 mono_thread_execute_interruption (current_thread);
2643 } else {
2644 current_thread->state |= ThreadState_Stopped;
2645 LeaveCriticalSection (current_thread->synch_cs);
2648 /* Wake up other threads potentially waiting for us */
2649 ExitThread (0);
2650 } else {
2651 shutting_down = TRUE;
2653 /* Not really a background state change, but this will
2654 * interrupt the main thread if it is waiting for all
2655 * the other threads.
2657 SetEvent (background_change_event);
2659 mono_threads_unlock ();
2663 /**
2664 * mono_threads_is_shutting_down:
2666 * Returns whether a thread has commenced shutdown of Mono. Note that
2667 * if the function returns FALSE the caller must not assume that
2668 * shutdown is not in progress, because the situation might have
2669 * changed since the function returned. For that reason this function
2670 * is of very limited utility.
2672 gboolean
2673 mono_threads_is_shutting_down (void)
2675 return shutting_down;
2678 void mono_thread_manage (void)
2680 struct wait_data *wait=g_new0 (struct wait_data, 1);
2682 /* join each thread that's still running */
2683 THREAD_DEBUG (g_message ("%s: Joining each running thread...", __func__));
2685 mono_threads_lock ();
2686 if(threads==NULL) {
2687 THREAD_DEBUG (g_message("%s: No threads", __func__));
2688 mono_threads_unlock ();
2689 return;
2691 mono_threads_unlock ();
2693 do {
2694 mono_threads_lock ();
2695 if (shutting_down) {
2696 /* somebody else is shutting down */
2697 mono_threads_unlock ();
2698 break;
2700 THREAD_DEBUG (g_message ("%s: There are %d threads to join", __func__, mono_g_hash_table_size (threads));
2701 mono_g_hash_table_foreach (threads, print_tids, NULL));
2703 ResetEvent (background_change_event);
2704 wait->num=0;
2705 mono_g_hash_table_foreach (threads, build_wait_tids, wait);
2706 mono_threads_unlock ();
2707 if(wait->num>0) {
2708 /* Something to wait for */
2709 wait_for_tids_or_state_change (wait, INFINITE);
2711 THREAD_DEBUG (g_message ("%s: I have %d threads after waiting.", __func__, wait->num));
2712 } while(wait->num>0);
2714 mono_threads_set_shutting_down ();
2716 /* No new threads will be created after this point */
2718 mono_runtime_set_shutting_down ();
2720 THREAD_DEBUG (g_message ("%s: threadpool cleanup", __func__));
2721 mono_thread_pool_cleanup ();
2724 * Remove everything but the finalizer thread and self.
2725 * Also abort all the background threads
2726 * */
2727 do {
2728 mono_threads_lock ();
2730 wait->num = 0;
2731 mono_g_hash_table_foreach_remove (threads, remove_and_abort_threads, wait);
2733 mono_threads_unlock ();
2735 THREAD_DEBUG (g_message ("%s: wait->num is now %d", __func__, wait->num));
2736 if(wait->num>0) {
2737 /* Something to wait for */
2738 wait_for_tids (wait, INFINITE);
2740 } while (wait->num > 0);
2743 * give the subthreads a chance to really quit (this is mainly needed
2744 * to get correct user and system times from getrusage/wait/time(1)).
2745 * This could be removed if we avoid pthread_detach() and use pthread_join().
2747 #ifndef PLATFORM_WIN32
2748 sched_yield ();
2749 #endif
2751 g_free (wait);
2754 static void terminate_thread (gpointer key, gpointer value, gpointer user)
2756 MonoThread *thread=(MonoThread *)value;
2758 if(thread->tid != (gsize)user) {
2759 /*TerminateThread (thread->handle, -1);*/
2763 void mono_thread_abort_all_other_threads (void)
2765 gsize self = GetCurrentThreadId ();
2767 mono_threads_lock ();
2768 THREAD_DEBUG (g_message ("%s: There are %d threads to abort", __func__,
2769 mono_g_hash_table_size (threads));
2770 mono_g_hash_table_foreach (threads, print_tids, NULL));
2772 mono_g_hash_table_foreach (threads, terminate_thread, (gpointer)self);
2774 mono_threads_unlock ();
2777 static void
2778 collect_threads_for_suspend (gpointer key, gpointer value, gpointer user_data)
2780 MonoThread *thread = (MonoThread*)value;
2781 struct wait_data *wait = (struct wait_data*)user_data;
2782 HANDLE handle;
2785 * We try to exclude threads early, to avoid running into the MAXIMUM_WAIT_OBJECTS
2786 * limitation.
2787 * This needs no locking.
2789 if ((thread->state & ThreadState_Suspended) != 0 ||
2790 (thread->state & ThreadState_Stopped) != 0)
2791 return;
2793 if (wait->num<MAXIMUM_WAIT_OBJECTS) {
2794 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
2795 if (handle == NULL)
2796 return;
2798 wait->handles [wait->num] = handle;
2799 wait->threads [wait->num] = thread;
2800 wait->num++;
2805 * mono_thread_suspend_all_other_threads:
2807 * Suspend all managed threads except the finalizer thread and this thread. It is
2808 * not possible to resume them later.
2810 void mono_thread_suspend_all_other_threads (void)
2812 struct wait_data *wait = g_new0 (struct wait_data, 1);
2813 int i;
2814 gsize self = GetCurrentThreadId ();
2815 gpointer *events;
2816 guint32 eventidx = 0;
2817 gboolean starting, finished;
2820 * The other threads could be in an arbitrary state at this point, i.e.
2821 * they could be starting up, shutting down etc. This means that there could be
2822 * threads which are not even in the threads hash table yet.
2826 * First we set a barrier which will be checked by all threads before they
2827 * are added to the threads hash table, and they will exit if the flag is set.
2828 * This ensures that no threads could be added to the hash later.
2829 * We will use shutting_down as the barrier for now.
2831 g_assert (shutting_down);
2834 * We make multiple calls to WaitForMultipleObjects since:
2835 * - we can only wait for MAXIMUM_WAIT_OBJECTS threads
2836 * - some threads could exit without becoming suspended
2838 finished = FALSE;
2839 while (!finished) {
2841 * Make a copy of the hashtable since we can't do anything with
2842 * threads while threads_mutex is held.
2844 wait->num = 0;
2845 mono_threads_lock ();
2846 mono_g_hash_table_foreach (threads, collect_threads_for_suspend, wait);
2847 mono_threads_unlock ();
2849 events = g_new0 (gpointer, wait->num);
2850 eventidx = 0;
2851 /* Get the suspended events that we'll be waiting for */
2852 for (i = 0; i < wait->num; ++i) {
2853 MonoThread *thread = wait->threads [i];
2854 gboolean signal_suspend = FALSE;
2856 if ((thread->tid == self) || mono_gc_is_finalizer_thread (thread)) {
2857 //CloseHandle (wait->handles [i]);
2858 wait->threads [i] = NULL; /* ignore this thread in next loop */
2859 continue;
2862 ensure_synch_cs_set (thread);
2864 EnterCriticalSection (thread->synch_cs);
2866 if (thread->suspended_event == NULL) {
2867 thread->suspended_event = CreateEvent (NULL, TRUE, FALSE, NULL);
2868 if (thread->suspended_event == NULL) {
2869 /* Forget this one and go on to the next */
2870 LeaveCriticalSection (thread->synch_cs);
2871 continue;
2875 if ((thread->state & ThreadState_Suspended) != 0 ||
2876 (thread->state & ThreadState_StopRequested) != 0 ||
2877 (thread->state & ThreadState_Stopped) != 0) {
2878 LeaveCriticalSection (thread->synch_cs);
2879 CloseHandle (wait->handles [i]);
2880 wait->threads [i] = NULL; /* ignore this thread in next loop */
2881 continue;
2884 if ((thread->state & ThreadState_SuspendRequested) == 0)
2885 signal_suspend = TRUE;
2887 events [eventidx++] = thread->suspended_event;
2889 /* Convert abort requests into suspend requests */
2890 if ((thread->state & ThreadState_AbortRequested) != 0)
2891 thread->state &= ~ThreadState_AbortRequested;
2893 thread->state |= ThreadState_SuspendRequested;
2895 LeaveCriticalSection (thread->synch_cs);
2897 /* Signal the thread to suspend */
2898 if (signal_suspend)
2899 signal_thread_state_change (thread);
2902 if (eventidx > 0) {
2903 WaitForMultipleObjectsEx (eventidx, events, TRUE, 100, FALSE);
2904 for (i = 0; i < wait->num; ++i) {
2905 MonoThread *thread = wait->threads [i];
2907 if (thread == NULL)
2908 continue;
2910 EnterCriticalSection (thread->synch_cs);
2911 if ((thread->state & ThreadState_Suspended) != 0) {
2912 CloseHandle (thread->suspended_event);
2913 thread->suspended_event = NULL;
2915 LeaveCriticalSection (thread->synch_cs);
2917 } else {
2919 * If there are threads which are starting up, we wait until they
2920 * are suspended when they try to register in the threads hash.
2921 * This is guaranteed to finish, since the threads which can create new
2922 * threads get suspended after a while.
2923 * FIXME: The finalizer thread can still create new threads.
2925 mono_threads_lock ();
2926 starting = mono_g_hash_table_size (threads_starting_up) > 0;
2927 mono_threads_unlock ();
2928 if (starting)
2929 Sleep (100);
2930 else
2931 finished = TRUE;
2934 g_free (events);
2937 g_free (wait);
2940 static void
2941 collect_threads (gpointer key, gpointer value, gpointer user_data)
2943 MonoThread *thread = (MonoThread*)value;
2944 struct wait_data *wait = (struct wait_data*)user_data;
2945 HANDLE handle;
2947 if (wait->num<MAXIMUM_WAIT_OBJECTS) {
2948 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
2949 if (handle == NULL)
2950 return;
2952 wait->handles [wait->num] = handle;
2953 wait->threads [wait->num] = thread;
2954 wait->num++;
2959 * mono_threads_request_thread_dump:
2961 * Ask all threads except the current to print their stacktrace to stdout.
2963 void
2964 mono_threads_request_thread_dump (void)
2966 struct wait_data *wait = g_new0 (struct wait_data, 1);
2967 int i;
2970 * Make a copy of the hashtable since we can't do anything with
2971 * threads while threads_mutex is held.
2973 mono_threads_lock ();
2974 mono_g_hash_table_foreach (threads, collect_threads, wait);
2975 mono_threads_unlock ();
2977 for (i = 0; i < wait->num; ++i) {
2978 MonoThread *thread = wait->threads [i];
2980 if (!mono_gc_is_finalizer_thread (thread) && (thread != mono_thread_current ()) && !thread->thread_dump_requested) {
2981 thread->thread_dump_requested = TRUE;
2983 signal_thread_state_change (thread);
2986 CloseHandle (wait->handles [i]);
2991 * mono_thread_push_appdomain_ref:
2993 * Register that the current thread may have references to objects in domain
2994 * @domain on its stack. Each call to this function should be paired with a
2995 * call to pop_appdomain_ref.
2997 void
2998 mono_thread_push_appdomain_ref (MonoDomain *domain)
3000 MonoThread *thread = mono_thread_current ();
3002 if (thread) {
3003 /* printf ("PUSH REF: %"G_GSIZE_FORMAT" -> %s.\n", (gsize)thread->tid, domain->friendly_name); */
3004 mono_threads_lock ();
3005 thread->appdomain_refs = g_slist_prepend (thread->appdomain_refs, domain);
3006 mono_threads_unlock ();
3010 void
3011 mono_thread_pop_appdomain_ref (void)
3013 MonoThread *thread = mono_thread_current ();
3015 if (thread) {
3016 /* printf ("POP REF: %"G_GSIZE_FORMAT" -> %s.\n", (gsize)thread->tid, ((MonoDomain*)(thread->appdomain_refs->data))->friendly_name); */
3017 mono_threads_lock ();
3018 /* FIXME: How can the list be empty ? */
3019 if (thread->appdomain_refs)
3020 thread->appdomain_refs = g_slist_remove (thread->appdomain_refs, thread->appdomain_refs->data);
3021 mono_threads_unlock ();
3025 gboolean
3026 mono_thread_has_appdomain_ref (MonoThread *thread, MonoDomain *domain)
3028 gboolean res;
3029 mono_threads_lock ();
3030 res = g_slist_find (thread->appdomain_refs, domain) != NULL;
3031 mono_threads_unlock ();
3032 return res;
3035 typedef struct abort_appdomain_data {
3036 struct wait_data wait;
3037 MonoDomain *domain;
3038 } abort_appdomain_data;
3040 static void
3041 collect_appdomain_thread (gpointer key, gpointer value, gpointer user_data)
3043 MonoThread *thread = (MonoThread*)value;
3044 abort_appdomain_data *data = (abort_appdomain_data*)user_data;
3045 MonoDomain *domain = data->domain;
3047 if (mono_thread_has_appdomain_ref (thread, domain)) {
3048 /* printf ("ABORTING THREAD %p BECAUSE IT REFERENCES DOMAIN %s.\n", thread->tid, domain->friendly_name); */
3050 if(data->wait.num<MAXIMUM_WAIT_OBJECTS) {
3051 HANDLE handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
3052 if (handle == NULL)
3053 return;
3054 data->wait.handles [data->wait.num] = handle;
3055 data->wait.threads [data->wait.num] = thread;
3056 data->wait.num++;
3057 } else {
3058 /* Just ignore the rest, we can't do anything with
3059 * them yet
3066 * mono_threads_abort_appdomain_threads:
3068 * Abort threads which has references to the given appdomain.
3070 gboolean
3071 mono_threads_abort_appdomain_threads (MonoDomain *domain, int timeout)
3073 abort_appdomain_data user_data;
3074 guint32 start_time;
3075 int orig_timeout = timeout;
3076 int i;
3078 THREAD_DEBUG (g_message ("%s: starting abort", __func__));
3080 start_time = mono_msec_ticks ();
3081 do {
3082 mono_threads_lock ();
3084 user_data.domain = domain;
3085 user_data.wait.num = 0;
3086 /* This shouldn't take any locks */
3087 mono_g_hash_table_foreach (threads, collect_appdomain_thread, &user_data);
3088 mono_threads_unlock ();
3090 if (user_data.wait.num > 0) {
3091 /* Abort the threads outside the threads lock */
3092 for (i = 0; i < user_data.wait.num; ++i)
3093 ves_icall_System_Threading_Thread_Abort (user_data.wait.threads [i], NULL);
3096 * We should wait for the threads either to abort, or to leave the
3097 * domain. We can't do the latter, so we wait with a timeout.
3099 wait_for_tids (&user_data.wait, 100);
3102 /* Update remaining time */
3103 timeout -= mono_msec_ticks () - start_time;
3104 start_time = mono_msec_ticks ();
3106 if (orig_timeout != -1 && timeout < 0)
3107 return FALSE;
3109 while (user_data.wait.num > 0);
3111 THREAD_DEBUG (g_message ("%s: abort done", __func__));
3113 return TRUE;
3116 static void
3117 clear_cached_culture (gpointer key, gpointer value, gpointer user_data)
3119 MonoThread *thread = (MonoThread*)value;
3120 MonoDomain *domain = (MonoDomain*)user_data;
3121 int i;
3123 /* No locking needed here */
3124 /* FIXME: why no locking? writes to the cache are protected with synch_cs above */
3126 if (thread->cached_culture_info) {
3127 for (i = 0; i < NUM_CACHED_CULTURES * 2; ++i) {
3128 MonoObject *obj = mono_array_get (thread->cached_culture_info, MonoObject*, i);
3129 if (obj && obj->vtable->domain == domain)
3130 mono_array_set (thread->cached_culture_info, MonoObject*, i, NULL);
3136 * mono_threads_clear_cached_culture:
3138 * Clear the cached_current_culture from all threads if it is in the
3139 * given appdomain.
3141 void
3142 mono_threads_clear_cached_culture (MonoDomain *domain)
3144 mono_threads_lock ();
3145 mono_g_hash_table_foreach (threads, clear_cached_culture, domain);
3146 mono_threads_unlock ();
3150 * mono_thread_get_undeniable_exception:
3152 * Return an exception which needs to be raised when leaving a catch clause.
3153 * This is used for undeniable exception propagation.
3155 MonoException*
3156 mono_thread_get_undeniable_exception (void)
3158 MonoThread *thread = mono_thread_current ();
3160 MONO_ARCH_SAVE_REGS;
3162 if (thread && thread->abort_exc && !is_running_protected_wrapper ()) {
3164 * FIXME: Clear the abort exception and return an AppDomainUnloaded
3165 * exception if the thread no longer references a dying appdomain.
3167 thread->abort_exc->trace_ips = NULL;
3168 thread->abort_exc->stack_trace = NULL;
3169 return thread->abort_exc;
3172 return NULL;
3175 #define NUM_STATIC_DATA_IDX 8
3176 static const int static_data_size [NUM_STATIC_DATA_IDX] = {
3177 1024, 4096, 16384, 65536, 262144, 1048576, 4194304, 16777216
3182 * mono_alloc_static_data
3184 * Allocate memory blocks for storing threads or context static data
3186 static void
3187 mono_alloc_static_data (gpointer **static_data_ptr, guint32 offset)
3189 guint idx = (offset >> 24) - 1;
3190 int i;
3192 gpointer* static_data = *static_data_ptr;
3193 if (!static_data) {
3194 static_data = mono_gc_alloc_fixed (static_data_size [0], NULL);
3195 *static_data_ptr = static_data;
3196 static_data [0] = static_data;
3199 for (i = 1; i <= idx; ++i) {
3200 if (static_data [i])
3201 continue;
3202 static_data [i] = mono_gc_alloc_fixed (static_data_size [i], NULL);
3207 * mono_init_static_data_info
3209 * Initializes static data counters
3211 static void mono_init_static_data_info (StaticDataInfo *static_data)
3213 static_data->idx = 0;
3214 static_data->offset = 0;
3215 static_data->freelist = NULL;
3219 * mono_alloc_static_data_slot
3221 * Generates an offset for static data. static_data contains the counters
3222 * used to generate it.
3224 static guint32
3225 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align)
3227 guint32 offset;
3229 if (!static_data->idx && !static_data->offset) {
3231 * we use the first chunk of the first allocation also as
3232 * an array for the rest of the data
3234 static_data->offset = sizeof (gpointer) * NUM_STATIC_DATA_IDX;
3236 static_data->offset += align - 1;
3237 static_data->offset &= ~(align - 1);
3238 if (static_data->offset + size >= static_data_size [static_data->idx]) {
3239 static_data->idx ++;
3240 g_assert (size <= static_data_size [static_data->idx]);
3241 g_assert (static_data->idx < NUM_STATIC_DATA_IDX);
3242 static_data->offset = 0;
3244 offset = static_data->offset | ((static_data->idx + 1) << 24);
3245 static_data->offset += size;
3246 return offset;
3250 * ensure thread static fields already allocated are valid for thread
3251 * This function is called when a thread is created or on thread attach.
3253 static void
3254 thread_adjust_static_data (MonoThread *thread)
3256 guint32 offset;
3258 mono_threads_lock ();
3259 if (thread_static_info.offset || thread_static_info.idx > 0) {
3260 /* get the current allocated size */
3261 offset = thread_static_info.offset | ((thread_static_info.idx + 1) << 24);
3262 mono_alloc_static_data (&(thread->static_data), offset);
3264 mono_threads_unlock ();
3267 static void
3268 alloc_thread_static_data_helper (gpointer key, gpointer value, gpointer user)
3270 MonoThread *thread = value;
3271 guint32 offset = GPOINTER_TO_UINT (user);
3273 mono_alloc_static_data (&(thread->static_data), offset);
3276 static MonoThreadDomainTls*
3277 search_tls_slot_in_freelist (StaticDataInfo *static_data, guint32 size, guint32 align)
3279 MonoThreadDomainTls* prev = NULL;
3280 MonoThreadDomainTls* tmp = static_data->freelist;
3281 while (tmp) {
3282 if (tmp->size == size) {
3283 if (prev)
3284 prev->next = tmp->next;
3285 else
3286 static_data->freelist = tmp->next;
3287 return tmp;
3289 tmp = tmp->next;
3291 return NULL;
3295 * The offset for a special static variable is composed of three parts:
3296 * a bit that indicates the type of static data (0:thread, 1:context),
3297 * an index in the array of chunks of memory for the thread (thread->static_data)
3298 * and an offset in that chunk of mem. This allows allocating less memory in the
3299 * common case.
3302 guint32
3303 mono_alloc_special_static_data (guint32 static_type, guint32 size, guint32 align)
3305 guint32 offset;
3306 if (static_type == SPECIAL_STATIC_THREAD)
3308 MonoThreadDomainTls *item;
3309 mono_threads_lock ();
3310 item = search_tls_slot_in_freelist (&thread_static_info, size, align);
3311 /*g_print ("TLS alloc: %d in domain %p (total: %d), cached: %p\n", size, mono_domain_get (), thread_static_info.offset, item);*/
3312 if (item) {
3313 offset = item->offset;
3314 g_free (item);
3315 } else {
3316 offset = mono_alloc_static_data_slot (&thread_static_info, size, align);
3318 /* This can be called during startup */
3319 if (threads != NULL)
3320 mono_g_hash_table_foreach (threads, alloc_thread_static_data_helper, GUINT_TO_POINTER (offset));
3321 mono_threads_unlock ();
3323 else
3325 g_assert (static_type == SPECIAL_STATIC_CONTEXT);
3326 mono_contexts_lock ();
3327 offset = mono_alloc_static_data_slot (&context_static_info, size, align);
3328 mono_contexts_unlock ();
3329 offset |= 0x80000000; /* Set the high bit to indicate context static data */
3331 return offset;
3334 gpointer
3335 mono_get_special_static_data (guint32 offset)
3337 /* The high bit means either thread (0) or static (1) data. */
3339 guint32 static_type = (offset & 0x80000000);
3340 int idx;
3342 offset &= 0x7fffffff;
3343 idx = (offset >> 24) - 1;
3345 if (static_type == 0)
3347 MonoThread *thread = mono_thread_current ();
3348 return ((char*) thread->static_data [idx]) + (offset & 0xffffff);
3350 else
3352 /* Allocate static data block under demand, since we don't have a list
3353 // of contexts
3355 MonoAppContext *context = mono_context_get ();
3356 if (!context->static_data || !context->static_data [idx]) {
3357 mono_contexts_lock ();
3358 mono_alloc_static_data (&(context->static_data), offset);
3359 mono_contexts_unlock ();
3361 return ((char*) context->static_data [idx]) + (offset & 0xffffff);
3365 typedef struct {
3366 guint32 offset;
3367 guint32 size;
3368 } TlsOffsetSize;
3370 static void
3371 free_thread_static_data_helper (gpointer key, gpointer value, gpointer user)
3373 MonoThread *thread = value;
3374 TlsOffsetSize *data = user;
3375 int idx = (data->offset >> 24) - 1;
3376 char *ptr;
3378 if (!thread->static_data || !thread->static_data [idx])
3379 return;
3380 ptr = ((char*) thread->static_data [idx]) + (data->offset & 0xffffff);
3381 memset (ptr, 0, data->size);
3384 static void
3385 do_free_special (gpointer key, gpointer value, gpointer data)
3387 MonoClassField *field = key;
3388 guint32 offset = GPOINTER_TO_UINT (value);
3389 guint32 static_type = (offset & 0x80000000);
3390 gint32 align;
3391 guint32 size;
3392 size = mono_type_size (field->type, &align);
3393 /*g_print ("free %s , size: %d, offset: %x\n", field->name, size, offset);*/
3394 if (static_type == 0) {
3395 TlsOffsetSize data;
3396 MonoThreadDomainTls *item = g_new0 (MonoThreadDomainTls, 1);
3397 data.offset = offset & 0x7fffffff;
3398 data.size = size;
3399 if (threads != NULL)
3400 mono_g_hash_table_foreach (threads, free_thread_static_data_helper, &data);
3401 item->offset = offset;
3402 item->size = size;
3403 item->next = thread_static_info.freelist;
3404 thread_static_info.freelist = item;
3405 } else {
3406 /* FIXME: free context static data as well */
3410 void
3411 mono_alloc_special_static_data_free (GHashTable *special_static_fields)
3413 mono_threads_lock ();
3414 g_hash_table_foreach (special_static_fields, do_free_special, NULL);
3415 mono_threads_unlock ();
3418 static MonoClassField *local_slots = NULL;
3420 typedef struct {
3421 /* local tls data to get locals_slot from a thread */
3422 guint32 offset;
3423 int idx;
3424 /* index in the locals_slot array */
3425 int slot;
3426 } LocalSlotID;
3428 static void
3429 clear_local_slot (gpointer key, gpointer value, gpointer user_data)
3431 LocalSlotID *sid = user_data;
3432 MonoThread *thread = (MonoThread*)value;
3433 MonoArray *slots_array;
3435 * the static field is stored at: ((char*) thread->static_data [idx]) + (offset & 0xffffff);
3436 * it is for the right domain, so we need to check if it is allocated an initialized
3437 * for the current thread.
3439 /*g_print ("handling thread %p\n", thread);*/
3440 if (!thread->static_data || !thread->static_data [sid->idx])
3441 return;
3442 slots_array = *(MonoArray **)(((char*) thread->static_data [sid->idx]) + (sid->offset & 0xffffff));
3443 if (!slots_array || sid->slot >= mono_array_length (slots_array))
3444 return;
3445 mono_array_set (slots_array, MonoObject*, sid->slot, NULL);
3448 void
3449 mono_thread_free_local_slot_values (int slot, MonoBoolean thread_local)
3451 MonoDomain *domain;
3452 LocalSlotID sid;
3453 sid.slot = slot;
3454 if (thread_local) {
3455 void *addr = NULL;
3456 if (!local_slots) {
3457 local_slots = mono_class_get_field_from_name (mono_defaults.thread_class, "local_slots");
3458 if (!local_slots) {
3459 g_warning ("local_slots field not found in Thread class");
3460 return;
3463 domain = mono_domain_get ();
3464 mono_domain_lock (domain);
3465 if (domain->special_static_fields)
3466 addr = g_hash_table_lookup (domain->special_static_fields, local_slots);
3467 mono_domain_unlock (domain);
3468 if (!addr)
3469 return;
3470 /*g_print ("freeing slot %d at %p\n", slot, addr);*/
3471 sid.offset = GPOINTER_TO_UINT (addr);
3472 sid.offset &= 0x7fffffff;
3473 sid.idx = (sid.offset >> 24) - 1;
3474 mono_threads_lock ();
3475 mono_g_hash_table_foreach (threads, clear_local_slot, &sid);
3476 mono_threads_unlock ();
3477 } else {
3478 /* FIXME: clear the slot for MonoAppContexts, too */
3482 #ifdef PLATFORM_WIN32
3483 static void CALLBACK dummy_apc (ULONG_PTR param)
3486 #else
3487 static guint32 dummy_apc (gpointer param)
3489 return 0;
3491 #endif
3494 * mono_thread_execute_interruption
3496 * Performs the operation that the requested thread state requires (abort,
3497 * suspend or stop)
3499 static MonoException* mono_thread_execute_interruption (MonoThread *thread)
3501 ensure_synch_cs_set (thread);
3503 EnterCriticalSection (thread->synch_cs);
3505 if (thread->interruption_requested) {
3506 /* this will consume pending APC calls */
3507 WaitForSingleObjectEx (GetCurrentThread(), 0, TRUE);
3508 InterlockedDecrement (&thread_interruption_requested);
3509 thread->interruption_requested = FALSE;
3510 #ifndef PLATFORM_WIN32
3511 /* Clear the interrupted flag of the thread so it can wait again */
3512 wapi_clear_interruption ();
3513 #endif
3516 if ((thread->state & ThreadState_AbortRequested) != 0) {
3517 if (thread->abort_exc == NULL)
3518 MONO_OBJECT_SETREF (thread, abort_exc, mono_get_exception_thread_abort ());
3519 LeaveCriticalSection (thread->synch_cs);
3520 return thread->abort_exc;
3522 else if ((thread->state & ThreadState_SuspendRequested) != 0) {
3523 thread->state &= ~ThreadState_SuspendRequested;
3524 thread->state |= ThreadState_Suspended;
3525 thread->suspend_event = CreateEvent (NULL, TRUE, FALSE, NULL);
3526 if (thread->suspend_event == NULL) {
3527 LeaveCriticalSection (thread->synch_cs);
3528 return(NULL);
3530 if (thread->suspended_event)
3531 SetEvent (thread->suspended_event);
3533 LeaveCriticalSection (thread->synch_cs);
3535 if (shutting_down) {
3536 /* After we left the lock, the runtime might shut down so everything becomes invalid */
3537 for (;;)
3538 Sleep (1000);
3541 WaitForSingleObject (thread->suspend_event, INFINITE);
3543 EnterCriticalSection (thread->synch_cs);
3545 CloseHandle (thread->suspend_event);
3546 thread->suspend_event = NULL;
3547 thread->state &= ~ThreadState_Suspended;
3549 /* The thread that requested the resume will have replaced this event
3550 * and will be waiting for it
3552 SetEvent (thread->resume_event);
3554 LeaveCriticalSection (thread->synch_cs);
3556 return NULL;
3558 else if ((thread->state & ThreadState_StopRequested) != 0) {
3559 /* FIXME: do this through the JIT? */
3561 LeaveCriticalSection (thread->synch_cs);
3563 mono_thread_exit ();
3564 return NULL;
3565 } else if (thread->thread_interrupt_requested) {
3567 thread->thread_interrupt_requested = FALSE;
3568 LeaveCriticalSection (thread->synch_cs);
3570 return(mono_get_exception_thread_interrupted ());
3573 LeaveCriticalSection (thread->synch_cs);
3575 return NULL;
3579 * mono_thread_request_interruption
3581 * A signal handler can call this method to request the interruption of a
3582 * thread. The result of the interruption will depend on the current state of
3583 * the thread. If the result is an exception that needs to be throw, it is
3584 * provided as return value.
3586 MonoException*
3587 mono_thread_request_interruption (gboolean running_managed)
3589 MonoThread *thread = mono_thread_current ();
3591 /* The thread may already be stopping */
3592 if (thread == NULL)
3593 return NULL;
3595 if (InterlockedCompareExchange (&thread->interruption_requested, 1, 0) == 1)
3596 return NULL;
3598 if (!running_managed || is_running_protected_wrapper ()) {
3599 /* Can't stop while in unmanaged code. Increase the global interruption
3600 request count. When exiting the unmanaged method the count will be
3601 checked and the thread will be interrupted. */
3603 InterlockedIncrement (&thread_interruption_requested);
3605 if (mono_thread_notify_pending_exc_fn && !running_managed)
3606 /* The JIT will notify the thread about the interruption */
3607 /* This shouldn't take any locks */
3608 mono_thread_notify_pending_exc_fn ();
3610 /* this will awake the thread if it is in WaitForSingleObject
3611 or similar */
3612 /* Our implementation of this function ignores the func argument */
3613 QueueUserAPC ((PAPCFUNC)dummy_apc, thread->handle, NULL);
3614 return NULL;
3616 else {
3617 return mono_thread_execute_interruption (thread);
3621 gboolean mono_thread_interruption_requested ()
3623 if (thread_interruption_requested) {
3624 MonoThread *thread = mono_thread_current ();
3625 /* The thread may already be stopping */
3626 if (thread != NULL)
3627 return (thread->interruption_requested);
3629 return FALSE;
3632 static void mono_thread_interruption_checkpoint_request (gboolean bypass_abort_protection)
3634 MonoThread *thread = mono_thread_current ();
3636 /* The thread may already be stopping */
3637 if (thread == NULL)
3638 return;
3640 mono_debugger_check_interruption ();
3642 if (thread->interruption_requested && (bypass_abort_protection || !is_running_protected_wrapper ())) {
3643 MonoException* exc = mono_thread_execute_interruption (thread);
3644 if (exc) mono_raise_exception (exc);
3649 * Performs the interruption of the current thread, if one has been requested,
3650 * and the thread is not running a protected wrapper.
3652 void mono_thread_interruption_checkpoint ()
3654 mono_thread_interruption_checkpoint_request (FALSE);
3658 * Performs the interruption of the current thread, if one has been requested.
3660 void mono_thread_force_interruption_checkpoint ()
3662 mono_thread_interruption_checkpoint_request (TRUE);
3666 * mono_thread_get_and_clear_pending_exception:
3668 * Return any pending exceptions for the current thread and clear it as a side effect.
3670 MonoException*
3671 mono_thread_get_and_clear_pending_exception (void)
3673 MonoThread *thread = mono_thread_current ();
3675 /* The thread may already be stopping */
3676 if (thread == NULL)
3677 return NULL;
3679 if (thread->interruption_requested && !is_running_protected_wrapper ()) {
3680 return mono_thread_execute_interruption (thread);
3683 if (thread->pending_exception) {
3684 MonoException *exc = thread->pending_exception;
3686 thread->pending_exception = NULL;
3687 return exc;
3690 return NULL;
3694 * mono_set_pending_exception:
3696 * Set the pending exception of the current thread to EXC. On platforms which
3697 * support it, the exception will be thrown when execution returns to managed code.
3698 * On other platforms, this function is equivalent to mono_raise_exception ().
3699 * Internal calls which report exceptions using this function instead of
3700 * raise_exception () might be called by JITted code using a more efficient calling
3701 * convention.
3703 void
3704 mono_set_pending_exception (MonoException *exc)
3706 MonoThread *thread = mono_thread_current ();
3708 /* The thread may already be stopping */
3709 if (thread == NULL)
3710 return;
3712 if (mono_thread_notify_pending_exc_fn) {
3713 MONO_OBJECT_SETREF (thread, pending_exception, exc);
3715 mono_thread_notify_pending_exc_fn ();
3716 } else {
3717 /* No way to notify the JIT about the exception, have to throw it now */
3718 mono_raise_exception (exc);
3723 * mono_thread_interruption_request_flag:
3725 * Returns the address of a flag that will be non-zero if an interruption has
3726 * been requested for a thread. The thread to interrupt may not be the current
3727 * thread, so an additional call to mono_thread_interruption_requested() or
3728 * mono_thread_interruption_checkpoint() is allways needed if the flag is not
3729 * zero.
3731 gint32* mono_thread_interruption_request_flag ()
3733 return &thread_interruption_requested;
3736 void
3737 mono_thread_init_apartment_state (void)
3739 MonoThread* thread;
3740 thread = mono_thread_current ();
3742 #ifdef PLATFORM_WIN32
3743 /* Positive return value indicates success, either
3744 * S_OK if this is first CoInitialize call, or
3745 * S_FALSE if CoInitialize already called, but with same
3746 * threading model. A negative value indicates failure,
3747 * probably due to trying to change the threading model.
3749 if (CoInitializeEx(NULL, (thread->apartment_state == ThreadApartmentState_STA)
3750 ? COINIT_APARTMENTTHREADED
3751 : COINIT_MULTITHREADED) < 0) {
3752 thread->apartment_state = ThreadApartmentState_Unknown;
3754 #endif
3757 void
3758 mono_thread_cleanup_apartment_state (void)
3760 #ifdef PLATFORM_WIN32
3761 MonoThread* thread;
3762 thread = mono_thread_current ();
3764 if (thread && thread->apartment_state != ThreadApartmentState_Unknown) {
3765 CoUninitialize ();
3767 #endif
3770 void
3771 mono_thread_set_state (MonoThread *thread, MonoThreadState state)
3773 ensure_synch_cs_set (thread);
3775 EnterCriticalSection (thread->synch_cs);
3776 thread->state |= state;
3777 LeaveCriticalSection (thread->synch_cs);
3780 void
3781 mono_thread_clr_state (MonoThread *thread, MonoThreadState state)
3783 ensure_synch_cs_set (thread);
3785 EnterCriticalSection (thread->synch_cs);
3786 thread->state &= ~state;
3787 LeaveCriticalSection (thread->synch_cs);
3790 gboolean
3791 mono_thread_test_state (MonoThread *thread, MonoThreadState test)
3793 gboolean ret = FALSE;
3795 ensure_synch_cs_set (thread);
3797 EnterCriticalSection (thread->synch_cs);
3799 if ((thread->state & test) != 0) {
3800 ret = TRUE;
3803 LeaveCriticalSection (thread->synch_cs);
3805 return ret;