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 #define mono_threads_lock() EnterCriticalSection (&threads_mutex)
79 #define mono_threads_unlock() LeaveCriticalSection (&threads_mutex)
80 static CRITICAL_SECTION threads_mutex;
82 /* Controls access to context static data */
83 #define mono_contexts_lock() EnterCriticalSection (&contexts_mutex)
84 #define mono_contexts_unlock() LeaveCriticalSection (&contexts_mutex)
85 static CRITICAL_SECTION contexts_mutex;
87 /* Holds current status of static data heap */
88 static StaticDataInfo thread_static_info;
89 static StaticDataInfo context_static_info;
91 /* The hash of existing threads (key is thread ID) that need joining
94 static MonoGHashTable *threads=NULL;
96 /* The TLS key that holds the MonoObject assigned to each thread */
97 static guint32 current_object_key = -1;
100 /* we need to use both the Tls* functions and __thread because
101 * the gc needs to see all the threads
103 static __thread MonoThread * tls_current_object MONO_TLS_FAST;
104 #define SET_CURRENT_OBJECT(x) do { \
105 tls_current_object = x; \
106 TlsSetValue (current_object_key, x); \
108 #define GET_CURRENT_OBJECT() tls_current_object
110 #define SET_CURRENT_OBJECT(x) TlsSetValue (current_object_key, x);
111 #define GET_CURRENT_OBJECT() (MonoThread*) TlsGetValue (current_object_key);
114 /* function called at thread start */
115 static MonoThreadStartCB mono_thread_start_cb = NULL;
117 /* function called at thread attach */
118 static MonoThreadAttachCB mono_thread_attach_cb = NULL;
120 /* function called at thread cleanup */
121 static MonoThreadCleanupFunc mono_thread_cleanup = NULL;
123 /* function called when a new thread has been created */
124 static MonoThreadCallbacks *mono_thread_callbacks = NULL;
126 /* The default stack size for each thread */
127 static guint32 default_stacksize = 0;
128 #define default_stacksize_for_thread(thread) ((thread)->stack_size? (thread)->stack_size: default_stacksize)
130 static void thread_adjust_static_data (MonoThread *thread);
131 static void mono_init_static_data_info (StaticDataInfo *static_data);
132 static guint32 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align);
133 static gboolean mono_thread_resume (MonoThread* thread);
134 static void mono_thread_start (MonoThread *thread);
136 /* Spin lock for InterlockedXXX 64 bit functions */
137 #define mono_interlocked_lock() EnterCriticalSection (&interlocked_mutex)
138 #define mono_interlocked_unlock() LeaveCriticalSection (&interlocked_mutex)
139 static CRITICAL_SECTION interlocked_mutex;
141 /* global count of thread interruptions requested */
142 static gint32 thread_interruption_requested = 0;
144 /* Event signaled when a thread changes its background mode */
145 static HANDLE background_change_event;
148 mono_thread_get_tls_key (void)
150 return current_object_key;
154 mono_thread_get_tls_offset (void)
157 MONO_THREAD_VAR_OFFSET (tls_current_object,offset);
161 /* handle_store() and handle_remove() manage the array of threads that
162 * still need to be waited for when the main thread exits.
164 static void handle_store(MonoThread *thread)
166 mono_threads_lock ();
168 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": thread %p ID %"G_GSIZE_FORMAT, thread, (gsize)thread->tid));
171 MONO_GC_REGISTER_ROOT (threads);
172 threads=mono_g_hash_table_new(NULL, NULL);
175 /* We don't need to duplicate thread->handle, because it is
176 * only closed when the thread object is finalized by the GC.
178 mono_g_hash_table_insert(threads, (gpointer)(gsize)(thread->tid),
181 mono_threads_unlock ();
184 static void handle_remove(gsize tid)
186 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": thread ID %"G_GSIZE_FORMAT, tid));
188 mono_threads_lock ();
192 mono_g_hash_table_remove (threads, (gpointer)tid);
194 mono_threads_unlock ();
196 /* Don't close the handle here, wait for the object finalizer
197 * to do it. Otherwise, the following race condition applies:
199 * 1) Thread exits (and handle_remove() closes the handle)
201 * 2) Some other handle is reassigned the same slot
203 * 3) Another thread tries to join the first thread, and
204 * blocks waiting for the reassigned handle to be signalled
205 * (which might never happen). This is possible, because the
206 * thread calling Join() still has a reference to the first
211 static void thread_cleanup (MonoThread *thread)
213 g_assert (thread != NULL);
215 mono_release_type_locks (thread);
217 if (!mono_monitor_enter (thread->synch_lock))
220 thread->state |= ThreadState_Stopped;
221 mono_monitor_exit (thread->synch_lock);
223 mono_profiler_thread_end (thread->tid);
224 handle_remove (thread->tid);
226 mono_thread_pop_appdomain_ref ();
228 if (thread->serialized_culture_info)
229 g_free (thread->serialized_culture_info);
231 mono_gc_free_fixed (thread->culture_info);
232 mono_gc_free_fixed (thread->ui_culture_info);
234 if (mono_thread_cleanup)
235 mono_thread_cleanup (thread);
238 static guint32 WINAPI start_wrapper(void *data)
240 struct StartInfo *start_info=(struct StartInfo *)data;
241 guint32 (*start_func)(void *);
244 MonoThread *thread=start_info->obj;
245 MonoObject *start_delegate = start_info->delegate;
247 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%"G_GSIZE_FORMAT") Start wrapper", GetCurrentThreadId ()));
249 /* We can be sure start_info->obj->tid and
250 * start_info->obj->handle have been set, because the thread
251 * was created suspended, and these values were set before the
257 SET_CURRENT_OBJECT (thread);
259 if (!mono_domain_set (start_info->domain, FALSE)) {
260 /* No point in raising an appdomain_unloaded exception here */
261 /* FIXME: Cleanup here */
265 start_func = start_info->func;
266 start_arg = start_info->start_arg;
268 /* This MUST be called before any managed code can be
269 * executed, as it calls the callback function that (for the
270 * jit) sets the lmf marker.
272 mono_thread_new_init (tid, &tid, start_func);
273 thread->stack_ptr = &tid;
275 LIBGC_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION
276 ": (%"G_GSIZE_FORMAT",%d) Setting thread stack to %p",
277 GetCurrentThreadId (), getpid (), thread->stack_ptr));
279 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION
280 ": (%"G_GSIZE_FORMAT") Setting current_object_key to %p",
281 GetCurrentThreadId (), thread));
283 mono_profiler_thread_start (tid);
285 if(thread->start_notify!=NULL) {
286 /* Let the thread that called Start() know we're
289 ReleaseSemaphore (thread->start_notify, 1, NULL);
294 /* Every thread references the appdomain which created it */
295 mono_thread_push_appdomain_ref (mono_domain_get ());
297 thread_adjust_static_data (thread);
299 g_message (G_GNUC_PRETTY_FUNCTION "start_wrapper for %"G_GSIZE_FORMAT,
303 /* start_func is set only for unamanged start functions */
305 start_func (start_arg);
308 g_assert (start_delegate != NULL);
309 args [0] = start_arg;
310 /* we may want to handle the exception here. See comment below on unhandled exceptions */
311 mono_runtime_delegate_invoke (start_delegate, args, NULL);
314 /* If the thread calls ExitThread at all, this remaining code
315 * will not be executed, but the main thread will eventually
316 * call thread_cleanup() on this thread's behalf.
319 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%"G_GSIZE_FORMAT") Start wrapper terminating", GetCurrentThreadId ()));
321 /* Remove the reference to the thread object in the TLS data,
322 * so the thread object can be finalized. This won't be
323 * reached if the thread threw an uncaught exception, so those
324 * thread handles will stay referenced :-( (This is due to
325 * missing support for scanning thread-specific data in the
326 * Boehm GC - the io-layer keeps a GC-visible hash of pointers
329 SET_CURRENT_OBJECT (NULL);
331 thread_cleanup (thread);
336 void mono_thread_new_init (gsize tid, gpointer stack_start, gpointer func)
338 if (mono_thread_start_cb) {
339 mono_thread_start_cb (tid, stack_start, func);
342 if (mono_thread_callbacks)
343 (* mono_thread_callbacks->thread_created) (tid, stack_start, func);
346 void mono_threads_set_default_stacksize (guint32 stacksize)
348 default_stacksize = stacksize;
351 guint32 mono_threads_get_default_stacksize (void)
353 return default_stacksize;
356 void mono_thread_create (MonoDomain *domain, gpointer func, gpointer arg)
359 HANDLE thread_handle;
360 struct StartInfo *start_info;
363 thread=(MonoThread *)mono_object_new (domain,
364 mono_defaults.thread_class);
366 start_info=g_new0 (struct StartInfo, 1);
367 start_info->func = func;
368 start_info->obj = thread;
369 start_info->domain = domain;
370 start_info->start_arg = arg;
372 /* Create suspended, so we can do some housekeeping before the thread
375 thread_handle = CreateThread(NULL, default_stacksize_for_thread (thread), (LPTHREAD_START_ROUTINE)start_wrapper, start_info,
376 CREATE_SUSPENDED, &tid);
377 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": Started thread ID %"G_GSIZE_FORMAT" (handle %p)",
378 tid, thread_handle));
379 if (thread_handle == NULL) {
380 /* The thread couldn't be created, so throw an exception */
381 mono_raise_exception (mono_get_exception_execution_engine ("Couldn't create thread"));
385 thread->handle=thread_handle;
388 thread->synch_lock=mono_object_new (domain, mono_defaults.object_class);
390 handle_store(thread);
392 ResumeThread (thread_handle);
396 mono_thread_attach (MonoDomain *domain)
399 HANDLE thread_handle;
402 if ((thread = mono_thread_current ())) {
403 /* Already attached */
407 if (!mono_gc_register_thread (&domain)) {
408 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 ());
411 thread = (MonoThread *)mono_object_new (domain,
412 mono_defaults.thread_class);
414 thread_handle = GetCurrentThread ();
415 g_assert (thread_handle);
417 tid=GetCurrentThreadId ();
419 #ifdef PLATFORM_WIN32
421 * The handle returned by GetCurrentThread () is a pseudo handle, so it can't be used to
422 * refer to the thread from other threads for things like aborting.
424 DuplicateHandle (GetCurrentProcess (), thread_handle, GetCurrentProcess (), &thread_handle,
425 THREAD_ALL_ACCESS, TRUE, 0);
428 thread->handle=thread_handle;
430 thread->synch_lock=mono_object_new (domain, mono_defaults.object_class);
432 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": Attached thread ID %"G_GSIZE_FORMAT" (handle %p)",
433 tid, thread_handle));
435 handle_store(thread);
437 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%"G_GSIZE_FORMAT") Setting current_object_key to %p",
438 GetCurrentThreadId (), thread));
440 SET_CURRENT_OBJECT (thread);
441 mono_domain_set (domain, TRUE);
443 thread_adjust_static_data (thread);
445 if (mono_thread_attach_cb) {
446 mono_thread_attach_cb (tid, &tid);
453 mono_thread_detach (MonoThread *thread)
455 g_return_if_fail (thread != NULL);
457 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION "mono_thread_detach for %"G_GSIZE_FORMAT, thread->tid));
458 SET_CURRENT_OBJECT (NULL);
460 thread_cleanup (thread);
466 MonoThread *thread = mono_thread_current ();
468 SET_CURRENT_OBJECT (NULL);
469 thread_cleanup (thread);
471 /* we could add a callback here for embedders to use. */
472 if (thread == mono_thread_get_main ())
473 exit (mono_environment_exitcode_get ());
477 HANDLE ves_icall_System_Threading_Thread_Thread_internal(MonoThread *this,
480 guint32 (*start_func)(void *);
481 struct StartInfo *start_info;
487 THREAD_DEBUG (g_message(G_GNUC_PRETTY_FUNCTION
488 ": Trying to start a new thread: this (%p) start (%p)", this, start));
490 mono_monitor_enter (this->synch_lock);
492 if ((this->state & ThreadState_Unstarted) == 0) {
493 mono_monitor_exit (this->synch_lock);
494 mono_raise_exception (mono_get_exception_thread_state ("Thread has already been started."));
498 if ((this->state & ThreadState_Aborted) != 0) {
499 mono_monitor_exit (this->synch_lock);
504 /* This is freed in start_wrapper */
505 start_info = g_new0 (struct StartInfo, 1);
506 start_info->func = start_func;
507 start_info->start_arg = this->start_obj;
508 start_info->delegate = start;
509 start_info->obj = this;
510 start_info->domain = mono_domain_get ();
512 this->start_notify=CreateSemaphore (NULL, 0, 0x7fffffff, NULL);
513 if(this->start_notify==NULL) {
514 mono_monitor_exit (this->synch_lock);
515 g_warning (G_GNUC_PRETTY_FUNCTION ": CreateSemaphore error 0x%x", GetLastError ());
519 thread=CreateThread(NULL, default_stacksize_for_thread (this), (LPTHREAD_START_ROUTINE)start_wrapper, start_info,
520 CREATE_SUSPENDED, &tid);
522 mono_monitor_exit (this->synch_lock);
523 g_warning(G_GNUC_PRETTY_FUNCTION
524 ": CreateThread error 0x%x", GetLastError());
531 /* Don't call handle_store() here, delay it to Start.
532 * We can't join a thread (trying to will just block
533 * forever) until it actually starts running, so don't
534 * store the handle till then.
537 mono_thread_start (this);
539 this->state &= ~ThreadState_Unstarted;
541 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": Started thread ID %"G_GSIZE_FORMAT" (handle %p)", tid, thread));
543 mono_monitor_exit (this->synch_lock);
548 void ves_icall_System_Threading_Thread_Thread_free_internal (MonoThread *this,
553 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": Closing thread %p, handle %p", this, thread));
555 CloseHandle (thread);
558 static void mono_thread_start (MonoThread *thread)
562 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%"G_GSIZE_FORMAT") Launching thread %p (%"G_GSIZE_FORMAT")", GetCurrentThreadId (), thread, (gsize)thread->tid));
564 /* Only store the handle when the thread is about to be
565 * launched, to avoid the main thread deadlocking while trying
566 * to clean up a thread that will never be signalled.
568 handle_store (thread);
570 if (mono_thread_callbacks)
571 (* mono_thread_callbacks->start_resume) (thread->tid);
573 ResumeThread (thread->handle);
575 if (mono_thread_callbacks)
576 (* mono_thread_callbacks->end_resume) (thread->tid);
578 if(thread->start_notify!=NULL) {
579 /* Wait for the thread to set up its TLS data etc, so
580 * theres no potential race condition if someone tries
581 * to look up the data believing the thread has
585 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%"G_GSIZE_FORMAT") waiting for thread %p (%"G_GSIZE_FORMAT") to start", GetCurrentThreadId (), thread, (gsize)thread->tid));
587 WaitForSingleObjectEx (thread->start_notify, INFINITE, FALSE);
588 CloseHandle (thread->start_notify);
589 thread->start_notify = NULL;
592 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%"G_GSIZE_FORMAT") Done launching thread %p (%"G_GSIZE_FORMAT")", GetCurrentThreadId (), thread, (gsize)thread->tid));
595 void ves_icall_System_Threading_Thread_Sleep_internal(gint32 ms)
597 MonoThread *thread = mono_thread_current ();
601 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": Sleeping for %d ms", ms));
603 mono_monitor_enter (thread->synch_lock);
604 thread->state |= ThreadState_WaitSleepJoin;
605 mono_monitor_exit (thread->synch_lock);
609 mono_monitor_enter (thread->synch_lock);
610 thread->state &= ~ThreadState_WaitSleepJoin;
611 mono_monitor_exit (thread->synch_lock);
615 ves_icall_System_Threading_Thread_GetDomainID (void)
619 return mono_domain_get()->domain_id;
623 ves_icall_System_Threading_Thread_GetName_internal (MonoThread *this_obj)
626 mono_monitor_enter (this_obj->synch_lock);
631 str = mono_string_new_utf16 (mono_domain_get (), this_obj->name, this_obj->name_len);
633 mono_monitor_exit (this_obj->synch_lock);
638 ves_icall_System_Threading_Thread_SetName_internal (MonoThread *this_obj, MonoString *name)
640 mono_monitor_enter (this_obj->synch_lock);
642 if (this_obj->name) {
643 mono_monitor_exit (this_obj->synch_lock);
644 mono_raise_exception (mono_get_exception_invalid_operation ("Thread.Name can only be set once."));
648 this_obj->name = g_new (gunichar2, mono_string_length (name));
649 memcpy (this_obj->name, mono_string_chars (name), mono_string_length (name) * 2);
650 this_obj->name_len = mono_string_length (name);
653 this_obj->name = NULL;
655 mono_monitor_exit (this_obj->synch_lock);
659 ves_icall_System_Threading_Thread_GetCachedCurrentCulture (MonoThread *this)
665 /* No need to lock here */
666 if (this->culture_info) {
667 domain = mono_domain_get ();
668 for (i = 0; i < NUM_CACHED_CULTURES; ++i) {
669 res = this->culture_info [i];
670 if (res && res->vtable->domain == domain)
679 ves_icall_System_Threading_Thread_GetSerializedCurrentCulture (MonoThread *this)
683 mono_monitor_enter (this->synch_lock);
684 if (this->serialized_culture_info) {
685 res = mono_array_new (mono_domain_get (), mono_defaults.byte_class, this->serialized_culture_info_len);
686 memcpy (mono_array_addr (res, guint8, 0), this->serialized_culture_info, this->serialized_culture_info_len);
690 mono_monitor_exit (this->synch_lock);
696 ves_icall_System_Threading_Thread_SetCachedCurrentCulture (MonoThread *this, MonoObject *culture)
699 MonoDomain *domain = mono_domain_get ();
701 mono_monitor_enter (this->synch_lock);
702 if (!this->culture_info) {
703 this->culture_info = mono_gc_alloc_fixed (sizeof (MonoObject*) * NUM_CACHED_CULTURES, NULL);
706 for (i = 0; i < NUM_CACHED_CULTURES; ++i) {
707 if (this->culture_info [i]) {
708 if (this->culture_info [i]->vtable->domain == domain)
716 if (i < NUM_CACHED_CULTURES)
717 this->culture_info [i] = culture;
718 mono_monitor_exit (this->synch_lock);
722 ves_icall_System_Threading_Thread_SetSerializedCurrentCulture (MonoThread *this, MonoArray *arr)
724 mono_monitor_enter (this->synch_lock);
725 if (this->serialized_culture_info)
726 g_free (this->serialized_culture_info);
727 this->serialized_culture_info = g_new0 (guint8, mono_array_length (arr));
728 this->serialized_culture_info_len = mono_array_length (arr);
729 memcpy (this->serialized_culture_info, mono_array_addr (arr, guint8, 0), mono_array_length (arr));
730 mono_monitor_exit (this->synch_lock);
735 ves_icall_System_Threading_Thread_GetCachedCurrentUICulture (MonoThread *this)
741 /* No need to lock here */
742 if (this->ui_culture_info) {
743 domain = mono_domain_get ();
744 for (i = 0; i < NUM_CACHED_CULTURES; ++i) {
745 res = this->ui_culture_info [i];
746 if (res && res->vtable->domain == domain)
755 ves_icall_System_Threading_Thread_GetSerializedCurrentUICulture (MonoThread *this)
759 mono_monitor_enter (this->synch_lock);
760 if (this->serialized_ui_culture_info) {
761 res = mono_array_new (mono_domain_get (), mono_defaults.byte_class, this->serialized_ui_culture_info_len);
762 memcpy (mono_array_addr (res, guint8, 0), this->serialized_ui_culture_info, this->serialized_ui_culture_info_len);
766 mono_monitor_exit (this->synch_lock);
772 ves_icall_System_Threading_Thread_SetCachedCurrentUICulture (MonoThread *this, MonoObject *culture)
775 MonoDomain *domain = mono_domain_get ();
777 mono_monitor_enter (this->synch_lock);
778 if (!this->ui_culture_info) {
779 this->ui_culture_info = mono_gc_alloc_fixed (sizeof (MonoObject*) * NUM_CACHED_CULTURES, NULL);
782 for (i = 0; i < NUM_CACHED_CULTURES; ++i) {
783 if (this->ui_culture_info [i]) {
784 if (this->ui_culture_info [i]->vtable->domain == domain)
792 if (i < NUM_CACHED_CULTURES)
793 this->ui_culture_info [i] = culture;
794 mono_monitor_exit (this->synch_lock);
798 ves_icall_System_Threading_Thread_SetSerializedCurrentUICulture (MonoThread *this, MonoArray *arr)
800 mono_monitor_enter (this->synch_lock);
801 if (this->serialized_ui_culture_info)
802 g_free (this->serialized_ui_culture_info);
803 this->serialized_ui_culture_info = g_new0 (guint8, mono_array_length (arr));
804 this->serialized_ui_culture_info_len = mono_array_length (arr);
805 memcpy (this->serialized_ui_culture_info, mono_array_addr (arr, guint8, 0), mono_array_length (arr));
806 mono_monitor_exit (this->synch_lock);
809 /* the jit may read the compiled code of this function */
811 mono_thread_current (void)
813 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": returning %p", GET_CURRENT_OBJECT ()));
814 return GET_CURRENT_OBJECT ();
817 gboolean ves_icall_System_Threading_Thread_Join_internal(MonoThread *this,
818 int ms, HANDLE thread)
824 mono_monitor_enter (this->synch_lock);
826 if ((this->state & ThreadState_Unstarted) != 0) {
827 mono_monitor_exit (this->synch_lock);
828 mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started."));
832 this->state |= ThreadState_WaitSleepJoin;
833 mono_monitor_exit (this->synch_lock);
838 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": joining thread handle %p, %d ms",
841 ret=WaitForSingleObjectEx (thread, ms, TRUE);
843 mono_monitor_enter (this->synch_lock);
844 this->state &= ~ThreadState_WaitSleepJoin;
845 mono_monitor_exit (this->synch_lock);
847 if(ret==WAIT_OBJECT_0) {
848 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": join successful"));
853 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": join failed"));
858 /* FIXME: exitContext isnt documented */
859 gboolean ves_icall_System_Threading_WaitHandle_WaitAll_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext)
865 MonoObject *waitHandle;
867 MonoThread *thread = mono_thread_current ();
871 numhandles = mono_array_length(mono_handles);
872 handles = g_new0(HANDLE, numhandles);
874 if (wait_handle_os_handle_field == 0) {
875 /* Get the field os_handle which will contain the actual handle */
876 klass = mono_class_from_name(mono_defaults.corlib, "System.Threading", "WaitHandle");
877 wait_handle_os_handle_field = mono_class_get_field_from_name(klass, "os_handle");
880 for(i = 0; i < numhandles; i++) {
881 waitHandle = mono_array_get(mono_handles, MonoObject*, i);
882 mono_field_get_value(waitHandle, wait_handle_os_handle_field, &handles[i]);
889 mono_monitor_enter (thread->synch_lock);
890 thread->state |= ThreadState_WaitSleepJoin;
891 mono_monitor_exit (thread->synch_lock);
893 ret=WaitForMultipleObjectsEx(numhandles, handles, TRUE, ms, TRUE);
895 mono_monitor_enter (thread->synch_lock);
896 thread->state &= ~ThreadState_WaitSleepJoin;
897 mono_monitor_exit (thread->synch_lock);
901 if(ret==WAIT_FAILED) {
902 THREAD_WAIT_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%"G_GSIZE_FORMAT") Wait failed", GetCurrentThreadId ()));
904 } else if(ret==WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION) {
905 /* Do we want to try again if we get
906 * WAIT_IO_COMPLETION? The documentation for
907 * WaitHandle doesn't give any clues. (We'd have to
908 * fiddle with the timeout if we retry.)
910 THREAD_WAIT_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%"G_GSIZE_FORMAT") Wait timed out", GetCurrentThreadId ()));
917 /* FIXME: exitContext isnt documented */
918 gint32 ves_icall_System_Threading_WaitHandle_WaitAny_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext)
924 MonoObject *waitHandle;
926 MonoThread *thread = mono_thread_current ();
930 numhandles = mono_array_length(mono_handles);
931 handles = g_new0(HANDLE, numhandles);
933 if (wait_handle_os_handle_field == 0) {
934 /* Get the field os_handle which will contain the actual handle */
935 klass = mono_class_from_name(mono_defaults.corlib, "System.Threading", "WaitHandle");
936 wait_handle_os_handle_field = mono_class_get_field_from_name(klass, "os_handle");
939 for(i = 0; i < numhandles; i++) {
940 waitHandle = mono_array_get(mono_handles, MonoObject*, i);
941 mono_field_get_value(waitHandle, wait_handle_os_handle_field, &handles[i]);
948 mono_monitor_enter (thread->synch_lock);
949 thread->state |= ThreadState_WaitSleepJoin;
950 mono_monitor_exit (thread->synch_lock);
952 ret=WaitForMultipleObjectsEx(numhandles, handles, FALSE, ms, TRUE);
954 mono_monitor_enter (thread->synch_lock);
955 thread->state &= ~ThreadState_WaitSleepJoin;
956 mono_monitor_exit (thread->synch_lock);
960 THREAD_WAIT_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%"G_GSIZE_FORMAT") returning %d", GetCurrentThreadId (), ret));
963 * These need to be here. See MSDN dos on WaitForMultipleObjects.
965 if (ret >= WAIT_OBJECT_0 && ret <= WAIT_OBJECT_0 + numhandles - 1) {
966 return ret - WAIT_OBJECT_0;
968 else if (ret >= WAIT_ABANDONED_0 && ret <= WAIT_ABANDONED_0 + numhandles - 1) {
969 return ret - WAIT_ABANDONED_0;
976 /* FIXME: exitContext isnt documented */
977 gboolean ves_icall_System_Threading_WaitHandle_WaitOne_internal(MonoObject *this, HANDLE handle, gint32 ms, gboolean exitContext)
980 MonoThread *thread = mono_thread_current ();
984 THREAD_WAIT_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%"G_GSIZE_FORMAT") waiting for %p, %d ms", GetCurrentThreadId (), handle, ms));
990 mono_monitor_enter (thread->synch_lock);
991 thread->state |= ThreadState_WaitSleepJoin;
992 mono_monitor_exit (thread->synch_lock);
994 ret=WaitForSingleObjectEx (handle, ms, TRUE);
996 mono_monitor_enter (thread->synch_lock);
997 thread->state &= ~ThreadState_WaitSleepJoin;
998 mono_monitor_exit (thread->synch_lock);
1000 if(ret==WAIT_FAILED) {
1001 THREAD_WAIT_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%"G_GSIZE_FORMAT") Wait failed", GetCurrentThreadId ()));
1003 } else if(ret==WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION) {
1004 /* Do we want to try again if we get
1005 * WAIT_IO_COMPLETION? The documentation for
1006 * WaitHandle doesn't give any clues. (We'd have to
1007 * fiddle with the timeout if we retry.)
1009 THREAD_WAIT_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%"G_GSIZE_FORMAT") Wait timed out", GetCurrentThreadId ()));
1016 HANDLE ves_icall_System_Threading_Mutex_CreateMutex_internal (MonoBoolean owned, MonoString *name, MonoBoolean *created)
1020 MONO_ARCH_SAVE_REGS;
1025 mutex = CreateMutex (NULL, owned, NULL);
1027 mutex = CreateMutex (NULL, owned, mono_string_chars (name));
1029 if (GetLastError () == ERROR_ALREADY_EXISTS) {
1037 void ves_icall_System_Threading_Mutex_ReleaseMutex_internal (HANDLE handle ) {
1038 MONO_ARCH_SAVE_REGS;
1040 ReleaseMutex(handle);
1043 HANDLE ves_icall_System_Threading_Events_CreateEvent_internal (MonoBoolean manual, MonoBoolean initial, MonoString *name) {
1044 MONO_ARCH_SAVE_REGS;
1046 return(CreateEvent (NULL, manual, initial,
1047 name==NULL?NULL:mono_string_chars (name)));
1050 gboolean ves_icall_System_Threading_Events_SetEvent_internal (HANDLE handle) {
1051 MONO_ARCH_SAVE_REGS;
1053 return (SetEvent(handle));
1056 gboolean ves_icall_System_Threading_Events_ResetEvent_internal (HANDLE handle) {
1057 MONO_ARCH_SAVE_REGS;
1059 return (ResetEvent(handle));
1063 ves_icall_System_Threading_Events_CloseEvent_internal (HANDLE handle) {
1064 MONO_ARCH_SAVE_REGS;
1066 CloseHandle (handle);
1069 gint32 ves_icall_System_Threading_Interlocked_Increment_Int (gint32 *location)
1071 MONO_ARCH_SAVE_REGS;
1073 return InterlockedIncrement (location);
1076 gint64 ves_icall_System_Threading_Interlocked_Increment_Long (gint64 *location)
1080 MONO_ARCH_SAVE_REGS;
1082 mono_interlocked_lock ();
1086 mono_interlocked_unlock ();
1092 gint32 ves_icall_System_Threading_Interlocked_Decrement_Int (gint32 *location)
1094 MONO_ARCH_SAVE_REGS;
1096 return InterlockedDecrement(location);
1099 gint64 ves_icall_System_Threading_Interlocked_Decrement_Long (gint64 * location)
1103 MONO_ARCH_SAVE_REGS;
1105 mono_interlocked_lock ();
1109 mono_interlocked_unlock ();
1114 gint32 ves_icall_System_Threading_Interlocked_Exchange_Int (gint32 *location, gint32 value)
1116 MONO_ARCH_SAVE_REGS;
1118 return InterlockedExchange(location, value);
1121 MonoObject * ves_icall_System_Threading_Interlocked_Exchange_Object (MonoObject **location, MonoObject *value)
1123 MONO_ARCH_SAVE_REGS;
1125 return (MonoObject *) InterlockedExchangePointer((gpointer *) location, value);
1128 gfloat ves_icall_System_Threading_Interlocked_Exchange_Single (gfloat *location, gfloat value)
1130 IntFloatUnion val, ret;
1132 MONO_ARCH_SAVE_REGS;
1135 ret.ival = InterlockedExchange((gint32 *) location, val.ival);
1141 ves_icall_System_Threading_Interlocked_Exchange_Long (gint64 *location, gint64 value)
1143 #if SIZEOF_VOID_P == 8
1144 return (gint64) InterlockedExchangePointer((gpointer *) location, (gpointer)value);
1149 * According to MSDN, this function is only atomic with regards to the
1150 * other Interlocked functions on 32 bit platforms.
1152 mono_interlocked_lock ();
1155 mono_interlocked_unlock ();
1162 ves_icall_System_Threading_Interlocked_Exchange_Double (gdouble *location, gdouble value)
1164 #if SIZEOF_VOID_P == 8
1165 LongDoubleUnion val, ret;
1168 ret.ival = (gint64)InterlockedExchangePointer((gpointer *) location, (gpointer)val.ival);
1175 * According to MSDN, this function is only atomic with regards to the
1176 * other Interlocked functions on 32 bit platforms.
1178 mono_interlocked_lock ();
1181 mono_interlocked_unlock ();
1187 gint32 ves_icall_System_Threading_Interlocked_CompareExchange_Int(gint32 *location, gint32 value, gint32 comparand)
1189 MONO_ARCH_SAVE_REGS;
1191 return InterlockedCompareExchange(location, value, comparand);
1194 MonoObject * ves_icall_System_Threading_Interlocked_CompareExchange_Object (MonoObject **location, MonoObject *value, MonoObject *comparand)
1196 MONO_ARCH_SAVE_REGS;
1198 return (MonoObject *) InterlockedCompareExchangePointer((gpointer *) location, value, comparand);
1201 gfloat ves_icall_System_Threading_Interlocked_CompareExchange_Single (gfloat *location, gfloat value, gfloat comparand)
1203 IntFloatUnion val, ret, cmp;
1205 MONO_ARCH_SAVE_REGS;
1208 cmp.fval = comparand;
1209 ret.ival = InterlockedCompareExchange((gint32 *) location, val.ival, cmp.ival);
1215 ves_icall_System_Threading_Interlocked_CompareExchange_Double (gdouble *location, gdouble value, gdouble comparand)
1217 #if SIZEOF_VOID_P == 8
1218 LongDoubleUnion val, comp, ret;
1221 comp.fval = comparand;
1222 ret.ival = (gint64)InterlockedCompareExchangePointer((gpointer *) location, (gpointer)val.ival, (gpointer)comp.ival);
1228 mono_interlocked_lock ();
1230 if (old == comparand)
1232 mono_interlocked_unlock ();
1239 ves_icall_System_Threading_Interlocked_CompareExchange_Long (gint64 *location, gint64 value, gint64 comparand)
1241 #if SIZEOF_VOID_P == 8
1242 return (gint64)InterlockedCompareExchangePointer((gpointer *) location, (gpointer)value, (gpointer)comparand);
1246 mono_interlocked_lock ();
1248 if (old == comparand)
1250 mono_interlocked_unlock ();
1257 ves_icall_System_Threading_Interlocked_CompareExchange_T (MonoObject **location, MonoObject *value, MonoObject *comparand)
1259 MONO_ARCH_SAVE_REGS;
1261 return InterlockedCompareExchangePointer ((gpointer *)location, value, comparand);
1265 ves_icall_System_Threading_Interlocked_Exchange_T (MonoObject **location, MonoObject *value)
1267 MONO_ARCH_SAVE_REGS;
1269 return InterlockedExchangePointer ((gpointer *)location, value);
1273 ves_icall_System_Threading_Interlocked_Add_Int (gint32 *location, gint32 value)
1275 #if SIZEOF_VOID_P == 8
1276 /* Should be implemented as a JIT intrinsic */
1277 mono_raise_exception (mono_get_exception_not_implemented (NULL));
1282 mono_interlocked_lock ();
1284 *location = orig + value;
1285 mono_interlocked_unlock ();
1292 ves_icall_System_Threading_Interlocked_Add_Long (gint64 *location, gint64 value)
1294 #if SIZEOF_VOID_P == 8
1295 /* Should be implemented as a JIT intrinsic */
1296 mono_raise_exception (mono_get_exception_not_implemented (NULL));
1301 mono_interlocked_lock ();
1303 *location = orig + value;
1304 mono_interlocked_unlock ();
1311 ves_icall_System_Threading_Interlocked_Read_Long (gint64 *location)
1313 #if SIZEOF_VOID_P == 8
1314 /* 64 bit reads are already atomic */
1319 mono_interlocked_lock ();
1321 mono_interlocked_unlock ();
1328 ves_icall_System_Threading_Thread_MemoryBarrier (void)
1330 /* Should be implemented as a JIT intrinsic */
1331 mono_raise_exception (mono_get_exception_not_implemented (NULL));
1335 ves_icall_System_Threading_Thread_ClrState (MonoThread* this, guint32 state)
1337 mono_monitor_enter (this->synch_lock);
1338 this->state &= ~state;
1339 if (state & ThreadState_Background) {
1340 /* If the thread changes the background mode, the main thread has to
1341 * be notified, since it has to rebuild the list of threads to
1344 SetEvent (background_change_event);
1346 mono_monitor_exit (this->synch_lock);
1350 ves_icall_System_Threading_Thread_SetState (MonoThread* this, guint32 state)
1352 mono_monitor_enter (this->synch_lock);
1353 this->state |= state;
1354 if (state & ThreadState_Background) {
1355 /* If the thread changes the background mode, the main thread has to
1356 * be notified, since it has to rebuild the list of threads to
1359 SetEvent (background_change_event);
1361 mono_monitor_exit (this->synch_lock);
1365 ves_icall_System_Threading_Thread_GetState (MonoThread* this)
1368 mono_monitor_enter (this->synch_lock);
1369 state = this->state;
1370 mono_monitor_exit (this->synch_lock);
1375 mono_thread_get_abort_signal (void)
1377 #if defined (__MINGW32__) || defined (_MSC_VER)
1383 static int abort_signum = -1;
1385 if (abort_signum != -1)
1386 return abort_signum;
1387 /* we try to avoid SIGRTMIN and any one that might have been set already, see bug #75387 */
1388 for (i = SIGRTMIN + 1; i < SIGRTMAX; ++i) {
1389 struct sigaction sinfo;
1390 sigaction (i, NULL, &sinfo);
1391 if (sinfo.sa_handler == SIG_DFL && (void*)sinfo.sa_sigaction == (void*)SIG_DFL) {
1396 /* fallback to the old way */
1399 #endif /*defined (__MINGW32__) || defined (_MSC_VER) */
1402 #if defined (__MINGW32__) || defined (_MSC_VER)
1403 static void CALLBACK interruption_request_apc (ULONG_PTR param)
1405 MonoException* exc = mono_thread_request_interruption (FALSE);
1406 if (exc) mono_raise_exception (exc);
1408 #endif /* defined (__MINGW32__) || defined (_MSC_VER) */
1411 * signal_thread_state_change
1413 * Tells the thread that his state has changed and it has to enter the new
1414 * state as soon as possible.
1416 static void signal_thread_state_change (MonoThread *thread)
1418 if (thread == mono_thread_current ()) {
1419 /* Do it synchronously */
1420 MonoException *exc = mono_thread_request_interruption (FALSE);
1422 mono_raise_exception (exc);
1425 #if defined (__MINGW32__) || defined (_MSC_VER)
1426 QueueUserAPC ((PAPCFUNC)interruption_request_apc, thread->handle, NULL);
1428 /* fixme: store the state somewhere */
1429 #ifdef PTHREAD_POINTER_ID
1430 pthread_kill ((gpointer)(gsize)(thread->tid), mono_thread_get_abort_signal ());
1432 pthread_kill (thread->tid, mono_thread_get_abort_signal ());
1434 #endif /* defined (__MINGW32__) || defined (__MSC_VER) */
1438 ves_icall_System_Threading_Thread_Abort (MonoThread *thread, MonoObject *state)
1440 MONO_ARCH_SAVE_REGS;
1442 mono_monitor_enter (thread->synch_lock);
1444 if ((thread->state & ThreadState_AbortRequested) != 0 ||
1445 (thread->state & ThreadState_StopRequested) != 0 ||
1446 (thread->state & ThreadState_Stopped) != 0)
1448 mono_monitor_exit (thread->synch_lock);
1452 if ((thread->state & ThreadState_Unstarted) != 0) {
1453 thread->state |= ThreadState_Aborted;
1454 mono_monitor_exit (thread->synch_lock);
1458 thread->state |= ThreadState_AbortRequested;
1459 thread->abort_state = state;
1460 thread->abort_exc = NULL;
1462 mono_monitor_exit (thread->synch_lock);
1464 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%"G_GSIZE_FORMAT") Abort requested for %p (%"G_GSIZE_FORMAT")", GetCurrentThreadId (), thread, (gsize)thread->tid));
1466 /* Make sure the thread is awake */
1467 mono_thread_resume (thread);
1469 signal_thread_state_change (thread);
1473 ves_icall_System_Threading_Thread_ResetAbort (void)
1475 MonoThread *thread = mono_thread_current ();
1477 MONO_ARCH_SAVE_REGS;
1479 mono_monitor_enter (thread->synch_lock);
1481 thread->state &= ~ThreadState_AbortRequested;
1483 if (!thread->abort_exc) {
1484 const char *msg = "Unable to reset abort because no abort was requested";
1485 mono_monitor_exit (thread->synch_lock);
1486 mono_raise_exception (mono_get_exception_thread_state (msg));
1488 thread->abort_exc = NULL;
1489 thread->abort_state = NULL;
1492 mono_monitor_exit (thread->synch_lock);
1496 mono_thread_suspend (MonoThread *thread)
1498 MONO_ARCH_SAVE_REGS;
1500 mono_monitor_enter (thread->synch_lock);
1502 if ((thread->state & ThreadState_Unstarted) != 0 ||
1503 (thread->state & ThreadState_Aborted) != 0 ||
1504 (thread->state & ThreadState_Stopped) != 0)
1506 mono_monitor_exit (thread->synch_lock);
1510 if ((thread->state & ThreadState_Suspended) != 0 ||
1511 (thread->state & ThreadState_SuspendRequested) != 0 ||
1512 (thread->state & ThreadState_StopRequested) != 0)
1514 mono_monitor_exit (thread->synch_lock);
1518 thread->state |= ThreadState_SuspendRequested;
1519 mono_monitor_exit (thread->synch_lock);
1521 signal_thread_state_change (thread);
1526 ves_icall_System_Threading_Thread_Suspend (MonoThread *thread)
1528 if (!mono_thread_suspend (thread))
1529 mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started, or is dead."));
1533 mono_thread_resume (MonoThread *thread)
1535 MONO_ARCH_SAVE_REGS;
1537 mono_monitor_enter (thread->synch_lock);
1539 if ((thread->state & ThreadState_SuspendRequested) != 0) {
1540 thread->state &= ~ThreadState_SuspendRequested;
1541 mono_monitor_exit (thread->synch_lock);
1545 if ((thread->state & ThreadState_Suspended) == 0 ||
1546 (thread->state & ThreadState_Unstarted) != 0 ||
1547 (thread->state & ThreadState_Aborted) != 0 ||
1548 (thread->state & ThreadState_Stopped) != 0)
1550 mono_monitor_exit (thread->synch_lock);
1554 thread->resume_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1556 /* Awake the thread */
1557 SetEvent (thread->suspend_event);
1559 mono_monitor_exit (thread->synch_lock);
1561 /* Wait for the thread to awake */
1562 WaitForSingleObject (thread->resume_event, INFINITE);
1563 CloseHandle (thread->resume_event);
1564 thread->resume_event = NULL;
1570 ves_icall_System_Threading_Thread_Resume (MonoThread *thread)
1572 if (!mono_thread_resume (thread))
1573 mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started, or is dead."));
1577 find_wrapper (MonoMethod *m, gint no, gint ilo, gboolean managed, gpointer data)
1582 if (m->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE ||
1583 m->wrapper_type == MONO_WRAPPER_XDOMAIN_INVOKE ||
1584 m->wrapper_type == MONO_WRAPPER_XDOMAIN_DISPATCH)
1586 *((gboolean*)data) = TRUE;
1593 is_running_protected_wrapper (void)
1595 gboolean found = FALSE;
1596 mono_stack_walk (find_wrapper, &found);
1600 void mono_thread_stop (MonoThread *thread)
1602 mono_monitor_enter (thread->synch_lock);
1604 if ((thread->state & ThreadState_StopRequested) != 0 ||
1605 (thread->state & ThreadState_Stopped) != 0)
1607 mono_monitor_exit (thread->synch_lock);
1611 /* Make sure the thread is awake */
1612 mono_thread_resume (thread);
1614 thread->state |= ThreadState_StopRequested;
1615 thread->state &= ~ThreadState_AbortRequested;
1617 mono_monitor_exit (thread->synch_lock);
1619 signal_thread_state_change (thread);
1623 ves_icall_System_Threading_Thread_VolatileRead1 (void *ptr)
1625 return *((volatile gint8 *) (ptr));
1629 ves_icall_System_Threading_Thread_VolatileRead2 (void *ptr)
1631 return *((volatile gint16 *) (ptr));
1635 ves_icall_System_Threading_Thread_VolatileRead4 (void *ptr)
1637 return *((volatile gint32 *) (ptr));
1641 ves_icall_System_Threading_Thread_VolatileRead8 (void *ptr)
1643 return *((volatile gint64 *) (ptr));
1647 ves_icall_System_Threading_Thread_VolatileReadIntPtr (void *ptr)
1649 return (void *) *((volatile void **) ptr);
1653 ves_icall_System_Threading_Thread_VolatileWrite1 (void *ptr, gint8 value)
1655 *((volatile gint8 *) ptr) = value;
1659 ves_icall_System_Threading_Thread_VolatileWrite2 (void *ptr, gint16 value)
1661 *((volatile gint16 *) ptr) = value;
1665 ves_icall_System_Threading_Thread_VolatileWrite4 (void *ptr, gint32 value)
1667 *((volatile gint32 *) ptr) = value;
1671 ves_icall_System_Threading_Thread_VolatileWrite8 (void *ptr, gint64 value)
1673 *((volatile gint64 *) ptr) = value;
1677 ves_icall_System_Threading_Thread_VolatileWriteIntPtr (void *ptr, void *value)
1679 *((volatile void **) ptr) = value;
1682 void mono_thread_init (MonoThreadStartCB start_cb,
1683 MonoThreadAttachCB attach_cb)
1685 InitializeCriticalSection(&threads_mutex);
1686 InitializeCriticalSection(&interlocked_mutex);
1687 InitializeCriticalSection(&contexts_mutex);
1688 background_change_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1690 mono_init_static_data_info (&thread_static_info);
1691 mono_init_static_data_info (&context_static_info);
1693 current_object_key=TlsAlloc();
1694 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": Allocated current_object_key %d",
1695 current_object_key));
1697 mono_thread_start_cb = start_cb;
1698 mono_thread_attach_cb = attach_cb;
1700 /* Get a pseudo handle to the current process. This is just a
1701 * kludge so that wapi can build a process handle if needed.
1702 * As a pseudo handle is returned, we don't need to clean
1705 GetCurrentProcess ();
1709 mono_threads_install_cleanup (MonoThreadCleanupFunc func)
1711 mono_thread_cleanup = func;
1714 void mono_install_thread_callbacks (MonoThreadCallbacks *callbacks)
1716 mono_thread_callbacks = callbacks;
1720 static void print_tids (gpointer key, gpointer value, gpointer user)
1722 /* GPOINTER_TO_UINT breaks horribly if sizeof(void *) >
1723 * sizeof(uint) and a cast to uint would overflow
1725 /* Older versions of glib don't have G_GSIZE_FORMAT, so just
1726 * print this as a pointer.
1728 g_message ("Waiting for: %p", key);
1733 HANDLE handles[MAXIMUM_WAIT_OBJECTS];
1734 MonoThread *threads[MAXIMUM_WAIT_OBJECTS];
1738 static void wait_for_tids (struct wait_data *wait, guint32 timeout)
1742 THREAD_DEBUG (g_message(G_GNUC_PRETTY_FUNCTION
1743 ": %d threads to wait for in this batch", wait->num));
1745 ret=WaitForMultipleObjectsEx(wait->num, wait->handles, TRUE, timeout, FALSE);
1747 if(ret==WAIT_FAILED) {
1748 /* See the comment in build_wait_tids() */
1749 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": Wait failed"));
1753 for(i=0; i<wait->num; i++)
1754 CloseHandle (wait->handles[i]);
1756 if (ret == WAIT_TIMEOUT)
1759 for(i=0; i<wait->num; i++) {
1760 gsize tid = wait->threads[i]->tid;
1762 if(mono_g_hash_table_lookup (threads, (gpointer)tid)!=NULL) {
1763 /* This thread must have been killed, because
1764 * it hasn't cleaned itself up. (It's just
1765 * possible that the thread exited before the
1766 * parent thread had a chance to store the
1767 * handle, and now there is another pointer to
1768 * the already-exited thread stored. In this
1769 * case, we'll just get two
1770 * mono_profiler_thread_end() calls for the
1774 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": cleaning up after thread %"G_GSIZE_FORMAT, tid));
1775 thread_cleanup (wait->threads[i]);
1780 static void wait_for_tids_or_state_change (struct wait_data *wait, guint32 timeout)
1782 guint32 i, ret, count;
1784 THREAD_DEBUG (g_message(G_GNUC_PRETTY_FUNCTION
1785 ": %d threads to wait for in this batch", wait->num));
1787 /* Add the thread state change event, so it wakes up if a thread changes
1788 * to background mode.
1791 if (count < MAXIMUM_WAIT_OBJECTS) {
1792 wait->handles [count] = background_change_event;
1796 ret=WaitForMultipleObjectsEx (count, wait->handles, FALSE, timeout, FALSE);
1798 if(ret==WAIT_FAILED) {
1799 /* See the comment in build_wait_tids() */
1800 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": Wait failed"));
1804 for(i=0; i<wait->num; i++)
1805 CloseHandle (wait->handles[i]);
1807 if (ret == WAIT_TIMEOUT)
1810 if (ret < wait->num) {
1811 gsize tid = wait->threads[ret]->tid;
1812 mono_threads_lock ();
1813 if (mono_g_hash_table_lookup (threads, (gpointer)tid)!=NULL) {
1814 /* See comment in wait_for_tids about thread cleanup */
1815 mono_threads_unlock ();
1816 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION
1817 ": cleaning up after thread %"G_GSIZE_FORMAT, tid));
1818 thread_cleanup (wait->threads [ret]);
1820 mono_threads_unlock ();
1824 static void build_wait_tids (gpointer key, gpointer value, gpointer user)
1826 struct wait_data *wait=(struct wait_data *)user;
1828 if(wait->num<MAXIMUM_WAIT_OBJECTS) {
1830 MonoThread *thread=(MonoThread *)value;
1832 /* Ignore background threads, we abort them later */
1833 mono_monitor_enter (thread->synch_lock);
1834 if (thread->state & ThreadState_Background) {
1835 mono_monitor_exit (thread->synch_lock);
1836 return; /* just leave, ignore */
1838 mono_monitor_exit (thread->synch_lock);
1840 if (mono_gc_is_finalizer_thread (thread))
1843 if (thread == mono_thread_current ())
1846 if (thread == mono_thread_get_main ())
1849 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
1853 wait->handles[wait->num]=handle;
1854 wait->threads[wait->num]=thread;
1857 /* Just ignore the rest, we can't do anything with
1864 remove_and_abort_threads (gpointer key, gpointer value, gpointer user)
1866 struct wait_data *wait=(struct wait_data *)user;
1867 gsize self = GetCurrentThreadId ();
1868 MonoThread *thread = (MonoThread *) value;
1871 if (wait->num >= MAXIMUM_WAIT_OBJECTS)
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 %"G_GSIZE_FORMAT" already aborting", (gsize)thread->tid));
1887 /* printf ("A: %d\n", wait->num); */
1888 wait->handles[wait->num]=thread->handle;
1889 wait->threads[wait->num]=thread;
1892 THREAD_DEBUG (g_print (G_GNUC_PRETTY_FUNCTION ": Aborting id: %"G_GSIZE_FORMAT"\n", (gsize)thread->tid));
1893 mono_thread_stop (thread);
1897 return (thread->tid != self && !mono_gc_is_finalizer_thread (thread));
1900 void mono_thread_manage (void)
1902 struct wait_data *wait=g_new0 (struct wait_data, 1);
1904 /* join each thread that's still running */
1905 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": Joining each running thread..."));
1907 mono_threads_lock ();
1909 THREAD_DEBUG (g_message(G_GNUC_PRETTY_FUNCTION ": No threads"));
1910 mono_threads_unlock ();
1913 mono_threads_unlock ();
1916 mono_threads_lock ();
1917 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION
1918 ":There are %d threads to join", mono_g_hash_table_size (threads));
1919 mono_g_hash_table_foreach (threads, print_tids, NULL));
1921 ResetEvent (background_change_event);
1923 mono_g_hash_table_foreach (threads, build_wait_tids, wait);
1924 mono_threads_unlock ();
1926 /* Something to wait for */
1927 wait_for_tids_or_state_change (wait, INFINITE);
1929 THREAD_DEBUG (g_message ("I have %d threads after waiting.", wait->num));
1930 } while(wait->num>0);
1932 mono_runtime_set_shutting_down ();
1934 THREAD_DEBUG (g_message ("threadpool cleanup"));
1935 mono_thread_pool_cleanup ();
1938 * Remove everything but the finalizer thread and self.
1939 * Also abort all the background threads
1942 mono_threads_lock ();
1945 mono_g_hash_table_foreach_remove (threads, remove_and_abort_threads, wait);
1947 mono_threads_unlock ();
1949 THREAD_DEBUG (g_message ("wait->num is now %d", wait->num));
1951 /* Something to wait for */
1952 wait_for_tids (wait, INFINITE);
1954 } while (wait->num > 0);
1956 #if !defined(PLATFORM_WIN32) && !defined(RUN_IN_SUBTHREAD)
1957 /* The main thread must abandon any held mutexes (particularly
1958 * important for named mutexes as they are shared across
1959 * processes, see bug 74680.) This will happen when the
1960 * thread exits, but if it's not running in a subthread it
1961 * won't exit in time.
1963 /* Using non-w32 API is a nasty kludge, but I couldn't find
1964 * anything in the documentation that would let me do this
1965 * here yet still be safe to call on windows.
1967 _wapi_thread_abandon_mutexes (GetCurrentThread ());
1971 * give the subthreads a chance to really quit (this is mainly needed
1972 * to get correct user and system times from getrusage/wait/time(1)).
1973 * This could be removed if we avoid pthread_detach() and use pthread_join().
1975 #ifndef PLATFORM_WIN32
1982 static void terminate_thread (gpointer key, gpointer value, gpointer user)
1984 MonoThread *thread=(MonoThread *)value;
1986 if(thread->tid != (gsize)user) {
1987 /*TerminateThread (thread->handle, -1);*/
1991 void mono_thread_abort_all_other_threads (void)
1993 gsize self = GetCurrentThreadId ();
1995 mono_threads_lock ();
1996 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ":There are %d threads to abort",
1997 mono_g_hash_table_size (threads));
1998 mono_g_hash_table_foreach (threads, print_tids, NULL));
2000 mono_g_hash_table_foreach (threads, terminate_thread, (gpointer)self);
2002 mono_threads_unlock ();
2006 collect_threads (gpointer key, gpointer value, gpointer user_data)
2008 MonoThread *thread = (MonoThread*)value;
2009 struct wait_data *wait = (struct wait_data*)user_data;
2012 if (wait->num<MAXIMUM_WAIT_OBJECTS) {
2013 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
2017 wait->handles [wait->num] = handle;
2018 wait->threads [wait->num] = thread;
2024 * mono_thread_suspend_all_other_threads:
2026 * Suspend all managed threads except the finalizer thread and this thread.
2028 void mono_thread_suspend_all_other_threads (void)
2030 struct wait_data *wait = g_new0 (struct wait_data, 1);
2032 gsize self = GetCurrentThreadId ();
2034 guint32 eventidx = 0;
2037 * Make a copy of the hashtable since we can't do anything with
2038 * threads while threads_mutex is held.
2040 mono_threads_lock ();
2041 mono_g_hash_table_foreach (threads, collect_threads, wait);
2042 mono_threads_unlock ();
2044 events = g_new0 (gpointer, wait->num);
2046 /* Get the suspended events that we'll be waiting for */
2047 for (i = 0; i < wait->num; ++i) {
2048 MonoThread *thread = wait->threads [i];
2050 if ((thread->tid == self) || mono_gc_is_finalizer_thread (thread)) {
2051 //CloseHandle (wait->handles [i]);
2052 wait->threads [i] = NULL; /* ignore this thread in next loop */
2056 mono_monitor_enter (thread->synch_lock);
2058 if ((thread->state & ThreadState_Suspended) != 0 ||
2059 (thread->state & ThreadState_SuspendRequested) != 0 ||
2060 (thread->state & ThreadState_StopRequested) != 0 ||
2061 (thread->state & ThreadState_Stopped) != 0) {
2062 mono_monitor_exit (thread->synch_lock);
2063 CloseHandle (wait->handles [i]);
2064 wait->threads [i] = NULL; /* ignore this thread in next loop */
2068 /* Convert abort requests into suspend requests */
2069 if ((thread->state & ThreadState_AbortRequested) != 0)
2070 thread->state &= ~ThreadState_AbortRequested;
2072 thread->state |= ThreadState_SuspendRequested;
2074 if (thread->suspended_event == NULL)
2075 thread->suspended_event = CreateEvent (NULL, TRUE, FALSE, NULL);
2077 events [eventidx++] = thread->suspended_event;
2078 mono_monitor_exit (thread->synch_lock);
2080 /* Signal the thread to suspend */
2081 signal_thread_state_change (thread);
2084 WaitForMultipleObjectsEx (eventidx, events, TRUE, INFINITE, FALSE);
2085 for (i = 0; i < wait->num; ++i) {
2086 MonoThread *thread = wait->threads [i];
2091 mono_monitor_enter (thread->synch_lock);
2092 CloseHandle (thread->suspended_event);
2093 thread->suspended_event = NULL;
2094 mono_monitor_exit (thread->synch_lock);
2102 * mono_thread_push_appdomain_ref:
2104 * Register that the current thread may have references to objects in domain
2105 * @domain on its stack. Each call to this function should be paired with a
2106 * call to pop_appdomain_ref.
2109 mono_thread_push_appdomain_ref (MonoDomain *domain)
2111 MonoThread *thread = mono_thread_current ();
2114 /* printf ("PUSH REF: %"G_GSIZE_FORMAT" -> %s.\n", (gsize)thread->tid, domain->friendly_name); */
2115 mono_threads_lock ();
2116 thread->appdomain_refs = g_slist_prepend (thread->appdomain_refs, domain);
2117 mono_threads_unlock ();
2122 mono_thread_pop_appdomain_ref (void)
2124 MonoThread *thread = mono_thread_current ();
2127 /* printf ("POP REF: %"G_GSIZE_FORMAT" -> %s.\n", (gsize)thread->tid, ((MonoDomain*)(thread->appdomain_refs->data))->friendly_name); */
2128 mono_threads_lock ();
2129 /* FIXME: How can the list be empty ? */
2130 if (thread->appdomain_refs)
2131 thread->appdomain_refs = g_slist_remove (thread->appdomain_refs, thread->appdomain_refs->data);
2132 mono_threads_unlock ();
2137 mono_thread_has_appdomain_ref (MonoThread *thread, MonoDomain *domain)
2140 mono_threads_lock ();
2141 res = g_slist_find (thread->appdomain_refs, domain) != NULL;
2142 mono_threads_unlock ();
2146 typedef struct abort_appdomain_data {
2147 struct wait_data wait;
2149 } abort_appdomain_data;
2152 abort_appdomain_thread (gpointer key, gpointer value, gpointer user_data)
2154 MonoThread *thread = (MonoThread*)value;
2155 abort_appdomain_data *data = (abort_appdomain_data*)user_data;
2156 MonoDomain *domain = data->domain;
2158 if (mono_thread_has_appdomain_ref (thread, domain)) {
2159 HANDLE handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
2163 /* printf ("ABORTING THREAD %p BECAUSE IT REFERENCES DOMAIN %s.\n", thread->tid, domain->friendly_name); */
2165 ves_icall_System_Threading_Thread_Abort (thread, NULL);
2167 if(data->wait.num<MAXIMUM_WAIT_OBJECTS) {
2168 data->wait.handles [data->wait.num] = handle;
2169 data->wait.threads [data->wait.num] = thread;
2172 /* Just ignore the rest, we can't do anything with
2180 * mono_threads_abort_appdomain_threads:
2182 * Abort threads which has references to the given appdomain.
2185 mono_threads_abort_appdomain_threads (MonoDomain *domain, int timeout)
2187 abort_appdomain_data user_data;
2190 /* printf ("ABORT BEGIN.\n"); */
2192 start_time = GetTickCount ();
2194 mono_threads_lock ();
2196 user_data.domain = domain;
2197 user_data.wait.num = 0;
2198 mono_g_hash_table_foreach (threads, abort_appdomain_thread, &user_data);
2199 mono_threads_unlock ();
2201 if (user_data.wait.num > 0)
2203 * We should wait for the threads either to abort, or to leave the
2204 * domain. We can't do the latter, so we wait with a timeout.
2206 wait_for_tids (&user_data.wait, 100);
2208 /* Update remaining time */
2209 timeout -= GetTickCount () - start_time;
2210 start_time = GetTickCount ();
2215 while (user_data.wait.num > 0);
2217 /* printf ("ABORT DONE.\n"); */
2223 clear_cached_culture (gpointer key, gpointer value, gpointer user_data)
2225 MonoThread *thread = (MonoThread*)value;
2226 MonoDomain *domain = (MonoDomain*)user_data;
2229 /* No locking needed here */
2231 if (thread->culture_info) {
2232 for (i = 0; i < NUM_CACHED_CULTURES; ++i) {
2233 if (thread->culture_info [i] && thread->culture_info [i]->vtable->domain == domain)
2234 thread->culture_info [i] = NULL;
2237 if (thread->ui_culture_info) {
2238 for (i = 0; i < NUM_CACHED_CULTURES; ++i) {
2239 if (thread->ui_culture_info [i] && thread->ui_culture_info [i]->vtable->domain == domain)
2240 thread->ui_culture_info [i] = NULL;
2246 * mono_threads_clear_cached_culture:
2248 * Clear the cached_current_culture from all threads if it is in the
2252 mono_threads_clear_cached_culture (MonoDomain *domain)
2254 mono_threads_lock ();
2255 mono_g_hash_table_foreach (threads, clear_cached_culture, domain);
2256 mono_threads_unlock ();
2260 * mono_thread_get_pending_exception:
2262 * Return an exception which needs to be raised when leaving a catch clause.
2263 * This is used for undeniable exception propagation.
2266 mono_thread_get_pending_exception (void)
2268 MonoThread *thread = mono_thread_current ();
2270 MONO_ARCH_SAVE_REGS;
2272 if (thread && thread->abort_exc && !is_running_protected_wrapper ()) {
2274 * FIXME: Clear the abort exception and return an AppDomainUnloaded
2275 * exception if the thread no longer references a dying appdomain.
2277 thread->abort_exc->trace_ips = NULL;
2278 thread->abort_exc->stack_trace = NULL;
2279 return thread->abort_exc;
2285 #define NUM_STATIC_DATA_IDX 8
2286 static const int static_data_size [NUM_STATIC_DATA_IDX] = {
2287 1024, 4096, 16384, 65536, 262144, 1048576, 4194304, 16777216
2292 * mono_alloc_static_data
2294 * Allocate memory blocks for storing threads or context static data
2297 mono_alloc_static_data (gpointer **static_data_ptr, guint32 offset)
2299 guint idx = (offset >> 24) - 1;
2302 gpointer* static_data = *static_data_ptr;
2304 static_data = mono_gc_alloc_fixed (static_data_size [0], NULL);
2305 *static_data_ptr = static_data;
2306 static_data [0] = static_data;
2309 for (i = 1; i <= idx; ++i) {
2310 if (static_data [i])
2312 static_data [i] = mono_gc_alloc_fixed (static_data_size [i], NULL);
2317 * mono_init_static_data_info
2319 * Initializes static data counters
2321 static void mono_init_static_data_info (StaticDataInfo *static_data)
2323 static_data->idx = 0;
2324 static_data->offset = 0;
2328 * mono_alloc_static_data_slot
2330 * Generates an offset for static data. static_data contains the counters
2331 * used to generate it.
2334 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align)
2338 if (!static_data->idx && !static_data->offset) {
2340 * we use the first chunk of the first allocation also as
2341 * an array for the rest of the data
2343 static_data->offset = sizeof (gpointer) * NUM_STATIC_DATA_IDX;
2345 static_data->offset += align - 1;
2346 static_data->offset &= ~(align - 1);
2347 if (static_data->offset + size >= static_data_size [static_data->idx]) {
2348 static_data->idx ++;
2349 g_assert (size <= static_data_size [static_data->idx]);
2351 * massive unloading and reloading of domains with thread-static
2352 * data may eventually exceed the allocated storage...
2353 * Need to check what the MS runtime does in that case.
2354 * Note that for each appdomain, we need to allocate a separate
2355 * thread data slot for security reasons. We could keep track
2356 * of the slots per-domain and when the domain is unloaded
2357 * out the slots on a sort of free list.
2359 g_assert (static_data->idx < NUM_STATIC_DATA_IDX);
2360 static_data->offset = 0;
2362 offset = static_data->offset | ((static_data->idx + 1) << 24);
2363 static_data->offset += size;
2368 * ensure thread static fields already allocated are valid for thread
2369 * This function is called when a thread is created or on thread attach.
2372 thread_adjust_static_data (MonoThread *thread)
2376 mono_threads_lock ();
2377 if (thread_static_info.offset || thread_static_info.idx > 0) {
2378 /* get the current allocated size */
2379 offset = thread_static_info.offset | ((thread_static_info.idx + 1) << 24);
2380 mono_alloc_static_data (&(thread->static_data), offset);
2382 mono_threads_unlock ();
2386 alloc_thread_static_data_helper (gpointer key, gpointer value, gpointer user)
2388 MonoThread *thread = value;
2389 guint32 offset = GPOINTER_TO_UINT (user);
2391 mono_alloc_static_data (&(thread->static_data), offset);
2395 * The offset for a special static variable is composed of three parts:
2396 * a bit that indicates the type of static data (0:thread, 1:context),
2397 * an index in the array of chunks of memory for the thread (thread->static_data)
2398 * and an offset in that chunk of mem. This allows allocating less memory in the
2403 mono_alloc_special_static_data (guint32 static_type, guint32 size, guint32 align)
2406 if (static_type == SPECIAL_STATIC_THREAD)
2408 mono_threads_lock ();
2409 offset = mono_alloc_static_data_slot (&thread_static_info, size, align);
2410 /* This can be called during startup */
2411 if (threads != NULL)
2412 mono_g_hash_table_foreach (threads, alloc_thread_static_data_helper, GUINT_TO_POINTER (offset));
2413 mono_threads_unlock ();
2417 g_assert (static_type == SPECIAL_STATIC_CONTEXT);
2418 mono_contexts_lock ();
2419 offset = mono_alloc_static_data_slot (&context_static_info, size, align);
2420 mono_contexts_unlock ();
2421 offset |= 0x80000000; /* Set the high bit to indicate context static data */
2427 mono_get_special_static_data (guint32 offset)
2429 /* The high bit means either thread (0) or static (1) data. */
2431 guint32 static_type = (offset & 0x80000000);
2434 offset &= 0x7fffffff;
2435 idx = (offset >> 24) - 1;
2437 if (static_type == 0)
2439 MonoThread *thread = mono_thread_current ();
2440 return ((char*) thread->static_data [idx]) + (offset & 0xffffff);
2444 /* Allocate static data block under demand, since we don't have a list
2447 MonoAppContext *context = mono_context_get ();
2448 if (!context->static_data || !context->static_data [idx]) {
2449 mono_contexts_lock ();
2450 mono_alloc_static_data (&(context->static_data), offset);
2451 mono_contexts_unlock ();
2453 return ((char*) context->static_data [idx]) + (offset & 0xffffff);
2457 static void gc_stop_world (gpointer key, gpointer value, gpointer user)
2459 MonoThread *thread=(MonoThread *)value;
2461 LIBGC_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": %"G_GSIZE_FORMAT" - %"G_GSIZE_FORMAT, (gsize)user, (gsize)thread->tid));
2463 if(thread->tid == (gsize)user)
2466 SuspendThread (thread->handle);
2469 void mono_gc_stop_world (void)
2471 gsize self = GetCurrentThreadId ();
2473 LIBGC_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": %"G_GSIZE_FORMAT" - %p", self, threads));
2475 mono_threads_lock ();
2477 if (threads != NULL)
2478 mono_g_hash_table_foreach (threads, gc_stop_world, (gpointer)self);
2480 mono_threads_unlock ();
2483 static void gc_start_world (gpointer key, gpointer value, gpointer user)
2485 MonoThread *thread=(MonoThread *)value;
2487 LIBGC_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": %"G_GSIZE_FORMAT" - %"G_GSIZE_FORMAT, (gsize)user, (gsize)thread->tid));
2489 if(thread->tid == (gsize)user)
2492 ResumeThread (thread->handle);
2495 void mono_gc_start_world (void)
2497 gsize self = GetCurrentThreadId ();
2499 LIBGC_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": %"G_GSIZE_FORMAT" - %p", self, threads));
2501 mono_threads_lock ();
2503 if (threads != NULL)
2504 mono_g_hash_table_foreach (threads, gc_start_world, (gpointer)self);
2506 mono_threads_unlock ();
2510 static CALLBACK void dummy_apc (ULONG_PTR param)
2514 static guint32 dummy_apc (gpointer param)
2521 * mono_thread_execute_interruption
2523 * Performs the operation that the requested thread state requires (abort,
2526 static MonoException* mono_thread_execute_interruption (MonoThread *thread)
2528 mono_monitor_enter (thread->synch_lock);
2530 if (thread->interruption_requested) {
2531 /* this will consume pending APC calls */
2532 WaitForSingleObjectEx (GetCurrentThread(), 0, TRUE);
2533 InterlockedDecrement (&thread_interruption_requested);
2534 thread->interruption_requested = FALSE;
2537 if ((thread->state & ThreadState_AbortRequested) != 0) {
2538 if (thread->abort_exc == NULL)
2539 thread->abort_exc = mono_get_exception_thread_abort ();
2540 mono_monitor_exit (thread->synch_lock);
2541 return thread->abort_exc;
2543 else if ((thread->state & ThreadState_SuspendRequested) != 0) {
2544 thread->state &= ~ThreadState_SuspendRequested;
2545 thread->state |= ThreadState_Suspended;
2546 thread->suspend_event = CreateEvent (NULL, TRUE, FALSE, NULL);
2547 if (thread->suspended_event)
2548 SetEvent (thread->suspended_event);
2549 mono_monitor_exit (thread->synch_lock);
2551 WaitForSingleObject (thread->suspend_event, INFINITE);
2553 mono_monitor_enter (thread->synch_lock);
2554 CloseHandle (thread->suspend_event);
2555 thread->suspend_event = NULL;
2556 thread->state &= ~ThreadState_Suspended;
2558 /* The thread that requested the resume will have replaced this event
2559 * and will be waiting for it
2561 SetEvent (thread->resume_event);
2562 mono_monitor_exit (thread->synch_lock);
2565 else if ((thread->state & ThreadState_StopRequested) != 0) {
2566 /* FIXME: do this through the JIT? */
2567 mono_monitor_exit (thread->synch_lock);
2568 mono_thread_exit ();
2572 mono_monitor_exit (thread->synch_lock);
2577 * mono_thread_request_interruption
2579 * A signal handler can call this method to request the interruption of a
2580 * thread. The result of the interruption will depend on the current state of
2581 * the thread. If the result is an exception that needs to be throw, it is
2582 * provided as return value.
2584 MonoException* mono_thread_request_interruption (gboolean running_managed)
2586 MonoThread *thread = mono_thread_current ();
2588 /* The thread may already be stopping */
2592 mono_monitor_enter (thread->synch_lock);
2594 if (thread->interruption_requested) {
2595 mono_monitor_exit (thread->synch_lock);
2599 if (!running_managed || is_running_protected_wrapper ()) {
2600 /* Can't stop while in unmanaged code. Increase the global interruption
2601 request count. When exiting the unmanaged method the count will be
2602 checked and the thread will be interrupted. */
2604 InterlockedIncrement (&thread_interruption_requested);
2605 thread->interruption_requested = TRUE;
2606 mono_monitor_exit (thread->synch_lock);
2608 /* this will awake the thread if it is in WaitForSingleObject
2610 QueueUserAPC ((PAPCFUNC)dummy_apc, thread->handle, NULL);
2614 mono_monitor_exit (thread->synch_lock);
2615 return mono_thread_execute_interruption (thread);
2619 gboolean mono_thread_interruption_requested ()
2621 if (thread_interruption_requested) {
2622 MonoThread *thread = mono_thread_current ();
2623 /* The thread may already be stopping */
2625 return (thread->interruption_requested);
2630 static void mono_thread_interruption_checkpoint_request (gboolean bypass_abort_protection)
2632 MonoThread *thread = mono_thread_current ();
2634 /* The thread may already be stopping */
2638 if (thread->interruption_requested && (bypass_abort_protection || !is_running_protected_wrapper ())) {
2639 MonoException* exc = mono_thread_execute_interruption (thread);
2640 if (exc) mono_raise_exception (exc);
2645 * Performs the interruption of the current thread, if one has been requested,
2646 * and the thread is not running a protected wrapper.
2648 void mono_thread_interruption_checkpoint ()
2650 mono_thread_interruption_checkpoint_request (FALSE);
2654 * Performs the interruption of the current thread, if one has been requested.
2656 void mono_thread_force_interruption_checkpoint ()
2658 mono_thread_interruption_checkpoint_request (TRUE);
2662 * mono_thread_interruption_request_flag:
2664 * Returns the address of a flag that will be non-zero if an interruption has
2665 * been requested for a thread. The thread to interrupt may not be the current
2666 * thread, so an additional call to mono_thread_interruption_requested() or
2667 * mono_thread_interruption_checkpoint() is allways needed if the flag is not
2670 gint32* mono_thread_interruption_request_flag ()
2672 return &thread_interruption_requested;
2675 #ifdef WITH_INCLUDED_LIBGC
2677 static void gc_push_all_stacks (gpointer key, gpointer value, gpointer user)
2679 MonoThread *thread=(MonoThread *)value;
2680 gsize *selfp = (gsize *)user, self = *selfp;
2682 LIBGC_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": %"G_GSIZE_FORMAT" - %"G_GSIZE_FORMAT" - %p", self, (gsize)thread->tid, thread->stack_ptr));
2684 if(thread->tid == self) {
2685 LIBGC_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": %p - %p", selfp, thread->stack_ptr));
2686 GC_push_all_stack (selfp, thread->stack_ptr);
2690 #ifdef PLATFORM_WIN32
2691 GC_win32_push_thread_stack (thread->handle, thread->stack_ptr);
2693 mono_wapi_push_thread_stack (thread->handle, thread->stack_ptr);
2697 void mono_gc_push_all_stacks (void)
2699 gsize self = GetCurrentThreadId ();
2701 LIBGC_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": %"G_GSIZE_FORMAT" - %p", self, threads));
2703 mono_threads_lock ();
2705 if (threads != NULL)
2706 mono_g_hash_table_foreach (threads, gc_push_all_stacks, &self);
2708 mono_threads_unlock ();
2711 #endif /* WITH_INCLUDED_LIBGC */