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>
35 #include <mono/os/gc_wrapper.h>
38 #undef THREAD_WAIT_DEBUG
42 guint32 (*func)(void *);
58 /* Number of cached culture objects in the MonoThread->culture_info array */
59 #define NUM_CACHED_CULTURES 4
62 * The "os_handle" field of the WaitHandle class.
64 static MonoClassField *wait_handle_os_handle_field = NULL;
66 /* Controls access to the 'threads' hash table */
67 static CRITICAL_SECTION threads_mutex;
69 /* Controls access to context static data */
70 static CRITICAL_SECTION contexts_mutex;
72 /* Holds current status of static data heap */
73 static StaticDataInfo thread_static_info;
74 static StaticDataInfo context_static_info;
76 /* The hash of existing threads (key is thread ID) that need joining
79 static MonoGHashTable *threads=NULL;
81 /* The TLS key that holds the MonoObject assigned to each thread */
82 static guint32 current_object_key = -1;
85 /* we need to use both the Tls* functions and __thread because
86 * the gc needs to see all the threads
88 static __thread MonoThread * tls_current_object;
89 #define SET_CURRENT_OBJECT(x) do { \
90 tls_current_object = x; \
91 TlsSetValue (current_object_key, x); \
93 #define GET_CURRENT_OBJECT() tls_current_object
95 #define SET_CURRENT_OBJECT(x) TlsSetValue (current_object_key, x);
96 #define GET_CURRENT_OBJECT() (MonoThread*) TlsGetValue (current_object_key);
99 /* function called at thread start */
100 static MonoThreadStartCB mono_thread_start_cb = NULL;
102 /* function called at thread attach */
103 static MonoThreadAttachCB mono_thread_attach_cb = NULL;
105 /* function called at thread cleanup */
106 static MonoThreadCleanupFunc mono_thread_cleanup = NULL;
108 /* function called when a new thread has been created */
109 static MonoThreadCallbacks *mono_thread_callbacks = NULL;
111 /* The TLS key that holds the LocalDataStoreSlot hash in each thread */
112 static guint32 slothash_key = -1;
114 /* The default stack size for each thread */
115 static guint32 default_stacksize = 0;
117 static void thread_adjust_static_data (MonoThread *thread);
118 static void mono_init_static_data_info (StaticDataInfo *static_data);
119 static guint32 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align);
121 /* Spin lock for InterlockedXXX 64 bit functions */
122 static CRITICAL_SECTION interlocked_mutex;
124 /* Controls access to interruption flag */
125 static CRITICAL_SECTION interruption_mutex;
127 /* global count of thread interruptions requested */
128 static gint32 thread_interruption_requested = 0;
131 mono_thread_get_tls_key (void)
133 return current_object_key;
136 /* handle_store() and handle_remove() manage the array of threads that
137 * still need to be waited for when the main thread exits.
139 static void handle_store(MonoThread *thread)
141 EnterCriticalSection(&threads_mutex);
144 g_message(G_GNUC_PRETTY_FUNCTION ": thread %p ID %d", thread,
149 MONO_GC_REGISTER_ROOT (threads);
150 threads=mono_g_hash_table_new(NULL, NULL);
153 /* We don't need to duplicate thread->handle, because it is
154 * only closed when the thread object is finalized by the GC.
156 mono_g_hash_table_insert(threads, GUINT_TO_POINTER(thread->tid), thread);
157 LeaveCriticalSection(&threads_mutex);
160 static void handle_remove(guint32 tid)
163 g_message(G_GNUC_PRETTY_FUNCTION ": thread ID %d", tid);
166 EnterCriticalSection(&threads_mutex);
169 mono_g_hash_table_remove (threads, GUINT_TO_POINTER(tid));
171 LeaveCriticalSection(&threads_mutex);
173 /* Don't close the handle here, wait for the object finalizer
174 * to do it. Otherwise, the following race condition applies:
176 * 1) Thread exits (and handle_remove() closes the handle)
178 * 2) Some other handle is reassigned the same slot
180 * 3) Another thread tries to join the first thread, and
181 * blocks waiting for the reassigned handle to be signalled
182 * (which might never happen). This is possible, because the
183 * thread calling Join() still has a reference to the first
188 static void thread_cleanup (MonoThread *thread)
190 mono_release_type_locks (thread);
192 if (!mono_monitor_enter (thread->synch_lock))
195 thread->state |= ThreadState_Stopped;
196 mono_monitor_exit (thread->synch_lock);
198 mono_profiler_thread_end (thread->tid);
199 handle_remove (thread->tid);
201 mono_thread_pop_appdomain_ref ();
203 if (thread->serialized_culture_info)
204 g_free (thread->serialized_culture_info);
206 #ifndef HAVE_BOEHM_GC
207 if (thread->culture_info)
208 g_free (thread->culture_info);
209 if (thread->ui_culture_info)
210 g_free (thread->ui_culture_info);
213 if (mono_thread_cleanup)
214 mono_thread_cleanup (thread);
217 static guint32 start_wrapper(void *data)
219 struct StartInfo *start_info=(struct StartInfo *)data;
220 guint32 (*start_func)(void *);
223 MonoThread *thread=start_info->obj;
226 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Start wrapper",
227 GetCurrentThreadId ());
230 /* We can be sure start_info->obj->tid and
231 * start_info->obj->handle have been set, because the thread
232 * was created suspended, and these values were set before the
238 SET_CURRENT_OBJECT (thread);
240 if (!mono_domain_set (start_info->domain, FALSE)) {
241 /* No point in raising an appdomain_unloaded exception here */
242 /* FIXME: Cleanup here */
246 start_func = start_info->func;
247 this = start_info->this;
249 /* This MUST be called before any managed code can be
250 * executed, as it calls the callback function that (for the
251 * jit) sets the lmf marker.
253 mono_thread_new_init (tid, &tid, start_func);
254 thread->stack_ptr = &tid;
257 g_message (G_GNUC_PRETTY_FUNCTION
258 ": (%d,%d) Setting thread stack to %p",
259 GetCurrentThreadId (), getpid (), thread->stack_ptr);
263 g_message (G_GNUC_PRETTY_FUNCTION
264 ": (%d) Setting current_object_key to %p",
265 GetCurrentThreadId (), thread);
268 mono_profiler_thread_start (tid);
270 if(thread->start_notify!=NULL) {
271 /* Let the thread that called Start() know we're
274 ReleaseSemaphore (thread->start_notify, 1, NULL);
279 /* Every thread references the appdomain which created it */
280 mono_thread_push_appdomain_ref (mono_domain_get ());
282 thread_adjust_static_data (thread);
284 g_message (G_GNUC_PRETTY_FUNCTION "start_wrapper for %d\n", thread->tid);
288 #ifdef PLATFORM_WIN32
289 /* If the thread calls ExitThread at all, this remaining code
290 * will not be executed, but the main thread will eventually
291 * call thread_cleanup() on this thread's behalf.
295 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Start wrapper terminating",
296 GetCurrentThreadId ());
299 /* Remove the reference to the thread object in the TLS data,
300 * so the thread object can be finalized. This won't be
301 * reached if the thread threw an uncaught exception, so those
302 * thread handles will stay referenced :-( (This is due to
303 * missing support for scanning thread-specific data in the
304 * Boehm GC - the io-layer keeps a GC-visible hash of pointers
307 SET_CURRENT_OBJECT (NULL);
310 thread_cleanup (thread);
315 void mono_thread_new_init (guint32 tid, gpointer stack_start, gpointer func)
317 if (mono_thread_start_cb) {
318 mono_thread_start_cb (tid, stack_start, func);
321 if (mono_thread_callbacks)
322 (* mono_thread_callbacks->thread_created) (tid, stack_start, func);
325 void mono_threads_set_default_stacksize (guint32 stacksize)
327 default_stacksize = stacksize;
330 guint32 mono_threads_get_default_stacksize (void)
332 return default_stacksize;
335 void mono_thread_create (MonoDomain *domain, gpointer func, gpointer arg)
338 HANDLE thread_handle;
339 struct StartInfo *start_info;
342 thread=(MonoThread *)mono_object_new (domain,
343 mono_defaults.thread_class);
345 start_info=g_new0 (struct StartInfo, 1);
346 start_info->func = func;
347 start_info->obj = thread;
348 start_info->domain = domain;
349 start_info->this = arg;
351 /* Create suspended, so we can do some housekeeping before the thread
354 #if defined(PLATFORM_WIN32) && defined(HAVE_BOEHM_GC)
355 thread_handle = GC_CreateThread(NULL, default_stacksize, start_wrapper, start_info,
356 CREATE_SUSPENDED, &tid);
358 thread_handle = CreateThread(NULL, default_stacksize, start_wrapper, start_info,
359 CREATE_SUSPENDED, &tid);
362 g_message(G_GNUC_PRETTY_FUNCTION ": Started thread ID %d (handle %p)",
365 g_assert (thread_handle);
367 thread->handle=thread_handle;
370 thread->synch_lock=mono_object_new (domain, mono_defaults.object_class);
372 handle_store(thread);
374 ResumeThread (thread_handle);
378 mono_thread_attach (MonoDomain *domain)
381 HANDLE thread_handle;
384 if ((thread = mono_thread_current ())) {
385 /* Already attached */
389 thread = (MonoThread *)mono_object_new (domain,
390 mono_defaults.thread_class);
392 thread_handle = GetCurrentThread ();
393 g_assert (thread_handle);
395 tid=GetCurrentThreadId ();
397 #ifdef PLATFORM_WIN32
399 * The handle returned by GetCurrentThread () is a pseudo handle, so it can't be used to
400 * refer to the thread from other threads for things like aborting.
402 DuplicateHandle (GetCurrentProcess (), thread_handle, GetCurrentProcess (), &thread_handle,
403 THREAD_ALL_ACCESS, TRUE, 0);
406 thread->handle=thread_handle;
408 thread->synch_lock=mono_object_new (domain, mono_defaults.object_class);
411 g_message(G_GNUC_PRETTY_FUNCTION ": Attached thread ID %d (handle %p)",
415 handle_store(thread);
418 g_message (G_GNUC_PRETTY_FUNCTION
419 ": (%d) Setting current_object_key to %p",
420 GetCurrentThreadId (), thread);
423 SET_CURRENT_OBJECT (thread);
424 mono_domain_set (domain, TRUE);
426 thread_adjust_static_data (thread);
428 if (mono_thread_attach_cb) {
429 mono_thread_attach_cb (tid, &tid);
436 mono_thread_detach (MonoThread *thread)
438 g_return_if_fail (thread != NULL);
441 g_message (G_GNUC_PRETTY_FUNCTION "mono_thread_detach for %d\n", thread->tid);
443 SET_CURRENT_OBJECT (NULL);
445 thread_cleanup (thread);
451 MonoThread *thread = mono_thread_current ();
453 SET_CURRENT_OBJECT (NULL);
454 thread_cleanup (thread);
456 /* we could add a callback here for embedders to use. */
457 if (thread == mono_thread_get_main ())
458 exit (mono_environment_exitcode_get ());
462 HANDLE ves_icall_System_Threading_Thread_Thread_internal(MonoThread *this,
465 MonoMulticastDelegate *delegate = (MonoMulticastDelegate*)start;
466 guint32 (*start_func)(void *);
467 struct StartInfo *start_info;
475 g_message(G_GNUC_PRETTY_FUNCTION
476 ": Trying to start a new thread: this (%p) start (%p)",
480 im = mono_get_delegate_invoke (start->vtable->klass);
481 im = mono_marshal_get_delegate_invoke (im);
482 if (mono_thread_callbacks)
483 start_func = (* mono_thread_callbacks->thread_start_compile_func) (im);
485 start_func = mono_compile_method (im);
487 if(start_func==NULL) {
488 g_warning(G_GNUC_PRETTY_FUNCTION
489 ": Can't locate start method!");
492 /* This is freed in start_wrapper */
493 start_info = g_new0 (struct StartInfo, 1);
494 start_info->func = start_func;
495 start_info->this = delegate;
496 start_info->obj = this;
497 start_info->domain = mono_domain_get ();
499 this->start_notify=CreateSemaphore (NULL, 0, 0x7fffffff, NULL);
500 if(this->start_notify==NULL) {
501 g_warning (G_GNUC_PRETTY_FUNCTION ": CreateSemaphore error 0x%x", GetLastError ());
505 #if defined(PLATFORM_WIN32) && defined(HAVE_BOEHM_GC)
506 thread=GC_CreateThread(NULL, default_stacksize, start_wrapper, start_info,
507 CREATE_SUSPENDED, &tid);
509 thread=CreateThread(NULL, default_stacksize, start_wrapper, start_info,
510 CREATE_SUSPENDED, &tid);
513 g_warning(G_GNUC_PRETTY_FUNCTION
514 ": CreateThread error 0x%x", GetLastError());
521 /* Don't call handle_store() here, delay it to Start.
522 * We can't join a thread (trying to will just block
523 * forever) until it actually starts running, so don't
524 * store the handle till then.
528 g_message(G_GNUC_PRETTY_FUNCTION
529 ": Started thread ID %d (handle %p)", tid, thread);
536 void ves_icall_System_Threading_Thread_Thread_free_internal (MonoThread *this,
542 g_message (G_GNUC_PRETTY_FUNCTION ": Closing thread %p, handle %p",
546 CloseHandle (thread);
549 void ves_icall_System_Threading_Thread_Start_internal(MonoThread *this,
555 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Launching thread %p (%d)",
556 GetCurrentThreadId (), this, this->tid);
559 /* Only store the handle when the thread is about to be
560 * launched, to avoid the main thread deadlocking while trying
561 * to clean up a thread that will never be signalled.
565 if (mono_thread_callbacks)
566 (* mono_thread_callbacks->start_resume) (this->tid);
568 ResumeThread(thread);
570 if (mono_thread_callbacks)
571 (* mono_thread_callbacks->end_resume) (this->tid);
573 if(this->start_notify!=NULL) {
574 /* Wait for the thread to set up its TLS data etc, so
575 * theres no potential race condition if someone tries
576 * to look up the data believing the thread has
581 g_message(G_GNUC_PRETTY_FUNCTION
582 ": (%d) waiting for thread %p (%d) to start",
583 GetCurrentThreadId (), this, this->tid);
586 WaitForSingleObjectEx (this->start_notify, INFINITE, FALSE);
587 CloseHandle (this->start_notify);
588 this->start_notify=NULL;
592 g_message(G_GNUC_PRETTY_FUNCTION
593 ": (%d) Done launching thread %p (%d)",
594 GetCurrentThreadId (), this, this->tid);
598 void ves_icall_System_Threading_Thread_Sleep_internal(gint32 ms)
600 MonoThread *thread = mono_thread_current ();
605 g_message(G_GNUC_PRETTY_FUNCTION ": Sleeping for %d ms", ms);
608 mono_monitor_enter (thread->synch_lock);
609 thread->state |= ThreadState_WaitSleepJoin;
610 mono_monitor_exit (thread->synch_lock);
614 mono_monitor_enter (thread->synch_lock);
615 thread->state &= ~ThreadState_WaitSleepJoin;
616 mono_monitor_exit (thread->synch_lock);
620 ves_icall_System_Threading_Thread_GetDomainID (void)
624 return mono_domain_get()->domain_id;
628 ves_icall_System_Threading_Thread_GetName_internal (MonoThread *this_obj)
633 return mono_string_new_utf16 (mono_domain_get (), this_obj->name, this_obj->name_len);
637 ves_icall_System_Threading_Thread_SetName_internal (MonoThread *this_obj, MonoString *name)
640 g_free (this_obj->name);
642 this_obj->name = g_new (gunichar2, mono_string_length (name));
643 memcpy (this_obj->name, mono_string_chars (name), mono_string_length (name) * 2);
644 this_obj->name_len = mono_string_length (name);
647 this_obj->name = NULL;
651 ves_icall_System_Threading_Thread_GetCachedCurrentCulture (MonoThread *this)
657 /* No need to lock here */
658 if (this->culture_info) {
659 domain = mono_domain_get ();
660 for (i = 0; i < NUM_CACHED_CULTURES; ++i) {
661 res = this->culture_info [i];
662 if (res && res->vtable->domain == domain)
671 ves_icall_System_Threading_Thread_GetSerializedCurrentCulture (MonoThread *this)
675 mono_monitor_enter (this->synch_lock);
676 if (this->serialized_culture_info) {
677 res = mono_array_new (mono_domain_get (), mono_defaults.byte_class, this->serialized_culture_info_len);
678 memcpy (mono_array_addr (res, guint8, 0), this->serialized_culture_info, this->serialized_culture_info_len);
682 mono_monitor_exit (this->synch_lock);
688 ves_icall_System_Threading_Thread_SetCachedCurrentCulture (MonoThread *this, MonoObject *culture)
691 MonoDomain *domain = mono_domain_get ();
693 mono_monitor_enter (this->synch_lock);
694 if (!this->culture_info) {
696 this->culture_info = GC_MALLOC (sizeof (MonoObject*) * NUM_CACHED_CULTURES);
698 this->culture_info = g_new0 (MonoObject*, NUM_CACHED_CULTURES);
702 for (i = 0; i < NUM_CACHED_CULTURES; ++i) {
703 if (this->culture_info [i]) {
704 if (this->culture_info [i]->vtable->domain == domain)
712 if (i < NUM_CACHED_CULTURES)
713 this->culture_info [i] = culture;
714 mono_monitor_exit (this->synch_lock);
718 ves_icall_System_Threading_Thread_SetSerializedCurrentCulture (MonoThread *this, MonoArray *arr)
720 mono_monitor_enter (this->synch_lock);
721 if (this->serialized_culture_info)
722 g_free (this->serialized_culture_info);
723 this->serialized_culture_info = g_new0 (guint8, mono_array_length (arr));
724 this->serialized_culture_info_len = mono_array_length (arr);
725 memcpy (this->serialized_culture_info, mono_array_addr (arr, guint8, 0), mono_array_length (arr));
726 mono_monitor_exit (this->synch_lock);
731 ves_icall_System_Threading_Thread_GetCachedCurrentUICulture (MonoThread *this)
737 /* No need to lock here */
738 if (this->ui_culture_info) {
739 domain = mono_domain_get ();
740 for (i = 0; i < NUM_CACHED_CULTURES; ++i) {
741 res = this->ui_culture_info [i];
742 if (res && res->vtable->domain == domain)
751 ves_icall_System_Threading_Thread_GetSerializedCurrentUICulture (MonoThread *this)
755 mono_monitor_enter (this->synch_lock);
756 if (this->serialized_ui_culture_info) {
757 res = mono_array_new (mono_domain_get (), mono_defaults.byte_class, this->serialized_ui_culture_info_len);
758 memcpy (mono_array_addr (res, guint8, 0), this->serialized_ui_culture_info, this->serialized_ui_culture_info_len);
762 mono_monitor_exit (this->synch_lock);
768 ves_icall_System_Threading_Thread_SetCachedCurrentUICulture (MonoThread *this, MonoObject *culture)
771 MonoDomain *domain = mono_domain_get ();
773 mono_monitor_enter (this->synch_lock);
774 if (!this->ui_culture_info) {
776 this->ui_culture_info = GC_MALLOC (sizeof (MonoObject*) * NUM_CACHED_CULTURES);
778 this->ui_culture_info = g_new0 (MonoObject*, NUM_CACHED_CULTURES);
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)
816 thread = GET_CURRENT_OBJECT ();
817 g_message (G_GNUC_PRETTY_FUNCTION ": returning %p", thread);
821 return GET_CURRENT_OBJECT ();
825 gboolean ves_icall_System_Threading_Thread_Join_internal(MonoThread *this,
826 int ms, HANDLE thread)
832 mono_monitor_enter (this->synch_lock);
833 this->state |= ThreadState_WaitSleepJoin;
834 mono_monitor_exit (this->synch_lock);
840 g_message (G_GNUC_PRETTY_FUNCTION ": joining thread handle %p, %d ms",
844 ret=WaitForSingleObjectEx (thread, ms, TRUE);
846 mono_monitor_enter (this->synch_lock);
847 this->state &= ~ThreadState_WaitSleepJoin;
848 mono_monitor_exit (this->synch_lock);
850 if(ret==WAIT_OBJECT_0) {
852 g_message (G_GNUC_PRETTY_FUNCTION ": join successful");
859 g_message (G_GNUC_PRETTY_FUNCTION ": join failed");
865 void ves_icall_System_Threading_Thread_SlotHash_store(MonoObject *data)
870 g_message(G_GNUC_PRETTY_FUNCTION ": Storing key %p", data);
873 /* Object location stored here */
874 TlsSetValue(slothash_key, data);
877 MonoObject *ves_icall_System_Threading_Thread_SlotHash_lookup(void)
883 data=TlsGetValue(slothash_key);
886 g_message(G_GNUC_PRETTY_FUNCTION ": Retrieved key %p", data);
892 /* FIXME: exitContext isnt documented */
893 gboolean ves_icall_System_Threading_WaitHandle_WaitAll_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext)
899 MonoObject *waitHandle;
901 MonoThread *thread = mono_thread_current ();
905 numhandles = mono_array_length(mono_handles);
906 handles = g_new0(HANDLE, numhandles);
908 if (wait_handle_os_handle_field == 0) {
909 /* Get the field os_handle which will contain the actual handle */
910 klass = mono_class_from_name(mono_defaults.corlib, "System.Threading", "WaitHandle");
911 wait_handle_os_handle_field = mono_class_get_field_from_name(klass, "os_handle");
914 for(i = 0; i < numhandles; i++) {
915 waitHandle = mono_array_get(mono_handles, MonoObject*, i);
916 mono_field_get_value(waitHandle, wait_handle_os_handle_field, &handles[i]);
923 mono_monitor_enter (thread->synch_lock);
924 thread->state |= ThreadState_WaitSleepJoin;
925 mono_monitor_exit (thread->synch_lock);
927 ret=WaitForMultipleObjectsEx(numhandles, handles, TRUE, ms, TRUE);
929 mono_monitor_enter (thread->synch_lock);
930 thread->state &= ~ThreadState_WaitSleepJoin;
931 mono_monitor_exit (thread->synch_lock);
935 if(ret==WAIT_FAILED) {
936 #ifdef THREAD_WAIT_DEBUG
937 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Wait failed",
938 GetCurrentThreadId ());
941 } else if(ret==WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION) {
942 /* Do we want to try again if we get
943 * WAIT_IO_COMPLETION? The documentation for
944 * WaitHandle doesn't give any clues. (We'd have to
945 * fiddle with the timeout if we retry.)
947 #ifdef THREAD_WAIT_DEBUG
948 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Wait timed out",
949 GetCurrentThreadId ());
957 /* FIXME: exitContext isnt documented */
958 gint32 ves_icall_System_Threading_WaitHandle_WaitAny_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext)
964 MonoObject *waitHandle;
966 MonoThread *thread = mono_thread_current ();
970 numhandles = mono_array_length(mono_handles);
971 handles = g_new0(HANDLE, numhandles);
973 if (wait_handle_os_handle_field == 0) {
974 /* Get the field os_handle which will contain the actual handle */
975 klass = mono_class_from_name(mono_defaults.corlib, "System.Threading", "WaitHandle");
976 wait_handle_os_handle_field = mono_class_get_field_from_name(klass, "os_handle");
979 for(i = 0; i < numhandles; i++) {
980 waitHandle = mono_array_get(mono_handles, MonoObject*, i);
981 mono_field_get_value(waitHandle, wait_handle_os_handle_field, &handles[i]);
988 mono_monitor_enter (thread->synch_lock);
989 thread->state |= ThreadState_WaitSleepJoin;
990 mono_monitor_exit (thread->synch_lock);
992 ret=WaitForMultipleObjectsEx(numhandles, handles, FALSE, ms, TRUE);
994 mono_monitor_enter (thread->synch_lock);
995 thread->state &= ~ThreadState_WaitSleepJoin;
996 mono_monitor_exit (thread->synch_lock);
1000 #ifdef THREAD_WAIT_DEBUG
1001 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) returning %d",
1002 GetCurrentThreadId (), ret);
1006 * These need to be here. See MSDN dos on WaitForMultipleObjects.
1008 if (ret >= WAIT_OBJECT_0 && ret <= WAIT_OBJECT_0 + numhandles - 1) {
1009 return ret - WAIT_OBJECT_0;
1011 else if (ret >= WAIT_ABANDONED_0 && ret <= WAIT_ABANDONED_0 + numhandles - 1) {
1012 return ret - WAIT_ABANDONED_0;
1019 /* FIXME: exitContext isnt documented */
1020 gboolean ves_icall_System_Threading_WaitHandle_WaitOne_internal(MonoObject *this, HANDLE handle, gint32 ms, gboolean exitContext)
1023 MonoThread *thread = mono_thread_current ();
1025 MONO_ARCH_SAVE_REGS;
1027 #ifdef THREAD_WAIT_DEBUG
1028 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) waiting for %p, %d ms",
1029 GetCurrentThreadId (), handle, ms);
1036 mono_monitor_enter (thread->synch_lock);
1037 thread->state |= ThreadState_WaitSleepJoin;
1038 mono_monitor_exit (thread->synch_lock);
1040 ret=WaitForSingleObjectEx (handle, ms, TRUE);
1042 mono_monitor_enter (thread->synch_lock);
1043 thread->state &= ~ThreadState_WaitSleepJoin;
1044 mono_monitor_exit (thread->synch_lock);
1046 if(ret==WAIT_FAILED) {
1047 #ifdef THREAD_WAIT_DEBUG
1048 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Wait failed",
1049 GetCurrentThreadId ());
1052 } else if(ret==WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION) {
1053 /* Do we want to try again if we get
1054 * WAIT_IO_COMPLETION? The documentation for
1055 * WaitHandle doesn't give any clues. (We'd have to
1056 * fiddle with the timeout if we retry.)
1058 #ifdef THREAD_WAIT_DEBUG
1059 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Wait timed out",
1060 GetCurrentThreadId ());
1068 HANDLE ves_icall_System_Threading_Mutex_CreateMutex_internal (MonoBoolean owned, MonoString *name, MonoBoolean *created)
1072 MONO_ARCH_SAVE_REGS;
1077 mutex = CreateMutex (NULL, owned, NULL);
1079 mutex = CreateMutex (NULL, owned, mono_string_chars (name));
1081 if (GetLastError () == ERROR_ALREADY_EXISTS) {
1089 void ves_icall_System_Threading_Mutex_ReleaseMutex_internal (HANDLE handle ) {
1090 MONO_ARCH_SAVE_REGS;
1092 ReleaseMutex(handle);
1095 HANDLE ves_icall_System_Threading_Events_CreateEvent_internal (MonoBoolean manual, MonoBoolean initial, MonoString *name) {
1096 MONO_ARCH_SAVE_REGS;
1098 return(CreateEvent (NULL, manual, initial,
1099 name==NULL?NULL:mono_string_chars (name)));
1102 gboolean ves_icall_System_Threading_Events_SetEvent_internal (HANDLE handle) {
1103 MONO_ARCH_SAVE_REGS;
1105 return (SetEvent(handle));
1108 gboolean ves_icall_System_Threading_Events_ResetEvent_internal (HANDLE handle) {
1109 MONO_ARCH_SAVE_REGS;
1111 return (ResetEvent(handle));
1115 ves_icall_System_Threading_Events_CloseEvent_internal (HANDLE handle) {
1116 MONO_ARCH_SAVE_REGS;
1118 CloseHandle (handle);
1121 gint32 ves_icall_System_Threading_Interlocked_Increment_Int (gint32 *location)
1123 MONO_ARCH_SAVE_REGS;
1125 return InterlockedIncrement (location);
1128 gint64 ves_icall_System_Threading_Interlocked_Increment_Long (gint64 *location)
1132 MONO_ARCH_SAVE_REGS;
1134 EnterCriticalSection(&interlocked_mutex);
1138 LeaveCriticalSection(&interlocked_mutex);
1144 gint32 ves_icall_System_Threading_Interlocked_Decrement_Int (gint32 *location)
1146 MONO_ARCH_SAVE_REGS;
1148 return InterlockedDecrement(location);
1151 gint64 ves_icall_System_Threading_Interlocked_Decrement_Long (gint64 * location)
1155 MONO_ARCH_SAVE_REGS;
1157 EnterCriticalSection(&interlocked_mutex);
1161 LeaveCriticalSection(&interlocked_mutex);
1166 gint32 ves_icall_System_Threading_Interlocked_Exchange_Int (gint32 *location1, gint32 value)
1168 MONO_ARCH_SAVE_REGS;
1170 return InterlockedExchange(location1, value);
1173 MonoObject * ves_icall_System_Threading_Interlocked_Exchange_Object (MonoObject **location1, MonoObject *value)
1175 MONO_ARCH_SAVE_REGS;
1177 return (MonoObject *) InterlockedExchangePointer((gpointer *) location1, value);
1180 gfloat ves_icall_System_Threading_Interlocked_Exchange_Single (gfloat *location1, gfloat value)
1182 IntFloatUnion val, ret;
1184 MONO_ARCH_SAVE_REGS;
1187 ret.ival = InterlockedExchange((gint32 *) location1, val.ival);
1192 gint32 ves_icall_System_Threading_Interlocked_CompareExchange_Int(gint32 *location1, gint32 value, gint32 comparand)
1194 MONO_ARCH_SAVE_REGS;
1196 return InterlockedCompareExchange(location1, value, comparand);
1199 MonoObject * ves_icall_System_Threading_Interlocked_CompareExchange_Object (MonoObject **location1, MonoObject *value, MonoObject *comparand)
1201 MONO_ARCH_SAVE_REGS;
1203 return (MonoObject *) InterlockedCompareExchangePointer((gpointer *) location1, value, comparand);
1206 gfloat ves_icall_System_Threading_Interlocked_CompareExchange_Single (gfloat *location1, gfloat value, gfloat comparand)
1208 IntFloatUnion val, ret, cmp;
1210 MONO_ARCH_SAVE_REGS;
1213 cmp.fval = comparand;
1214 ret.ival = InterlockedCompareExchange((gint32 *) location1, val.ival, cmp.ival);
1220 mono_thread_get_abort_signal (void)
1230 #endif /* __MINGW32__ */
1234 static CALLBACK void interruption_request_apc (ULONG_PTR param)
1236 MonoException* exc = mono_thread_request_interruption (FALSE);
1237 if (exc) mono_raise_exception (exc);
1240 #endif /* __MINGW32__ */
1243 * signal_thread_state_change
1245 * Tells the thread that his state has changed and it has to enter the new
1246 * state as soon as possible.
1248 static void signal_thread_state_change (MonoThread *thread)
1251 QueueUserAPC (interruption_request_apc, thread->handle, NULL);
1253 /* fixme: store the state somewhere */
1254 #ifdef PTHREAD_POINTER_ID
1255 pthread_kill (GUINT_TO_POINTER(thread->tid), mono_thread_get_abort_signal ());
1257 pthread_kill (thread->tid, mono_thread_get_abort_signal ());
1259 #endif /* __MINGW32__ */
1263 ves_icall_System_Threading_Thread_Abort (MonoThread *thread, MonoObject *state)
1265 MONO_ARCH_SAVE_REGS;
1267 mono_monitor_enter (thread->synch_lock);
1269 if ((thread->state & ThreadState_AbortRequested) != 0 ||
1270 (thread->state & ThreadState_StopRequested) != 0)
1272 mono_monitor_exit (thread->synch_lock);
1276 thread->state |= ThreadState_AbortRequested;
1277 thread->abort_state = state;
1278 thread->abort_exc = NULL;
1280 mono_monitor_exit (thread->synch_lock);
1283 g_message (G_GNUC_PRETTY_FUNCTION
1284 ": (%d) Abort requested for %p (%d)", GetCurrentThreadId (),
1285 thread, thread->tid);
1288 /* Make sure the thread is awake */
1289 ves_icall_System_Threading_Thread_Resume (thread);
1291 signal_thread_state_change (thread);
1295 ves_icall_System_Threading_Thread_ResetAbort (void)
1297 MonoThread *thread = mono_thread_current ();
1299 MONO_ARCH_SAVE_REGS;
1301 mono_monitor_enter (thread->synch_lock);
1303 thread->state &= ~ThreadState_AbortRequested;
1305 if (!thread->abort_exc) {
1306 const char *msg = "Unable to reset abort because no abort was requested";
1307 mono_monitor_exit (thread->synch_lock);
1308 mono_raise_exception (mono_get_exception_thread_state (msg));
1310 thread->abort_exc = NULL;
1311 thread->abort_state = NULL;
1314 mono_monitor_exit (thread->synch_lock);
1318 ves_icall_System_Threading_Thread_Suspend (MonoThread *thread)
1320 MONO_ARCH_SAVE_REGS;
1322 mono_monitor_enter (thread->synch_lock);
1324 if ((thread->state & ThreadState_Suspended) != 0 ||
1325 (thread->state & ThreadState_SuspendRequested) != 0 ||
1326 (thread->state & ThreadState_StopRequested) != 0)
1328 mono_monitor_exit (thread->synch_lock);
1332 thread->state |= ThreadState_SuspendRequested;
1333 mono_monitor_exit (thread->synch_lock);
1335 signal_thread_state_change (thread);
1339 ves_icall_System_Threading_Thread_Resume (MonoThread *thread)
1341 MONO_ARCH_SAVE_REGS;
1343 mono_monitor_enter (thread->synch_lock);
1345 if ((thread->state & ThreadState_SuspendRequested) != 0) {
1346 thread->state &= ~ThreadState_SuspendRequested;
1347 mono_monitor_exit (thread->synch_lock);
1351 if ((thread->state & ThreadState_Suspended) == 0)
1353 mono_monitor_exit (thread->synch_lock);
1357 thread->resume_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1359 /* Awake the thread */
1360 SetEvent (thread->suspend_event);
1362 mono_monitor_exit (thread->synch_lock);
1364 /* Wait for the thread to awake */
1365 WaitForSingleObject (thread->resume_event, INFINITE);
1366 CloseHandle (thread->resume_event);
1367 thread->resume_event = NULL;
1371 find_wrapper (MonoMethod *m, gint no, gint ilo, gboolean managed, gpointer data)
1376 if (m->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE ||
1377 m->wrapper_type == MONO_WRAPPER_XDOMAIN_INVOKE ||
1378 m->wrapper_type == MONO_WRAPPER_XDOMAIN_DISPATCH)
1380 *((gboolean*)data) = TRUE;
1387 is_running_protected_wrapper (void)
1389 gboolean found = FALSE;
1390 mono_stack_walk (find_wrapper, &found);
1394 void mono_thread_stop (MonoThread *thread)
1396 mono_monitor_enter (thread->synch_lock);
1398 if ((thread->state & ThreadState_StopRequested) != 0 ||
1399 (thread->state & ThreadState_Stopped) != 0)
1401 mono_monitor_exit (thread->synch_lock);
1405 /* Make sure the thread is awake */
1406 ves_icall_System_Threading_Thread_Resume (thread);
1408 thread->state |= ThreadState_StopRequested;
1409 thread->state &= ~ThreadState_AbortRequested;
1411 mono_monitor_exit (thread->synch_lock);
1413 signal_thread_state_change (thread);
1417 ves_icall_System_Threading_Thread_VolatileRead1 (void *ptr)
1419 return *((volatile gint8 *) (ptr));
1423 ves_icall_System_Threading_Thread_VolatileRead2 (void *ptr)
1425 return *((volatile gint16 *) (ptr));
1429 ves_icall_System_Threading_Thread_VolatileRead4 (void *ptr)
1431 return *((volatile gint32 *) (ptr));
1435 ves_icall_System_Threading_Thread_VolatileRead8 (void *ptr)
1437 return *((volatile gint64 *) (ptr));
1441 ves_icall_System_Threading_Thread_VolatileReadIntPtr (void *ptr)
1443 return (void *) *((volatile void **) ptr);
1447 ves_icall_System_Threading_Thread_VolatileWrite1 (void *ptr, gint8 value)
1449 *((volatile gint8 *) ptr) = value;
1453 ves_icall_System_Threading_Thread_VolatileWrite2 (void *ptr, gint16 value)
1455 *((volatile gint16 *) ptr) = value;
1459 ves_icall_System_Threading_Thread_VolatileWrite4 (void *ptr, gint32 value)
1461 *((volatile gint32 *) ptr) = value;
1465 ves_icall_System_Threading_Thread_VolatileWrite8 (void *ptr, gint64 value)
1467 *((volatile gint64 *) ptr) = value;
1471 ves_icall_System_Threading_Thread_VolatileWriteIntPtr (void *ptr, void *value)
1473 *((volatile void **) ptr) = value;
1476 void mono_thread_init (MonoThreadStartCB start_cb,
1477 MonoThreadAttachCB attach_cb)
1479 InitializeCriticalSection(&threads_mutex);
1480 InitializeCriticalSection(&interlocked_mutex);
1481 InitializeCriticalSection(&contexts_mutex);
1482 InitializeCriticalSection(&interruption_mutex);
1484 mono_init_static_data_info (&thread_static_info);
1485 mono_init_static_data_info (&context_static_info);
1487 current_object_key=TlsAlloc();
1489 g_message (G_GNUC_PRETTY_FUNCTION ": Allocated current_object_key %d",
1490 current_object_key);
1493 mono_thread_start_cb = start_cb;
1494 mono_thread_attach_cb = attach_cb;
1496 slothash_key=TlsAlloc();
1498 /* Get a pseudo handle to the current process. This is just a
1499 * kludge so that wapi can build a process handle if needed.
1500 * As a pseudo handle is returned, we don't need to clean
1503 GetCurrentProcess ();
1507 mono_threads_install_cleanup (MonoThreadCleanupFunc func)
1509 mono_thread_cleanup = func;
1512 void mono_install_thread_callbacks (MonoThreadCallbacks *callbacks)
1514 mono_thread_callbacks = callbacks;
1518 static void print_tids (gpointer key, gpointer value, gpointer user)
1520 g_message ("Waiting for: %d", GPOINTER_TO_UINT(key));
1526 HANDLE handles[MAXIMUM_WAIT_OBJECTS];
1527 MonoThread *threads[MAXIMUM_WAIT_OBJECTS];
1531 static void wait_for_tids (struct wait_data *wait, guint32 timeout)
1536 g_message(G_GNUC_PRETTY_FUNCTION
1537 ": %d threads to wait for in this batch", wait->num);
1540 ret=WaitForMultipleObjectsEx(wait->num, wait->handles, TRUE, timeout, FALSE);
1542 if(ret==WAIT_FAILED) {
1543 /* See the comment in build_wait_tids() */
1545 g_message (G_GNUC_PRETTY_FUNCTION ": Wait failed");
1550 for(i=0; i<wait->num; i++)
1551 CloseHandle (wait->handles[i]);
1553 if (ret == WAIT_TIMEOUT)
1556 for(i=0; i<wait->num; i++) {
1557 guint32 tid=wait->threads[i]->tid;
1559 if(mono_g_hash_table_lookup (threads, GUINT_TO_POINTER(tid))!=NULL) {
1560 /* This thread must have been killed, because
1561 * it hasn't cleaned itself up. (It's just
1562 * possible that the thread exited before the
1563 * parent thread had a chance to store the
1564 * handle, and now there is another pointer to
1565 * the already-exited thread stored. In this
1566 * case, we'll just get two
1567 * mono_profiler_thread_end() calls for the
1572 g_message (G_GNUC_PRETTY_FUNCTION
1573 ": cleaning up after thread %d", tid);
1575 thread_cleanup (wait->threads[i]);
1580 static void build_wait_tids (gpointer key, gpointer value, gpointer user)
1582 struct wait_data *wait=(struct wait_data *)user;
1584 if(wait->num<MAXIMUM_WAIT_OBJECTS) {
1586 MonoThread *thread=(MonoThread *)value;
1588 /* Ignore background threads, we abort them later */
1589 if (thread->state & ThreadState_Background)
1590 return; /* just leave, ignore */
1592 if (mono_gc_is_finalizer_thread (thread))
1595 if (thread == mono_thread_current ())
1598 if (thread == mono_thread_get_main ())
1601 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
1605 wait->handles[wait->num]=handle;
1606 wait->threads[wait->num]=thread;
1609 /* Just ignore the rest, we can't do anything with
1616 remove_and_abort_threads (gpointer key, gpointer value, gpointer user)
1618 struct wait_data *wait=(struct wait_data *)user;
1619 guint32 self = GetCurrentThreadId ();
1620 MonoThread *thread = (MonoThread *) value;
1623 /* The finalizer thread is not a background thread */
1624 if (thread->tid != self && thread->state & ThreadState_Background) {
1626 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
1630 wait->handles[wait->num]=thread->handle;
1631 wait->threads[wait->num]=thread;
1634 if(thread->state & ThreadState_AbortRequested ||
1635 thread->state & ThreadState_Aborted) {
1637 g_message (G_GNUC_PRETTY_FUNCTION ": Thread id %d already aborting", thread->tid);
1643 g_print (G_GNUC_PRETTY_FUNCTION ": Aborting id: %d\n", thread->tid);
1645 mono_thread_stop (thread);
1649 return (thread->tid != self && !mono_gc_is_finalizer_thread (thread));
1652 void mono_thread_manage (void)
1654 struct wait_data *wait=g_new0 (struct wait_data, 1);
1656 /* join each thread that's still running */
1658 g_message(G_GNUC_PRETTY_FUNCTION ": Joining each running thread...");
1661 EnterCriticalSection (&threads_mutex);
1664 g_message(G_GNUC_PRETTY_FUNCTION ": No threads");
1666 LeaveCriticalSection (&threads_mutex);
1669 LeaveCriticalSection (&threads_mutex);
1672 EnterCriticalSection (&threads_mutex);
1674 g_message(G_GNUC_PRETTY_FUNCTION
1675 ":There are %d threads to join",
1676 mono_g_hash_table_size (threads));
1677 mono_g_hash_table_foreach (threads, print_tids, NULL);
1681 mono_g_hash_table_foreach (threads, build_wait_tids, wait);
1682 LeaveCriticalSection (&threads_mutex);
1684 /* Something to wait for */
1685 wait_for_tids (wait, INFINITE);
1687 } while(wait->num>0);
1689 mono_thread_pool_cleanup ();
1691 EnterCriticalSection(&threads_mutex);
1694 * Remove everything but the finalizer thread and self.
1695 * Also abort all the background threads
1698 mono_g_hash_table_foreach_remove (threads, remove_and_abort_threads, wait);
1700 LeaveCriticalSection(&threads_mutex);
1703 /* Something to wait for */
1704 wait_for_tids (wait, INFINITE);
1707 * give the subthreads a chance to really quit (this is mainly needed
1708 * to get correct user and system times from getrusage/wait/time(1)).
1709 * This could be removed if we avoid pthread_detach() and use pthread_join().
1711 #ifndef PLATFORM_WIN32
1718 static void terminate_thread (gpointer key, gpointer value, gpointer user)
1720 MonoThread *thread=(MonoThread *)value;
1721 guint32 self=GPOINTER_TO_UINT (user);
1723 if(thread->tid!=self) {
1724 /*TerminateThread (thread->handle, -1);*/
1728 void mono_thread_abort_all_other_threads (void)
1730 guint32 self=GetCurrentThreadId ();
1732 EnterCriticalSection (&threads_mutex);
1734 g_message(G_GNUC_PRETTY_FUNCTION ":There are %d threads to abort",
1735 mono_g_hash_table_size (threads));
1736 mono_g_hash_table_foreach (threads, print_tids, NULL);
1739 mono_g_hash_table_foreach (threads, terminate_thread,
1740 GUINT_TO_POINTER (self));
1742 LeaveCriticalSection (&threads_mutex);
1746 * mono_thread_push_appdomain_ref:
1748 * Register that the current thread may have references to objects in domain
1749 * @domain on its stack. Each call to this function should be paired with a
1750 * call to pop_appdomain_ref.
1753 mono_thread_push_appdomain_ref (MonoDomain *domain)
1755 MonoThread *thread = mono_thread_current ();
1758 /* printf ("PUSH REF: %x -> %s.\n", thread->tid, domain->friendly_name); */
1759 EnterCriticalSection (&threads_mutex);
1760 thread->appdomain_refs = g_slist_prepend (thread->appdomain_refs, domain);
1761 LeaveCriticalSection (&threads_mutex);
1766 mono_thread_pop_appdomain_ref (void)
1768 MonoThread *thread = mono_thread_current ();
1771 /* printf ("POP REF: %x -> %s.\n", thread->tid, ((MonoDomain*)(thread->appdomain_refs->data))->friendly_name); */
1772 EnterCriticalSection (&threads_mutex);
1773 /* FIXME: How can the list be empty ? */
1774 if (thread->appdomain_refs)
1775 thread->appdomain_refs = g_slist_remove (thread->appdomain_refs, thread->appdomain_refs->data);
1776 LeaveCriticalSection (&threads_mutex);
1781 mono_thread_has_appdomain_ref (MonoThread *thread, MonoDomain *domain)
1784 EnterCriticalSection (&threads_mutex);
1785 res = g_slist_find (thread->appdomain_refs, domain) != NULL;
1786 LeaveCriticalSection (&threads_mutex);
1790 typedef struct abort_appdomain_data {
1791 struct wait_data wait;
1793 } abort_appdomain_data;
1796 abort_appdomain_thread (gpointer key, gpointer value, gpointer user_data)
1798 MonoThread *thread = (MonoThread*)value;
1799 abort_appdomain_data *data = (abort_appdomain_data*)user_data;
1800 MonoDomain *domain = data->domain;
1802 if (mono_thread_has_appdomain_ref (thread, domain)) {
1803 /* printf ("ABORTING THREAD %p BECAUSE IT REFERENCES DOMAIN %s.\n", thread->tid, domain->friendly_name); */
1804 HANDLE handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
1808 ves_icall_System_Threading_Thread_Abort (thread, NULL);
1810 if(data->wait.num<MAXIMUM_WAIT_OBJECTS) {
1811 data->wait.handles [data->wait.num] = handle;
1812 data->wait.threads [data->wait.num] = thread;
1815 /* Just ignore the rest, we can't do anything with
1823 * mono_threads_abort_appdomain_threads:
1825 * Abort threads which has references to the given appdomain.
1828 mono_threads_abort_appdomain_threads (MonoDomain *domain, int timeout)
1830 abort_appdomain_data user_data;
1833 /* printf ("ABORT BEGIN.\n"); */
1835 start_time = GetTickCount ();
1837 EnterCriticalSection (&threads_mutex);
1839 user_data.domain = domain;
1840 user_data.wait.num = 0;
1841 mono_g_hash_table_foreach (threads, abort_appdomain_thread, &user_data);
1842 LeaveCriticalSection (&threads_mutex);
1844 if (user_data.wait.num > 0)
1845 wait_for_tids (&user_data.wait, timeout);
1847 /* Update remaining time */
1848 timeout -= GetTickCount () - start_time;
1849 start_time = GetTickCount ();
1854 while (user_data.wait.num > 0);
1856 /* printf ("ABORT DONE.\n"); */
1862 clear_cached_culture (gpointer key, gpointer value, gpointer user_data)
1864 MonoThread *thread = (MonoThread*)value;
1865 MonoDomain *domain = (MonoDomain*)user_data;
1868 /* No locking needed here */
1870 if (thread->culture_info) {
1871 for (i = 0; i < NUM_CACHED_CULTURES; ++i) {
1872 if (thread->culture_info [i] && thread->culture_info [i]->vtable->domain == domain)
1873 thread->culture_info [i] = NULL;
1876 if (thread->ui_culture_info) {
1877 for (i = 0; i < NUM_CACHED_CULTURES; ++i) {
1878 if (thread->ui_culture_info [i] && thread->ui_culture_info [i]->vtable->domain == domain)
1879 thread->ui_culture_info [i] = NULL;
1885 * mono_threads_clear_cached_culture:
1887 * Clear the cached_current_culture from all threads if it is in the
1891 mono_threads_clear_cached_culture (MonoDomain *domain)
1893 EnterCriticalSection (&threads_mutex);
1894 mono_g_hash_table_foreach (threads, clear_cached_culture, domain);
1895 LeaveCriticalSection (&threads_mutex);
1899 * mono_thread_get_pending_exception:
1901 * Return an exception which needs to be raised when leaving a catch clause.
1902 * This is used for undeniable exception propagation.
1905 mono_thread_get_pending_exception (void)
1907 MonoThread *thread = mono_thread_current ();
1909 MONO_ARCH_SAVE_REGS;
1911 if (thread && thread->abort_exc && !is_running_protected_wrapper ()) {
1913 * FIXME: Clear the abort exception and return an AppDomainUnloaded
1914 * exception if the thread no longer references a dying appdomain.
1916 thread->abort_exc->trace_ips = NULL;
1917 thread->abort_exc->stack_trace = NULL;
1918 return thread->abort_exc;
1924 #define NUM_STATIC_DATA_IDX 8
1925 static const int static_data_size [NUM_STATIC_DATA_IDX] = {
1926 1024, 4096, 16384, 65536, 262144, 1048576, 4194304, 16777216
1931 * mono_alloc_static_data
1933 * Allocate memory blocks for storing threads or context static data
1936 mono_alloc_static_data (gpointer **static_data_ptr, guint32 offset)
1938 guint idx = (offset >> 24) - 1;
1941 gpointer* static_data = *static_data_ptr;
1944 static_data = GC_MALLOC (static_data_size [0]);
1946 static_data = g_malloc0 (static_data_size [0]);
1948 *static_data_ptr = static_data;
1949 static_data [0] = static_data;
1952 for (i = 1; i < idx; ++i) {
1953 if (static_data [i])
1956 static_data [i] = GC_MALLOC (static_data_size [i]);
1958 static_data [i] = g_malloc0 (static_data_size [i]);
1964 * mono_init_static_data_info
1966 * Initializes static data counters
1968 static void mono_init_static_data_info (StaticDataInfo *static_data)
1970 static_data->idx = 0;
1971 static_data->offset = 0;
1975 * mono_alloc_static_data_slot
1977 * Generates an offset for static data. static_data contains the counters
1978 * used to generate it.
1981 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align)
1985 if (!static_data->idx && !static_data->offset) {
1987 * we use the first chunk of the first allocation also as
1988 * an array for the rest of the data
1990 static_data->offset = sizeof (gpointer) * NUM_STATIC_DATA_IDX;
1992 static_data->offset += align - 1;
1993 static_data->offset &= ~(align - 1);
1994 if (static_data->offset + size >= static_data_size [static_data->idx]) {
1995 static_data->idx ++;
1996 g_assert (size <= static_data_size [static_data->idx]);
1998 * massive unloading and reloading of domains with thread-static
1999 * data may eventually exceed the allocated storage...
2000 * Need to check what the MS runtime does in that case.
2001 * Note that for each appdomain, we need to allocate a separate
2002 * thread data slot for security reasons. We could keep track
2003 * of the slots per-domain and when the domain is unloaded
2004 * out the slots on a sort of free list.
2006 g_assert (static_data->idx < NUM_STATIC_DATA_IDX);
2007 static_data->offset = 0;
2009 offset = static_data->offset | ((static_data->idx + 1) << 24);
2010 static_data->offset += size;
2015 * ensure thread static fields already allocated are valid for thread
2016 * This function is called when a thread is created or on thread attach.
2019 thread_adjust_static_data (MonoThread *thread)
2023 EnterCriticalSection (&threads_mutex);
2024 if (thread_static_info.offset || thread_static_info.idx > 0) {
2025 /* get the current allocated size */
2026 offset = thread_static_info.offset | ((thread_static_info.idx + 1) << 24);
2027 mono_alloc_static_data (&(thread->static_data), offset);
2029 LeaveCriticalSection (&threads_mutex);
2033 alloc_thread_static_data_helper (gpointer key, gpointer value, gpointer user)
2035 MonoThread *thread = value;
2036 guint32 offset = GPOINTER_TO_UINT (user);
2038 mono_alloc_static_data (&(thread->static_data), offset);
2042 * The offset for a special static variable is composed of three parts:
2043 * a bit that indicates the type of static data (0:thread, 1:context),
2044 * an index in the array of chunks of memory for the thread (thread->static_data)
2045 * and an offset in that chunk of mem. This allows allocating less memory in the
2050 mono_alloc_special_static_data (guint32 static_type, guint32 size, guint32 align)
2053 if (static_type == SPECIAL_STATIC_THREAD)
2055 EnterCriticalSection (&threads_mutex);
2056 offset = mono_alloc_static_data_slot (&thread_static_info, size, align);
2057 /* This can be called during startup */
2058 if (threads != NULL)
2059 mono_g_hash_table_foreach (threads, alloc_thread_static_data_helper, GUINT_TO_POINTER (offset));
2060 LeaveCriticalSection (&threads_mutex);
2064 g_assert (static_type == SPECIAL_STATIC_CONTEXT);
2065 EnterCriticalSection (&contexts_mutex);
2066 offset = mono_alloc_static_data_slot (&context_static_info, size, align);
2067 LeaveCriticalSection (&contexts_mutex);
2068 offset |= 0x80000000; /* Set the high bit to indicate context static data */
2074 mono_get_special_static_data (guint32 offset)
2076 /* The high bit means either thread (0) or static (1) data. */
2078 guint32 static_type = (offset & 0x80000000);
2081 offset &= 0x7fffffff;
2082 idx = (offset >> 24) - 1;
2084 if (static_type == 0)
2086 MonoThread *thread = mono_thread_current ();
2087 return ((char*) thread->static_data [idx]) + (offset & 0xffffff);
2091 /* Allocate static data block under demand, since we don't have a list
2094 MonoAppContext *context = mono_context_get ();
2095 if (!context->static_data || !context->static_data [idx]) {
2096 EnterCriticalSection (&contexts_mutex);
2097 mono_alloc_static_data (&(context->static_data), offset);
2098 LeaveCriticalSection (&contexts_mutex);
2100 return ((char*) context->static_data [idx]) + (offset & 0xffffff);
2104 static void gc_stop_world (gpointer key, gpointer value, gpointer user)
2106 MonoThread *thread=(MonoThread *)value;
2107 guint32 self=GPOINTER_TO_UINT (user);
2110 g_message (G_GNUC_PRETTY_FUNCTION ": %d - %d", self, thread->tid);
2113 if(thread->tid==self)
2116 SuspendThread (thread->handle);
2119 void mono_gc_stop_world (void)
2121 guint32 self=GetCurrentThreadId ();
2124 g_message (G_GNUC_PRETTY_FUNCTION ": %d - %p", self, threads);
2127 EnterCriticalSection (&threads_mutex);
2129 if (threads != NULL)
2130 mono_g_hash_table_foreach (threads, gc_stop_world, GUINT_TO_POINTER (self));
2132 LeaveCriticalSection (&threads_mutex);
2135 static void gc_start_world (gpointer key, gpointer value, gpointer user)
2137 MonoThread *thread=(MonoThread *)value;
2138 guint32 self=GPOINTER_TO_UINT (user);
2141 g_message (G_GNUC_PRETTY_FUNCTION ": %d - %d", self, thread->tid);
2144 if(thread->tid==self)
2147 ResumeThread (thread->handle);
2150 void mono_gc_start_world (void)
2152 guint32 self=GetCurrentThreadId ();
2155 g_message (G_GNUC_PRETTY_FUNCTION ": %d - %p", self, threads);
2158 EnterCriticalSection (&threads_mutex);
2160 if (threads != NULL)
2161 mono_g_hash_table_foreach (threads, gc_start_world, GUINT_TO_POINTER (self));
2163 LeaveCriticalSection (&threads_mutex);
2167 static CALLBACK void dummy_apc (ULONG_PTR param)
2171 static guint32 dummy_apc (gpointer param)
2178 * mono_thread_execute_interruption
2180 * Performs the operation that the requested thread state requires (abort,
2183 static MonoException* mono_thread_execute_interruption (MonoThread *thread)
2185 mono_monitor_enter (thread->synch_lock);
2187 if (thread->interruption_requested) {
2188 /* this will consume pending APC calls */
2189 WaitForSingleObjectEx (GetCurrentThread(), 0, TRUE);
2190 EnterCriticalSection (&interruption_mutex);
2191 thread_interruption_requested--;
2192 LeaveCriticalSection (&interruption_mutex);
2193 thread->interruption_requested = FALSE;
2196 if ((thread->state & ThreadState_AbortRequested) != 0) {
2197 if (thread->abort_exc == NULL)
2198 thread->abort_exc = mono_get_exception_thread_abort ();
2199 mono_monitor_exit (thread->synch_lock);
2200 return thread->abort_exc;
2202 else if ((thread->state & ThreadState_SuspendRequested) != 0) {
2203 thread->state &= ~ThreadState_SuspendRequested;
2204 thread->state |= ThreadState_Suspended;
2205 thread->suspend_event = CreateEvent (NULL, TRUE, FALSE, NULL);
2206 mono_monitor_exit (thread->synch_lock);
2208 WaitForSingleObject (thread->suspend_event, INFINITE);
2210 mono_monitor_enter (thread->synch_lock);
2211 CloseHandle (thread->suspend_event);
2212 thread->suspend_event = NULL;
2213 thread->state &= ~ThreadState_Suspended;
2215 /* The thread that requested the resume will have replaced this event
2216 * and will be waiting for it
2218 SetEvent (thread->resume_event);
2219 mono_monitor_exit (thread->synch_lock);
2222 else if ((thread->state & ThreadState_StopRequested) != 0) {
2223 /* FIXME: do this through the JIT? */
2224 mono_monitor_exit (thread->synch_lock);
2225 mono_thread_exit ();
2229 mono_monitor_exit (thread->synch_lock);
2234 * mono_thread_request_interruption
2236 * A signal handler can call this method to request the interruption of a
2237 * thread. The result of the interruption will depend on the current state of
2238 * the thread. If the result is an exception that needs to be throw, it is
2239 * provided as return value.
2241 MonoException* mono_thread_request_interruption (gboolean running_managed)
2243 MonoThread *thread = mono_thread_current ();
2245 /* The thread may already be stopping */
2249 mono_monitor_enter (thread->synch_lock);
2251 if (thread->interruption_requested) {
2252 mono_monitor_exit (thread->synch_lock);
2256 if (!running_managed || is_running_protected_wrapper ()) {
2257 /* Can't stop while in unmanaged code. Increase the global interruption
2258 request count. When exiting the unmanaged method the count will be
2259 checked and the thread will be interrupted. */
2261 EnterCriticalSection (&interruption_mutex);
2262 thread_interruption_requested++;
2263 LeaveCriticalSection (&interruption_mutex);
2265 thread->interruption_requested = TRUE;
2266 mono_monitor_exit (thread->synch_lock);
2268 /* this will awake the thread if it is in WaitForSingleObject
2270 QueueUserAPC (dummy_apc, thread->handle, NULL);
2275 mono_monitor_exit (thread->synch_lock);
2276 return mono_thread_execute_interruption (thread);
2280 gboolean mono_thread_interruption_requested ()
2282 if (thread_interruption_requested) {
2283 MonoThread *thread = mono_thread_current ();
2284 /* The thread may already be stopping */
2286 return (thread->interruption_requested);
2291 static void mono_thread_interruption_checkpoint_request (gboolean bypass_abort_protection)
2293 MonoThread *thread = mono_thread_current ();
2295 /* The thread may already be stopping */
2299 if (thread->interruption_requested && (bypass_abort_protection || !is_running_protected_wrapper ())) {
2300 MonoException* exc = mono_thread_execute_interruption (thread);
2301 if (exc) mono_raise_exception (exc);
2306 * Performs the interruption of the current thread, if one has been requested,
2307 * and the thread is not running a protected wrapper.
2309 void mono_thread_interruption_checkpoint ()
2311 mono_thread_interruption_checkpoint_request (FALSE);
2315 * Performs the interruption of the current thread, if one has been requested.
2317 void mono_thread_force_interruption_checkpoint ()
2319 mono_thread_interruption_checkpoint_request (TRUE);
2323 * mono_thread_interruption_request_flag:
2325 * Returns the address of a flag that will be non-zero if an interruption has
2326 * been requested for a thread. The thread to interrupt may not be the current
2327 * thread, so an additional call to mono_thread_interruption_requested() or
2328 * mono_thread_interruption_checkpoint() is allways needed if the flag is not
2331 gint32* mono_thread_interruption_request_flag ()
2333 return &thread_interruption_requested;
2336 #ifdef WITH_INCLUDED_LIBGC
2338 static void gc_push_all_stacks (gpointer key, gpointer value, gpointer user)
2340 MonoThread *thread=(MonoThread *)value;
2341 guint32 *selfp=(guint32 *)user, self = *selfp;
2344 g_message (G_GNUC_PRETTY_FUNCTION ": %d - %d - %p", self, thread->tid, thread->stack_ptr);
2347 if(thread->tid==self) {
2349 g_message (G_GNUC_PRETTY_FUNCTION ": %p - %p", selfp, thread->stack_ptr);
2351 GC_push_all_stack (selfp, thread->stack_ptr);
2355 #ifdef PLATFORM_WIN32
2356 GC_win32_push_thread_stack (thread->handle, thread->stack_ptr);
2358 mono_wapi_push_thread_stack (thread->handle, thread->stack_ptr);
2362 void mono_gc_push_all_stacks (void)
2364 guint32 self=GetCurrentThreadId ();
2367 g_message (G_GNUC_PRETTY_FUNCTION ": %d - %p", self, threads);
2370 EnterCriticalSection (&threads_mutex);
2372 if (threads != NULL)
2373 mono_g_hash_table_foreach (threads, gc_push_all_stacks, &self);
2375 LeaveCriticalSection (&threads_mutex);
2378 #endif /* WITH_INCLUDED_LIBGC */