Fix a sgen shutdown crash.
[mono-project.git] / mono / metadata / threads.c
blob11b18a00b6ddf944f534a023c5b67561a24da7f7
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;
1281 gboolean
1282 ves_icall_System_Threading_Thread_Yield (void)
1284 #ifdef HOST_WIN32
1285 return SwitchToThread ();
1286 #else
1287 return sched_yield () == 0;
1288 #endif
1292 * mono_thread_get_name:
1294 * Return the name of the thread. NAME_LEN is set to the length of the name.
1295 * Return NULL if the thread has no name. The returned memory is owned by the
1296 * caller.
1298 gunichar2*
1299 mono_thread_get_name (MonoInternalThread *this_obj, guint32 *name_len)
1301 gunichar2 *res;
1303 ensure_synch_cs_set (this_obj);
1305 EnterCriticalSection (this_obj->synch_cs);
1307 if (!this_obj->name) {
1308 *name_len = 0;
1309 res = NULL;
1310 } else {
1311 *name_len = this_obj->name_len;
1312 res = g_new (gunichar2, this_obj->name_len);
1313 memcpy (res, this_obj->name, sizeof (gunichar2) * this_obj->name_len);
1316 LeaveCriticalSection (this_obj->synch_cs);
1318 return res;
1321 MonoString*
1322 ves_icall_System_Threading_Thread_GetName_internal (MonoInternalThread *this_obj)
1324 MonoString* str;
1326 ensure_synch_cs_set (this_obj);
1328 EnterCriticalSection (this_obj->synch_cs);
1330 if (!this_obj->name)
1331 str = NULL;
1332 else
1333 str = mono_string_new_utf16 (mono_domain_get (), this_obj->name, this_obj->name_len);
1335 LeaveCriticalSection (this_obj->synch_cs);
1337 return str;
1340 void
1341 ves_icall_System_Threading_Thread_SetName_internal (MonoInternalThread *this_obj, MonoString *name)
1343 ensure_synch_cs_set (this_obj);
1345 EnterCriticalSection (this_obj->synch_cs);
1347 if (this_obj->name) {
1348 LeaveCriticalSection (this_obj->synch_cs);
1350 mono_raise_exception (mono_get_exception_invalid_operation ("Thread.Name can only be set once."));
1351 return;
1353 if (name) {
1354 this_obj->name = g_new (gunichar2, mono_string_length (name));
1355 memcpy (this_obj->name, mono_string_chars (name), mono_string_length (name) * 2);
1356 this_obj->name_len = mono_string_length (name);
1358 else
1359 this_obj->name = NULL;
1361 LeaveCriticalSection (this_obj->synch_cs);
1364 static MonoObject*
1365 lookup_cached_culture (MonoInternalThread *this, MonoDomain *domain, int start_idx)
1367 MonoObject *res;
1368 int i;
1370 if (this->cached_culture_info) {
1371 domain = mono_domain_get ();
1372 for (i = start_idx; i < start_idx + NUM_CACHED_CULTURES; ++i) {
1373 res = mono_array_get (this->cached_culture_info, MonoObject*, i);
1374 if (res && res->vtable->domain == domain)
1375 return res;
1379 return NULL;
1382 /* If the array is already in the requested domain, we just return it,
1383 otherwise we return a copy in that domain. */
1384 static MonoArray*
1385 byte_array_to_domain (MonoArray *arr, MonoDomain *domain)
1387 MonoArray *copy;
1389 if (!arr)
1390 return NULL;
1392 if (mono_object_domain (arr) == domain)
1393 return arr;
1395 copy = mono_array_new (domain, mono_defaults.byte_class, arr->max_length);
1396 memcpy (mono_array_addr (copy, guint8, 0), mono_array_addr (arr, guint8, 0), arr->max_length);
1397 return copy;
1400 MonoArray*
1401 ves_icall_System_Threading_Thread_ByteArrayToRootDomain (MonoArray *arr)
1403 return byte_array_to_domain (arr, mono_get_root_domain ());
1406 MonoArray*
1407 ves_icall_System_Threading_Thread_ByteArrayToCurrentDomain (MonoArray *arr)
1409 return byte_array_to_domain (arr, mono_domain_get ());
1412 MonoObject*
1413 ves_icall_System_Threading_Thread_GetCachedCurrentCulture (MonoInternalThread *this)
1415 return lookup_cached_culture (this, mono_domain_get (), CULTURES_START_IDX);
1418 static void
1419 cache_culture (MonoInternalThread *this, MonoObject *culture, int start_idx)
1421 int i;
1422 MonoDomain *domain = mono_domain_get ();
1423 MonoObject *obj;
1424 int free_slot = -1;
1425 int same_domain_slot = -1;
1427 ensure_synch_cs_set (this);
1429 EnterCriticalSection (this->synch_cs);
1431 if (!this->cached_culture_info)
1432 MONO_OBJECT_SETREF (this, cached_culture_info, mono_array_new_cached (mono_get_root_domain (), mono_defaults.object_class, NUM_CACHED_CULTURES * 2));
1434 for (i = start_idx; i < start_idx + NUM_CACHED_CULTURES; ++i) {
1435 obj = mono_array_get (this->cached_culture_info, MonoObject*, i);
1436 /* Free entry */
1437 if (!obj) {
1438 free_slot = i;
1439 /* we continue, because there may be a slot used with the same domain */
1440 continue;
1442 /* Replace */
1443 if (obj->vtable->domain == domain) {
1444 same_domain_slot = i;
1445 break;
1448 if (same_domain_slot >= 0)
1449 mono_array_setref (this->cached_culture_info, same_domain_slot, culture);
1450 else if (free_slot >= 0)
1451 mono_array_setref (this->cached_culture_info, free_slot, culture);
1452 /* we may want to replace an existing entry here, even when no suitable slot is found */
1454 LeaveCriticalSection (this->synch_cs);
1457 void
1458 ves_icall_System_Threading_Thread_SetCachedCurrentCulture (MonoThread *this, MonoObject *culture)
1460 MonoDomain *domain = mono_object_get_domain (&this->obj);
1461 g_assert (domain == mono_domain_get ());
1462 cache_culture (this->internal_thread, culture, CULTURES_START_IDX);
1465 MonoObject*
1466 ves_icall_System_Threading_Thread_GetCachedCurrentUICulture (MonoInternalThread *this)
1468 return lookup_cached_culture (this, mono_domain_get (), UICULTURES_START_IDX);
1471 void
1472 ves_icall_System_Threading_Thread_SetCachedCurrentUICulture (MonoThread *this, MonoObject *culture)
1474 MonoDomain *domain = mono_object_get_domain (&this->obj);
1475 g_assert (domain == mono_domain_get ());
1476 cache_culture (this->internal_thread, culture, UICULTURES_START_IDX);
1479 MonoThread *
1480 mono_thread_current (void)
1482 MonoDomain *domain = mono_domain_get ();
1483 MonoInternalThread *internal = mono_thread_internal_current ();
1484 MonoThread **current_thread_ptr;
1486 g_assert (internal);
1487 current_thread_ptr = get_current_thread_ptr_for_domain (domain, internal);
1489 if (!*current_thread_ptr) {
1490 g_assert (domain != mono_get_root_domain ());
1491 *current_thread_ptr = new_thread_with_internal (domain, internal);
1493 return *current_thread_ptr;
1496 MonoInternalThread*
1497 mono_thread_internal_current (void)
1499 MonoInternalThread *res = GET_CURRENT_OBJECT ();
1500 THREAD_DEBUG (g_message ("%s: returning %p", __func__, res));
1501 return res;
1504 gboolean ves_icall_System_Threading_Thread_Join_internal(MonoInternalThread *this,
1505 int ms, HANDLE thread)
1507 MonoInternalThread *cur_thread = mono_thread_internal_current ();
1508 gboolean ret;
1510 mono_thread_current_check_pending_interrupt ();
1512 ensure_synch_cs_set (this);
1514 EnterCriticalSection (this->synch_cs);
1516 if ((this->state & ThreadState_Unstarted) != 0) {
1517 LeaveCriticalSection (this->synch_cs);
1519 mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started."));
1520 return FALSE;
1523 LeaveCriticalSection (this->synch_cs);
1525 if(ms== -1) {
1526 ms=INFINITE;
1528 THREAD_DEBUG (g_message ("%s: joining thread handle %p, %d ms", __func__, thread, ms));
1530 mono_thread_set_state (cur_thread, ThreadState_WaitSleepJoin);
1532 ret=WaitForSingleObjectEx (thread, ms, TRUE);
1534 mono_thread_clr_state (cur_thread, ThreadState_WaitSleepJoin);
1536 if(ret==WAIT_OBJECT_0) {
1537 THREAD_DEBUG (g_message ("%s: join successful", __func__));
1539 return(TRUE);
1542 THREAD_DEBUG (g_message ("%s: join failed", __func__));
1544 return(FALSE);
1547 /* FIXME: exitContext isnt documented */
1548 gboolean ves_icall_System_Threading_WaitHandle_WaitAll_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext)
1550 HANDLE *handles;
1551 guint32 numhandles;
1552 guint32 ret;
1553 guint32 i;
1554 MonoObject *waitHandle;
1555 MonoInternalThread *thread = mono_thread_internal_current ();
1557 /* Do this WaitSleepJoin check before creating objects */
1558 mono_thread_current_check_pending_interrupt ();
1560 numhandles = mono_array_length(mono_handles);
1561 handles = g_new0(HANDLE, numhandles);
1563 for(i = 0; i < numhandles; i++) {
1564 waitHandle = mono_array_get(mono_handles, MonoObject*, i);
1565 handles [i] = mono_wait_handle_get_handle ((MonoWaitHandle *) waitHandle);
1568 if(ms== -1) {
1569 ms=INFINITE;
1572 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1574 ret=WaitForMultipleObjectsEx(numhandles, handles, TRUE, ms, TRUE);
1576 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1578 g_free(handles);
1580 if(ret==WAIT_FAILED) {
1581 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait failed", __func__, GetCurrentThreadId ()));
1582 return(FALSE);
1583 } else if(ret==WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION) {
1584 /* Do we want to try again if we get
1585 * WAIT_IO_COMPLETION? The documentation for
1586 * WaitHandle doesn't give any clues. (We'd have to
1587 * fiddle with the timeout if we retry.)
1589 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait timed out", __func__, GetCurrentThreadId ()));
1590 return(FALSE);
1593 return(TRUE);
1596 /* FIXME: exitContext isnt documented */
1597 gint32 ves_icall_System_Threading_WaitHandle_WaitAny_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext)
1599 HANDLE *handles;
1600 guint32 numhandles;
1601 guint32 ret;
1602 guint32 i;
1603 MonoObject *waitHandle;
1604 MonoInternalThread *thread = mono_thread_internal_current ();
1606 /* Do this WaitSleepJoin check before creating objects */
1607 mono_thread_current_check_pending_interrupt ();
1609 numhandles = mono_array_length(mono_handles);
1610 handles = g_new0(HANDLE, numhandles);
1612 for(i = 0; i < numhandles; i++) {
1613 waitHandle = mono_array_get(mono_handles, MonoObject*, i);
1614 handles [i] = mono_wait_handle_get_handle ((MonoWaitHandle *) waitHandle);
1617 if(ms== -1) {
1618 ms=INFINITE;
1621 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1623 ret=WaitForMultipleObjectsEx(numhandles, handles, FALSE, ms, TRUE);
1625 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1627 g_free(handles);
1629 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") returning %d", __func__, GetCurrentThreadId (), ret));
1632 * These need to be here. See MSDN dos on WaitForMultipleObjects.
1634 if (ret >= WAIT_OBJECT_0 && ret <= WAIT_OBJECT_0 + numhandles - 1) {
1635 return ret - WAIT_OBJECT_0;
1637 else if (ret >= WAIT_ABANDONED_0 && ret <= WAIT_ABANDONED_0 + numhandles - 1) {
1638 return ret - WAIT_ABANDONED_0;
1640 else {
1641 return ret;
1645 /* FIXME: exitContext isnt documented */
1646 gboolean ves_icall_System_Threading_WaitHandle_WaitOne_internal(MonoObject *this, HANDLE handle, gint32 ms, gboolean exitContext)
1648 guint32 ret;
1649 MonoInternalThread *thread = mono_thread_internal_current ();
1651 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") waiting for %p, %d ms", __func__, GetCurrentThreadId (), handle, ms));
1653 if(ms== -1) {
1654 ms=INFINITE;
1657 mono_thread_current_check_pending_interrupt ();
1659 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1661 ret=WaitForSingleObjectEx (handle, ms, TRUE);
1663 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1665 if(ret==WAIT_FAILED) {
1666 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait failed", __func__, GetCurrentThreadId ()));
1667 return(FALSE);
1668 } else if(ret==WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION) {
1669 /* Do we want to try again if we get
1670 * WAIT_IO_COMPLETION? The documentation for
1671 * WaitHandle doesn't give any clues. (We'd have to
1672 * fiddle with the timeout if we retry.)
1674 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait timed out", __func__, GetCurrentThreadId ()));
1675 return(FALSE);
1678 return(TRUE);
1681 gboolean
1682 ves_icall_System_Threading_WaitHandle_SignalAndWait_Internal (HANDLE toSignal, HANDLE toWait, gint32 ms, gboolean exitContext)
1684 guint32 ret;
1685 MonoInternalThread *thread = mono_thread_internal_current ();
1687 MONO_ARCH_SAVE_REGS;
1689 if (ms == -1)
1690 ms = INFINITE;
1692 mono_thread_current_check_pending_interrupt ();
1694 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1696 ret = SignalObjectAndWait (toSignal, toWait, ms, TRUE);
1698 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1700 return (!(ret == WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION || ret == WAIT_FAILED));
1703 HANDLE ves_icall_System_Threading_Mutex_CreateMutex_internal (MonoBoolean owned, MonoString *name, MonoBoolean *created)
1705 HANDLE mutex;
1707 MONO_ARCH_SAVE_REGS;
1709 *created = TRUE;
1711 if (name == NULL) {
1712 mutex = CreateMutex (NULL, owned, NULL);
1713 } else {
1714 mutex = CreateMutex (NULL, owned, mono_string_chars (name));
1716 if (GetLastError () == ERROR_ALREADY_EXISTS) {
1717 *created = FALSE;
1721 return(mutex);
1724 MonoBoolean ves_icall_System_Threading_Mutex_ReleaseMutex_internal (HANDLE handle ) {
1725 MONO_ARCH_SAVE_REGS;
1727 return(ReleaseMutex (handle));
1730 HANDLE ves_icall_System_Threading_Mutex_OpenMutex_internal (MonoString *name,
1731 gint32 rights,
1732 gint32 *error)
1734 HANDLE ret;
1736 MONO_ARCH_SAVE_REGS;
1738 *error = ERROR_SUCCESS;
1740 ret = OpenMutex (rights, FALSE, mono_string_chars (name));
1741 if (ret == NULL) {
1742 *error = GetLastError ();
1745 return(ret);
1749 HANDLE ves_icall_System_Threading_Semaphore_CreateSemaphore_internal (gint32 initialCount, gint32 maximumCount, MonoString *name, MonoBoolean *created)
1751 HANDLE sem;
1753 MONO_ARCH_SAVE_REGS;
1755 *created = TRUE;
1757 if (name == NULL) {
1758 sem = CreateSemaphore (NULL, initialCount, maximumCount, NULL);
1759 } else {
1760 sem = CreateSemaphore (NULL, initialCount, maximumCount,
1761 mono_string_chars (name));
1763 if (GetLastError () == ERROR_ALREADY_EXISTS) {
1764 *created = FALSE;
1768 return(sem);
1771 gint32 ves_icall_System_Threading_Semaphore_ReleaseSemaphore_internal (HANDLE handle, gint32 releaseCount, MonoBoolean *fail)
1773 gint32 prevcount;
1775 MONO_ARCH_SAVE_REGS;
1777 *fail = !ReleaseSemaphore (handle, releaseCount, &prevcount);
1779 return (prevcount);
1782 HANDLE ves_icall_System_Threading_Semaphore_OpenSemaphore_internal (MonoString *name, gint32 rights, gint32 *error)
1784 HANDLE ret;
1786 MONO_ARCH_SAVE_REGS;
1788 *error = ERROR_SUCCESS;
1790 ret = OpenSemaphore (rights, FALSE, mono_string_chars (name));
1791 if (ret == NULL) {
1792 *error = GetLastError ();
1795 return(ret);
1798 HANDLE ves_icall_System_Threading_Events_CreateEvent_internal (MonoBoolean manual, MonoBoolean initial, MonoString *name, MonoBoolean *created)
1800 HANDLE event;
1802 MONO_ARCH_SAVE_REGS;
1804 *created = TRUE;
1806 if (name == NULL) {
1807 event = CreateEvent (NULL, manual, initial, NULL);
1808 } else {
1809 event = CreateEvent (NULL, manual, initial,
1810 mono_string_chars (name));
1812 if (GetLastError () == ERROR_ALREADY_EXISTS) {
1813 *created = FALSE;
1817 return(event);
1820 gboolean ves_icall_System_Threading_Events_SetEvent_internal (HANDLE handle) {
1821 MONO_ARCH_SAVE_REGS;
1823 return (SetEvent(handle));
1826 gboolean ves_icall_System_Threading_Events_ResetEvent_internal (HANDLE handle) {
1827 MONO_ARCH_SAVE_REGS;
1829 return (ResetEvent(handle));
1832 void
1833 ves_icall_System_Threading_Events_CloseEvent_internal (HANDLE handle) {
1834 MONO_ARCH_SAVE_REGS;
1836 CloseHandle (handle);
1839 HANDLE ves_icall_System_Threading_Events_OpenEvent_internal (MonoString *name,
1840 gint32 rights,
1841 gint32 *error)
1843 HANDLE ret;
1845 MONO_ARCH_SAVE_REGS;
1847 *error = ERROR_SUCCESS;
1849 ret = OpenEvent (rights, FALSE, mono_string_chars (name));
1850 if (ret == NULL) {
1851 *error = GetLastError ();
1854 return(ret);
1857 gint32 ves_icall_System_Threading_Interlocked_Increment_Int (gint32 *location)
1859 MONO_ARCH_SAVE_REGS;
1861 return InterlockedIncrement (location);
1864 gint64 ves_icall_System_Threading_Interlocked_Increment_Long (gint64 *location)
1866 gint64 ret;
1868 MONO_ARCH_SAVE_REGS;
1870 mono_interlocked_lock ();
1872 ret = ++ *location;
1874 mono_interlocked_unlock ();
1877 return ret;
1880 gint32 ves_icall_System_Threading_Interlocked_Decrement_Int (gint32 *location)
1882 MONO_ARCH_SAVE_REGS;
1884 return InterlockedDecrement(location);
1887 gint64 ves_icall_System_Threading_Interlocked_Decrement_Long (gint64 * location)
1889 gint64 ret;
1891 MONO_ARCH_SAVE_REGS;
1893 mono_interlocked_lock ();
1895 ret = -- *location;
1897 mono_interlocked_unlock ();
1899 return ret;
1902 gint32 ves_icall_System_Threading_Interlocked_Exchange_Int (gint32 *location, gint32 value)
1904 MONO_ARCH_SAVE_REGS;
1906 return InterlockedExchange(location, value);
1909 MonoObject * ves_icall_System_Threading_Interlocked_Exchange_Object (MonoObject **location, MonoObject *value)
1911 MonoObject *res;
1912 res = (MonoObject *) InterlockedExchangePointer((gpointer *) location, value);
1913 mono_gc_wbarrier_generic_nostore (location);
1914 return res;
1917 gpointer ves_icall_System_Threading_Interlocked_Exchange_IntPtr (gpointer *location, gpointer value)
1919 return InterlockedExchangePointer(location, value);
1922 gfloat ves_icall_System_Threading_Interlocked_Exchange_Single (gfloat *location, gfloat value)
1924 IntFloatUnion val, ret;
1926 MONO_ARCH_SAVE_REGS;
1928 val.fval = value;
1929 ret.ival = InterlockedExchange((gint32 *) location, val.ival);
1931 return ret.fval;
1934 gint64
1935 ves_icall_System_Threading_Interlocked_Exchange_Long (gint64 *location, gint64 value)
1937 #if SIZEOF_VOID_P == 8
1938 return (gint64) InterlockedExchangePointer((gpointer *) location, (gpointer)value);
1939 #else
1940 gint64 res;
1943 * According to MSDN, this function is only atomic with regards to the
1944 * other Interlocked functions on 32 bit platforms.
1946 mono_interlocked_lock ();
1947 res = *location;
1948 *location = value;
1949 mono_interlocked_unlock ();
1951 return res;
1952 #endif
1955 gdouble
1956 ves_icall_System_Threading_Interlocked_Exchange_Double (gdouble *location, gdouble value)
1958 #if SIZEOF_VOID_P == 8
1959 LongDoubleUnion val, ret;
1961 val.fval = value;
1962 ret.ival = (gint64)InterlockedExchangePointer((gpointer *) location, (gpointer)val.ival);
1964 return ret.fval;
1965 #else
1966 gdouble res;
1969 * According to MSDN, this function is only atomic with regards to the
1970 * other Interlocked functions on 32 bit platforms.
1972 mono_interlocked_lock ();
1973 res = *location;
1974 *location = value;
1975 mono_interlocked_unlock ();
1977 return res;
1978 #endif
1981 gint32 ves_icall_System_Threading_Interlocked_CompareExchange_Int(gint32 *location, gint32 value, gint32 comparand)
1983 MONO_ARCH_SAVE_REGS;
1985 return InterlockedCompareExchange(location, value, comparand);
1988 MonoObject * ves_icall_System_Threading_Interlocked_CompareExchange_Object (MonoObject **location, MonoObject *value, MonoObject *comparand)
1990 MonoObject *res;
1991 res = (MonoObject *) InterlockedCompareExchangePointer((gpointer *) location, value, comparand);
1992 mono_gc_wbarrier_generic_nostore (location);
1993 return res;
1996 gpointer ves_icall_System_Threading_Interlocked_CompareExchange_IntPtr(gpointer *location, gpointer value, gpointer comparand)
1998 return InterlockedCompareExchangePointer(location, value, comparand);
2001 gfloat ves_icall_System_Threading_Interlocked_CompareExchange_Single (gfloat *location, gfloat value, gfloat comparand)
2003 IntFloatUnion val, ret, cmp;
2005 MONO_ARCH_SAVE_REGS;
2007 val.fval = value;
2008 cmp.fval = comparand;
2009 ret.ival = InterlockedCompareExchange((gint32 *) location, val.ival, cmp.ival);
2011 return ret.fval;
2014 gdouble
2015 ves_icall_System_Threading_Interlocked_CompareExchange_Double (gdouble *location, gdouble value, gdouble comparand)
2017 #if SIZEOF_VOID_P == 8
2018 LongDoubleUnion val, comp, ret;
2020 val.fval = value;
2021 comp.fval = comparand;
2022 ret.ival = (gint64)InterlockedCompareExchangePointer((gpointer *) location, (gpointer)val.ival, (gpointer)comp.ival);
2024 return ret.fval;
2025 #else
2026 gdouble old;
2028 mono_interlocked_lock ();
2029 old = *location;
2030 if (old == comparand)
2031 *location = value;
2032 mono_interlocked_unlock ();
2034 return old;
2035 #endif
2038 gint64
2039 ves_icall_System_Threading_Interlocked_CompareExchange_Long (gint64 *location, gint64 value, gint64 comparand)
2041 #if SIZEOF_VOID_P == 8
2042 return (gint64)InterlockedCompareExchangePointer((gpointer *) location, (gpointer)value, (gpointer)comparand);
2043 #else
2044 gint64 old;
2046 mono_interlocked_lock ();
2047 old = *location;
2048 if (old == comparand)
2049 *location = value;
2050 mono_interlocked_unlock ();
2052 return old;
2053 #endif
2056 MonoObject*
2057 ves_icall_System_Threading_Interlocked_CompareExchange_T (MonoObject **location, MonoObject *value, MonoObject *comparand)
2059 MonoObject *res;
2060 res = InterlockedCompareExchangePointer ((gpointer *)location, value, comparand);
2061 mono_gc_wbarrier_generic_nostore (location);
2062 return res;
2065 MonoObject*
2066 ves_icall_System_Threading_Interlocked_Exchange_T (MonoObject **location, MonoObject *value)
2068 MonoObject *res;
2069 res = InterlockedExchangePointer ((gpointer *)location, value);
2070 mono_gc_wbarrier_generic_nostore (location);
2071 return res;
2074 gint32
2075 ves_icall_System_Threading_Interlocked_Add_Int (gint32 *location, gint32 value)
2077 #if SIZEOF_VOID_P == 8
2078 /* Should be implemented as a JIT intrinsic */
2079 mono_raise_exception (mono_get_exception_not_implemented (NULL));
2080 return 0;
2081 #else
2082 gint32 orig;
2084 mono_interlocked_lock ();
2085 orig = *location;
2086 *location = orig + value;
2087 mono_interlocked_unlock ();
2089 return orig + value;
2090 #endif
2093 gint64
2094 ves_icall_System_Threading_Interlocked_Add_Long (gint64 *location, gint64 value)
2096 #if SIZEOF_VOID_P == 8
2097 /* Should be implemented as a JIT intrinsic */
2098 mono_raise_exception (mono_get_exception_not_implemented (NULL));
2099 return 0;
2100 #else
2101 gint64 orig;
2103 mono_interlocked_lock ();
2104 orig = *location;
2105 *location = orig + value;
2106 mono_interlocked_unlock ();
2108 return orig + value;
2109 #endif
2112 gint64
2113 ves_icall_System_Threading_Interlocked_Read_Long (gint64 *location)
2115 #if SIZEOF_VOID_P == 8
2116 /* 64 bit reads are already atomic */
2117 return *location;
2118 #else
2119 gint64 res;
2121 mono_interlocked_lock ();
2122 res = *location;
2123 mono_interlocked_unlock ();
2125 return res;
2126 #endif
2129 void
2130 ves_icall_System_Threading_Thread_MemoryBarrier (void)
2132 mono_threads_lock ();
2133 mono_threads_unlock ();
2136 void
2137 ves_icall_System_Threading_Thread_ClrState (MonoInternalThread* this, guint32 state)
2139 mono_thread_clr_state (this, state);
2141 if (state & ThreadState_Background) {
2142 /* If the thread changes the background mode, the main thread has to
2143 * be notified, since it has to rebuild the list of threads to
2144 * wait for.
2146 SetEvent (background_change_event);
2150 void
2151 ves_icall_System_Threading_Thread_SetState (MonoInternalThread* this, guint32 state)
2153 mono_thread_set_state (this, state);
2155 if (state & ThreadState_Background) {
2156 /* If the thread changes the background mode, the main thread has to
2157 * be notified, since it has to rebuild the list of threads to
2158 * wait for.
2160 SetEvent (background_change_event);
2164 guint32
2165 ves_icall_System_Threading_Thread_GetState (MonoInternalThread* this)
2167 guint32 state;
2169 ensure_synch_cs_set (this);
2171 EnterCriticalSection (this->synch_cs);
2173 state = this->state;
2175 LeaveCriticalSection (this->synch_cs);
2177 return state;
2180 void ves_icall_System_Threading_Thread_Interrupt_internal (MonoInternalThread *this)
2182 gboolean throw = FALSE;
2184 ensure_synch_cs_set (this);
2186 if (this == mono_thread_internal_current ())
2187 return;
2189 EnterCriticalSection (this->synch_cs);
2191 this->thread_interrupt_requested = TRUE;
2193 if (this->state & ThreadState_WaitSleepJoin) {
2194 throw = TRUE;
2197 LeaveCriticalSection (this->synch_cs);
2199 if (throw) {
2200 signal_thread_state_change (this);
2204 void mono_thread_current_check_pending_interrupt ()
2206 MonoInternalThread *thread = mono_thread_internal_current ();
2207 gboolean throw = FALSE;
2209 mono_debugger_check_interruption ();
2211 ensure_synch_cs_set (thread);
2213 EnterCriticalSection (thread->synch_cs);
2215 if (thread->thread_interrupt_requested) {
2216 throw = TRUE;
2217 thread->thread_interrupt_requested = FALSE;
2220 LeaveCriticalSection (thread->synch_cs);
2222 if (throw) {
2223 mono_raise_exception (mono_get_exception_thread_interrupted ());
2227 int
2228 mono_thread_get_abort_signal (void)
2230 #ifdef HOST_WIN32
2231 return -1;
2232 #else
2233 #ifndef SIGRTMIN
2234 #ifdef SIGUSR1
2235 return SIGUSR1;
2236 #else
2237 return -1;
2238 #endif
2239 #else
2240 static int abort_signum = -1;
2241 int i;
2242 if (abort_signum != -1)
2243 return abort_signum;
2244 /* we try to avoid SIGRTMIN and any one that might have been set already, see bug #75387 */
2245 for (i = SIGRTMIN + 1; i < SIGRTMAX; ++i) {
2246 struct sigaction sinfo;
2247 sigaction (i, NULL, &sinfo);
2248 if (sinfo.sa_handler == SIG_DFL && (void*)sinfo.sa_sigaction == (void*)SIG_DFL) {
2249 abort_signum = i;
2250 return i;
2253 /* fallback to the old way */
2254 return SIGRTMIN;
2255 #endif
2256 #endif /* HOST_WIN32 */
2259 #ifdef HOST_WIN32
2260 static void CALLBACK interruption_request_apc (ULONG_PTR param)
2262 MonoException* exc = mono_thread_request_interruption (FALSE);
2263 if (exc) mono_raise_exception (exc);
2265 #endif /* HOST_WIN32 */
2268 * signal_thread_state_change
2270 * Tells the thread that his state has changed and it has to enter the new
2271 * state as soon as possible.
2273 static void signal_thread_state_change (MonoInternalThread *thread)
2275 if (thread == mono_thread_internal_current ()) {
2276 /* Do it synchronously */
2277 MonoException *exc = mono_thread_request_interruption (FALSE);
2278 if (exc)
2279 mono_raise_exception (exc);
2282 #ifdef HOST_WIN32
2283 QueueUserAPC ((PAPCFUNC)interruption_request_apc, thread->handle, NULL);
2284 #else
2285 /* fixme: store the state somewhere */
2286 #ifdef PTHREAD_POINTER_ID
2287 pthread_kill ((gpointer)(gsize)(thread->tid), mono_thread_get_abort_signal ());
2288 #else
2289 pthread_kill (thread->tid, mono_thread_get_abort_signal ());
2290 #endif
2293 * This will cause waits to be broken.
2294 * It will also prevent the thread from entering a wait, so if the thread returns
2295 * from the wait before it receives the abort signal, it will just spin in the wait
2296 * functions in the io-layer until the signal handler calls QueueUserAPC which will
2297 * make it return.
2299 wapi_interrupt_thread (thread->handle);
2300 #endif /* HOST_WIN32 */
2303 void
2304 ves_icall_System_Threading_Thread_Abort (MonoInternalThread *thread, MonoObject *state)
2306 ensure_synch_cs_set (thread);
2308 EnterCriticalSection (thread->synch_cs);
2310 if ((thread->state & ThreadState_AbortRequested) != 0 ||
2311 (thread->state & ThreadState_StopRequested) != 0 ||
2312 (thread->state & ThreadState_Stopped) != 0)
2314 LeaveCriticalSection (thread->synch_cs);
2315 return;
2318 if ((thread->state & ThreadState_Unstarted) != 0) {
2319 thread->state |= ThreadState_Aborted;
2320 LeaveCriticalSection (thread->synch_cs);
2321 return;
2324 thread->state |= ThreadState_AbortRequested;
2325 if (thread->abort_state_handle)
2326 mono_gchandle_free (thread->abort_state_handle);
2327 if (state) {
2328 thread->abort_state_handle = mono_gchandle_new (state, FALSE);
2329 g_assert (thread->abort_state_handle);
2330 } else {
2331 thread->abort_state_handle = 0;
2333 thread->abort_exc = NULL;
2336 * abort_exc is set in mono_thread_execute_interruption(),
2337 * triggered by the call to signal_thread_state_change(),
2338 * below. There's a point between where we have
2339 * abort_state_handle set, but abort_exc NULL, but that's not
2340 * a problem.
2343 LeaveCriticalSection (thread->synch_cs);
2345 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Abort requested for %p (%"G_GSIZE_FORMAT")", __func__, GetCurrentThreadId (), thread, (gsize)thread->tid));
2347 /* During shutdown, we can't wait for other threads */
2348 if (!shutting_down)
2349 /* Make sure the thread is awake */
2350 mono_thread_resume (thread);
2352 signal_thread_state_change (thread);
2355 void
2356 ves_icall_System_Threading_Thread_ResetAbort (void)
2358 MonoInternalThread *thread = mono_thread_internal_current ();
2359 gboolean was_aborting;
2361 ensure_synch_cs_set (thread);
2363 EnterCriticalSection (thread->synch_cs);
2364 was_aborting = thread->state & ThreadState_AbortRequested;
2365 thread->state &= ~ThreadState_AbortRequested;
2366 LeaveCriticalSection (thread->synch_cs);
2368 if (!was_aborting) {
2369 const char *msg = "Unable to reset abort because no abort was requested";
2370 mono_raise_exception (mono_get_exception_thread_state (msg));
2372 thread->abort_exc = NULL;
2373 if (thread->abort_state_handle) {
2374 mono_gchandle_free (thread->abort_state_handle);
2375 /* This is actually not necessary - the handle
2376 only counts if the exception is set */
2377 thread->abort_state_handle = 0;
2381 void
2382 mono_thread_internal_reset_abort (MonoInternalThread *thread)
2384 ensure_synch_cs_set (thread);
2386 EnterCriticalSection (thread->synch_cs);
2388 thread->state &= ~ThreadState_AbortRequested;
2390 if (thread->abort_exc) {
2391 thread->abort_exc = NULL;
2392 if (thread->abort_state_handle) {
2393 mono_gchandle_free (thread->abort_state_handle);
2394 /* This is actually not necessary - the handle
2395 only counts if the exception is set */
2396 thread->abort_state_handle = 0;
2400 LeaveCriticalSection (thread->synch_cs);
2403 MonoObject*
2404 ves_icall_System_Threading_Thread_GetAbortExceptionState (MonoThread *this)
2406 MonoInternalThread *thread = this->internal_thread;
2407 MonoObject *state, *deserialized = NULL, *exc;
2408 MonoDomain *domain;
2410 if (!thread->abort_state_handle)
2411 return NULL;
2413 state = mono_gchandle_get_target (thread->abort_state_handle);
2414 g_assert (state);
2416 domain = mono_domain_get ();
2417 if (mono_object_domain (state) == domain)
2418 return state;
2420 deserialized = mono_object_xdomain_representation (state, domain, &exc);
2422 if (!deserialized) {
2423 MonoException *invalid_op_exc = mono_get_exception_invalid_operation ("Thread.ExceptionState cannot access an ExceptionState from a different AppDomain");
2424 if (exc)
2425 MONO_OBJECT_SETREF (invalid_op_exc, inner_ex, exc);
2426 mono_raise_exception (invalid_op_exc);
2429 return deserialized;
2432 static gboolean
2433 mono_thread_suspend (MonoInternalThread *thread)
2435 ensure_synch_cs_set (thread);
2437 EnterCriticalSection (thread->synch_cs);
2439 if ((thread->state & ThreadState_Unstarted) != 0 ||
2440 (thread->state & ThreadState_Aborted) != 0 ||
2441 (thread->state & ThreadState_Stopped) != 0)
2443 LeaveCriticalSection (thread->synch_cs);
2444 return FALSE;
2447 if ((thread->state & ThreadState_Suspended) != 0 ||
2448 (thread->state & ThreadState_SuspendRequested) != 0 ||
2449 (thread->state & ThreadState_StopRequested) != 0)
2451 LeaveCriticalSection (thread->synch_cs);
2452 return TRUE;
2455 thread->state |= ThreadState_SuspendRequested;
2457 LeaveCriticalSection (thread->synch_cs);
2459 signal_thread_state_change (thread);
2460 return TRUE;
2463 void
2464 ves_icall_System_Threading_Thread_Suspend (MonoInternalThread *thread)
2466 if (!mono_thread_suspend (thread))
2467 mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started, or is dead."));
2470 static gboolean
2471 mono_thread_resume (MonoInternalThread *thread)
2473 ensure_synch_cs_set (thread);
2475 EnterCriticalSection (thread->synch_cs);
2477 if ((thread->state & ThreadState_SuspendRequested) != 0) {
2478 thread->state &= ~ThreadState_SuspendRequested;
2479 LeaveCriticalSection (thread->synch_cs);
2480 return TRUE;
2483 if ((thread->state & ThreadState_Suspended) == 0 ||
2484 (thread->state & ThreadState_Unstarted) != 0 ||
2485 (thread->state & ThreadState_Aborted) != 0 ||
2486 (thread->state & ThreadState_Stopped) != 0)
2488 LeaveCriticalSection (thread->synch_cs);
2489 return FALSE;
2492 thread->resume_event = CreateEvent (NULL, TRUE, FALSE, NULL);
2493 if (thread->resume_event == NULL) {
2494 LeaveCriticalSection (thread->synch_cs);
2495 return(FALSE);
2498 /* Awake the thread */
2499 SetEvent (thread->suspend_event);
2501 LeaveCriticalSection (thread->synch_cs);
2503 /* Wait for the thread to awake */
2504 WaitForSingleObject (thread->resume_event, INFINITE);
2505 CloseHandle (thread->resume_event);
2506 thread->resume_event = NULL;
2508 return TRUE;
2511 void
2512 ves_icall_System_Threading_Thread_Resume (MonoThread *thread)
2514 if (!thread->internal_thread || !mono_thread_resume (thread->internal_thread))
2515 mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started, or is dead."));
2518 static gboolean
2519 find_wrapper (MonoMethod *m, gint no, gint ilo, gboolean managed, gpointer data)
2521 if (managed)
2522 return TRUE;
2524 if (m->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE ||
2525 m->wrapper_type == MONO_WRAPPER_XDOMAIN_INVOKE ||
2526 m->wrapper_type == MONO_WRAPPER_XDOMAIN_DISPATCH)
2528 *((gboolean*)data) = TRUE;
2529 return TRUE;
2531 return FALSE;
2534 static gboolean
2535 is_running_protected_wrapper (void)
2537 gboolean found = FALSE;
2538 mono_stack_walk (find_wrapper, &found);
2539 return found;
2542 void mono_thread_internal_stop (MonoInternalThread *thread)
2544 ensure_synch_cs_set (thread);
2546 EnterCriticalSection (thread->synch_cs);
2548 if ((thread->state & ThreadState_StopRequested) != 0 ||
2549 (thread->state & ThreadState_Stopped) != 0)
2551 LeaveCriticalSection (thread->synch_cs);
2552 return;
2555 /* Make sure the thread is awake */
2556 mono_thread_resume (thread);
2558 thread->state |= ThreadState_StopRequested;
2559 thread->state &= ~ThreadState_AbortRequested;
2561 LeaveCriticalSection (thread->synch_cs);
2563 signal_thread_state_change (thread);
2566 void mono_thread_stop (MonoThread *thread)
2568 mono_thread_internal_stop (thread->internal_thread);
2571 gint8
2572 ves_icall_System_Threading_Thread_VolatileRead1 (void *ptr)
2574 return *((volatile gint8 *) (ptr));
2577 gint16
2578 ves_icall_System_Threading_Thread_VolatileRead2 (void *ptr)
2580 return *((volatile gint16 *) (ptr));
2583 gint32
2584 ves_icall_System_Threading_Thread_VolatileRead4 (void *ptr)
2586 return *((volatile gint32 *) (ptr));
2589 gint64
2590 ves_icall_System_Threading_Thread_VolatileRead8 (void *ptr)
2592 return *((volatile gint64 *) (ptr));
2595 void *
2596 ves_icall_System_Threading_Thread_VolatileReadIntPtr (void *ptr)
2598 return (void *) *((volatile void **) ptr);
2601 void
2602 ves_icall_System_Threading_Thread_VolatileWrite1 (void *ptr, gint8 value)
2604 *((volatile gint8 *) ptr) = value;
2607 void
2608 ves_icall_System_Threading_Thread_VolatileWrite2 (void *ptr, gint16 value)
2610 *((volatile gint16 *) ptr) = value;
2613 void
2614 ves_icall_System_Threading_Thread_VolatileWrite4 (void *ptr, gint32 value)
2616 *((volatile gint32 *) ptr) = value;
2619 void
2620 ves_icall_System_Threading_Thread_VolatileWrite8 (void *ptr, gint64 value)
2622 *((volatile gint64 *) ptr) = value;
2625 void
2626 ves_icall_System_Threading_Thread_VolatileWriteIntPtr (void *ptr, void *value)
2628 *((volatile void **) ptr) = value;
2631 void
2632 ves_icall_System_Threading_Thread_VolatileWriteObject (void *ptr, void *value)
2634 mono_gc_wbarrier_generic_store (ptr, value);
2637 void mono_thread_init (MonoThreadStartCB start_cb,
2638 MonoThreadAttachCB attach_cb)
2640 MONO_GC_REGISTER_ROOT (small_id_table);
2641 InitializeCriticalSection(&threads_mutex);
2642 InitializeCriticalSection(&interlocked_mutex);
2643 InitializeCriticalSection(&contexts_mutex);
2644 InitializeCriticalSection(&delayed_free_table_mutex);
2645 InitializeCriticalSection(&small_id_mutex);
2647 background_change_event = CreateEvent (NULL, TRUE, FALSE, NULL);
2648 g_assert(background_change_event != NULL);
2650 mono_init_static_data_info (&thread_static_info);
2651 mono_init_static_data_info (&context_static_info);
2653 current_object_key=TlsAlloc();
2654 THREAD_DEBUG (g_message ("%s: Allocated current_object_key %d", __func__, current_object_key));
2656 mono_thread_start_cb = start_cb;
2657 mono_thread_attach_cb = attach_cb;
2659 delayed_free_table = g_array_new (FALSE, FALSE, sizeof (DelayedFreeItem));
2661 /* Get a pseudo handle to the current process. This is just a
2662 * kludge so that wapi can build a process handle if needed.
2663 * As a pseudo handle is returned, we don't need to clean
2664 * anything up.
2666 GetCurrentProcess ();
2669 void mono_thread_cleanup (void)
2671 mono_thread_hazardous_try_free_all ();
2673 #if !defined(HOST_WIN32) && !defined(RUN_IN_SUBTHREAD)
2674 /* The main thread must abandon any held mutexes (particularly
2675 * important for named mutexes as they are shared across
2676 * processes, see bug 74680.) This will happen when the
2677 * thread exits, but if it's not running in a subthread it
2678 * won't exit in time.
2680 /* Using non-w32 API is a nasty kludge, but I couldn't find
2681 * anything in the documentation that would let me do this
2682 * here yet still be safe to call on windows.
2684 _wapi_thread_signal_self (mono_environment_exitcode_get ());
2685 #endif
2687 #if 0
2688 /* This stuff needs more testing, it seems one of these
2689 * critical sections can be locked when mono_thread_cleanup is
2690 * called.
2692 DeleteCriticalSection (&threads_mutex);
2693 DeleteCriticalSection (&interlocked_mutex);
2694 DeleteCriticalSection (&contexts_mutex);
2695 DeleteCriticalSection (&delayed_free_table_mutex);
2696 DeleteCriticalSection (&small_id_mutex);
2697 CloseHandle (background_change_event);
2698 #endif
2700 g_array_free (delayed_free_table, TRUE);
2701 delayed_free_table = NULL;
2703 TlsFree (current_object_key);
2706 void
2707 mono_threads_install_cleanup (MonoThreadCleanupFunc func)
2709 mono_thread_cleanup_fn = func;
2712 void
2713 mono_thread_set_manage_callback (MonoThread *thread, MonoThreadManageCallback func)
2715 thread->internal_thread->manage_callback = func;
2718 void mono_threads_install_notify_pending_exc (MonoThreadNotifyPendingExcFunc func)
2720 mono_thread_notify_pending_exc_fn = func;
2723 G_GNUC_UNUSED
2724 static void print_tids (gpointer key, gpointer value, gpointer user)
2726 /* GPOINTER_TO_UINT breaks horribly if sizeof(void *) >
2727 * sizeof(uint) and a cast to uint would overflow
2729 /* Older versions of glib don't have G_GSIZE_FORMAT, so just
2730 * print this as a pointer.
2732 g_message ("Waiting for: %p", key);
2735 struct wait_data
2737 HANDLE handles[MAXIMUM_WAIT_OBJECTS];
2738 MonoInternalThread *threads[MAXIMUM_WAIT_OBJECTS];
2739 guint32 num;
2742 static void wait_for_tids (struct wait_data *wait, guint32 timeout)
2744 guint32 i, ret;
2746 THREAD_DEBUG (g_message("%s: %d threads to wait for in this batch", __func__, wait->num));
2748 ret=WaitForMultipleObjectsEx(wait->num, wait->handles, TRUE, timeout, TRUE);
2750 if(ret==WAIT_FAILED) {
2751 /* See the comment in build_wait_tids() */
2752 THREAD_DEBUG (g_message ("%s: Wait failed", __func__));
2753 return;
2756 for(i=0; i<wait->num; i++)
2757 CloseHandle (wait->handles[i]);
2759 if (ret == WAIT_TIMEOUT)
2760 return;
2762 for(i=0; i<wait->num; i++) {
2763 gsize tid = wait->threads[i]->tid;
2765 mono_threads_lock ();
2766 if(mono_g_hash_table_lookup (threads, (gpointer)tid)!=NULL) {
2767 /* This thread must have been killed, because
2768 * it hasn't cleaned itself up. (It's just
2769 * possible that the thread exited before the
2770 * parent thread had a chance to store the
2771 * handle, and now there is another pointer to
2772 * the already-exited thread stored. In this
2773 * case, we'll just get two
2774 * mono_profiler_thread_end() calls for the
2775 * same thread.)
2778 mono_threads_unlock ();
2779 THREAD_DEBUG (g_message ("%s: cleaning up after thread %p (%"G_GSIZE_FORMAT")", __func__, wait->threads[i], tid));
2780 thread_cleanup (wait->threads[i]);
2781 } else {
2782 mono_threads_unlock ();
2787 static void wait_for_tids_or_state_change (struct wait_data *wait, guint32 timeout)
2789 guint32 i, ret, count;
2791 THREAD_DEBUG (g_message("%s: %d threads to wait for in this batch", __func__, wait->num));
2793 /* Add the thread state change event, so it wakes up if a thread changes
2794 * to background mode.
2796 count = wait->num;
2797 if (count < MAXIMUM_WAIT_OBJECTS) {
2798 wait->handles [count] = background_change_event;
2799 count++;
2802 ret=WaitForMultipleObjectsEx (count, wait->handles, FALSE, timeout, TRUE);
2804 if(ret==WAIT_FAILED) {
2805 /* See the comment in build_wait_tids() */
2806 THREAD_DEBUG (g_message ("%s: Wait failed", __func__));
2807 return;
2810 for(i=0; i<wait->num; i++)
2811 CloseHandle (wait->handles[i]);
2813 if (ret == WAIT_TIMEOUT)
2814 return;
2816 if (ret < wait->num) {
2817 gsize tid = wait->threads[ret]->tid;
2818 mono_threads_lock ();
2819 if (mono_g_hash_table_lookup (threads, (gpointer)tid)!=NULL) {
2820 /* See comment in wait_for_tids about thread cleanup */
2821 mono_threads_unlock ();
2822 THREAD_DEBUG (g_message ("%s: cleaning up after thread %"G_GSIZE_FORMAT, __func__, tid));
2823 thread_cleanup (wait->threads [ret]);
2824 } else
2825 mono_threads_unlock ();
2829 static void build_wait_tids (gpointer key, gpointer value, gpointer user)
2831 struct wait_data *wait=(struct wait_data *)user;
2833 if(wait->num<MAXIMUM_WAIT_OBJECTS) {
2834 HANDLE handle;
2835 MonoInternalThread *thread=(MonoInternalThread *)value;
2837 /* Ignore background threads, we abort them later */
2838 /* Do not lock here since it is not needed and the caller holds threads_lock */
2839 if (thread->state & ThreadState_Background) {
2840 THREAD_DEBUG (g_message ("%s: ignoring background thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2841 return; /* just leave, ignore */
2844 if (mono_gc_is_finalizer_internal_thread (thread)) {
2845 THREAD_DEBUG (g_message ("%s: ignoring finalizer thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2846 return;
2849 if (thread == mono_thread_internal_current ()) {
2850 THREAD_DEBUG (g_message ("%s: ignoring current thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2851 return;
2854 if (mono_thread_get_main () && (thread == mono_thread_get_main ()->internal_thread)) {
2855 THREAD_DEBUG (g_message ("%s: ignoring main thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2856 return;
2859 if (thread->flags & MONO_THREAD_FLAG_DONT_MANAGE) {
2860 THREAD_DEBUG (g_message ("%s: ignoring thread %" G_GSIZE_FORMAT "with DONT_MANAGE flag set.", __func__, (gsize)thread->tid));
2861 return;
2864 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
2865 if (handle == NULL) {
2866 THREAD_DEBUG (g_message ("%s: ignoring unopenable thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2867 return;
2870 THREAD_DEBUG (g_message ("%s: Invoking mono_thread_manage callback on thread %p", __func__, thread));
2871 if ((thread->manage_callback == NULL) || (thread->manage_callback (thread->root_domain_thread) == TRUE)) {
2872 wait->handles[wait->num]=handle;
2873 wait->threads[wait->num]=thread;
2874 wait->num++;
2876 THREAD_DEBUG (g_message ("%s: adding thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2877 } else {
2878 THREAD_DEBUG (g_message ("%s: ignoring (because of callback) thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2882 } else {
2883 /* Just ignore the rest, we can't do anything with
2884 * them yet
2889 static gboolean
2890 remove_and_abort_threads (gpointer key, gpointer value, gpointer user)
2892 struct wait_data *wait=(struct wait_data *)user;
2893 gsize self = GetCurrentThreadId ();
2894 MonoInternalThread *thread = value;
2895 HANDLE handle;
2897 if (wait->num >= MAXIMUM_WAIT_OBJECTS)
2898 return FALSE;
2900 /* The finalizer thread is not a background thread */
2901 if (thread->tid != self && (thread->state & ThreadState_Background) != 0 &&
2902 !(thread->flags & MONO_THREAD_FLAG_DONT_MANAGE)) {
2904 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
2905 if (handle == NULL)
2906 return FALSE;
2908 /* printf ("A: %d\n", wait->num); */
2909 wait->handles[wait->num]=thread->handle;
2910 wait->threads[wait->num]=thread;
2911 wait->num++;
2913 THREAD_DEBUG (g_print ("%s: Aborting id: %"G_GSIZE_FORMAT"\n", __func__, (gsize)thread->tid));
2914 mono_thread_internal_stop (thread);
2915 return TRUE;
2918 return (thread->tid != self && !mono_gc_is_finalizer_internal_thread (thread));
2921 /**
2922 * mono_threads_set_shutting_down:
2924 * Is called by a thread that wants to shut down Mono. If the runtime is already
2925 * shutting down, the calling thread is suspended/stopped, and this function never
2926 * returns.
2928 void
2929 mono_threads_set_shutting_down (void)
2931 MonoInternalThread *current_thread = mono_thread_internal_current ();
2933 mono_threads_lock ();
2935 if (shutting_down) {
2936 mono_threads_unlock ();
2938 /* Make sure we're properly suspended/stopped */
2940 EnterCriticalSection (current_thread->synch_cs);
2942 if ((current_thread->state & ThreadState_SuspendRequested) ||
2943 (current_thread->state & ThreadState_AbortRequested) ||
2944 (current_thread->state & ThreadState_StopRequested)) {
2945 LeaveCriticalSection (current_thread->synch_cs);
2946 mono_thread_execute_interruption (current_thread);
2947 } else {
2948 current_thread->state |= ThreadState_Stopped;
2949 LeaveCriticalSection (current_thread->synch_cs);
2952 /* Wake up other threads potentially waiting for us */
2953 ExitThread (0);
2954 } else {
2955 shutting_down = TRUE;
2957 /* Not really a background state change, but this will
2958 * interrupt the main thread if it is waiting for all
2959 * the other threads.
2961 SetEvent (background_change_event);
2963 mono_threads_unlock ();
2967 /**
2968 * mono_threads_is_shutting_down:
2970 * Returns whether a thread has commenced shutdown of Mono. Note that
2971 * if the function returns FALSE the caller must not assume that
2972 * shutdown is not in progress, because the situation might have
2973 * changed since the function returned. For that reason this function
2974 * is of very limited utility.
2976 gboolean
2977 mono_threads_is_shutting_down (void)
2979 return shutting_down;
2982 void mono_thread_manage (void)
2984 struct wait_data wait_data;
2985 struct wait_data *wait = &wait_data;
2987 memset (wait, 0, sizeof (struct wait_data));
2988 /* join each thread that's still running */
2989 THREAD_DEBUG (g_message ("%s: Joining each running thread...", __func__));
2991 mono_threads_lock ();
2992 if(threads==NULL) {
2993 THREAD_DEBUG (g_message("%s: No threads", __func__));
2994 mono_threads_unlock ();
2995 return;
2997 mono_threads_unlock ();
2999 do {
3000 mono_threads_lock ();
3001 if (shutting_down) {
3002 /* somebody else is shutting down */
3003 mono_threads_unlock ();
3004 break;
3006 THREAD_DEBUG (g_message ("%s: There are %d threads to join", __func__, mono_g_hash_table_size (threads));
3007 mono_g_hash_table_foreach (threads, print_tids, NULL));
3009 ResetEvent (background_change_event);
3010 wait->num=0;
3011 /*We must zero all InternalThread pointers to avoid making the GC unhappy.*/
3012 memset (wait->threads, 0, MAXIMUM_WAIT_OBJECTS * SIZEOF_VOID_P);
3013 mono_g_hash_table_foreach (threads, build_wait_tids, wait);
3014 mono_threads_unlock ();
3015 if(wait->num>0) {
3016 /* Something to wait for */
3017 wait_for_tids_or_state_change (wait, INFINITE);
3019 THREAD_DEBUG (g_message ("%s: I have %d threads after waiting.", __func__, wait->num));
3020 } while(wait->num>0);
3022 mono_threads_set_shutting_down ();
3024 /* No new threads will be created after this point */
3026 mono_runtime_set_shutting_down ();
3028 THREAD_DEBUG (g_message ("%s: threadpool cleanup", __func__));
3029 mono_thread_pool_cleanup ();
3032 * Remove everything but the finalizer thread and self.
3033 * Also abort all the background threads
3034 * */
3035 do {
3036 mono_threads_lock ();
3038 wait->num = 0;
3039 /*We must zero all InternalThread pointers to avoid making the GC unhappy.*/
3040 memset (wait->threads, 0, MAXIMUM_WAIT_OBJECTS * SIZEOF_VOID_P);
3041 mono_g_hash_table_foreach_remove (threads, remove_and_abort_threads, wait);
3043 mono_threads_unlock ();
3045 THREAD_DEBUG (g_message ("%s: wait->num is now %d", __func__, wait->num));
3046 if(wait->num>0) {
3047 /* Something to wait for */
3048 wait_for_tids (wait, INFINITE);
3050 } while (wait->num > 0);
3053 * give the subthreads a chance to really quit (this is mainly needed
3054 * to get correct user and system times from getrusage/wait/time(1)).
3055 * This could be removed if we avoid pthread_detach() and use pthread_join().
3057 #ifndef HOST_WIN32
3058 sched_yield ();
3059 #endif
3062 static void terminate_thread (gpointer key, gpointer value, gpointer user)
3064 MonoInternalThread *thread=(MonoInternalThread *)value;
3066 if(thread->tid != (gsize)user) {
3067 /*TerminateThread (thread->handle, -1);*/
3071 void mono_thread_abort_all_other_threads (void)
3073 gsize self = GetCurrentThreadId ();
3075 mono_threads_lock ();
3076 THREAD_DEBUG (g_message ("%s: There are %d threads to abort", __func__,
3077 mono_g_hash_table_size (threads));
3078 mono_g_hash_table_foreach (threads, print_tids, NULL));
3080 mono_g_hash_table_foreach (threads, terminate_thread, (gpointer)self);
3082 mono_threads_unlock ();
3085 static void
3086 collect_threads_for_suspend (gpointer key, gpointer value, gpointer user_data)
3088 MonoInternalThread *thread = (MonoInternalThread*)value;
3089 struct wait_data *wait = (struct wait_data*)user_data;
3090 HANDLE handle;
3093 * We try to exclude threads early, to avoid running into the MAXIMUM_WAIT_OBJECTS
3094 * limitation.
3095 * This needs no locking.
3097 if ((thread->state & ThreadState_Suspended) != 0 ||
3098 (thread->state & ThreadState_Stopped) != 0)
3099 return;
3101 if (wait->num<MAXIMUM_WAIT_OBJECTS) {
3102 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
3103 if (handle == NULL)
3104 return;
3106 wait->handles [wait->num] = handle;
3107 wait->threads [wait->num] = thread;
3108 wait->num++;
3113 * mono_thread_suspend_all_other_threads:
3115 * Suspend all managed threads except the finalizer thread and this thread. It is
3116 * not possible to resume them later.
3118 void mono_thread_suspend_all_other_threads (void)
3120 struct wait_data wait_data;
3121 struct wait_data *wait = &wait_data;
3122 int i;
3123 gsize self = GetCurrentThreadId ();
3124 gpointer *events;
3125 guint32 eventidx = 0;
3126 gboolean starting, finished;
3128 memset (wait, 0, sizeof (struct wait_data));
3130 * The other threads could be in an arbitrary state at this point, i.e.
3131 * they could be starting up, shutting down etc. This means that there could be
3132 * threads which are not even in the threads hash table yet.
3136 * First we set a barrier which will be checked by all threads before they
3137 * are added to the threads hash table, and they will exit if the flag is set.
3138 * This ensures that no threads could be added to the hash later.
3139 * We will use shutting_down as the barrier for now.
3141 g_assert (shutting_down);
3144 * We make multiple calls to WaitForMultipleObjects since:
3145 * - we can only wait for MAXIMUM_WAIT_OBJECTS threads
3146 * - some threads could exit without becoming suspended
3148 finished = FALSE;
3149 while (!finished) {
3151 * Make a copy of the hashtable since we can't do anything with
3152 * threads while threads_mutex is held.
3154 wait->num = 0;
3155 /*We must zero all InternalThread pointers to avoid making the GC unhappy.*/
3156 memset (wait->threads, 0, MAXIMUM_WAIT_OBJECTS * SIZEOF_VOID_P);
3157 mono_threads_lock ();
3158 mono_g_hash_table_foreach (threads, collect_threads_for_suspend, wait);
3159 mono_threads_unlock ();
3161 events = g_new0 (gpointer, wait->num);
3162 eventidx = 0;
3163 /* Get the suspended events that we'll be waiting for */
3164 for (i = 0; i < wait->num; ++i) {
3165 MonoInternalThread *thread = wait->threads [i];
3166 gboolean signal_suspend = FALSE;
3168 if ((thread->tid == self) || mono_gc_is_finalizer_internal_thread (thread) || (thread->flags & MONO_THREAD_FLAG_DONT_MANAGE)) {
3169 //CloseHandle (wait->handles [i]);
3170 wait->threads [i] = NULL; /* ignore this thread in next loop */
3171 continue;
3174 ensure_synch_cs_set (thread);
3176 EnterCriticalSection (thread->synch_cs);
3178 if (thread->suspended_event == NULL) {
3179 thread->suspended_event = CreateEvent (NULL, TRUE, FALSE, NULL);
3180 if (thread->suspended_event == NULL) {
3181 /* Forget this one and go on to the next */
3182 LeaveCriticalSection (thread->synch_cs);
3183 continue;
3187 if ((thread->state & ThreadState_Suspended) != 0 ||
3188 (thread->state & ThreadState_StopRequested) != 0 ||
3189 (thread->state & ThreadState_Stopped) != 0) {
3190 LeaveCriticalSection (thread->synch_cs);
3191 CloseHandle (wait->handles [i]);
3192 wait->threads [i] = NULL; /* ignore this thread in next loop */
3193 continue;
3196 if ((thread->state & ThreadState_SuspendRequested) == 0)
3197 signal_suspend = TRUE;
3199 events [eventidx++] = thread->suspended_event;
3201 /* Convert abort requests into suspend requests */
3202 if ((thread->state & ThreadState_AbortRequested) != 0)
3203 thread->state &= ~ThreadState_AbortRequested;
3205 thread->state |= ThreadState_SuspendRequested;
3207 LeaveCriticalSection (thread->synch_cs);
3209 /* Signal the thread to suspend */
3210 if (signal_suspend)
3211 signal_thread_state_change (thread);
3214 if (eventidx > 0) {
3215 WaitForMultipleObjectsEx (eventidx, events, TRUE, 100, FALSE);
3216 for (i = 0; i < wait->num; ++i) {
3217 MonoInternalThread *thread = wait->threads [i];
3219 if (thread == NULL)
3220 continue;
3222 ensure_synch_cs_set (thread);
3224 EnterCriticalSection (thread->synch_cs);
3225 if ((thread->state & ThreadState_Suspended) != 0) {
3226 CloseHandle (thread->suspended_event);
3227 thread->suspended_event = NULL;
3229 LeaveCriticalSection (thread->synch_cs);
3231 } else {
3233 * If there are threads which are starting up, we wait until they
3234 * are suspended when they try to register in the threads hash.
3235 * This is guaranteed to finish, since the threads which can create new
3236 * threads get suspended after a while.
3237 * FIXME: The finalizer thread can still create new threads.
3239 mono_threads_lock ();
3240 if (threads_starting_up)
3241 starting = mono_g_hash_table_size (threads_starting_up) > 0;
3242 else
3243 starting = FALSE;
3244 mono_threads_unlock ();
3245 if (starting)
3246 Sleep (100);
3247 else
3248 finished = TRUE;
3251 g_free (events);
3255 static void
3256 collect_threads (gpointer key, gpointer value, gpointer user_data)
3258 MonoInternalThread *thread = (MonoInternalThread*)value;
3259 struct wait_data *wait = (struct wait_data*)user_data;
3260 HANDLE handle;
3262 if (wait->num<MAXIMUM_WAIT_OBJECTS) {
3263 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
3264 if (handle == NULL)
3265 return;
3267 wait->handles [wait->num] = handle;
3268 wait->threads [wait->num] = thread;
3269 wait->num++;
3274 * mono_threads_request_thread_dump:
3276 * Ask all threads except the current to print their stacktrace to stdout.
3278 void
3279 mono_threads_request_thread_dump (void)
3281 struct wait_data wait_data;
3282 struct wait_data *wait = &wait_data;
3283 int i;
3285 memset (wait, 0, sizeof (struct wait_data));
3288 * Make a copy of the hashtable since we can't do anything with
3289 * threads while threads_mutex is held.
3291 mono_threads_lock ();
3292 mono_g_hash_table_foreach (threads, collect_threads, wait);
3293 mono_threads_unlock ();
3295 for (i = 0; i < wait->num; ++i) {
3296 MonoInternalThread *thread = wait->threads [i];
3298 if (!mono_gc_is_finalizer_internal_thread (thread) &&
3299 (thread != mono_thread_internal_current ()) &&
3300 !thread->thread_dump_requested) {
3301 thread->thread_dump_requested = TRUE;
3303 signal_thread_state_change (thread);
3306 CloseHandle (wait->handles [i]);
3311 * mono_thread_push_appdomain_ref:
3313 * Register that the current thread may have references to objects in domain
3314 * @domain on its stack. Each call to this function should be paired with a
3315 * call to pop_appdomain_ref.
3317 void
3318 mono_thread_push_appdomain_ref (MonoDomain *domain)
3320 MonoInternalThread *thread = mono_thread_internal_current ();
3322 if (thread) {
3323 /* printf ("PUSH REF: %"G_GSIZE_FORMAT" -> %s.\n", (gsize)thread->tid, domain->friendly_name); */
3324 SPIN_LOCK (thread->lock_thread_id);
3325 thread->appdomain_refs = g_slist_prepend (thread->appdomain_refs, domain);
3326 SPIN_UNLOCK (thread->lock_thread_id);
3330 void
3331 mono_thread_pop_appdomain_ref (void)
3333 MonoInternalThread *thread = mono_thread_internal_current ();
3335 if (thread) {
3336 /* printf ("POP REF: %"G_GSIZE_FORMAT" -> %s.\n", (gsize)thread->tid, ((MonoDomain*)(thread->appdomain_refs->data))->friendly_name); */
3337 /* FIXME: How can the list be empty ? */
3338 SPIN_LOCK (thread->lock_thread_id);
3339 if (thread->appdomain_refs)
3340 thread->appdomain_refs = g_slist_remove (thread->appdomain_refs, thread->appdomain_refs->data);
3341 SPIN_UNLOCK (thread->lock_thread_id);
3345 gboolean
3346 mono_thread_internal_has_appdomain_ref (MonoInternalThread *thread, MonoDomain *domain)
3348 gboolean res;
3349 SPIN_LOCK (thread->lock_thread_id);
3350 res = g_slist_find (thread->appdomain_refs, domain) != NULL;
3351 SPIN_UNLOCK (thread->lock_thread_id);
3352 return res;
3355 gboolean
3356 mono_thread_has_appdomain_ref (MonoThread *thread, MonoDomain *domain)
3358 return mono_thread_internal_has_appdomain_ref (thread->internal_thread, domain);
3361 typedef struct abort_appdomain_data {
3362 struct wait_data wait;
3363 MonoDomain *domain;
3364 } abort_appdomain_data;
3366 static void
3367 collect_appdomain_thread (gpointer key, gpointer value, gpointer user_data)
3369 MonoInternalThread *thread = (MonoInternalThread*)value;
3370 abort_appdomain_data *data = (abort_appdomain_data*)user_data;
3371 MonoDomain *domain = data->domain;
3373 if (mono_thread_internal_has_appdomain_ref (thread, domain)) {
3374 /* printf ("ABORTING THREAD %p BECAUSE IT REFERENCES DOMAIN %s.\n", thread->tid, domain->friendly_name); */
3376 if(data->wait.num<MAXIMUM_WAIT_OBJECTS) {
3377 HANDLE handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
3378 if (handle == NULL)
3379 return;
3380 data->wait.handles [data->wait.num] = handle;
3381 data->wait.threads [data->wait.num] = thread;
3382 data->wait.num++;
3383 } else {
3384 /* Just ignore the rest, we can't do anything with
3385 * them yet
3392 * mono_threads_abort_appdomain_threads:
3394 * Abort threads which has references to the given appdomain.
3396 gboolean
3397 mono_threads_abort_appdomain_threads (MonoDomain *domain, int timeout)
3399 abort_appdomain_data user_data;
3400 guint32 start_time;
3401 int orig_timeout = timeout;
3402 int i;
3404 THREAD_DEBUG (g_message ("%s: starting abort", __func__));
3406 start_time = mono_msec_ticks ();
3407 do {
3408 mono_threads_lock ();
3410 user_data.domain = domain;
3411 user_data.wait.num = 0;
3412 /* This shouldn't take any locks */
3413 mono_g_hash_table_foreach (threads, collect_appdomain_thread, &user_data);
3414 mono_threads_unlock ();
3416 if (user_data.wait.num > 0) {
3417 /* Abort the threads outside the threads lock */
3418 for (i = 0; i < user_data.wait.num; ++i)
3419 ves_icall_System_Threading_Thread_Abort (user_data.wait.threads [i], NULL);
3422 * We should wait for the threads either to abort, or to leave the
3423 * domain. We can't do the latter, so we wait with a timeout.
3425 wait_for_tids (&user_data.wait, 100);
3428 /* Update remaining time */
3429 timeout -= mono_msec_ticks () - start_time;
3430 start_time = mono_msec_ticks ();
3432 if (orig_timeout != -1 && timeout < 0)
3433 return FALSE;
3435 while (user_data.wait.num > 0);
3437 THREAD_DEBUG (g_message ("%s: abort done", __func__));
3439 return TRUE;
3442 static void
3443 clear_cached_culture (gpointer key, gpointer value, gpointer user_data)
3445 MonoInternalThread *thread = (MonoInternalThread*)value;
3446 MonoDomain *domain = (MonoDomain*)user_data;
3447 int i;
3449 /* No locking needed here */
3450 /* FIXME: why no locking? writes to the cache are protected with synch_cs above */
3452 if (thread->cached_culture_info) {
3453 for (i = 0; i < NUM_CACHED_CULTURES * 2; ++i) {
3454 MonoObject *obj = mono_array_get (thread->cached_culture_info, MonoObject*, i);
3455 if (obj && obj->vtable->domain == domain)
3456 mono_array_set (thread->cached_culture_info, MonoObject*, i, NULL);
3462 * mono_threads_clear_cached_culture:
3464 * Clear the cached_current_culture from all threads if it is in the
3465 * given appdomain.
3467 void
3468 mono_threads_clear_cached_culture (MonoDomain *domain)
3470 mono_threads_lock ();
3471 mono_g_hash_table_foreach (threads, clear_cached_culture, domain);
3472 mono_threads_unlock ();
3476 * mono_thread_get_undeniable_exception:
3478 * Return an exception which needs to be raised when leaving a catch clause.
3479 * This is used for undeniable exception propagation.
3481 MonoException*
3482 mono_thread_get_undeniable_exception (void)
3484 MonoInternalThread *thread = mono_thread_internal_current ();
3486 if (thread && thread->abort_exc && !is_running_protected_wrapper ()) {
3488 * FIXME: Clear the abort exception and return an AppDomainUnloaded
3489 * exception if the thread no longer references a dying appdomain.
3491 thread->abort_exc->trace_ips = NULL;
3492 thread->abort_exc->stack_trace = NULL;
3493 return thread->abort_exc;
3496 return NULL;
3499 #if MONO_SMALL_CONFIG
3500 #define NUM_STATIC_DATA_IDX 4
3501 static const int static_data_size [NUM_STATIC_DATA_IDX] = {
3502 64, 256, 1024, 4096
3504 #else
3505 #define NUM_STATIC_DATA_IDX 8
3506 static const int static_data_size [NUM_STATIC_DATA_IDX] = {
3507 1024, 4096, 16384, 65536, 262144, 1048576, 4194304, 16777216
3509 #endif
3511 static uintptr_t* static_reference_bitmaps [NUM_STATIC_DATA_IDX];
3513 #ifdef HAVE_SGEN_GC
3514 static void
3515 mark_tls_slots (void *addr, MonoGCMarkFunc mark_func)
3517 int i;
3518 gpointer *static_data = addr;
3519 for (i = 0; i < NUM_STATIC_DATA_IDX; ++i) {
3520 int j, numwords;
3521 void **ptr;
3522 if (!static_data [i])
3523 continue;
3524 numwords = 1 + static_data_size [i] / sizeof (gpointer) / (sizeof(uintptr_t) * 8);
3525 ptr = static_data [i];
3526 for (j = 0; j < numwords; ++j, ptr += sizeof (uintptr_t) * 8) {
3527 uintptr_t bmap = static_reference_bitmaps [i][j];
3528 void ** p = ptr;
3529 while (bmap) {
3530 if ((bmap & 1) && *p) {
3531 mark_func (p);
3533 p++;
3534 bmap >>= 1;
3539 #endif
3542 * mono_alloc_static_data
3544 * Allocate memory blocks for storing threads or context static data
3546 static void
3547 mono_alloc_static_data (gpointer **static_data_ptr, guint32 offset, gboolean threadlocal)
3549 guint idx = (offset >> 24) - 1;
3550 int i;
3552 gpointer* static_data = *static_data_ptr;
3553 if (!static_data) {
3554 static void* tls_desc = NULL;
3555 #ifdef HAVE_SGEN_GC
3556 if (!tls_desc)
3557 tls_desc = mono_gc_make_root_descr_user (mark_tls_slots);
3558 #endif
3559 static_data = mono_gc_alloc_fixed (static_data_size [0], threadlocal?tls_desc:NULL);
3560 *static_data_ptr = static_data;
3561 static_data [0] = static_data;
3564 for (i = 1; i <= idx; ++i) {
3565 if (static_data [i])
3566 continue;
3567 #ifdef HAVE_SGEN_GC
3568 static_data [i] = threadlocal?g_malloc0 (static_data_size [i]):mono_gc_alloc_fixed (static_data_size [i], NULL);
3569 #else
3570 static_data [i] = mono_gc_alloc_fixed (static_data_size [i], NULL);
3571 #endif
3575 static void
3576 mono_free_static_data (gpointer* static_data, gboolean threadlocal)
3578 int i;
3579 for (i = 1; i < NUM_STATIC_DATA_IDX; ++i) {
3580 if (!static_data [i])
3581 continue;
3582 #ifdef HAVE_SGEN_GC
3583 if (threadlocal)
3584 g_free (static_data [i]);
3585 else
3586 mono_gc_free_fixed (static_data [i]);
3587 #else
3588 mono_gc_free_fixed (static_data [i]);
3589 #endif
3591 mono_gc_free_fixed (static_data);
3595 * mono_init_static_data_info
3597 * Initializes static data counters
3599 static void mono_init_static_data_info (StaticDataInfo *static_data)
3601 static_data->idx = 0;
3602 static_data->offset = 0;
3603 static_data->freelist = NULL;
3607 * mono_alloc_static_data_slot
3609 * Generates an offset for static data. static_data contains the counters
3610 * used to generate it.
3612 static guint32
3613 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align)
3615 guint32 offset;
3617 if (!static_data->idx && !static_data->offset) {
3619 * we use the first chunk of the first allocation also as
3620 * an array for the rest of the data
3622 static_data->offset = sizeof (gpointer) * NUM_STATIC_DATA_IDX;
3624 static_data->offset += align - 1;
3625 static_data->offset &= ~(align - 1);
3626 if (static_data->offset + size >= static_data_size [static_data->idx]) {
3627 static_data->idx ++;
3628 g_assert (size <= static_data_size [static_data->idx]);
3629 g_assert (static_data->idx < NUM_STATIC_DATA_IDX);
3630 static_data->offset = 0;
3632 offset = static_data->offset | ((static_data->idx + 1) << 24);
3633 static_data->offset += size;
3634 return offset;
3638 * ensure thread static fields already allocated are valid for thread
3639 * This function is called when a thread is created or on thread attach.
3641 static void
3642 thread_adjust_static_data (MonoInternalThread *thread)
3644 guint32 offset;
3646 mono_threads_lock ();
3647 if (thread_static_info.offset || thread_static_info.idx > 0) {
3648 /* get the current allocated size */
3649 offset = thread_static_info.offset | ((thread_static_info.idx + 1) << 24);
3650 mono_alloc_static_data (&(thread->static_data), offset, TRUE);
3652 mono_threads_unlock ();
3655 static void
3656 alloc_thread_static_data_helper (gpointer key, gpointer value, gpointer user)
3658 MonoInternalThread *thread = value;
3659 guint32 offset = GPOINTER_TO_UINT (user);
3661 mono_alloc_static_data (&(thread->static_data), offset, TRUE);
3664 static MonoThreadDomainTls*
3665 search_tls_slot_in_freelist (StaticDataInfo *static_data, guint32 size, guint32 align)
3667 MonoThreadDomainTls* prev = NULL;
3668 MonoThreadDomainTls* tmp = static_data->freelist;
3669 while (tmp) {
3670 if (tmp->size == size) {
3671 if (prev)
3672 prev->next = tmp->next;
3673 else
3674 static_data->freelist = tmp->next;
3675 return tmp;
3677 tmp = tmp->next;
3679 return NULL;
3682 static void
3683 update_tls_reference_bitmap (guint32 offset, uintptr_t *bitmap, int max_set)
3685 int i;
3686 int idx = (offset >> 24) - 1;
3687 uintptr_t *rb;
3688 if (!static_reference_bitmaps [idx])
3689 static_reference_bitmaps [idx] = g_new0 (uintptr_t, 1 + static_data_size [idx] / sizeof(gpointer) / (sizeof(uintptr_t) * 8));
3690 rb = static_reference_bitmaps [idx];
3691 offset &= 0xffffff;
3692 offset /= sizeof (gpointer);
3693 /* offset is now the bitmap offset */
3694 for (i = 0; i < max_set; ++i) {
3695 if (bitmap [i / sizeof (uintptr_t)] & (1L << (i & (sizeof (uintptr_t) * 8 -1))))
3696 rb [(offset + i) / (sizeof (uintptr_t) * 8)] |= (1L << ((offset + i) & (sizeof (uintptr_t) * 8 -1)));
3700 static void
3701 clear_reference_bitmap (guint32 offset, guint32 size)
3703 int idx = (offset >> 24) - 1;
3704 uintptr_t *rb;
3705 rb = static_reference_bitmaps [idx];
3706 offset &= 0xffffff;
3707 offset /= sizeof (gpointer);
3708 size /= sizeof (gpointer);
3709 size += offset;
3710 /* offset is now the bitmap offset */
3711 for (; offset < size; ++offset)
3712 rb [offset / (sizeof (uintptr_t) * 8)] &= ~(1L << (offset & (sizeof (uintptr_t) * 8 -1)));
3716 * The offset for a special static variable is composed of three parts:
3717 * a bit that indicates the type of static data (0:thread, 1:context),
3718 * an index in the array of chunks of memory for the thread (thread->static_data)
3719 * and an offset in that chunk of mem. This allows allocating less memory in the
3720 * common case.
3723 guint32
3724 mono_alloc_special_static_data (guint32 static_type, guint32 size, guint32 align, uintptr_t *bitmap, int max_set)
3726 guint32 offset;
3727 if (static_type == SPECIAL_STATIC_THREAD) {
3728 MonoThreadDomainTls *item;
3729 mono_threads_lock ();
3730 item = search_tls_slot_in_freelist (&thread_static_info, size, align);
3731 /*g_print ("TLS alloc: %d in domain %p (total: %d), cached: %p\n", size, mono_domain_get (), thread_static_info.offset, item);*/
3732 if (item) {
3733 offset = item->offset;
3734 g_free (item);
3735 } else {
3736 offset = mono_alloc_static_data_slot (&thread_static_info, size, align);
3738 update_tls_reference_bitmap (offset, bitmap, max_set);
3739 /* This can be called during startup */
3740 if (threads != NULL)
3741 mono_g_hash_table_foreach (threads, alloc_thread_static_data_helper, GUINT_TO_POINTER (offset));
3742 mono_threads_unlock ();
3743 } else {
3744 g_assert (static_type == SPECIAL_STATIC_CONTEXT);
3745 mono_contexts_lock ();
3746 offset = mono_alloc_static_data_slot (&context_static_info, size, align);
3747 mono_contexts_unlock ();
3748 offset |= 0x80000000; /* Set the high bit to indicate context static data */
3750 return offset;
3753 gpointer
3754 mono_get_special_static_data (guint32 offset)
3756 /* The high bit means either thread (0) or static (1) data. */
3758 guint32 static_type = (offset & 0x80000000);
3759 int idx;
3761 offset &= 0x7fffffff;
3762 idx = (offset >> 24) - 1;
3764 if (static_type == 0) {
3765 return get_thread_static_data (mono_thread_internal_current (), offset);
3766 } else {
3767 /* Allocate static data block under demand, since we don't have a list
3768 // of contexts
3770 MonoAppContext *context = mono_context_get ();
3771 if (!context->static_data || !context->static_data [idx]) {
3772 mono_contexts_lock ();
3773 mono_alloc_static_data (&(context->static_data), offset, FALSE);
3774 mono_contexts_unlock ();
3776 return ((char*) context->static_data [idx]) + (offset & 0xffffff);
3780 typedef struct {
3781 guint32 offset;
3782 guint32 size;
3783 } TlsOffsetSize;
3785 static void
3786 free_thread_static_data_helper (gpointer key, gpointer value, gpointer user)
3788 MonoInternalThread *thread = value;
3789 TlsOffsetSize *data = user;
3790 int idx = (data->offset >> 24) - 1;
3791 char *ptr;
3793 if (!thread->static_data || !thread->static_data [idx])
3794 return;
3795 ptr = ((char*) thread->static_data [idx]) + (data->offset & 0xffffff);
3796 memset (ptr, 0, data->size);
3799 static void
3800 do_free_special (gpointer key, gpointer value, gpointer data)
3802 MonoClassField *field = key;
3803 guint32 offset = GPOINTER_TO_UINT (value);
3804 guint32 static_type = (offset & 0x80000000);
3805 gint32 align;
3806 guint32 size;
3807 size = mono_type_size (field->type, &align);
3808 /*g_print ("free %s , size: %d, offset: %x\n", field->name, size, offset);*/
3809 if (static_type == 0) {
3810 TlsOffsetSize data;
3811 MonoThreadDomainTls *item = g_new0 (MonoThreadDomainTls, 1);
3812 data.offset = offset & 0x7fffffff;
3813 data.size = size;
3814 clear_reference_bitmap (data.offset, data.size);
3815 if (threads != NULL)
3816 mono_g_hash_table_foreach (threads, free_thread_static_data_helper, &data);
3817 item->offset = offset;
3818 item->size = size;
3820 if (!mono_runtime_is_shutting_down ()) {
3821 item->next = thread_static_info.freelist;
3822 thread_static_info.freelist = item;
3823 } else {
3824 /* We could be called during shutdown after mono_thread_cleanup () is called */
3825 g_free (item);
3827 } else {
3828 /* FIXME: free context static data as well */
3832 void
3833 mono_alloc_special_static_data_free (GHashTable *special_static_fields)
3835 mono_threads_lock ();
3836 g_hash_table_foreach (special_static_fields, do_free_special, NULL);
3837 mono_threads_unlock ();
3840 static MonoClassField *local_slots = NULL;
3842 typedef struct {
3843 /* local tls data to get locals_slot from a thread */
3844 guint32 offset;
3845 int idx;
3846 /* index in the locals_slot array */
3847 int slot;
3848 } LocalSlotID;
3850 static void
3851 clear_local_slot (gpointer key, gpointer value, gpointer user_data)
3853 LocalSlotID *sid = user_data;
3854 MonoInternalThread *thread = (MonoInternalThread*)value;
3855 MonoArray *slots_array;
3857 * the static field is stored at: ((char*) thread->static_data [idx]) + (offset & 0xffffff);
3858 * it is for the right domain, so we need to check if it is allocated an initialized
3859 * for the current thread.
3861 /*g_print ("handling thread %p\n", thread);*/
3862 if (!thread->static_data || !thread->static_data [sid->idx])
3863 return;
3864 slots_array = *(MonoArray **)(((char*) thread->static_data [sid->idx]) + (sid->offset & 0xffffff));
3865 if (!slots_array || sid->slot >= mono_array_length (slots_array))
3866 return;
3867 mono_array_set (slots_array, MonoObject*, sid->slot, NULL);
3870 void
3871 mono_thread_free_local_slot_values (int slot, MonoBoolean thread_local)
3873 MonoDomain *domain;
3874 LocalSlotID sid;
3875 sid.slot = slot;
3876 if (thread_local) {
3877 void *addr = NULL;
3878 if (!local_slots) {
3879 local_slots = mono_class_get_field_from_name (mono_defaults.thread_class, "local_slots");
3880 if (!local_slots) {
3881 g_warning ("local_slots field not found in Thread class");
3882 return;
3885 domain = mono_domain_get ();
3886 mono_domain_lock (domain);
3887 if (domain->special_static_fields)
3888 addr = g_hash_table_lookup (domain->special_static_fields, local_slots);
3889 mono_domain_unlock (domain);
3890 if (!addr)
3891 return;
3892 /*g_print ("freeing slot %d at %p\n", slot, addr);*/
3893 sid.offset = GPOINTER_TO_UINT (addr);
3894 sid.offset &= 0x7fffffff;
3895 sid.idx = (sid.offset >> 24) - 1;
3896 mono_threads_lock ();
3897 mono_g_hash_table_foreach (threads, clear_local_slot, &sid);
3898 mono_threads_unlock ();
3899 } else {
3900 /* FIXME: clear the slot for MonoAppContexts, too */
3904 #ifdef HOST_WIN32
3905 static void CALLBACK dummy_apc (ULONG_PTR param)
3908 #else
3909 static guint32 dummy_apc (gpointer param)
3911 return 0;
3913 #endif
3916 * mono_thread_execute_interruption
3918 * Performs the operation that the requested thread state requires (abort,
3919 * suspend or stop)
3921 static MonoException* mono_thread_execute_interruption (MonoInternalThread *thread)
3923 ensure_synch_cs_set (thread);
3925 EnterCriticalSection (thread->synch_cs);
3927 /* MonoThread::interruption_requested can only be changed with atomics */
3928 if (InterlockedCompareExchange (&thread->interruption_requested, FALSE, TRUE)) {
3929 /* this will consume pending APC calls */
3930 WaitForSingleObjectEx (GetCurrentThread(), 0, TRUE);
3931 InterlockedDecrement (&thread_interruption_requested);
3932 #ifndef HOST_WIN32
3933 /* Clear the interrupted flag of the thread so it can wait again */
3934 wapi_clear_interruption ();
3935 #endif
3938 if ((thread->state & ThreadState_AbortRequested) != 0) {
3939 LeaveCriticalSection (thread->synch_cs);
3940 if (thread->abort_exc == NULL) {
3942 * This might be racy, but it has to be called outside the lock
3943 * since it calls managed code.
3945 MONO_OBJECT_SETREF (thread, abort_exc, mono_get_exception_thread_abort ());
3947 return thread->abort_exc;
3949 else if ((thread->state & ThreadState_SuspendRequested) != 0) {
3950 thread->state &= ~ThreadState_SuspendRequested;
3951 thread->state |= ThreadState_Suspended;
3952 thread->suspend_event = CreateEvent (NULL, TRUE, FALSE, NULL);
3953 if (thread->suspend_event == NULL) {
3954 LeaveCriticalSection (thread->synch_cs);
3955 return(NULL);
3957 if (thread->suspended_event)
3958 SetEvent (thread->suspended_event);
3960 LeaveCriticalSection (thread->synch_cs);
3962 if (shutting_down) {
3963 /* After we left the lock, the runtime might shut down so everything becomes invalid */
3964 for (;;)
3965 Sleep (1000);
3968 WaitForSingleObject (thread->suspend_event, INFINITE);
3970 EnterCriticalSection (thread->synch_cs);
3972 CloseHandle (thread->suspend_event);
3973 thread->suspend_event = NULL;
3974 thread->state &= ~ThreadState_Suspended;
3976 /* The thread that requested the resume will have replaced this event
3977 * and will be waiting for it
3979 SetEvent (thread->resume_event);
3981 LeaveCriticalSection (thread->synch_cs);
3983 return NULL;
3985 else if ((thread->state & ThreadState_StopRequested) != 0) {
3986 /* FIXME: do this through the JIT? */
3988 LeaveCriticalSection (thread->synch_cs);
3990 mono_thread_exit ();
3991 return NULL;
3992 } else if (thread->thread_interrupt_requested) {
3994 thread->thread_interrupt_requested = FALSE;
3995 LeaveCriticalSection (thread->synch_cs);
3997 return(mono_get_exception_thread_interrupted ());
4000 LeaveCriticalSection (thread->synch_cs);
4002 return NULL;
4006 * mono_thread_request_interruption
4008 * A signal handler can call this method to request the interruption of a
4009 * thread. The result of the interruption will depend on the current state of
4010 * the thread. If the result is an exception that needs to be throw, it is
4011 * provided as return value.
4013 MonoException*
4014 mono_thread_request_interruption (gboolean running_managed)
4016 MonoInternalThread *thread = mono_thread_internal_current ();
4018 /* The thread may already be stopping */
4019 if (thread == NULL)
4020 return NULL;
4022 #ifdef HOST_WIN32
4023 if (thread->interrupt_on_stop &&
4024 thread->state & ThreadState_StopRequested &&
4025 thread->state & ThreadState_Background)
4026 ExitThread (1);
4027 #endif
4029 if (InterlockedCompareExchange (&thread->interruption_requested, 1, 0) == 1)
4030 return NULL;
4032 if (!running_managed || is_running_protected_wrapper ()) {
4033 /* Can't stop while in unmanaged code. Increase the global interruption
4034 request count. When exiting the unmanaged method the count will be
4035 checked and the thread will be interrupted. */
4037 InterlockedIncrement (&thread_interruption_requested);
4039 if (mono_thread_notify_pending_exc_fn && !running_managed)
4040 /* The JIT will notify the thread about the interruption */
4041 /* This shouldn't take any locks */
4042 mono_thread_notify_pending_exc_fn ();
4044 /* this will awake the thread if it is in WaitForSingleObject
4045 or similar */
4046 /* Our implementation of this function ignores the func argument */
4047 QueueUserAPC ((PAPCFUNC)dummy_apc, thread->handle, NULL);
4048 return NULL;
4050 else {
4051 return mono_thread_execute_interruption (thread);
4055 /*This function should be called by a thread after it has exited all of
4056 * its handle blocks at interruption time.*/
4057 MonoException*
4058 mono_thread_resume_interruption (void)
4060 MonoInternalThread *thread = mono_thread_internal_current ();
4061 gboolean still_aborting;
4063 /* The thread may already be stopping */
4064 if (thread == NULL)
4065 return NULL;
4067 ensure_synch_cs_set (thread);
4068 EnterCriticalSection (thread->synch_cs);
4069 still_aborting = (thread->state & ThreadState_AbortRequested) != 0;
4070 LeaveCriticalSection (thread->synch_cs);
4072 /*This can happen if the protected block called Thread::ResetAbort*/
4073 if (!still_aborting)
4074 return FALSE;
4076 if (InterlockedCompareExchange (&thread->interruption_requested, 1, 0) == 1)
4077 return NULL;
4078 InterlockedIncrement (&thread_interruption_requested);
4080 #ifndef HOST_WIN32
4081 wapi_self_interrupt ();
4082 #endif
4083 return mono_thread_execute_interruption (thread);
4086 gboolean mono_thread_interruption_requested ()
4088 if (thread_interruption_requested) {
4089 MonoInternalThread *thread = mono_thread_internal_current ();
4090 /* The thread may already be stopping */
4091 if (thread != NULL)
4092 return (thread->interruption_requested);
4094 return FALSE;
4097 static void mono_thread_interruption_checkpoint_request (gboolean bypass_abort_protection)
4099 MonoInternalThread *thread = mono_thread_internal_current ();
4101 /* The thread may already be stopping */
4102 if (thread == NULL)
4103 return;
4105 mono_debugger_check_interruption ();
4107 if (thread->interruption_requested && (bypass_abort_protection || !is_running_protected_wrapper ())) {
4108 MonoException* exc = mono_thread_execute_interruption (thread);
4109 if (exc) mono_raise_exception (exc);
4114 * Performs the interruption of the current thread, if one has been requested,
4115 * and the thread is not running a protected wrapper.
4117 void mono_thread_interruption_checkpoint ()
4119 mono_thread_interruption_checkpoint_request (FALSE);
4123 * Performs the interruption of the current thread, if one has been requested.
4125 void mono_thread_force_interruption_checkpoint ()
4127 mono_thread_interruption_checkpoint_request (TRUE);
4131 * mono_thread_get_and_clear_pending_exception:
4133 * Return any pending exceptions for the current thread and clear it as a side effect.
4135 MonoException*
4136 mono_thread_get_and_clear_pending_exception (void)
4138 MonoInternalThread *thread = mono_thread_internal_current ();
4140 /* The thread may already be stopping */
4141 if (thread == NULL)
4142 return NULL;
4144 if (thread->interruption_requested && !is_running_protected_wrapper ()) {
4145 return mono_thread_execute_interruption (thread);
4148 if (thread->pending_exception) {
4149 MonoException *exc = thread->pending_exception;
4151 thread->pending_exception = NULL;
4152 return exc;
4155 return NULL;
4159 * mono_set_pending_exception:
4161 * Set the pending exception of the current thread to EXC. On platforms which
4162 * support it, the exception will be thrown when execution returns to managed code.
4163 * On other platforms, this function is equivalent to mono_raise_exception ().
4164 * Internal calls which report exceptions using this function instead of
4165 * raise_exception () might be called by JITted code using a more efficient calling
4166 * convention.
4168 void
4169 mono_set_pending_exception (MonoException *exc)
4171 MonoInternalThread *thread = mono_thread_internal_current ();
4173 /* The thread may already be stopping */
4174 if (thread == NULL)
4175 return;
4177 if (mono_thread_notify_pending_exc_fn) {
4178 MONO_OBJECT_SETREF (thread, pending_exception, exc);
4180 mono_thread_notify_pending_exc_fn ();
4181 } else {
4182 /* No way to notify the JIT about the exception, have to throw it now */
4183 mono_raise_exception (exc);
4188 * mono_thread_interruption_request_flag:
4190 * Returns the address of a flag that will be non-zero if an interruption has
4191 * been requested for a thread. The thread to interrupt may not be the current
4192 * thread, so an additional call to mono_thread_interruption_requested() or
4193 * mono_thread_interruption_checkpoint() is allways needed if the flag is not
4194 * zero.
4196 gint32* mono_thread_interruption_request_flag ()
4198 return &thread_interruption_requested;
4201 void
4202 mono_thread_init_apartment_state (void)
4204 #ifdef HOST_WIN32
4205 MonoInternalThread* thread = mono_thread_internal_current ();
4207 /* Positive return value indicates success, either
4208 * S_OK if this is first CoInitialize call, or
4209 * S_FALSE if CoInitialize already called, but with same
4210 * threading model. A negative value indicates failure,
4211 * probably due to trying to change the threading model.
4213 if (CoInitializeEx(NULL, (thread->apartment_state == ThreadApartmentState_STA)
4214 ? COINIT_APARTMENTTHREADED
4215 : COINIT_MULTITHREADED) < 0) {
4216 thread->apartment_state = ThreadApartmentState_Unknown;
4218 #endif
4221 void
4222 mono_thread_cleanup_apartment_state (void)
4224 #ifdef HOST_WIN32
4225 MonoInternalThread* thread = mono_thread_internal_current ();
4227 if (thread && thread->apartment_state != ThreadApartmentState_Unknown) {
4228 CoUninitialize ();
4230 #endif
4233 void
4234 mono_thread_set_state (MonoInternalThread *thread, MonoThreadState state)
4236 ensure_synch_cs_set (thread);
4238 EnterCriticalSection (thread->synch_cs);
4239 thread->state |= state;
4240 LeaveCriticalSection (thread->synch_cs);
4243 void
4244 mono_thread_clr_state (MonoInternalThread *thread, MonoThreadState state)
4246 ensure_synch_cs_set (thread);
4248 EnterCriticalSection (thread->synch_cs);
4249 thread->state &= ~state;
4250 LeaveCriticalSection (thread->synch_cs);
4253 gboolean
4254 mono_thread_test_state (MonoInternalThread *thread, MonoThreadState test)
4256 gboolean ret = FALSE;
4258 ensure_synch_cs_set (thread);
4260 EnterCriticalSection (thread->synch_cs);
4262 if ((thread->state & test) != 0) {
4263 ret = TRUE;
4266 LeaveCriticalSection (thread->synch_cs);
4268 return ret;
4271 static MonoClassField *execution_context_field;
4273 static MonoObject**
4274 get_execution_context_addr (void)
4276 MonoDomain *domain = mono_domain_get ();
4277 guint32 offset;
4279 if (!execution_context_field) {
4280 execution_context_field = mono_class_get_field_from_name (mono_defaults.thread_class,
4281 "_ec");
4282 g_assert (execution_context_field);
4285 g_assert (mono_class_try_get_vtable (domain, mono_defaults.appdomain_class));
4287 mono_domain_lock (domain);
4288 offset = GPOINTER_TO_UINT (g_hash_table_lookup (domain->special_static_fields, execution_context_field));
4289 mono_domain_unlock (domain);
4290 g_assert (offset);
4292 return (MonoObject**) mono_get_special_static_data (offset);
4295 MonoObject*
4296 mono_thread_get_execution_context (void)
4298 return *get_execution_context_addr ();
4301 void
4302 mono_thread_set_execution_context (MonoObject *ec)
4304 *get_execution_context_addr () = ec;
4307 static gboolean has_tls_get = FALSE;
4309 void
4310 mono_runtime_set_has_tls_get (gboolean val)
4312 has_tls_get = val;
4315 gboolean
4316 mono_runtime_has_tls_get (void)
4318 return has_tls_get;