2 * threads.c: Thread support internal calls
5 * Dick Porter (dick@ximian.com)
6 * Paolo Molaro (lupus@ximian.com)
7 * Patrik Torstensson (patrik.torstensson@labs2.com)
9 * (C) 2001 Ximian, Inc.
14 #define _WIN32_WINNT 0x0500
21 #include <mono/metadata/object.h>
22 #include <mono/metadata/domain-internals.h>
23 #include <mono/metadata/profiler-private.h>
24 #include <mono/metadata/threads.h>
25 #include <mono/metadata/threadpool.h>
26 #include <mono/metadata/threads-types.h>
27 #include <mono/metadata/exception.h>
28 #include <mono/metadata/environment.h>
29 #include <mono/metadata/monitor.h>
30 #include <mono/metadata/gc-internal.h>
31 #include <mono/metadata/marshal.h>
32 #include <mono/io-layer/io-layer.h>
33 #include <mono/metadata/object-internals.h>
34 #include <mono/utils/mono-compiler.h>
36 #include <mono/os/gc_wrapper.h>
38 /*#define THREAD_DEBUG(a) do { a; } while (0)*/
39 #define THREAD_DEBUG(a)
40 /*#define THREAD_WAIT_DEBUG(a) do { a; } while (0)*/
41 #define THREAD_WAIT_DEBUG(a)
42 /*#define LIBGC_DEBUG(a) do { a; } while (0)*/
43 #define LIBGC_DEBUG(a)
47 guint32 (*func)(void *);
69 /* Number of cached culture objects in the MonoThread->culture_info array */
70 #define NUM_CACHED_CULTURES 4
73 * The "os_handle" field of the WaitHandle class.
75 static MonoClassField *wait_handle_os_handle_field = NULL;
77 /* Controls access to the 'threads' hash table */
78 static CRITICAL_SECTION threads_mutex;
80 /* Controls access to context static data */
81 static CRITICAL_SECTION contexts_mutex;
83 /* Holds current status of static data heap */
84 static StaticDataInfo thread_static_info;
85 static StaticDataInfo context_static_info;
87 /* The hash of existing threads (key is thread ID) that need joining
90 static MonoGHashTable *threads=NULL;
92 /* The TLS key that holds the MonoObject assigned to each thread */
93 static guint32 current_object_key = -1;
96 /* we need to use both the Tls* functions and __thread because
97 * the gc needs to see all the threads
99 static __thread MonoThread * tls_current_object MONO_TLS_FAST;
100 #define SET_CURRENT_OBJECT(x) do { \
101 tls_current_object = x; \
102 TlsSetValue (current_object_key, x); \
104 #define GET_CURRENT_OBJECT() tls_current_object
106 #define SET_CURRENT_OBJECT(x) TlsSetValue (current_object_key, x);
107 #define GET_CURRENT_OBJECT() (MonoThread*) TlsGetValue (current_object_key);
110 /* function called at thread start */
111 static MonoThreadStartCB mono_thread_start_cb = NULL;
113 /* function called at thread attach */
114 static MonoThreadAttachCB mono_thread_attach_cb = NULL;
116 /* function called at thread cleanup */
117 static MonoThreadCleanupFunc mono_thread_cleanup = NULL;
119 /* function called when a new thread has been created */
120 static MonoThreadCallbacks *mono_thread_callbacks = NULL;
122 /* The default stack size for each thread */
123 static guint32 default_stacksize = 0;
124 #define default_stacksize_for_thread(thread) ((thread)->stack_size? (thread)->stack_size: default_stacksize)
126 static void thread_adjust_static_data (MonoThread *thread);
127 static void mono_init_static_data_info (StaticDataInfo *static_data);
128 static guint32 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align);
129 static gboolean mono_thread_resume (MonoThread* thread);
130 static void mono_thread_start (MonoThread *thread);
132 /* Spin lock for InterlockedXXX 64 bit functions */
133 static CRITICAL_SECTION interlocked_mutex;
135 /* global count of thread interruptions requested */
136 static gint32 thread_interruption_requested = 0;
138 /* Event signaled when a thread changes its background mode */
139 static HANDLE background_change_event;
142 mono_thread_get_tls_key (void)
144 return current_object_key;
148 mono_thread_get_tls_offset (void)
151 MONO_THREAD_VAR_OFFSET (tls_current_object,offset);
155 /* handle_store() and handle_remove() manage the array of threads that
156 * still need to be waited for when the main thread exits.
158 static void handle_store(MonoThread *thread)
160 EnterCriticalSection(&threads_mutex);
162 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": thread %p ID %d", thread, thread->tid));
165 MONO_GC_REGISTER_ROOT (threads);
166 threads=mono_g_hash_table_new(NULL, NULL);
169 /* We don't need to duplicate thread->handle, because it is
170 * only closed when the thread object is finalized by the GC.
172 mono_g_hash_table_insert(threads, GUINT_TO_POINTER(thread->tid), thread);
173 LeaveCriticalSection(&threads_mutex);
176 static void handle_remove(guint32 tid)
178 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": thread ID %d", tid));
180 EnterCriticalSection(&threads_mutex);
183 mono_g_hash_table_remove (threads, GUINT_TO_POINTER(tid));
185 LeaveCriticalSection(&threads_mutex);
187 /* Don't close the handle here, wait for the object finalizer
188 * to do it. Otherwise, the following race condition applies:
190 * 1) Thread exits (and handle_remove() closes the handle)
192 * 2) Some other handle is reassigned the same slot
194 * 3) Another thread tries to join the first thread, and
195 * blocks waiting for the reassigned handle to be signalled
196 * (which might never happen). This is possible, because the
197 * thread calling Join() still has a reference to the first
202 static void thread_cleanup (MonoThread *thread)
204 g_assert (thread != NULL);
206 mono_release_type_locks (thread);
208 if (!mono_monitor_enter (thread->synch_lock))
211 thread->state |= ThreadState_Stopped;
212 mono_monitor_exit (thread->synch_lock);
214 mono_profiler_thread_end (thread->tid);
215 handle_remove (thread->tid);
217 mono_thread_pop_appdomain_ref ();
219 if (thread->serialized_culture_info)
220 g_free (thread->serialized_culture_info);
222 mono_gc_free_fixed (thread->culture_info);
223 mono_gc_free_fixed (thread->ui_culture_info);
225 if (mono_thread_cleanup)
226 mono_thread_cleanup (thread);
229 static guint32 WINAPI start_wrapper(void *data)
231 struct StartInfo *start_info=(struct StartInfo *)data;
232 guint32 (*start_func)(void *);
235 MonoThread *thread=start_info->obj;
236 MonoObject *start_delegate = start_info->delegate;
238 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%d) Start wrapper", GetCurrentThreadId ()));
240 /* We can be sure start_info->obj->tid and
241 * start_info->obj->handle have been set, because the thread
242 * was created suspended, and these values were set before the
248 SET_CURRENT_OBJECT (thread);
250 if (!mono_domain_set (start_info->domain, FALSE)) {
251 /* No point in raising an appdomain_unloaded exception here */
252 /* FIXME: Cleanup here */
256 start_func = start_info->func;
257 start_arg = start_info->start_arg;
259 /* This MUST be called before any managed code can be
260 * executed, as it calls the callback function that (for the
261 * jit) sets the lmf marker.
263 mono_thread_new_init (tid, &tid, start_func);
264 thread->stack_ptr = &tid;
266 LIBGC_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION
267 ": (%d,%d) Setting thread stack to %p",
268 GetCurrentThreadId (), getpid (), thread->stack_ptr));
270 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION
271 ": (%d) Setting current_object_key to %p",
272 GetCurrentThreadId (), thread));
274 mono_profiler_thread_start (tid);
276 if(thread->start_notify!=NULL) {
277 /* Let the thread that called Start() know we're
280 ReleaseSemaphore (thread->start_notify, 1, NULL);
285 /* Every thread references the appdomain which created it */
286 mono_thread_push_appdomain_ref (mono_domain_get ());
288 thread_adjust_static_data (thread);
290 g_message (G_GNUC_PRETTY_FUNCTION "start_wrapper for %d\n", thread->tid);
293 /* start_func is set only for unamanged start functions */
295 start_func (start_arg);
298 g_assert (start_delegate != NULL);
299 args [0] = start_arg;
300 /* we may want to handle the exception here. See comment below on unhandled exceptions */
301 mono_runtime_delegate_invoke (start_delegate, args, NULL);
304 /* If the thread calls ExitThread at all, this remaining code
305 * will not be executed, but the main thread will eventually
306 * call thread_cleanup() on this thread's behalf.
309 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%d) Start wrapper terminating",
310 GetCurrentThreadId ()));
312 /* Remove the reference to the thread object in the TLS data,
313 * so the thread object can be finalized. This won't be
314 * reached if the thread threw an uncaught exception, so those
315 * thread handles will stay referenced :-( (This is due to
316 * missing support for scanning thread-specific data in the
317 * Boehm GC - the io-layer keeps a GC-visible hash of pointers
320 SET_CURRENT_OBJECT (NULL);
322 thread_cleanup (thread);
327 void mono_thread_new_init (guint32 tid, gpointer stack_start, gpointer func)
329 if (mono_thread_start_cb) {
330 mono_thread_start_cb (tid, stack_start, func);
333 if (mono_thread_callbacks)
334 (* mono_thread_callbacks->thread_created) (tid, stack_start, func);
337 void mono_threads_set_default_stacksize (guint32 stacksize)
339 default_stacksize = stacksize;
342 guint32 mono_threads_get_default_stacksize (void)
344 return default_stacksize;
347 void mono_thread_create (MonoDomain *domain, gpointer func, gpointer arg)
350 HANDLE thread_handle;
351 struct StartInfo *start_info;
354 thread=(MonoThread *)mono_object_new (domain,
355 mono_defaults.thread_class);
357 start_info=g_new0 (struct StartInfo, 1);
358 start_info->func = func;
359 start_info->obj = thread;
360 start_info->domain = domain;
361 start_info->start_arg = arg;
363 /* Create suspended, so we can do some housekeeping before the thread
366 thread_handle = CreateThread(NULL, default_stacksize_for_thread (thread), (LPTHREAD_START_ROUTINE)start_wrapper, start_info,
367 CREATE_SUSPENDED, &tid);
368 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": Started thread ID %d (handle %p)",
369 tid, thread_handle));
370 if (thread_handle == NULL) {
371 /* The thread couldn't be created, so throw an exception */
372 mono_raise_exception (mono_get_exception_execution_engine ("Couldn't create thread"));
376 thread->handle=thread_handle;
379 thread->synch_lock=mono_object_new (domain, mono_defaults.object_class);
381 handle_store(thread);
383 ResumeThread (thread_handle);
387 mono_thread_attach (MonoDomain *domain)
390 HANDLE thread_handle;
393 if ((thread = mono_thread_current ())) {
394 /* Already attached */
398 if (!mono_gc_register_thread (&domain)) {
399 g_error ("Thread %p 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.", GetCurrentThread ());
402 thread = (MonoThread *)mono_object_new (domain,
403 mono_defaults.thread_class);
405 thread_handle = GetCurrentThread ();
406 g_assert (thread_handle);
408 tid=GetCurrentThreadId ();
410 #ifdef PLATFORM_WIN32
412 * The handle returned by GetCurrentThread () is a pseudo handle, so it can't be used to
413 * refer to the thread from other threads for things like aborting.
415 DuplicateHandle (GetCurrentProcess (), thread_handle, GetCurrentProcess (), &thread_handle,
416 THREAD_ALL_ACCESS, TRUE, 0);
419 thread->handle=thread_handle;
421 thread->synch_lock=mono_object_new (domain, mono_defaults.object_class);
423 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": Attached thread ID %d (handle %p)",
424 tid, thread_handle));
426 handle_store(thread);
428 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%d) Setting current_object_key to %p",
429 GetCurrentThreadId (), thread));
431 SET_CURRENT_OBJECT (thread);
432 mono_domain_set (domain, TRUE);
434 thread_adjust_static_data (thread);
436 if (mono_thread_attach_cb) {
437 mono_thread_attach_cb (tid, &tid);
444 mono_thread_detach (MonoThread *thread)
446 g_return_if_fail (thread != NULL);
448 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION "mono_thread_detach for %d\n", thread->tid));
449 SET_CURRENT_OBJECT (NULL);
451 thread_cleanup (thread);
457 MonoThread *thread = mono_thread_current ();
459 SET_CURRENT_OBJECT (NULL);
460 thread_cleanup (thread);
462 /* we could add a callback here for embedders to use. */
463 if (thread == mono_thread_get_main ())
464 exit (mono_environment_exitcode_get ());
468 HANDLE ves_icall_System_Threading_Thread_Thread_internal(MonoThread *this,
471 guint32 (*start_func)(void *);
472 struct StartInfo *start_info;
479 THREAD_DEBUG (g_message(G_GNUC_PRETTY_FUNCTION
480 ": Trying to start a new thread: this (%p) start (%p)", this, start));
482 mono_monitor_enter (this->synch_lock);
484 if ((this->state & ThreadState_Unstarted) == 0) {
485 mono_monitor_exit (this->synch_lock);
486 mono_raise_exception (mono_get_exception_thread_state ("Thread has already been started."));
490 if ((this->state & ThreadState_Aborted) != 0) {
491 mono_monitor_exit (this->synch_lock);
494 /* FIXME: remove the code inside BROKEN_THREAD_START once martin gets rid of the
495 * thread_start_compile_func stuff.
497 #define BROKEN_THREAD_START
498 #ifdef BROKEN_THREAD_START
499 im = mono_get_delegate_invoke (start->vtable->klass);
500 im = mono_marshal_get_delegate_invoke (im);
501 if (mono_thread_callbacks)
502 start_func = (* mono_thread_callbacks->thread_start_compile_func) (im);
504 start_func = mono_compile_method (im);
506 if(start_func==NULL) {
507 mono_monitor_exit (this->synch_lock);
508 g_warning(G_GNUC_PRETTY_FUNCTION
509 ": Can't locate start method!");
516 /* This is freed in start_wrapper */
517 start_info = g_new0 (struct StartInfo, 1);
518 start_info->func = start_func;
519 #ifdef BROKEN_THREAD_START
520 start_info->start_arg = start;
522 start_info->start_arg = this->start_obj;
524 start_info->delegate = start;
525 start_info->obj = this;
526 start_info->domain = mono_domain_get ();
528 this->start_notify=CreateSemaphore (NULL, 0, 0x7fffffff, NULL);
529 if(this->start_notify==NULL) {
530 mono_monitor_exit (this->synch_lock);
531 g_warning (G_GNUC_PRETTY_FUNCTION ": CreateSemaphore error 0x%x", GetLastError ());
535 thread=CreateThread(NULL, default_stacksize_for_thread (this), (LPTHREAD_START_ROUTINE)start_wrapper, start_info,
536 CREATE_SUSPENDED, &tid);
538 mono_monitor_exit (this->synch_lock);
539 g_warning(G_GNUC_PRETTY_FUNCTION
540 ": CreateThread error 0x%x", GetLastError());
547 /* Don't call handle_store() here, delay it to Start.
548 * We can't join a thread (trying to will just block
549 * forever) until it actually starts running, so don't
550 * store the handle till then.
553 mono_thread_start (this);
555 this->state &= ~ThreadState_Unstarted;
557 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION
558 ": Started thread ID %d (handle %p)", tid, thread));
560 mono_monitor_exit (this->synch_lock);
565 void ves_icall_System_Threading_Thread_Thread_free_internal (MonoThread *this,
570 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": Closing thread %p, handle %p",
573 CloseHandle (thread);
576 static void mono_thread_start (MonoThread *thread)
580 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%d) Launching thread %p (%d)",
581 GetCurrentThreadId (), thread, thread->tid));
583 /* Only store the handle when the thread is about to be
584 * launched, to avoid the main thread deadlocking while trying
585 * to clean up a thread that will never be signalled.
587 handle_store (thread);
589 if (mono_thread_callbacks)
590 (* mono_thread_callbacks->start_resume) (thread->tid);
592 ResumeThread (thread->handle);
594 if (mono_thread_callbacks)
595 (* mono_thread_callbacks->end_resume) (thread->tid);
597 if(thread->start_notify!=NULL) {
598 /* Wait for the thread to set up its TLS data etc, so
599 * theres no potential race condition if someone tries
600 * to look up the data believing the thread has
604 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION
605 ": (%d) waiting for thread %p (%d) to start",
606 GetCurrentThreadId (), thread, thread->tid));
608 WaitForSingleObjectEx (thread->start_notify, INFINITE, FALSE);
609 CloseHandle (thread->start_notify);
610 thread->start_notify = NULL;
613 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION
614 ": (%d) Done launching thread %p (%d)",
615 GetCurrentThreadId (), thread, thread->tid));
618 void ves_icall_System_Threading_Thread_Sleep_internal(gint32 ms)
620 MonoThread *thread = mono_thread_current ();
624 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": Sleeping for %d ms", ms));
626 mono_monitor_enter (thread->synch_lock);
627 thread->state |= ThreadState_WaitSleepJoin;
628 mono_monitor_exit (thread->synch_lock);
632 mono_monitor_enter (thread->synch_lock);
633 thread->state &= ~ThreadState_WaitSleepJoin;
634 mono_monitor_exit (thread->synch_lock);
638 ves_icall_System_Threading_Thread_GetDomainID (void)
642 return mono_domain_get()->domain_id;
646 ves_icall_System_Threading_Thread_GetName_internal (MonoThread *this_obj)
649 mono_monitor_enter (this_obj->synch_lock);
654 str = mono_string_new_utf16 (mono_domain_get (), this_obj->name, this_obj->name_len);
656 mono_monitor_exit (this_obj->synch_lock);
661 ves_icall_System_Threading_Thread_SetName_internal (MonoThread *this_obj, MonoString *name)
663 mono_monitor_enter (this_obj->synch_lock);
665 if (this_obj->name) {
666 mono_monitor_exit (this_obj->synch_lock);
667 mono_raise_exception (mono_get_exception_invalid_operation ("Thread.Name can only be set once."));
671 this_obj->name = g_new (gunichar2, mono_string_length (name));
672 memcpy (this_obj->name, mono_string_chars (name), mono_string_length (name) * 2);
673 this_obj->name_len = mono_string_length (name);
676 this_obj->name = NULL;
678 mono_monitor_exit (this_obj->synch_lock);
682 ves_icall_System_Threading_Thread_GetCachedCurrentCulture (MonoThread *this)
688 /* No need to lock here */
689 if (this->culture_info) {
690 domain = mono_domain_get ();
691 for (i = 0; i < NUM_CACHED_CULTURES; ++i) {
692 res = this->culture_info [i];
693 if (res && res->vtable->domain == domain)
702 ves_icall_System_Threading_Thread_GetSerializedCurrentCulture (MonoThread *this)
706 mono_monitor_enter (this->synch_lock);
707 if (this->serialized_culture_info) {
708 res = mono_array_new (mono_domain_get (), mono_defaults.byte_class, this->serialized_culture_info_len);
709 memcpy (mono_array_addr (res, guint8, 0), this->serialized_culture_info, this->serialized_culture_info_len);
713 mono_monitor_exit (this->synch_lock);
719 ves_icall_System_Threading_Thread_SetCachedCurrentCulture (MonoThread *this, MonoObject *culture)
722 MonoDomain *domain = mono_domain_get ();
724 mono_monitor_enter (this->synch_lock);
725 if (!this->culture_info) {
726 this->culture_info = mono_gc_alloc_fixed (sizeof (MonoObject*) * NUM_CACHED_CULTURES, NULL);
729 for (i = 0; i < NUM_CACHED_CULTURES; ++i) {
730 if (this->culture_info [i]) {
731 if (this->culture_info [i]->vtable->domain == domain)
739 if (i < NUM_CACHED_CULTURES)
740 this->culture_info [i] = culture;
741 mono_monitor_exit (this->synch_lock);
745 ves_icall_System_Threading_Thread_SetSerializedCurrentCulture (MonoThread *this, MonoArray *arr)
747 mono_monitor_enter (this->synch_lock);
748 if (this->serialized_culture_info)
749 g_free (this->serialized_culture_info);
750 this->serialized_culture_info = g_new0 (guint8, mono_array_length (arr));
751 this->serialized_culture_info_len = mono_array_length (arr);
752 memcpy (this->serialized_culture_info, mono_array_addr (arr, guint8, 0), mono_array_length (arr));
753 mono_monitor_exit (this->synch_lock);
758 ves_icall_System_Threading_Thread_GetCachedCurrentUICulture (MonoThread *this)
764 /* No need to lock here */
765 if (this->ui_culture_info) {
766 domain = mono_domain_get ();
767 for (i = 0; i < NUM_CACHED_CULTURES; ++i) {
768 res = this->ui_culture_info [i];
769 if (res && res->vtable->domain == domain)
778 ves_icall_System_Threading_Thread_GetSerializedCurrentUICulture (MonoThread *this)
782 mono_monitor_enter (this->synch_lock);
783 if (this->serialized_ui_culture_info) {
784 res = mono_array_new (mono_domain_get (), mono_defaults.byte_class, this->serialized_ui_culture_info_len);
785 memcpy (mono_array_addr (res, guint8, 0), this->serialized_ui_culture_info, this->serialized_ui_culture_info_len);
789 mono_monitor_exit (this->synch_lock);
795 ves_icall_System_Threading_Thread_SetCachedCurrentUICulture (MonoThread *this, MonoObject *culture)
798 MonoDomain *domain = mono_domain_get ();
800 mono_monitor_enter (this->synch_lock);
801 if (!this->ui_culture_info) {
802 this->ui_culture_info = mono_gc_alloc_fixed (sizeof (MonoObject*) * NUM_CACHED_CULTURES, NULL);
805 for (i = 0; i < NUM_CACHED_CULTURES; ++i) {
806 if (this->ui_culture_info [i]) {
807 if (this->ui_culture_info [i]->vtable->domain == domain)
815 if (i < NUM_CACHED_CULTURES)
816 this->ui_culture_info [i] = culture;
817 mono_monitor_exit (this->synch_lock);
821 ves_icall_System_Threading_Thread_SetSerializedCurrentUICulture (MonoThread *this, MonoArray *arr)
823 mono_monitor_enter (this->synch_lock);
824 if (this->serialized_ui_culture_info)
825 g_free (this->serialized_ui_culture_info);
826 this->serialized_ui_culture_info = g_new0 (guint8, mono_array_length (arr));
827 this->serialized_ui_culture_info_len = mono_array_length (arr);
828 memcpy (this->serialized_ui_culture_info, mono_array_addr (arr, guint8, 0), mono_array_length (arr));
829 mono_monitor_exit (this->synch_lock);
832 /* the jit may read the compiled code of this function */
834 mono_thread_current (void)
836 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": returning %p", GET_CURRENT_OBJECT ()));
837 return GET_CURRENT_OBJECT ();
840 gboolean ves_icall_System_Threading_Thread_Join_internal(MonoThread *this,
841 int ms, HANDLE thread)
847 mono_monitor_enter (this->synch_lock);
849 if ((this->state & ThreadState_Unstarted) != 0) {
850 mono_monitor_exit (this->synch_lock);
851 mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started."));
855 this->state |= ThreadState_WaitSleepJoin;
856 mono_monitor_exit (this->synch_lock);
861 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": joining thread handle %p, %d ms",
864 ret=WaitForSingleObjectEx (thread, ms, TRUE);
866 mono_monitor_enter (this->synch_lock);
867 this->state &= ~ThreadState_WaitSleepJoin;
868 mono_monitor_exit (this->synch_lock);
870 if(ret==WAIT_OBJECT_0) {
871 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": join successful"));
876 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": join failed"));
881 /* FIXME: exitContext isnt documented */
882 gboolean ves_icall_System_Threading_WaitHandle_WaitAll_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext)
888 MonoObject *waitHandle;
890 MonoThread *thread = mono_thread_current ();
894 numhandles = mono_array_length(mono_handles);
895 handles = g_new0(HANDLE, numhandles);
897 if (wait_handle_os_handle_field == 0) {
898 /* Get the field os_handle which will contain the actual handle */
899 klass = mono_class_from_name(mono_defaults.corlib, "System.Threading", "WaitHandle");
900 wait_handle_os_handle_field = mono_class_get_field_from_name(klass, "os_handle");
903 for(i = 0; i < numhandles; i++) {
904 waitHandle = mono_array_get(mono_handles, MonoObject*, i);
905 mono_field_get_value(waitHandle, wait_handle_os_handle_field, &handles[i]);
912 mono_monitor_enter (thread->synch_lock);
913 thread->state |= ThreadState_WaitSleepJoin;
914 mono_monitor_exit (thread->synch_lock);
916 ret=WaitForMultipleObjectsEx(numhandles, handles, TRUE, ms, TRUE);
918 mono_monitor_enter (thread->synch_lock);
919 thread->state &= ~ThreadState_WaitSleepJoin;
920 mono_monitor_exit (thread->synch_lock);
924 if(ret==WAIT_FAILED) {
925 THREAD_WAIT_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%d) Wait failed",
926 GetCurrentThreadId ()));
928 } else if(ret==WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION) {
929 /* Do we want to try again if we get
930 * WAIT_IO_COMPLETION? The documentation for
931 * WaitHandle doesn't give any clues. (We'd have to
932 * fiddle with the timeout if we retry.)
934 THREAD_WAIT_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%d) Wait timed out",
935 GetCurrentThreadId ()));
942 /* FIXME: exitContext isnt documented */
943 gint32 ves_icall_System_Threading_WaitHandle_WaitAny_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext)
949 MonoObject *waitHandle;
951 MonoThread *thread = mono_thread_current ();
955 numhandles = mono_array_length(mono_handles);
956 handles = g_new0(HANDLE, numhandles);
958 if (wait_handle_os_handle_field == 0) {
959 /* Get the field os_handle which will contain the actual handle */
960 klass = mono_class_from_name(mono_defaults.corlib, "System.Threading", "WaitHandle");
961 wait_handle_os_handle_field = mono_class_get_field_from_name(klass, "os_handle");
964 for(i = 0; i < numhandles; i++) {
965 waitHandle = mono_array_get(mono_handles, MonoObject*, i);
966 mono_field_get_value(waitHandle, wait_handle_os_handle_field, &handles[i]);
973 mono_monitor_enter (thread->synch_lock);
974 thread->state |= ThreadState_WaitSleepJoin;
975 mono_monitor_exit (thread->synch_lock);
977 ret=WaitForMultipleObjectsEx(numhandles, handles, FALSE, ms, TRUE);
979 mono_monitor_enter (thread->synch_lock);
980 thread->state &= ~ThreadState_WaitSleepJoin;
981 mono_monitor_exit (thread->synch_lock);
985 THREAD_WAIT_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%d) returning %d",
986 GetCurrentThreadId (), ret));
989 * These need to be here. See MSDN dos on WaitForMultipleObjects.
991 if (ret >= WAIT_OBJECT_0 && ret <= WAIT_OBJECT_0 + numhandles - 1) {
992 return ret - WAIT_OBJECT_0;
994 else if (ret >= WAIT_ABANDONED_0 && ret <= WAIT_ABANDONED_0 + numhandles - 1) {
995 return ret - WAIT_ABANDONED_0;
1002 /* FIXME: exitContext isnt documented */
1003 gboolean ves_icall_System_Threading_WaitHandle_WaitOne_internal(MonoObject *this, HANDLE handle, gint32 ms, gboolean exitContext)
1006 MonoThread *thread = mono_thread_current ();
1008 MONO_ARCH_SAVE_REGS;
1010 THREAD_WAIT_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%d) waiting for %p, %d ms",
1011 GetCurrentThreadId (), handle, ms));
1017 mono_monitor_enter (thread->synch_lock);
1018 thread->state |= ThreadState_WaitSleepJoin;
1019 mono_monitor_exit (thread->synch_lock);
1021 ret=WaitForSingleObjectEx (handle, ms, TRUE);
1023 mono_monitor_enter (thread->synch_lock);
1024 thread->state &= ~ThreadState_WaitSleepJoin;
1025 mono_monitor_exit (thread->synch_lock);
1027 if(ret==WAIT_FAILED) {
1028 THREAD_WAIT_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%d) Wait failed",
1029 GetCurrentThreadId ()));
1031 } else if(ret==WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION) {
1032 /* Do we want to try again if we get
1033 * WAIT_IO_COMPLETION? The documentation for
1034 * WaitHandle doesn't give any clues. (We'd have to
1035 * fiddle with the timeout if we retry.)
1037 THREAD_WAIT_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%d) Wait timed out",
1038 GetCurrentThreadId ()));
1045 HANDLE ves_icall_System_Threading_Mutex_CreateMutex_internal (MonoBoolean owned, MonoString *name, MonoBoolean *created)
1049 MONO_ARCH_SAVE_REGS;
1054 mutex = CreateMutex (NULL, owned, NULL);
1056 mutex = CreateMutex (NULL, owned, mono_string_chars (name));
1058 if (GetLastError () == ERROR_ALREADY_EXISTS) {
1066 void ves_icall_System_Threading_Mutex_ReleaseMutex_internal (HANDLE handle ) {
1067 MONO_ARCH_SAVE_REGS;
1069 ReleaseMutex(handle);
1072 HANDLE ves_icall_System_Threading_Events_CreateEvent_internal (MonoBoolean manual, MonoBoolean initial, MonoString *name) {
1073 MONO_ARCH_SAVE_REGS;
1075 return(CreateEvent (NULL, manual, initial,
1076 name==NULL?NULL:mono_string_chars (name)));
1079 gboolean ves_icall_System_Threading_Events_SetEvent_internal (HANDLE handle) {
1080 MONO_ARCH_SAVE_REGS;
1082 return (SetEvent(handle));
1085 gboolean ves_icall_System_Threading_Events_ResetEvent_internal (HANDLE handle) {
1086 MONO_ARCH_SAVE_REGS;
1088 return (ResetEvent(handle));
1092 ves_icall_System_Threading_Events_CloseEvent_internal (HANDLE handle) {
1093 MONO_ARCH_SAVE_REGS;
1095 CloseHandle (handle);
1098 gint32 ves_icall_System_Threading_Interlocked_Increment_Int (gint32 *location)
1100 MONO_ARCH_SAVE_REGS;
1102 return InterlockedIncrement (location);
1105 gint64 ves_icall_System_Threading_Interlocked_Increment_Long (gint64 *location)
1109 MONO_ARCH_SAVE_REGS;
1111 EnterCriticalSection(&interlocked_mutex);
1115 LeaveCriticalSection(&interlocked_mutex);
1121 gint32 ves_icall_System_Threading_Interlocked_Decrement_Int (gint32 *location)
1123 MONO_ARCH_SAVE_REGS;
1125 return InterlockedDecrement(location);
1128 gint64 ves_icall_System_Threading_Interlocked_Decrement_Long (gint64 * location)
1132 MONO_ARCH_SAVE_REGS;
1134 EnterCriticalSection(&interlocked_mutex);
1138 LeaveCriticalSection(&interlocked_mutex);
1143 gint32 ves_icall_System_Threading_Interlocked_Exchange_Int (gint32 *location, gint32 value)
1145 MONO_ARCH_SAVE_REGS;
1147 return InterlockedExchange(location, value);
1150 MonoObject * ves_icall_System_Threading_Interlocked_Exchange_Object (MonoObject **location, MonoObject *value)
1152 MONO_ARCH_SAVE_REGS;
1154 return (MonoObject *) InterlockedExchangePointer((gpointer *) location, value);
1157 gfloat ves_icall_System_Threading_Interlocked_Exchange_Single (gfloat *location, gfloat value)
1159 IntFloatUnion val, ret;
1161 MONO_ARCH_SAVE_REGS;
1164 ret.ival = InterlockedExchange((gint32 *) location, val.ival);
1170 ves_icall_System_Threading_Interlocked_Exchange_Long (gint64 *location, gint64 value)
1172 #if SIZEOF_VOID_P == 8
1173 return (gint64) InterlockedExchangePointer((gpointer *) location, (gpointer)value);
1178 * According to MSDN, this function is only atomic with regards to the
1179 * other Interlocked functions on 32 bit platforms.
1181 EnterCriticalSection(&interlocked_mutex);
1184 LeaveCriticalSection(&interlocked_mutex);
1191 ves_icall_System_Threading_Interlocked_Exchange_Double (gdouble *location, gdouble value)
1193 #if SIZEOF_VOID_P == 8
1194 LongDoubleUnion val, ret;
1197 ret.ival = (gint64)InterlockedExchangePointer((gpointer *) location, (gpointer)val.ival);
1204 * According to MSDN, this function is only atomic with regards to the
1205 * other Interlocked functions on 32 bit platforms.
1207 EnterCriticalSection(&interlocked_mutex);
1210 LeaveCriticalSection(&interlocked_mutex);
1216 gint32 ves_icall_System_Threading_Interlocked_CompareExchange_Int(gint32 *location, gint32 value, gint32 comparand)
1218 MONO_ARCH_SAVE_REGS;
1220 return InterlockedCompareExchange(location, value, comparand);
1223 MonoObject * ves_icall_System_Threading_Interlocked_CompareExchange_Object (MonoObject **location, MonoObject *value, MonoObject *comparand)
1225 MONO_ARCH_SAVE_REGS;
1227 return (MonoObject *) InterlockedCompareExchangePointer((gpointer *) location, value, comparand);
1230 gfloat ves_icall_System_Threading_Interlocked_CompareExchange_Single (gfloat *location, gfloat value, gfloat comparand)
1232 IntFloatUnion val, ret, cmp;
1234 MONO_ARCH_SAVE_REGS;
1237 cmp.fval = comparand;
1238 ret.ival = InterlockedCompareExchange((gint32 *) location, val.ival, cmp.ival);
1244 ves_icall_System_Threading_Interlocked_CompareExchange_Double (gdouble *location, gdouble value, gdouble comparand)
1246 #if SIZEOF_VOID_P == 8
1247 LongDoubleUnion val, comp, ret;
1250 comp.fval = comparand;
1251 ret.ival = (gint64)InterlockedCompareExchangePointer((gpointer *) location, (gpointer)val.ival, (gpointer)comp.ival);
1257 EnterCriticalSection(&interlocked_mutex);
1259 if (old == comparand)
1261 LeaveCriticalSection(&interlocked_mutex);
1268 ves_icall_System_Threading_Interlocked_CompareExchange_Long (gint64 *location, gint64 value, gint64 comparand)
1270 #if SIZEOF_VOID_P == 8
1271 return (gint64)InterlockedCompareExchangePointer((gpointer *) location, (gpointer)value, (gpointer)comparand);
1275 EnterCriticalSection(&interlocked_mutex);
1277 if (old == comparand)
1279 LeaveCriticalSection(&interlocked_mutex);
1286 ves_icall_System_Threading_Interlocked_Add_Int (gint32 *location, gint32 value)
1288 #if SIZEOF_VOID_P == 8
1289 /* Should be implemented as a JIT intrinsic */
1290 mono_raise_exception (mono_get_exception_not_implemented (NULL));
1295 EnterCriticalSection(&interlocked_mutex);
1297 *location = orig + value;
1298 LeaveCriticalSection(&interlocked_mutex);
1305 ves_icall_System_Threading_Interlocked_Add_Long (gint64 *location, gint64 value)
1307 #if SIZEOF_VOID_P == 8
1308 /* Should be implemented as a JIT intrinsic */
1309 mono_raise_exception (mono_get_exception_not_implemented (NULL));
1314 EnterCriticalSection(&interlocked_mutex);
1316 *location = orig + value;
1317 LeaveCriticalSection(&interlocked_mutex);
1324 ves_icall_System_Threading_Interlocked_Read_Long (gint64 *location)
1326 #if SIZEOF_VOID_P == 8
1327 /* 64 bit reads are already atomic */
1332 EnterCriticalSection(&interlocked_mutex);
1334 LeaveCriticalSection(&interlocked_mutex);
1341 ves_icall_System_Threading_Thread_ClrState (MonoThread* this, guint32 state)
1343 mono_monitor_enter (this->synch_lock);
1344 this->state &= ~state;
1345 if (state & ThreadState_Background) {
1346 /* If the thread changes the background mode, the main thread has to
1347 * be notified, since it has to rebuild the list of threads to
1350 SetEvent (background_change_event);
1352 mono_monitor_exit (this->synch_lock);
1356 ves_icall_System_Threading_Thread_SetState (MonoThread* this, guint32 state)
1358 mono_monitor_enter (this->synch_lock);
1359 this->state |= state;
1360 if (state & ThreadState_Background) {
1361 /* If the thread changes the background mode, the main thread has to
1362 * be notified, since it has to rebuild the list of threads to
1365 SetEvent (background_change_event);
1367 mono_monitor_exit (this->synch_lock);
1371 ves_icall_System_Threading_Thread_GetState (MonoThread* this)
1374 mono_monitor_enter (this->synch_lock);
1375 state = this->state;
1376 mono_monitor_exit (this->synch_lock);
1381 mono_thread_get_abort_signal (void)
1383 #if defined (__MINGW32__) || defined (_MSC_VER)
1389 static int abort_signum = -1;
1391 if (abort_signum != -1)
1392 return abort_signum;
1393 /* we try to avoid SIGRTMIN and any one that might have been set already, see bug #75387 */
1394 for (i = SIGRTMIN + 1; i < SIGRTMAX; ++i) {
1395 struct sigaction sinfo;
1396 sigaction (i, NULL, &sinfo);
1397 if (sinfo.sa_handler == SIG_DFL && (void*)sinfo.sa_sigaction == (void*)SIG_DFL) {
1402 /* fallback to the old way */
1405 #endif /*defined (__MINGW32__) || defined (_MSC_VER) */
1408 #if defined (__MINGW32__) || defined (_MSC_VER)
1409 static void CALLBACK interruption_request_apc (ULONG_PTR param)
1411 MonoException* exc = mono_thread_request_interruption (FALSE);
1412 if (exc) mono_raise_exception (exc);
1414 #endif /* defined (__MINGW32__) || defined (_MSC_VER) */
1417 * signal_thread_state_change
1419 * Tells the thread that his state has changed and it has to enter the new
1420 * state as soon as possible.
1422 static void signal_thread_state_change (MonoThread *thread)
1424 if (thread == mono_thread_current ()) {
1425 /* Do it synchronously */
1426 MonoException *exc = mono_thread_request_interruption (FALSE);
1428 mono_raise_exception (exc);
1431 #if defined (__MINGW32__) || defined (_MSC_VER)
1432 QueueUserAPC ((PAPCFUNC)interruption_request_apc, thread->handle, NULL);
1434 /* fixme: store the state somewhere */
1435 #ifdef PTHREAD_POINTER_ID
1436 pthread_kill (GUINT_TO_POINTER(thread->tid), mono_thread_get_abort_signal ());
1438 pthread_kill (thread->tid, mono_thread_get_abort_signal ());
1440 #endif /* defined (__MINGW32__) || defined (__MSC_VER) */
1444 ves_icall_System_Threading_Thread_Abort (MonoThread *thread, MonoObject *state)
1446 MONO_ARCH_SAVE_REGS;
1448 mono_monitor_enter (thread->synch_lock);
1450 if ((thread->state & ThreadState_AbortRequested) != 0 ||
1451 (thread->state & ThreadState_StopRequested) != 0)
1453 mono_monitor_exit (thread->synch_lock);
1457 if ((thread->state & ThreadState_Unstarted) != 0) {
1458 thread->state |= ThreadState_Aborted;
1459 mono_monitor_exit (thread->synch_lock);
1463 thread->state |= ThreadState_AbortRequested;
1464 thread->abort_state = state;
1465 thread->abort_exc = NULL;
1467 mono_monitor_exit (thread->synch_lock);
1469 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION
1470 ": (%d) Abort requested for %p (%d)", GetCurrentThreadId (),
1471 thread, thread->tid));
1473 /* Make sure the thread is awake */
1474 mono_thread_resume (thread);
1476 signal_thread_state_change (thread);
1480 ves_icall_System_Threading_Thread_ResetAbort (void)
1482 MonoThread *thread = mono_thread_current ();
1484 MONO_ARCH_SAVE_REGS;
1486 mono_monitor_enter (thread->synch_lock);
1488 thread->state &= ~ThreadState_AbortRequested;
1490 if (!thread->abort_exc) {
1491 const char *msg = "Unable to reset abort because no abort was requested";
1492 mono_monitor_exit (thread->synch_lock);
1493 mono_raise_exception (mono_get_exception_thread_state (msg));
1495 thread->abort_exc = NULL;
1496 thread->abort_state = NULL;
1499 mono_monitor_exit (thread->synch_lock);
1503 mono_thread_suspend (MonoThread *thread)
1505 MONO_ARCH_SAVE_REGS;
1507 mono_monitor_enter (thread->synch_lock);
1509 if ((thread->state & ThreadState_Unstarted) != 0 ||
1510 (thread->state & ThreadState_Aborted) != 0 ||
1511 (thread->state & ThreadState_Stopped) != 0)
1513 mono_monitor_exit (thread->synch_lock);
1517 if ((thread->state & ThreadState_Suspended) != 0 ||
1518 (thread->state & ThreadState_SuspendRequested) != 0 ||
1519 (thread->state & ThreadState_StopRequested) != 0)
1521 mono_monitor_exit (thread->synch_lock);
1525 thread->state |= ThreadState_SuspendRequested;
1526 mono_monitor_exit (thread->synch_lock);
1528 signal_thread_state_change (thread);
1533 ves_icall_System_Threading_Thread_Suspend (MonoThread *thread)
1535 if (!mono_thread_suspend (thread))
1536 mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started, or is dead."));
1540 mono_thread_resume (MonoThread *thread)
1542 MONO_ARCH_SAVE_REGS;
1544 mono_monitor_enter (thread->synch_lock);
1546 if ((thread->state & ThreadState_SuspendRequested) != 0) {
1547 thread->state &= ~ThreadState_SuspendRequested;
1548 mono_monitor_exit (thread->synch_lock);
1552 if ((thread->state & ThreadState_Suspended) == 0 ||
1553 (thread->state & ThreadState_Unstarted) != 0 ||
1554 (thread->state & ThreadState_Aborted) != 0 ||
1555 (thread->state & ThreadState_Stopped) != 0)
1557 mono_monitor_exit (thread->synch_lock);
1561 thread->resume_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1563 /* Awake the thread */
1564 SetEvent (thread->suspend_event);
1566 mono_monitor_exit (thread->synch_lock);
1568 /* Wait for the thread to awake */
1569 WaitForSingleObject (thread->resume_event, INFINITE);
1570 CloseHandle (thread->resume_event);
1571 thread->resume_event = NULL;
1577 ves_icall_System_Threading_Thread_Resume (MonoThread *thread)
1579 if (!mono_thread_resume (thread))
1580 mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started, or is dead."));
1584 find_wrapper (MonoMethod *m, gint no, gint ilo, gboolean managed, gpointer data)
1589 if (m->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE ||
1590 m->wrapper_type == MONO_WRAPPER_XDOMAIN_INVOKE ||
1591 m->wrapper_type == MONO_WRAPPER_XDOMAIN_DISPATCH)
1593 *((gboolean*)data) = TRUE;
1600 is_running_protected_wrapper (void)
1602 gboolean found = FALSE;
1603 mono_stack_walk (find_wrapper, &found);
1607 void mono_thread_stop (MonoThread *thread)
1609 mono_monitor_enter (thread->synch_lock);
1611 if ((thread->state & ThreadState_StopRequested) != 0 ||
1612 (thread->state & ThreadState_Stopped) != 0)
1614 mono_monitor_exit (thread->synch_lock);
1618 /* Make sure the thread is awake */
1619 mono_thread_resume (thread);
1621 thread->state |= ThreadState_StopRequested;
1622 thread->state &= ~ThreadState_AbortRequested;
1624 mono_monitor_exit (thread->synch_lock);
1626 signal_thread_state_change (thread);
1630 ves_icall_System_Threading_Thread_VolatileRead1 (void *ptr)
1632 return *((volatile gint8 *) (ptr));
1636 ves_icall_System_Threading_Thread_VolatileRead2 (void *ptr)
1638 return *((volatile gint16 *) (ptr));
1642 ves_icall_System_Threading_Thread_VolatileRead4 (void *ptr)
1644 return *((volatile gint32 *) (ptr));
1648 ves_icall_System_Threading_Thread_VolatileRead8 (void *ptr)
1650 return *((volatile gint64 *) (ptr));
1654 ves_icall_System_Threading_Thread_VolatileReadIntPtr (void *ptr)
1656 return (void *) *((volatile void **) ptr);
1660 ves_icall_System_Threading_Thread_VolatileWrite1 (void *ptr, gint8 value)
1662 *((volatile gint8 *) ptr) = value;
1666 ves_icall_System_Threading_Thread_VolatileWrite2 (void *ptr, gint16 value)
1668 *((volatile gint16 *) ptr) = value;
1672 ves_icall_System_Threading_Thread_VolatileWrite4 (void *ptr, gint32 value)
1674 *((volatile gint32 *) ptr) = value;
1678 ves_icall_System_Threading_Thread_VolatileWrite8 (void *ptr, gint64 value)
1680 *((volatile gint64 *) ptr) = value;
1684 ves_icall_System_Threading_Thread_VolatileWriteIntPtr (void *ptr, void *value)
1686 *((volatile void **) ptr) = value;
1689 void mono_thread_init (MonoThreadStartCB start_cb,
1690 MonoThreadAttachCB attach_cb)
1692 InitializeCriticalSection(&threads_mutex);
1693 InitializeCriticalSection(&interlocked_mutex);
1694 InitializeCriticalSection(&contexts_mutex);
1695 background_change_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1697 mono_init_static_data_info (&thread_static_info);
1698 mono_init_static_data_info (&context_static_info);
1700 current_object_key=TlsAlloc();
1701 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": Allocated current_object_key %d",
1702 current_object_key));
1704 mono_thread_start_cb = start_cb;
1705 mono_thread_attach_cb = attach_cb;
1707 /* Get a pseudo handle to the current process. This is just a
1708 * kludge so that wapi can build a process handle if needed.
1709 * As a pseudo handle is returned, we don't need to clean
1712 GetCurrentProcess ();
1716 mono_threads_install_cleanup (MonoThreadCleanupFunc func)
1718 mono_thread_cleanup = func;
1721 void mono_install_thread_callbacks (MonoThreadCallbacks *callbacks)
1723 mono_thread_callbacks = callbacks;
1727 static void print_tids (gpointer key, gpointer value, gpointer user)
1729 g_message ("Waiting for: %d", GPOINTER_TO_UINT(key));
1734 HANDLE handles[MAXIMUM_WAIT_OBJECTS];
1735 MonoThread *threads[MAXIMUM_WAIT_OBJECTS];
1739 static void wait_for_tids (struct wait_data *wait, guint32 timeout)
1743 THREAD_DEBUG (g_message(G_GNUC_PRETTY_FUNCTION
1744 ": %d threads to wait for in this batch", wait->num));
1746 ret=WaitForMultipleObjectsEx(wait->num, wait->handles, TRUE, timeout, FALSE);
1748 if(ret==WAIT_FAILED) {
1749 /* See the comment in build_wait_tids() */
1750 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": Wait failed"));
1754 for(i=0; i<wait->num; i++)
1755 CloseHandle (wait->handles[i]);
1757 if (ret == WAIT_TIMEOUT)
1760 for(i=0; i<wait->num; i++) {
1761 guint32 tid=wait->threads[i]->tid;
1763 if(mono_g_hash_table_lookup (threads, GUINT_TO_POINTER(tid))!=NULL) {
1764 /* This thread must have been killed, because
1765 * it hasn't cleaned itself up. (It's just
1766 * possible that the thread exited before the
1767 * parent thread had a chance to store the
1768 * handle, and now there is another pointer to
1769 * the already-exited thread stored. In this
1770 * case, we'll just get two
1771 * mono_profiler_thread_end() calls for the
1775 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION
1776 ": cleaning up after thread %d", tid));
1777 thread_cleanup (wait->threads[i]);
1782 static void wait_for_tids_or_state_change (struct wait_data *wait, guint32 timeout)
1784 guint32 i, ret, count;
1786 THREAD_DEBUG (g_message(G_GNUC_PRETTY_FUNCTION
1787 ": %d threads to wait for in this batch", wait->num));
1789 /* Add the thread state change event, so it wakes up if a thread changes
1790 * to background mode.
1793 if (count < MAXIMUM_WAIT_OBJECTS) {
1794 wait->handles [count] = background_change_event;
1798 ret=WaitForMultipleObjectsEx (count, wait->handles, FALSE, timeout, FALSE);
1800 if(ret==WAIT_FAILED) {
1801 /* See the comment in build_wait_tids() */
1802 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": Wait failed"));
1806 for(i=0; i<wait->num; i++)
1807 CloseHandle (wait->handles[i]);
1809 if (ret == WAIT_TIMEOUT)
1812 if (ret < wait->num) {
1813 guint32 tid=wait->threads[ret]->tid;
1814 EnterCriticalSection (&threads_mutex);
1815 if (mono_g_hash_table_lookup (threads, GUINT_TO_POINTER(tid))!=NULL) {
1816 /* See comment in wait_for_tids about thread cleanup */
1817 LeaveCriticalSection (&threads_mutex);
1818 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION
1819 ": cleaning up after thread %d", tid));
1820 thread_cleanup (wait->threads [ret]);
1823 LeaveCriticalSection (&threads_mutex);
1827 static void build_wait_tids (gpointer key, gpointer value, gpointer user)
1829 struct wait_data *wait=(struct wait_data *)user;
1831 if(wait->num<MAXIMUM_WAIT_OBJECTS) {
1833 MonoThread *thread=(MonoThread *)value;
1835 /* Ignore background threads, we abort them later */
1836 mono_monitor_enter (thread->synch_lock);
1837 if (thread->state & ThreadState_Background) {
1838 mono_monitor_exit (thread->synch_lock);
1839 return; /* just leave, ignore */
1841 mono_monitor_exit (thread->synch_lock);
1843 if (mono_gc_is_finalizer_thread (thread))
1846 if (thread == mono_thread_current ())
1849 if (thread == mono_thread_get_main ())
1852 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
1856 wait->handles[wait->num]=handle;
1857 wait->threads[wait->num]=thread;
1860 /* Just ignore the rest, we can't do anything with
1867 remove_and_abort_threads (gpointer key, gpointer value, gpointer user)
1869 struct wait_data *wait=(struct wait_data *)user;
1870 guint32 self = GetCurrentThreadId ();
1871 MonoThread *thread = (MonoThread *) value;
1874 /* The finalizer thread is not a background thread */
1875 if (thread->tid != self && (thread->state & ThreadState_Background) != 0) {
1877 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
1881 if(thread->state & ThreadState_AbortRequested ||
1882 thread->state & ThreadState_Aborted) {
1883 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": Thread id %d already aborting", thread->tid));
1887 wait->handles[wait->num]=thread->handle;
1888 wait->threads[wait->num]=thread;
1891 THREAD_DEBUG (g_print (G_GNUC_PRETTY_FUNCTION ": Aborting id: %d\n", thread->tid));
1892 mono_thread_stop (thread);
1896 return (thread->tid != self && !mono_gc_is_finalizer_thread (thread));
1899 void mono_thread_manage (void)
1901 struct wait_data *wait=g_new0 (struct wait_data, 1);
1903 /* join each thread that's still running */
1904 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": Joining each running thread..."));
1906 EnterCriticalSection (&threads_mutex);
1908 THREAD_DEBUG (g_message(G_GNUC_PRETTY_FUNCTION ": No threads"));
1909 LeaveCriticalSection (&threads_mutex);
1912 LeaveCriticalSection (&threads_mutex);
1915 EnterCriticalSection (&threads_mutex);
1916 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION
1917 ":There are %d threads to join", mono_g_hash_table_size (threads));
1918 mono_g_hash_table_foreach (threads, print_tids, NULL));
1920 ResetEvent (background_change_event);
1922 mono_g_hash_table_foreach (threads, build_wait_tids, wait);
1923 LeaveCriticalSection (&threads_mutex);
1925 /* Something to wait for */
1926 wait_for_tids_or_state_change (wait, INFINITE);
1928 THREAD_DEBUG (g_message ("I have %d threads after waiting.", wait->num));
1929 } while(wait->num>0);
1931 mono_runtime_set_shutting_down ();
1933 THREAD_DEBUG (g_message ("threadpool cleanup"));
1934 mono_thread_pool_cleanup ();
1936 EnterCriticalSection(&threads_mutex);
1939 * Remove everything but the finalizer thread and self.
1940 * Also abort all the background threads
1943 mono_g_hash_table_foreach_remove (threads, remove_and_abort_threads, wait);
1945 LeaveCriticalSection(&threads_mutex);
1947 THREAD_DEBUG (g_message ("wait->num is now %d", wait->num));
1949 /* Something to wait for */
1950 wait_for_tids (wait, INFINITE);
1953 * give the subthreads a chance to really quit (this is mainly needed
1954 * to get correct user and system times from getrusage/wait/time(1)).
1955 * This could be removed if we avoid pthread_detach() and use pthread_join().
1957 #ifndef PLATFORM_WIN32
1964 static void terminate_thread (gpointer key, gpointer value, gpointer user)
1966 MonoThread *thread=(MonoThread *)value;
1967 guint32 self=GPOINTER_TO_UINT (user);
1969 if(thread->tid!=self) {
1970 /*TerminateThread (thread->handle, -1);*/
1974 void mono_thread_abort_all_other_threads (void)
1976 guint32 self=GetCurrentThreadId ();
1978 EnterCriticalSection (&threads_mutex);
1979 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ":There are %d threads to abort",
1980 mono_g_hash_table_size (threads));
1981 mono_g_hash_table_foreach (threads, print_tids, NULL));
1983 mono_g_hash_table_foreach (threads, terminate_thread,
1984 GUINT_TO_POINTER (self));
1986 LeaveCriticalSection (&threads_mutex);
1990 collect_threads (gpointer key, gpointer value, gpointer user_data)
1992 MonoThread *thread = (MonoThread*)value;
1993 struct wait_data *wait = (struct wait_data*)user_data;
1996 if (wait->num<MAXIMUM_WAIT_OBJECTS) {
1997 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
2001 wait->handles [wait->num] = handle;
2002 wait->threads [wait->num] = thread;
2008 * mono_thread_suspend_all_other_threads:
2010 * Suspend all managed threads except the finalizer thread and this thread.
2012 void mono_thread_suspend_all_other_threads (void)
2014 struct wait_data *wait = g_new0 (struct wait_data, 1);
2016 guint32 self = GetCurrentThreadId ();
2018 guint32 eventidx = 0;
2021 * Make a copy of the hashtable since we can't do anything with
2022 * threads while threads_mutex is held.
2024 EnterCriticalSection (&threads_mutex);
2025 mono_g_hash_table_foreach (threads, collect_threads, wait);
2026 LeaveCriticalSection (&threads_mutex);
2028 events = g_new0 (gpointer, wait->num);
2030 /* Get the suspended events that we'll be waiting for */
2031 for (i = 0; i < wait->num; ++i) {
2032 MonoThread *thread = wait->threads [i];
2034 if ((thread->tid == self) || mono_gc_is_finalizer_thread (thread)) {
2035 //CloseHandle (wait->handles [i]);
2036 wait->threads [i] = NULL; /* ignore this thread in next loop */
2040 mono_monitor_enter (thread->synch_lock);
2042 if ((thread->state & ThreadState_Suspended) != 0 ||
2043 (thread->state & ThreadState_SuspendRequested) != 0 ||
2044 (thread->state & ThreadState_StopRequested) != 0 ||
2045 (thread->state & ThreadState_Stopped) != 0) {
2046 mono_monitor_exit (thread->synch_lock);
2047 CloseHandle (wait->handles [i]);
2048 wait->threads [i] = NULL; /* ignore this thread in next loop */
2052 /* Convert abort requests into suspend requests */
2053 if ((thread->state & ThreadState_AbortRequested) != 0)
2054 thread->state &= ~ThreadState_AbortRequested;
2056 thread->state |= ThreadState_SuspendRequested;
2058 if (thread->suspended_event == NULL)
2059 thread->suspended_event = CreateEvent (NULL, TRUE, FALSE, NULL);
2061 events [eventidx++] = thread->suspended_event;
2062 mono_monitor_exit (thread->synch_lock);
2064 /* Signal the thread to suspend */
2065 signal_thread_state_change (thread);
2068 WaitForMultipleObjectsEx (eventidx, events, TRUE, INFINITE, FALSE);
2069 for (i = 0; i < wait->num; ++i) {
2070 MonoThread *thread = wait->threads [i];
2075 mono_monitor_enter (thread->synch_lock);
2076 CloseHandle (thread->suspended_event);
2077 thread->suspended_event = NULL;
2078 mono_monitor_exit (thread->synch_lock);
2086 * mono_thread_push_appdomain_ref:
2088 * Register that the current thread may have references to objects in domain
2089 * @domain on its stack. Each call to this function should be paired with a
2090 * call to pop_appdomain_ref.
2093 mono_thread_push_appdomain_ref (MonoDomain *domain)
2095 MonoThread *thread = mono_thread_current ();
2098 /* printf ("PUSH REF: %x -> %s.\n", thread->tid, domain->friendly_name); */
2099 EnterCriticalSection (&threads_mutex);
2100 thread->appdomain_refs = g_slist_prepend (thread->appdomain_refs, domain);
2101 LeaveCriticalSection (&threads_mutex);
2106 mono_thread_pop_appdomain_ref (void)
2108 MonoThread *thread = mono_thread_current ();
2111 /* printf ("POP REF: %x -> %s.\n", thread->tid, ((MonoDomain*)(thread->appdomain_refs->data))->friendly_name); */
2112 EnterCriticalSection (&threads_mutex);
2113 /* FIXME: How can the list be empty ? */
2114 if (thread->appdomain_refs)
2115 thread->appdomain_refs = g_slist_remove (thread->appdomain_refs, thread->appdomain_refs->data);
2116 LeaveCriticalSection (&threads_mutex);
2121 mono_thread_has_appdomain_ref (MonoThread *thread, MonoDomain *domain)
2124 EnterCriticalSection (&threads_mutex);
2125 res = g_slist_find (thread->appdomain_refs, domain) != NULL;
2126 LeaveCriticalSection (&threads_mutex);
2130 typedef struct abort_appdomain_data {
2131 struct wait_data wait;
2133 } abort_appdomain_data;
2136 abort_appdomain_thread (gpointer key, gpointer value, gpointer user_data)
2138 MonoThread *thread = (MonoThread*)value;
2139 abort_appdomain_data *data = (abort_appdomain_data*)user_data;
2140 MonoDomain *domain = data->domain;
2142 if (mono_thread_has_appdomain_ref (thread, domain)) {
2143 HANDLE handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
2147 /* printf ("ABORTING THREAD %p BECAUSE IT REFERENCES DOMAIN %s.\n", thread->tid, domain->friendly_name); */
2149 ves_icall_System_Threading_Thread_Abort (thread, NULL);
2151 if(data->wait.num<MAXIMUM_WAIT_OBJECTS) {
2152 data->wait.handles [data->wait.num] = handle;
2153 data->wait.threads [data->wait.num] = thread;
2156 /* Just ignore the rest, we can't do anything with
2164 * mono_threads_abort_appdomain_threads:
2166 * Abort threads which has references to the given appdomain.
2169 mono_threads_abort_appdomain_threads (MonoDomain *domain, int timeout)
2171 abort_appdomain_data user_data;
2174 /* printf ("ABORT BEGIN.\n"); */
2176 start_time = GetTickCount ();
2178 EnterCriticalSection (&threads_mutex);
2180 user_data.domain = domain;
2181 user_data.wait.num = 0;
2182 mono_g_hash_table_foreach (threads, abort_appdomain_thread, &user_data);
2183 LeaveCriticalSection (&threads_mutex);
2185 if (user_data.wait.num > 0)
2187 * We should wait for the threads either to abort, or to leave the
2188 * domain. We can't do the latter, so we wait with a timeout.
2190 wait_for_tids (&user_data.wait, 100);
2192 /* Update remaining time */
2193 timeout -= GetTickCount () - start_time;
2194 start_time = GetTickCount ();
2199 while (user_data.wait.num > 0);
2201 /* printf ("ABORT DONE.\n"); */
2207 clear_cached_culture (gpointer key, gpointer value, gpointer user_data)
2209 MonoThread *thread = (MonoThread*)value;
2210 MonoDomain *domain = (MonoDomain*)user_data;
2213 /* No locking needed here */
2215 if (thread->culture_info) {
2216 for (i = 0; i < NUM_CACHED_CULTURES; ++i) {
2217 if (thread->culture_info [i] && thread->culture_info [i]->vtable->domain == domain)
2218 thread->culture_info [i] = NULL;
2221 if (thread->ui_culture_info) {
2222 for (i = 0; i < NUM_CACHED_CULTURES; ++i) {
2223 if (thread->ui_culture_info [i] && thread->ui_culture_info [i]->vtable->domain == domain)
2224 thread->ui_culture_info [i] = NULL;
2230 * mono_threads_clear_cached_culture:
2232 * Clear the cached_current_culture from all threads if it is in the
2236 mono_threads_clear_cached_culture (MonoDomain *domain)
2238 EnterCriticalSection (&threads_mutex);
2239 mono_g_hash_table_foreach (threads, clear_cached_culture, domain);
2240 LeaveCriticalSection (&threads_mutex);
2244 * mono_thread_get_pending_exception:
2246 * Return an exception which needs to be raised when leaving a catch clause.
2247 * This is used for undeniable exception propagation.
2250 mono_thread_get_pending_exception (void)
2252 MonoThread *thread = mono_thread_current ();
2254 MONO_ARCH_SAVE_REGS;
2256 if (thread && thread->abort_exc && !is_running_protected_wrapper ()) {
2258 * FIXME: Clear the abort exception and return an AppDomainUnloaded
2259 * exception if the thread no longer references a dying appdomain.
2261 thread->abort_exc->trace_ips = NULL;
2262 thread->abort_exc->stack_trace = NULL;
2263 return thread->abort_exc;
2269 #define NUM_STATIC_DATA_IDX 8
2270 static const int static_data_size [NUM_STATIC_DATA_IDX] = {
2271 1024, 4096, 16384, 65536, 262144, 1048576, 4194304, 16777216
2276 * mono_alloc_static_data
2278 * Allocate memory blocks for storing threads or context static data
2281 mono_alloc_static_data (gpointer **static_data_ptr, guint32 offset)
2283 guint idx = (offset >> 24) - 1;
2286 gpointer* static_data = *static_data_ptr;
2288 static_data = mono_gc_alloc_fixed (static_data_size [0], NULL);
2289 *static_data_ptr = static_data;
2290 static_data [0] = static_data;
2293 for (i = 1; i <= idx; ++i) {
2294 if (static_data [i])
2296 static_data [i] = mono_gc_alloc_fixed (static_data_size [i], NULL);
2301 * mono_init_static_data_info
2303 * Initializes static data counters
2305 static void mono_init_static_data_info (StaticDataInfo *static_data)
2307 static_data->idx = 0;
2308 static_data->offset = 0;
2312 * mono_alloc_static_data_slot
2314 * Generates an offset for static data. static_data contains the counters
2315 * used to generate it.
2318 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align)
2322 if (!static_data->idx && !static_data->offset) {
2324 * we use the first chunk of the first allocation also as
2325 * an array for the rest of the data
2327 static_data->offset = sizeof (gpointer) * NUM_STATIC_DATA_IDX;
2329 static_data->offset += align - 1;
2330 static_data->offset &= ~(align - 1);
2331 if (static_data->offset + size >= static_data_size [static_data->idx]) {
2332 static_data->idx ++;
2333 g_assert (size <= static_data_size [static_data->idx]);
2335 * massive unloading and reloading of domains with thread-static
2336 * data may eventually exceed the allocated storage...
2337 * Need to check what the MS runtime does in that case.
2338 * Note that for each appdomain, we need to allocate a separate
2339 * thread data slot for security reasons. We could keep track
2340 * of the slots per-domain and when the domain is unloaded
2341 * out the slots on a sort of free list.
2343 g_assert (static_data->idx < NUM_STATIC_DATA_IDX);
2344 static_data->offset = 0;
2346 offset = static_data->offset | ((static_data->idx + 1) << 24);
2347 static_data->offset += size;
2352 * ensure thread static fields already allocated are valid for thread
2353 * This function is called when a thread is created or on thread attach.
2356 thread_adjust_static_data (MonoThread *thread)
2360 EnterCriticalSection (&threads_mutex);
2361 if (thread_static_info.offset || thread_static_info.idx > 0) {
2362 /* get the current allocated size */
2363 offset = thread_static_info.offset | ((thread_static_info.idx + 1) << 24);
2364 mono_alloc_static_data (&(thread->static_data), offset);
2366 LeaveCriticalSection (&threads_mutex);
2370 alloc_thread_static_data_helper (gpointer key, gpointer value, gpointer user)
2372 MonoThread *thread = value;
2373 guint32 offset = GPOINTER_TO_UINT (user);
2375 mono_alloc_static_data (&(thread->static_data), offset);
2379 * The offset for a special static variable is composed of three parts:
2380 * a bit that indicates the type of static data (0:thread, 1:context),
2381 * an index in the array of chunks of memory for the thread (thread->static_data)
2382 * and an offset in that chunk of mem. This allows allocating less memory in the
2387 mono_alloc_special_static_data (guint32 static_type, guint32 size, guint32 align)
2390 if (static_type == SPECIAL_STATIC_THREAD)
2392 EnterCriticalSection (&threads_mutex);
2393 offset = mono_alloc_static_data_slot (&thread_static_info, size, align);
2394 /* This can be called during startup */
2395 if (threads != NULL)
2396 mono_g_hash_table_foreach (threads, alloc_thread_static_data_helper, GUINT_TO_POINTER (offset));
2397 LeaveCriticalSection (&threads_mutex);
2401 g_assert (static_type == SPECIAL_STATIC_CONTEXT);
2402 EnterCriticalSection (&contexts_mutex);
2403 offset = mono_alloc_static_data_slot (&context_static_info, size, align);
2404 LeaveCriticalSection (&contexts_mutex);
2405 offset |= 0x80000000; /* Set the high bit to indicate context static data */
2411 mono_get_special_static_data (guint32 offset)
2413 /* The high bit means either thread (0) or static (1) data. */
2415 guint32 static_type = (offset & 0x80000000);
2418 offset &= 0x7fffffff;
2419 idx = (offset >> 24) - 1;
2421 if (static_type == 0)
2423 MonoThread *thread = mono_thread_current ();
2424 return ((char*) thread->static_data [idx]) + (offset & 0xffffff);
2428 /* Allocate static data block under demand, since we don't have a list
2431 MonoAppContext *context = mono_context_get ();
2432 if (!context->static_data || !context->static_data [idx]) {
2433 EnterCriticalSection (&contexts_mutex);
2434 mono_alloc_static_data (&(context->static_data), offset);
2435 LeaveCriticalSection (&contexts_mutex);
2437 return ((char*) context->static_data [idx]) + (offset & 0xffffff);
2441 static void gc_stop_world (gpointer key, gpointer value, gpointer user)
2443 MonoThread *thread=(MonoThread *)value;
2444 guint32 self=GPOINTER_TO_UINT (user);
2446 LIBGC_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": %d - %d", self, thread->tid));
2448 if(thread->tid==self)
2451 SuspendThread (thread->handle);
2454 void mono_gc_stop_world (void)
2456 guint32 self=GetCurrentThreadId ();
2458 LIBGC_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": %d - %p", self, threads));
2460 EnterCriticalSection (&threads_mutex);
2462 if (threads != NULL)
2463 mono_g_hash_table_foreach (threads, gc_stop_world, GUINT_TO_POINTER (self));
2465 LeaveCriticalSection (&threads_mutex);
2468 static void gc_start_world (gpointer key, gpointer value, gpointer user)
2470 MonoThread *thread=(MonoThread *)value;
2471 guint32 self=GPOINTER_TO_UINT (user);
2473 LIBGC_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": %d - %d", self, thread->tid));
2475 if(thread->tid==self)
2478 ResumeThread (thread->handle);
2481 void mono_gc_start_world (void)
2483 guint32 self=GetCurrentThreadId ();
2485 LIBGC_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": %d - %p", self, threads));
2487 EnterCriticalSection (&threads_mutex);
2489 if (threads != NULL)
2490 mono_g_hash_table_foreach (threads, gc_start_world, GUINT_TO_POINTER (self));
2492 LeaveCriticalSection (&threads_mutex);
2496 static CALLBACK void dummy_apc (ULONG_PTR param)
2500 static guint32 dummy_apc (gpointer param)
2507 * mono_thread_execute_interruption
2509 * Performs the operation that the requested thread state requires (abort,
2512 static MonoException* mono_thread_execute_interruption (MonoThread *thread)
2514 mono_monitor_enter (thread->synch_lock);
2516 if (thread->interruption_requested) {
2517 /* this will consume pending APC calls */
2518 WaitForSingleObjectEx (GetCurrentThread(), 0, TRUE);
2519 InterlockedDecrement (&thread_interruption_requested);
2520 thread->interruption_requested = FALSE;
2523 if ((thread->state & ThreadState_AbortRequested) != 0) {
2524 if (thread->abort_exc == NULL)
2525 thread->abort_exc = mono_get_exception_thread_abort ();
2526 mono_monitor_exit (thread->synch_lock);
2527 return thread->abort_exc;
2529 else if ((thread->state & ThreadState_SuspendRequested) != 0) {
2530 thread->state &= ~ThreadState_SuspendRequested;
2531 thread->state |= ThreadState_Suspended;
2532 thread->suspend_event = CreateEvent (NULL, TRUE, FALSE, NULL);
2533 if (thread->suspended_event)
2534 SetEvent (thread->suspended_event);
2535 mono_monitor_exit (thread->synch_lock);
2537 WaitForSingleObject (thread->suspend_event, INFINITE);
2539 mono_monitor_enter (thread->synch_lock);
2540 CloseHandle (thread->suspend_event);
2541 thread->suspend_event = NULL;
2542 thread->state &= ~ThreadState_Suspended;
2544 /* The thread that requested the resume will have replaced this event
2545 * and will be waiting for it
2547 SetEvent (thread->resume_event);
2548 mono_monitor_exit (thread->synch_lock);
2551 else if ((thread->state & ThreadState_StopRequested) != 0) {
2552 /* FIXME: do this through the JIT? */
2553 mono_monitor_exit (thread->synch_lock);
2554 mono_thread_exit ();
2558 mono_monitor_exit (thread->synch_lock);
2563 * mono_thread_request_interruption
2565 * A signal handler can call this method to request the interruption of a
2566 * thread. The result of the interruption will depend on the current state of
2567 * the thread. If the result is an exception that needs to be throw, it is
2568 * provided as return value.
2570 MonoException* mono_thread_request_interruption (gboolean running_managed)
2572 MonoThread *thread = mono_thread_current ();
2574 /* The thread may already be stopping */
2578 mono_monitor_enter (thread->synch_lock);
2580 if (thread->interruption_requested) {
2581 mono_monitor_exit (thread->synch_lock);
2585 if (!running_managed || is_running_protected_wrapper ()) {
2586 /* Can't stop while in unmanaged code. Increase the global interruption
2587 request count. When exiting the unmanaged method the count will be
2588 checked and the thread will be interrupted. */
2590 InterlockedIncrement (&thread_interruption_requested);
2591 thread->interruption_requested = TRUE;
2592 mono_monitor_exit (thread->synch_lock);
2594 /* this will awake the thread if it is in WaitForSingleObject
2596 QueueUserAPC ((PAPCFUNC)dummy_apc, thread->handle, NULL);
2600 mono_monitor_exit (thread->synch_lock);
2601 return mono_thread_execute_interruption (thread);
2605 gboolean mono_thread_interruption_requested ()
2607 if (thread_interruption_requested) {
2608 MonoThread *thread = mono_thread_current ();
2609 /* The thread may already be stopping */
2611 return (thread->interruption_requested);
2616 static void mono_thread_interruption_checkpoint_request (gboolean bypass_abort_protection)
2618 MonoThread *thread = mono_thread_current ();
2620 /* The thread may already be stopping */
2624 if (thread->interruption_requested && (bypass_abort_protection || !is_running_protected_wrapper ())) {
2625 MonoException* exc = mono_thread_execute_interruption (thread);
2626 if (exc) mono_raise_exception (exc);
2631 * Performs the interruption of the current thread, if one has been requested,
2632 * and the thread is not running a protected wrapper.
2634 void mono_thread_interruption_checkpoint ()
2636 mono_thread_interruption_checkpoint_request (FALSE);
2640 * Performs the interruption of the current thread, if one has been requested.
2642 void mono_thread_force_interruption_checkpoint ()
2644 mono_thread_interruption_checkpoint_request (TRUE);
2648 * mono_thread_interruption_request_flag:
2650 * Returns the address of a flag that will be non-zero if an interruption has
2651 * been requested for a thread. The thread to interrupt may not be the current
2652 * thread, so an additional call to mono_thread_interruption_requested() or
2653 * mono_thread_interruption_checkpoint() is allways needed if the flag is not
2656 gint32* mono_thread_interruption_request_flag ()
2658 return &thread_interruption_requested;
2661 #ifdef WITH_INCLUDED_LIBGC
2663 static void gc_push_all_stacks (gpointer key, gpointer value, gpointer user)
2665 MonoThread *thread=(MonoThread *)value;
2666 guint32 *selfp=(guint32 *)user, self = *selfp;
2668 LIBGC_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": %d - %d - %p", self, thread->tid, thread->stack_ptr));
2670 if(thread->tid==self) {
2671 LIBGC_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": %p - %p", selfp, thread->stack_ptr));
2672 GC_push_all_stack (selfp, thread->stack_ptr);
2676 #ifdef PLATFORM_WIN32
2677 GC_win32_push_thread_stack (thread->handle, thread->stack_ptr);
2679 mono_wapi_push_thread_stack (thread->handle, thread->stack_ptr);
2683 void mono_gc_push_all_stacks (void)
2685 guint32 self=GetCurrentThreadId ();
2687 LIBGC_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": %d - %p", self, threads));
2689 EnterCriticalSection (&threads_mutex);
2691 if (threads != NULL)
2692 mono_g_hash_table_foreach (threads, gc_push_all_stacks, &self);
2694 LeaveCriticalSection (&threads_mutex);
2697 #endif /* WITH_INCLUDED_LIBGC */