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_Semaphore_CreateSemaphore_internal (gint32 initialCount, gint32 maximumCount, MonoString *name, MonoBoolean *created)
1047 MONO_ARCH_SAVE_REGS;
1052 sem = CreateSemaphore (NULL, initialCount, maximumCount, NULL);
1054 sem = CreateSemaphore (NULL, initialCount, maximumCount,
1055 mono_string_chars (name));
1057 if (GetLastError () == ERROR_ALREADY_EXISTS) {
1065 gint32 ves_icall_System_Threading_Semaphore_ReleaseSemaphore_internal (HANDLE handle, gint32 releaseCount, MonoBoolean *fail)
1069 MONO_ARCH_SAVE_REGS;
1071 *fail = !ReleaseSemaphore (handle, releaseCount, &prevcount);
1076 HANDLE ves_icall_System_Threading_Events_CreateEvent_internal (MonoBoolean manual, MonoBoolean initial, MonoString *name) {
1077 MONO_ARCH_SAVE_REGS;
1079 return(CreateEvent (NULL, manual, initial,
1080 name==NULL?NULL:mono_string_chars (name)));
1083 gboolean ves_icall_System_Threading_Events_SetEvent_internal (HANDLE handle) {
1084 MONO_ARCH_SAVE_REGS;
1086 return (SetEvent(handle));
1089 gboolean ves_icall_System_Threading_Events_ResetEvent_internal (HANDLE handle) {
1090 MONO_ARCH_SAVE_REGS;
1092 return (ResetEvent(handle));
1096 ves_icall_System_Threading_Events_CloseEvent_internal (HANDLE handle) {
1097 MONO_ARCH_SAVE_REGS;
1099 CloseHandle (handle);
1102 gint32 ves_icall_System_Threading_Interlocked_Increment_Int (gint32 *location)
1104 MONO_ARCH_SAVE_REGS;
1106 return InterlockedIncrement (location);
1109 gint64 ves_icall_System_Threading_Interlocked_Increment_Long (gint64 *location)
1113 MONO_ARCH_SAVE_REGS;
1115 mono_interlocked_lock ();
1119 mono_interlocked_unlock ();
1125 gint32 ves_icall_System_Threading_Interlocked_Decrement_Int (gint32 *location)
1127 MONO_ARCH_SAVE_REGS;
1129 return InterlockedDecrement(location);
1132 gint64 ves_icall_System_Threading_Interlocked_Decrement_Long (gint64 * location)
1136 MONO_ARCH_SAVE_REGS;
1138 mono_interlocked_lock ();
1142 mono_interlocked_unlock ();
1147 gint32 ves_icall_System_Threading_Interlocked_Exchange_Int (gint32 *location, gint32 value)
1149 MONO_ARCH_SAVE_REGS;
1151 return InterlockedExchange(location, value);
1154 MonoObject * ves_icall_System_Threading_Interlocked_Exchange_Object (MonoObject **location, MonoObject *value)
1156 MONO_ARCH_SAVE_REGS;
1158 return (MonoObject *) InterlockedExchangePointer((gpointer *) location, value);
1161 gfloat ves_icall_System_Threading_Interlocked_Exchange_Single (gfloat *location, gfloat value)
1163 IntFloatUnion val, ret;
1165 MONO_ARCH_SAVE_REGS;
1168 ret.ival = InterlockedExchange((gint32 *) location, val.ival);
1174 ves_icall_System_Threading_Interlocked_Exchange_Long (gint64 *location, gint64 value)
1176 #if SIZEOF_VOID_P == 8
1177 return (gint64) InterlockedExchangePointer((gpointer *) location, (gpointer)value);
1182 * According to MSDN, this function is only atomic with regards to the
1183 * other Interlocked functions on 32 bit platforms.
1185 mono_interlocked_lock ();
1188 mono_interlocked_unlock ();
1195 ves_icall_System_Threading_Interlocked_Exchange_Double (gdouble *location, gdouble value)
1197 #if SIZEOF_VOID_P == 8
1198 LongDoubleUnion val, ret;
1201 ret.ival = (gint64)InterlockedExchangePointer((gpointer *) location, (gpointer)val.ival);
1208 * According to MSDN, this function is only atomic with regards to the
1209 * other Interlocked functions on 32 bit platforms.
1211 mono_interlocked_lock ();
1214 mono_interlocked_unlock ();
1220 gint32 ves_icall_System_Threading_Interlocked_CompareExchange_Int(gint32 *location, gint32 value, gint32 comparand)
1222 MONO_ARCH_SAVE_REGS;
1224 return InterlockedCompareExchange(location, value, comparand);
1227 MonoObject * ves_icall_System_Threading_Interlocked_CompareExchange_Object (MonoObject **location, MonoObject *value, MonoObject *comparand)
1229 MONO_ARCH_SAVE_REGS;
1231 return (MonoObject *) InterlockedCompareExchangePointer((gpointer *) location, value, comparand);
1234 gfloat ves_icall_System_Threading_Interlocked_CompareExchange_Single (gfloat *location, gfloat value, gfloat comparand)
1236 IntFloatUnion val, ret, cmp;
1238 MONO_ARCH_SAVE_REGS;
1241 cmp.fval = comparand;
1242 ret.ival = InterlockedCompareExchange((gint32 *) location, val.ival, cmp.ival);
1248 ves_icall_System_Threading_Interlocked_CompareExchange_Double (gdouble *location, gdouble value, gdouble comparand)
1250 #if SIZEOF_VOID_P == 8
1251 LongDoubleUnion val, comp, ret;
1254 comp.fval = comparand;
1255 ret.ival = (gint64)InterlockedCompareExchangePointer((gpointer *) location, (gpointer)val.ival, (gpointer)comp.ival);
1261 mono_interlocked_lock ();
1263 if (old == comparand)
1265 mono_interlocked_unlock ();
1272 ves_icall_System_Threading_Interlocked_CompareExchange_Long (gint64 *location, gint64 value, gint64 comparand)
1274 #if SIZEOF_VOID_P == 8
1275 return (gint64)InterlockedCompareExchangePointer((gpointer *) location, (gpointer)value, (gpointer)comparand);
1279 mono_interlocked_lock ();
1281 if (old == comparand)
1283 mono_interlocked_unlock ();
1290 ves_icall_System_Threading_Interlocked_CompareExchange_T (MonoObject **location, MonoObject *value, MonoObject *comparand)
1292 MONO_ARCH_SAVE_REGS;
1294 return InterlockedCompareExchangePointer ((gpointer *)location, value, comparand);
1298 ves_icall_System_Threading_Interlocked_Exchange_T (MonoObject **location, MonoObject *value)
1300 MONO_ARCH_SAVE_REGS;
1302 return InterlockedExchangePointer ((gpointer *)location, value);
1306 ves_icall_System_Threading_Interlocked_Add_Int (gint32 *location, gint32 value)
1308 #if SIZEOF_VOID_P == 8
1309 /* Should be implemented as a JIT intrinsic */
1310 mono_raise_exception (mono_get_exception_not_implemented (NULL));
1315 mono_interlocked_lock ();
1317 *location = orig + value;
1318 mono_interlocked_unlock ();
1325 ves_icall_System_Threading_Interlocked_Add_Long (gint64 *location, gint64 value)
1327 #if SIZEOF_VOID_P == 8
1328 /* Should be implemented as a JIT intrinsic */
1329 mono_raise_exception (mono_get_exception_not_implemented (NULL));
1334 mono_interlocked_lock ();
1336 *location = orig + value;
1337 mono_interlocked_unlock ();
1344 ves_icall_System_Threading_Interlocked_Read_Long (gint64 *location)
1346 #if SIZEOF_VOID_P == 8
1347 /* 64 bit reads are already atomic */
1352 mono_interlocked_lock ();
1354 mono_interlocked_unlock ();
1361 ves_icall_System_Threading_Thread_MemoryBarrier (void)
1363 /* Should be implemented as a JIT intrinsic */
1364 mono_raise_exception (mono_get_exception_not_implemented (NULL));
1368 ves_icall_System_Threading_Thread_ClrState (MonoThread* this, guint32 state)
1370 mono_monitor_enter (this->synch_lock);
1371 this->state &= ~state;
1372 if (state & ThreadState_Background) {
1373 /* If the thread changes the background mode, the main thread has to
1374 * be notified, since it has to rebuild the list of threads to
1377 SetEvent (background_change_event);
1379 mono_monitor_exit (this->synch_lock);
1383 ves_icall_System_Threading_Thread_SetState (MonoThread* this, guint32 state)
1385 mono_monitor_enter (this->synch_lock);
1386 this->state |= state;
1387 if (state & ThreadState_Background) {
1388 /* If the thread changes the background mode, the main thread has to
1389 * be notified, since it has to rebuild the list of threads to
1392 SetEvent (background_change_event);
1394 mono_monitor_exit (this->synch_lock);
1398 ves_icall_System_Threading_Thread_GetState (MonoThread* this)
1401 mono_monitor_enter (this->synch_lock);
1402 state = this->state;
1403 mono_monitor_exit (this->synch_lock);
1408 mono_thread_get_abort_signal (void)
1410 #if defined (__MINGW32__) || defined (_MSC_VER)
1416 static int abort_signum = -1;
1418 if (abort_signum != -1)
1419 return abort_signum;
1420 /* we try to avoid SIGRTMIN and any one that might have been set already, see bug #75387 */
1421 for (i = SIGRTMIN + 1; i < SIGRTMAX; ++i) {
1422 struct sigaction sinfo;
1423 sigaction (i, NULL, &sinfo);
1424 if (sinfo.sa_handler == SIG_DFL && (void*)sinfo.sa_sigaction == (void*)SIG_DFL) {
1429 /* fallback to the old way */
1432 #endif /*defined (__MINGW32__) || defined (_MSC_VER) */
1435 #if defined (__MINGW32__) || defined (_MSC_VER)
1436 static void CALLBACK interruption_request_apc (ULONG_PTR param)
1438 MonoException* exc = mono_thread_request_interruption (FALSE);
1439 if (exc) mono_raise_exception (exc);
1441 #endif /* defined (__MINGW32__) || defined (_MSC_VER) */
1444 * signal_thread_state_change
1446 * Tells the thread that his state has changed and it has to enter the new
1447 * state as soon as possible.
1449 static void signal_thread_state_change (MonoThread *thread)
1451 if (thread == mono_thread_current ()) {
1452 /* Do it synchronously */
1453 MonoException *exc = mono_thread_request_interruption (FALSE);
1455 mono_raise_exception (exc);
1458 #if defined (__MINGW32__) || defined (_MSC_VER)
1459 QueueUserAPC ((PAPCFUNC)interruption_request_apc, thread->handle, NULL);
1461 /* fixme: store the state somewhere */
1462 #ifdef PTHREAD_POINTER_ID
1463 pthread_kill ((gpointer)(gsize)(thread->tid), mono_thread_get_abort_signal ());
1465 pthread_kill (thread->tid, mono_thread_get_abort_signal ());
1467 #endif /* defined (__MINGW32__) || defined (__MSC_VER) */
1471 ves_icall_System_Threading_Thread_Abort (MonoThread *thread, MonoObject *state)
1473 MONO_ARCH_SAVE_REGS;
1475 mono_monitor_enter (thread->synch_lock);
1477 if ((thread->state & ThreadState_AbortRequested) != 0 ||
1478 (thread->state & ThreadState_StopRequested) != 0 ||
1479 (thread->state & ThreadState_Stopped) != 0)
1481 mono_monitor_exit (thread->synch_lock);
1485 if ((thread->state & ThreadState_Unstarted) != 0) {
1486 thread->state |= ThreadState_Aborted;
1487 mono_monitor_exit (thread->synch_lock);
1491 thread->state |= ThreadState_AbortRequested;
1492 thread->abort_state = state;
1493 thread->abort_exc = NULL;
1495 mono_monitor_exit (thread->synch_lock);
1497 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%"G_GSIZE_FORMAT") Abort requested for %p (%"G_GSIZE_FORMAT")", GetCurrentThreadId (), thread, (gsize)thread->tid));
1499 /* Make sure the thread is awake */
1500 mono_thread_resume (thread);
1502 signal_thread_state_change (thread);
1506 ves_icall_System_Threading_Thread_ResetAbort (void)
1508 MonoThread *thread = mono_thread_current ();
1510 MONO_ARCH_SAVE_REGS;
1512 mono_monitor_enter (thread->synch_lock);
1514 thread->state &= ~ThreadState_AbortRequested;
1516 if (!thread->abort_exc) {
1517 const char *msg = "Unable to reset abort because no abort was requested";
1518 mono_monitor_exit (thread->synch_lock);
1519 mono_raise_exception (mono_get_exception_thread_state (msg));
1521 thread->abort_exc = NULL;
1522 thread->abort_state = NULL;
1525 mono_monitor_exit (thread->synch_lock);
1529 mono_thread_suspend (MonoThread *thread)
1531 MONO_ARCH_SAVE_REGS;
1533 mono_monitor_enter (thread->synch_lock);
1535 if ((thread->state & ThreadState_Unstarted) != 0 ||
1536 (thread->state & ThreadState_Aborted) != 0 ||
1537 (thread->state & ThreadState_Stopped) != 0)
1539 mono_monitor_exit (thread->synch_lock);
1543 if ((thread->state & ThreadState_Suspended) != 0 ||
1544 (thread->state & ThreadState_SuspendRequested) != 0 ||
1545 (thread->state & ThreadState_StopRequested) != 0)
1547 mono_monitor_exit (thread->synch_lock);
1551 thread->state |= ThreadState_SuspendRequested;
1552 mono_monitor_exit (thread->synch_lock);
1554 signal_thread_state_change (thread);
1559 ves_icall_System_Threading_Thread_Suspend (MonoThread *thread)
1561 if (!mono_thread_suspend (thread))
1562 mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started, or is dead."));
1566 mono_thread_resume (MonoThread *thread)
1568 MONO_ARCH_SAVE_REGS;
1570 mono_monitor_enter (thread->synch_lock);
1572 if ((thread->state & ThreadState_SuspendRequested) != 0) {
1573 thread->state &= ~ThreadState_SuspendRequested;
1574 mono_monitor_exit (thread->synch_lock);
1578 if ((thread->state & ThreadState_Suspended) == 0 ||
1579 (thread->state & ThreadState_Unstarted) != 0 ||
1580 (thread->state & ThreadState_Aborted) != 0 ||
1581 (thread->state & ThreadState_Stopped) != 0)
1583 mono_monitor_exit (thread->synch_lock);
1587 thread->resume_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1589 /* Awake the thread */
1590 SetEvent (thread->suspend_event);
1592 mono_monitor_exit (thread->synch_lock);
1594 /* Wait for the thread to awake */
1595 WaitForSingleObject (thread->resume_event, INFINITE);
1596 CloseHandle (thread->resume_event);
1597 thread->resume_event = NULL;
1603 ves_icall_System_Threading_Thread_Resume (MonoThread *thread)
1605 if (!mono_thread_resume (thread))
1606 mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started, or is dead."));
1610 find_wrapper (MonoMethod *m, gint no, gint ilo, gboolean managed, gpointer data)
1615 if (m->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE ||
1616 m->wrapper_type == MONO_WRAPPER_XDOMAIN_INVOKE ||
1617 m->wrapper_type == MONO_WRAPPER_XDOMAIN_DISPATCH)
1619 *((gboolean*)data) = TRUE;
1626 is_running_protected_wrapper (void)
1628 gboolean found = FALSE;
1629 mono_stack_walk (find_wrapper, &found);
1633 void mono_thread_stop (MonoThread *thread)
1635 mono_monitor_enter (thread->synch_lock);
1637 if ((thread->state & ThreadState_StopRequested) != 0 ||
1638 (thread->state & ThreadState_Stopped) != 0)
1640 mono_monitor_exit (thread->synch_lock);
1644 /* Make sure the thread is awake */
1645 mono_thread_resume (thread);
1647 thread->state |= ThreadState_StopRequested;
1648 thread->state &= ~ThreadState_AbortRequested;
1650 mono_monitor_exit (thread->synch_lock);
1652 signal_thread_state_change (thread);
1656 ves_icall_System_Threading_Thread_VolatileRead1 (void *ptr)
1658 return *((volatile gint8 *) (ptr));
1662 ves_icall_System_Threading_Thread_VolatileRead2 (void *ptr)
1664 return *((volatile gint16 *) (ptr));
1668 ves_icall_System_Threading_Thread_VolatileRead4 (void *ptr)
1670 return *((volatile gint32 *) (ptr));
1674 ves_icall_System_Threading_Thread_VolatileRead8 (void *ptr)
1676 return *((volatile gint64 *) (ptr));
1680 ves_icall_System_Threading_Thread_VolatileReadIntPtr (void *ptr)
1682 return (void *) *((volatile void **) ptr);
1686 ves_icall_System_Threading_Thread_VolatileWrite1 (void *ptr, gint8 value)
1688 *((volatile gint8 *) ptr) = value;
1692 ves_icall_System_Threading_Thread_VolatileWrite2 (void *ptr, gint16 value)
1694 *((volatile gint16 *) ptr) = value;
1698 ves_icall_System_Threading_Thread_VolatileWrite4 (void *ptr, gint32 value)
1700 *((volatile gint32 *) ptr) = value;
1704 ves_icall_System_Threading_Thread_VolatileWrite8 (void *ptr, gint64 value)
1706 *((volatile gint64 *) ptr) = value;
1710 ves_icall_System_Threading_Thread_VolatileWriteIntPtr (void *ptr, void *value)
1712 *((volatile void **) ptr) = value;
1715 void mono_thread_init (MonoThreadStartCB start_cb,
1716 MonoThreadAttachCB attach_cb)
1718 InitializeCriticalSection(&threads_mutex);
1719 InitializeCriticalSection(&interlocked_mutex);
1720 InitializeCriticalSection(&contexts_mutex);
1721 background_change_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1723 mono_init_static_data_info (&thread_static_info);
1724 mono_init_static_data_info (&context_static_info);
1726 current_object_key=TlsAlloc();
1727 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": Allocated current_object_key %d",
1728 current_object_key));
1730 mono_thread_start_cb = start_cb;
1731 mono_thread_attach_cb = attach_cb;
1733 /* Get a pseudo handle to the current process. This is just a
1734 * kludge so that wapi can build a process handle if needed.
1735 * As a pseudo handle is returned, we don't need to clean
1738 GetCurrentProcess ();
1742 mono_threads_install_cleanup (MonoThreadCleanupFunc func)
1744 mono_thread_cleanup = func;
1747 void mono_install_thread_callbacks (MonoThreadCallbacks *callbacks)
1749 mono_thread_callbacks = callbacks;
1753 static void print_tids (gpointer key, gpointer value, gpointer user)
1755 /* GPOINTER_TO_UINT breaks horribly if sizeof(void *) >
1756 * sizeof(uint) and a cast to uint would overflow
1758 /* Older versions of glib don't have G_GSIZE_FORMAT, so just
1759 * print this as a pointer.
1761 g_message ("Waiting for: %p", key);
1766 HANDLE handles[MAXIMUM_WAIT_OBJECTS];
1767 MonoThread *threads[MAXIMUM_WAIT_OBJECTS];
1771 static void wait_for_tids (struct wait_data *wait, guint32 timeout)
1775 THREAD_DEBUG (g_message(G_GNUC_PRETTY_FUNCTION
1776 ": %d threads to wait for in this batch", wait->num));
1778 ret=WaitForMultipleObjectsEx(wait->num, wait->handles, TRUE, timeout, FALSE);
1780 if(ret==WAIT_FAILED) {
1781 /* See the comment in build_wait_tids() */
1782 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": Wait failed"));
1786 for(i=0; i<wait->num; i++)
1787 CloseHandle (wait->handles[i]);
1789 if (ret == WAIT_TIMEOUT)
1792 for(i=0; i<wait->num; i++) {
1793 gsize tid = wait->threads[i]->tid;
1795 if(mono_g_hash_table_lookup (threads, (gpointer)tid)!=NULL) {
1796 /* This thread must have been killed, because
1797 * it hasn't cleaned itself up. (It's just
1798 * possible that the thread exited before the
1799 * parent thread had a chance to store the
1800 * handle, and now there is another pointer to
1801 * the already-exited thread stored. In this
1802 * case, we'll just get two
1803 * mono_profiler_thread_end() calls for the
1807 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": cleaning up after thread %"G_GSIZE_FORMAT, tid));
1808 thread_cleanup (wait->threads[i]);
1813 static void wait_for_tids_or_state_change (struct wait_data *wait, guint32 timeout)
1815 guint32 i, ret, count;
1817 THREAD_DEBUG (g_message(G_GNUC_PRETTY_FUNCTION
1818 ": %d threads to wait for in this batch", wait->num));
1820 /* Add the thread state change event, so it wakes up if a thread changes
1821 * to background mode.
1824 if (count < MAXIMUM_WAIT_OBJECTS) {
1825 wait->handles [count] = background_change_event;
1829 ret=WaitForMultipleObjectsEx (count, wait->handles, FALSE, timeout, FALSE);
1831 if(ret==WAIT_FAILED) {
1832 /* See the comment in build_wait_tids() */
1833 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": Wait failed"));
1837 for(i=0; i<wait->num; i++)
1838 CloseHandle (wait->handles[i]);
1840 if (ret == WAIT_TIMEOUT)
1843 if (ret < wait->num) {
1844 gsize tid = wait->threads[ret]->tid;
1845 mono_threads_lock ();
1846 if (mono_g_hash_table_lookup (threads, (gpointer)tid)!=NULL) {
1847 /* See comment in wait_for_tids about thread cleanup */
1848 mono_threads_unlock ();
1849 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION
1850 ": cleaning up after thread %"G_GSIZE_FORMAT, tid));
1851 thread_cleanup (wait->threads [ret]);
1853 mono_threads_unlock ();
1857 static void build_wait_tids (gpointer key, gpointer value, gpointer user)
1859 struct wait_data *wait=(struct wait_data *)user;
1861 if(wait->num<MAXIMUM_WAIT_OBJECTS) {
1863 MonoThread *thread=(MonoThread *)value;
1865 /* Ignore background threads, we abort them later */
1866 mono_monitor_enter (thread->synch_lock);
1867 if (thread->state & ThreadState_Background) {
1868 mono_monitor_exit (thread->synch_lock);
1869 return; /* just leave, ignore */
1871 mono_monitor_exit (thread->synch_lock);
1873 if (mono_gc_is_finalizer_thread (thread))
1876 if (thread == mono_thread_current ())
1879 if (thread == mono_thread_get_main ())
1882 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
1886 wait->handles[wait->num]=handle;
1887 wait->threads[wait->num]=thread;
1890 /* Just ignore the rest, we can't do anything with
1897 remove_and_abort_threads (gpointer key, gpointer value, gpointer user)
1899 struct wait_data *wait=(struct wait_data *)user;
1900 gsize self = GetCurrentThreadId ();
1901 MonoThread *thread = (MonoThread *) value;
1904 if (wait->num >= MAXIMUM_WAIT_OBJECTS)
1907 /* The finalizer thread is not a background thread */
1908 if (thread->tid != self && (thread->state & ThreadState_Background) != 0) {
1910 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
1914 if(thread->state & ThreadState_AbortRequested ||
1915 thread->state & ThreadState_Aborted) {
1916 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": Thread id %"G_GSIZE_FORMAT" already aborting", (gsize)thread->tid));
1920 /* printf ("A: %d\n", wait->num); */
1921 wait->handles[wait->num]=thread->handle;
1922 wait->threads[wait->num]=thread;
1925 THREAD_DEBUG (g_print (G_GNUC_PRETTY_FUNCTION ": Aborting id: %"G_GSIZE_FORMAT"\n", (gsize)thread->tid));
1926 mono_thread_stop (thread);
1930 return (thread->tid != self && !mono_gc_is_finalizer_thread (thread));
1933 void mono_thread_manage (void)
1935 struct wait_data *wait=g_new0 (struct wait_data, 1);
1937 /* join each thread that's still running */
1938 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": Joining each running thread..."));
1940 mono_threads_lock ();
1942 THREAD_DEBUG (g_message(G_GNUC_PRETTY_FUNCTION ": No threads"));
1943 mono_threads_unlock ();
1946 mono_threads_unlock ();
1949 mono_threads_lock ();
1950 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION
1951 ":There are %d threads to join", mono_g_hash_table_size (threads));
1952 mono_g_hash_table_foreach (threads, print_tids, NULL));
1954 ResetEvent (background_change_event);
1956 mono_g_hash_table_foreach (threads, build_wait_tids, wait);
1957 mono_threads_unlock ();
1959 /* Something to wait for */
1960 wait_for_tids_or_state_change (wait, INFINITE);
1962 THREAD_DEBUG (g_message ("I have %d threads after waiting.", wait->num));
1963 } while(wait->num>0);
1965 mono_runtime_set_shutting_down ();
1967 THREAD_DEBUG (g_message ("threadpool cleanup"));
1968 mono_thread_pool_cleanup ();
1971 * Remove everything but the finalizer thread and self.
1972 * Also abort all the background threads
1975 mono_threads_lock ();
1978 mono_g_hash_table_foreach_remove (threads, remove_and_abort_threads, wait);
1980 mono_threads_unlock ();
1982 THREAD_DEBUG (g_message ("wait->num is now %d", wait->num));
1984 /* Something to wait for */
1985 wait_for_tids (wait, INFINITE);
1987 } while (wait->num > 0);
1989 #if !defined(PLATFORM_WIN32) && !defined(RUN_IN_SUBTHREAD)
1990 /* The main thread must abandon any held mutexes (particularly
1991 * important for named mutexes as they are shared across
1992 * processes, see bug 74680.) This will happen when the
1993 * thread exits, but if it's not running in a subthread it
1994 * won't exit in time.
1996 /* Using non-w32 API is a nasty kludge, but I couldn't find
1997 * anything in the documentation that would let me do this
1998 * here yet still be safe to call on windows.
2000 _wapi_thread_abandon_mutexes (GetCurrentThread ());
2004 * give the subthreads a chance to really quit (this is mainly needed
2005 * to get correct user and system times from getrusage/wait/time(1)).
2006 * This could be removed if we avoid pthread_detach() and use pthread_join().
2008 #ifndef PLATFORM_WIN32
2015 static void terminate_thread (gpointer key, gpointer value, gpointer user)
2017 MonoThread *thread=(MonoThread *)value;
2019 if(thread->tid != (gsize)user) {
2020 /*TerminateThread (thread->handle, -1);*/
2024 void mono_thread_abort_all_other_threads (void)
2026 gsize self = GetCurrentThreadId ();
2028 mono_threads_lock ();
2029 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ":There are %d threads to abort",
2030 mono_g_hash_table_size (threads));
2031 mono_g_hash_table_foreach (threads, print_tids, NULL));
2033 mono_g_hash_table_foreach (threads, terminate_thread, (gpointer)self);
2035 mono_threads_unlock ();
2039 collect_threads (gpointer key, gpointer value, gpointer user_data)
2041 MonoThread *thread = (MonoThread*)value;
2042 struct wait_data *wait = (struct wait_data*)user_data;
2045 if (wait->num<MAXIMUM_WAIT_OBJECTS) {
2046 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
2050 wait->handles [wait->num] = handle;
2051 wait->threads [wait->num] = thread;
2057 * mono_thread_suspend_all_other_threads:
2059 * Suspend all managed threads except the finalizer thread and this thread.
2061 void mono_thread_suspend_all_other_threads (void)
2063 struct wait_data *wait = g_new0 (struct wait_data, 1);
2065 gsize self = GetCurrentThreadId ();
2067 guint32 eventidx = 0;
2070 * Make a copy of the hashtable since we can't do anything with
2071 * threads while threads_mutex is held.
2073 mono_threads_lock ();
2074 mono_g_hash_table_foreach (threads, collect_threads, wait);
2075 mono_threads_unlock ();
2077 events = g_new0 (gpointer, wait->num);
2079 /* Get the suspended events that we'll be waiting for */
2080 for (i = 0; i < wait->num; ++i) {
2081 MonoThread *thread = wait->threads [i];
2083 if ((thread->tid == self) || mono_gc_is_finalizer_thread (thread)) {
2084 //CloseHandle (wait->handles [i]);
2085 wait->threads [i] = NULL; /* ignore this thread in next loop */
2089 mono_monitor_enter (thread->synch_lock);
2091 if ((thread->state & ThreadState_Suspended) != 0 ||
2092 (thread->state & ThreadState_SuspendRequested) != 0 ||
2093 (thread->state & ThreadState_StopRequested) != 0 ||
2094 (thread->state & ThreadState_Stopped) != 0) {
2095 mono_monitor_exit (thread->synch_lock);
2096 CloseHandle (wait->handles [i]);
2097 wait->threads [i] = NULL; /* ignore this thread in next loop */
2101 /* Convert abort requests into suspend requests */
2102 if ((thread->state & ThreadState_AbortRequested) != 0)
2103 thread->state &= ~ThreadState_AbortRequested;
2105 thread->state |= ThreadState_SuspendRequested;
2107 if (thread->suspended_event == NULL)
2108 thread->suspended_event = CreateEvent (NULL, TRUE, FALSE, NULL);
2110 events [eventidx++] = thread->suspended_event;
2111 mono_monitor_exit (thread->synch_lock);
2113 /* Signal the thread to suspend */
2114 signal_thread_state_change (thread);
2117 WaitForMultipleObjectsEx (eventidx, events, TRUE, INFINITE, FALSE);
2118 for (i = 0; i < wait->num; ++i) {
2119 MonoThread *thread = wait->threads [i];
2124 mono_monitor_enter (thread->synch_lock);
2125 CloseHandle (thread->suspended_event);
2126 thread->suspended_event = NULL;
2127 mono_monitor_exit (thread->synch_lock);
2135 * mono_thread_push_appdomain_ref:
2137 * Register that the current thread may have references to objects in domain
2138 * @domain on its stack. Each call to this function should be paired with a
2139 * call to pop_appdomain_ref.
2142 mono_thread_push_appdomain_ref (MonoDomain *domain)
2144 MonoThread *thread = mono_thread_current ();
2147 /* printf ("PUSH REF: %"G_GSIZE_FORMAT" -> %s.\n", (gsize)thread->tid, domain->friendly_name); */
2148 mono_threads_lock ();
2149 thread->appdomain_refs = g_slist_prepend (thread->appdomain_refs, domain);
2150 mono_threads_unlock ();
2155 mono_thread_pop_appdomain_ref (void)
2157 MonoThread *thread = mono_thread_current ();
2160 /* printf ("POP REF: %"G_GSIZE_FORMAT" -> %s.\n", (gsize)thread->tid, ((MonoDomain*)(thread->appdomain_refs->data))->friendly_name); */
2161 mono_threads_lock ();
2162 /* FIXME: How can the list be empty ? */
2163 if (thread->appdomain_refs)
2164 thread->appdomain_refs = g_slist_remove (thread->appdomain_refs, thread->appdomain_refs->data);
2165 mono_threads_unlock ();
2170 mono_thread_has_appdomain_ref (MonoThread *thread, MonoDomain *domain)
2173 mono_threads_lock ();
2174 res = g_slist_find (thread->appdomain_refs, domain) != NULL;
2175 mono_threads_unlock ();
2179 typedef struct abort_appdomain_data {
2180 struct wait_data wait;
2182 } abort_appdomain_data;
2185 abort_appdomain_thread (gpointer key, gpointer value, gpointer user_data)
2187 MonoThread *thread = (MonoThread*)value;
2188 abort_appdomain_data *data = (abort_appdomain_data*)user_data;
2189 MonoDomain *domain = data->domain;
2191 if (mono_thread_has_appdomain_ref (thread, domain)) {
2192 HANDLE handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
2196 /* printf ("ABORTING THREAD %p BECAUSE IT REFERENCES DOMAIN %s.\n", thread->tid, domain->friendly_name); */
2198 ves_icall_System_Threading_Thread_Abort (thread, NULL);
2200 if(data->wait.num<MAXIMUM_WAIT_OBJECTS) {
2201 data->wait.handles [data->wait.num] = handle;
2202 data->wait.threads [data->wait.num] = thread;
2205 /* Just ignore the rest, we can't do anything with
2213 * mono_threads_abort_appdomain_threads:
2215 * Abort threads which has references to the given appdomain.
2218 mono_threads_abort_appdomain_threads (MonoDomain *domain, int timeout)
2220 abort_appdomain_data user_data;
2223 /* printf ("ABORT BEGIN.\n"); */
2225 start_time = GetTickCount ();
2227 mono_threads_lock ();
2229 user_data.domain = domain;
2230 user_data.wait.num = 0;
2231 mono_g_hash_table_foreach (threads, abort_appdomain_thread, &user_data);
2232 mono_threads_unlock ();
2234 if (user_data.wait.num > 0)
2236 * We should wait for the threads either to abort, or to leave the
2237 * domain. We can't do the latter, so we wait with a timeout.
2239 wait_for_tids (&user_data.wait, 100);
2241 /* Update remaining time */
2242 timeout -= GetTickCount () - start_time;
2243 start_time = GetTickCount ();
2248 while (user_data.wait.num > 0);
2250 /* printf ("ABORT DONE.\n"); */
2256 clear_cached_culture (gpointer key, gpointer value, gpointer user_data)
2258 MonoThread *thread = (MonoThread*)value;
2259 MonoDomain *domain = (MonoDomain*)user_data;
2262 /* No locking needed here */
2264 if (thread->culture_info) {
2265 for (i = 0; i < NUM_CACHED_CULTURES; ++i) {
2266 if (thread->culture_info [i] && thread->culture_info [i]->vtable->domain == domain)
2267 thread->culture_info [i] = NULL;
2270 if (thread->ui_culture_info) {
2271 for (i = 0; i < NUM_CACHED_CULTURES; ++i) {
2272 if (thread->ui_culture_info [i] && thread->ui_culture_info [i]->vtable->domain == domain)
2273 thread->ui_culture_info [i] = NULL;
2279 * mono_threads_clear_cached_culture:
2281 * Clear the cached_current_culture from all threads if it is in the
2285 mono_threads_clear_cached_culture (MonoDomain *domain)
2287 mono_threads_lock ();
2288 mono_g_hash_table_foreach (threads, clear_cached_culture, domain);
2289 mono_threads_unlock ();
2293 * mono_thread_get_pending_exception:
2295 * Return an exception which needs to be raised when leaving a catch clause.
2296 * This is used for undeniable exception propagation.
2299 mono_thread_get_pending_exception (void)
2301 MonoThread *thread = mono_thread_current ();
2303 MONO_ARCH_SAVE_REGS;
2305 if (thread && thread->abort_exc && !is_running_protected_wrapper ()) {
2307 * FIXME: Clear the abort exception and return an AppDomainUnloaded
2308 * exception if the thread no longer references a dying appdomain.
2310 thread->abort_exc->trace_ips = NULL;
2311 thread->abort_exc->stack_trace = NULL;
2312 return thread->abort_exc;
2318 #define NUM_STATIC_DATA_IDX 8
2319 static const int static_data_size [NUM_STATIC_DATA_IDX] = {
2320 1024, 4096, 16384, 65536, 262144, 1048576, 4194304, 16777216
2325 * mono_alloc_static_data
2327 * Allocate memory blocks for storing threads or context static data
2330 mono_alloc_static_data (gpointer **static_data_ptr, guint32 offset)
2332 guint idx = (offset >> 24) - 1;
2335 gpointer* static_data = *static_data_ptr;
2337 static_data = mono_gc_alloc_fixed (static_data_size [0], NULL);
2338 *static_data_ptr = static_data;
2339 static_data [0] = static_data;
2342 for (i = 1; i <= idx; ++i) {
2343 if (static_data [i])
2345 static_data [i] = mono_gc_alloc_fixed (static_data_size [i], NULL);
2350 * mono_init_static_data_info
2352 * Initializes static data counters
2354 static void mono_init_static_data_info (StaticDataInfo *static_data)
2356 static_data->idx = 0;
2357 static_data->offset = 0;
2361 * mono_alloc_static_data_slot
2363 * Generates an offset for static data. static_data contains the counters
2364 * used to generate it.
2367 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align)
2371 if (!static_data->idx && !static_data->offset) {
2373 * we use the first chunk of the first allocation also as
2374 * an array for the rest of the data
2376 static_data->offset = sizeof (gpointer) * NUM_STATIC_DATA_IDX;
2378 static_data->offset += align - 1;
2379 static_data->offset &= ~(align - 1);
2380 if (static_data->offset + size >= static_data_size [static_data->idx]) {
2381 static_data->idx ++;
2382 g_assert (size <= static_data_size [static_data->idx]);
2384 * massive unloading and reloading of domains with thread-static
2385 * data may eventually exceed the allocated storage...
2386 * Need to check what the MS runtime does in that case.
2387 * Note that for each appdomain, we need to allocate a separate
2388 * thread data slot for security reasons. We could keep track
2389 * of the slots per-domain and when the domain is unloaded
2390 * out the slots on a sort of free list.
2392 g_assert (static_data->idx < NUM_STATIC_DATA_IDX);
2393 static_data->offset = 0;
2395 offset = static_data->offset | ((static_data->idx + 1) << 24);
2396 static_data->offset += size;
2401 * ensure thread static fields already allocated are valid for thread
2402 * This function is called when a thread is created or on thread attach.
2405 thread_adjust_static_data (MonoThread *thread)
2409 mono_threads_lock ();
2410 if (thread_static_info.offset || thread_static_info.idx > 0) {
2411 /* get the current allocated size */
2412 offset = thread_static_info.offset | ((thread_static_info.idx + 1) << 24);
2413 mono_alloc_static_data (&(thread->static_data), offset);
2415 mono_threads_unlock ();
2419 alloc_thread_static_data_helper (gpointer key, gpointer value, gpointer user)
2421 MonoThread *thread = value;
2422 guint32 offset = GPOINTER_TO_UINT (user);
2424 mono_alloc_static_data (&(thread->static_data), offset);
2428 * The offset for a special static variable is composed of three parts:
2429 * a bit that indicates the type of static data (0:thread, 1:context),
2430 * an index in the array of chunks of memory for the thread (thread->static_data)
2431 * and an offset in that chunk of mem. This allows allocating less memory in the
2436 mono_alloc_special_static_data (guint32 static_type, guint32 size, guint32 align)
2439 if (static_type == SPECIAL_STATIC_THREAD)
2441 mono_threads_lock ();
2442 offset = mono_alloc_static_data_slot (&thread_static_info, size, align);
2443 /* This can be called during startup */
2444 if (threads != NULL)
2445 mono_g_hash_table_foreach (threads, alloc_thread_static_data_helper, GUINT_TO_POINTER (offset));
2446 mono_threads_unlock ();
2450 g_assert (static_type == SPECIAL_STATIC_CONTEXT);
2451 mono_contexts_lock ();
2452 offset = mono_alloc_static_data_slot (&context_static_info, size, align);
2453 mono_contexts_unlock ();
2454 offset |= 0x80000000; /* Set the high bit to indicate context static data */
2460 mono_get_special_static_data (guint32 offset)
2462 /* The high bit means either thread (0) or static (1) data. */
2464 guint32 static_type = (offset & 0x80000000);
2467 offset &= 0x7fffffff;
2468 idx = (offset >> 24) - 1;
2470 if (static_type == 0)
2472 MonoThread *thread = mono_thread_current ();
2473 return ((char*) thread->static_data [idx]) + (offset & 0xffffff);
2477 /* Allocate static data block under demand, since we don't have a list
2480 MonoAppContext *context = mono_context_get ();
2481 if (!context->static_data || !context->static_data [idx]) {
2482 mono_contexts_lock ();
2483 mono_alloc_static_data (&(context->static_data), offset);
2484 mono_contexts_unlock ();
2486 return ((char*) context->static_data [idx]) + (offset & 0xffffff);
2490 static void gc_stop_world (gpointer key, gpointer value, gpointer user)
2492 MonoThread *thread=(MonoThread *)value;
2494 LIBGC_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": %"G_GSIZE_FORMAT" - %"G_GSIZE_FORMAT, (gsize)user, (gsize)thread->tid));
2496 if(thread->tid == (gsize)user)
2499 SuspendThread (thread->handle);
2502 void mono_gc_stop_world (void)
2504 gsize self = GetCurrentThreadId ();
2506 LIBGC_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": %"G_GSIZE_FORMAT" - %p", self, threads));
2508 mono_threads_lock ();
2510 if (threads != NULL)
2511 mono_g_hash_table_foreach (threads, gc_stop_world, (gpointer)self);
2513 mono_threads_unlock ();
2516 static void gc_start_world (gpointer key, gpointer value, gpointer user)
2518 MonoThread *thread=(MonoThread *)value;
2520 LIBGC_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": %"G_GSIZE_FORMAT" - %"G_GSIZE_FORMAT, (gsize)user, (gsize)thread->tid));
2522 if(thread->tid == (gsize)user)
2525 ResumeThread (thread->handle);
2528 void mono_gc_start_world (void)
2530 gsize self = GetCurrentThreadId ();
2532 LIBGC_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": %"G_GSIZE_FORMAT" - %p", self, threads));
2534 mono_threads_lock ();
2536 if (threads != NULL)
2537 mono_g_hash_table_foreach (threads, gc_start_world, (gpointer)self);
2539 mono_threads_unlock ();
2543 static CALLBACK void dummy_apc (ULONG_PTR param)
2547 static guint32 dummy_apc (gpointer param)
2554 * mono_thread_execute_interruption
2556 * Performs the operation that the requested thread state requires (abort,
2559 static MonoException* mono_thread_execute_interruption (MonoThread *thread)
2561 mono_monitor_enter (thread->synch_lock);
2563 if (thread->interruption_requested) {
2564 /* this will consume pending APC calls */
2565 WaitForSingleObjectEx (GetCurrentThread(), 0, TRUE);
2566 InterlockedDecrement (&thread_interruption_requested);
2567 thread->interruption_requested = FALSE;
2570 if ((thread->state & ThreadState_AbortRequested) != 0) {
2571 if (thread->abort_exc == NULL)
2572 thread->abort_exc = mono_get_exception_thread_abort ();
2573 mono_monitor_exit (thread->synch_lock);
2574 return thread->abort_exc;
2576 else if ((thread->state & ThreadState_SuspendRequested) != 0) {
2577 thread->state &= ~ThreadState_SuspendRequested;
2578 thread->state |= ThreadState_Suspended;
2579 thread->suspend_event = CreateEvent (NULL, TRUE, FALSE, NULL);
2580 if (thread->suspended_event)
2581 SetEvent (thread->suspended_event);
2582 mono_monitor_exit (thread->synch_lock);
2584 WaitForSingleObject (thread->suspend_event, INFINITE);
2586 mono_monitor_enter (thread->synch_lock);
2587 CloseHandle (thread->suspend_event);
2588 thread->suspend_event = NULL;
2589 thread->state &= ~ThreadState_Suspended;
2591 /* The thread that requested the resume will have replaced this event
2592 * and will be waiting for it
2594 SetEvent (thread->resume_event);
2595 mono_monitor_exit (thread->synch_lock);
2598 else if ((thread->state & ThreadState_StopRequested) != 0) {
2599 /* FIXME: do this through the JIT? */
2600 mono_monitor_exit (thread->synch_lock);
2601 mono_thread_exit ();
2605 mono_monitor_exit (thread->synch_lock);
2610 * mono_thread_request_interruption
2612 * A signal handler can call this method to request the interruption of a
2613 * thread. The result of the interruption will depend on the current state of
2614 * the thread. If the result is an exception that needs to be throw, it is
2615 * provided as return value.
2617 MonoException* mono_thread_request_interruption (gboolean running_managed)
2619 MonoThread *thread = mono_thread_current ();
2621 /* The thread may already be stopping */
2625 mono_monitor_enter (thread->synch_lock);
2627 if (thread->interruption_requested) {
2628 mono_monitor_exit (thread->synch_lock);
2632 if (!running_managed || is_running_protected_wrapper ()) {
2633 /* Can't stop while in unmanaged code. Increase the global interruption
2634 request count. When exiting the unmanaged method the count will be
2635 checked and the thread will be interrupted. */
2637 InterlockedIncrement (&thread_interruption_requested);
2638 thread->interruption_requested = TRUE;
2639 mono_monitor_exit (thread->synch_lock);
2641 /* this will awake the thread if it is in WaitForSingleObject
2643 QueueUserAPC ((PAPCFUNC)dummy_apc, thread->handle, NULL);
2647 mono_monitor_exit (thread->synch_lock);
2648 return mono_thread_execute_interruption (thread);
2652 gboolean mono_thread_interruption_requested ()
2654 if (thread_interruption_requested) {
2655 MonoThread *thread = mono_thread_current ();
2656 /* The thread may already be stopping */
2658 return (thread->interruption_requested);
2663 static void mono_thread_interruption_checkpoint_request (gboolean bypass_abort_protection)
2665 MonoThread *thread = mono_thread_current ();
2667 /* The thread may already be stopping */
2671 if (thread->interruption_requested && (bypass_abort_protection || !is_running_protected_wrapper ())) {
2672 MonoException* exc = mono_thread_execute_interruption (thread);
2673 if (exc) mono_raise_exception (exc);
2678 * Performs the interruption of the current thread, if one has been requested,
2679 * and the thread is not running a protected wrapper.
2681 void mono_thread_interruption_checkpoint ()
2683 mono_thread_interruption_checkpoint_request (FALSE);
2687 * Performs the interruption of the current thread, if one has been requested.
2689 void mono_thread_force_interruption_checkpoint ()
2691 mono_thread_interruption_checkpoint_request (TRUE);
2695 * mono_thread_interruption_request_flag:
2697 * Returns the address of a flag that will be non-zero if an interruption has
2698 * been requested for a thread. The thread to interrupt may not be the current
2699 * thread, so an additional call to mono_thread_interruption_requested() or
2700 * mono_thread_interruption_checkpoint() is allways needed if the flag is not
2703 gint32* mono_thread_interruption_request_flag ()
2705 return &thread_interruption_requested;
2708 #ifdef WITH_INCLUDED_LIBGC
2710 static void gc_push_all_stacks (gpointer key, gpointer value, gpointer user)
2712 MonoThread *thread=(MonoThread *)value;
2713 gsize *selfp = (gsize *)user, self = *selfp;
2715 LIBGC_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": %"G_GSIZE_FORMAT" - %"G_GSIZE_FORMAT" - %p", self, (gsize)thread->tid, thread->stack_ptr));
2717 if(thread->tid == self) {
2718 LIBGC_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": %p - %p", selfp, thread->stack_ptr));
2719 GC_push_all_stack (selfp, thread->stack_ptr);
2723 #ifdef PLATFORM_WIN32
2724 GC_win32_push_thread_stack (thread->handle, thread->stack_ptr);
2726 mono_wapi_push_thread_stack (thread->handle, thread->stack_ptr);
2730 void mono_gc_push_all_stacks (void)
2732 gsize self = GetCurrentThreadId ();
2734 LIBGC_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": %"G_GSIZE_FORMAT" - %p", self, threads));
2736 mono_threads_lock ();
2738 if (threads != NULL)
2739 mono_g_hash_table_foreach (threads, gc_push_all_stacks, &self);
2741 mono_threads_unlock ();
2744 #endif /* WITH_INCLUDED_LIBGC */