2009-11-02 Zoltan Varga <vargaz@gmail.com>
[mono-project.git] / mono / metadata / threads.c
blob6fbecd988ee5d0a8330cc6e0c4c900e1b8c48dd3
1 /*
2 * threads.c: Thread support internal calls
4 * Author:
5 * Dick Porter (dick@ximian.com)
6 * Paolo Molaro (lupus@ximian.com)
7 * Patrik Torstensson (patrik.torstensson@labs2.com)
9 * Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
10 * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
13 #include <config.h>
15 #include <glib.h>
16 #include <signal.h>
17 #include <string.h>
19 #include <mono/metadata/object.h>
20 #include <mono/metadata/domain-internals.h>
21 #include <mono/metadata/profiler-private.h>
22 #include <mono/metadata/threads.h>
23 #include <mono/metadata/threadpool.h>
24 #include <mono/metadata/threads-types.h>
25 #include <mono/metadata/exception.h>
26 #include <mono/metadata/environment.h>
27 #include <mono/metadata/monitor.h>
28 #include <mono/metadata/gc-internal.h>
29 #include <mono/metadata/marshal.h>
30 #include <mono/io-layer/io-layer.h>
31 #ifndef PLATFORM_WIN32
32 #include <mono/io-layer/threads.h>
33 #endif
34 #include <mono/metadata/object-internals.h>
35 #include <mono/metadata/mono-debug-debugger.h>
36 #include <mono/utils/mono-compiler.h>
37 #include <mono/utils/mono-mmap.h>
38 #include <mono/utils/mono-membar.h>
39 #include <mono/utils/mono-time.h>
41 #include <mono/metadata/gc-internal.h>
43 /*#define THREAD_DEBUG(a) do { a; } while (0)*/
44 #define THREAD_DEBUG(a)
45 /*#define THREAD_WAIT_DEBUG(a) do { a; } while (0)*/
46 #define THREAD_WAIT_DEBUG(a)
47 /*#define LIBGC_DEBUG(a) do { a; } while (0)*/
48 #define LIBGC_DEBUG(a)
50 /* Provide this for systems with glib < 2.6 */
51 #ifndef G_GSIZE_FORMAT
52 # if GLIB_SIZEOF_LONG == 8
53 # define G_GSIZE_FORMAT "lu"
54 # else
55 # define G_GSIZE_FORMAT "u"
56 # endif
57 #endif
59 struct StartInfo
61 guint32 (*func)(void *);
62 MonoThread *obj;
63 MonoObject *delegate;
64 void *start_arg;
65 MonoDomain *domain;
68 typedef union {
69 gint32 ival;
70 gfloat fval;
71 } IntFloatUnion;
73 typedef union {
74 gint64 ival;
75 gdouble fval;
76 } LongDoubleUnion;
78 typedef struct _MonoThreadDomainTls MonoThreadDomainTls;
79 struct _MonoThreadDomainTls {
80 MonoThreadDomainTls *next;
81 guint32 offset;
82 guint32 size;
85 typedef struct {
86 int idx;
87 int offset;
88 MonoThreadDomainTls *freelist;
89 } StaticDataInfo;
91 typedef struct {
92 gpointer p;
93 MonoHazardousFreeFunc free_func;
94 } DelayedFreeItem;
96 /* Number of cached culture objects in the MonoThread->cached_culture_info array
97 * (per-type): we use the first NUM entries for CultureInfo and the last for
98 * UICultureInfo. So the size of the array is really NUM_CACHED_CULTURES * 2.
100 #define NUM_CACHED_CULTURES 4
101 #define CULTURES_START_IDX 0
102 #define UICULTURES_START_IDX NUM_CACHED_CULTURES
104 /* Controls access to the 'threads' hash table */
105 #define mono_threads_lock() EnterCriticalSection (&threads_mutex)
106 #define mono_threads_unlock() LeaveCriticalSection (&threads_mutex)
107 static CRITICAL_SECTION threads_mutex;
109 /* Controls access to context static data */
110 #define mono_contexts_lock() EnterCriticalSection (&contexts_mutex)
111 #define mono_contexts_unlock() LeaveCriticalSection (&contexts_mutex)
112 static CRITICAL_SECTION contexts_mutex;
114 /* Holds current status of static data heap */
115 static StaticDataInfo thread_static_info;
116 static StaticDataInfo context_static_info;
118 /* The hash of existing threads (key is thread ID) that need joining
119 * before exit
121 static MonoGHashTable *threads=NULL;
124 * Threads which are starting up and they are not in the 'threads' hash yet.
125 * When handle_store is called for a thread, it will be removed from this hash table.
126 * Protected by mono_threads_lock ().
128 static MonoGHashTable *threads_starting_up = NULL;
130 /* Maps a MonoThread to its start argument */
131 /* Protected by mono_threads_lock () */
132 static MonoGHashTable *thread_start_args = NULL;
134 /* The TLS key that holds the MonoObject assigned to each thread */
135 static guint32 current_object_key = -1;
137 #ifdef HAVE_KW_THREAD
138 /* we need to use both the Tls* functions and __thread because
139 * the gc needs to see all the threads
141 static __thread MonoThread * tls_current_object MONO_TLS_FAST;
142 #define SET_CURRENT_OBJECT(x) do { \
143 tls_current_object = x; \
144 TlsSetValue (current_object_key, x); \
145 } while (FALSE)
146 #define GET_CURRENT_OBJECT() tls_current_object
147 #else
148 #define SET_CURRENT_OBJECT(x) TlsSetValue (current_object_key, x)
149 #define GET_CURRENT_OBJECT() (MonoThread*) TlsGetValue (current_object_key)
150 #endif
152 /* function called at thread start */
153 static MonoThreadStartCB mono_thread_start_cb = NULL;
155 /* function called at thread attach */
156 static MonoThreadAttachCB mono_thread_attach_cb = NULL;
158 /* function called at thread cleanup */
159 static MonoThreadCleanupFunc mono_thread_cleanup_fn = NULL;
161 /* function called to notify the runtime about a pending exception on the current thread */
162 static MonoThreadNotifyPendingExcFunc mono_thread_notify_pending_exc_fn = NULL;
164 /* The default stack size for each thread */
165 static guint32 default_stacksize = 0;
166 #define default_stacksize_for_thread(thread) ((thread)->stack_size? (thread)->stack_size: default_stacksize)
168 static void thread_adjust_static_data (MonoThread *thread);
169 static void mono_init_static_data_info (StaticDataInfo *static_data);
170 static guint32 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align);
171 static gboolean mono_thread_resume (MonoThread* thread);
172 static void mono_thread_start (MonoThread *thread);
173 static void signal_thread_state_change (MonoThread *thread);
175 static MonoException* mono_thread_execute_interruption (MonoThread *thread);
177 /* Spin lock for InterlockedXXX 64 bit functions */
178 #define mono_interlocked_lock() EnterCriticalSection (&interlocked_mutex)
179 #define mono_interlocked_unlock() LeaveCriticalSection (&interlocked_mutex)
180 static CRITICAL_SECTION interlocked_mutex;
182 /* global count of thread interruptions requested */
183 static gint32 thread_interruption_requested = 0;
185 /* Event signaled when a thread changes its background mode */
186 static HANDLE background_change_event;
188 /* The table for small ID assignment */
189 static CRITICAL_SECTION small_id_mutex;
190 static int small_id_table_size = 0;
191 static int small_id_next = 0;
192 static int highest_small_id = -1;
193 static MonoThread **small_id_table = NULL;
195 /* The hazard table */
196 #define HAZARD_TABLE_MAX_SIZE 16384 /* There cannot be more threads than this number. */
197 static volatile int hazard_table_size = 0;
198 static MonoThreadHazardPointers * volatile hazard_table = NULL;
200 /* The table where we keep pointers to blocks to be freed but that
201 have to wait because they're guarded by a hazard pointer. */
202 static CRITICAL_SECTION delayed_free_table_mutex;
203 static GArray *delayed_free_table = NULL;
205 static gboolean shutting_down = FALSE;
207 guint32
208 mono_thread_get_tls_key (void)
210 return current_object_key;
213 gint32
214 mono_thread_get_tls_offset (void)
216 int offset;
217 MONO_THREAD_VAR_OFFSET (tls_current_object,offset);
218 return offset;
221 /* handle_store() and handle_remove() manage the array of threads that
222 * still need to be waited for when the main thread exits.
224 * If handle_store() returns FALSE the thread must not be started
225 * because Mono is shutting down.
227 static gboolean handle_store(MonoThread *thread)
229 mono_threads_lock ();
231 THREAD_DEBUG (g_message ("%s: thread %p ID %"G_GSIZE_FORMAT, __func__, thread, (gsize)thread->tid));
233 if (threads_starting_up)
234 mono_g_hash_table_remove (threads_starting_up, thread);
236 if (shutting_down) {
237 mono_threads_unlock ();
238 return FALSE;
241 if(threads==NULL) {
242 MONO_GC_REGISTER_ROOT (threads);
243 threads=mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
246 /* We don't need to duplicate thread->handle, because it is
247 * only closed when the thread object is finalized by the GC.
249 mono_g_hash_table_insert(threads, (gpointer)(gsize)(thread->tid),
250 thread);
252 mono_threads_unlock ();
254 return TRUE;
257 static gboolean handle_remove(MonoThread *thread)
259 gboolean ret;
260 gsize tid = thread->tid;
262 THREAD_DEBUG (g_message ("%s: thread ID %"G_GSIZE_FORMAT, __func__, tid));
264 mono_threads_lock ();
266 if (threads) {
267 /* We have to check whether the thread object for the
268 * tid is still the same in the table because the
269 * thread might have been destroyed and the tid reused
270 * in the meantime, in which case the tid would be in
271 * the table, but with another thread object.
273 if (mono_g_hash_table_lookup (threads, (gpointer)tid) == thread) {
274 mono_g_hash_table_remove (threads, (gpointer)tid);
275 ret = TRUE;
276 } else {
277 ret = FALSE;
280 else
281 ret = FALSE;
283 mono_threads_unlock ();
285 /* Don't close the handle here, wait for the object finalizer
286 * to do it. Otherwise, the following race condition applies:
288 * 1) Thread exits (and handle_remove() closes the handle)
290 * 2) Some other handle is reassigned the same slot
292 * 3) Another thread tries to join the first thread, and
293 * blocks waiting for the reassigned handle to be signalled
294 * (which might never happen). This is possible, because the
295 * thread calling Join() still has a reference to the first
296 * thread's object.
298 return ret;
302 * Allocate a small thread id.
304 * FIXME: The biggest part of this function is very similar to
305 * domain_id_alloc() in domain.c and should be merged.
307 static int
308 small_id_alloc (MonoThread *thread)
310 int id = -1, i;
312 EnterCriticalSection (&small_id_mutex);
314 if (!small_id_table) {
315 small_id_table_size = 2;
316 small_id_table = mono_gc_alloc_fixed (small_id_table_size * sizeof (MonoThread*), NULL);
318 for (i = small_id_next; i < small_id_table_size; ++i) {
319 if (!small_id_table [i]) {
320 id = i;
321 break;
324 if (id == -1) {
325 for (i = 0; i < small_id_next; ++i) {
326 if (!small_id_table [i]) {
327 id = i;
328 break;
332 if (id == -1) {
333 MonoThread **new_table;
334 int new_size = small_id_table_size * 2;
335 if (new_size >= (1 << 16))
336 g_assert_not_reached ();
337 id = small_id_table_size;
338 new_table = mono_gc_alloc_fixed (new_size * sizeof (MonoThread*), NULL);
339 memcpy (new_table, small_id_table, small_id_table_size * sizeof (void*));
340 mono_gc_free_fixed (small_id_table);
341 small_id_table = new_table;
342 small_id_table_size = new_size;
344 thread->small_id = id;
345 g_assert (small_id_table [id] == NULL);
346 small_id_table [id] = thread;
347 small_id_next++;
348 if (small_id_next > small_id_table_size)
349 small_id_next = 0;
351 if (id >= hazard_table_size) {
352 gpointer page_addr;
353 int pagesize = mono_pagesize ();
354 int num_pages = (hazard_table_size * sizeof (MonoThreadHazardPointers) + pagesize - 1) / pagesize;
356 if (hazard_table == NULL) {
357 hazard_table = mono_valloc (NULL,
358 sizeof (MonoThreadHazardPointers) * HAZARD_TABLE_MAX_SIZE,
359 MONO_MMAP_NONE);
362 g_assert (hazard_table != NULL);
363 page_addr = (guint8*)hazard_table + num_pages * pagesize;
365 g_assert (id < HAZARD_TABLE_MAX_SIZE);
367 mono_mprotect (page_addr, pagesize, MONO_MMAP_READ | MONO_MMAP_WRITE);
369 ++num_pages;
370 hazard_table_size = num_pages * pagesize / sizeof (MonoThreadHazardPointers);
372 g_assert (id < hazard_table_size);
374 hazard_table [id].hazard_pointers [0] = NULL;
375 hazard_table [id].hazard_pointers [1] = NULL;
378 if (id > highest_small_id) {
379 highest_small_id = id;
380 mono_memory_write_barrier ();
383 LeaveCriticalSection (&small_id_mutex);
385 return id;
388 static void
389 small_id_free (int id)
391 g_assert (id >= 0 && id < small_id_table_size);
392 g_assert (small_id_table [id] != NULL);
394 small_id_table [id] = NULL;
397 static gboolean
398 is_pointer_hazardous (gpointer p)
400 int i;
401 int highest = highest_small_id;
403 g_assert (highest < hazard_table_size);
405 for (i = 0; i <= highest; ++i) {
406 if (hazard_table [i].hazard_pointers [0] == p
407 || hazard_table [i].hazard_pointers [1] == p)
408 return TRUE;
411 return FALSE;
414 MonoThreadHazardPointers*
415 mono_hazard_pointer_get (void)
417 MonoThread *current_thread = mono_thread_current ();
419 if (!(current_thread && current_thread->small_id >= 0)) {
420 static MonoThreadHazardPointers emerg_hazard_table;
421 g_warning ("Thread %p may have been prematurely finalized", current_thread);
422 return &emerg_hazard_table;
425 return &hazard_table [current_thread->small_id];
428 static void
429 try_free_delayed_free_item (int index)
431 if (delayed_free_table->len > index) {
432 DelayedFreeItem item = { NULL, NULL };
434 EnterCriticalSection (&delayed_free_table_mutex);
435 /* We have to check the length again because another
436 thread might have freed an item before we acquired
437 the lock. */
438 if (delayed_free_table->len > index) {
439 item = g_array_index (delayed_free_table, DelayedFreeItem, index);
441 if (!is_pointer_hazardous (item.p))
442 g_array_remove_index_fast (delayed_free_table, index);
443 else
444 item.p = NULL;
446 LeaveCriticalSection (&delayed_free_table_mutex);
448 if (item.p != NULL)
449 item.free_func (item.p);
453 void
454 mono_thread_hazardous_free_or_queue (gpointer p, MonoHazardousFreeFunc free_func)
456 int i;
458 /* First try to free a few entries in the delayed free
459 table. */
460 for (i = 2; i >= 0; --i)
461 try_free_delayed_free_item (i);
463 /* Now see if the pointer we're freeing is hazardous. If it
464 isn't, free it. Otherwise put it in the delay list. */
465 if (is_pointer_hazardous (p)) {
466 DelayedFreeItem item = { p, free_func };
468 ++mono_stats.hazardous_pointer_count;
470 EnterCriticalSection (&delayed_free_table_mutex);
471 g_array_append_val (delayed_free_table, item);
472 LeaveCriticalSection (&delayed_free_table_mutex);
473 } else
474 free_func (p);
477 void
478 mono_thread_hazardous_try_free_all (void)
480 int len;
481 int i;
483 if (!delayed_free_table)
484 return;
486 len = delayed_free_table->len;
488 for (i = len - 1; i >= 0; --i)
489 try_free_delayed_free_item (i);
492 static void ensure_synch_cs_set (MonoThread *thread)
494 CRITICAL_SECTION *synch_cs;
496 if (thread->synch_cs != NULL) {
497 return;
500 synch_cs = g_new0 (CRITICAL_SECTION, 1);
501 InitializeCriticalSection (synch_cs);
503 if (InterlockedCompareExchangePointer ((gpointer *)&thread->synch_cs,
504 synch_cs, NULL) != NULL) {
505 /* Another thread must have installed this CS */
506 DeleteCriticalSection (synch_cs);
507 g_free (synch_cs);
512 * NOTE: this function can be called also for threads different from the current one:
513 * make sure no code called from it will ever assume it is run on the thread that is
514 * getting cleaned up.
516 static void thread_cleanup (MonoThread *thread)
518 g_assert (thread != NULL);
520 if (thread->abort_state_handle) {
521 g_assert (thread->abort_exc);
522 mono_gchandle_free (thread->abort_state_handle);
523 thread->abort_state_handle = 0;
525 thread->abort_exc = NULL;
526 thread->current_appcontext = NULL;
529 * This is necessary because otherwise we might have
530 * cross-domain references which will not get cleaned up when
531 * the target domain is unloaded.
533 if (thread->cached_culture_info) {
534 int i;
535 for (i = 0; i < NUM_CACHED_CULTURES * 2; ++i)
536 mono_array_set (thread->cached_culture_info, MonoObject*, i, NULL);
539 /* if the thread is not in the hash it has been removed already */
540 if (!handle_remove (thread))
541 return;
542 mono_release_type_locks (thread);
544 EnterCriticalSection (thread->synch_cs);
546 thread->state |= ThreadState_Stopped;
547 thread->state &= ~ThreadState_Background;
549 LeaveCriticalSection (thread->synch_cs);
551 mono_profiler_thread_end (thread->tid);
553 if (thread == mono_thread_current ())
554 mono_thread_pop_appdomain_ref ();
556 if (thread->serialized_culture_info)
557 g_free (thread->serialized_culture_info);
559 if (thread->serialized_ui_culture_info)
560 g_free (thread->serialized_ui_culture_info);
562 g_free (thread->name);
564 thread->cached_culture_info = NULL;
566 mono_gc_free_fixed (thread->static_data);
567 thread->static_data = NULL;
569 if (mono_thread_cleanup_fn)
570 mono_thread_cleanup_fn (thread);
572 small_id_free (thread->small_id);
573 thread->small_id = -2;
576 static guint32 WINAPI start_wrapper(void *data)
578 struct StartInfo *start_info=(struct StartInfo *)data;
579 guint32 (*start_func)(void *);
580 void *start_arg;
581 gsize tid;
582 MonoThread *thread=start_info->obj;
583 MonoObject *start_delegate = start_info->delegate;
585 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Start wrapper", __func__, GetCurrentThreadId ()));
587 /* We can be sure start_info->obj->tid and
588 * start_info->obj->handle have been set, because the thread
589 * was created suspended, and these values were set before the
590 * thread resumed
593 tid=thread->tid;
595 SET_CURRENT_OBJECT (thread);
597 mono_monitor_init_tls ();
599 /* Every thread references the appdomain which created it */
600 mono_thread_push_appdomain_ref (start_info->domain);
602 if (!mono_domain_set (start_info->domain, FALSE)) {
603 /* No point in raising an appdomain_unloaded exception here */
604 /* FIXME: Cleanup here */
605 mono_thread_pop_appdomain_ref ();
606 return 0;
609 start_func = start_info->func;
610 start_arg = start_info->start_arg;
612 /* This MUST be called before any managed code can be
613 * executed, as it calls the callback function that (for the
614 * jit) sets the lmf marker.
616 mono_thread_new_init (tid, &tid, start_func);
617 thread->stack_ptr = &tid;
619 LIBGC_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT",%d) Setting thread stack to %p", __func__, GetCurrentThreadId (), getpid (), thread->stack_ptr));
621 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Setting current_object_key to %p", __func__, GetCurrentThreadId (), thread));
623 /* On 2.0 profile (and higher), set explicitly since state might have been
624 Unknown */
625 if (mono_framework_version () != 1) {
626 if (thread->apartment_state == ThreadApartmentState_Unknown)
627 thread->apartment_state = ThreadApartmentState_MTA;
630 mono_thread_init_apartment_state ();
632 if(thread->start_notify!=NULL) {
633 /* Let the thread that called Start() know we're
634 * ready
636 ReleaseSemaphore (thread->start_notify, 1, NULL);
639 mono_threads_lock ();
640 mono_g_hash_table_remove (thread_start_args, thread);
641 mono_threads_unlock ();
643 g_free (start_info);
645 thread_adjust_static_data (thread);
646 #ifdef DEBUG
647 g_message ("%s: start_wrapper for %"G_GSIZE_FORMAT, __func__,
648 thread->tid);
649 #endif
651 mono_thread_set_execution_context (thread->ec_to_set);
654 * Call this after calling start_notify, since the profiler callback might want
655 * to lock the thread, and the lock is held by thread_start () which waits for
656 * start_notify.
658 mono_profiler_thread_start (tid);
660 /* start_func is set only for unmanaged start functions */
661 if (start_func) {
662 start_func (start_arg);
663 } else {
664 void *args [1];
665 g_assert (start_delegate != NULL);
666 args [0] = start_arg;
667 /* we may want to handle the exception here. See comment below on unhandled exceptions */
668 mono_runtime_delegate_invoke (start_delegate, args, NULL);
671 /* If the thread calls ExitThread at all, this remaining code
672 * will not be executed, but the main thread will eventually
673 * call thread_cleanup() on this thread's behalf.
676 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Start wrapper terminating", __func__, GetCurrentThreadId ()));
678 thread_cleanup (thread);
680 /* Do any cleanup needed for apartment state. This
681 * cannot be done in thread_cleanup since thread_cleanup could be
682 * called for a thread other than the current thread.
683 * mono_thread_cleanup_apartment_state cleans up apartment
684 * for the current thead */
685 mono_thread_cleanup_apartment_state ();
687 /* Remove the reference to the thread object in the TLS data,
688 * so the thread object can be finalized. This won't be
689 * reached if the thread threw an uncaught exception, so those
690 * thread handles will stay referenced :-( (This is due to
691 * missing support for scanning thread-specific data in the
692 * Boehm GC - the io-layer keeps a GC-visible hash of pointers
693 * to TLS data.)
695 SET_CURRENT_OBJECT (NULL);
697 return(0);
700 void mono_thread_new_init (gsize tid, gpointer stack_start, gpointer func)
702 if (mono_thread_start_cb) {
703 mono_thread_start_cb (tid, stack_start, func);
707 void mono_threads_set_default_stacksize (guint32 stacksize)
709 default_stacksize = stacksize;
712 guint32 mono_threads_get_default_stacksize (void)
714 return default_stacksize;
718 * mono_create_thread:
720 * This is a wrapper around CreateThread which handles differences in the type of
721 * the the 'tid' argument.
723 gpointer mono_create_thread (WapiSecurityAttributes *security,
724 guint32 stacksize, WapiThreadStart start,
725 gpointer param, guint32 create, gsize *tid)
727 gpointer res;
729 #ifdef PLATFORM_WIN32
730 DWORD real_tid;
732 res = CreateThread (security, stacksize, start, param, create, &real_tid);
733 if (tid)
734 *tid = real_tid;
735 #else
736 res = CreateThread (security, stacksize, start, param, create, tid);
737 #endif
739 return res;
743 * The thread start argument may be an object reference, and there is
744 * no ref to keep it alive when the new thread is started but not yet
745 * registered with the collector. So we store it in a GC tracked hash
746 * table.
748 * LOCKING: Assumes the threads lock is held.
750 static void
751 register_thread_start_argument (MonoThread *thread, struct StartInfo *start_info)
753 if (thread_start_args == NULL) {
754 MONO_GC_REGISTER_ROOT (thread_start_args);
755 thread_start_args = mono_g_hash_table_new (NULL, NULL);
757 mono_g_hash_table_insert (thread_start_args, thread, start_info->start_arg);
760 MonoThread* mono_thread_create_internal (MonoDomain *domain, gpointer func, gpointer arg, gboolean threadpool_thread)
762 MonoThread *thread;
763 HANDLE thread_handle;
764 struct StartInfo *start_info;
765 gsize tid;
767 thread=(MonoThread *)mono_object_new (domain,
768 mono_defaults.thread_class);
770 start_info=g_new0 (struct StartInfo, 1);
771 start_info->func = func;
772 start_info->obj = thread;
773 start_info->domain = domain;
774 start_info->start_arg = arg;
776 mono_threads_lock ();
777 if (shutting_down) {
778 mono_threads_unlock ();
779 g_free (start_info);
780 return NULL;
782 if (threads_starting_up == NULL) {
783 MONO_GC_REGISTER_ROOT (threads_starting_up);
784 threads_starting_up = mono_g_hash_table_new (NULL, NULL);
787 register_thread_start_argument (thread, start_info);
788 mono_g_hash_table_insert (threads_starting_up, thread, thread);
789 mono_threads_unlock ();
791 /* Create suspended, so we can do some housekeeping before the thread
792 * starts
794 thread_handle = mono_create_thread (NULL, default_stacksize_for_thread (thread), (LPTHREAD_START_ROUTINE)start_wrapper, start_info,
795 CREATE_SUSPENDED, &tid);
796 THREAD_DEBUG (g_message ("%s: Started thread ID %"G_GSIZE_FORMAT" (handle %p)", __func__, tid, thread_handle));
797 if (thread_handle == NULL) {
798 /* The thread couldn't be created, so throw an exception */
799 mono_threads_lock ();
800 mono_g_hash_table_remove (threads_starting_up, thread);
801 mono_threads_unlock ();
802 g_free (start_info);
803 mono_raise_exception (mono_get_exception_execution_engine ("Couldn't create thread"));
804 return NULL;
807 thread->handle=thread_handle;
808 thread->tid=tid;
809 thread->apartment_state=ThreadApartmentState_Unknown;
810 small_id_alloc (thread);
812 thread->synch_cs = g_new0 (CRITICAL_SECTION, 1);
813 InitializeCriticalSection (thread->synch_cs);
815 thread->threadpool_thread = threadpool_thread;
816 if (threadpool_thread)
817 mono_thread_set_state (thread, ThreadState_Background);
819 if (handle_store (thread))
820 ResumeThread (thread_handle);
822 return thread;
825 void
826 mono_thread_create (MonoDomain *domain, gpointer func, gpointer arg)
828 mono_thread_create_internal (domain, func, arg, FALSE);
832 * mono_thread_get_stack_bounds:
834 * Return the address and size of the current threads stack. Return NULL as the
835 * stack address if the stack address cannot be determined.
837 void
838 mono_thread_get_stack_bounds (guint8 **staddr, size_t *stsize)
840 #if defined(HAVE_PTHREAD_GET_STACKSIZE_NP) && defined(HAVE_PTHREAD_GET_STACKADDR_NP)
841 *staddr = (guint8*)pthread_get_stackaddr_np (pthread_self ());
842 *stsize = pthread_get_stacksize_np (pthread_self ());
843 *staddr = (guint8*)((gssize)*staddr & ~(mono_pagesize () - 1));
844 return;
845 /* FIXME: simplify the mess below */
846 #elif !defined(PLATFORM_WIN32)
847 pthread_attr_t attr;
848 guint8 *current = (guint8*)&attr;
850 pthread_attr_init (&attr);
851 # ifdef HAVE_PTHREAD_GETATTR_NP
852 pthread_getattr_np (pthread_self(), &attr);
853 # else
854 # ifdef HAVE_PTHREAD_ATTR_GET_NP
855 pthread_attr_get_np (pthread_self(), &attr);
856 # elif defined(sun)
857 *staddr = NULL;
858 pthread_attr_getstacksize (&attr, &stsize);
859 # else
860 *staddr = NULL;
861 *stsize = 0;
862 return;
863 # endif
864 # endif
866 # ifndef sun
867 pthread_attr_getstack (&attr, (void**)staddr, stsize);
868 if (*staddr)
869 g_assert ((current > *staddr) && (current < *staddr + *stsize));
870 # endif
872 pthread_attr_destroy (&attr);
873 #endif
875 /* When running under emacs, sometimes staddr is not aligned to a page size */
876 *staddr = (guint8*)((gssize)*staddr & ~(mono_pagesize () - 1));
879 MonoThread *
880 mono_thread_attach (MonoDomain *domain)
882 MonoThread *thread;
883 HANDLE thread_handle;
884 gsize tid;
886 if ((thread = mono_thread_current ())) {
887 if (domain != mono_domain_get ())
888 mono_domain_set (domain, TRUE);
889 /* Already attached */
890 return thread;
893 if (!mono_gc_register_thread (&domain)) {
894 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 ());
897 thread = (MonoThread *)mono_object_new (domain,
898 mono_defaults.thread_class);
900 thread_handle = GetCurrentThread ();
901 g_assert (thread_handle);
903 tid=GetCurrentThreadId ();
906 * The handle returned by GetCurrentThread () is a pseudo handle, so it can't be used to
907 * refer to the thread from other threads for things like aborting.
909 DuplicateHandle (GetCurrentProcess (), thread_handle, GetCurrentProcess (), &thread_handle,
910 THREAD_ALL_ACCESS, TRUE, 0);
912 thread->handle=thread_handle;
913 thread->tid=tid;
914 thread->apartment_state=ThreadApartmentState_Unknown;
915 small_id_alloc (thread);
916 thread->stack_ptr = &tid;
918 thread->synch_cs = g_new0 (CRITICAL_SECTION, 1);
919 InitializeCriticalSection (thread->synch_cs);
921 THREAD_DEBUG (g_message ("%s: Attached thread ID %"G_GSIZE_FORMAT" (handle %p)", __func__, tid, thread_handle));
923 if (!handle_store (thread)) {
924 /* Mono is shutting down, so just wait for the end */
925 for (;;)
926 Sleep (10000);
929 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Setting current_object_key to %p", __func__, GetCurrentThreadId (), thread));
931 SET_CURRENT_OBJECT (thread);
932 mono_domain_set (domain, TRUE);
934 mono_monitor_init_tls ();
936 thread_adjust_static_data (thread);
938 if (mono_thread_attach_cb) {
939 guint8 *staddr;
940 size_t stsize;
942 mono_thread_get_stack_bounds (&staddr, &stsize);
944 if (staddr == NULL)
945 mono_thread_attach_cb (tid, &tid);
946 else
947 mono_thread_attach_cb (tid, staddr + stsize);
950 // FIXME: Need a separate callback
951 mono_profiler_thread_start (tid);
953 return(thread);
956 void
957 mono_thread_detach (MonoThread *thread)
959 g_return_if_fail (thread != NULL);
961 THREAD_DEBUG (g_message ("%s: mono_thread_detach for %p (%"G_GSIZE_FORMAT")", __func__, thread, (gsize)thread->tid));
963 thread_cleanup (thread);
965 SET_CURRENT_OBJECT (NULL);
967 /* Don't need to CloseHandle this thread, even though we took a
968 * reference in mono_thread_attach (), because the GC will do it
969 * when the Thread object is finalised.
973 void
974 mono_thread_exit ()
976 MonoThread *thread = mono_thread_current ();
978 THREAD_DEBUG (g_message ("%s: mono_thread_exit for %p (%"G_GSIZE_FORMAT")", __func__, thread, (gsize)thread->tid));
980 thread_cleanup (thread);
981 SET_CURRENT_OBJECT (NULL);
983 /* we could add a callback here for embedders to use. */
984 if (thread == mono_thread_get_main ())
985 exit (mono_environment_exitcode_get ());
986 ExitThread (-1);
989 HANDLE ves_icall_System_Threading_Thread_Thread_internal(MonoThread *this,
990 MonoObject *start)
992 guint32 (*start_func)(void *);
993 struct StartInfo *start_info;
994 HANDLE thread;
995 gsize tid;
997 MONO_ARCH_SAVE_REGS;
999 THREAD_DEBUG (g_message("%s: Trying to start a new thread: this (%p) start (%p)", __func__, this, start));
1001 ensure_synch_cs_set (this);
1003 EnterCriticalSection (this->synch_cs);
1005 if ((this->state & ThreadState_Unstarted) == 0) {
1006 LeaveCriticalSection (this->synch_cs);
1007 mono_raise_exception (mono_get_exception_thread_state ("Thread has already been started."));
1008 return NULL;
1011 this->small_id = -1;
1013 if ((this->state & ThreadState_Aborted) != 0) {
1014 LeaveCriticalSection (this->synch_cs);
1015 return this;
1017 start_func = NULL;
1019 /* This is freed in start_wrapper */
1020 start_info = g_new0 (struct StartInfo, 1);
1021 start_info->func = start_func;
1022 start_info->start_arg = this->start_obj; /* FIXME: GC object stored in unmanaged memory */
1023 start_info->delegate = start;
1024 start_info->obj = this;
1025 start_info->domain = mono_domain_get ();
1027 this->start_notify=CreateSemaphore (NULL, 0, 0x7fffffff, NULL);
1028 if(this->start_notify==NULL) {
1029 LeaveCriticalSection (this->synch_cs);
1030 g_warning ("%s: CreateSemaphore error 0x%x", __func__, GetLastError ());
1031 g_free (start_info);
1032 return(NULL);
1035 mono_threads_lock ();
1036 register_thread_start_argument (this, start_info);
1037 if (threads_starting_up == NULL) {
1038 MONO_GC_REGISTER_ROOT (threads_starting_up);
1039 threads_starting_up = mono_g_hash_table_new (NULL, NULL);
1041 mono_g_hash_table_insert (threads_starting_up, this, this);
1042 mono_threads_unlock ();
1044 thread=mono_create_thread(NULL, default_stacksize_for_thread (this), (LPTHREAD_START_ROUTINE)start_wrapper, start_info,
1045 CREATE_SUSPENDED, &tid);
1046 if(thread==NULL) {
1047 LeaveCriticalSection (this->synch_cs);
1048 mono_threads_lock ();
1049 mono_g_hash_table_remove (threads_starting_up, this);
1050 mono_threads_unlock ();
1051 g_warning("%s: CreateThread error 0x%x", __func__, GetLastError());
1052 return(NULL);
1055 this->handle=thread;
1056 this->tid=tid;
1057 small_id_alloc (this);
1059 /* Don't call handle_store() here, delay it to Start.
1060 * We can't join a thread (trying to will just block
1061 * forever) until it actually starts running, so don't
1062 * store the handle till then.
1065 mono_thread_start (this);
1067 this->state &= ~ThreadState_Unstarted;
1069 THREAD_DEBUG (g_message ("%s: Started thread ID %"G_GSIZE_FORMAT" (handle %p)", __func__, tid, thread));
1071 LeaveCriticalSection (this->synch_cs);
1072 return(thread);
1076 void ves_icall_System_Threading_Thread_Thread_init (MonoThread *this)
1078 MONO_ARCH_SAVE_REGS;
1080 ensure_synch_cs_set (this);
1083 void ves_icall_System_Threading_Thread_Thread_free_internal (MonoThread *this,
1084 HANDLE thread)
1086 MONO_ARCH_SAVE_REGS;
1088 THREAD_DEBUG (g_message ("%s: Closing thread %p, handle %p", __func__, this, thread));
1090 if (thread)
1091 CloseHandle (thread);
1093 if (this->synch_cs) {
1094 DeleteCriticalSection (this->synch_cs);
1095 g_free (this->synch_cs);
1096 this->synch_cs = NULL;
1099 g_assert (!this->abort_exc && !this->abort_state_handle);
1102 static void mono_thread_start (MonoThread *thread)
1104 MONO_ARCH_SAVE_REGS;
1106 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Launching thread %p (%"G_GSIZE_FORMAT")", __func__, GetCurrentThreadId (), thread, (gsize)thread->tid));
1108 /* Only store the handle when the thread is about to be
1109 * launched, to avoid the main thread deadlocking while trying
1110 * to clean up a thread that will never be signalled.
1112 if (!handle_store (thread))
1113 return;
1115 ResumeThread (thread->handle);
1117 if(thread->start_notify!=NULL) {
1118 /* Wait for the thread to set up its TLS data etc, so
1119 * theres no potential race condition if someone tries
1120 * to look up the data believing the thread has
1121 * started
1124 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") waiting for thread %p (%"G_GSIZE_FORMAT") to start", __func__, GetCurrentThreadId (), thread, (gsize)thread->tid));
1126 WaitForSingleObjectEx (thread->start_notify, INFINITE, FALSE);
1127 CloseHandle (thread->start_notify);
1128 thread->start_notify = NULL;
1131 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Done launching thread %p (%"G_GSIZE_FORMAT")", __func__, GetCurrentThreadId (), thread, (gsize)thread->tid));
1134 void ves_icall_System_Threading_Thread_Sleep_internal(gint32 ms)
1136 guint32 res;
1137 MonoThread *thread = mono_thread_current ();
1139 MONO_ARCH_SAVE_REGS;
1141 THREAD_DEBUG (g_message ("%s: Sleeping for %d ms", __func__, ms));
1143 mono_thread_current_check_pending_interrupt ();
1145 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1147 res = SleepEx(ms,TRUE);
1149 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1151 if (res == WAIT_IO_COMPLETION) { /* we might have been interrupted */
1152 MonoException* exc = mono_thread_execute_interruption (thread);
1153 if (exc) mono_raise_exception (exc);
1157 void ves_icall_System_Threading_Thread_SpinWait_nop (void)
1161 gint32
1162 ves_icall_System_Threading_Thread_GetDomainID (void)
1164 MONO_ARCH_SAVE_REGS;
1166 return mono_domain_get()->domain_id;
1170 * mono_thread_get_name:
1172 * Return the name of the thread. NAME_LEN is set to the length of the name.
1173 * Return NULL if the thread has no name. The returned memory is owned by the
1174 * caller.
1176 gunichar2*
1177 mono_thread_get_name (MonoThread *this_obj, guint32 *name_len)
1179 gunichar2 *res;
1181 ensure_synch_cs_set (this_obj);
1183 EnterCriticalSection (this_obj->synch_cs);
1185 if (!this_obj->name) {
1186 *name_len = 0;
1187 res = NULL;
1188 } else {
1189 *name_len = this_obj->name_len;
1190 res = g_new (gunichar2, this_obj->name_len);
1191 memcpy (res, this_obj->name, sizeof (gunichar2) * this_obj->name_len);
1194 LeaveCriticalSection (this_obj->synch_cs);
1196 return res;
1199 MonoString*
1200 ves_icall_System_Threading_Thread_GetName_internal (MonoThread *this_obj)
1202 MonoString* str;
1204 ensure_synch_cs_set (this_obj);
1206 EnterCriticalSection (this_obj->synch_cs);
1208 if (!this_obj->name)
1209 str = NULL;
1210 else
1211 str = mono_string_new_utf16 (mono_domain_get (), this_obj->name, this_obj->name_len);
1213 LeaveCriticalSection (this_obj->synch_cs);
1215 return str;
1218 void
1219 ves_icall_System_Threading_Thread_SetName_internal (MonoThread *this_obj, MonoString *name)
1221 ensure_synch_cs_set (this_obj);
1223 EnterCriticalSection (this_obj->synch_cs);
1225 if (this_obj->name) {
1226 LeaveCriticalSection (this_obj->synch_cs);
1228 mono_raise_exception (mono_get_exception_invalid_operation ("Thread.Name can only be set once."));
1229 return;
1231 if (name) {
1232 this_obj->name = g_new (gunichar2, mono_string_length (name));
1233 memcpy (this_obj->name, mono_string_chars (name), mono_string_length (name) * 2);
1234 this_obj->name_len = mono_string_length (name);
1236 else
1237 this_obj->name = NULL;
1239 LeaveCriticalSection (this_obj->synch_cs);
1242 static MonoObject*
1243 lookup_cached_culture (MonoThread *this, MonoDomain *domain, int start_idx)
1245 MonoObject *res;
1246 int i;
1248 if (this->cached_culture_info) {
1249 domain = mono_domain_get ();
1250 for (i = start_idx; i < start_idx + NUM_CACHED_CULTURES; ++i) {
1251 res = mono_array_get (this->cached_culture_info, MonoObject*, i);
1252 if (res && res->vtable->domain == domain)
1253 return res;
1257 return NULL;
1260 MonoObject*
1261 ves_icall_System_Threading_Thread_GetCachedCurrentCulture (MonoThread *this)
1263 return lookup_cached_culture (this, mono_domain_get (), CULTURES_START_IDX);
1266 MonoArray*
1267 ves_icall_System_Threading_Thread_GetSerializedCurrentCulture (MonoThread *this)
1269 MonoArray *res;
1271 ensure_synch_cs_set (this);
1273 EnterCriticalSection (this->synch_cs);
1275 if (this->serialized_culture_info) {
1276 res = mono_array_new (mono_domain_get (), mono_defaults.byte_class, this->serialized_culture_info_len);
1277 memcpy (mono_array_addr (res, guint8, 0), this->serialized_culture_info, this->serialized_culture_info_len);
1278 } else {
1279 res = NULL;
1282 LeaveCriticalSection (this->synch_cs);
1284 return res;
1287 static void
1288 cache_culture (MonoThread *this, MonoObject *culture, int start_idx)
1290 int i;
1291 MonoDomain *domain = mono_domain_get ();
1292 MonoObject *obj;
1293 int free_slot = -1;
1294 int same_domain_slot = -1;
1296 ensure_synch_cs_set (this);
1298 EnterCriticalSection (this->synch_cs);
1300 if (!this->cached_culture_info)
1301 MONO_OBJECT_SETREF (this, cached_culture_info, mono_array_new_cached (mono_object_domain (this), mono_defaults.object_class, NUM_CACHED_CULTURES * 2));
1303 for (i = start_idx; i < start_idx + NUM_CACHED_CULTURES; ++i) {
1304 obj = mono_array_get (this->cached_culture_info, MonoObject*, i);
1305 /* Free entry */
1306 if (!obj) {
1307 free_slot = i;
1308 /* we continue, because there may be a slot used with the same domain */
1309 continue;
1311 /* Replace */
1312 if (obj->vtable->domain == domain) {
1313 same_domain_slot = i;
1314 break;
1317 if (same_domain_slot >= 0)
1318 mono_array_setref (this->cached_culture_info, same_domain_slot, culture);
1319 else if (free_slot >= 0)
1320 mono_array_setref (this->cached_culture_info, free_slot, culture);
1321 /* we may want to replace an existing entry here, even when no suitable slot is found */
1323 LeaveCriticalSection (this->synch_cs);
1326 void
1327 ves_icall_System_Threading_Thread_SetCachedCurrentCulture (MonoThread *this, MonoObject *culture)
1329 cache_culture (this, culture, CULTURES_START_IDX);
1332 void
1333 ves_icall_System_Threading_Thread_SetSerializedCurrentCulture (MonoThread *this, MonoArray *arr)
1335 ensure_synch_cs_set (this);
1337 EnterCriticalSection (this->synch_cs);
1339 if (this->serialized_culture_info)
1340 g_free (this->serialized_culture_info);
1341 this->serialized_culture_info = g_new0 (guint8, mono_array_length (arr));
1342 this->serialized_culture_info_len = mono_array_length (arr);
1343 memcpy (this->serialized_culture_info, mono_array_addr (arr, guint8, 0), mono_array_length (arr));
1345 LeaveCriticalSection (this->synch_cs);
1349 MonoObject*
1350 ves_icall_System_Threading_Thread_GetCachedCurrentUICulture (MonoThread *this)
1352 return lookup_cached_culture (this, mono_domain_get (), UICULTURES_START_IDX);
1355 MonoArray*
1356 ves_icall_System_Threading_Thread_GetSerializedCurrentUICulture (MonoThread *this)
1358 MonoArray *res;
1360 ensure_synch_cs_set (this);
1362 EnterCriticalSection (this->synch_cs);
1364 if (this->serialized_ui_culture_info) {
1365 res = mono_array_new (mono_domain_get (), mono_defaults.byte_class, this->serialized_ui_culture_info_len);
1366 memcpy (mono_array_addr (res, guint8, 0), this->serialized_ui_culture_info, this->serialized_ui_culture_info_len);
1367 } else {
1368 res = NULL;
1371 LeaveCriticalSection (this->synch_cs);
1373 return res;
1376 void
1377 ves_icall_System_Threading_Thread_SetCachedCurrentUICulture (MonoThread *this, MonoObject *culture)
1379 cache_culture (this, culture, UICULTURES_START_IDX);
1382 void
1383 ves_icall_System_Threading_Thread_SetSerializedCurrentUICulture (MonoThread *this, MonoArray *arr)
1385 ensure_synch_cs_set (this);
1387 EnterCriticalSection (this->synch_cs);
1389 if (this->serialized_ui_culture_info)
1390 g_free (this->serialized_ui_culture_info);
1391 this->serialized_ui_culture_info = g_new0 (guint8, mono_array_length (arr));
1392 this->serialized_ui_culture_info_len = mono_array_length (arr);
1393 memcpy (this->serialized_ui_culture_info, mono_array_addr (arr, guint8, 0), mono_array_length (arr));
1395 LeaveCriticalSection (this->synch_cs);
1398 /* the jit may read the compiled code of this function */
1399 MonoThread *
1400 mono_thread_current (void)
1402 MonoThread *res = GET_CURRENT_OBJECT ();
1403 THREAD_DEBUG (g_message ("%s: returning %p", __func__, res));
1404 return res;
1407 gboolean ves_icall_System_Threading_Thread_Join_internal(MonoThread *this,
1408 int ms, HANDLE thread)
1410 MonoThread *cur_thread = mono_thread_current ();
1411 gboolean ret;
1413 MONO_ARCH_SAVE_REGS;
1415 mono_thread_current_check_pending_interrupt ();
1417 ensure_synch_cs_set (this);
1419 EnterCriticalSection (this->synch_cs);
1421 if ((this->state & ThreadState_Unstarted) != 0) {
1422 LeaveCriticalSection (this->synch_cs);
1424 mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started."));
1425 return FALSE;
1428 LeaveCriticalSection (this->synch_cs);
1430 if(ms== -1) {
1431 ms=INFINITE;
1433 THREAD_DEBUG (g_message ("%s: joining thread handle %p, %d ms", __func__, thread, ms));
1435 mono_thread_set_state (cur_thread, ThreadState_WaitSleepJoin);
1437 ret=WaitForSingleObjectEx (thread, ms, TRUE);
1439 mono_thread_clr_state (cur_thread, ThreadState_WaitSleepJoin);
1441 if(ret==WAIT_OBJECT_0) {
1442 THREAD_DEBUG (g_message ("%s: join successful", __func__));
1444 return(TRUE);
1447 THREAD_DEBUG (g_message ("%s: join failed", __func__));
1449 return(FALSE);
1452 /* FIXME: exitContext isnt documented */
1453 gboolean ves_icall_System_Threading_WaitHandle_WaitAll_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext)
1455 HANDLE *handles;
1456 guint32 numhandles;
1457 guint32 ret;
1458 guint32 i;
1459 MonoObject *waitHandle;
1460 MonoThread *thread = mono_thread_current ();
1462 MONO_ARCH_SAVE_REGS;
1464 /* Do this WaitSleepJoin check before creating objects */
1465 mono_thread_current_check_pending_interrupt ();
1467 numhandles = mono_array_length(mono_handles);
1468 handles = g_new0(HANDLE, numhandles);
1470 for(i = 0; i < numhandles; i++) {
1471 waitHandle = mono_array_get(mono_handles, MonoObject*, i);
1472 handles [i] = mono_wait_handle_get_handle ((MonoWaitHandle *) waitHandle);
1475 if(ms== -1) {
1476 ms=INFINITE;
1479 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1481 ret=WaitForMultipleObjectsEx(numhandles, handles, TRUE, ms, TRUE);
1483 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1485 g_free(handles);
1487 if(ret==WAIT_FAILED) {
1488 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait failed", __func__, GetCurrentThreadId ()));
1489 return(FALSE);
1490 } else if(ret==WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION) {
1491 /* Do we want to try again if we get
1492 * WAIT_IO_COMPLETION? The documentation for
1493 * WaitHandle doesn't give any clues. (We'd have to
1494 * fiddle with the timeout if we retry.)
1496 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait timed out", __func__, GetCurrentThreadId ()));
1497 return(FALSE);
1500 return(TRUE);
1503 /* FIXME: exitContext isnt documented */
1504 gint32 ves_icall_System_Threading_WaitHandle_WaitAny_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext)
1506 HANDLE *handles;
1507 guint32 numhandles;
1508 guint32 ret;
1509 guint32 i;
1510 MonoObject *waitHandle;
1511 MonoThread *thread = mono_thread_current ();
1513 MONO_ARCH_SAVE_REGS;
1515 /* Do this WaitSleepJoin check before creating objects */
1516 mono_thread_current_check_pending_interrupt ();
1518 numhandles = mono_array_length(mono_handles);
1519 handles = g_new0(HANDLE, numhandles);
1521 for(i = 0; i < numhandles; i++) {
1522 waitHandle = mono_array_get(mono_handles, MonoObject*, i);
1523 handles [i] = mono_wait_handle_get_handle ((MonoWaitHandle *) waitHandle);
1526 if(ms== -1) {
1527 ms=INFINITE;
1530 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1532 ret=WaitForMultipleObjectsEx(numhandles, handles, FALSE, ms, TRUE);
1534 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1536 g_free(handles);
1538 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") returning %d", __func__, GetCurrentThreadId (), ret));
1541 * These need to be here. See MSDN dos on WaitForMultipleObjects.
1543 if (ret >= WAIT_OBJECT_0 && ret <= WAIT_OBJECT_0 + numhandles - 1) {
1544 return ret - WAIT_OBJECT_0;
1546 else if (ret >= WAIT_ABANDONED_0 && ret <= WAIT_ABANDONED_0 + numhandles - 1) {
1547 return ret - WAIT_ABANDONED_0;
1549 else {
1550 return ret;
1554 /* FIXME: exitContext isnt documented */
1555 gboolean ves_icall_System_Threading_WaitHandle_WaitOne_internal(MonoObject *this, HANDLE handle, gint32 ms, gboolean exitContext)
1557 guint32 ret;
1558 MonoThread *thread = mono_thread_current ();
1560 MONO_ARCH_SAVE_REGS;
1562 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") waiting for %p, %d ms", __func__, GetCurrentThreadId (), handle, ms));
1564 if(ms== -1) {
1565 ms=INFINITE;
1568 mono_thread_current_check_pending_interrupt ();
1570 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1572 ret=WaitForSingleObjectEx (handle, ms, TRUE);
1574 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1576 if(ret==WAIT_FAILED) {
1577 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait failed", __func__, GetCurrentThreadId ()));
1578 return(FALSE);
1579 } else if(ret==WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION) {
1580 /* Do we want to try again if we get
1581 * WAIT_IO_COMPLETION? The documentation for
1582 * WaitHandle doesn't give any clues. (We'd have to
1583 * fiddle with the timeout if we retry.)
1585 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait timed out", __func__, GetCurrentThreadId ()));
1586 return(FALSE);
1589 return(TRUE);
1592 gboolean
1593 ves_icall_System_Threading_WaitHandle_SignalAndWait_Internal (HANDLE toSignal, HANDLE toWait, gint32 ms, gboolean exitContext)
1595 guint32 ret;
1596 MonoThread *thread = mono_thread_current ();
1598 MONO_ARCH_SAVE_REGS;
1600 if (ms == -1)
1601 ms = INFINITE;
1603 mono_thread_current_check_pending_interrupt ();
1605 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1607 ret = SignalObjectAndWait (toSignal, toWait, ms, TRUE);
1609 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1611 return (!(ret == WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION || ret == WAIT_FAILED));
1614 HANDLE ves_icall_System_Threading_Mutex_CreateMutex_internal (MonoBoolean owned, MonoString *name, MonoBoolean *created)
1616 HANDLE mutex;
1618 MONO_ARCH_SAVE_REGS;
1620 *created = TRUE;
1622 if (name == NULL) {
1623 mutex = CreateMutex (NULL, owned, NULL);
1624 } else {
1625 mutex = CreateMutex (NULL, owned, mono_string_chars (name));
1627 if (GetLastError () == ERROR_ALREADY_EXISTS) {
1628 *created = FALSE;
1632 return(mutex);
1635 MonoBoolean ves_icall_System_Threading_Mutex_ReleaseMutex_internal (HANDLE handle ) {
1636 MONO_ARCH_SAVE_REGS;
1638 return(ReleaseMutex (handle));
1641 HANDLE ves_icall_System_Threading_Mutex_OpenMutex_internal (MonoString *name,
1642 gint32 rights,
1643 gint32 *error)
1645 HANDLE ret;
1647 MONO_ARCH_SAVE_REGS;
1649 *error = ERROR_SUCCESS;
1651 ret = OpenMutex (rights, FALSE, mono_string_chars (name));
1652 if (ret == NULL) {
1653 *error = GetLastError ();
1656 return(ret);
1660 HANDLE ves_icall_System_Threading_Semaphore_CreateSemaphore_internal (gint32 initialCount, gint32 maximumCount, MonoString *name, MonoBoolean *created)
1662 HANDLE sem;
1664 MONO_ARCH_SAVE_REGS;
1666 *created = TRUE;
1668 if (name == NULL) {
1669 sem = CreateSemaphore (NULL, initialCount, maximumCount, NULL);
1670 } else {
1671 sem = CreateSemaphore (NULL, initialCount, maximumCount,
1672 mono_string_chars (name));
1674 if (GetLastError () == ERROR_ALREADY_EXISTS) {
1675 *created = FALSE;
1679 return(sem);
1682 gint32 ves_icall_System_Threading_Semaphore_ReleaseSemaphore_internal (HANDLE handle, gint32 releaseCount, MonoBoolean *fail)
1684 gint32 prevcount;
1686 MONO_ARCH_SAVE_REGS;
1688 *fail = !ReleaseSemaphore (handle, releaseCount, &prevcount);
1690 return (prevcount);
1693 HANDLE ves_icall_System_Threading_Semaphore_OpenSemaphore_internal (MonoString *name, gint32 rights, gint32 *error)
1695 HANDLE ret;
1697 MONO_ARCH_SAVE_REGS;
1699 *error = ERROR_SUCCESS;
1701 ret = OpenSemaphore (rights, FALSE, mono_string_chars (name));
1702 if (ret == NULL) {
1703 *error = GetLastError ();
1706 return(ret);
1709 HANDLE ves_icall_System_Threading_Events_CreateEvent_internal (MonoBoolean manual, MonoBoolean initial, MonoString *name, MonoBoolean *created)
1711 HANDLE event;
1713 MONO_ARCH_SAVE_REGS;
1715 *created = TRUE;
1717 if (name == NULL) {
1718 event = CreateEvent (NULL, manual, initial, NULL);
1719 } else {
1720 event = CreateEvent (NULL, manual, initial,
1721 mono_string_chars (name));
1723 if (GetLastError () == ERROR_ALREADY_EXISTS) {
1724 *created = FALSE;
1728 return(event);
1731 gboolean ves_icall_System_Threading_Events_SetEvent_internal (HANDLE handle) {
1732 MONO_ARCH_SAVE_REGS;
1734 return (SetEvent(handle));
1737 gboolean ves_icall_System_Threading_Events_ResetEvent_internal (HANDLE handle) {
1738 MONO_ARCH_SAVE_REGS;
1740 return (ResetEvent(handle));
1743 void
1744 ves_icall_System_Threading_Events_CloseEvent_internal (HANDLE handle) {
1745 MONO_ARCH_SAVE_REGS;
1747 CloseHandle (handle);
1750 HANDLE ves_icall_System_Threading_Events_OpenEvent_internal (MonoString *name,
1751 gint32 rights,
1752 gint32 *error)
1754 HANDLE ret;
1756 MONO_ARCH_SAVE_REGS;
1758 *error = ERROR_SUCCESS;
1760 ret = OpenEvent (rights, FALSE, mono_string_chars (name));
1761 if (ret == NULL) {
1762 *error = GetLastError ();
1765 return(ret);
1768 gint32 ves_icall_System_Threading_Interlocked_Increment_Int (gint32 *location)
1770 MONO_ARCH_SAVE_REGS;
1772 return InterlockedIncrement (location);
1775 gint64 ves_icall_System_Threading_Interlocked_Increment_Long (gint64 *location)
1777 gint64 ret;
1779 MONO_ARCH_SAVE_REGS;
1781 mono_interlocked_lock ();
1783 ret = ++ *location;
1785 mono_interlocked_unlock ();
1788 return ret;
1791 gint32 ves_icall_System_Threading_Interlocked_Decrement_Int (gint32 *location)
1793 MONO_ARCH_SAVE_REGS;
1795 return InterlockedDecrement(location);
1798 gint64 ves_icall_System_Threading_Interlocked_Decrement_Long (gint64 * location)
1800 gint64 ret;
1802 MONO_ARCH_SAVE_REGS;
1804 mono_interlocked_lock ();
1806 ret = -- *location;
1808 mono_interlocked_unlock ();
1810 return ret;
1813 gint32 ves_icall_System_Threading_Interlocked_Exchange_Int (gint32 *location, gint32 value)
1815 MONO_ARCH_SAVE_REGS;
1817 return InterlockedExchange(location, value);
1820 MonoObject * ves_icall_System_Threading_Interlocked_Exchange_Object (MonoObject **location, MonoObject *value)
1822 MonoObject *res;
1823 res = (MonoObject *) InterlockedExchangePointer((gpointer *) location, value);
1824 mono_gc_wbarrier_generic_nostore (location);
1825 return res;
1828 gpointer ves_icall_System_Threading_Interlocked_Exchange_IntPtr (gpointer *location, gpointer value)
1830 return InterlockedExchangePointer(location, value);
1833 gfloat ves_icall_System_Threading_Interlocked_Exchange_Single (gfloat *location, gfloat value)
1835 IntFloatUnion val, ret;
1837 MONO_ARCH_SAVE_REGS;
1839 val.fval = value;
1840 ret.ival = InterlockedExchange((gint32 *) location, val.ival);
1842 return ret.fval;
1845 gint64
1846 ves_icall_System_Threading_Interlocked_Exchange_Long (gint64 *location, gint64 value)
1848 #if SIZEOF_VOID_P == 8
1849 return (gint64) InterlockedExchangePointer((gpointer *) location, (gpointer)value);
1850 #else
1851 gint64 res;
1854 * According to MSDN, this function is only atomic with regards to the
1855 * other Interlocked functions on 32 bit platforms.
1857 mono_interlocked_lock ();
1858 res = *location;
1859 *location = value;
1860 mono_interlocked_unlock ();
1862 return res;
1863 #endif
1866 gdouble
1867 ves_icall_System_Threading_Interlocked_Exchange_Double (gdouble *location, gdouble value)
1869 #if SIZEOF_VOID_P == 8
1870 LongDoubleUnion val, ret;
1872 val.fval = value;
1873 ret.ival = (gint64)InterlockedExchangePointer((gpointer *) location, (gpointer)val.ival);
1875 return ret.fval;
1876 #else
1877 gdouble res;
1880 * According to MSDN, this function is only atomic with regards to the
1881 * other Interlocked functions on 32 bit platforms.
1883 mono_interlocked_lock ();
1884 res = *location;
1885 *location = value;
1886 mono_interlocked_unlock ();
1888 return res;
1889 #endif
1892 gint32 ves_icall_System_Threading_Interlocked_CompareExchange_Int(gint32 *location, gint32 value, gint32 comparand)
1894 MONO_ARCH_SAVE_REGS;
1896 return InterlockedCompareExchange(location, value, comparand);
1899 MonoObject * ves_icall_System_Threading_Interlocked_CompareExchange_Object (MonoObject **location, MonoObject *value, MonoObject *comparand)
1901 MonoObject *res;
1902 res = (MonoObject *) InterlockedCompareExchangePointer((gpointer *) location, value, comparand);
1903 mono_gc_wbarrier_generic_nostore (location);
1904 return res;
1907 gpointer ves_icall_System_Threading_Interlocked_CompareExchange_IntPtr(gpointer *location, gpointer value, gpointer comparand)
1909 return InterlockedCompareExchangePointer(location, value, comparand);
1912 gfloat ves_icall_System_Threading_Interlocked_CompareExchange_Single (gfloat *location, gfloat value, gfloat comparand)
1914 IntFloatUnion val, ret, cmp;
1916 MONO_ARCH_SAVE_REGS;
1918 val.fval = value;
1919 cmp.fval = comparand;
1920 ret.ival = InterlockedCompareExchange((gint32 *) location, val.ival, cmp.ival);
1922 return ret.fval;
1925 gdouble
1926 ves_icall_System_Threading_Interlocked_CompareExchange_Double (gdouble *location, gdouble value, gdouble comparand)
1928 #if SIZEOF_VOID_P == 8
1929 LongDoubleUnion val, comp, ret;
1931 val.fval = value;
1932 comp.fval = comparand;
1933 ret.ival = (gint64)InterlockedCompareExchangePointer((gpointer *) location, (gpointer)val.ival, (gpointer)comp.ival);
1935 return ret.fval;
1936 #else
1937 gdouble old;
1939 mono_interlocked_lock ();
1940 old = *location;
1941 if (old == comparand)
1942 *location = value;
1943 mono_interlocked_unlock ();
1945 return old;
1946 #endif
1949 gint64
1950 ves_icall_System_Threading_Interlocked_CompareExchange_Long (gint64 *location, gint64 value, gint64 comparand)
1952 #if SIZEOF_VOID_P == 8
1953 return (gint64)InterlockedCompareExchangePointer((gpointer *) location, (gpointer)value, (gpointer)comparand);
1954 #else
1955 gint64 old;
1957 mono_interlocked_lock ();
1958 old = *location;
1959 if (old == comparand)
1960 *location = value;
1961 mono_interlocked_unlock ();
1963 return old;
1964 #endif
1967 MonoObject*
1968 ves_icall_System_Threading_Interlocked_CompareExchange_T (MonoObject **location, MonoObject *value, MonoObject *comparand)
1970 MonoObject *res;
1971 res = InterlockedCompareExchangePointer ((gpointer *)location, value, comparand);
1972 mono_gc_wbarrier_generic_nostore (location);
1973 return res;
1976 MonoObject*
1977 ves_icall_System_Threading_Interlocked_Exchange_T (MonoObject **location, MonoObject *value)
1979 MonoObject *res;
1980 res = InterlockedExchangePointer ((gpointer *)location, value);
1981 mono_gc_wbarrier_generic_nostore (location);
1982 return res;
1985 gint32
1986 ves_icall_System_Threading_Interlocked_Add_Int (gint32 *location, gint32 value)
1988 #if SIZEOF_VOID_P == 8
1989 /* Should be implemented as a JIT intrinsic */
1990 mono_raise_exception (mono_get_exception_not_implemented (NULL));
1991 return 0;
1992 #else
1993 gint32 orig;
1995 mono_interlocked_lock ();
1996 orig = *location;
1997 *location = orig + value;
1998 mono_interlocked_unlock ();
2000 return orig + value;
2001 #endif
2004 gint64
2005 ves_icall_System_Threading_Interlocked_Add_Long (gint64 *location, gint64 value)
2007 #if SIZEOF_VOID_P == 8
2008 /* Should be implemented as a JIT intrinsic */
2009 mono_raise_exception (mono_get_exception_not_implemented (NULL));
2010 return 0;
2011 #else
2012 gint64 orig;
2014 mono_interlocked_lock ();
2015 orig = *location;
2016 *location = orig + value;
2017 mono_interlocked_unlock ();
2019 return orig + value;
2020 #endif
2023 gint64
2024 ves_icall_System_Threading_Interlocked_Read_Long (gint64 *location)
2026 #if SIZEOF_VOID_P == 8
2027 /* 64 bit reads are already atomic */
2028 return *location;
2029 #else
2030 gint64 res;
2032 mono_interlocked_lock ();
2033 res = *location;
2034 mono_interlocked_unlock ();
2036 return res;
2037 #endif
2040 void
2041 ves_icall_System_Threading_Thread_MemoryBarrier (void)
2043 mono_threads_lock ();
2044 mono_threads_unlock ();
2047 void
2048 ves_icall_System_Threading_Thread_ClrState (MonoThread* this, guint32 state)
2050 mono_thread_clr_state (this, state);
2052 if (state & ThreadState_Background) {
2053 /* If the thread changes the background mode, the main thread has to
2054 * be notified, since it has to rebuild the list of threads to
2055 * wait for.
2057 SetEvent (background_change_event);
2061 void
2062 ves_icall_System_Threading_Thread_SetState (MonoThread* this, guint32 state)
2064 mono_thread_set_state (this, state);
2066 if (state & ThreadState_Background) {
2067 /* If the thread changes the background mode, the main thread has to
2068 * be notified, since it has to rebuild the list of threads to
2069 * wait for.
2071 SetEvent (background_change_event);
2075 guint32
2076 ves_icall_System_Threading_Thread_GetState (MonoThread* this)
2078 guint32 state;
2080 ensure_synch_cs_set (this);
2082 EnterCriticalSection (this->synch_cs);
2084 state = this->state;
2086 LeaveCriticalSection (this->synch_cs);
2088 return state;
2091 void ves_icall_System_Threading_Thread_Interrupt_internal (MonoThread *this)
2093 gboolean throw = FALSE;
2095 ensure_synch_cs_set (this);
2097 if (this == mono_thread_current ())
2098 return;
2100 EnterCriticalSection (this->synch_cs);
2102 this->thread_interrupt_requested = TRUE;
2104 if (this->state & ThreadState_WaitSleepJoin) {
2105 throw = TRUE;
2108 LeaveCriticalSection (this->synch_cs);
2110 if (throw) {
2111 signal_thread_state_change (this);
2115 void mono_thread_current_check_pending_interrupt ()
2117 MonoThread *thread = mono_thread_current ();
2118 gboolean throw = FALSE;
2120 mono_debugger_check_interruption ();
2122 ensure_synch_cs_set (thread);
2124 EnterCriticalSection (thread->synch_cs);
2126 if (thread->thread_interrupt_requested) {
2127 throw = TRUE;
2128 thread->thread_interrupt_requested = FALSE;
2131 LeaveCriticalSection (thread->synch_cs);
2133 if (throw) {
2134 mono_raise_exception (mono_get_exception_thread_interrupted ());
2138 int
2139 mono_thread_get_abort_signal (void)
2141 #ifdef PLATFORM_WIN32
2142 return -1;
2143 #else
2144 #ifndef SIGRTMIN
2145 #ifdef SIGUSR1
2146 return SIGUSR1;
2147 #else
2148 return -1;
2149 #endif
2150 #else
2151 static int abort_signum = -1;
2152 int i;
2153 if (abort_signum != -1)
2154 return abort_signum;
2155 /* we try to avoid SIGRTMIN and any one that might have been set already, see bug #75387 */
2156 for (i = SIGRTMIN + 1; i < SIGRTMAX; ++i) {
2157 struct sigaction sinfo;
2158 sigaction (i, NULL, &sinfo);
2159 if (sinfo.sa_handler == SIG_DFL && (void*)sinfo.sa_sigaction == (void*)SIG_DFL) {
2160 abort_signum = i;
2161 return i;
2164 /* fallback to the old way */
2165 return SIGRTMIN;
2166 #endif
2167 #endif /* PLATFORM_WIN32 */
2170 #ifdef PLATFORM_WIN32
2171 static void CALLBACK interruption_request_apc (ULONG_PTR param)
2173 MonoException* exc = mono_thread_request_interruption (FALSE);
2174 if (exc) mono_raise_exception (exc);
2176 #endif /* PLATFORM_WIN32 */
2179 * signal_thread_state_change
2181 * Tells the thread that his state has changed and it has to enter the new
2182 * state as soon as possible.
2184 static void signal_thread_state_change (MonoThread *thread)
2186 if (thread == mono_thread_current ()) {
2187 /* Do it synchronously */
2188 MonoException *exc = mono_thread_request_interruption (FALSE);
2189 if (exc)
2190 mono_raise_exception (exc);
2193 #ifdef PLATFORM_WIN32
2194 QueueUserAPC ((PAPCFUNC)interruption_request_apc, thread->handle, NULL);
2195 #else
2196 /* fixme: store the state somewhere */
2197 #ifdef PTHREAD_POINTER_ID
2198 pthread_kill ((gpointer)(gsize)(thread->tid), mono_thread_get_abort_signal ());
2199 #else
2200 pthread_kill (thread->tid, mono_thread_get_abort_signal ());
2201 #endif
2204 * This will cause waits to be broken.
2205 * It will also prevent the thread from entering a wait, so if the thread returns
2206 * from the wait before it receives the abort signal, it will just spin in the wait
2207 * functions in the io-layer until the signal handler calls QueueUserAPC which will
2208 * make it return.
2210 wapi_interrupt_thread (thread->handle);
2211 #endif /* PLATFORM_WIN32 */
2214 void
2215 ves_icall_System_Threading_Thread_Abort (MonoThread *thread, MonoObject *state)
2217 MONO_ARCH_SAVE_REGS;
2219 ensure_synch_cs_set (thread);
2221 EnterCriticalSection (thread->synch_cs);
2223 if ((thread->state & ThreadState_AbortRequested) != 0 ||
2224 (thread->state & ThreadState_StopRequested) != 0 ||
2225 (thread->state & ThreadState_Stopped) != 0)
2227 LeaveCriticalSection (thread->synch_cs);
2228 return;
2231 if ((thread->state & ThreadState_Unstarted) != 0) {
2232 thread->state |= ThreadState_Aborted;
2233 LeaveCriticalSection (thread->synch_cs);
2234 return;
2237 thread->state |= ThreadState_AbortRequested;
2238 if (thread->abort_state_handle)
2239 mono_gchandle_free (thread->abort_state_handle);
2240 if (state) {
2241 thread->abort_state_handle = mono_gchandle_new (state, FALSE);
2242 g_assert (thread->abort_state_handle);
2243 } else {
2244 thread->abort_state_handle = 0;
2246 thread->abort_exc = NULL;
2248 LeaveCriticalSection (thread->synch_cs);
2250 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Abort requested for %p (%"G_GSIZE_FORMAT")", __func__, GetCurrentThreadId (), thread, (gsize)thread->tid));
2252 /* During shutdown, we can't wait for other threads */
2253 if (!shutting_down)
2254 /* Make sure the thread is awake */
2255 mono_thread_resume (thread);
2257 signal_thread_state_change (thread);
2260 void
2261 ves_icall_System_Threading_Thread_ResetAbort (void)
2263 MonoThread *thread = mono_thread_current ();
2265 MONO_ARCH_SAVE_REGS;
2267 ensure_synch_cs_set (thread);
2269 EnterCriticalSection (thread->synch_cs);
2271 thread->state &= ~ThreadState_AbortRequested;
2273 if (!thread->abort_exc) {
2274 const char *msg = "Unable to reset abort because no abort was requested";
2275 LeaveCriticalSection (thread->synch_cs);
2276 mono_raise_exception (mono_get_exception_thread_state (msg));
2277 } else {
2278 thread->abort_exc = NULL;
2279 if (thread->abort_state_handle) {
2280 mono_gchandle_free (thread->abort_state_handle);
2281 /* This is actually not necessary - the handle
2282 only counts if the exception is set */
2283 thread->abort_state_handle = 0;
2287 LeaveCriticalSection (thread->synch_cs);
2290 static MonoObject*
2291 serialize_object (MonoObject *obj, gboolean *failure, MonoObject **exc)
2293 static MonoMethod *serialize_method;
2295 void *params [1];
2296 MonoObject *array;
2298 if (!serialize_method) {
2299 MonoClass *klass = mono_class_from_name (mono_defaults.corlib, "System.Runtime.Remoting", "RemotingServices");
2300 serialize_method = mono_class_get_method_from_name (klass, "SerializeCallData", -1);
2303 if (!serialize_method) {
2304 *failure = TRUE;
2305 return NULL;
2308 g_assert (!obj->vtable->klass->marshalbyref);
2310 params [0] = obj;
2311 *exc = NULL;
2312 array = mono_runtime_invoke (serialize_method, NULL, params, exc);
2313 if (*exc)
2314 *failure = TRUE;
2316 return array;
2319 static MonoObject*
2320 deserialize_object (MonoObject *obj, gboolean *failure, MonoObject **exc)
2322 static MonoMethod *deserialize_method;
2324 void *params [1];
2325 MonoObject *result;
2327 if (!deserialize_method) {
2328 MonoClass *klass = mono_class_from_name (mono_defaults.corlib, "System.Runtime.Remoting", "RemotingServices");
2329 deserialize_method = mono_class_get_method_from_name (klass, "DeserializeCallData", -1);
2331 if (!deserialize_method) {
2332 *failure = TRUE;
2333 return NULL;
2336 params [0] = obj;
2337 *exc = NULL;
2338 result = mono_runtime_invoke (deserialize_method, NULL, params, exc);
2339 if (*exc)
2340 *failure = TRUE;
2342 return result;
2345 static MonoObject*
2346 make_transparent_proxy (MonoObject *obj, gboolean *failure, MonoObject **exc)
2348 static MonoMethod *get_proxy_method;
2350 MonoDomain *domain = mono_domain_get ();
2351 MonoRealProxy *real_proxy;
2352 MonoReflectionType *reflection_type;
2353 MonoTransparentProxy *transparent_proxy;
2355 if (!get_proxy_method)
2356 get_proxy_method = mono_class_get_method_from_name (mono_defaults.real_proxy_class, "GetTransparentProxy", 0);
2358 g_assert (obj->vtable->klass->marshalbyref);
2360 real_proxy = (MonoRealProxy*) mono_object_new (domain, mono_defaults.real_proxy_class);
2361 reflection_type = mono_type_get_object (domain, &obj->vtable->klass->byval_arg);
2363 real_proxy->class_to_proxy = reflection_type;
2364 real_proxy->unwrapped_server = obj;
2366 *exc = NULL;
2367 transparent_proxy = (MonoTransparentProxy*) mono_runtime_invoke (get_proxy_method, real_proxy, NULL, exc);
2368 if (*exc)
2369 *failure = TRUE;
2371 return (MonoObject*) transparent_proxy;
2374 MonoObject*
2375 ves_icall_System_Threading_Thread_GetAbortExceptionState (MonoThread *thread)
2377 MonoObject *state, *serialized, *deserialized = NULL, *exc;
2378 MonoDomain *domain;
2379 gboolean failure = FALSE;
2381 if (!thread->abort_state_handle)
2382 return NULL;
2384 state = mono_gchandle_get_target (thread->abort_state_handle);
2385 g_assert (state);
2387 domain = mono_domain_get ();
2388 if (state->vtable->domain == domain)
2389 return state;
2391 if (state->vtable->klass->marshalbyref) {
2392 deserialized = make_transparent_proxy (state, &failure, &exc);
2393 } else {
2394 mono_domain_set_internal_with_options (state->vtable->domain, FALSE);
2395 serialized = serialize_object (state, &failure, &exc);
2396 mono_domain_set_internal_with_options (domain, FALSE);
2397 if (!failure)
2398 deserialized = deserialize_object (serialized, &failure, &exc);
2401 if (failure) {
2402 MonoException *invalid_op_exc = mono_get_exception_invalid_operation ("Thread.ExceptionState cannot access an ExceptionState from a different AppDomain");
2403 if (exc)
2404 MONO_OBJECT_SETREF (invalid_op_exc, inner_ex, exc);
2405 mono_raise_exception (invalid_op_exc);
2408 return deserialized;
2411 static gboolean
2412 mono_thread_suspend (MonoThread *thread)
2414 MONO_ARCH_SAVE_REGS;
2416 ensure_synch_cs_set (thread);
2418 EnterCriticalSection (thread->synch_cs);
2420 if ((thread->state & ThreadState_Unstarted) != 0 ||
2421 (thread->state & ThreadState_Aborted) != 0 ||
2422 (thread->state & ThreadState_Stopped) != 0)
2424 LeaveCriticalSection (thread->synch_cs);
2425 return FALSE;
2428 if ((thread->state & ThreadState_Suspended) != 0 ||
2429 (thread->state & ThreadState_SuspendRequested) != 0 ||
2430 (thread->state & ThreadState_StopRequested) != 0)
2432 LeaveCriticalSection (thread->synch_cs);
2433 return TRUE;
2436 thread->state |= ThreadState_SuspendRequested;
2438 LeaveCriticalSection (thread->synch_cs);
2440 signal_thread_state_change (thread);
2441 return TRUE;
2444 void
2445 ves_icall_System_Threading_Thread_Suspend (MonoThread *thread)
2447 if (!mono_thread_suspend (thread))
2448 mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started, or is dead."));
2451 static gboolean
2452 mono_thread_resume (MonoThread *thread)
2454 MONO_ARCH_SAVE_REGS;
2456 ensure_synch_cs_set (thread);
2458 EnterCriticalSection (thread->synch_cs);
2460 if ((thread->state & ThreadState_SuspendRequested) != 0) {
2461 thread->state &= ~ThreadState_SuspendRequested;
2462 LeaveCriticalSection (thread->synch_cs);
2463 return TRUE;
2466 if ((thread->state & ThreadState_Suspended) == 0 ||
2467 (thread->state & ThreadState_Unstarted) != 0 ||
2468 (thread->state & ThreadState_Aborted) != 0 ||
2469 (thread->state & ThreadState_Stopped) != 0)
2471 LeaveCriticalSection (thread->synch_cs);
2472 return FALSE;
2475 thread->resume_event = CreateEvent (NULL, TRUE, FALSE, NULL);
2476 if (thread->resume_event == NULL) {
2477 LeaveCriticalSection (thread->synch_cs);
2478 return(FALSE);
2481 /* Awake the thread */
2482 SetEvent (thread->suspend_event);
2484 LeaveCriticalSection (thread->synch_cs);
2486 /* Wait for the thread to awake */
2487 WaitForSingleObject (thread->resume_event, INFINITE);
2488 CloseHandle (thread->resume_event);
2489 thread->resume_event = NULL;
2491 return TRUE;
2494 void
2495 ves_icall_System_Threading_Thread_Resume (MonoThread *thread)
2497 if (!mono_thread_resume (thread))
2498 mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started, or is dead."));
2501 static gboolean
2502 find_wrapper (MonoMethod *m, gint no, gint ilo, gboolean managed, gpointer data)
2504 if (managed)
2505 return TRUE;
2507 if (m->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE ||
2508 m->wrapper_type == MONO_WRAPPER_XDOMAIN_INVOKE ||
2509 m->wrapper_type == MONO_WRAPPER_XDOMAIN_DISPATCH)
2511 *((gboolean*)data) = TRUE;
2512 return TRUE;
2514 return FALSE;
2517 static gboolean
2518 is_running_protected_wrapper (void)
2520 gboolean found = FALSE;
2521 mono_stack_walk (find_wrapper, &found);
2522 return found;
2525 void mono_thread_stop (MonoThread *thread)
2527 ensure_synch_cs_set (thread);
2529 EnterCriticalSection (thread->synch_cs);
2531 if ((thread->state & ThreadState_StopRequested) != 0 ||
2532 (thread->state & ThreadState_Stopped) != 0)
2534 LeaveCriticalSection (thread->synch_cs);
2535 return;
2538 /* Make sure the thread is awake */
2539 mono_thread_resume (thread);
2541 thread->state |= ThreadState_StopRequested;
2542 thread->state &= ~ThreadState_AbortRequested;
2544 LeaveCriticalSection (thread->synch_cs);
2546 signal_thread_state_change (thread);
2549 gint8
2550 ves_icall_System_Threading_Thread_VolatileRead1 (void *ptr)
2552 return *((volatile gint8 *) (ptr));
2555 gint16
2556 ves_icall_System_Threading_Thread_VolatileRead2 (void *ptr)
2558 return *((volatile gint16 *) (ptr));
2561 gint32
2562 ves_icall_System_Threading_Thread_VolatileRead4 (void *ptr)
2564 return *((volatile gint32 *) (ptr));
2567 gint64
2568 ves_icall_System_Threading_Thread_VolatileRead8 (void *ptr)
2570 return *((volatile gint64 *) (ptr));
2573 void *
2574 ves_icall_System_Threading_Thread_VolatileReadIntPtr (void *ptr)
2576 return (void *) *((volatile void **) ptr);
2579 void
2580 ves_icall_System_Threading_Thread_VolatileWrite1 (void *ptr, gint8 value)
2582 *((volatile gint8 *) ptr) = value;
2585 void
2586 ves_icall_System_Threading_Thread_VolatileWrite2 (void *ptr, gint16 value)
2588 *((volatile gint16 *) ptr) = value;
2591 void
2592 ves_icall_System_Threading_Thread_VolatileWrite4 (void *ptr, gint32 value)
2594 *((volatile gint32 *) ptr) = value;
2597 void
2598 ves_icall_System_Threading_Thread_VolatileWrite8 (void *ptr, gint64 value)
2600 *((volatile gint64 *) ptr) = value;
2603 void
2604 ves_icall_System_Threading_Thread_VolatileWriteIntPtr (void *ptr, void *value)
2606 *((volatile void **) ptr) = value;
2609 void
2610 ves_icall_System_Threading_Thread_VolatileWriteObject (void *ptr, void *value)
2612 mono_gc_wbarrier_generic_store (ptr, value);
2615 void mono_thread_init (MonoThreadStartCB start_cb,
2616 MonoThreadAttachCB attach_cb)
2618 MONO_GC_REGISTER_ROOT (small_id_table);
2619 InitializeCriticalSection(&threads_mutex);
2620 InitializeCriticalSection(&interlocked_mutex);
2621 InitializeCriticalSection(&contexts_mutex);
2622 InitializeCriticalSection(&delayed_free_table_mutex);
2623 InitializeCriticalSection(&small_id_mutex);
2625 background_change_event = CreateEvent (NULL, TRUE, FALSE, NULL);
2626 g_assert(background_change_event != NULL);
2628 mono_init_static_data_info (&thread_static_info);
2629 mono_init_static_data_info (&context_static_info);
2631 current_object_key=TlsAlloc();
2632 THREAD_DEBUG (g_message ("%s: Allocated current_object_key %d", __func__, current_object_key));
2634 mono_thread_start_cb = start_cb;
2635 mono_thread_attach_cb = attach_cb;
2637 delayed_free_table = g_array_new (FALSE, FALSE, sizeof (DelayedFreeItem));
2639 /* Get a pseudo handle to the current process. This is just a
2640 * kludge so that wapi can build a process handle if needed.
2641 * As a pseudo handle is returned, we don't need to clean
2642 * anything up.
2644 GetCurrentProcess ();
2647 void mono_thread_cleanup (void)
2649 mono_thread_hazardous_try_free_all ();
2651 #if !defined(PLATFORM_WIN32) && !defined(RUN_IN_SUBTHREAD)
2652 /* The main thread must abandon any held mutexes (particularly
2653 * important for named mutexes as they are shared across
2654 * processes, see bug 74680.) This will happen when the
2655 * thread exits, but if it's not running in a subthread it
2656 * won't exit in time.
2658 /* Using non-w32 API is a nasty kludge, but I couldn't find
2659 * anything in the documentation that would let me do this
2660 * here yet still be safe to call on windows.
2662 _wapi_thread_signal_self (mono_environment_exitcode_get ());
2663 #endif
2665 #if 0
2666 /* This stuff needs more testing, it seems one of these
2667 * critical sections can be locked when mono_thread_cleanup is
2668 * called.
2670 DeleteCriticalSection (&threads_mutex);
2671 DeleteCriticalSection (&interlocked_mutex);
2672 DeleteCriticalSection (&contexts_mutex);
2673 DeleteCriticalSection (&delayed_free_table_mutex);
2674 DeleteCriticalSection (&small_id_mutex);
2675 CloseHandle (background_change_event);
2676 #endif
2678 g_array_free (delayed_free_table, TRUE);
2679 delayed_free_table = NULL;
2681 TlsFree (current_object_key);
2684 void
2685 mono_threads_install_cleanup (MonoThreadCleanupFunc func)
2687 mono_thread_cleanup_fn = func;
2690 void
2691 mono_thread_set_manage_callback (MonoThread *thread, MonoThreadManageCallback func)
2693 thread->manage_callback = func;
2696 void mono_threads_install_notify_pending_exc (MonoThreadNotifyPendingExcFunc func)
2698 mono_thread_notify_pending_exc_fn = func;
2701 G_GNUC_UNUSED
2702 static void print_tids (gpointer key, gpointer value, gpointer user)
2704 /* GPOINTER_TO_UINT breaks horribly if sizeof(void *) >
2705 * sizeof(uint) and a cast to uint would overflow
2707 /* Older versions of glib don't have G_GSIZE_FORMAT, so just
2708 * print this as a pointer.
2710 g_message ("Waiting for: %p", key);
2713 struct wait_data
2715 HANDLE handles[MAXIMUM_WAIT_OBJECTS];
2716 MonoThread *threads[MAXIMUM_WAIT_OBJECTS];
2717 guint32 num;
2720 static void wait_for_tids (struct wait_data *wait, guint32 timeout)
2722 guint32 i, ret;
2724 THREAD_DEBUG (g_message("%s: %d threads to wait for in this batch", __func__, wait->num));
2726 ret=WaitForMultipleObjectsEx(wait->num, wait->handles, TRUE, timeout, FALSE);
2728 if(ret==WAIT_FAILED) {
2729 /* See the comment in build_wait_tids() */
2730 THREAD_DEBUG (g_message ("%s: Wait failed", __func__));
2731 return;
2734 for(i=0; i<wait->num; i++)
2735 CloseHandle (wait->handles[i]);
2737 if (ret == WAIT_TIMEOUT)
2738 return;
2740 for(i=0; i<wait->num; i++) {
2741 gsize tid = wait->threads[i]->tid;
2743 mono_threads_lock ();
2744 if(mono_g_hash_table_lookup (threads, (gpointer)tid)!=NULL) {
2745 /* This thread must have been killed, because
2746 * it hasn't cleaned itself up. (It's just
2747 * possible that the thread exited before the
2748 * parent thread had a chance to store the
2749 * handle, and now there is another pointer to
2750 * the already-exited thread stored. In this
2751 * case, we'll just get two
2752 * mono_profiler_thread_end() calls for the
2753 * same thread.)
2756 mono_threads_unlock ();
2757 THREAD_DEBUG (g_message ("%s: cleaning up after thread %p (%"G_GSIZE_FORMAT")", __func__, wait->threads[i], tid));
2758 thread_cleanup (wait->threads[i]);
2759 } else {
2760 mono_threads_unlock ();
2765 static void wait_for_tids_or_state_change (struct wait_data *wait, guint32 timeout)
2767 guint32 i, ret, count;
2769 THREAD_DEBUG (g_message("%s: %d threads to wait for in this batch", __func__, wait->num));
2771 /* Add the thread state change event, so it wakes up if a thread changes
2772 * to background mode.
2774 count = wait->num;
2775 if (count < MAXIMUM_WAIT_OBJECTS) {
2776 wait->handles [count] = background_change_event;
2777 count++;
2780 ret=WaitForMultipleObjectsEx (count, wait->handles, FALSE, timeout, FALSE);
2782 if(ret==WAIT_FAILED) {
2783 /* See the comment in build_wait_tids() */
2784 THREAD_DEBUG (g_message ("%s: Wait failed", __func__));
2785 return;
2788 for(i=0; i<wait->num; i++)
2789 CloseHandle (wait->handles[i]);
2791 if (ret == WAIT_TIMEOUT)
2792 return;
2794 if (ret < wait->num) {
2795 gsize tid = wait->threads[ret]->tid;
2796 mono_threads_lock ();
2797 if (mono_g_hash_table_lookup (threads, (gpointer)tid)!=NULL) {
2798 /* See comment in wait_for_tids about thread cleanup */
2799 mono_threads_unlock ();
2800 THREAD_DEBUG (g_message ("%s: cleaning up after thread %"G_GSIZE_FORMAT, __func__, tid));
2801 thread_cleanup (wait->threads [ret]);
2802 } else
2803 mono_threads_unlock ();
2807 static void build_wait_tids (gpointer key, gpointer value, gpointer user)
2809 struct wait_data *wait=(struct wait_data *)user;
2811 if(wait->num<MAXIMUM_WAIT_OBJECTS) {
2812 HANDLE handle;
2813 MonoThread *thread=(MonoThread *)value;
2815 /* Ignore background threads, we abort them later */
2816 /* Do not lock here since it is not needed and the caller holds threads_lock */
2817 if (thread->state & ThreadState_Background) {
2818 THREAD_DEBUG (g_message ("%s: ignoring background thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2819 return; /* just leave, ignore */
2822 if (mono_gc_is_finalizer_thread (thread)) {
2823 THREAD_DEBUG (g_message ("%s: ignoring finalizer thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2824 return;
2827 if (thread == mono_thread_current ()) {
2828 THREAD_DEBUG (g_message ("%s: ignoring current thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2829 return;
2832 if (thread == mono_thread_get_main ()) {
2833 THREAD_DEBUG (g_message ("%s: ignoring main thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2834 return;
2837 if (thread->flags & MONO_THREAD_FLAG_DONT_MANAGE) {
2838 THREAD_DEBUG (g_message ("%s: ignoring thread %" G_GSIZE_FORMAT "with DONT_MANAGE flag set.", __func__, (gsize)thread->tid));
2839 return;
2842 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
2843 if (handle == NULL) {
2844 THREAD_DEBUG (g_message ("%s: ignoring unopenable thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2845 return;
2848 THREAD_DEBUG (g_message ("%s: Invoking mono_thread_manage callback on thread %p", __func__, thread));
2849 if ((thread->manage_callback == NULL) || (thread->manage_callback (thread) == TRUE)) {
2850 wait->handles[wait->num]=handle;
2851 wait->threads[wait->num]=thread;
2852 wait->num++;
2854 THREAD_DEBUG (g_message ("%s: adding thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2855 } else {
2856 THREAD_DEBUG (g_message ("%s: ignoring (because of callback) thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2860 } else {
2861 /* Just ignore the rest, we can't do anything with
2862 * them yet
2867 static gboolean
2868 remove_and_abort_threads (gpointer key, gpointer value, gpointer user)
2870 struct wait_data *wait=(struct wait_data *)user;
2871 gsize self = GetCurrentThreadId ();
2872 MonoThread *thread = (MonoThread *) value;
2873 HANDLE handle;
2875 if (wait->num >= MAXIMUM_WAIT_OBJECTS)
2876 return FALSE;
2878 /* The finalizer thread is not a background thread */
2879 if (thread->tid != self && (thread->state & ThreadState_Background) != 0 &&
2880 !(thread->flags & MONO_THREAD_FLAG_DONT_MANAGE)) {
2882 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
2883 if (handle == NULL)
2884 return FALSE;
2886 /* printf ("A: %d\n", wait->num); */
2887 wait->handles[wait->num]=thread->handle;
2888 wait->threads[wait->num]=thread;
2889 wait->num++;
2891 THREAD_DEBUG (g_print ("%s: Aborting id: %"G_GSIZE_FORMAT"\n", __func__, (gsize)thread->tid));
2892 mono_thread_stop (thread);
2893 return TRUE;
2896 return (thread->tid != self && !mono_gc_is_finalizer_thread (thread));
2899 /**
2900 * mono_threads_set_shutting_down:
2902 * Is called by a thread that wants to shut down Mono. If the runtime is already
2903 * shutting down, the calling thread is suspended/stopped, and this function never
2904 * returns.
2906 void
2907 mono_threads_set_shutting_down (void)
2909 MonoThread *current_thread = mono_thread_current ();
2911 mono_threads_lock ();
2913 if (shutting_down) {
2914 mono_threads_unlock ();
2916 /* Make sure we're properly suspended/stopped */
2918 EnterCriticalSection (current_thread->synch_cs);
2920 if ((current_thread->state & ThreadState_SuspendRequested) ||
2921 (current_thread->state & ThreadState_AbortRequested) ||
2922 (current_thread->state & ThreadState_StopRequested)) {
2923 LeaveCriticalSection (current_thread->synch_cs);
2924 mono_thread_execute_interruption (current_thread);
2925 } else {
2926 current_thread->state |= ThreadState_Stopped;
2927 LeaveCriticalSection (current_thread->synch_cs);
2930 /* Wake up other threads potentially waiting for us */
2931 ExitThread (0);
2932 } else {
2933 shutting_down = TRUE;
2935 /* Not really a background state change, but this will
2936 * interrupt the main thread if it is waiting for all
2937 * the other threads.
2939 SetEvent (background_change_event);
2941 mono_threads_unlock ();
2945 /**
2946 * mono_threads_is_shutting_down:
2948 * Returns whether a thread has commenced shutdown of Mono. Note that
2949 * if the function returns FALSE the caller must not assume that
2950 * shutdown is not in progress, because the situation might have
2951 * changed since the function returned. For that reason this function
2952 * is of very limited utility.
2954 gboolean
2955 mono_threads_is_shutting_down (void)
2957 return shutting_down;
2960 void mono_thread_manage (void)
2962 struct wait_data *wait=g_new0 (struct wait_data, 1);
2964 /* join each thread that's still running */
2965 THREAD_DEBUG (g_message ("%s: Joining each running thread...", __func__));
2967 mono_threads_lock ();
2968 if(threads==NULL) {
2969 THREAD_DEBUG (g_message("%s: No threads", __func__));
2970 mono_threads_unlock ();
2971 g_free (wait);
2972 return;
2974 mono_threads_unlock ();
2976 do {
2977 mono_threads_lock ();
2978 if (shutting_down) {
2979 /* somebody else is shutting down */
2980 mono_threads_unlock ();
2981 break;
2983 THREAD_DEBUG (g_message ("%s: There are %d threads to join", __func__, mono_g_hash_table_size (threads));
2984 mono_g_hash_table_foreach (threads, print_tids, NULL));
2986 ResetEvent (background_change_event);
2987 wait->num=0;
2988 mono_g_hash_table_foreach (threads, build_wait_tids, wait);
2989 mono_threads_unlock ();
2990 if(wait->num>0) {
2991 /* Something to wait for */
2992 wait_for_tids_or_state_change (wait, INFINITE);
2994 THREAD_DEBUG (g_message ("%s: I have %d threads after waiting.", __func__, wait->num));
2995 } while(wait->num>0);
2997 mono_threads_set_shutting_down ();
2999 /* No new threads will be created after this point */
3001 mono_runtime_set_shutting_down ();
3003 THREAD_DEBUG (g_message ("%s: threadpool cleanup", __func__));
3004 mono_thread_pool_cleanup ();
3007 * Remove everything but the finalizer thread and self.
3008 * Also abort all the background threads
3009 * */
3010 do {
3011 mono_threads_lock ();
3013 wait->num = 0;
3014 mono_g_hash_table_foreach_remove (threads, remove_and_abort_threads, wait);
3016 mono_threads_unlock ();
3018 THREAD_DEBUG (g_message ("%s: wait->num is now %d", __func__, wait->num));
3019 if(wait->num>0) {
3020 /* Something to wait for */
3021 wait_for_tids (wait, INFINITE);
3023 } while (wait->num > 0);
3026 * give the subthreads a chance to really quit (this is mainly needed
3027 * to get correct user and system times from getrusage/wait/time(1)).
3028 * This could be removed if we avoid pthread_detach() and use pthread_join().
3030 #ifndef PLATFORM_WIN32
3031 sched_yield ();
3032 #endif
3034 g_free (wait);
3037 static void terminate_thread (gpointer key, gpointer value, gpointer user)
3039 MonoThread *thread=(MonoThread *)value;
3041 if(thread->tid != (gsize)user) {
3042 /*TerminateThread (thread->handle, -1);*/
3046 void mono_thread_abort_all_other_threads (void)
3048 gsize self = GetCurrentThreadId ();
3050 mono_threads_lock ();
3051 THREAD_DEBUG (g_message ("%s: There are %d threads to abort", __func__,
3052 mono_g_hash_table_size (threads));
3053 mono_g_hash_table_foreach (threads, print_tids, NULL));
3055 mono_g_hash_table_foreach (threads, terminate_thread, (gpointer)self);
3057 mono_threads_unlock ();
3060 static void
3061 collect_threads_for_suspend (gpointer key, gpointer value, gpointer user_data)
3063 MonoThread *thread = (MonoThread*)value;
3064 struct wait_data *wait = (struct wait_data*)user_data;
3065 HANDLE handle;
3068 * We try to exclude threads early, to avoid running into the MAXIMUM_WAIT_OBJECTS
3069 * limitation.
3070 * This needs no locking.
3072 if ((thread->state & ThreadState_Suspended) != 0 ||
3073 (thread->state & ThreadState_Stopped) != 0)
3074 return;
3076 if (wait->num<MAXIMUM_WAIT_OBJECTS) {
3077 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
3078 if (handle == NULL)
3079 return;
3081 wait->handles [wait->num] = handle;
3082 wait->threads [wait->num] = thread;
3083 wait->num++;
3088 * mono_thread_suspend_all_other_threads:
3090 * Suspend all managed threads except the finalizer thread and this thread. It is
3091 * not possible to resume them later.
3093 void mono_thread_suspend_all_other_threads (void)
3095 struct wait_data *wait = g_new0 (struct wait_data, 1);
3096 int i;
3097 gsize self = GetCurrentThreadId ();
3098 gpointer *events;
3099 guint32 eventidx = 0;
3100 gboolean starting, finished;
3103 * The other threads could be in an arbitrary state at this point, i.e.
3104 * they could be starting up, shutting down etc. This means that there could be
3105 * threads which are not even in the threads hash table yet.
3109 * First we set a barrier which will be checked by all threads before they
3110 * are added to the threads hash table, and they will exit if the flag is set.
3111 * This ensures that no threads could be added to the hash later.
3112 * We will use shutting_down as the barrier for now.
3114 g_assert (shutting_down);
3117 * We make multiple calls to WaitForMultipleObjects since:
3118 * - we can only wait for MAXIMUM_WAIT_OBJECTS threads
3119 * - some threads could exit without becoming suspended
3121 finished = FALSE;
3122 while (!finished) {
3124 * Make a copy of the hashtable since we can't do anything with
3125 * threads while threads_mutex is held.
3127 wait->num = 0;
3128 mono_threads_lock ();
3129 mono_g_hash_table_foreach (threads, collect_threads_for_suspend, wait);
3130 mono_threads_unlock ();
3132 events = g_new0 (gpointer, wait->num);
3133 eventidx = 0;
3134 /* Get the suspended events that we'll be waiting for */
3135 for (i = 0; i < wait->num; ++i) {
3136 MonoThread *thread = wait->threads [i];
3137 gboolean signal_suspend = FALSE;
3139 if ((thread->tid == self) || mono_gc_is_finalizer_thread (thread)) {
3140 //CloseHandle (wait->handles [i]);
3141 wait->threads [i] = NULL; /* ignore this thread in next loop */
3142 continue;
3145 ensure_synch_cs_set (thread);
3147 EnterCriticalSection (thread->synch_cs);
3149 if (thread->suspended_event == NULL) {
3150 thread->suspended_event = CreateEvent (NULL, TRUE, FALSE, NULL);
3151 if (thread->suspended_event == NULL) {
3152 /* Forget this one and go on to the next */
3153 LeaveCriticalSection (thread->synch_cs);
3154 continue;
3158 if ((thread->state & ThreadState_Suspended) != 0 ||
3159 (thread->state & ThreadState_StopRequested) != 0 ||
3160 (thread->state & ThreadState_Stopped) != 0) {
3161 LeaveCriticalSection (thread->synch_cs);
3162 CloseHandle (wait->handles [i]);
3163 wait->threads [i] = NULL; /* ignore this thread in next loop */
3164 continue;
3167 if ((thread->state & ThreadState_SuspendRequested) == 0)
3168 signal_suspend = TRUE;
3170 events [eventidx++] = thread->suspended_event;
3172 /* Convert abort requests into suspend requests */
3173 if ((thread->state & ThreadState_AbortRequested) != 0)
3174 thread->state &= ~ThreadState_AbortRequested;
3176 thread->state |= ThreadState_SuspendRequested;
3178 LeaveCriticalSection (thread->synch_cs);
3180 /* Signal the thread to suspend */
3181 if (signal_suspend)
3182 signal_thread_state_change (thread);
3185 if (eventidx > 0) {
3186 WaitForMultipleObjectsEx (eventidx, events, TRUE, 100, FALSE);
3187 for (i = 0; i < wait->num; ++i) {
3188 MonoThread *thread = wait->threads [i];
3190 if (thread == NULL)
3191 continue;
3193 EnterCriticalSection (thread->synch_cs);
3194 if ((thread->state & ThreadState_Suspended) != 0) {
3195 CloseHandle (thread->suspended_event);
3196 thread->suspended_event = NULL;
3198 LeaveCriticalSection (thread->synch_cs);
3200 } else {
3202 * If there are threads which are starting up, we wait until they
3203 * are suspended when they try to register in the threads hash.
3204 * This is guaranteed to finish, since the threads which can create new
3205 * threads get suspended after a while.
3206 * FIXME: The finalizer thread can still create new threads.
3208 mono_threads_lock ();
3209 if (threads_starting_up)
3210 starting = mono_g_hash_table_size (threads_starting_up) > 0;
3211 else
3212 starting = FALSE;
3213 mono_threads_unlock ();
3214 if (starting)
3215 Sleep (100);
3216 else
3217 finished = TRUE;
3220 g_free (events);
3223 g_free (wait);
3226 static void
3227 collect_threads (gpointer key, gpointer value, gpointer user_data)
3229 MonoThread *thread = (MonoThread*)value;
3230 struct wait_data *wait = (struct wait_data*)user_data;
3231 HANDLE handle;
3233 if (wait->num<MAXIMUM_WAIT_OBJECTS) {
3234 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
3235 if (handle == NULL)
3236 return;
3238 wait->handles [wait->num] = handle;
3239 wait->threads [wait->num] = thread;
3240 wait->num++;
3245 * mono_threads_request_thread_dump:
3247 * Ask all threads except the current to print their stacktrace to stdout.
3249 void
3250 mono_threads_request_thread_dump (void)
3252 struct wait_data *wait = g_new0 (struct wait_data, 1);
3253 int i;
3256 * Make a copy of the hashtable since we can't do anything with
3257 * threads while threads_mutex is held.
3259 mono_threads_lock ();
3260 mono_g_hash_table_foreach (threads, collect_threads, wait);
3261 mono_threads_unlock ();
3263 for (i = 0; i < wait->num; ++i) {
3264 MonoThread *thread = wait->threads [i];
3266 if (!mono_gc_is_finalizer_thread (thread) && (thread != mono_thread_current ()) && !thread->thread_dump_requested) {
3267 thread->thread_dump_requested = TRUE;
3269 signal_thread_state_change (thread);
3272 CloseHandle (wait->handles [i]);
3277 * mono_thread_push_appdomain_ref:
3279 * Register that the current thread may have references to objects in domain
3280 * @domain on its stack. Each call to this function should be paired with a
3281 * call to pop_appdomain_ref.
3283 void
3284 mono_thread_push_appdomain_ref (MonoDomain *domain)
3286 MonoThread *thread = mono_thread_current ();
3288 if (thread) {
3289 /* printf ("PUSH REF: %"G_GSIZE_FORMAT" -> %s.\n", (gsize)thread->tid, domain->friendly_name); */
3290 mono_threads_lock ();
3291 thread->appdomain_refs = g_slist_prepend (thread->appdomain_refs, domain);
3292 mono_threads_unlock ();
3296 void
3297 mono_thread_pop_appdomain_ref (void)
3299 MonoThread *thread = mono_thread_current ();
3301 if (thread) {
3302 /* printf ("POP REF: %"G_GSIZE_FORMAT" -> %s.\n", (gsize)thread->tid, ((MonoDomain*)(thread->appdomain_refs->data))->friendly_name); */
3303 mono_threads_lock ();
3304 /* FIXME: How can the list be empty ? */
3305 if (thread->appdomain_refs)
3306 thread->appdomain_refs = g_slist_remove (thread->appdomain_refs, thread->appdomain_refs->data);
3307 mono_threads_unlock ();
3311 gboolean
3312 mono_thread_has_appdomain_ref (MonoThread *thread, MonoDomain *domain)
3314 gboolean res;
3315 mono_threads_lock ();
3316 res = g_slist_find (thread->appdomain_refs, domain) != NULL;
3317 mono_threads_unlock ();
3318 return res;
3321 typedef struct abort_appdomain_data {
3322 struct wait_data wait;
3323 MonoDomain *domain;
3324 } abort_appdomain_data;
3326 static void
3327 collect_appdomain_thread (gpointer key, gpointer value, gpointer user_data)
3329 MonoThread *thread = (MonoThread*)value;
3330 abort_appdomain_data *data = (abort_appdomain_data*)user_data;
3331 MonoDomain *domain = data->domain;
3333 if (mono_thread_has_appdomain_ref (thread, domain)) {
3334 /* printf ("ABORTING THREAD %p BECAUSE IT REFERENCES DOMAIN %s.\n", thread->tid, domain->friendly_name); */
3336 if(data->wait.num<MAXIMUM_WAIT_OBJECTS) {
3337 HANDLE handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
3338 if (handle == NULL)
3339 return;
3340 data->wait.handles [data->wait.num] = handle;
3341 data->wait.threads [data->wait.num] = thread;
3342 data->wait.num++;
3343 } else {
3344 /* Just ignore the rest, we can't do anything with
3345 * them yet
3352 * mono_threads_abort_appdomain_threads:
3354 * Abort threads which has references to the given appdomain.
3356 gboolean
3357 mono_threads_abort_appdomain_threads (MonoDomain *domain, int timeout)
3359 abort_appdomain_data user_data;
3360 guint32 start_time;
3361 int orig_timeout = timeout;
3362 int i;
3364 THREAD_DEBUG (g_message ("%s: starting abort", __func__));
3366 start_time = mono_msec_ticks ();
3367 do {
3368 mono_threads_lock ();
3370 user_data.domain = domain;
3371 user_data.wait.num = 0;
3372 /* This shouldn't take any locks */
3373 mono_g_hash_table_foreach (threads, collect_appdomain_thread, &user_data);
3374 mono_threads_unlock ();
3376 if (user_data.wait.num > 0) {
3377 /* Abort the threads outside the threads lock */
3378 for (i = 0; i < user_data.wait.num; ++i)
3379 ves_icall_System_Threading_Thread_Abort (user_data.wait.threads [i], NULL);
3382 * We should wait for the threads either to abort, or to leave the
3383 * domain. We can't do the latter, so we wait with a timeout.
3385 wait_for_tids (&user_data.wait, 100);
3388 /* Update remaining time */
3389 timeout -= mono_msec_ticks () - start_time;
3390 start_time = mono_msec_ticks ();
3392 if (orig_timeout != -1 && timeout < 0)
3393 return FALSE;
3395 while (user_data.wait.num > 0);
3397 THREAD_DEBUG (g_message ("%s: abort done", __func__));
3399 return TRUE;
3402 static void
3403 clear_cached_culture (gpointer key, gpointer value, gpointer user_data)
3405 MonoThread *thread = (MonoThread*)value;
3406 MonoDomain *domain = (MonoDomain*)user_data;
3407 int i;
3409 /* No locking needed here */
3410 /* FIXME: why no locking? writes to the cache are protected with synch_cs above */
3412 if (thread->cached_culture_info) {
3413 for (i = 0; i < NUM_CACHED_CULTURES * 2; ++i) {
3414 MonoObject *obj = mono_array_get (thread->cached_culture_info, MonoObject*, i);
3415 if (obj && obj->vtable->domain == domain)
3416 mono_array_set (thread->cached_culture_info, MonoObject*, i, NULL);
3422 * mono_threads_clear_cached_culture:
3424 * Clear the cached_current_culture from all threads if it is in the
3425 * given appdomain.
3427 void
3428 mono_threads_clear_cached_culture (MonoDomain *domain)
3430 mono_threads_lock ();
3431 mono_g_hash_table_foreach (threads, clear_cached_culture, domain);
3432 mono_threads_unlock ();
3436 * mono_thread_get_undeniable_exception:
3438 * Return an exception which needs to be raised when leaving a catch clause.
3439 * This is used for undeniable exception propagation.
3441 MonoException*
3442 mono_thread_get_undeniable_exception (void)
3444 MonoThread *thread = mono_thread_current ();
3446 MONO_ARCH_SAVE_REGS;
3448 if (thread && thread->abort_exc && !is_running_protected_wrapper ()) {
3450 * FIXME: Clear the abort exception and return an AppDomainUnloaded
3451 * exception if the thread no longer references a dying appdomain.
3453 thread->abort_exc->trace_ips = NULL;
3454 thread->abort_exc->stack_trace = NULL;
3455 return thread->abort_exc;
3458 return NULL;
3461 #define NUM_STATIC_DATA_IDX 8
3462 static const int static_data_size [NUM_STATIC_DATA_IDX] = {
3463 1024, 4096, 16384, 65536, 262144, 1048576, 4194304, 16777216
3468 * mono_alloc_static_data
3470 * Allocate memory blocks for storing threads or context static data
3472 static void
3473 mono_alloc_static_data (gpointer **static_data_ptr, guint32 offset)
3475 guint idx = (offset >> 24) - 1;
3476 int i;
3478 gpointer* static_data = *static_data_ptr;
3479 if (!static_data) {
3480 static_data = mono_gc_alloc_fixed (static_data_size [0], NULL);
3481 *static_data_ptr = static_data;
3482 static_data [0] = static_data;
3485 for (i = 1; i <= idx; ++i) {
3486 if (static_data [i])
3487 continue;
3488 static_data [i] = mono_gc_alloc_fixed (static_data_size [i], NULL);
3493 * mono_init_static_data_info
3495 * Initializes static data counters
3497 static void mono_init_static_data_info (StaticDataInfo *static_data)
3499 static_data->idx = 0;
3500 static_data->offset = 0;
3501 static_data->freelist = NULL;
3505 * mono_alloc_static_data_slot
3507 * Generates an offset for static data. static_data contains the counters
3508 * used to generate it.
3510 static guint32
3511 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align)
3513 guint32 offset;
3515 if (!static_data->idx && !static_data->offset) {
3517 * we use the first chunk of the first allocation also as
3518 * an array for the rest of the data
3520 static_data->offset = sizeof (gpointer) * NUM_STATIC_DATA_IDX;
3522 static_data->offset += align - 1;
3523 static_data->offset &= ~(align - 1);
3524 if (static_data->offset + size >= static_data_size [static_data->idx]) {
3525 static_data->idx ++;
3526 g_assert (size <= static_data_size [static_data->idx]);
3527 g_assert (static_data->idx < NUM_STATIC_DATA_IDX);
3528 static_data->offset = 0;
3530 offset = static_data->offset | ((static_data->idx + 1) << 24);
3531 static_data->offset += size;
3532 return offset;
3536 * ensure thread static fields already allocated are valid for thread
3537 * This function is called when a thread is created or on thread attach.
3539 static void
3540 thread_adjust_static_data (MonoThread *thread)
3542 guint32 offset;
3544 mono_threads_lock ();
3545 if (thread_static_info.offset || thread_static_info.idx > 0) {
3546 /* get the current allocated size */
3547 offset = thread_static_info.offset | ((thread_static_info.idx + 1) << 24);
3548 mono_alloc_static_data (&(thread->static_data), offset);
3550 mono_threads_unlock ();
3553 static void
3554 alloc_thread_static_data_helper (gpointer key, gpointer value, gpointer user)
3556 MonoThread *thread = value;
3557 guint32 offset = GPOINTER_TO_UINT (user);
3559 mono_alloc_static_data (&(thread->static_data), offset);
3562 static MonoThreadDomainTls*
3563 search_tls_slot_in_freelist (StaticDataInfo *static_data, guint32 size, guint32 align)
3565 MonoThreadDomainTls* prev = NULL;
3566 MonoThreadDomainTls* tmp = static_data->freelist;
3567 while (tmp) {
3568 if (tmp->size == size) {
3569 if (prev)
3570 prev->next = tmp->next;
3571 else
3572 static_data->freelist = tmp->next;
3573 return tmp;
3575 tmp = tmp->next;
3577 return NULL;
3581 * The offset for a special static variable is composed of three parts:
3582 * a bit that indicates the type of static data (0:thread, 1:context),
3583 * an index in the array of chunks of memory for the thread (thread->static_data)
3584 * and an offset in that chunk of mem. This allows allocating less memory in the
3585 * common case.
3588 guint32
3589 mono_alloc_special_static_data (guint32 static_type, guint32 size, guint32 align)
3591 guint32 offset;
3592 if (static_type == SPECIAL_STATIC_THREAD)
3594 MonoThreadDomainTls *item;
3595 mono_threads_lock ();
3596 item = search_tls_slot_in_freelist (&thread_static_info, size, align);
3597 /*g_print ("TLS alloc: %d in domain %p (total: %d), cached: %p\n", size, mono_domain_get (), thread_static_info.offset, item);*/
3598 if (item) {
3599 offset = item->offset;
3600 g_free (item);
3601 } else {
3602 offset = mono_alloc_static_data_slot (&thread_static_info, size, align);
3604 /* This can be called during startup */
3605 if (threads != NULL)
3606 mono_g_hash_table_foreach (threads, alloc_thread_static_data_helper, GUINT_TO_POINTER (offset));
3607 mono_threads_unlock ();
3609 else
3611 g_assert (static_type == SPECIAL_STATIC_CONTEXT);
3612 mono_contexts_lock ();
3613 offset = mono_alloc_static_data_slot (&context_static_info, size, align);
3614 mono_contexts_unlock ();
3615 offset |= 0x80000000; /* Set the high bit to indicate context static data */
3617 return offset;
3620 gpointer
3621 mono_get_special_static_data (guint32 offset)
3623 /* The high bit means either thread (0) or static (1) data. */
3625 guint32 static_type = (offset & 0x80000000);
3626 int idx;
3628 offset &= 0x7fffffff;
3629 idx = (offset >> 24) - 1;
3631 if (static_type == 0)
3633 MonoThread *thread = mono_thread_current ();
3634 return ((char*) thread->static_data [idx]) + (offset & 0xffffff);
3636 else
3638 /* Allocate static data block under demand, since we don't have a list
3639 // of contexts
3641 MonoAppContext *context = mono_context_get ();
3642 if (!context->static_data || !context->static_data [idx]) {
3643 mono_contexts_lock ();
3644 mono_alloc_static_data (&(context->static_data), offset);
3645 mono_contexts_unlock ();
3647 return ((char*) context->static_data [idx]) + (offset & 0xffffff);
3651 typedef struct {
3652 guint32 offset;
3653 guint32 size;
3654 } TlsOffsetSize;
3656 static void
3657 free_thread_static_data_helper (gpointer key, gpointer value, gpointer user)
3659 MonoThread *thread = value;
3660 TlsOffsetSize *data = user;
3661 int idx = (data->offset >> 24) - 1;
3662 char *ptr;
3664 if (!thread->static_data || !thread->static_data [idx])
3665 return;
3666 ptr = ((char*) thread->static_data [idx]) + (data->offset & 0xffffff);
3667 memset (ptr, 0, data->size);
3670 static void
3671 do_free_special (gpointer key, gpointer value, gpointer data)
3673 MonoClassField *field = key;
3674 guint32 offset = GPOINTER_TO_UINT (value);
3675 guint32 static_type = (offset & 0x80000000);
3676 gint32 align;
3677 guint32 size;
3678 size = mono_type_size (field->type, &align);
3679 /*g_print ("free %s , size: %d, offset: %x\n", field->name, size, offset);*/
3680 if (static_type == 0) {
3681 TlsOffsetSize data;
3682 MonoThreadDomainTls *item = g_new0 (MonoThreadDomainTls, 1);
3683 data.offset = offset & 0x7fffffff;
3684 data.size = size;
3685 if (threads != NULL)
3686 mono_g_hash_table_foreach (threads, free_thread_static_data_helper, &data);
3687 item->offset = offset;
3688 item->size = size;
3689 item->next = thread_static_info.freelist;
3690 thread_static_info.freelist = item;
3691 } else {
3692 /* FIXME: free context static data as well */
3696 void
3697 mono_alloc_special_static_data_free (GHashTable *special_static_fields)
3699 mono_threads_lock ();
3700 g_hash_table_foreach (special_static_fields, do_free_special, NULL);
3701 mono_threads_unlock ();
3704 static MonoClassField *local_slots = NULL;
3706 typedef struct {
3707 /* local tls data to get locals_slot from a thread */
3708 guint32 offset;
3709 int idx;
3710 /* index in the locals_slot array */
3711 int slot;
3712 } LocalSlotID;
3714 static void
3715 clear_local_slot (gpointer key, gpointer value, gpointer user_data)
3717 LocalSlotID *sid = user_data;
3718 MonoThread *thread = (MonoThread*)value;
3719 MonoArray *slots_array;
3721 * the static field is stored at: ((char*) thread->static_data [idx]) + (offset & 0xffffff);
3722 * it is for the right domain, so we need to check if it is allocated an initialized
3723 * for the current thread.
3725 /*g_print ("handling thread %p\n", thread);*/
3726 if (!thread->static_data || !thread->static_data [sid->idx])
3727 return;
3728 slots_array = *(MonoArray **)(((char*) thread->static_data [sid->idx]) + (sid->offset & 0xffffff));
3729 if (!slots_array || sid->slot >= mono_array_length (slots_array))
3730 return;
3731 mono_array_set (slots_array, MonoObject*, sid->slot, NULL);
3734 void
3735 mono_thread_free_local_slot_values (int slot, MonoBoolean thread_local)
3737 MonoDomain *domain;
3738 LocalSlotID sid;
3739 sid.slot = slot;
3740 if (thread_local) {
3741 void *addr = NULL;
3742 if (!local_slots) {
3743 local_slots = mono_class_get_field_from_name (mono_defaults.thread_class, "local_slots");
3744 if (!local_slots) {
3745 g_warning ("local_slots field not found in Thread class");
3746 return;
3749 domain = mono_domain_get ();
3750 mono_domain_lock (domain);
3751 if (domain->special_static_fields)
3752 addr = g_hash_table_lookup (domain->special_static_fields, local_slots);
3753 mono_domain_unlock (domain);
3754 if (!addr)
3755 return;
3756 /*g_print ("freeing slot %d at %p\n", slot, addr);*/
3757 sid.offset = GPOINTER_TO_UINT (addr);
3758 sid.offset &= 0x7fffffff;
3759 sid.idx = (sid.offset >> 24) - 1;
3760 mono_threads_lock ();
3761 mono_g_hash_table_foreach (threads, clear_local_slot, &sid);
3762 mono_threads_unlock ();
3763 } else {
3764 /* FIXME: clear the slot for MonoAppContexts, too */
3768 #ifdef PLATFORM_WIN32
3769 static void CALLBACK dummy_apc (ULONG_PTR param)
3772 #else
3773 static guint32 dummy_apc (gpointer param)
3775 return 0;
3777 #endif
3780 * mono_thread_execute_interruption
3782 * Performs the operation that the requested thread state requires (abort,
3783 * suspend or stop)
3785 static MonoException* mono_thread_execute_interruption (MonoThread *thread)
3787 ensure_synch_cs_set (thread);
3789 EnterCriticalSection (thread->synch_cs);
3791 /* MonoThread::interruption_requested can only be changed with atomics */
3792 if (InterlockedCompareExchange (&thread->interruption_requested, FALSE, TRUE)) {
3793 /* this will consume pending APC calls */
3794 WaitForSingleObjectEx (GetCurrentThread(), 0, TRUE);
3795 InterlockedDecrement (&thread_interruption_requested);
3796 #ifndef PLATFORM_WIN32
3797 /* Clear the interrupted flag of the thread so it can wait again */
3798 wapi_clear_interruption ();
3799 #endif
3802 if ((thread->state & ThreadState_AbortRequested) != 0) {
3803 LeaveCriticalSection (thread->synch_cs);
3804 if (thread->abort_exc == NULL) {
3806 * This might be racy, but it has to be called outside the lock
3807 * since it calls managed code.
3809 MONO_OBJECT_SETREF (thread, abort_exc, mono_get_exception_thread_abort ());
3811 return thread->abort_exc;
3813 else if ((thread->state & ThreadState_SuspendRequested) != 0) {
3814 thread->state &= ~ThreadState_SuspendRequested;
3815 thread->state |= ThreadState_Suspended;
3816 thread->suspend_event = CreateEvent (NULL, TRUE, FALSE, NULL);
3817 if (thread->suspend_event == NULL) {
3818 LeaveCriticalSection (thread->synch_cs);
3819 return(NULL);
3821 if (thread->suspended_event)
3822 SetEvent (thread->suspended_event);
3824 LeaveCriticalSection (thread->synch_cs);
3826 if (shutting_down) {
3827 /* After we left the lock, the runtime might shut down so everything becomes invalid */
3828 for (;;)
3829 Sleep (1000);
3832 WaitForSingleObject (thread->suspend_event, INFINITE);
3834 EnterCriticalSection (thread->synch_cs);
3836 CloseHandle (thread->suspend_event);
3837 thread->suspend_event = NULL;
3838 thread->state &= ~ThreadState_Suspended;
3840 /* The thread that requested the resume will have replaced this event
3841 * and will be waiting for it
3843 SetEvent (thread->resume_event);
3845 LeaveCriticalSection (thread->synch_cs);
3847 return NULL;
3849 else if ((thread->state & ThreadState_StopRequested) != 0) {
3850 /* FIXME: do this through the JIT? */
3852 LeaveCriticalSection (thread->synch_cs);
3854 mono_thread_exit ();
3855 return NULL;
3856 } else if (thread->thread_interrupt_requested) {
3858 thread->thread_interrupt_requested = FALSE;
3859 LeaveCriticalSection (thread->synch_cs);
3861 return(mono_get_exception_thread_interrupted ());
3864 LeaveCriticalSection (thread->synch_cs);
3866 return NULL;
3870 * mono_thread_request_interruption
3872 * A signal handler can call this method to request the interruption of a
3873 * thread. The result of the interruption will depend on the current state of
3874 * the thread. If the result is an exception that needs to be throw, it is
3875 * provided as return value.
3877 MonoException*
3878 mono_thread_request_interruption (gboolean running_managed)
3880 MonoThread *thread = mono_thread_current ();
3882 /* The thread may already be stopping */
3883 if (thread == NULL)
3884 return NULL;
3886 #ifdef PLATFORM_WIN32
3887 if (thread->interrupt_on_stop &&
3888 thread->state & ThreadState_StopRequested &&
3889 thread->state & ThreadState_Background)
3890 ExitThread (1);
3891 #endif
3893 if (InterlockedCompareExchange (&thread->interruption_requested, 1, 0) == 1)
3894 return NULL;
3896 if (!running_managed || is_running_protected_wrapper ()) {
3897 /* Can't stop while in unmanaged code. Increase the global interruption
3898 request count. When exiting the unmanaged method the count will be
3899 checked and the thread will be interrupted. */
3901 InterlockedIncrement (&thread_interruption_requested);
3903 if (mono_thread_notify_pending_exc_fn && !running_managed)
3904 /* The JIT will notify the thread about the interruption */
3905 /* This shouldn't take any locks */
3906 mono_thread_notify_pending_exc_fn ();
3908 /* this will awake the thread if it is in WaitForSingleObject
3909 or similar */
3910 /* Our implementation of this function ignores the func argument */
3911 QueueUserAPC ((PAPCFUNC)dummy_apc, thread->handle, NULL);
3912 return NULL;
3914 else {
3915 return mono_thread_execute_interruption (thread);
3919 gboolean mono_thread_interruption_requested ()
3921 if (thread_interruption_requested) {
3922 MonoThread *thread = mono_thread_current ();
3923 /* The thread may already be stopping */
3924 if (thread != NULL)
3925 return (thread->interruption_requested);
3927 return FALSE;
3930 static void mono_thread_interruption_checkpoint_request (gboolean bypass_abort_protection)
3932 MonoThread *thread = mono_thread_current ();
3934 /* The thread may already be stopping */
3935 if (thread == NULL)
3936 return;
3938 mono_debugger_check_interruption ();
3940 if (thread->interruption_requested && (bypass_abort_protection || !is_running_protected_wrapper ())) {
3941 MonoException* exc = mono_thread_execute_interruption (thread);
3942 if (exc) mono_raise_exception (exc);
3947 * Performs the interruption of the current thread, if one has been requested,
3948 * and the thread is not running a protected wrapper.
3950 void mono_thread_interruption_checkpoint ()
3952 mono_thread_interruption_checkpoint_request (FALSE);
3956 * Performs the interruption of the current thread, if one has been requested.
3958 void mono_thread_force_interruption_checkpoint ()
3960 mono_thread_interruption_checkpoint_request (TRUE);
3964 * mono_thread_get_and_clear_pending_exception:
3966 * Return any pending exceptions for the current thread and clear it as a side effect.
3968 MonoException*
3969 mono_thread_get_and_clear_pending_exception (void)
3971 MonoThread *thread = mono_thread_current ();
3973 /* The thread may already be stopping */
3974 if (thread == NULL)
3975 return NULL;
3977 if (thread->interruption_requested && !is_running_protected_wrapper ()) {
3978 return mono_thread_execute_interruption (thread);
3981 if (thread->pending_exception) {
3982 MonoException *exc = thread->pending_exception;
3984 thread->pending_exception = NULL;
3985 return exc;
3988 return NULL;
3992 * mono_set_pending_exception:
3994 * Set the pending exception of the current thread to EXC. On platforms which
3995 * support it, the exception will be thrown when execution returns to managed code.
3996 * On other platforms, this function is equivalent to mono_raise_exception ().
3997 * Internal calls which report exceptions using this function instead of
3998 * raise_exception () might be called by JITted code using a more efficient calling
3999 * convention.
4001 void
4002 mono_set_pending_exception (MonoException *exc)
4004 MonoThread *thread = mono_thread_current ();
4006 /* The thread may already be stopping */
4007 if (thread == NULL)
4008 return;
4010 if (mono_thread_notify_pending_exc_fn) {
4011 MONO_OBJECT_SETREF (thread, pending_exception, exc);
4013 mono_thread_notify_pending_exc_fn ();
4014 } else {
4015 /* No way to notify the JIT about the exception, have to throw it now */
4016 mono_raise_exception (exc);
4021 * mono_thread_interruption_request_flag:
4023 * Returns the address of a flag that will be non-zero if an interruption has
4024 * been requested for a thread. The thread to interrupt may not be the current
4025 * thread, so an additional call to mono_thread_interruption_requested() or
4026 * mono_thread_interruption_checkpoint() is allways needed if the flag is not
4027 * zero.
4029 gint32* mono_thread_interruption_request_flag ()
4031 return &thread_interruption_requested;
4034 void
4035 mono_thread_init_apartment_state (void)
4037 MonoThread* thread;
4038 thread = mono_thread_current ();
4040 #ifdef PLATFORM_WIN32
4041 /* Positive return value indicates success, either
4042 * S_OK if this is first CoInitialize call, or
4043 * S_FALSE if CoInitialize already called, but with same
4044 * threading model. A negative value indicates failure,
4045 * probably due to trying to change the threading model.
4047 if (CoInitializeEx(NULL, (thread->apartment_state == ThreadApartmentState_STA)
4048 ? COINIT_APARTMENTTHREADED
4049 : COINIT_MULTITHREADED) < 0) {
4050 thread->apartment_state = ThreadApartmentState_Unknown;
4052 #endif
4055 void
4056 mono_thread_cleanup_apartment_state (void)
4058 #ifdef PLATFORM_WIN32
4059 MonoThread* thread;
4060 thread = mono_thread_current ();
4062 if (thread && thread->apartment_state != ThreadApartmentState_Unknown) {
4063 CoUninitialize ();
4065 #endif
4068 void
4069 mono_thread_set_state (MonoThread *thread, MonoThreadState state)
4071 ensure_synch_cs_set (thread);
4073 EnterCriticalSection (thread->synch_cs);
4074 thread->state |= state;
4075 LeaveCriticalSection (thread->synch_cs);
4078 void
4079 mono_thread_clr_state (MonoThread *thread, MonoThreadState state)
4081 ensure_synch_cs_set (thread);
4083 EnterCriticalSection (thread->synch_cs);
4084 thread->state &= ~state;
4085 LeaveCriticalSection (thread->synch_cs);
4088 gboolean
4089 mono_thread_test_state (MonoThread *thread, MonoThreadState test)
4091 gboolean ret = FALSE;
4093 ensure_synch_cs_set (thread);
4095 EnterCriticalSection (thread->synch_cs);
4097 if ((thread->state & test) != 0) {
4098 ret = TRUE;
4101 LeaveCriticalSection (thread->synch_cs);
4103 return ret;
4106 static MonoClassField *execution_context_field;
4108 static MonoObject**
4109 get_execution_context_addr (void)
4111 MonoDomain *domain = mono_domain_get ();
4112 guint32 offset;
4114 if (!execution_context_field) {
4115 execution_context_field = mono_class_get_field_from_name (mono_defaults.thread_class,
4116 "_ec");
4117 g_assert (execution_context_field);
4120 g_assert (mono_class_try_get_vtable (domain, mono_defaults.appdomain_class));
4122 mono_domain_lock (domain);
4123 offset = GPOINTER_TO_UINT (g_hash_table_lookup (domain->special_static_fields, execution_context_field));
4124 mono_domain_unlock (domain);
4125 g_assert (offset);
4127 return (MonoObject**) mono_get_special_static_data (offset);
4130 MonoObject*
4131 mono_thread_get_execution_context (void)
4133 return *get_execution_context_addr ();
4136 void
4137 mono_thread_set_execution_context (MonoObject *ec)
4139 *get_execution_context_addr () = ec;
4142 static gboolean has_tls_get = FALSE;
4144 void
4145 mono_runtime_set_has_tls_get (gboolean val)
4147 has_tls_get = val;
4150 gboolean
4151 mono_runtime_has_tls_get (void)
4153 return has_tls_get;