2010-05-14 Rodrigo Kumpera <rkumpera@novell.com>
[mono-project.git] / mono / metadata / threads.c
blob7a2bb5c90ba3e175a62c635fb5245e1bdf5e6fc4
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 #if defined(__OpenBSD__)
20 #include <pthread.h>
21 #include <pthread_np.h>
22 #endif
24 #include <mono/metadata/object.h>
25 #include <mono/metadata/domain-internals.h>
26 #include <mono/metadata/profiler-private.h>
27 #include <mono/metadata/threads.h>
28 #include <mono/metadata/threadpool.h>
29 #include <mono/metadata/threads-types.h>
30 #include <mono/metadata/exception.h>
31 #include <mono/metadata/environment.h>
32 #include <mono/metadata/monitor.h>
33 #include <mono/metadata/gc-internal.h>
34 #include <mono/metadata/marshal.h>
35 #include <mono/io-layer/io-layer.h>
36 #ifndef HOST_WIN32
37 #include <mono/io-layer/threads.h>
38 #endif
39 #include <mono/metadata/object-internals.h>
40 #include <mono/metadata/mono-debug-debugger.h>
41 #include <mono/utils/mono-compiler.h>
42 #include <mono/utils/mono-mmap.h>
43 #include <mono/utils/mono-membar.h>
44 #include <mono/utils/mono-time.h>
46 #include <mono/metadata/gc-internal.h>
48 /*#define THREAD_DEBUG(a) do { a; } while (0)*/
49 #define THREAD_DEBUG(a)
50 /*#define THREAD_WAIT_DEBUG(a) do { a; } while (0)*/
51 #define THREAD_WAIT_DEBUG(a)
52 /*#define LIBGC_DEBUG(a) do { a; } while (0)*/
53 #define LIBGC_DEBUG(a)
55 #define SPIN_TRYLOCK(i) (InterlockedCompareExchange (&(i), 1, 0) == 0)
56 #define SPIN_LOCK(i) do { \
57 if (SPIN_TRYLOCK (i)) \
58 break; \
59 } while (1)
61 #define SPIN_UNLOCK(i) i = 0
63 /* Provide this for systems with glib < 2.6 */
64 #ifndef G_GSIZE_FORMAT
65 # if GLIB_SIZEOF_LONG == 8
66 # define G_GSIZE_FORMAT "lu"
67 # else
68 # define G_GSIZE_FORMAT "u"
69 # endif
70 #endif
72 struct StartInfo
74 guint32 (*func)(void *);
75 MonoThread *obj;
76 MonoObject *delegate;
77 void *start_arg;
80 typedef union {
81 gint32 ival;
82 gfloat fval;
83 } IntFloatUnion;
85 typedef union {
86 gint64 ival;
87 gdouble fval;
88 } LongDoubleUnion;
90 typedef struct _MonoThreadDomainTls MonoThreadDomainTls;
91 struct _MonoThreadDomainTls {
92 MonoThreadDomainTls *next;
93 guint32 offset;
94 guint32 size;
97 typedef struct {
98 int idx;
99 int offset;
100 MonoThreadDomainTls *freelist;
101 } StaticDataInfo;
103 typedef struct {
104 gpointer p;
105 MonoHazardousFreeFunc free_func;
106 } DelayedFreeItem;
108 /* Number of cached culture objects in the MonoThread->cached_culture_info array
109 * (per-type): we use the first NUM entries for CultureInfo and the last for
110 * UICultureInfo. So the size of the array is really NUM_CACHED_CULTURES * 2.
112 #define NUM_CACHED_CULTURES 4
113 #define CULTURES_START_IDX 0
114 #define UICULTURES_START_IDX NUM_CACHED_CULTURES
116 /* Controls access to the 'threads' hash table */
117 #define mono_threads_lock() EnterCriticalSection (&threads_mutex)
118 #define mono_threads_unlock() LeaveCriticalSection (&threads_mutex)
119 static CRITICAL_SECTION threads_mutex;
121 /* Controls access to context static data */
122 #define mono_contexts_lock() EnterCriticalSection (&contexts_mutex)
123 #define mono_contexts_unlock() LeaveCriticalSection (&contexts_mutex)
124 static CRITICAL_SECTION contexts_mutex;
126 /* Holds current status of static data heap */
127 static StaticDataInfo thread_static_info;
128 static StaticDataInfo context_static_info;
130 /* The hash of existing threads (key is thread ID, value is
131 * MonoInternalThread*) that need joining before exit
133 static MonoGHashTable *threads=NULL;
136 * Threads which are starting up and they are not in the 'threads' hash yet.
137 * When handle_store is called for a thread, it will be removed from this hash table.
138 * Protected by mono_threads_lock ().
140 static MonoGHashTable *threads_starting_up = NULL;
142 /* Maps a MonoThread to its start argument */
143 /* Protected by mono_threads_lock () */
144 static MonoGHashTable *thread_start_args = NULL;
146 /* The TLS key that holds the MonoObject assigned to each thread */
147 static guint32 current_object_key = -1;
149 #ifdef HAVE_KW_THREAD
150 /* we need to use both the Tls* functions and __thread because
151 * the gc needs to see all the threads
153 static __thread MonoInternalThread * tls_current_object MONO_TLS_FAST;
154 #define SET_CURRENT_OBJECT(x) do { \
155 tls_current_object = x; \
156 TlsSetValue (current_object_key, x); \
157 } while (FALSE)
158 #define GET_CURRENT_OBJECT() tls_current_object
159 #else
160 #define SET_CURRENT_OBJECT(x) TlsSetValue (current_object_key, x)
161 #define GET_CURRENT_OBJECT() (MonoThread*) TlsGetValue (current_object_key)
162 #endif
164 /* function called at thread start */
165 static MonoThreadStartCB mono_thread_start_cb = NULL;
167 /* function called at thread attach */
168 static MonoThreadAttachCB mono_thread_attach_cb = NULL;
170 /* function called at thread cleanup */
171 static MonoThreadCleanupFunc mono_thread_cleanup_fn = NULL;
173 /* function called to notify the runtime about a pending exception on the current thread */
174 static MonoThreadNotifyPendingExcFunc mono_thread_notify_pending_exc_fn = NULL;
176 /* The default stack size for each thread */
177 static guint32 default_stacksize = 0;
178 #define default_stacksize_for_thread(thread) ((thread)->stack_size? (thread)->stack_size: default_stacksize)
180 static void thread_adjust_static_data (MonoInternalThread *thread);
181 static void mono_free_static_data (gpointer* static_data, gboolean threadlocal);
182 static void mono_init_static_data_info (StaticDataInfo *static_data);
183 static guint32 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align);
184 static gboolean mono_thread_resume (MonoInternalThread* thread);
185 static void mono_thread_start (MonoThread *thread);
186 static void signal_thread_state_change (MonoInternalThread *thread);
188 static MonoException* mono_thread_execute_interruption (MonoInternalThread *thread);
190 /* Spin lock for InterlockedXXX 64 bit functions */
191 #define mono_interlocked_lock() EnterCriticalSection (&interlocked_mutex)
192 #define mono_interlocked_unlock() LeaveCriticalSection (&interlocked_mutex)
193 static CRITICAL_SECTION interlocked_mutex;
195 /* global count of thread interruptions requested */
196 static gint32 thread_interruption_requested = 0;
198 /* Event signaled when a thread changes its background mode */
199 static HANDLE background_change_event;
201 /* The table for small ID assignment */
202 static CRITICAL_SECTION small_id_mutex;
203 static int small_id_table_size = 0;
204 static int small_id_next = 0;
205 static int highest_small_id = -1;
206 static MonoInternalThread **small_id_table = NULL;
208 /* The hazard table */
209 #if MONO_SMALL_CONFIG
210 #define HAZARD_TABLE_MAX_SIZE 256
211 #else
212 #define HAZARD_TABLE_MAX_SIZE 16384 /* There cannot be more threads than this number. */
213 #endif
214 static volatile int hazard_table_size = 0;
215 static MonoThreadHazardPointers * volatile hazard_table = NULL;
217 /* The table where we keep pointers to blocks to be freed but that
218 have to wait because they're guarded by a hazard pointer. */
219 static CRITICAL_SECTION delayed_free_table_mutex;
220 static GArray *delayed_free_table = NULL;
222 static gboolean shutting_down = FALSE;
224 guint32
225 mono_thread_get_tls_key (void)
227 return current_object_key;
230 gint32
231 mono_thread_get_tls_offset (void)
233 int offset;
234 MONO_THREAD_VAR_OFFSET (tls_current_object,offset);
235 return offset;
238 /* handle_store() and handle_remove() manage the array of threads that
239 * still need to be waited for when the main thread exits.
241 * If handle_store() returns FALSE the thread must not be started
242 * because Mono is shutting down.
244 static gboolean handle_store(MonoThread *thread)
246 mono_threads_lock ();
248 THREAD_DEBUG (g_message ("%s: thread %p ID %"G_GSIZE_FORMAT, __func__, thread, (gsize)thread->tid));
250 if (threads_starting_up)
251 mono_g_hash_table_remove (threads_starting_up, thread);
253 if (shutting_down) {
254 mono_threads_unlock ();
255 return FALSE;
258 if(threads==NULL) {
259 MONO_GC_REGISTER_ROOT (threads);
260 threads=mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
263 /* We don't need to duplicate thread->handle, because it is
264 * only closed when the thread object is finalized by the GC.
266 g_assert (thread->internal_thread);
267 mono_g_hash_table_insert(threads, (gpointer)(gsize)(thread->internal_thread->tid),
268 thread->internal_thread);
270 mono_threads_unlock ();
272 return TRUE;
275 static gboolean handle_remove(MonoInternalThread *thread)
277 gboolean ret;
278 gsize tid = thread->tid;
280 THREAD_DEBUG (g_message ("%s: thread ID %"G_GSIZE_FORMAT, __func__, tid));
282 mono_threads_lock ();
284 if (threads) {
285 /* We have to check whether the thread object for the
286 * tid is still the same in the table because the
287 * thread might have been destroyed and the tid reused
288 * in the meantime, in which case the tid would be in
289 * the table, but with another thread object.
291 if (mono_g_hash_table_lookup (threads, (gpointer)tid) == thread) {
292 mono_g_hash_table_remove (threads, (gpointer)tid);
293 ret = TRUE;
294 } else {
295 ret = FALSE;
298 else
299 ret = FALSE;
301 mono_threads_unlock ();
303 /* Don't close the handle here, wait for the object finalizer
304 * to do it. Otherwise, the following race condition applies:
306 * 1) Thread exits (and handle_remove() closes the handle)
308 * 2) Some other handle is reassigned the same slot
310 * 3) Another thread tries to join the first thread, and
311 * blocks waiting for the reassigned handle to be signalled
312 * (which might never happen). This is possible, because the
313 * thread calling Join() still has a reference to the first
314 * thread's object.
316 return ret;
320 * Allocate a small thread id.
322 * FIXME: The biggest part of this function is very similar to
323 * domain_id_alloc() in domain.c and should be merged.
325 static int
326 small_id_alloc (MonoInternalThread *thread)
328 int id = -1, i;
330 EnterCriticalSection (&small_id_mutex);
332 if (!small_id_table) {
333 small_id_table_size = 2;
334 small_id_table = mono_gc_alloc_fixed (small_id_table_size * sizeof (MonoInternalThread*), NULL);
336 for (i = small_id_next; i < small_id_table_size; ++i) {
337 if (!small_id_table [i]) {
338 id = i;
339 break;
342 if (id == -1) {
343 for (i = 0; i < small_id_next; ++i) {
344 if (!small_id_table [i]) {
345 id = i;
346 break;
350 if (id == -1) {
351 MonoInternalThread **new_table;
352 int new_size = small_id_table_size * 2;
353 if (new_size >= (1 << 16))
354 g_assert_not_reached ();
355 id = small_id_table_size;
356 new_table = mono_gc_alloc_fixed (new_size * sizeof (MonoInternalThread*), NULL);
357 memcpy (new_table, small_id_table, small_id_table_size * sizeof (void*));
358 mono_gc_free_fixed (small_id_table);
359 small_id_table = new_table;
360 small_id_table_size = new_size;
362 thread->small_id = id;
363 g_assert (small_id_table [id] == NULL);
364 small_id_table [id] = thread;
365 small_id_next++;
366 if (small_id_next > small_id_table_size)
367 small_id_next = 0;
369 g_assert (id < HAZARD_TABLE_MAX_SIZE);
370 if (id >= hazard_table_size) {
371 #if MONO_SMALL_CONFIG
372 hazard_table = g_malloc0 (sizeof (MonoThreadHazardPointers) * HAZARD_TABLE_MAX_SIZE);
373 hazard_table_size = HAZARD_TABLE_MAX_SIZE;
374 #else
375 gpointer page_addr;
376 int pagesize = mono_pagesize ();
377 int num_pages = (hazard_table_size * sizeof (MonoThreadHazardPointers) + pagesize - 1) / pagesize;
379 if (hazard_table == NULL) {
380 hazard_table = mono_valloc (NULL,
381 sizeof (MonoThreadHazardPointers) * HAZARD_TABLE_MAX_SIZE,
382 MONO_MMAP_NONE);
385 g_assert (hazard_table != NULL);
386 page_addr = (guint8*)hazard_table + num_pages * pagesize;
388 mono_mprotect (page_addr, pagesize, MONO_MMAP_READ | MONO_MMAP_WRITE);
390 ++num_pages;
391 hazard_table_size = num_pages * pagesize / sizeof (MonoThreadHazardPointers);
393 #endif
394 g_assert (id < hazard_table_size);
395 hazard_table [id].hazard_pointers [0] = NULL;
396 hazard_table [id].hazard_pointers [1] = NULL;
399 if (id > highest_small_id) {
400 highest_small_id = id;
401 mono_memory_write_barrier ();
404 LeaveCriticalSection (&small_id_mutex);
406 return id;
409 static void
410 small_id_free (int id)
412 g_assert (id >= 0 && id < small_id_table_size);
413 g_assert (small_id_table [id] != NULL);
415 small_id_table [id] = NULL;
418 static gboolean
419 is_pointer_hazardous (gpointer p)
421 int i;
422 int highest = highest_small_id;
424 g_assert (highest < hazard_table_size);
426 for (i = 0; i <= highest; ++i) {
427 if (hazard_table [i].hazard_pointers [0] == p
428 || hazard_table [i].hazard_pointers [1] == p)
429 return TRUE;
432 return FALSE;
435 MonoThreadHazardPointers*
436 mono_hazard_pointer_get (void)
438 MonoInternalThread *current_thread = mono_thread_internal_current ();
440 if (!(current_thread && current_thread->small_id >= 0)) {
441 static MonoThreadHazardPointers emerg_hazard_table;
442 g_warning ("Thread %p may have been prematurely finalized", current_thread);
443 return &emerg_hazard_table;
446 return &hazard_table [current_thread->small_id];
449 static void
450 try_free_delayed_free_item (int index)
452 if (delayed_free_table->len > index) {
453 DelayedFreeItem item = { NULL, NULL };
455 EnterCriticalSection (&delayed_free_table_mutex);
456 /* We have to check the length again because another
457 thread might have freed an item before we acquired
458 the lock. */
459 if (delayed_free_table->len > index) {
460 item = g_array_index (delayed_free_table, DelayedFreeItem, index);
462 if (!is_pointer_hazardous (item.p))
463 g_array_remove_index_fast (delayed_free_table, index);
464 else
465 item.p = NULL;
467 LeaveCriticalSection (&delayed_free_table_mutex);
469 if (item.p != NULL)
470 item.free_func (item.p);
474 void
475 mono_thread_hazardous_free_or_queue (gpointer p, MonoHazardousFreeFunc free_func)
477 int i;
479 /* First try to free a few entries in the delayed free
480 table. */
481 for (i = 2; i >= 0; --i)
482 try_free_delayed_free_item (i);
484 /* Now see if the pointer we're freeing is hazardous. If it
485 isn't, free it. Otherwise put it in the delay list. */
486 if (is_pointer_hazardous (p)) {
487 DelayedFreeItem item = { p, free_func };
489 ++mono_stats.hazardous_pointer_count;
491 EnterCriticalSection (&delayed_free_table_mutex);
492 g_array_append_val (delayed_free_table, item);
493 LeaveCriticalSection (&delayed_free_table_mutex);
494 } else
495 free_func (p);
498 void
499 mono_thread_hazardous_try_free_all (void)
501 int len;
502 int i;
504 if (!delayed_free_table)
505 return;
507 len = delayed_free_table->len;
509 for (i = len - 1; i >= 0; --i)
510 try_free_delayed_free_item (i);
513 static void ensure_synch_cs_set (MonoInternalThread *thread)
515 CRITICAL_SECTION *synch_cs;
517 if (thread->synch_cs != NULL) {
518 return;
521 synch_cs = g_new0 (CRITICAL_SECTION, 1);
522 InitializeCriticalSection (synch_cs);
524 if (InterlockedCompareExchangePointer ((gpointer *)&thread->synch_cs,
525 synch_cs, NULL) != NULL) {
526 /* Another thread must have installed this CS */
527 DeleteCriticalSection (synch_cs);
528 g_free (synch_cs);
533 * NOTE: this function can be called also for threads different from the current one:
534 * make sure no code called from it will ever assume it is run on the thread that is
535 * getting cleaned up.
537 static void thread_cleanup (MonoInternalThread *thread)
539 g_assert (thread != NULL);
541 if (thread->abort_state_handle) {
542 mono_gchandle_free (thread->abort_state_handle);
543 thread->abort_state_handle = 0;
545 thread->abort_exc = NULL;
546 thread->current_appcontext = NULL;
549 * This is necessary because otherwise we might have
550 * cross-domain references which will not get cleaned up when
551 * the target domain is unloaded.
553 if (thread->cached_culture_info) {
554 int i;
555 for (i = 0; i < NUM_CACHED_CULTURES * 2; ++i)
556 mono_array_set (thread->cached_culture_info, MonoObject*, i, NULL);
559 /* if the thread is not in the hash it has been removed already */
560 if (!handle_remove (thread))
561 return;
562 mono_release_type_locks (thread);
564 EnterCriticalSection (thread->synch_cs);
566 thread->state |= ThreadState_Stopped;
567 thread->state &= ~ThreadState_Background;
569 LeaveCriticalSection (thread->synch_cs);
571 mono_profiler_thread_end (thread->tid);
573 if (thread == mono_thread_internal_current ())
574 mono_thread_pop_appdomain_ref ();
576 thread->cached_culture_info = NULL;
578 mono_free_static_data (thread->static_data, TRUE);
579 thread->static_data = NULL;
582 * FIXME: The check for shutting_down here is a kludge and
583 * should be removed. The reason we need it here is because
584 * mono_thread_manage() does not wait for finalizer threads,
585 * so we might still be at this point in a finalizer thread
586 * after the main thread has cleared the root domain, so
587 * thread could have been zeroed out.
589 if (mono_thread_cleanup_fn && !shutting_down)
590 mono_thread_cleanup_fn (thread->root_domain_thread);
592 small_id_free (thread->small_id);
593 thread->small_id = -2;
596 static gpointer
597 get_thread_static_data (MonoInternalThread *thread, guint32 offset)
599 int idx;
600 g_assert ((offset & 0x80000000) == 0);
601 offset &= 0x7fffffff;
602 idx = (offset >> 24) - 1;
603 return ((char*) thread->static_data [idx]) + (offset & 0xffffff);
606 static MonoThread**
607 get_current_thread_ptr_for_domain (MonoDomain *domain, MonoInternalThread *thread)
609 static MonoClassField *current_thread_field = NULL;
611 guint32 offset;
613 if (!current_thread_field) {
614 current_thread_field = mono_class_get_field_from_name (mono_defaults.thread_class, "current_thread");
615 g_assert (current_thread_field);
618 mono_class_vtable (domain, mono_defaults.thread_class);
619 mono_domain_lock (domain);
620 offset = GPOINTER_TO_UINT (g_hash_table_lookup (domain->special_static_fields, current_thread_field));
621 mono_domain_unlock (domain);
622 g_assert (offset);
624 return get_thread_static_data (thread, offset);
627 static void
628 set_current_thread_for_domain (MonoDomain *domain, MonoInternalThread *thread, MonoThread *current)
630 MonoThread **current_thread_ptr = get_current_thread_ptr_for_domain (domain, thread);
632 g_assert (current->obj.vtable->domain == domain);
634 g_assert (!*current_thread_ptr);
635 *current_thread_ptr = current;
638 static MonoThread*
639 new_thread_with_internal (MonoDomain *domain, MonoInternalThread *internal)
641 MonoThread *thread = (MonoThread*) mono_object_new (domain, mono_defaults.thread_class);
642 MONO_OBJECT_SETREF (thread, internal_thread, internal);
643 return thread;
646 static void
647 init_root_domain_thread (MonoInternalThread *thread, MonoThread *candidate)
649 MonoDomain *domain = mono_get_root_domain ();
651 if (!candidate || candidate->obj.vtable->domain != domain)
652 candidate = new_thread_with_internal (domain, thread);
653 set_current_thread_for_domain (domain, thread, candidate);
654 g_assert (!thread->root_domain_thread);
655 MONO_OBJECT_SETREF (thread, root_domain_thread, candidate);
658 static guint32 WINAPI start_wrapper(void *data)
660 struct StartInfo *start_info=(struct StartInfo *)data;
661 guint32 (*start_func)(void *);
662 void *start_arg;
663 gsize tid;
664 MonoThread *thread=start_info->obj;
665 MonoInternalThread *internal = thread->internal_thread;
666 MonoObject *start_delegate = start_info->delegate;
668 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Start wrapper", __func__, GetCurrentThreadId ()));
670 /* We can be sure start_info->obj->tid and
671 * start_info->obj->handle have been set, because the thread
672 * was created suspended, and these values were set before the
673 * thread resumed
676 tid=internal->tid;
678 SET_CURRENT_OBJECT (internal);
680 mono_monitor_init_tls ();
682 /* Every thread references the appdomain which created it */
683 mono_thread_push_appdomain_ref (thread->obj.vtable->domain);
685 if (!mono_domain_set (thread->obj.vtable->domain, FALSE)) {
686 /* No point in raising an appdomain_unloaded exception here */
687 /* FIXME: Cleanup here */
688 mono_thread_pop_appdomain_ref ();
689 return 0;
692 start_func = start_info->func;
693 start_arg = start_info->start_arg;
695 /* We have to do this here because mono_thread_new_init()
696 requires that root_domain_thread is set up. */
697 thread_adjust_static_data (internal);
698 init_root_domain_thread (internal, thread);
700 /* This MUST be called before any managed code can be
701 * executed, as it calls the callback function that (for the
702 * jit) sets the lmf marker.
704 mono_thread_new_init (tid, &tid, start_func);
705 internal->stack_ptr = &tid;
707 LIBGC_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT",%d) Setting thread stack to %p", __func__, GetCurrentThreadId (), getpid (), thread->stack_ptr));
709 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Setting current_object_key to %p", __func__, GetCurrentThreadId (), thread));
711 /* On 2.0 profile (and higher), set explicitly since state might have been
712 Unknown */
713 if (internal->apartment_state == ThreadApartmentState_Unknown)
714 internal->apartment_state = ThreadApartmentState_MTA;
716 mono_thread_init_apartment_state ();
718 if(internal->start_notify!=NULL) {
719 /* Let the thread that called Start() know we're
720 * ready
722 ReleaseSemaphore (internal->start_notify, 1, NULL);
725 mono_threads_lock ();
726 mono_g_hash_table_remove (thread_start_args, thread);
727 mono_threads_unlock ();
729 g_free (start_info);
730 #ifdef DEBUG
731 g_message ("%s: start_wrapper for %"G_GSIZE_FORMAT, __func__,
732 thread->tid);
733 #endif
735 mono_thread_set_execution_context (thread->ec_to_set);
736 thread->ec_to_set = NULL;
739 * Call this after calling start_notify, since the profiler callback might want
740 * to lock the thread, and the lock is held by thread_start () which waits for
741 * start_notify.
743 mono_profiler_thread_start (tid);
745 /* start_func is set only for unmanaged start functions */
746 if (start_func) {
747 start_func (start_arg);
748 } else {
749 void *args [1];
750 g_assert (start_delegate != NULL);
751 args [0] = start_arg;
752 /* we may want to handle the exception here. See comment below on unhandled exceptions */
753 mono_runtime_delegate_invoke (start_delegate, args, NULL);
756 /* If the thread calls ExitThread at all, this remaining code
757 * will not be executed, but the main thread will eventually
758 * call thread_cleanup() on this thread's behalf.
761 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Start wrapper terminating", __func__, GetCurrentThreadId ()));
763 thread_cleanup (internal);
765 /* Do any cleanup needed for apartment state. This
766 * cannot be done in thread_cleanup since thread_cleanup could be
767 * called for a thread other than the current thread.
768 * mono_thread_cleanup_apartment_state cleans up apartment
769 * for the current thead */
770 mono_thread_cleanup_apartment_state ();
772 /* Remove the reference to the thread object in the TLS data,
773 * so the thread object can be finalized. This won't be
774 * reached if the thread threw an uncaught exception, so those
775 * thread handles will stay referenced :-( (This is due to
776 * missing support for scanning thread-specific data in the
777 * Boehm GC - the io-layer keeps a GC-visible hash of pointers
778 * to TLS data.)
780 SET_CURRENT_OBJECT (NULL);
781 mono_domain_unset ();
783 return(0);
786 void mono_thread_new_init (intptr_t tid, gpointer stack_start, gpointer func)
788 if (mono_thread_start_cb) {
789 mono_thread_start_cb (tid, stack_start, func);
793 void mono_threads_set_default_stacksize (guint32 stacksize)
795 default_stacksize = stacksize;
798 guint32 mono_threads_get_default_stacksize (void)
800 return default_stacksize;
804 * mono_create_thread:
806 * This is a wrapper around CreateThread which handles differences in the type of
807 * the the 'tid' argument.
809 gpointer mono_create_thread (WapiSecurityAttributes *security,
810 guint32 stacksize, WapiThreadStart start,
811 gpointer param, guint32 create, gsize *tid)
813 gpointer res;
815 #ifdef HOST_WIN32
816 DWORD real_tid;
818 res = CreateThread (security, stacksize, start, param, create, &real_tid);
819 if (tid)
820 *tid = real_tid;
821 #else
822 res = CreateThread (security, stacksize, start, param, create, tid);
823 #endif
825 return res;
829 * The thread start argument may be an object reference, and there is
830 * no ref to keep it alive when the new thread is started but not yet
831 * registered with the collector. So we store it in a GC tracked hash
832 * table.
834 * LOCKING: Assumes the threads lock is held.
836 static void
837 register_thread_start_argument (MonoThread *thread, struct StartInfo *start_info)
839 if (thread_start_args == NULL) {
840 MONO_GC_REGISTER_ROOT (thread_start_args);
841 thread_start_args = mono_g_hash_table_new (NULL, NULL);
843 mono_g_hash_table_insert (thread_start_args, thread, start_info->start_arg);
846 MonoInternalThread* mono_thread_create_internal (MonoDomain *domain, gpointer func, gpointer arg, gboolean threadpool_thread)
848 MonoThread *thread;
849 MonoInternalThread *internal;
850 HANDLE thread_handle;
851 struct StartInfo *start_info;
852 gsize tid;
854 thread=(MonoThread *)mono_object_new (domain,
855 mono_defaults.thread_class);
856 internal = (MonoInternalThread*)mono_object_new (mono_get_root_domain (),
857 mono_defaults.internal_thread_class);
858 MONO_OBJECT_SETREF (thread, internal_thread, internal);
860 start_info=g_new0 (struct StartInfo, 1);
861 start_info->func = func;
862 start_info->obj = thread;
863 start_info->start_arg = arg;
865 mono_threads_lock ();
866 if (shutting_down) {
867 mono_threads_unlock ();
868 g_free (start_info);
869 return NULL;
871 if (threads_starting_up == NULL) {
872 MONO_GC_REGISTER_ROOT (threads_starting_up);
873 threads_starting_up = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_VALUE_GC);
876 register_thread_start_argument (thread, start_info);
877 mono_g_hash_table_insert (threads_starting_up, thread, thread);
878 mono_threads_unlock ();
880 /* Create suspended, so we can do some housekeeping before the thread
881 * starts
883 thread_handle = mono_create_thread (NULL, default_stacksize_for_thread (internal), (LPTHREAD_START_ROUTINE)start_wrapper, start_info,
884 CREATE_SUSPENDED, &tid);
885 THREAD_DEBUG (g_message ("%s: Started thread ID %"G_GSIZE_FORMAT" (handle %p)", __func__, tid, thread_handle));
886 if (thread_handle == NULL) {
887 /* The thread couldn't be created, so throw an exception */
888 mono_threads_lock ();
889 mono_g_hash_table_remove (threads_starting_up, thread);
890 mono_threads_unlock ();
891 g_free (start_info);
892 mono_raise_exception (mono_get_exception_execution_engine ("Couldn't create thread"));
893 return NULL;
896 internal->handle=thread_handle;
897 internal->tid=tid;
898 internal->apartment_state=ThreadApartmentState_Unknown;
899 small_id_alloc (internal);
901 internal->synch_cs = g_new0 (CRITICAL_SECTION, 1);
902 InitializeCriticalSection (internal->synch_cs);
904 internal->threadpool_thread = threadpool_thread;
905 if (threadpool_thread)
906 mono_thread_set_state (internal, ThreadState_Background);
908 if (handle_store (thread))
909 ResumeThread (thread_handle);
911 return internal;
914 void
915 mono_thread_create (MonoDomain *domain, gpointer func, gpointer arg)
917 mono_thread_create_internal (domain, func, arg, FALSE);
921 * mono_thread_get_stack_bounds:
923 * Return the address and size of the current threads stack. Return NULL as the
924 * stack address if the stack address cannot be determined.
926 void
927 mono_thread_get_stack_bounds (guint8 **staddr, size_t *stsize)
929 #if defined(HAVE_PTHREAD_GET_STACKSIZE_NP) && defined(HAVE_PTHREAD_GET_STACKADDR_NP)
930 *staddr = (guint8*)pthread_get_stackaddr_np (pthread_self ());
931 *stsize = pthread_get_stacksize_np (pthread_self ());
932 *staddr = (guint8*)((gssize)*staddr & ~(mono_pagesize () - 1));
933 return;
934 /* FIXME: simplify the mess below */
935 #elif !defined(HOST_WIN32)
936 pthread_attr_t attr;
937 guint8 *current = (guint8*)&attr;
939 pthread_attr_init (&attr);
940 # ifdef HAVE_PTHREAD_GETATTR_NP
941 pthread_getattr_np (pthread_self(), &attr);
942 # else
943 # ifdef HAVE_PTHREAD_ATTR_GET_NP
944 pthread_attr_get_np (pthread_self(), &attr);
945 # elif defined(sun)
946 *staddr = NULL;
947 pthread_attr_getstacksize (&attr, &stsize);
948 # elif defined(__OpenBSD__)
949 stack_t ss;
950 int rslt;
952 rslt = pthread_stackseg_np(pthread_self(), &ss);
953 g_assert (rslt == 0);
955 *staddr = (guint8*)((size_t)ss.ss_sp - ss.ss_size);
956 *stsize = ss.ss_size;
957 # else
958 *staddr = NULL;
959 *stsize = 0;
960 return;
961 # endif
962 # endif
964 # if !defined(sun)
965 # if !defined(__OpenBSD__)
966 pthread_attr_getstack (&attr, (void**)staddr, stsize);
967 # endif
968 if (*staddr)
969 g_assert ((current > *staddr) && (current < *staddr + *stsize));
970 # endif
972 pthread_attr_destroy (&attr);
973 #endif
975 /* When running under emacs, sometimes staddr is not aligned to a page size */
976 *staddr = (guint8*)((gssize)*staddr & ~(mono_pagesize () - 1));
979 MonoThread *
980 mono_thread_attach (MonoDomain *domain)
982 MonoInternalThread *thread;
983 MonoThread *current_thread;
984 HANDLE thread_handle;
985 gsize tid;
987 if ((thread = mono_thread_internal_current ())) {
988 if (domain != mono_domain_get ())
989 mono_domain_set (domain, TRUE);
990 /* Already attached */
991 return mono_thread_current ();
994 if (!mono_gc_register_thread (&domain)) {
995 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 ());
998 thread = (MonoInternalThread *)mono_object_new (domain, mono_defaults.internal_thread_class);
1000 thread_handle = GetCurrentThread ();
1001 g_assert (thread_handle);
1003 tid=GetCurrentThreadId ();
1006 * The handle returned by GetCurrentThread () is a pseudo handle, so it can't be used to
1007 * refer to the thread from other threads for things like aborting.
1009 DuplicateHandle (GetCurrentProcess (), thread_handle, GetCurrentProcess (), &thread_handle,
1010 THREAD_ALL_ACCESS, TRUE, 0);
1012 thread->handle=thread_handle;
1013 thread->tid=tid;
1014 thread->apartment_state=ThreadApartmentState_Unknown;
1015 small_id_alloc (thread);
1016 thread->stack_ptr = &tid;
1018 thread->synch_cs = g_new0 (CRITICAL_SECTION, 1);
1019 InitializeCriticalSection (thread->synch_cs);
1021 THREAD_DEBUG (g_message ("%s: Attached thread ID %"G_GSIZE_FORMAT" (handle %p)", __func__, tid, thread_handle));
1023 current_thread = new_thread_with_internal (domain, thread);
1025 if (!handle_store (current_thread)) {
1026 /* Mono is shutting down, so just wait for the end */
1027 for (;;)
1028 Sleep (10000);
1031 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Setting current_object_key to %p", __func__, GetCurrentThreadId (), thread));
1033 SET_CURRENT_OBJECT (thread);
1034 mono_domain_set (domain, TRUE);
1036 mono_monitor_init_tls ();
1038 thread_adjust_static_data (thread);
1040 init_root_domain_thread (thread, current_thread);
1041 if (domain != mono_get_root_domain ())
1042 set_current_thread_for_domain (domain, thread, current_thread);
1045 if (mono_thread_attach_cb) {
1046 guint8 *staddr;
1047 size_t stsize;
1049 mono_thread_get_stack_bounds (&staddr, &stsize);
1051 if (staddr == NULL)
1052 mono_thread_attach_cb (tid, &tid);
1053 else
1054 mono_thread_attach_cb (tid, staddr + stsize);
1057 // FIXME: Need a separate callback
1058 mono_profiler_thread_start (tid);
1060 return current_thread;
1063 void
1064 mono_thread_detach (MonoThread *thread)
1066 g_return_if_fail (thread != NULL);
1068 THREAD_DEBUG (g_message ("%s: mono_thread_detach for %p (%"G_GSIZE_FORMAT")", __func__, thread, (gsize)thread->tid));
1070 thread_cleanup (thread->internal_thread);
1072 SET_CURRENT_OBJECT (NULL);
1073 mono_domain_unset ();
1075 /* Don't need to CloseHandle this thread, even though we took a
1076 * reference in mono_thread_attach (), because the GC will do it
1077 * when the Thread object is finalised.
1081 void
1082 mono_thread_exit ()
1084 MonoInternalThread *thread = mono_thread_internal_current ();
1086 THREAD_DEBUG (g_message ("%s: mono_thread_exit for %p (%"G_GSIZE_FORMAT")", __func__, thread, (gsize)thread->tid));
1088 thread_cleanup (thread);
1089 SET_CURRENT_OBJECT (NULL);
1090 mono_domain_unset ();
1092 /* we could add a callback here for embedders to use. */
1093 if (mono_thread_get_main () && (thread == mono_thread_get_main ()->internal_thread))
1094 exit (mono_environment_exitcode_get ());
1095 ExitThread (-1);
1098 void
1099 ves_icall_System_Threading_Thread_ConstructInternalThread (MonoThread *this)
1101 MonoInternalThread *internal = (MonoInternalThread*)mono_object_new (mono_get_root_domain (), mono_defaults.internal_thread_class);
1102 internal->state = ThreadState_Unstarted;
1103 internal->apartment_state = ThreadApartmentState_Unknown;
1105 InterlockedCompareExchangePointer ((gpointer)&this->internal_thread, internal, NULL);
1108 HANDLE ves_icall_System_Threading_Thread_Thread_internal(MonoThread *this,
1109 MonoObject *start)
1111 guint32 (*start_func)(void *);
1112 struct StartInfo *start_info;
1113 HANDLE thread;
1114 gsize tid;
1115 MonoInternalThread *internal;
1117 THREAD_DEBUG (g_message("%s: Trying to start a new thread: this (%p) start (%p)", __func__, this, start));
1119 if (!this->internal_thread)
1120 ves_icall_System_Threading_Thread_ConstructInternalThread (this);
1121 internal = this->internal_thread;
1123 ensure_synch_cs_set (internal);
1125 EnterCriticalSection (internal->synch_cs);
1127 if ((internal->state & ThreadState_Unstarted) == 0) {
1128 LeaveCriticalSection (internal->synch_cs);
1129 mono_raise_exception (mono_get_exception_thread_state ("Thread has already been started."));
1130 return NULL;
1133 internal->small_id = -1;
1135 if ((internal->state & ThreadState_Aborted) != 0) {
1136 LeaveCriticalSection (internal->synch_cs);
1137 return this;
1139 start_func = NULL;
1141 /* This is freed in start_wrapper */
1142 start_info = g_new0 (struct StartInfo, 1);
1143 start_info->func = start_func;
1144 start_info->start_arg = this->start_obj; /* FIXME: GC object stored in unmanaged memory */
1145 start_info->delegate = start;
1146 start_info->obj = this;
1147 g_assert (this->obj.vtable->domain == mono_domain_get ());
1149 internal->start_notify=CreateSemaphore (NULL, 0, 0x7fffffff, NULL);
1150 if (internal->start_notify==NULL) {
1151 LeaveCriticalSection (internal->synch_cs);
1152 g_warning ("%s: CreateSemaphore error 0x%x", __func__, GetLastError ());
1153 g_free (start_info);
1154 return(NULL);
1157 mono_threads_lock ();
1158 register_thread_start_argument (this, start_info);
1159 if (threads_starting_up == NULL) {
1160 MONO_GC_REGISTER_ROOT (threads_starting_up);
1161 threads_starting_up = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_VALUE_GC);
1163 mono_g_hash_table_insert (threads_starting_up, this, this);
1164 mono_threads_unlock ();
1166 thread=mono_create_thread(NULL, default_stacksize_for_thread (internal), (LPTHREAD_START_ROUTINE)start_wrapper, start_info,
1167 CREATE_SUSPENDED, &tid);
1168 if(thread==NULL) {
1169 LeaveCriticalSection (internal->synch_cs);
1170 mono_threads_lock ();
1171 mono_g_hash_table_remove (threads_starting_up, this);
1172 mono_threads_unlock ();
1173 g_warning("%s: CreateThread error 0x%x", __func__, GetLastError());
1174 return(NULL);
1177 internal->handle=thread;
1178 internal->tid=tid;
1179 small_id_alloc (internal);
1181 /* Don't call handle_store() here, delay it to Start.
1182 * We can't join a thread (trying to will just block
1183 * forever) until it actually starts running, so don't
1184 * store the handle till then.
1187 mono_thread_start (this);
1189 internal->state &= ~ThreadState_Unstarted;
1191 THREAD_DEBUG (g_message ("%s: Started thread ID %"G_GSIZE_FORMAT" (handle %p)", __func__, tid, thread));
1193 LeaveCriticalSection (internal->synch_cs);
1194 return(thread);
1198 void ves_icall_System_Threading_InternalThread_Thread_free_internal (MonoInternalThread *this, HANDLE thread)
1200 MONO_ARCH_SAVE_REGS;
1202 THREAD_DEBUG (g_message ("%s: Closing thread %p, handle %p", __func__, this, thread));
1204 if (thread)
1205 CloseHandle (thread);
1207 if (this->synch_cs) {
1208 DeleteCriticalSection (this->synch_cs);
1209 g_free (this->synch_cs);
1210 this->synch_cs = NULL;
1213 g_free (this->name);
1216 static void mono_thread_start (MonoThread *thread)
1218 MonoInternalThread *internal = thread->internal_thread;
1220 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Launching thread %p (%"G_GSIZE_FORMAT")", __func__, GetCurrentThreadId (), thread, (gsize)thread->tid));
1222 /* Only store the handle when the thread is about to be
1223 * launched, to avoid the main thread deadlocking while trying
1224 * to clean up a thread that will never be signalled.
1226 if (!handle_store (thread))
1227 return;
1229 ResumeThread (internal->handle);
1231 if(internal->start_notify!=NULL) {
1232 /* Wait for the thread to set up its TLS data etc, so
1233 * theres no potential race condition if someone tries
1234 * to look up the data believing the thread has
1235 * started
1238 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") waiting for thread %p (%"G_GSIZE_FORMAT") to start", __func__, GetCurrentThreadId (), thread, (gsize)thread->tid));
1240 WaitForSingleObjectEx (internal->start_notify, INFINITE, FALSE);
1241 CloseHandle (internal->start_notify);
1242 internal->start_notify = NULL;
1245 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Done launching thread %p (%"G_GSIZE_FORMAT")", __func__, GetCurrentThreadId (), thread, (gsize)thread->tid));
1248 void ves_icall_System_Threading_Thread_Sleep_internal(gint32 ms)
1250 guint32 res;
1251 MonoInternalThread *thread = mono_thread_internal_current ();
1253 THREAD_DEBUG (g_message ("%s: Sleeping for %d ms", __func__, ms));
1255 mono_thread_current_check_pending_interrupt ();
1257 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1259 res = SleepEx(ms,TRUE);
1261 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1263 if (res == WAIT_IO_COMPLETION) { /* we might have been interrupted */
1264 MonoException* exc = mono_thread_execute_interruption (thread);
1265 if (exc) mono_raise_exception (exc);
1269 void ves_icall_System_Threading_Thread_SpinWait_nop (void)
1273 gint32
1274 ves_icall_System_Threading_Thread_GetDomainID (void)
1276 MONO_ARCH_SAVE_REGS;
1278 return mono_domain_get()->domain_id;
1282 * mono_thread_get_name:
1284 * Return the name of the thread. NAME_LEN is set to the length of the name.
1285 * Return NULL if the thread has no name. The returned memory is owned by the
1286 * caller.
1288 gunichar2*
1289 mono_thread_get_name (MonoInternalThread *this_obj, guint32 *name_len)
1291 gunichar2 *res;
1293 ensure_synch_cs_set (this_obj);
1295 EnterCriticalSection (this_obj->synch_cs);
1297 if (!this_obj->name) {
1298 *name_len = 0;
1299 res = NULL;
1300 } else {
1301 *name_len = this_obj->name_len;
1302 res = g_new (gunichar2, this_obj->name_len);
1303 memcpy (res, this_obj->name, sizeof (gunichar2) * this_obj->name_len);
1306 LeaveCriticalSection (this_obj->synch_cs);
1308 return res;
1311 MonoString*
1312 ves_icall_System_Threading_Thread_GetName_internal (MonoInternalThread *this_obj)
1314 MonoString* str;
1316 ensure_synch_cs_set (this_obj);
1318 EnterCriticalSection (this_obj->synch_cs);
1320 if (!this_obj->name)
1321 str = NULL;
1322 else
1323 str = mono_string_new_utf16 (mono_domain_get (), this_obj->name, this_obj->name_len);
1325 LeaveCriticalSection (this_obj->synch_cs);
1327 return str;
1330 void
1331 ves_icall_System_Threading_Thread_SetName_internal (MonoInternalThread *this_obj, MonoString *name)
1333 ensure_synch_cs_set (this_obj);
1335 EnterCriticalSection (this_obj->synch_cs);
1337 if (this_obj->name) {
1338 LeaveCriticalSection (this_obj->synch_cs);
1340 mono_raise_exception (mono_get_exception_invalid_operation ("Thread.Name can only be set once."));
1341 return;
1343 if (name) {
1344 this_obj->name = g_new (gunichar2, mono_string_length (name));
1345 memcpy (this_obj->name, mono_string_chars (name), mono_string_length (name) * 2);
1346 this_obj->name_len = mono_string_length (name);
1348 else
1349 this_obj->name = NULL;
1351 LeaveCriticalSection (this_obj->synch_cs);
1354 static MonoObject*
1355 lookup_cached_culture (MonoInternalThread *this, MonoDomain *domain, int start_idx)
1357 MonoObject *res;
1358 int i;
1360 if (this->cached_culture_info) {
1361 domain = mono_domain_get ();
1362 for (i = start_idx; i < start_idx + NUM_CACHED_CULTURES; ++i) {
1363 res = mono_array_get (this->cached_culture_info, MonoObject*, i);
1364 if (res && res->vtable->domain == domain)
1365 return res;
1369 return NULL;
1372 /* If the array is already in the requested domain, we just return it,
1373 otherwise we return a copy in that domain. */
1374 static MonoArray*
1375 byte_array_to_domain (MonoArray *arr, MonoDomain *domain)
1377 MonoArray *copy;
1379 if (!arr)
1380 return NULL;
1382 if (mono_object_domain (arr) == domain)
1383 return arr;
1385 copy = mono_array_new (domain, mono_defaults.byte_class, arr->max_length);
1386 memcpy (mono_array_addr (copy, guint8, 0), mono_array_addr (arr, guint8, 0), arr->max_length);
1387 return copy;
1390 MonoArray*
1391 ves_icall_System_Threading_Thread_ByteArrayToRootDomain (MonoArray *arr)
1393 return byte_array_to_domain (arr, mono_get_root_domain ());
1396 MonoArray*
1397 ves_icall_System_Threading_Thread_ByteArrayToCurrentDomain (MonoArray *arr)
1399 return byte_array_to_domain (arr, mono_domain_get ());
1402 MonoObject*
1403 ves_icall_System_Threading_Thread_GetCachedCurrentCulture (MonoInternalThread *this)
1405 return lookup_cached_culture (this, mono_domain_get (), CULTURES_START_IDX);
1408 static void
1409 cache_culture (MonoInternalThread *this, MonoObject *culture, int start_idx)
1411 int i;
1412 MonoDomain *domain = mono_domain_get ();
1413 MonoObject *obj;
1414 int free_slot = -1;
1415 int same_domain_slot = -1;
1417 ensure_synch_cs_set (this);
1419 EnterCriticalSection (this->synch_cs);
1421 if (!this->cached_culture_info)
1422 MONO_OBJECT_SETREF (this, cached_culture_info, mono_array_new_cached (mono_get_root_domain (), mono_defaults.object_class, NUM_CACHED_CULTURES * 2));
1424 for (i = start_idx; i < start_idx + NUM_CACHED_CULTURES; ++i) {
1425 obj = mono_array_get (this->cached_culture_info, MonoObject*, i);
1426 /* Free entry */
1427 if (!obj) {
1428 free_slot = i;
1429 /* we continue, because there may be a slot used with the same domain */
1430 continue;
1432 /* Replace */
1433 if (obj->vtable->domain == domain) {
1434 same_domain_slot = i;
1435 break;
1438 if (same_domain_slot >= 0)
1439 mono_array_setref (this->cached_culture_info, same_domain_slot, culture);
1440 else if (free_slot >= 0)
1441 mono_array_setref (this->cached_culture_info, free_slot, culture);
1442 /* we may want to replace an existing entry here, even when no suitable slot is found */
1444 LeaveCriticalSection (this->synch_cs);
1447 void
1448 ves_icall_System_Threading_Thread_SetCachedCurrentCulture (MonoThread *this, MonoObject *culture)
1450 MonoDomain *domain = mono_object_get_domain (&this->obj);
1451 g_assert (domain == mono_domain_get ());
1452 cache_culture (this->internal_thread, culture, CULTURES_START_IDX);
1455 MonoObject*
1456 ves_icall_System_Threading_Thread_GetCachedCurrentUICulture (MonoInternalThread *this)
1458 return lookup_cached_culture (this, mono_domain_get (), UICULTURES_START_IDX);
1461 void
1462 ves_icall_System_Threading_Thread_SetCachedCurrentUICulture (MonoThread *this, MonoObject *culture)
1464 MonoDomain *domain = mono_object_get_domain (&this->obj);
1465 g_assert (domain == mono_domain_get ());
1466 cache_culture (this->internal_thread, culture, UICULTURES_START_IDX);
1469 MonoThread *
1470 mono_thread_current (void)
1472 MonoDomain *domain = mono_domain_get ();
1473 MonoInternalThread *internal = mono_thread_internal_current ();
1474 MonoThread **current_thread_ptr;
1476 g_assert (internal);
1477 current_thread_ptr = get_current_thread_ptr_for_domain (domain, internal);
1479 if (!*current_thread_ptr) {
1480 g_assert (domain != mono_get_root_domain ());
1481 *current_thread_ptr = new_thread_with_internal (domain, internal);
1483 return *current_thread_ptr;
1486 MonoInternalThread*
1487 mono_thread_internal_current (void)
1489 MonoInternalThread *res = GET_CURRENT_OBJECT ();
1490 THREAD_DEBUG (g_message ("%s: returning %p", __func__, res));
1491 return res;
1494 gboolean ves_icall_System_Threading_Thread_Join_internal(MonoInternalThread *this,
1495 int ms, HANDLE thread)
1497 MonoInternalThread *cur_thread = mono_thread_internal_current ();
1498 gboolean ret;
1500 mono_thread_current_check_pending_interrupt ();
1502 ensure_synch_cs_set (this);
1504 EnterCriticalSection (this->synch_cs);
1506 if ((this->state & ThreadState_Unstarted) != 0) {
1507 LeaveCriticalSection (this->synch_cs);
1509 mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started."));
1510 return FALSE;
1513 LeaveCriticalSection (this->synch_cs);
1515 if(ms== -1) {
1516 ms=INFINITE;
1518 THREAD_DEBUG (g_message ("%s: joining thread handle %p, %d ms", __func__, thread, ms));
1520 mono_thread_set_state (cur_thread, ThreadState_WaitSleepJoin);
1522 ret=WaitForSingleObjectEx (thread, ms, TRUE);
1524 mono_thread_clr_state (cur_thread, ThreadState_WaitSleepJoin);
1526 if(ret==WAIT_OBJECT_0) {
1527 THREAD_DEBUG (g_message ("%s: join successful", __func__));
1529 return(TRUE);
1532 THREAD_DEBUG (g_message ("%s: join failed", __func__));
1534 return(FALSE);
1537 /* FIXME: exitContext isnt documented */
1538 gboolean ves_icall_System_Threading_WaitHandle_WaitAll_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext)
1540 HANDLE *handles;
1541 guint32 numhandles;
1542 guint32 ret;
1543 guint32 i;
1544 MonoObject *waitHandle;
1545 MonoInternalThread *thread = mono_thread_internal_current ();
1547 /* Do this WaitSleepJoin check before creating objects */
1548 mono_thread_current_check_pending_interrupt ();
1550 numhandles = mono_array_length(mono_handles);
1551 handles = g_new0(HANDLE, numhandles);
1553 for(i = 0; i < numhandles; i++) {
1554 waitHandle = mono_array_get(mono_handles, MonoObject*, i);
1555 handles [i] = mono_wait_handle_get_handle ((MonoWaitHandle *) waitHandle);
1558 if(ms== -1) {
1559 ms=INFINITE;
1562 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1564 ret=WaitForMultipleObjectsEx(numhandles, handles, TRUE, ms, TRUE);
1566 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1568 g_free(handles);
1570 if(ret==WAIT_FAILED) {
1571 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait failed", __func__, GetCurrentThreadId ()));
1572 return(FALSE);
1573 } else if(ret==WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION) {
1574 /* Do we want to try again if we get
1575 * WAIT_IO_COMPLETION? The documentation for
1576 * WaitHandle doesn't give any clues. (We'd have to
1577 * fiddle with the timeout if we retry.)
1579 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait timed out", __func__, GetCurrentThreadId ()));
1580 return(FALSE);
1583 return(TRUE);
1586 /* FIXME: exitContext isnt documented */
1587 gint32 ves_icall_System_Threading_WaitHandle_WaitAny_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext)
1589 HANDLE *handles;
1590 guint32 numhandles;
1591 guint32 ret;
1592 guint32 i;
1593 MonoObject *waitHandle;
1594 MonoInternalThread *thread = mono_thread_internal_current ();
1596 /* Do this WaitSleepJoin check before creating objects */
1597 mono_thread_current_check_pending_interrupt ();
1599 numhandles = mono_array_length(mono_handles);
1600 handles = g_new0(HANDLE, numhandles);
1602 for(i = 0; i < numhandles; i++) {
1603 waitHandle = mono_array_get(mono_handles, MonoObject*, i);
1604 handles [i] = mono_wait_handle_get_handle ((MonoWaitHandle *) waitHandle);
1607 if(ms== -1) {
1608 ms=INFINITE;
1611 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1613 ret=WaitForMultipleObjectsEx(numhandles, handles, FALSE, ms, TRUE);
1615 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1617 g_free(handles);
1619 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") returning %d", __func__, GetCurrentThreadId (), ret));
1622 * These need to be here. See MSDN dos on WaitForMultipleObjects.
1624 if (ret >= WAIT_OBJECT_0 && ret <= WAIT_OBJECT_0 + numhandles - 1) {
1625 return ret - WAIT_OBJECT_0;
1627 else if (ret >= WAIT_ABANDONED_0 && ret <= WAIT_ABANDONED_0 + numhandles - 1) {
1628 return ret - WAIT_ABANDONED_0;
1630 else {
1631 return ret;
1635 /* FIXME: exitContext isnt documented */
1636 gboolean ves_icall_System_Threading_WaitHandle_WaitOne_internal(MonoObject *this, HANDLE handle, gint32 ms, gboolean exitContext)
1638 guint32 ret;
1639 MonoInternalThread *thread = mono_thread_internal_current ();
1641 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") waiting for %p, %d ms", __func__, GetCurrentThreadId (), handle, ms));
1643 if(ms== -1) {
1644 ms=INFINITE;
1647 mono_thread_current_check_pending_interrupt ();
1649 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1651 ret=WaitForSingleObjectEx (handle, ms, TRUE);
1653 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1655 if(ret==WAIT_FAILED) {
1656 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait failed", __func__, GetCurrentThreadId ()));
1657 return(FALSE);
1658 } else if(ret==WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION) {
1659 /* Do we want to try again if we get
1660 * WAIT_IO_COMPLETION? The documentation for
1661 * WaitHandle doesn't give any clues. (We'd have to
1662 * fiddle with the timeout if we retry.)
1664 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait timed out", __func__, GetCurrentThreadId ()));
1665 return(FALSE);
1668 return(TRUE);
1671 gboolean
1672 ves_icall_System_Threading_WaitHandle_SignalAndWait_Internal (HANDLE toSignal, HANDLE toWait, gint32 ms, gboolean exitContext)
1674 guint32 ret;
1675 MonoInternalThread *thread = mono_thread_internal_current ();
1677 MONO_ARCH_SAVE_REGS;
1679 if (ms == -1)
1680 ms = INFINITE;
1682 mono_thread_current_check_pending_interrupt ();
1684 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1686 ret = SignalObjectAndWait (toSignal, toWait, ms, TRUE);
1688 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1690 return (!(ret == WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION || ret == WAIT_FAILED));
1693 HANDLE ves_icall_System_Threading_Mutex_CreateMutex_internal (MonoBoolean owned, MonoString *name, MonoBoolean *created)
1695 HANDLE mutex;
1697 MONO_ARCH_SAVE_REGS;
1699 *created = TRUE;
1701 if (name == NULL) {
1702 mutex = CreateMutex (NULL, owned, NULL);
1703 } else {
1704 mutex = CreateMutex (NULL, owned, mono_string_chars (name));
1706 if (GetLastError () == ERROR_ALREADY_EXISTS) {
1707 *created = FALSE;
1711 return(mutex);
1714 MonoBoolean ves_icall_System_Threading_Mutex_ReleaseMutex_internal (HANDLE handle ) {
1715 MONO_ARCH_SAVE_REGS;
1717 return(ReleaseMutex (handle));
1720 HANDLE ves_icall_System_Threading_Mutex_OpenMutex_internal (MonoString *name,
1721 gint32 rights,
1722 gint32 *error)
1724 HANDLE ret;
1726 MONO_ARCH_SAVE_REGS;
1728 *error = ERROR_SUCCESS;
1730 ret = OpenMutex (rights, FALSE, mono_string_chars (name));
1731 if (ret == NULL) {
1732 *error = GetLastError ();
1735 return(ret);
1739 HANDLE ves_icall_System_Threading_Semaphore_CreateSemaphore_internal (gint32 initialCount, gint32 maximumCount, MonoString *name, MonoBoolean *created)
1741 HANDLE sem;
1743 MONO_ARCH_SAVE_REGS;
1745 *created = TRUE;
1747 if (name == NULL) {
1748 sem = CreateSemaphore (NULL, initialCount, maximumCount, NULL);
1749 } else {
1750 sem = CreateSemaphore (NULL, initialCount, maximumCount,
1751 mono_string_chars (name));
1753 if (GetLastError () == ERROR_ALREADY_EXISTS) {
1754 *created = FALSE;
1758 return(sem);
1761 gint32 ves_icall_System_Threading_Semaphore_ReleaseSemaphore_internal (HANDLE handle, gint32 releaseCount, MonoBoolean *fail)
1763 gint32 prevcount;
1765 MONO_ARCH_SAVE_REGS;
1767 *fail = !ReleaseSemaphore (handle, releaseCount, &prevcount);
1769 return (prevcount);
1772 HANDLE ves_icall_System_Threading_Semaphore_OpenSemaphore_internal (MonoString *name, gint32 rights, gint32 *error)
1774 HANDLE ret;
1776 MONO_ARCH_SAVE_REGS;
1778 *error = ERROR_SUCCESS;
1780 ret = OpenSemaphore (rights, FALSE, mono_string_chars (name));
1781 if (ret == NULL) {
1782 *error = GetLastError ();
1785 return(ret);
1788 HANDLE ves_icall_System_Threading_Events_CreateEvent_internal (MonoBoolean manual, MonoBoolean initial, MonoString *name, MonoBoolean *created)
1790 HANDLE event;
1792 MONO_ARCH_SAVE_REGS;
1794 *created = TRUE;
1796 if (name == NULL) {
1797 event = CreateEvent (NULL, manual, initial, NULL);
1798 } else {
1799 event = CreateEvent (NULL, manual, initial,
1800 mono_string_chars (name));
1802 if (GetLastError () == ERROR_ALREADY_EXISTS) {
1803 *created = FALSE;
1807 return(event);
1810 gboolean ves_icall_System_Threading_Events_SetEvent_internal (HANDLE handle) {
1811 MONO_ARCH_SAVE_REGS;
1813 return (SetEvent(handle));
1816 gboolean ves_icall_System_Threading_Events_ResetEvent_internal (HANDLE handle) {
1817 MONO_ARCH_SAVE_REGS;
1819 return (ResetEvent(handle));
1822 void
1823 ves_icall_System_Threading_Events_CloseEvent_internal (HANDLE handle) {
1824 MONO_ARCH_SAVE_REGS;
1826 CloseHandle (handle);
1829 HANDLE ves_icall_System_Threading_Events_OpenEvent_internal (MonoString *name,
1830 gint32 rights,
1831 gint32 *error)
1833 HANDLE ret;
1835 MONO_ARCH_SAVE_REGS;
1837 *error = ERROR_SUCCESS;
1839 ret = OpenEvent (rights, FALSE, mono_string_chars (name));
1840 if (ret == NULL) {
1841 *error = GetLastError ();
1844 return(ret);
1847 gint32 ves_icall_System_Threading_Interlocked_Increment_Int (gint32 *location)
1849 MONO_ARCH_SAVE_REGS;
1851 return InterlockedIncrement (location);
1854 gint64 ves_icall_System_Threading_Interlocked_Increment_Long (gint64 *location)
1856 gint64 ret;
1858 MONO_ARCH_SAVE_REGS;
1860 mono_interlocked_lock ();
1862 ret = ++ *location;
1864 mono_interlocked_unlock ();
1867 return ret;
1870 gint32 ves_icall_System_Threading_Interlocked_Decrement_Int (gint32 *location)
1872 MONO_ARCH_SAVE_REGS;
1874 return InterlockedDecrement(location);
1877 gint64 ves_icall_System_Threading_Interlocked_Decrement_Long (gint64 * location)
1879 gint64 ret;
1881 MONO_ARCH_SAVE_REGS;
1883 mono_interlocked_lock ();
1885 ret = -- *location;
1887 mono_interlocked_unlock ();
1889 return ret;
1892 gint32 ves_icall_System_Threading_Interlocked_Exchange_Int (gint32 *location, gint32 value)
1894 MONO_ARCH_SAVE_REGS;
1896 return InterlockedExchange(location, value);
1899 MonoObject * ves_icall_System_Threading_Interlocked_Exchange_Object (MonoObject **location, MonoObject *value)
1901 MonoObject *res;
1902 res = (MonoObject *) InterlockedExchangePointer((gpointer *) location, value);
1903 mono_gc_wbarrier_generic_nostore (location);
1904 return res;
1907 gpointer ves_icall_System_Threading_Interlocked_Exchange_IntPtr (gpointer *location, gpointer value)
1909 return InterlockedExchangePointer(location, value);
1912 gfloat ves_icall_System_Threading_Interlocked_Exchange_Single (gfloat *location, gfloat value)
1914 IntFloatUnion val, ret;
1916 MONO_ARCH_SAVE_REGS;
1918 val.fval = value;
1919 ret.ival = InterlockedExchange((gint32 *) location, val.ival);
1921 return ret.fval;
1924 gint64
1925 ves_icall_System_Threading_Interlocked_Exchange_Long (gint64 *location, gint64 value)
1927 #if SIZEOF_VOID_P == 8
1928 return (gint64) InterlockedExchangePointer((gpointer *) location, (gpointer)value);
1929 #else
1930 gint64 res;
1933 * According to MSDN, this function is only atomic with regards to the
1934 * other Interlocked functions on 32 bit platforms.
1936 mono_interlocked_lock ();
1937 res = *location;
1938 *location = value;
1939 mono_interlocked_unlock ();
1941 return res;
1942 #endif
1945 gdouble
1946 ves_icall_System_Threading_Interlocked_Exchange_Double (gdouble *location, gdouble value)
1948 #if SIZEOF_VOID_P == 8
1949 LongDoubleUnion val, ret;
1951 val.fval = value;
1952 ret.ival = (gint64)InterlockedExchangePointer((gpointer *) location, (gpointer)val.ival);
1954 return ret.fval;
1955 #else
1956 gdouble res;
1959 * According to MSDN, this function is only atomic with regards to the
1960 * other Interlocked functions on 32 bit platforms.
1962 mono_interlocked_lock ();
1963 res = *location;
1964 *location = value;
1965 mono_interlocked_unlock ();
1967 return res;
1968 #endif
1971 gint32 ves_icall_System_Threading_Interlocked_CompareExchange_Int(gint32 *location, gint32 value, gint32 comparand)
1973 MONO_ARCH_SAVE_REGS;
1975 return InterlockedCompareExchange(location, value, comparand);
1978 MonoObject * ves_icall_System_Threading_Interlocked_CompareExchange_Object (MonoObject **location, MonoObject *value, MonoObject *comparand)
1980 MonoObject *res;
1981 res = (MonoObject *) InterlockedCompareExchangePointer((gpointer *) location, value, comparand);
1982 mono_gc_wbarrier_generic_nostore (location);
1983 return res;
1986 gpointer ves_icall_System_Threading_Interlocked_CompareExchange_IntPtr(gpointer *location, gpointer value, gpointer comparand)
1988 return InterlockedCompareExchangePointer(location, value, comparand);
1991 gfloat ves_icall_System_Threading_Interlocked_CompareExchange_Single (gfloat *location, gfloat value, gfloat comparand)
1993 IntFloatUnion val, ret, cmp;
1995 MONO_ARCH_SAVE_REGS;
1997 val.fval = value;
1998 cmp.fval = comparand;
1999 ret.ival = InterlockedCompareExchange((gint32 *) location, val.ival, cmp.ival);
2001 return ret.fval;
2004 gdouble
2005 ves_icall_System_Threading_Interlocked_CompareExchange_Double (gdouble *location, gdouble value, gdouble comparand)
2007 #if SIZEOF_VOID_P == 8
2008 LongDoubleUnion val, comp, ret;
2010 val.fval = value;
2011 comp.fval = comparand;
2012 ret.ival = (gint64)InterlockedCompareExchangePointer((gpointer *) location, (gpointer)val.ival, (gpointer)comp.ival);
2014 return ret.fval;
2015 #else
2016 gdouble old;
2018 mono_interlocked_lock ();
2019 old = *location;
2020 if (old == comparand)
2021 *location = value;
2022 mono_interlocked_unlock ();
2024 return old;
2025 #endif
2028 gint64
2029 ves_icall_System_Threading_Interlocked_CompareExchange_Long (gint64 *location, gint64 value, gint64 comparand)
2031 #if SIZEOF_VOID_P == 8
2032 return (gint64)InterlockedCompareExchangePointer((gpointer *) location, (gpointer)value, (gpointer)comparand);
2033 #else
2034 gint64 old;
2036 mono_interlocked_lock ();
2037 old = *location;
2038 if (old == comparand)
2039 *location = value;
2040 mono_interlocked_unlock ();
2042 return old;
2043 #endif
2046 MonoObject*
2047 ves_icall_System_Threading_Interlocked_CompareExchange_T (MonoObject **location, MonoObject *value, MonoObject *comparand)
2049 MonoObject *res;
2050 res = InterlockedCompareExchangePointer ((gpointer *)location, value, comparand);
2051 mono_gc_wbarrier_generic_nostore (location);
2052 return res;
2055 MonoObject*
2056 ves_icall_System_Threading_Interlocked_Exchange_T (MonoObject **location, MonoObject *value)
2058 MonoObject *res;
2059 res = InterlockedExchangePointer ((gpointer *)location, value);
2060 mono_gc_wbarrier_generic_nostore (location);
2061 return res;
2064 gint32
2065 ves_icall_System_Threading_Interlocked_Add_Int (gint32 *location, gint32 value)
2067 #if SIZEOF_VOID_P == 8
2068 /* Should be implemented as a JIT intrinsic */
2069 mono_raise_exception (mono_get_exception_not_implemented (NULL));
2070 return 0;
2071 #else
2072 gint32 orig;
2074 mono_interlocked_lock ();
2075 orig = *location;
2076 *location = orig + value;
2077 mono_interlocked_unlock ();
2079 return orig + value;
2080 #endif
2083 gint64
2084 ves_icall_System_Threading_Interlocked_Add_Long (gint64 *location, gint64 value)
2086 #if SIZEOF_VOID_P == 8
2087 /* Should be implemented as a JIT intrinsic */
2088 mono_raise_exception (mono_get_exception_not_implemented (NULL));
2089 return 0;
2090 #else
2091 gint64 orig;
2093 mono_interlocked_lock ();
2094 orig = *location;
2095 *location = orig + value;
2096 mono_interlocked_unlock ();
2098 return orig + value;
2099 #endif
2102 gint64
2103 ves_icall_System_Threading_Interlocked_Read_Long (gint64 *location)
2105 #if SIZEOF_VOID_P == 8
2106 /* 64 bit reads are already atomic */
2107 return *location;
2108 #else
2109 gint64 res;
2111 mono_interlocked_lock ();
2112 res = *location;
2113 mono_interlocked_unlock ();
2115 return res;
2116 #endif
2119 void
2120 ves_icall_System_Threading_Thread_MemoryBarrier (void)
2122 mono_threads_lock ();
2123 mono_threads_unlock ();
2126 void
2127 ves_icall_System_Threading_Thread_ClrState (MonoInternalThread* this, guint32 state)
2129 mono_thread_clr_state (this, state);
2131 if (state & ThreadState_Background) {
2132 /* If the thread changes the background mode, the main thread has to
2133 * be notified, since it has to rebuild the list of threads to
2134 * wait for.
2136 SetEvent (background_change_event);
2140 void
2141 ves_icall_System_Threading_Thread_SetState (MonoInternalThread* this, guint32 state)
2143 mono_thread_set_state (this, state);
2145 if (state & ThreadState_Background) {
2146 /* If the thread changes the background mode, the main thread has to
2147 * be notified, since it has to rebuild the list of threads to
2148 * wait for.
2150 SetEvent (background_change_event);
2154 guint32
2155 ves_icall_System_Threading_Thread_GetState (MonoInternalThread* this)
2157 guint32 state;
2159 ensure_synch_cs_set (this);
2161 EnterCriticalSection (this->synch_cs);
2163 state = this->state;
2165 LeaveCriticalSection (this->synch_cs);
2167 return state;
2170 void ves_icall_System_Threading_Thread_Interrupt_internal (MonoInternalThread *this)
2172 gboolean throw = FALSE;
2174 ensure_synch_cs_set (this);
2176 if (this == mono_thread_internal_current ())
2177 return;
2179 EnterCriticalSection (this->synch_cs);
2181 this->thread_interrupt_requested = TRUE;
2183 if (this->state & ThreadState_WaitSleepJoin) {
2184 throw = TRUE;
2187 LeaveCriticalSection (this->synch_cs);
2189 if (throw) {
2190 signal_thread_state_change (this);
2194 void mono_thread_current_check_pending_interrupt ()
2196 MonoInternalThread *thread = mono_thread_internal_current ();
2197 gboolean throw = FALSE;
2199 mono_debugger_check_interruption ();
2201 ensure_synch_cs_set (thread);
2203 EnterCriticalSection (thread->synch_cs);
2205 if (thread->thread_interrupt_requested) {
2206 throw = TRUE;
2207 thread->thread_interrupt_requested = FALSE;
2210 LeaveCriticalSection (thread->synch_cs);
2212 if (throw) {
2213 mono_raise_exception (mono_get_exception_thread_interrupted ());
2217 int
2218 mono_thread_get_abort_signal (void)
2220 #ifdef HOST_WIN32
2221 return -1;
2222 #else
2223 #ifndef SIGRTMIN
2224 #ifdef SIGUSR1
2225 return SIGUSR1;
2226 #else
2227 return -1;
2228 #endif
2229 #else
2230 static int abort_signum = -1;
2231 int i;
2232 if (abort_signum != -1)
2233 return abort_signum;
2234 /* we try to avoid SIGRTMIN and any one that might have been set already, see bug #75387 */
2235 for (i = SIGRTMIN + 1; i < SIGRTMAX; ++i) {
2236 struct sigaction sinfo;
2237 sigaction (i, NULL, &sinfo);
2238 if (sinfo.sa_handler == SIG_DFL && (void*)sinfo.sa_sigaction == (void*)SIG_DFL) {
2239 abort_signum = i;
2240 return i;
2243 /* fallback to the old way */
2244 return SIGRTMIN;
2245 #endif
2246 #endif /* HOST_WIN32 */
2249 #ifdef HOST_WIN32
2250 static void CALLBACK interruption_request_apc (ULONG_PTR param)
2252 MonoException* exc = mono_thread_request_interruption (FALSE);
2253 if (exc) mono_raise_exception (exc);
2255 #endif /* HOST_WIN32 */
2258 * signal_thread_state_change
2260 * Tells the thread that his state has changed and it has to enter the new
2261 * state as soon as possible.
2263 static void signal_thread_state_change (MonoInternalThread *thread)
2265 if (thread == mono_thread_internal_current ()) {
2266 /* Do it synchronously */
2267 MonoException *exc = mono_thread_request_interruption (FALSE);
2268 if (exc)
2269 mono_raise_exception (exc);
2272 #ifdef HOST_WIN32
2273 QueueUserAPC ((PAPCFUNC)interruption_request_apc, thread->handle, NULL);
2274 #else
2275 /* fixme: store the state somewhere */
2276 #ifdef PTHREAD_POINTER_ID
2277 pthread_kill ((gpointer)(gsize)(thread->tid), mono_thread_get_abort_signal ());
2278 #else
2279 pthread_kill (thread->tid, mono_thread_get_abort_signal ());
2280 #endif
2283 * This will cause waits to be broken.
2284 * It will also prevent the thread from entering a wait, so if the thread returns
2285 * from the wait before it receives the abort signal, it will just spin in the wait
2286 * functions in the io-layer until the signal handler calls QueueUserAPC which will
2287 * make it return.
2289 wapi_interrupt_thread (thread->handle);
2290 #endif /* HOST_WIN32 */
2293 void
2294 ves_icall_System_Threading_Thread_Abort (MonoInternalThread *thread, MonoObject *state)
2296 ensure_synch_cs_set (thread);
2298 EnterCriticalSection (thread->synch_cs);
2300 if ((thread->state & ThreadState_AbortRequested) != 0 ||
2301 (thread->state & ThreadState_StopRequested) != 0 ||
2302 (thread->state & ThreadState_Stopped) != 0)
2304 LeaveCriticalSection (thread->synch_cs);
2305 return;
2308 if ((thread->state & ThreadState_Unstarted) != 0) {
2309 thread->state |= ThreadState_Aborted;
2310 LeaveCriticalSection (thread->synch_cs);
2311 return;
2314 thread->state |= ThreadState_AbortRequested;
2315 if (thread->abort_state_handle)
2316 mono_gchandle_free (thread->abort_state_handle);
2317 if (state) {
2318 thread->abort_state_handle = mono_gchandle_new (state, FALSE);
2319 g_assert (thread->abort_state_handle);
2320 } else {
2321 thread->abort_state_handle = 0;
2323 thread->abort_exc = NULL;
2326 * abort_exc is set in mono_thread_execute_interruption(),
2327 * triggered by the call to signal_thread_state_change(),
2328 * below. There's a point between where we have
2329 * abort_state_handle set, but abort_exc NULL, but that's not
2330 * a problem.
2333 LeaveCriticalSection (thread->synch_cs);
2335 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Abort requested for %p (%"G_GSIZE_FORMAT")", __func__, GetCurrentThreadId (), thread, (gsize)thread->tid));
2337 /* During shutdown, we can't wait for other threads */
2338 if (!shutting_down)
2339 /* Make sure the thread is awake */
2340 mono_thread_resume (thread);
2342 signal_thread_state_change (thread);
2345 void
2346 ves_icall_System_Threading_Thread_ResetAbort (void)
2348 MonoInternalThread *thread = mono_thread_internal_current ();
2349 gboolean was_aborting;
2351 ensure_synch_cs_set (thread);
2353 EnterCriticalSection (thread->synch_cs);
2354 was_aborting = thread->state & ThreadState_AbortRequested;
2355 thread->state &= ~ThreadState_AbortRequested;
2356 LeaveCriticalSection (thread->synch_cs);
2358 if (!was_aborting) {
2359 const char *msg = "Unable to reset abort because no abort was requested";
2360 mono_raise_exception (mono_get_exception_thread_state (msg));
2362 thread->abort_exc = NULL;
2363 if (thread->abort_state_handle) {
2364 mono_gchandle_free (thread->abort_state_handle);
2365 /* This is actually not necessary - the handle
2366 only counts if the exception is set */
2367 thread->abort_state_handle = 0;
2371 void
2372 mono_thread_internal_reset_abort (MonoInternalThread *thread)
2374 ensure_synch_cs_set (thread);
2376 EnterCriticalSection (thread->synch_cs);
2378 thread->state &= ~ThreadState_AbortRequested;
2380 if (thread->abort_exc) {
2381 thread->abort_exc = NULL;
2382 if (thread->abort_state_handle) {
2383 mono_gchandle_free (thread->abort_state_handle);
2384 /* This is actually not necessary - the handle
2385 only counts if the exception is set */
2386 thread->abort_state_handle = 0;
2390 LeaveCriticalSection (thread->synch_cs);
2393 MonoObject*
2394 ves_icall_System_Threading_Thread_GetAbortExceptionState (MonoThread *this)
2396 MonoInternalThread *thread = this->internal_thread;
2397 MonoObject *state, *deserialized = NULL, *exc;
2398 MonoDomain *domain;
2400 if (!thread->abort_state_handle)
2401 return NULL;
2403 state = mono_gchandle_get_target (thread->abort_state_handle);
2404 g_assert (state);
2406 domain = mono_domain_get ();
2407 if (mono_object_domain (state) == domain)
2408 return state;
2410 deserialized = mono_object_xdomain_representation (state, domain, &exc);
2412 if (!deserialized) {
2413 MonoException *invalid_op_exc = mono_get_exception_invalid_operation ("Thread.ExceptionState cannot access an ExceptionState from a different AppDomain");
2414 if (exc)
2415 MONO_OBJECT_SETREF (invalid_op_exc, inner_ex, exc);
2416 mono_raise_exception (invalid_op_exc);
2419 return deserialized;
2422 static gboolean
2423 mono_thread_suspend (MonoInternalThread *thread)
2425 ensure_synch_cs_set (thread);
2427 EnterCriticalSection (thread->synch_cs);
2429 if ((thread->state & ThreadState_Unstarted) != 0 ||
2430 (thread->state & ThreadState_Aborted) != 0 ||
2431 (thread->state & ThreadState_Stopped) != 0)
2433 LeaveCriticalSection (thread->synch_cs);
2434 return FALSE;
2437 if ((thread->state & ThreadState_Suspended) != 0 ||
2438 (thread->state & ThreadState_SuspendRequested) != 0 ||
2439 (thread->state & ThreadState_StopRequested) != 0)
2441 LeaveCriticalSection (thread->synch_cs);
2442 return TRUE;
2445 thread->state |= ThreadState_SuspendRequested;
2447 LeaveCriticalSection (thread->synch_cs);
2449 signal_thread_state_change (thread);
2450 return TRUE;
2453 void
2454 ves_icall_System_Threading_Thread_Suspend (MonoInternalThread *thread)
2456 if (!mono_thread_suspend (thread))
2457 mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started, or is dead."));
2460 static gboolean
2461 mono_thread_resume (MonoInternalThread *thread)
2463 ensure_synch_cs_set (thread);
2465 EnterCriticalSection (thread->synch_cs);
2467 if ((thread->state & ThreadState_SuspendRequested) != 0) {
2468 thread->state &= ~ThreadState_SuspendRequested;
2469 LeaveCriticalSection (thread->synch_cs);
2470 return TRUE;
2473 if ((thread->state & ThreadState_Suspended) == 0 ||
2474 (thread->state & ThreadState_Unstarted) != 0 ||
2475 (thread->state & ThreadState_Aborted) != 0 ||
2476 (thread->state & ThreadState_Stopped) != 0)
2478 LeaveCriticalSection (thread->synch_cs);
2479 return FALSE;
2482 thread->resume_event = CreateEvent (NULL, TRUE, FALSE, NULL);
2483 if (thread->resume_event == NULL) {
2484 LeaveCriticalSection (thread->synch_cs);
2485 return(FALSE);
2488 /* Awake the thread */
2489 SetEvent (thread->suspend_event);
2491 LeaveCriticalSection (thread->synch_cs);
2493 /* Wait for the thread to awake */
2494 WaitForSingleObject (thread->resume_event, INFINITE);
2495 CloseHandle (thread->resume_event);
2496 thread->resume_event = NULL;
2498 return TRUE;
2501 void
2502 ves_icall_System_Threading_Thread_Resume (MonoThread *thread)
2504 if (!thread->internal_thread || !mono_thread_resume (thread->internal_thread))
2505 mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started, or is dead."));
2508 static gboolean
2509 find_wrapper (MonoMethod *m, gint no, gint ilo, gboolean managed, gpointer data)
2511 if (managed)
2512 return TRUE;
2514 if (m->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE ||
2515 m->wrapper_type == MONO_WRAPPER_XDOMAIN_INVOKE ||
2516 m->wrapper_type == MONO_WRAPPER_XDOMAIN_DISPATCH)
2518 *((gboolean*)data) = TRUE;
2519 return TRUE;
2521 return FALSE;
2524 static gboolean
2525 is_running_protected_wrapper (void)
2527 gboolean found = FALSE;
2528 mono_stack_walk (find_wrapper, &found);
2529 return found;
2532 void mono_thread_internal_stop (MonoInternalThread *thread)
2534 ensure_synch_cs_set (thread);
2536 EnterCriticalSection (thread->synch_cs);
2538 if ((thread->state & ThreadState_StopRequested) != 0 ||
2539 (thread->state & ThreadState_Stopped) != 0)
2541 LeaveCriticalSection (thread->synch_cs);
2542 return;
2545 /* Make sure the thread is awake */
2546 mono_thread_resume (thread);
2548 thread->state |= ThreadState_StopRequested;
2549 thread->state &= ~ThreadState_AbortRequested;
2551 LeaveCriticalSection (thread->synch_cs);
2553 signal_thread_state_change (thread);
2556 void mono_thread_stop (MonoThread *thread)
2558 mono_thread_internal_stop (thread->internal_thread);
2561 gint8
2562 ves_icall_System_Threading_Thread_VolatileRead1 (void *ptr)
2564 return *((volatile gint8 *) (ptr));
2567 gint16
2568 ves_icall_System_Threading_Thread_VolatileRead2 (void *ptr)
2570 return *((volatile gint16 *) (ptr));
2573 gint32
2574 ves_icall_System_Threading_Thread_VolatileRead4 (void *ptr)
2576 return *((volatile gint32 *) (ptr));
2579 gint64
2580 ves_icall_System_Threading_Thread_VolatileRead8 (void *ptr)
2582 return *((volatile gint64 *) (ptr));
2585 void *
2586 ves_icall_System_Threading_Thread_VolatileReadIntPtr (void *ptr)
2588 return (void *) *((volatile void **) ptr);
2591 void
2592 ves_icall_System_Threading_Thread_VolatileWrite1 (void *ptr, gint8 value)
2594 *((volatile gint8 *) ptr) = value;
2597 void
2598 ves_icall_System_Threading_Thread_VolatileWrite2 (void *ptr, gint16 value)
2600 *((volatile gint16 *) ptr) = value;
2603 void
2604 ves_icall_System_Threading_Thread_VolatileWrite4 (void *ptr, gint32 value)
2606 *((volatile gint32 *) ptr) = value;
2609 void
2610 ves_icall_System_Threading_Thread_VolatileWrite8 (void *ptr, gint64 value)
2612 *((volatile gint64 *) ptr) = value;
2615 void
2616 ves_icall_System_Threading_Thread_VolatileWriteIntPtr (void *ptr, void *value)
2618 *((volatile void **) ptr) = value;
2621 void
2622 ves_icall_System_Threading_Thread_VolatileWriteObject (void *ptr, void *value)
2624 mono_gc_wbarrier_generic_store (ptr, value);
2627 void mono_thread_init (MonoThreadStartCB start_cb,
2628 MonoThreadAttachCB attach_cb)
2630 MONO_GC_REGISTER_ROOT (small_id_table);
2631 InitializeCriticalSection(&threads_mutex);
2632 InitializeCriticalSection(&interlocked_mutex);
2633 InitializeCriticalSection(&contexts_mutex);
2634 InitializeCriticalSection(&delayed_free_table_mutex);
2635 InitializeCriticalSection(&small_id_mutex);
2637 background_change_event = CreateEvent (NULL, TRUE, FALSE, NULL);
2638 g_assert(background_change_event != NULL);
2640 mono_init_static_data_info (&thread_static_info);
2641 mono_init_static_data_info (&context_static_info);
2643 current_object_key=TlsAlloc();
2644 THREAD_DEBUG (g_message ("%s: Allocated current_object_key %d", __func__, current_object_key));
2646 mono_thread_start_cb = start_cb;
2647 mono_thread_attach_cb = attach_cb;
2649 delayed_free_table = g_array_new (FALSE, FALSE, sizeof (DelayedFreeItem));
2651 /* Get a pseudo handle to the current process. This is just a
2652 * kludge so that wapi can build a process handle if needed.
2653 * As a pseudo handle is returned, we don't need to clean
2654 * anything up.
2656 GetCurrentProcess ();
2659 void mono_thread_cleanup (void)
2661 mono_thread_hazardous_try_free_all ();
2663 #if !defined(HOST_WIN32) && !defined(RUN_IN_SUBTHREAD)
2664 /* The main thread must abandon any held mutexes (particularly
2665 * important for named mutexes as they are shared across
2666 * processes, see bug 74680.) This will happen when the
2667 * thread exits, but if it's not running in a subthread it
2668 * won't exit in time.
2670 /* Using non-w32 API is a nasty kludge, but I couldn't find
2671 * anything in the documentation that would let me do this
2672 * here yet still be safe to call on windows.
2674 _wapi_thread_signal_self (mono_environment_exitcode_get ());
2675 #endif
2677 #if 0
2678 /* This stuff needs more testing, it seems one of these
2679 * critical sections can be locked when mono_thread_cleanup is
2680 * called.
2682 DeleteCriticalSection (&threads_mutex);
2683 DeleteCriticalSection (&interlocked_mutex);
2684 DeleteCriticalSection (&contexts_mutex);
2685 DeleteCriticalSection (&delayed_free_table_mutex);
2686 DeleteCriticalSection (&small_id_mutex);
2687 CloseHandle (background_change_event);
2688 #endif
2690 g_array_free (delayed_free_table, TRUE);
2691 delayed_free_table = NULL;
2693 TlsFree (current_object_key);
2696 void
2697 mono_threads_install_cleanup (MonoThreadCleanupFunc func)
2699 mono_thread_cleanup_fn = func;
2702 void
2703 mono_thread_set_manage_callback (MonoThread *thread, MonoThreadManageCallback func)
2705 thread->internal_thread->manage_callback = func;
2708 void mono_threads_install_notify_pending_exc (MonoThreadNotifyPendingExcFunc func)
2710 mono_thread_notify_pending_exc_fn = func;
2713 G_GNUC_UNUSED
2714 static void print_tids (gpointer key, gpointer value, gpointer user)
2716 /* GPOINTER_TO_UINT breaks horribly if sizeof(void *) >
2717 * sizeof(uint) and a cast to uint would overflow
2719 /* Older versions of glib don't have G_GSIZE_FORMAT, so just
2720 * print this as a pointer.
2722 g_message ("Waiting for: %p", key);
2725 struct wait_data
2727 HANDLE handles[MAXIMUM_WAIT_OBJECTS];
2728 MonoInternalThread *threads[MAXIMUM_WAIT_OBJECTS];
2729 guint32 num;
2732 static void wait_for_tids (struct wait_data *wait, guint32 timeout)
2734 guint32 i, ret;
2736 THREAD_DEBUG (g_message("%s: %d threads to wait for in this batch", __func__, wait->num));
2738 ret=WaitForMultipleObjectsEx(wait->num, wait->handles, TRUE, timeout, FALSE);
2740 if(ret==WAIT_FAILED) {
2741 /* See the comment in build_wait_tids() */
2742 THREAD_DEBUG (g_message ("%s: Wait failed", __func__));
2743 return;
2746 for(i=0; i<wait->num; i++)
2747 CloseHandle (wait->handles[i]);
2749 if (ret == WAIT_TIMEOUT)
2750 return;
2752 for(i=0; i<wait->num; i++) {
2753 gsize tid = wait->threads[i]->tid;
2755 mono_threads_lock ();
2756 if(mono_g_hash_table_lookup (threads, (gpointer)tid)!=NULL) {
2757 /* This thread must have been killed, because
2758 * it hasn't cleaned itself up. (It's just
2759 * possible that the thread exited before the
2760 * parent thread had a chance to store the
2761 * handle, and now there is another pointer to
2762 * the already-exited thread stored. In this
2763 * case, we'll just get two
2764 * mono_profiler_thread_end() calls for the
2765 * same thread.)
2768 mono_threads_unlock ();
2769 THREAD_DEBUG (g_message ("%s: cleaning up after thread %p (%"G_GSIZE_FORMAT")", __func__, wait->threads[i], tid));
2770 thread_cleanup (wait->threads[i]);
2771 } else {
2772 mono_threads_unlock ();
2777 static void wait_for_tids_or_state_change (struct wait_data *wait, guint32 timeout)
2779 guint32 i, ret, count;
2781 THREAD_DEBUG (g_message("%s: %d threads to wait for in this batch", __func__, wait->num));
2783 /* Add the thread state change event, so it wakes up if a thread changes
2784 * to background mode.
2786 count = wait->num;
2787 if (count < MAXIMUM_WAIT_OBJECTS) {
2788 wait->handles [count] = background_change_event;
2789 count++;
2792 ret=WaitForMultipleObjectsEx (count, wait->handles, FALSE, timeout, FALSE);
2794 if(ret==WAIT_FAILED) {
2795 /* See the comment in build_wait_tids() */
2796 THREAD_DEBUG (g_message ("%s: Wait failed", __func__));
2797 return;
2800 for(i=0; i<wait->num; i++)
2801 CloseHandle (wait->handles[i]);
2803 if (ret == WAIT_TIMEOUT)
2804 return;
2806 if (ret < wait->num) {
2807 gsize tid = wait->threads[ret]->tid;
2808 mono_threads_lock ();
2809 if (mono_g_hash_table_lookup (threads, (gpointer)tid)!=NULL) {
2810 /* See comment in wait_for_tids about thread cleanup */
2811 mono_threads_unlock ();
2812 THREAD_DEBUG (g_message ("%s: cleaning up after thread %"G_GSIZE_FORMAT, __func__, tid));
2813 thread_cleanup (wait->threads [ret]);
2814 } else
2815 mono_threads_unlock ();
2819 static void build_wait_tids (gpointer key, gpointer value, gpointer user)
2821 struct wait_data *wait=(struct wait_data *)user;
2823 if(wait->num<MAXIMUM_WAIT_OBJECTS) {
2824 HANDLE handle;
2825 MonoInternalThread *thread=(MonoInternalThread *)value;
2827 /* Ignore background threads, we abort them later */
2828 /* Do not lock here since it is not needed and the caller holds threads_lock */
2829 if (thread->state & ThreadState_Background) {
2830 THREAD_DEBUG (g_message ("%s: ignoring background thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2831 return; /* just leave, ignore */
2834 if (mono_gc_is_finalizer_internal_thread (thread)) {
2835 THREAD_DEBUG (g_message ("%s: ignoring finalizer thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2836 return;
2839 if (thread == mono_thread_internal_current ()) {
2840 THREAD_DEBUG (g_message ("%s: ignoring current thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2841 return;
2844 if (mono_thread_get_main () && (thread == mono_thread_get_main ()->internal_thread)) {
2845 THREAD_DEBUG (g_message ("%s: ignoring main thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2846 return;
2849 if (thread->flags & MONO_THREAD_FLAG_DONT_MANAGE) {
2850 THREAD_DEBUG (g_message ("%s: ignoring thread %" G_GSIZE_FORMAT "with DONT_MANAGE flag set.", __func__, (gsize)thread->tid));
2851 return;
2854 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
2855 if (handle == NULL) {
2856 THREAD_DEBUG (g_message ("%s: ignoring unopenable thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2857 return;
2860 THREAD_DEBUG (g_message ("%s: Invoking mono_thread_manage callback on thread %p", __func__, thread));
2861 if ((thread->manage_callback == NULL) || (thread->manage_callback (thread->root_domain_thread) == TRUE)) {
2862 wait->handles[wait->num]=handle;
2863 wait->threads[wait->num]=thread;
2864 wait->num++;
2866 THREAD_DEBUG (g_message ("%s: adding thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2867 } else {
2868 THREAD_DEBUG (g_message ("%s: ignoring (because of callback) thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2872 } else {
2873 /* Just ignore the rest, we can't do anything with
2874 * them yet
2879 static gboolean
2880 remove_and_abort_threads (gpointer key, gpointer value, gpointer user)
2882 struct wait_data *wait=(struct wait_data *)user;
2883 gsize self = GetCurrentThreadId ();
2884 MonoInternalThread *thread = value;
2885 HANDLE handle;
2887 if (wait->num >= MAXIMUM_WAIT_OBJECTS)
2888 return FALSE;
2890 /* The finalizer thread is not a background thread */
2891 if (thread->tid != self && (thread->state & ThreadState_Background) != 0 &&
2892 !(thread->flags & MONO_THREAD_FLAG_DONT_MANAGE)) {
2894 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
2895 if (handle == NULL)
2896 return FALSE;
2898 /* printf ("A: %d\n", wait->num); */
2899 wait->handles[wait->num]=thread->handle;
2900 wait->threads[wait->num]=thread;
2901 wait->num++;
2903 THREAD_DEBUG (g_print ("%s: Aborting id: %"G_GSIZE_FORMAT"\n", __func__, (gsize)thread->tid));
2904 mono_thread_internal_stop (thread);
2905 return TRUE;
2908 return (thread->tid != self && !mono_gc_is_finalizer_internal_thread (thread));
2911 /**
2912 * mono_threads_set_shutting_down:
2914 * Is called by a thread that wants to shut down Mono. If the runtime is already
2915 * shutting down, the calling thread is suspended/stopped, and this function never
2916 * returns.
2918 void
2919 mono_threads_set_shutting_down (void)
2921 MonoInternalThread *current_thread = mono_thread_internal_current ();
2923 mono_threads_lock ();
2925 if (shutting_down) {
2926 mono_threads_unlock ();
2928 /* Make sure we're properly suspended/stopped */
2930 EnterCriticalSection (current_thread->synch_cs);
2932 if ((current_thread->state & ThreadState_SuspendRequested) ||
2933 (current_thread->state & ThreadState_AbortRequested) ||
2934 (current_thread->state & ThreadState_StopRequested)) {
2935 LeaveCriticalSection (current_thread->synch_cs);
2936 mono_thread_execute_interruption (current_thread);
2937 } else {
2938 current_thread->state |= ThreadState_Stopped;
2939 LeaveCriticalSection (current_thread->synch_cs);
2942 /* Wake up other threads potentially waiting for us */
2943 ExitThread (0);
2944 } else {
2945 shutting_down = TRUE;
2947 /* Not really a background state change, but this will
2948 * interrupt the main thread if it is waiting for all
2949 * the other threads.
2951 SetEvent (background_change_event);
2953 mono_threads_unlock ();
2957 /**
2958 * mono_threads_is_shutting_down:
2960 * Returns whether a thread has commenced shutdown of Mono. Note that
2961 * if the function returns FALSE the caller must not assume that
2962 * shutdown is not in progress, because the situation might have
2963 * changed since the function returned. For that reason this function
2964 * is of very limited utility.
2966 gboolean
2967 mono_threads_is_shutting_down (void)
2969 return shutting_down;
2972 void mono_thread_manage (void)
2974 struct wait_data *wait=g_new0 (struct wait_data, 1);
2976 /* join each thread that's still running */
2977 THREAD_DEBUG (g_message ("%s: Joining each running thread...", __func__));
2979 mono_threads_lock ();
2980 if(threads==NULL) {
2981 THREAD_DEBUG (g_message("%s: No threads", __func__));
2982 mono_threads_unlock ();
2983 g_free (wait);
2984 return;
2986 mono_threads_unlock ();
2988 do {
2989 mono_threads_lock ();
2990 if (shutting_down) {
2991 /* somebody else is shutting down */
2992 mono_threads_unlock ();
2993 break;
2995 THREAD_DEBUG (g_message ("%s: There are %d threads to join", __func__, mono_g_hash_table_size (threads));
2996 mono_g_hash_table_foreach (threads, print_tids, NULL));
2998 ResetEvent (background_change_event);
2999 wait->num=0;
3000 mono_g_hash_table_foreach (threads, build_wait_tids, wait);
3001 mono_threads_unlock ();
3002 if(wait->num>0) {
3003 /* Something to wait for */
3004 wait_for_tids_or_state_change (wait, INFINITE);
3006 THREAD_DEBUG (g_message ("%s: I have %d threads after waiting.", __func__, wait->num));
3007 } while(wait->num>0);
3009 mono_threads_set_shutting_down ();
3011 /* No new threads will be created after this point */
3013 mono_runtime_set_shutting_down ();
3015 THREAD_DEBUG (g_message ("%s: threadpool cleanup", __func__));
3016 mono_thread_pool_cleanup ();
3019 * Remove everything but the finalizer thread and self.
3020 * Also abort all the background threads
3021 * */
3022 do {
3023 mono_threads_lock ();
3025 wait->num = 0;
3026 mono_g_hash_table_foreach_remove (threads, remove_and_abort_threads, wait);
3028 mono_threads_unlock ();
3030 THREAD_DEBUG (g_message ("%s: wait->num is now %d", __func__, wait->num));
3031 if(wait->num>0) {
3032 /* Something to wait for */
3033 wait_for_tids (wait, INFINITE);
3035 } while (wait->num > 0);
3038 * give the subthreads a chance to really quit (this is mainly needed
3039 * to get correct user and system times from getrusage/wait/time(1)).
3040 * This could be removed if we avoid pthread_detach() and use pthread_join().
3042 #ifndef HOST_WIN32
3043 sched_yield ();
3044 #endif
3046 g_free (wait);
3049 static void terminate_thread (gpointer key, gpointer value, gpointer user)
3051 MonoInternalThread *thread=(MonoInternalThread *)value;
3053 if(thread->tid != (gsize)user) {
3054 /*TerminateThread (thread->handle, -1);*/
3058 void mono_thread_abort_all_other_threads (void)
3060 gsize self = GetCurrentThreadId ();
3062 mono_threads_lock ();
3063 THREAD_DEBUG (g_message ("%s: There are %d threads to abort", __func__,
3064 mono_g_hash_table_size (threads));
3065 mono_g_hash_table_foreach (threads, print_tids, NULL));
3067 mono_g_hash_table_foreach (threads, terminate_thread, (gpointer)self);
3069 mono_threads_unlock ();
3072 static void
3073 collect_threads_for_suspend (gpointer key, gpointer value, gpointer user_data)
3075 MonoInternalThread *thread = (MonoInternalThread*)value;
3076 struct wait_data *wait = (struct wait_data*)user_data;
3077 HANDLE handle;
3080 * We try to exclude threads early, to avoid running into the MAXIMUM_WAIT_OBJECTS
3081 * limitation.
3082 * This needs no locking.
3084 if ((thread->state & ThreadState_Suspended) != 0 ||
3085 (thread->state & ThreadState_Stopped) != 0)
3086 return;
3088 if (wait->num<MAXIMUM_WAIT_OBJECTS) {
3089 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
3090 if (handle == NULL)
3091 return;
3093 wait->handles [wait->num] = handle;
3094 wait->threads [wait->num] = thread;
3095 wait->num++;
3100 * mono_thread_suspend_all_other_threads:
3102 * Suspend all managed threads except the finalizer thread and this thread. It is
3103 * not possible to resume them later.
3105 void mono_thread_suspend_all_other_threads (void)
3107 struct wait_data *wait = g_new0 (struct wait_data, 1);
3108 int i;
3109 gsize self = GetCurrentThreadId ();
3110 gpointer *events;
3111 guint32 eventidx = 0;
3112 gboolean starting, finished;
3115 * The other threads could be in an arbitrary state at this point, i.e.
3116 * they could be starting up, shutting down etc. This means that there could be
3117 * threads which are not even in the threads hash table yet.
3121 * First we set a barrier which will be checked by all threads before they
3122 * are added to the threads hash table, and they will exit if the flag is set.
3123 * This ensures that no threads could be added to the hash later.
3124 * We will use shutting_down as the barrier for now.
3126 g_assert (shutting_down);
3129 * We make multiple calls to WaitForMultipleObjects since:
3130 * - we can only wait for MAXIMUM_WAIT_OBJECTS threads
3131 * - some threads could exit without becoming suspended
3133 finished = FALSE;
3134 while (!finished) {
3136 * Make a copy of the hashtable since we can't do anything with
3137 * threads while threads_mutex is held.
3139 wait->num = 0;
3140 mono_threads_lock ();
3141 mono_g_hash_table_foreach (threads, collect_threads_for_suspend, wait);
3142 mono_threads_unlock ();
3144 events = g_new0 (gpointer, wait->num);
3145 eventidx = 0;
3146 /* Get the suspended events that we'll be waiting for */
3147 for (i = 0; i < wait->num; ++i) {
3148 MonoInternalThread *thread = wait->threads [i];
3149 gboolean signal_suspend = FALSE;
3151 if ((thread->tid == self) || mono_gc_is_finalizer_internal_thread (thread) || (thread->flags & MONO_THREAD_FLAG_DONT_MANAGE)) {
3152 //CloseHandle (wait->handles [i]);
3153 wait->threads [i] = NULL; /* ignore this thread in next loop */
3154 continue;
3157 ensure_synch_cs_set (thread);
3159 EnterCriticalSection (thread->synch_cs);
3161 if (thread->suspended_event == NULL) {
3162 thread->suspended_event = CreateEvent (NULL, TRUE, FALSE, NULL);
3163 if (thread->suspended_event == NULL) {
3164 /* Forget this one and go on to the next */
3165 LeaveCriticalSection (thread->synch_cs);
3166 continue;
3170 if ((thread->state & ThreadState_Suspended) != 0 ||
3171 (thread->state & ThreadState_StopRequested) != 0 ||
3172 (thread->state & ThreadState_Stopped) != 0) {
3173 LeaveCriticalSection (thread->synch_cs);
3174 CloseHandle (wait->handles [i]);
3175 wait->threads [i] = NULL; /* ignore this thread in next loop */
3176 continue;
3179 if ((thread->state & ThreadState_SuspendRequested) == 0)
3180 signal_suspend = TRUE;
3182 events [eventidx++] = thread->suspended_event;
3184 /* Convert abort requests into suspend requests */
3185 if ((thread->state & ThreadState_AbortRequested) != 0)
3186 thread->state &= ~ThreadState_AbortRequested;
3188 thread->state |= ThreadState_SuspendRequested;
3190 LeaveCriticalSection (thread->synch_cs);
3192 /* Signal the thread to suspend */
3193 if (signal_suspend)
3194 signal_thread_state_change (thread);
3197 if (eventidx > 0) {
3198 WaitForMultipleObjectsEx (eventidx, events, TRUE, 100, FALSE);
3199 for (i = 0; i < wait->num; ++i) {
3200 MonoInternalThread *thread = wait->threads [i];
3202 if (thread == NULL)
3203 continue;
3205 ensure_synch_cs_set (thread);
3207 EnterCriticalSection (thread->synch_cs);
3208 if ((thread->state & ThreadState_Suspended) != 0) {
3209 CloseHandle (thread->suspended_event);
3210 thread->suspended_event = NULL;
3212 LeaveCriticalSection (thread->synch_cs);
3214 } else {
3216 * If there are threads which are starting up, we wait until they
3217 * are suspended when they try to register in the threads hash.
3218 * This is guaranteed to finish, since the threads which can create new
3219 * threads get suspended after a while.
3220 * FIXME: The finalizer thread can still create new threads.
3222 mono_threads_lock ();
3223 if (threads_starting_up)
3224 starting = mono_g_hash_table_size (threads_starting_up) > 0;
3225 else
3226 starting = FALSE;
3227 mono_threads_unlock ();
3228 if (starting)
3229 Sleep (100);
3230 else
3231 finished = TRUE;
3234 g_free (events);
3237 g_free (wait);
3240 static void
3241 collect_threads (gpointer key, gpointer value, gpointer user_data)
3243 MonoInternalThread *thread = (MonoInternalThread*)value;
3244 struct wait_data *wait = (struct wait_data*)user_data;
3245 HANDLE handle;
3247 if (wait->num<MAXIMUM_WAIT_OBJECTS) {
3248 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
3249 if (handle == NULL)
3250 return;
3252 wait->handles [wait->num] = handle;
3253 wait->threads [wait->num] = thread;
3254 wait->num++;
3259 * mono_threads_request_thread_dump:
3261 * Ask all threads except the current to print their stacktrace to stdout.
3263 void
3264 mono_threads_request_thread_dump (void)
3266 struct wait_data *wait = g_new0 (struct wait_data, 1);
3267 int i;
3270 * Make a copy of the hashtable since we can't do anything with
3271 * threads while threads_mutex is held.
3273 mono_threads_lock ();
3274 mono_g_hash_table_foreach (threads, collect_threads, wait);
3275 mono_threads_unlock ();
3277 for (i = 0; i < wait->num; ++i) {
3278 MonoInternalThread *thread = wait->threads [i];
3280 if (!mono_gc_is_finalizer_internal_thread (thread) &&
3281 (thread != mono_thread_internal_current ()) &&
3282 !thread->thread_dump_requested) {
3283 thread->thread_dump_requested = TRUE;
3285 signal_thread_state_change (thread);
3288 CloseHandle (wait->handles [i]);
3293 * mono_thread_push_appdomain_ref:
3295 * Register that the current thread may have references to objects in domain
3296 * @domain on its stack. Each call to this function should be paired with a
3297 * call to pop_appdomain_ref.
3299 void
3300 mono_thread_push_appdomain_ref (MonoDomain *domain)
3302 MonoInternalThread *thread = mono_thread_internal_current ();
3304 if (thread) {
3305 /* printf ("PUSH REF: %"G_GSIZE_FORMAT" -> %s.\n", (gsize)thread->tid, domain->friendly_name); */
3306 SPIN_LOCK (thread->lock_thread_id);
3307 thread->appdomain_refs = g_slist_prepend (thread->appdomain_refs, domain);
3308 SPIN_UNLOCK (thread->lock_thread_id);
3312 void
3313 mono_thread_pop_appdomain_ref (void)
3315 MonoInternalThread *thread = mono_thread_internal_current ();
3317 if (thread) {
3318 /* printf ("POP REF: %"G_GSIZE_FORMAT" -> %s.\n", (gsize)thread->tid, ((MonoDomain*)(thread->appdomain_refs->data))->friendly_name); */
3319 /* FIXME: How can the list be empty ? */
3320 SPIN_LOCK (thread->lock_thread_id);
3321 if (thread->appdomain_refs)
3322 thread->appdomain_refs = g_slist_remove (thread->appdomain_refs, thread->appdomain_refs->data);
3323 SPIN_UNLOCK (thread->lock_thread_id);
3327 gboolean
3328 mono_thread_internal_has_appdomain_ref (MonoInternalThread *thread, MonoDomain *domain)
3330 gboolean res;
3331 SPIN_LOCK (thread->lock_thread_id);
3332 res = g_slist_find (thread->appdomain_refs, domain) != NULL;
3333 SPIN_UNLOCK (thread->lock_thread_id);
3334 return res;
3337 gboolean
3338 mono_thread_has_appdomain_ref (MonoThread *thread, MonoDomain *domain)
3340 return mono_thread_internal_has_appdomain_ref (thread->internal_thread, domain);
3343 typedef struct abort_appdomain_data {
3344 struct wait_data wait;
3345 MonoDomain *domain;
3346 } abort_appdomain_data;
3348 static void
3349 collect_appdomain_thread (gpointer key, gpointer value, gpointer user_data)
3351 MonoInternalThread *thread = (MonoInternalThread*)value;
3352 abort_appdomain_data *data = (abort_appdomain_data*)user_data;
3353 MonoDomain *domain = data->domain;
3355 if (mono_thread_internal_has_appdomain_ref (thread, domain)) {
3356 /* printf ("ABORTING THREAD %p BECAUSE IT REFERENCES DOMAIN %s.\n", thread->tid, domain->friendly_name); */
3358 if(data->wait.num<MAXIMUM_WAIT_OBJECTS) {
3359 HANDLE handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
3360 if (handle == NULL)
3361 return;
3362 data->wait.handles [data->wait.num] = handle;
3363 data->wait.threads [data->wait.num] = thread;
3364 data->wait.num++;
3365 } else {
3366 /* Just ignore the rest, we can't do anything with
3367 * them yet
3374 * mono_threads_abort_appdomain_threads:
3376 * Abort threads which has references to the given appdomain.
3378 gboolean
3379 mono_threads_abort_appdomain_threads (MonoDomain *domain, int timeout)
3381 abort_appdomain_data user_data;
3382 guint32 start_time;
3383 int orig_timeout = timeout;
3384 int i;
3386 THREAD_DEBUG (g_message ("%s: starting abort", __func__));
3388 start_time = mono_msec_ticks ();
3389 do {
3390 mono_threads_lock ();
3392 user_data.domain = domain;
3393 user_data.wait.num = 0;
3394 /* This shouldn't take any locks */
3395 mono_g_hash_table_foreach (threads, collect_appdomain_thread, &user_data);
3396 mono_threads_unlock ();
3398 if (user_data.wait.num > 0) {
3399 /* Abort the threads outside the threads lock */
3400 for (i = 0; i < user_data.wait.num; ++i)
3401 ves_icall_System_Threading_Thread_Abort (user_data.wait.threads [i], NULL);
3404 * We should wait for the threads either to abort, or to leave the
3405 * domain. We can't do the latter, so we wait with a timeout.
3407 wait_for_tids (&user_data.wait, 100);
3410 /* Update remaining time */
3411 timeout -= mono_msec_ticks () - start_time;
3412 start_time = mono_msec_ticks ();
3414 if (orig_timeout != -1 && timeout < 0)
3415 return FALSE;
3417 while (user_data.wait.num > 0);
3419 THREAD_DEBUG (g_message ("%s: abort done", __func__));
3421 return TRUE;
3424 static void
3425 clear_cached_culture (gpointer key, gpointer value, gpointer user_data)
3427 MonoInternalThread *thread = (MonoInternalThread*)value;
3428 MonoDomain *domain = (MonoDomain*)user_data;
3429 int i;
3431 /* No locking needed here */
3432 /* FIXME: why no locking? writes to the cache are protected with synch_cs above */
3434 if (thread->cached_culture_info) {
3435 for (i = 0; i < NUM_CACHED_CULTURES * 2; ++i) {
3436 MonoObject *obj = mono_array_get (thread->cached_culture_info, MonoObject*, i);
3437 if (obj && obj->vtable->domain == domain)
3438 mono_array_set (thread->cached_culture_info, MonoObject*, i, NULL);
3444 * mono_threads_clear_cached_culture:
3446 * Clear the cached_current_culture from all threads if it is in the
3447 * given appdomain.
3449 void
3450 mono_threads_clear_cached_culture (MonoDomain *domain)
3452 mono_threads_lock ();
3453 mono_g_hash_table_foreach (threads, clear_cached_culture, domain);
3454 mono_threads_unlock ();
3458 * mono_thread_get_undeniable_exception:
3460 * Return an exception which needs to be raised when leaving a catch clause.
3461 * This is used for undeniable exception propagation.
3463 MonoException*
3464 mono_thread_get_undeniable_exception (void)
3466 MonoInternalThread *thread = mono_thread_internal_current ();
3468 if (thread && thread->abort_exc && !is_running_protected_wrapper ()) {
3470 * FIXME: Clear the abort exception and return an AppDomainUnloaded
3471 * exception if the thread no longer references a dying appdomain.
3473 thread->abort_exc->trace_ips = NULL;
3474 thread->abort_exc->stack_trace = NULL;
3475 return thread->abort_exc;
3478 return NULL;
3481 #if MONO_SMALL_CONFIG
3482 #define NUM_STATIC_DATA_IDX 4
3483 static const int static_data_size [NUM_STATIC_DATA_IDX] = {
3484 64, 256, 1024, 4096
3486 #else
3487 #define NUM_STATIC_DATA_IDX 8
3488 static const int static_data_size [NUM_STATIC_DATA_IDX] = {
3489 1024, 4096, 16384, 65536, 262144, 1048576, 4194304, 16777216
3491 #endif
3493 static uintptr_t* static_reference_bitmaps [NUM_STATIC_DATA_IDX];
3495 #ifdef HAVE_SGEN_GC
3496 static void
3497 mark_tls_slots (void *addr, MonoGCMarkFunc mark_func)
3499 int i;
3500 gpointer *static_data = addr;
3501 for (i = 0; i < NUM_STATIC_DATA_IDX; ++i) {
3502 int j, numwords;
3503 void **ptr;
3504 if (!static_data [i])
3505 continue;
3506 numwords = 1 + static_data_size [i] / sizeof (gpointer) / (sizeof(uintptr_t) * 8);
3507 ptr = static_data [i];
3508 for (j = 0; j < numwords; ++j, ptr += sizeof (uintptr_t) * 8) {
3509 uintptr_t bmap = static_reference_bitmaps [i][j];
3510 void ** p = ptr;
3511 while (bmap) {
3512 if ((bmap & 1) && *p) {
3513 mark_func (p);
3515 p++;
3516 bmap >>= 1;
3521 #endif
3524 * mono_alloc_static_data
3526 * Allocate memory blocks for storing threads or context static data
3528 static void
3529 mono_alloc_static_data (gpointer **static_data_ptr, guint32 offset, gboolean threadlocal)
3531 guint idx = (offset >> 24) - 1;
3532 int i;
3534 gpointer* static_data = *static_data_ptr;
3535 if (!static_data) {
3536 static void* tls_desc = NULL;
3537 #ifdef HAVE_SGEN_GC
3538 if (!tls_desc)
3539 tls_desc = mono_gc_make_root_descr_user (mark_tls_slots);
3540 #endif
3541 static_data = mono_gc_alloc_fixed (static_data_size [0], threadlocal?tls_desc:NULL);
3542 *static_data_ptr = static_data;
3543 static_data [0] = static_data;
3546 for (i = 1; i <= idx; ++i) {
3547 if (static_data [i])
3548 continue;
3549 #ifdef HAVE_SGEN_GC
3550 static_data [i] = threadlocal?g_malloc0 (static_data_size [i]):mono_gc_alloc_fixed (static_data_size [i], NULL);
3551 #else
3552 static_data [i] = mono_gc_alloc_fixed (static_data_size [i], NULL);
3553 #endif
3557 static void
3558 mono_free_static_data (gpointer* static_data, gboolean threadlocal)
3560 int i;
3561 for (i = 1; i < NUM_STATIC_DATA_IDX; ++i) {
3562 if (!static_data [i])
3563 continue;
3564 #ifdef HAVE_SGEN_GC
3565 if (threadlocal)
3566 g_free (static_data [i]);
3567 else
3568 mono_gc_free_fixed (static_data [i]);
3569 #else
3570 mono_gc_free_fixed (static_data [i]);
3571 #endif
3573 mono_gc_free_fixed (static_data);
3577 * mono_init_static_data_info
3579 * Initializes static data counters
3581 static void mono_init_static_data_info (StaticDataInfo *static_data)
3583 static_data->idx = 0;
3584 static_data->offset = 0;
3585 static_data->freelist = NULL;
3589 * mono_alloc_static_data_slot
3591 * Generates an offset for static data. static_data contains the counters
3592 * used to generate it.
3594 static guint32
3595 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align)
3597 guint32 offset;
3599 if (!static_data->idx && !static_data->offset) {
3601 * we use the first chunk of the first allocation also as
3602 * an array for the rest of the data
3604 static_data->offset = sizeof (gpointer) * NUM_STATIC_DATA_IDX;
3606 static_data->offset += align - 1;
3607 static_data->offset &= ~(align - 1);
3608 if (static_data->offset + size >= static_data_size [static_data->idx]) {
3609 static_data->idx ++;
3610 g_assert (size <= static_data_size [static_data->idx]);
3611 g_assert (static_data->idx < NUM_STATIC_DATA_IDX);
3612 static_data->offset = 0;
3614 offset = static_data->offset | ((static_data->idx + 1) << 24);
3615 static_data->offset += size;
3616 return offset;
3620 * ensure thread static fields already allocated are valid for thread
3621 * This function is called when a thread is created or on thread attach.
3623 static void
3624 thread_adjust_static_data (MonoInternalThread *thread)
3626 guint32 offset;
3628 mono_threads_lock ();
3629 if (thread_static_info.offset || thread_static_info.idx > 0) {
3630 /* get the current allocated size */
3631 offset = thread_static_info.offset | ((thread_static_info.idx + 1) << 24);
3632 mono_alloc_static_data (&(thread->static_data), offset, TRUE);
3634 mono_threads_unlock ();
3637 static void
3638 alloc_thread_static_data_helper (gpointer key, gpointer value, gpointer user)
3640 MonoInternalThread *thread = value;
3641 guint32 offset = GPOINTER_TO_UINT (user);
3643 mono_alloc_static_data (&(thread->static_data), offset, TRUE);
3646 static MonoThreadDomainTls*
3647 search_tls_slot_in_freelist (StaticDataInfo *static_data, guint32 size, guint32 align)
3649 MonoThreadDomainTls* prev = NULL;
3650 MonoThreadDomainTls* tmp = static_data->freelist;
3651 while (tmp) {
3652 if (tmp->size == size) {
3653 if (prev)
3654 prev->next = tmp->next;
3655 else
3656 static_data->freelist = tmp->next;
3657 return tmp;
3659 tmp = tmp->next;
3661 return NULL;
3664 static void
3665 update_tls_reference_bitmap (guint32 offset, uintptr_t *bitmap, int max_set)
3667 int i;
3668 int idx = (offset >> 24) - 1;
3669 uintptr_t *rb;
3670 if (!static_reference_bitmaps [idx])
3671 static_reference_bitmaps [idx] = g_new0 (uintptr_t, 1 + static_data_size [idx] / sizeof(gpointer) / (sizeof(uintptr_t) * 8));
3672 rb = static_reference_bitmaps [idx];
3673 offset &= 0xffffff;
3674 offset /= sizeof (gpointer);
3675 /* offset is now the bitmap offset */
3676 for (i = 0; i < max_set; ++i) {
3677 if (bitmap [i / sizeof (uintptr_t)] & (1L << (i & (sizeof (uintptr_t) * 8 -1))))
3678 rb [(offset + i) / (sizeof (uintptr_t) * 8)] |= (1L << ((offset + i) & (sizeof (uintptr_t) * 8 -1)));
3682 static void
3683 clear_reference_bitmap (guint32 offset, guint32 size)
3685 int idx = (offset >> 24) - 1;
3686 uintptr_t *rb;
3687 rb = static_reference_bitmaps [idx];
3688 offset &= 0xffffff;
3689 offset /= sizeof (gpointer);
3690 size /= sizeof (gpointer);
3691 size += offset;
3692 /* offset is now the bitmap offset */
3693 for (; offset < size; ++offset)
3694 rb [offset / (sizeof (uintptr_t) * 8)] &= ~(1L << (offset & (sizeof (uintptr_t) * 8 -1)));
3698 * The offset for a special static variable is composed of three parts:
3699 * a bit that indicates the type of static data (0:thread, 1:context),
3700 * an index in the array of chunks of memory for the thread (thread->static_data)
3701 * and an offset in that chunk of mem. This allows allocating less memory in the
3702 * common case.
3705 guint32
3706 mono_alloc_special_static_data (guint32 static_type, guint32 size, guint32 align, uintptr_t *bitmap, int max_set)
3708 guint32 offset;
3709 if (static_type == SPECIAL_STATIC_THREAD) {
3710 MonoThreadDomainTls *item;
3711 mono_threads_lock ();
3712 item = search_tls_slot_in_freelist (&thread_static_info, size, align);
3713 /*g_print ("TLS alloc: %d in domain %p (total: %d), cached: %p\n", size, mono_domain_get (), thread_static_info.offset, item);*/
3714 if (item) {
3715 offset = item->offset;
3716 g_free (item);
3717 } else {
3718 offset = mono_alloc_static_data_slot (&thread_static_info, size, align);
3720 update_tls_reference_bitmap (offset, bitmap, max_set);
3721 /* This can be called during startup */
3722 if (threads != NULL)
3723 mono_g_hash_table_foreach (threads, alloc_thread_static_data_helper, GUINT_TO_POINTER (offset));
3724 mono_threads_unlock ();
3725 } else {
3726 g_assert (static_type == SPECIAL_STATIC_CONTEXT);
3727 mono_contexts_lock ();
3728 offset = mono_alloc_static_data_slot (&context_static_info, size, align);
3729 mono_contexts_unlock ();
3730 offset |= 0x80000000; /* Set the high bit to indicate context static data */
3732 return offset;
3735 gpointer
3736 mono_get_special_static_data (guint32 offset)
3738 /* The high bit means either thread (0) or static (1) data. */
3740 guint32 static_type = (offset & 0x80000000);
3741 int idx;
3743 offset &= 0x7fffffff;
3744 idx = (offset >> 24) - 1;
3746 if (static_type == 0) {
3747 return get_thread_static_data (mono_thread_internal_current (), offset);
3748 } else {
3749 /* Allocate static data block under demand, since we don't have a list
3750 // of contexts
3752 MonoAppContext *context = mono_context_get ();
3753 if (!context->static_data || !context->static_data [idx]) {
3754 mono_contexts_lock ();
3755 mono_alloc_static_data (&(context->static_data), offset, FALSE);
3756 mono_contexts_unlock ();
3758 return ((char*) context->static_data [idx]) + (offset & 0xffffff);
3762 typedef struct {
3763 guint32 offset;
3764 guint32 size;
3765 } TlsOffsetSize;
3767 static void
3768 free_thread_static_data_helper (gpointer key, gpointer value, gpointer user)
3770 MonoInternalThread *thread = value;
3771 TlsOffsetSize *data = user;
3772 int idx = (data->offset >> 24) - 1;
3773 char *ptr;
3775 if (!thread->static_data || !thread->static_data [idx])
3776 return;
3777 ptr = ((char*) thread->static_data [idx]) + (data->offset & 0xffffff);
3778 memset (ptr, 0, data->size);
3781 static void
3782 do_free_special (gpointer key, gpointer value, gpointer data)
3784 MonoClassField *field = key;
3785 guint32 offset = GPOINTER_TO_UINT (value);
3786 guint32 static_type = (offset & 0x80000000);
3787 gint32 align;
3788 guint32 size;
3789 size = mono_type_size (field->type, &align);
3790 /*g_print ("free %s , size: %d, offset: %x\n", field->name, size, offset);*/
3791 if (static_type == 0) {
3792 TlsOffsetSize data;
3793 MonoThreadDomainTls *item = g_new0 (MonoThreadDomainTls, 1);
3794 data.offset = offset & 0x7fffffff;
3795 data.size = size;
3796 clear_reference_bitmap (data.offset, data.size);
3797 if (threads != NULL)
3798 mono_g_hash_table_foreach (threads, free_thread_static_data_helper, &data);
3799 item->offset = offset;
3800 item->size = size;
3801 item->next = thread_static_info.freelist;
3802 thread_static_info.freelist = item;
3803 } else {
3804 /* FIXME: free context static data as well */
3808 void
3809 mono_alloc_special_static_data_free (GHashTable *special_static_fields)
3811 mono_threads_lock ();
3812 g_hash_table_foreach (special_static_fields, do_free_special, NULL);
3813 mono_threads_unlock ();
3816 static MonoClassField *local_slots = NULL;
3818 typedef struct {
3819 /* local tls data to get locals_slot from a thread */
3820 guint32 offset;
3821 int idx;
3822 /* index in the locals_slot array */
3823 int slot;
3824 } LocalSlotID;
3826 static void
3827 clear_local_slot (gpointer key, gpointer value, gpointer user_data)
3829 LocalSlotID *sid = user_data;
3830 MonoInternalThread *thread = (MonoInternalThread*)value;
3831 MonoArray *slots_array;
3833 * the static field is stored at: ((char*) thread->static_data [idx]) + (offset & 0xffffff);
3834 * it is for the right domain, so we need to check if it is allocated an initialized
3835 * for the current thread.
3837 /*g_print ("handling thread %p\n", thread);*/
3838 if (!thread->static_data || !thread->static_data [sid->idx])
3839 return;
3840 slots_array = *(MonoArray **)(((char*) thread->static_data [sid->idx]) + (sid->offset & 0xffffff));
3841 if (!slots_array || sid->slot >= mono_array_length (slots_array))
3842 return;
3843 mono_array_set (slots_array, MonoObject*, sid->slot, NULL);
3846 void
3847 mono_thread_free_local_slot_values (int slot, MonoBoolean thread_local)
3849 MonoDomain *domain;
3850 LocalSlotID sid;
3851 sid.slot = slot;
3852 if (thread_local) {
3853 void *addr = NULL;
3854 if (!local_slots) {
3855 local_slots = mono_class_get_field_from_name (mono_defaults.thread_class, "local_slots");
3856 if (!local_slots) {
3857 g_warning ("local_slots field not found in Thread class");
3858 return;
3861 domain = mono_domain_get ();
3862 mono_domain_lock (domain);
3863 if (domain->special_static_fields)
3864 addr = g_hash_table_lookup (domain->special_static_fields, local_slots);
3865 mono_domain_unlock (domain);
3866 if (!addr)
3867 return;
3868 /*g_print ("freeing slot %d at %p\n", slot, addr);*/
3869 sid.offset = GPOINTER_TO_UINT (addr);
3870 sid.offset &= 0x7fffffff;
3871 sid.idx = (sid.offset >> 24) - 1;
3872 mono_threads_lock ();
3873 mono_g_hash_table_foreach (threads, clear_local_slot, &sid);
3874 mono_threads_unlock ();
3875 } else {
3876 /* FIXME: clear the slot for MonoAppContexts, too */
3880 #ifdef HOST_WIN32
3881 static void CALLBACK dummy_apc (ULONG_PTR param)
3884 #else
3885 static guint32 dummy_apc (gpointer param)
3887 return 0;
3889 #endif
3892 * mono_thread_execute_interruption
3894 * Performs the operation that the requested thread state requires (abort,
3895 * suspend or stop)
3897 static MonoException* mono_thread_execute_interruption (MonoInternalThread *thread)
3899 ensure_synch_cs_set (thread);
3901 EnterCriticalSection (thread->synch_cs);
3903 /* MonoThread::interruption_requested can only be changed with atomics */
3904 if (InterlockedCompareExchange (&thread->interruption_requested, FALSE, TRUE)) {
3905 /* this will consume pending APC calls */
3906 WaitForSingleObjectEx (GetCurrentThread(), 0, TRUE);
3907 InterlockedDecrement (&thread_interruption_requested);
3908 #ifndef HOST_WIN32
3909 /* Clear the interrupted flag of the thread so it can wait again */
3910 wapi_clear_interruption ();
3911 #endif
3914 if ((thread->state & ThreadState_AbortRequested) != 0) {
3915 LeaveCriticalSection (thread->synch_cs);
3916 if (thread->abort_exc == NULL) {
3918 * This might be racy, but it has to be called outside the lock
3919 * since it calls managed code.
3921 MONO_OBJECT_SETREF (thread, abort_exc, mono_get_exception_thread_abort ());
3923 return thread->abort_exc;
3925 else if ((thread->state & ThreadState_SuspendRequested) != 0) {
3926 thread->state &= ~ThreadState_SuspendRequested;
3927 thread->state |= ThreadState_Suspended;
3928 thread->suspend_event = CreateEvent (NULL, TRUE, FALSE, NULL);
3929 if (thread->suspend_event == NULL) {
3930 LeaveCriticalSection (thread->synch_cs);
3931 return(NULL);
3933 if (thread->suspended_event)
3934 SetEvent (thread->suspended_event);
3936 LeaveCriticalSection (thread->synch_cs);
3938 if (shutting_down) {
3939 /* After we left the lock, the runtime might shut down so everything becomes invalid */
3940 for (;;)
3941 Sleep (1000);
3944 WaitForSingleObject (thread->suspend_event, INFINITE);
3946 EnterCriticalSection (thread->synch_cs);
3948 CloseHandle (thread->suspend_event);
3949 thread->suspend_event = NULL;
3950 thread->state &= ~ThreadState_Suspended;
3952 /* The thread that requested the resume will have replaced this event
3953 * and will be waiting for it
3955 SetEvent (thread->resume_event);
3957 LeaveCriticalSection (thread->synch_cs);
3959 return NULL;
3961 else if ((thread->state & ThreadState_StopRequested) != 0) {
3962 /* FIXME: do this through the JIT? */
3964 LeaveCriticalSection (thread->synch_cs);
3966 mono_thread_exit ();
3967 return NULL;
3968 } else if (thread->thread_interrupt_requested) {
3970 thread->thread_interrupt_requested = FALSE;
3971 LeaveCriticalSection (thread->synch_cs);
3973 return(mono_get_exception_thread_interrupted ());
3976 LeaveCriticalSection (thread->synch_cs);
3978 return NULL;
3982 * mono_thread_request_interruption
3984 * A signal handler can call this method to request the interruption of a
3985 * thread. The result of the interruption will depend on the current state of
3986 * the thread. If the result is an exception that needs to be throw, it is
3987 * provided as return value.
3989 MonoException*
3990 mono_thread_request_interruption (gboolean running_managed)
3992 MonoInternalThread *thread = mono_thread_internal_current ();
3994 /* The thread may already be stopping */
3995 if (thread == NULL)
3996 return NULL;
3998 #ifdef HOST_WIN32
3999 if (thread->interrupt_on_stop &&
4000 thread->state & ThreadState_StopRequested &&
4001 thread->state & ThreadState_Background)
4002 ExitThread (1);
4003 #endif
4005 if (InterlockedCompareExchange (&thread->interruption_requested, 1, 0) == 1)
4006 return NULL;
4008 if (!running_managed || is_running_protected_wrapper ()) {
4009 /* Can't stop while in unmanaged code. Increase the global interruption
4010 request count. When exiting the unmanaged method the count will be
4011 checked and the thread will be interrupted. */
4013 InterlockedIncrement (&thread_interruption_requested);
4015 if (mono_thread_notify_pending_exc_fn && !running_managed)
4016 /* The JIT will notify the thread about the interruption */
4017 /* This shouldn't take any locks */
4018 mono_thread_notify_pending_exc_fn ();
4020 /* this will awake the thread if it is in WaitForSingleObject
4021 or similar */
4022 /* Our implementation of this function ignores the func argument */
4023 QueueUserAPC ((PAPCFUNC)dummy_apc, thread->handle, NULL);
4024 return NULL;
4026 else {
4027 return mono_thread_execute_interruption (thread);
4031 /*This function should be called by a thread after it has exited all of
4032 * its handle blocks at interruption time.*/
4033 MonoException*
4034 mono_thread_resume_interruption (void)
4036 MonoInternalThread *thread = mono_thread_internal_current ();
4037 gboolean still_aborting;
4039 /* The thread may already be stopping */
4040 if (thread == NULL)
4041 return NULL;
4043 ensure_synch_cs_set (thread);
4044 EnterCriticalSection (thread->synch_cs);
4045 still_aborting = (thread->state & ThreadState_AbortRequested) != 0;
4046 LeaveCriticalSection (thread->synch_cs);
4048 /*This can happen if the protected block called Thread::ResetAbort*/
4049 if (!still_aborting)
4050 return FALSE;
4052 if (InterlockedCompareExchange (&thread->interruption_requested, 1, 0) == 1)
4053 return NULL;
4054 InterlockedIncrement (&thread_interruption_requested);
4056 #ifndef HOST_WIN32
4057 wapi_self_interrupt ();
4058 #endif
4059 return mono_thread_execute_interruption (thread);
4062 gboolean mono_thread_interruption_requested ()
4064 if (thread_interruption_requested) {
4065 MonoInternalThread *thread = mono_thread_internal_current ();
4066 /* The thread may already be stopping */
4067 if (thread != NULL)
4068 return (thread->interruption_requested);
4070 return FALSE;
4073 static void mono_thread_interruption_checkpoint_request (gboolean bypass_abort_protection)
4075 MonoInternalThread *thread = mono_thread_internal_current ();
4077 /* The thread may already be stopping */
4078 if (thread == NULL)
4079 return;
4081 mono_debugger_check_interruption ();
4083 if (thread->interruption_requested && (bypass_abort_protection || !is_running_protected_wrapper ())) {
4084 MonoException* exc = mono_thread_execute_interruption (thread);
4085 if (exc) mono_raise_exception (exc);
4090 * Performs the interruption of the current thread, if one has been requested,
4091 * and the thread is not running a protected wrapper.
4093 void mono_thread_interruption_checkpoint ()
4095 mono_thread_interruption_checkpoint_request (FALSE);
4099 * Performs the interruption of the current thread, if one has been requested.
4101 void mono_thread_force_interruption_checkpoint ()
4103 mono_thread_interruption_checkpoint_request (TRUE);
4107 * mono_thread_get_and_clear_pending_exception:
4109 * Return any pending exceptions for the current thread and clear it as a side effect.
4111 MonoException*
4112 mono_thread_get_and_clear_pending_exception (void)
4114 MonoInternalThread *thread = mono_thread_internal_current ();
4116 /* The thread may already be stopping */
4117 if (thread == NULL)
4118 return NULL;
4120 if (thread->interruption_requested && !is_running_protected_wrapper ()) {
4121 return mono_thread_execute_interruption (thread);
4124 if (thread->pending_exception) {
4125 MonoException *exc = thread->pending_exception;
4127 thread->pending_exception = NULL;
4128 return exc;
4131 return NULL;
4135 * mono_set_pending_exception:
4137 * Set the pending exception of the current thread to EXC. On platforms which
4138 * support it, the exception will be thrown when execution returns to managed code.
4139 * On other platforms, this function is equivalent to mono_raise_exception ().
4140 * Internal calls which report exceptions using this function instead of
4141 * raise_exception () might be called by JITted code using a more efficient calling
4142 * convention.
4144 void
4145 mono_set_pending_exception (MonoException *exc)
4147 MonoInternalThread *thread = mono_thread_internal_current ();
4149 /* The thread may already be stopping */
4150 if (thread == NULL)
4151 return;
4153 if (mono_thread_notify_pending_exc_fn) {
4154 MONO_OBJECT_SETREF (thread, pending_exception, exc);
4156 mono_thread_notify_pending_exc_fn ();
4157 } else {
4158 /* No way to notify the JIT about the exception, have to throw it now */
4159 mono_raise_exception (exc);
4164 * mono_thread_interruption_request_flag:
4166 * Returns the address of a flag that will be non-zero if an interruption has
4167 * been requested for a thread. The thread to interrupt may not be the current
4168 * thread, so an additional call to mono_thread_interruption_requested() or
4169 * mono_thread_interruption_checkpoint() is allways needed if the flag is not
4170 * zero.
4172 gint32* mono_thread_interruption_request_flag ()
4174 return &thread_interruption_requested;
4177 void
4178 mono_thread_init_apartment_state (void)
4180 #ifdef HOST_WIN32
4181 MonoInternalThread* thread = mono_thread_internal_current ();
4183 /* Positive return value indicates success, either
4184 * S_OK if this is first CoInitialize call, or
4185 * S_FALSE if CoInitialize already called, but with same
4186 * threading model. A negative value indicates failure,
4187 * probably due to trying to change the threading model.
4189 if (CoInitializeEx(NULL, (thread->apartment_state == ThreadApartmentState_STA)
4190 ? COINIT_APARTMENTTHREADED
4191 : COINIT_MULTITHREADED) < 0) {
4192 thread->apartment_state = ThreadApartmentState_Unknown;
4194 #endif
4197 void
4198 mono_thread_cleanup_apartment_state (void)
4200 #ifdef HOST_WIN32
4201 MonoInternalThread* thread = mono_thread_internal_current ();
4203 if (thread && thread->apartment_state != ThreadApartmentState_Unknown) {
4204 CoUninitialize ();
4206 #endif
4209 void
4210 mono_thread_set_state (MonoInternalThread *thread, MonoThreadState state)
4212 ensure_synch_cs_set (thread);
4214 EnterCriticalSection (thread->synch_cs);
4215 thread->state |= state;
4216 LeaveCriticalSection (thread->synch_cs);
4219 void
4220 mono_thread_clr_state (MonoInternalThread *thread, MonoThreadState state)
4222 ensure_synch_cs_set (thread);
4224 EnterCriticalSection (thread->synch_cs);
4225 thread->state &= ~state;
4226 LeaveCriticalSection (thread->synch_cs);
4229 gboolean
4230 mono_thread_test_state (MonoInternalThread *thread, MonoThreadState test)
4232 gboolean ret = FALSE;
4234 ensure_synch_cs_set (thread);
4236 EnterCriticalSection (thread->synch_cs);
4238 if ((thread->state & test) != 0) {
4239 ret = TRUE;
4242 LeaveCriticalSection (thread->synch_cs);
4244 return ret;
4247 static MonoClassField *execution_context_field;
4249 static MonoObject**
4250 get_execution_context_addr (void)
4252 MonoDomain *domain = mono_domain_get ();
4253 guint32 offset;
4255 if (!execution_context_field) {
4256 execution_context_field = mono_class_get_field_from_name (mono_defaults.thread_class,
4257 "_ec");
4258 g_assert (execution_context_field);
4261 g_assert (mono_class_try_get_vtable (domain, mono_defaults.appdomain_class));
4263 mono_domain_lock (domain);
4264 offset = GPOINTER_TO_UINT (g_hash_table_lookup (domain->special_static_fields, execution_context_field));
4265 mono_domain_unlock (domain);
4266 g_assert (offset);
4268 return (MonoObject**) mono_get_special_static_data (offset);
4271 MonoObject*
4272 mono_thread_get_execution_context (void)
4274 return *get_execution_context_addr ();
4277 void
4278 mono_thread_set_execution_context (MonoObject *ec)
4280 *get_execution_context_addr () = ec;
4283 static gboolean has_tls_get = FALSE;
4285 void
4286 mono_runtime_set_has_tls_get (gboolean val)
4288 has_tls_get = val;
4291 gboolean
4292 mono_runtime_has_tls_get (void)
4294 return has_tls_get;