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/metadata/mono-debug-debugger.h>
35 #include <mono/utils/mono-compiler.h>
37 #include <mono/os/gc_wrapper.h>
39 /*#define THREAD_DEBUG(a) do { a; } while (0)*/
40 #define THREAD_DEBUG(a)
41 /*#define THREAD_WAIT_DEBUG(a) do { a; } while (0)*/
42 #define THREAD_WAIT_DEBUG(a)
43 /*#define LIBGC_DEBUG(a) do { a; } while (0)*/
44 #define LIBGC_DEBUG(a)
46 /* Provide this for systems with glib < 2.6 */
47 #ifndef G_GSIZE_FORMAT
48 # if GLIB_SIZEOF_LONG == 8
49 # define G_GSIZE_FORMAT "lu"
51 # define G_GSIZE_FORMAT "u"
57 guint32 (*func)(void *);
79 /* Number of cached culture objects in the MonoThread->cached_culture_info array
80 * (per-type): we use the first NUM entries for CultureInfo and the last for
81 * UICultureInfo. So the size of the array is really NUM_CACHED_CULTURES * 2.
83 #define NUM_CACHED_CULTURES 4
84 #define CULTURES_START_IDX 0
85 #define UICULTURES_START_IDX NUM_CACHED_CULTURES
87 /* Controls access to the 'threads' hash table */
88 #define mono_threads_lock() EnterCriticalSection (&threads_mutex)
89 #define mono_threads_unlock() LeaveCriticalSection (&threads_mutex)
90 static CRITICAL_SECTION threads_mutex;
92 /* Controls access to context static data */
93 #define mono_contexts_lock() EnterCriticalSection (&contexts_mutex)
94 #define mono_contexts_unlock() LeaveCriticalSection (&contexts_mutex)
95 static CRITICAL_SECTION contexts_mutex;
97 /* Holds current status of static data heap */
98 static StaticDataInfo thread_static_info;
99 static StaticDataInfo context_static_info;
101 /* The hash of existing threads (key is thread ID) that need joining
104 static MonoGHashTable *threads=NULL;
106 /* The TLS key that holds the MonoObject assigned to each thread */
107 static guint32 current_object_key = -1;
109 #ifdef HAVE_KW_THREAD
110 /* we need to use both the Tls* functions and __thread because
111 * the gc needs to see all the threads
113 static __thread MonoThread * tls_current_object MONO_TLS_FAST;
114 #define SET_CURRENT_OBJECT(x) do { \
115 tls_current_object = x; \
116 TlsSetValue (current_object_key, x); \
118 #define GET_CURRENT_OBJECT() tls_current_object
120 #define SET_CURRENT_OBJECT(x) TlsSetValue (current_object_key, x);
121 #define GET_CURRENT_OBJECT() (MonoThread*) TlsGetValue (current_object_key);
124 /* function called at thread start */
125 static MonoThreadStartCB mono_thread_start_cb = NULL;
127 /* function called at thread attach */
128 static MonoThreadAttachCB mono_thread_attach_cb = NULL;
130 /* function called at thread cleanup */
131 static MonoThreadCleanupFunc mono_thread_cleanup_fn = NULL;
133 /* The default stack size for each thread */
134 static guint32 default_stacksize = 0;
135 #define default_stacksize_for_thread(thread) ((thread)->stack_size? (thread)->stack_size: default_stacksize)
137 static void thread_adjust_static_data (MonoThread *thread);
138 static void mono_init_static_data_info (StaticDataInfo *static_data);
139 static guint32 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align);
140 static gboolean mono_thread_resume (MonoThread* thread);
141 static void mono_thread_start (MonoThread *thread);
142 static void signal_thread_state_change (MonoThread *thread);
144 /* Spin lock for InterlockedXXX 64 bit functions */
145 #define mono_interlocked_lock() EnterCriticalSection (&interlocked_mutex)
146 #define mono_interlocked_unlock() LeaveCriticalSection (&interlocked_mutex)
147 static CRITICAL_SECTION interlocked_mutex;
149 /* global count of thread interruptions requested */
150 static gint32 thread_interruption_requested = 0;
152 /* Event signaled when a thread changes its background mode */
153 static HANDLE background_change_event;
156 mono_thread_get_tls_key (void)
158 return current_object_key;
162 mono_thread_get_tls_offset (void)
165 MONO_THREAD_VAR_OFFSET (tls_current_object,offset);
169 /* handle_store() and handle_remove() manage the array of threads that
170 * still need to be waited for when the main thread exits.
172 static void handle_store(MonoThread *thread)
174 mono_threads_lock ();
176 THREAD_DEBUG (g_message ("%s: thread %p ID %"G_GSIZE_FORMAT, __func__, thread, (gsize)thread->tid));
179 MONO_GC_REGISTER_ROOT (threads);
180 threads=mono_g_hash_table_new(NULL, NULL);
183 /* We don't need to duplicate thread->handle, because it is
184 * only closed when the thread object is finalized by the GC.
186 mono_g_hash_table_insert(threads, (gpointer)(gsize)(thread->tid),
189 mono_threads_unlock ();
192 static void handle_remove(gsize tid)
194 THREAD_DEBUG (g_message ("%s: thread ID %"G_GSIZE_FORMAT, __func__, tid));
196 mono_threads_lock ();
200 mono_g_hash_table_remove (threads, (gpointer)tid);
202 mono_threads_unlock ();
204 /* Don't close the handle here, wait for the object finalizer
205 * to do it. Otherwise, the following race condition applies:
207 * 1) Thread exits (and handle_remove() closes the handle)
209 * 2) Some other handle is reassigned the same slot
211 * 3) Another thread tries to join the first thread, and
212 * blocks waiting for the reassigned handle to be signalled
213 * (which might never happen). This is possible, because the
214 * thread calling Join() still has a reference to the first
219 static void thread_cleanup (MonoThread *thread)
221 g_assert (thread != NULL);
223 mono_release_type_locks (thread);
225 if (!mono_monitor_enter (thread->synch_lock))
228 thread->state |= ThreadState_Stopped;
229 mono_monitor_exit (thread->synch_lock);
231 mono_profiler_thread_end (thread->tid);
232 handle_remove (thread->tid);
234 mono_thread_pop_appdomain_ref ();
236 if (thread->serialized_culture_info)
237 g_free (thread->serialized_culture_info);
239 thread->cached_culture_info = NULL;
241 if (mono_thread_cleanup_fn)
242 mono_thread_cleanup_fn (thread);
245 static guint32 WINAPI start_wrapper(void *data)
247 struct StartInfo *start_info=(struct StartInfo *)data;
248 guint32 (*start_func)(void *);
251 MonoThread *thread=start_info->obj;
252 MonoObject *start_delegate = start_info->delegate;
254 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Start wrapper", __func__, GetCurrentThreadId ()));
256 /* We can be sure start_info->obj->tid and
257 * start_info->obj->handle have been set, because the thread
258 * was created suspended, and these values were set before the
264 SET_CURRENT_OBJECT (thread);
266 /* Every thread references the appdomain which created it */
267 mono_thread_push_appdomain_ref (start_info->domain);
269 if (!mono_domain_set (start_info->domain, FALSE)) {
270 /* No point in raising an appdomain_unloaded exception here */
271 /* FIXME: Cleanup here */
272 mono_thread_pop_appdomain_ref ();
276 start_func = start_info->func;
277 start_arg = start_info->start_arg;
279 /* This MUST be called before any managed code can be
280 * executed, as it calls the callback function that (for the
281 * jit) sets the lmf marker.
283 mono_thread_new_init (tid, &tid, start_func);
284 thread->stack_ptr = &tid;
286 LIBGC_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT",%d) Setting thread stack to %p", __func__, GetCurrentThreadId (), getpid (), thread->stack_ptr));
288 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Setting current_object_key to %p", __func__, GetCurrentThreadId (), thread));
290 mono_profiler_thread_start (tid);
292 if(thread->start_notify!=NULL) {
293 /* Let the thread that called Start() know we're
296 ReleaseSemaphore (thread->start_notify, 1, NULL);
301 thread_adjust_static_data (thread);
303 g_message ("%s: start_wrapper for %"G_GSIZE_FORMAT, __func__,
307 /* start_func is set only for unmanaged start functions */
309 start_func (start_arg);
312 g_assert (start_delegate != NULL);
313 args [0] = start_arg;
314 /* we may want to handle the exception here. See comment below on unhandled exceptions */
315 mono_runtime_delegate_invoke (start_delegate, args, NULL);
318 /* If the thread calls ExitThread at all, this remaining code
319 * will not be executed, but the main thread will eventually
320 * call thread_cleanup() on this thread's behalf.
323 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Start wrapper terminating", __func__, GetCurrentThreadId ()));
325 thread_cleanup (thread);
327 /* Remove the reference to the thread object in the TLS data,
328 * so the thread object can be finalized. This won't be
329 * reached if the thread threw an uncaught exception, so those
330 * thread handles will stay referenced :-( (This is due to
331 * missing support for scanning thread-specific data in the
332 * Boehm GC - the io-layer keeps a GC-visible hash of pointers
335 SET_CURRENT_OBJECT (NULL);
340 void mono_thread_new_init (gsize tid, gpointer stack_start, gpointer func)
342 if (mono_thread_start_cb) {
343 mono_thread_start_cb (tid, stack_start, func);
347 void mono_threads_set_default_stacksize (guint32 stacksize)
349 default_stacksize = stacksize;
352 guint32 mono_threads_get_default_stacksize (void)
354 return default_stacksize;
357 void mono_thread_create (MonoDomain *domain, gpointer func, gpointer arg)
360 HANDLE thread_handle;
361 struct StartInfo *start_info;
364 thread=(MonoThread *)mono_object_new (domain,
365 mono_defaults.thread_class);
367 start_info=g_new0 (struct StartInfo, 1);
368 start_info->func = func;
369 start_info->obj = thread;
370 start_info->domain = domain;
371 start_info->start_arg = arg;
373 /* Create suspended, so we can do some housekeeping before the thread
376 thread_handle = CreateThread(NULL, default_stacksize_for_thread (thread), (LPTHREAD_START_ROUTINE)start_wrapper, start_info,
377 CREATE_SUSPENDED, &tid);
378 THREAD_DEBUG (g_message ("%s: Started thread ID %"G_GSIZE_FORMAT" (handle %p)", __func__, 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 MONO_OBJECT_SETREF (thread, synch_lock, mono_object_new (domain, mono_defaults.object_class));
390 handle_store(thread);
392 ResumeThread (thread_handle);
396 * mono_thread_get_stack_bounds:
398 * Return the address and size of the current threads stack. Return NULL as the stack
399 * address if the stack address cannot be determined.
402 mono_thread_get_stack_bounds (guint8 **staddr, size_t *stsize)
404 #ifndef PLATFORM_WIN32
406 guint8 *current = (guint8*)&attr;
408 pthread_attr_init (&attr);
409 #ifdef HAVE_PTHREAD_GETATTR_NP
410 pthread_getattr_np (pthread_self(), &attr);
412 #ifdef HAVE_PTHREAD_ATTR_GET_NP
413 pthread_attr_get_np (pthread_self(), &attr);
416 pthread_attr_getstacksize (&attr, &stsize);
425 pthread_attr_getstack (&attr, (void**)staddr, stsize);
427 g_assert ((current > *staddr) && (current < *staddr + *stsize));
433 mono_thread_attach (MonoDomain *domain)
436 HANDLE thread_handle;
439 if ((thread = mono_thread_current ())) {
440 if (domain != mono_domain_get ())
441 mono_domain_set (domain, TRUE);
442 /* Already attached */
446 if (!mono_gc_register_thread (&domain)) {
447 g_error ("Thread %"G_GSIZE_FORMAT" calling into managed code is not registered with the GC. On UNIX, this can be fixed by #include-ing <gc.h> before <pthread.h> in the file containing the thread creation code.", GetCurrentThreadId ());
450 thread = (MonoThread *)mono_object_new (domain,
451 mono_defaults.thread_class);
453 thread_handle = GetCurrentThread ();
454 g_assert (thread_handle);
456 tid=GetCurrentThreadId ();
459 * The handle returned by GetCurrentThread () is a pseudo handle, so it can't be used to
460 * refer to the thread from other threads for things like aborting.
462 DuplicateHandle (GetCurrentProcess (), thread_handle, GetCurrentProcess (), &thread_handle,
463 THREAD_ALL_ACCESS, TRUE, 0);
465 thread->handle=thread_handle;
467 thread->stack_ptr = &tid;
468 MONO_OBJECT_SETREF (thread, synch_lock, mono_object_new (domain, mono_defaults.object_class));
470 THREAD_DEBUG (g_message ("%s: Attached thread ID %"G_GSIZE_FORMAT" (handle %p)", __func__, tid, thread_handle));
472 handle_store(thread);
474 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Setting current_object_key to %p", __func__, GetCurrentThreadId (), thread));
476 SET_CURRENT_OBJECT (thread);
477 mono_domain_set (domain, TRUE);
479 thread_adjust_static_data (thread);
481 if (mono_thread_attach_cb) {
485 mono_thread_get_stack_bounds (&staddr, &stsize);
488 mono_thread_attach_cb (tid, &tid);
490 mono_thread_attach_cb (tid, staddr + stsize);
497 mono_thread_detach (MonoThread *thread)
499 g_return_if_fail (thread != NULL);
501 THREAD_DEBUG (g_message ("%s: mono_thread_detach for %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
503 thread_cleanup (thread);
505 SET_CURRENT_OBJECT (NULL);
507 /* Don't need to CloseHandle this thread, even though we took a
508 * reference in mono_thread_attach (), because the GC will do it
509 * when the Thread object is finalised.
516 MonoThread *thread = mono_thread_current ();
518 thread_cleanup (thread);
519 SET_CURRENT_OBJECT (NULL);
521 /* we could add a callback here for embedders to use. */
522 if (thread == mono_thread_get_main ())
523 exit (mono_environment_exitcode_get ());
527 HANDLE ves_icall_System_Threading_Thread_Thread_internal(MonoThread *this,
530 guint32 (*start_func)(void *);
531 struct StartInfo *start_info;
537 THREAD_DEBUG (g_message("%s: Trying to start a new thread: this (%p) start (%p)", __func__, this, start));
539 mono_monitor_enter (this->synch_lock);
541 if ((this->state & ThreadState_Unstarted) == 0) {
542 mono_monitor_exit (this->synch_lock);
543 mono_raise_exception (mono_get_exception_thread_state ("Thread has already been started."));
547 if ((this->state & ThreadState_Aborted) != 0) {
548 mono_monitor_exit (this->synch_lock);
553 /* This is freed in start_wrapper */
554 start_info = g_new0 (struct StartInfo, 1);
555 start_info->func = start_func;
556 start_info->start_arg = this->start_obj; /* FIXME: GC object stored in unmanaged memory */
557 start_info->delegate = start;
558 start_info->obj = this;
559 start_info->domain = mono_domain_get ();
561 this->start_notify=CreateSemaphore (NULL, 0, 0x7fffffff, NULL);
562 if(this->start_notify==NULL) {
563 mono_monitor_exit (this->synch_lock);
564 g_warning ("%s: CreateSemaphore error 0x%x", __func__, GetLastError ());
568 thread=CreateThread(NULL, default_stacksize_for_thread (this), (LPTHREAD_START_ROUTINE)start_wrapper, start_info,
569 CREATE_SUSPENDED, &tid);
571 mono_monitor_exit (this->synch_lock);
572 g_warning("%s: CreateThread error 0x%x", __func__, GetLastError());
579 /* Don't call handle_store() here, delay it to Start.
580 * We can't join a thread (trying to will just block
581 * forever) until it actually starts running, so don't
582 * store the handle till then.
585 mono_thread_start (this);
587 this->state &= ~ThreadState_Unstarted;
589 THREAD_DEBUG (g_message ("%s: Started thread ID %"G_GSIZE_FORMAT" (handle %p)", __func__, tid, thread));
591 mono_monitor_exit (this->synch_lock);
596 void ves_icall_System_Threading_Thread_Thread_free_internal (MonoThread *this,
601 THREAD_DEBUG (g_message ("%s: Closing thread %p, handle %p", __func__, this, thread));
603 CloseHandle (thread);
606 static void mono_thread_start (MonoThread *thread)
610 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Launching thread %p (%"G_GSIZE_FORMAT")", __func__, GetCurrentThreadId (), thread, (gsize)thread->tid));
612 /* Only store the handle when the thread is about to be
613 * launched, to avoid the main thread deadlocking while trying
614 * to clean up a thread that will never be signalled.
616 handle_store (thread);
618 ResumeThread (thread->handle);
620 if(thread->start_notify!=NULL) {
621 /* Wait for the thread to set up its TLS data etc, so
622 * theres no potential race condition if someone tries
623 * to look up the data believing the thread has
627 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") waiting for thread %p (%"G_GSIZE_FORMAT") to start", __func__, GetCurrentThreadId (), thread, (gsize)thread->tid));
629 WaitForSingleObjectEx (thread->start_notify, INFINITE, FALSE);
630 CloseHandle (thread->start_notify);
631 thread->start_notify = NULL;
634 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Done launching thread %p (%"G_GSIZE_FORMAT")", __func__, GetCurrentThreadId (), thread, (gsize)thread->tid));
637 void ves_icall_System_Threading_Thread_Sleep_internal(gint32 ms)
639 MonoThread *thread = mono_thread_current ();
643 THREAD_DEBUG (g_message ("%s: Sleeping for %d ms", __func__, ms));
645 mono_thread_current_check_pending_interrupt ();
647 mono_monitor_enter (thread->synch_lock);
648 thread->state |= ThreadState_WaitSleepJoin;
649 mono_monitor_exit (thread->synch_lock);
653 mono_monitor_enter (thread->synch_lock);
654 thread->state &= ~ThreadState_WaitSleepJoin;
655 mono_monitor_exit (thread->synch_lock);
658 void ves_icall_System_Threading_Thread_SpinWait_internal (gint32 iterations)
662 for(i = 0; i < iterations; i++) {
663 /* We're busy waiting, but at least we can tell the
664 * scheduler to let someone else have a go...
671 ves_icall_System_Threading_Thread_GetDomainID (void)
675 return mono_domain_get()->domain_id;
679 ves_icall_System_Threading_Thread_GetName_internal (MonoThread *this_obj)
682 mono_monitor_enter (this_obj->synch_lock);
687 str = mono_string_new_utf16 (mono_domain_get (), this_obj->name, this_obj->name_len);
689 mono_monitor_exit (this_obj->synch_lock);
694 ves_icall_System_Threading_Thread_SetName_internal (MonoThread *this_obj, MonoString *name)
696 mono_monitor_enter (this_obj->synch_lock);
698 if (this_obj->name) {
699 mono_monitor_exit (this_obj->synch_lock);
700 mono_raise_exception (mono_get_exception_invalid_operation ("Thread.Name can only be set once."));
704 this_obj->name = g_new (gunichar2, mono_string_length (name));
705 memcpy (this_obj->name, mono_string_chars (name), mono_string_length (name) * 2);
706 this_obj->name_len = mono_string_length (name);
709 this_obj->name = NULL;
711 mono_monitor_exit (this_obj->synch_lock);
715 lookup_cached_culture (MonoThread *this, MonoDomain *domain, int start_idx)
720 if (this->cached_culture_info) {
721 domain = mono_domain_get ();
722 for (i = start_idx; i < start_idx + NUM_CACHED_CULTURES; ++i) {
723 res = mono_array_get (this->cached_culture_info, MonoObject*, i);
724 if (res && res->vtable->domain == domain)
733 ves_icall_System_Threading_Thread_GetCachedCurrentCulture (MonoThread *this)
735 return lookup_cached_culture (this, mono_domain_get (), CULTURES_START_IDX);
739 ves_icall_System_Threading_Thread_GetSerializedCurrentCulture (MonoThread *this)
743 mono_monitor_enter (this->synch_lock);
744 if (this->serialized_culture_info) {
745 res = mono_array_new (mono_domain_get (), mono_defaults.byte_class, this->serialized_culture_info_len);
746 memcpy (mono_array_addr (res, guint8, 0), this->serialized_culture_info, this->serialized_culture_info_len);
750 mono_monitor_exit (this->synch_lock);
756 cache_culture (MonoThread *this, MonoObject *culture, int start_idx)
759 MonoDomain *domain = mono_domain_get ();
762 int same_domain_slot = -1;
764 mono_monitor_enter (this->synch_lock);
765 if (!this->cached_culture_info)
766 this->cached_culture_info = mono_array_new (mono_object_domain (this), mono_defaults.object_class, NUM_CACHED_CULTURES * 2);
768 for (i = start_idx; i < start_idx + NUM_CACHED_CULTURES; ++i) {
769 obj = mono_array_get (this->cached_culture_info, MonoObject*, i);
773 /* we continue, because there may be a slot used with the same domain */
777 if (obj->vtable->domain == domain) {
778 same_domain_slot = i;
782 if (same_domain_slot >= 0)
783 mono_array_setref (this->cached_culture_info, same_domain_slot, culture);
784 else if (free_slot >= 0)
785 mono_array_setref (this->cached_culture_info, free_slot, culture);
786 /* we may want to replace an existing entry here, even when no suitable slot is found */
787 mono_monitor_exit (this->synch_lock);
791 ves_icall_System_Threading_Thread_SetCachedCurrentCulture (MonoThread *this, MonoObject *culture)
793 cache_culture (this, culture, CULTURES_START_IDX);
797 ves_icall_System_Threading_Thread_SetSerializedCurrentCulture (MonoThread *this, MonoArray *arr)
799 mono_monitor_enter (this->synch_lock);
800 if (this->serialized_culture_info)
801 g_free (this->serialized_culture_info);
802 this->serialized_culture_info = g_new0 (guint8, mono_array_length (arr));
803 this->serialized_culture_info_len = mono_array_length (arr);
804 memcpy (this->serialized_culture_info, mono_array_addr (arr, guint8, 0), mono_array_length (arr));
805 mono_monitor_exit (this->synch_lock);
810 ves_icall_System_Threading_Thread_GetCachedCurrentUICulture (MonoThread *this)
812 return lookup_cached_culture (this, mono_domain_get (), UICULTURES_START_IDX);
816 ves_icall_System_Threading_Thread_GetSerializedCurrentUICulture (MonoThread *this)
820 mono_monitor_enter (this->synch_lock);
821 if (this->serialized_ui_culture_info) {
822 res = mono_array_new (mono_domain_get (), mono_defaults.byte_class, this->serialized_ui_culture_info_len);
823 memcpy (mono_array_addr (res, guint8, 0), this->serialized_ui_culture_info, this->serialized_ui_culture_info_len);
827 mono_monitor_exit (this->synch_lock);
833 ves_icall_System_Threading_Thread_SetCachedCurrentUICulture (MonoThread *this, MonoObject *culture)
835 cache_culture (this, culture, UICULTURES_START_IDX);
839 ves_icall_System_Threading_Thread_SetSerializedCurrentUICulture (MonoThread *this, MonoArray *arr)
841 mono_monitor_enter (this->synch_lock);
842 if (this->serialized_ui_culture_info)
843 g_free (this->serialized_ui_culture_info);
844 this->serialized_ui_culture_info = g_new0 (guint8, mono_array_length (arr));
845 this->serialized_ui_culture_info_len = mono_array_length (arr);
846 memcpy (this->serialized_ui_culture_info, mono_array_addr (arr, guint8, 0), mono_array_length (arr));
847 mono_monitor_exit (this->synch_lock);
850 /* the jit may read the compiled code of this function */
852 mono_thread_current (void)
854 THREAD_DEBUG (g_message ("%s: returning %p", __func__, GET_CURRENT_OBJECT ()));
855 return GET_CURRENT_OBJECT ();
858 gboolean ves_icall_System_Threading_Thread_Join_internal(MonoThread *this,
859 int ms, HANDLE thread)
865 mono_monitor_enter (this->synch_lock);
867 if ((this->state & ThreadState_Unstarted) != 0) {
868 mono_monitor_exit (this->synch_lock);
869 mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started."));
873 mono_thread_current_check_pending_interrupt ();
875 this->state |= ThreadState_WaitSleepJoin;
876 mono_monitor_exit (this->synch_lock);
881 THREAD_DEBUG (g_message ("%s: joining thread handle %p, %d ms", __func__, thread, ms));
883 ret=WaitForSingleObjectEx (thread, ms, TRUE);
885 mono_monitor_enter (this->synch_lock);
886 this->state &= ~ThreadState_WaitSleepJoin;
887 mono_monitor_exit (this->synch_lock);
889 if(ret==WAIT_OBJECT_0) {
890 THREAD_DEBUG (g_message ("%s: join successful", __func__));
895 THREAD_DEBUG (g_message ("%s: join failed", __func__));
900 /* FIXME: exitContext isnt documented */
901 gboolean ves_icall_System_Threading_WaitHandle_WaitAll_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext)
907 MonoObject *waitHandle;
908 MonoThread *thread = mono_thread_current ();
912 /* Do this WaitSleepJoin check before creating objects */
913 mono_thread_current_check_pending_interrupt ();
915 numhandles = mono_array_length(mono_handles);
916 handles = g_new0(HANDLE, numhandles);
918 for(i = 0; i < numhandles; i++) {
919 waitHandle = mono_array_get(mono_handles, MonoObject*, i);
920 handles [i] = mono_wait_handle_get_handle ((MonoWaitHandle *) waitHandle);
927 mono_monitor_enter (thread->synch_lock);
928 thread->state |= ThreadState_WaitSleepJoin;
929 mono_monitor_exit (thread->synch_lock);
931 ret=WaitForMultipleObjectsEx(numhandles, handles, TRUE, ms, TRUE);
933 mono_monitor_enter (thread->synch_lock);
934 thread->state &= ~ThreadState_WaitSleepJoin;
935 mono_monitor_exit (thread->synch_lock);
939 if(ret==WAIT_FAILED) {
940 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait failed", __func__, GetCurrentThreadId ()));
942 } else if(ret==WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION) {
943 /* Do we want to try again if we get
944 * WAIT_IO_COMPLETION? The documentation for
945 * WaitHandle doesn't give any clues. (We'd have to
946 * fiddle with the timeout if we retry.)
948 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait timed out", __func__, GetCurrentThreadId ()));
955 /* FIXME: exitContext isnt documented */
956 gint32 ves_icall_System_Threading_WaitHandle_WaitAny_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext)
962 MonoObject *waitHandle;
963 MonoThread *thread = mono_thread_current ();
967 /* Do this WaitSleepJoin check before creating objects */
968 mono_thread_current_check_pending_interrupt ();
970 numhandles = mono_array_length(mono_handles);
971 handles = g_new0(HANDLE, numhandles);
973 for(i = 0; i < numhandles; i++) {
974 waitHandle = mono_array_get(mono_handles, MonoObject*, i);
975 handles [i] = mono_wait_handle_get_handle ((MonoWaitHandle *) waitHandle);
982 mono_monitor_enter (thread->synch_lock);
983 thread->state |= ThreadState_WaitSleepJoin;
984 mono_monitor_exit (thread->synch_lock);
986 ret=WaitForMultipleObjectsEx(numhandles, handles, FALSE, ms, TRUE);
988 mono_monitor_enter (thread->synch_lock);
989 thread->state &= ~ThreadState_WaitSleepJoin;
990 mono_monitor_exit (thread->synch_lock);
994 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") returning %d", __func__, GetCurrentThreadId (), ret));
997 * These need to be here. See MSDN dos on WaitForMultipleObjects.
999 if (ret >= WAIT_OBJECT_0 && ret <= WAIT_OBJECT_0 + numhandles - 1) {
1000 return ret - WAIT_OBJECT_0;
1002 else if (ret >= WAIT_ABANDONED_0 && ret <= WAIT_ABANDONED_0 + numhandles - 1) {
1003 return ret - WAIT_ABANDONED_0;
1010 /* FIXME: exitContext isnt documented */
1011 gboolean ves_icall_System_Threading_WaitHandle_WaitOne_internal(MonoObject *this, HANDLE handle, gint32 ms, gboolean exitContext)
1014 MonoThread *thread = mono_thread_current ();
1016 MONO_ARCH_SAVE_REGS;
1018 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") waiting for %p, %d ms", __func__, GetCurrentThreadId (), handle, ms));
1024 mono_thread_current_check_pending_interrupt ();
1026 mono_monitor_enter (thread->synch_lock);
1027 thread->state |= ThreadState_WaitSleepJoin;
1028 mono_monitor_exit (thread->synch_lock);
1030 ret=WaitForSingleObjectEx (handle, ms, TRUE);
1032 mono_monitor_enter (thread->synch_lock);
1033 thread->state &= ~ThreadState_WaitSleepJoin;
1034 mono_monitor_exit (thread->synch_lock);
1036 if(ret==WAIT_FAILED) {
1037 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait failed", __func__, GetCurrentThreadId ()));
1039 } else if(ret==WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION) {
1040 /* Do we want to try again if we get
1041 * WAIT_IO_COMPLETION? The documentation for
1042 * WaitHandle doesn't give any clues. (We'd have to
1043 * fiddle with the timeout if we retry.)
1045 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait timed out", __func__, GetCurrentThreadId ()));
1052 HANDLE ves_icall_System_Threading_Mutex_CreateMutex_internal (MonoBoolean owned, MonoString *name, MonoBoolean *created)
1056 MONO_ARCH_SAVE_REGS;
1061 mutex = CreateMutex (NULL, owned, NULL);
1063 mutex = CreateMutex (NULL, owned, mono_string_chars (name));
1065 if (GetLastError () == ERROR_ALREADY_EXISTS) {
1073 MonoBoolean ves_icall_System_Threading_Mutex_ReleaseMutex_internal (HANDLE handle ) {
1074 MONO_ARCH_SAVE_REGS;
1076 return(ReleaseMutex (handle));
1079 HANDLE ves_icall_System_Threading_Mutex_OpenMutex_internal (MonoString *name,
1085 MONO_ARCH_SAVE_REGS;
1087 *error = ERROR_SUCCESS;
1089 ret = OpenMutex (rights, FALSE, mono_string_chars (name));
1091 *error = GetLastError ();
1098 HANDLE ves_icall_System_Threading_Semaphore_CreateSemaphore_internal (gint32 initialCount, gint32 maximumCount, MonoString *name, MonoBoolean *created)
1102 MONO_ARCH_SAVE_REGS;
1107 sem = CreateSemaphore (NULL, initialCount, maximumCount, NULL);
1109 sem = CreateSemaphore (NULL, initialCount, maximumCount,
1110 mono_string_chars (name));
1112 if (GetLastError () == ERROR_ALREADY_EXISTS) {
1120 gint32 ves_icall_System_Threading_Semaphore_ReleaseSemaphore_internal (HANDLE handle, gint32 releaseCount, MonoBoolean *fail)
1124 MONO_ARCH_SAVE_REGS;
1126 *fail = !ReleaseSemaphore (handle, releaseCount, &prevcount);
1131 HANDLE ves_icall_System_Threading_Semaphore_OpenSemaphore_internal (MonoString *name, gint32 rights, gint32 *error)
1135 MONO_ARCH_SAVE_REGS;
1137 *error = ERROR_SUCCESS;
1139 ret = OpenSemaphore (rights, FALSE, mono_string_chars (name));
1141 *error = GetLastError ();
1147 HANDLE ves_icall_System_Threading_Events_CreateEvent_internal (MonoBoolean manual, MonoBoolean initial, MonoString *name, MonoBoolean *created)
1151 MONO_ARCH_SAVE_REGS;
1156 event = CreateEvent (NULL, manual, initial, NULL);
1158 event = CreateEvent (NULL, manual, initial,
1159 mono_string_chars (name));
1161 if (GetLastError () == ERROR_ALREADY_EXISTS) {
1169 gboolean ves_icall_System_Threading_Events_SetEvent_internal (HANDLE handle) {
1170 MONO_ARCH_SAVE_REGS;
1172 return (SetEvent(handle));
1175 gboolean ves_icall_System_Threading_Events_ResetEvent_internal (HANDLE handle) {
1176 MONO_ARCH_SAVE_REGS;
1178 return (ResetEvent(handle));
1182 ves_icall_System_Threading_Events_CloseEvent_internal (HANDLE handle) {
1183 MONO_ARCH_SAVE_REGS;
1185 CloseHandle (handle);
1188 HANDLE ves_icall_System_Threading_Events_OpenEvent_internal (MonoString *name,
1194 MONO_ARCH_SAVE_REGS;
1196 *error = ERROR_SUCCESS;
1198 ret = OpenEvent (rights, FALSE, mono_string_chars (name));
1200 *error = GetLastError ();
1206 gint32 ves_icall_System_Threading_Interlocked_Increment_Int (gint32 *location)
1208 MONO_ARCH_SAVE_REGS;
1210 return InterlockedIncrement (location);
1213 gint64 ves_icall_System_Threading_Interlocked_Increment_Long (gint64 *location)
1217 MONO_ARCH_SAVE_REGS;
1219 mono_interlocked_lock ();
1223 mono_interlocked_unlock ();
1229 gint32 ves_icall_System_Threading_Interlocked_Decrement_Int (gint32 *location)
1231 MONO_ARCH_SAVE_REGS;
1233 return InterlockedDecrement(location);
1236 gint64 ves_icall_System_Threading_Interlocked_Decrement_Long (gint64 * location)
1240 MONO_ARCH_SAVE_REGS;
1242 mono_interlocked_lock ();
1246 mono_interlocked_unlock ();
1251 gint32 ves_icall_System_Threading_Interlocked_Exchange_Int (gint32 *location, gint32 value)
1253 MONO_ARCH_SAVE_REGS;
1255 return InterlockedExchange(location, value);
1258 MonoObject * ves_icall_System_Threading_Interlocked_Exchange_Object (MonoObject **location, MonoObject *value)
1260 MONO_ARCH_SAVE_REGS;
1262 return (MonoObject *) InterlockedExchangePointer((gpointer *) location, value);
1265 gfloat ves_icall_System_Threading_Interlocked_Exchange_Single (gfloat *location, gfloat value)
1267 IntFloatUnion val, ret;
1269 MONO_ARCH_SAVE_REGS;
1272 ret.ival = InterlockedExchange((gint32 *) location, val.ival);
1278 ves_icall_System_Threading_Interlocked_Exchange_Long (gint64 *location, gint64 value)
1280 #if SIZEOF_VOID_P == 8
1281 return (gint64) InterlockedExchangePointer((gpointer *) location, (gpointer)value);
1286 * According to MSDN, this function is only atomic with regards to the
1287 * other Interlocked functions on 32 bit platforms.
1289 mono_interlocked_lock ();
1292 mono_interlocked_unlock ();
1299 ves_icall_System_Threading_Interlocked_Exchange_Double (gdouble *location, gdouble value)
1301 #if SIZEOF_VOID_P == 8
1302 LongDoubleUnion val, ret;
1305 ret.ival = (gint64)InterlockedExchangePointer((gpointer *) location, (gpointer)val.ival);
1312 * According to MSDN, this function is only atomic with regards to the
1313 * other Interlocked functions on 32 bit platforms.
1315 mono_interlocked_lock ();
1318 mono_interlocked_unlock ();
1324 gint32 ves_icall_System_Threading_Interlocked_CompareExchange_Int(gint32 *location, gint32 value, gint32 comparand)
1326 MONO_ARCH_SAVE_REGS;
1328 return InterlockedCompareExchange(location, value, comparand);
1331 MonoObject * ves_icall_System_Threading_Interlocked_CompareExchange_Object (MonoObject **location, MonoObject *value, MonoObject *comparand)
1333 MONO_ARCH_SAVE_REGS;
1335 return (MonoObject *) InterlockedCompareExchangePointer((gpointer *) location, value, comparand);
1338 gfloat ves_icall_System_Threading_Interlocked_CompareExchange_Single (gfloat *location, gfloat value, gfloat comparand)
1340 IntFloatUnion val, ret, cmp;
1342 MONO_ARCH_SAVE_REGS;
1345 cmp.fval = comparand;
1346 ret.ival = InterlockedCompareExchange((gint32 *) location, val.ival, cmp.ival);
1352 ves_icall_System_Threading_Interlocked_CompareExchange_Double (gdouble *location, gdouble value, gdouble comparand)
1354 #if SIZEOF_VOID_P == 8
1355 LongDoubleUnion val, comp, ret;
1358 comp.fval = comparand;
1359 ret.ival = (gint64)InterlockedCompareExchangePointer((gpointer *) location, (gpointer)val.ival, (gpointer)comp.ival);
1365 mono_interlocked_lock ();
1367 if (old == comparand)
1369 mono_interlocked_unlock ();
1376 ves_icall_System_Threading_Interlocked_CompareExchange_Long (gint64 *location, gint64 value, gint64 comparand)
1378 #if SIZEOF_VOID_P == 8
1379 return (gint64)InterlockedCompareExchangePointer((gpointer *) location, (gpointer)value, (gpointer)comparand);
1383 mono_interlocked_lock ();
1385 if (old == comparand)
1387 mono_interlocked_unlock ();
1394 ves_icall_System_Threading_Interlocked_CompareExchange_T (MonoObject **location, MonoObject *value, MonoObject *comparand)
1396 MONO_ARCH_SAVE_REGS;
1398 return InterlockedCompareExchangePointer ((gpointer *)location, value, comparand);
1402 ves_icall_System_Threading_Interlocked_Exchange_T (MonoObject **location, MonoObject *value)
1404 MONO_ARCH_SAVE_REGS;
1406 return InterlockedExchangePointer ((gpointer *)location, value);
1410 ves_icall_System_Threading_Interlocked_Add_Int (gint32 *location, gint32 value)
1412 #if SIZEOF_VOID_P == 8
1413 /* Should be implemented as a JIT intrinsic */
1414 mono_raise_exception (mono_get_exception_not_implemented (NULL));
1419 mono_interlocked_lock ();
1421 *location = orig + value;
1422 mono_interlocked_unlock ();
1424 return orig + value;
1429 ves_icall_System_Threading_Interlocked_Add_Long (gint64 *location, gint64 value)
1431 #if SIZEOF_VOID_P == 8
1432 /* Should be implemented as a JIT intrinsic */
1433 mono_raise_exception (mono_get_exception_not_implemented (NULL));
1438 mono_interlocked_lock ();
1440 *location = orig + value;
1441 mono_interlocked_unlock ();
1443 return orig + value;
1448 ves_icall_System_Threading_Interlocked_Read_Long (gint64 *location)
1450 #if SIZEOF_VOID_P == 8
1451 /* 64 bit reads are already atomic */
1456 mono_interlocked_lock ();
1458 mono_interlocked_unlock ();
1465 ves_icall_System_Threading_Thread_MemoryBarrier (void)
1467 mono_threads_lock ();
1468 mono_threads_unlock ();
1472 ves_icall_System_Threading_Thread_ClrState (MonoThread* this, guint32 state)
1474 mono_monitor_enter (this->synch_lock);
1475 this->state &= ~state;
1476 if (state & ThreadState_Background) {
1477 /* If the thread changes the background mode, the main thread has to
1478 * be notified, since it has to rebuild the list of threads to
1481 SetEvent (background_change_event);
1483 mono_monitor_exit (this->synch_lock);
1487 ves_icall_System_Threading_Thread_SetState (MonoThread* this, guint32 state)
1489 mono_monitor_enter (this->synch_lock);
1490 this->state |= state;
1491 if (state & ThreadState_Background) {
1492 /* If the thread changes the background mode, the main thread has to
1493 * be notified, since it has to rebuild the list of threads to
1496 SetEvent (background_change_event);
1498 mono_monitor_exit (this->synch_lock);
1502 ves_icall_System_Threading_Thread_GetState (MonoThread* this)
1505 mono_monitor_enter (this->synch_lock);
1506 state = this->state;
1507 mono_monitor_exit (this->synch_lock);
1511 void ves_icall_System_Threading_Thread_Interrupt_internal (MonoThread *this)
1513 gboolean throw = FALSE;
1515 mono_monitor_enter (this->synch_lock);
1517 /* Clear out any previous request */
1518 this->thread_interrupt_requested = FALSE;
1520 if (this->state & ThreadState_WaitSleepJoin) {
1523 this->thread_interrupt_requested = TRUE;
1526 mono_monitor_exit (this->synch_lock);
1529 signal_thread_state_change (this);
1533 void mono_thread_current_check_pending_interrupt ()
1535 MonoThread *thread = mono_thread_current ();
1536 gboolean throw = FALSE;
1538 mono_monitor_enter (thread->synch_lock);
1540 if (thread->thread_interrupt_requested) {
1542 thread->thread_interrupt_requested = FALSE;
1545 mono_monitor_exit (thread->synch_lock);
1548 mono_raise_exception (mono_get_exception_thread_interrupted ());
1553 mono_thread_get_abort_signal (void)
1555 #ifdef PLATFORM_WIN32
1561 static int abort_signum = -1;
1563 if (abort_signum != -1)
1564 return abort_signum;
1565 /* we try to avoid SIGRTMIN and any one that might have been set already, see bug #75387 */
1566 for (i = SIGRTMIN + 1; i < SIGRTMAX; ++i) {
1567 struct sigaction sinfo;
1568 sigaction (i, NULL, &sinfo);
1569 if (sinfo.sa_handler == SIG_DFL && (void*)sinfo.sa_sigaction == (void*)SIG_DFL) {
1574 /* fallback to the old way */
1577 #endif /* PLATFORM_WIN32 */
1580 #ifdef PLATFORM_WIN32
1581 static void CALLBACK interruption_request_apc (ULONG_PTR param)
1583 MonoException* exc = mono_thread_request_interruption (FALSE);
1584 if (exc) mono_raise_exception (exc);
1586 #endif /* PLATFORM_WIN32 */
1589 * signal_thread_state_change
1591 * Tells the thread that his state has changed and it has to enter the new
1592 * state as soon as possible.
1594 static void signal_thread_state_change (MonoThread *thread)
1596 if (thread == mono_thread_current ()) {
1597 /* Do it synchronously */
1598 MonoException *exc = mono_thread_request_interruption (FALSE);
1600 mono_raise_exception (exc);
1603 #ifdef PLATFORM_WIN32
1604 QueueUserAPC ((PAPCFUNC)interruption_request_apc, thread->handle, NULL);
1606 /* fixme: store the state somewhere */
1607 #ifdef PTHREAD_POINTER_ID
1608 pthread_kill ((gpointer)(gsize)(thread->tid), mono_thread_get_abort_signal ());
1610 pthread_kill (thread->tid, mono_thread_get_abort_signal ());
1612 #endif /* PLATFORM_WIN32 */
1616 ves_icall_System_Threading_Thread_Abort (MonoThread *thread, MonoObject *state)
1618 MONO_ARCH_SAVE_REGS;
1620 mono_monitor_enter (thread->synch_lock);
1622 if ((thread->state & ThreadState_AbortRequested) != 0 ||
1623 (thread->state & ThreadState_StopRequested) != 0 ||
1624 (thread->state & ThreadState_Stopped) != 0)
1626 mono_monitor_exit (thread->synch_lock);
1630 if ((thread->state & ThreadState_Unstarted) != 0) {
1631 thread->state |= ThreadState_Aborted;
1632 mono_monitor_exit (thread->synch_lock);
1636 thread->state |= ThreadState_AbortRequested;
1637 MONO_OBJECT_SETREF (thread, abort_state, state);
1638 thread->abort_exc = NULL;
1640 mono_monitor_exit (thread->synch_lock);
1642 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Abort requested for %p (%"G_GSIZE_FORMAT")", __func__, GetCurrentThreadId (), thread, (gsize)thread->tid));
1644 /* Make sure the thread is awake */
1645 mono_thread_resume (thread);
1647 signal_thread_state_change (thread);
1651 ves_icall_System_Threading_Thread_ResetAbort (void)
1653 MonoThread *thread = mono_thread_current ();
1655 MONO_ARCH_SAVE_REGS;
1657 mono_monitor_enter (thread->synch_lock);
1659 thread->state &= ~ThreadState_AbortRequested;
1661 if (!thread->abort_exc) {
1662 const char *msg = "Unable to reset abort because no abort was requested";
1663 mono_monitor_exit (thread->synch_lock);
1664 mono_raise_exception (mono_get_exception_thread_state (msg));
1666 thread->abort_exc = NULL;
1667 thread->abort_state = NULL;
1670 mono_monitor_exit (thread->synch_lock);
1674 mono_thread_suspend (MonoThread *thread)
1676 MONO_ARCH_SAVE_REGS;
1678 mono_monitor_enter (thread->synch_lock);
1680 if ((thread->state & ThreadState_Unstarted) != 0 ||
1681 (thread->state & ThreadState_Aborted) != 0 ||
1682 (thread->state & ThreadState_Stopped) != 0)
1684 mono_monitor_exit (thread->synch_lock);
1688 if ((thread->state & ThreadState_Suspended) != 0 ||
1689 (thread->state & ThreadState_SuspendRequested) != 0 ||
1690 (thread->state & ThreadState_StopRequested) != 0)
1692 mono_monitor_exit (thread->synch_lock);
1696 thread->state |= ThreadState_SuspendRequested;
1697 mono_monitor_exit (thread->synch_lock);
1699 signal_thread_state_change (thread);
1704 ves_icall_System_Threading_Thread_Suspend (MonoThread *thread)
1706 if (!mono_thread_suspend (thread))
1707 mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started, or is dead."));
1711 mono_thread_resume (MonoThread *thread)
1713 MONO_ARCH_SAVE_REGS;
1715 mono_monitor_enter (thread->synch_lock);
1717 if ((thread->state & ThreadState_SuspendRequested) != 0) {
1718 thread->state &= ~ThreadState_SuspendRequested;
1719 mono_monitor_exit (thread->synch_lock);
1723 if ((thread->state & ThreadState_Suspended) == 0 ||
1724 (thread->state & ThreadState_Unstarted) != 0 ||
1725 (thread->state & ThreadState_Aborted) != 0 ||
1726 (thread->state & ThreadState_Stopped) != 0)
1728 mono_monitor_exit (thread->synch_lock);
1732 thread->resume_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1733 if (thread->resume_event == NULL) {
1734 mono_monitor_exit (thread->synch_lock);
1738 /* Awake the thread */
1739 SetEvent (thread->suspend_event);
1741 mono_monitor_exit (thread->synch_lock);
1743 /* Wait for the thread to awake */
1744 WaitForSingleObject (thread->resume_event, INFINITE);
1745 CloseHandle (thread->resume_event);
1746 thread->resume_event = NULL;
1752 ves_icall_System_Threading_Thread_Resume (MonoThread *thread)
1754 if (!mono_thread_resume (thread))
1755 mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started, or is dead."));
1759 find_wrapper (MonoMethod *m, gint no, gint ilo, gboolean managed, gpointer data)
1764 if (m->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE ||
1765 m->wrapper_type == MONO_WRAPPER_XDOMAIN_INVOKE ||
1766 m->wrapper_type == MONO_WRAPPER_XDOMAIN_DISPATCH)
1768 *((gboolean*)data) = TRUE;
1775 is_running_protected_wrapper (void)
1777 gboolean found = FALSE;
1778 mono_stack_walk (find_wrapper, &found);
1782 void mono_thread_stop (MonoThread *thread)
1784 mono_monitor_enter (thread->synch_lock);
1786 if ((thread->state & ThreadState_StopRequested) != 0 ||
1787 (thread->state & ThreadState_Stopped) != 0)
1789 mono_monitor_exit (thread->synch_lock);
1793 /* Make sure the thread is awake */
1794 mono_thread_resume (thread);
1796 thread->state |= ThreadState_StopRequested;
1797 thread->state &= ~ThreadState_AbortRequested;
1799 mono_monitor_exit (thread->synch_lock);
1801 signal_thread_state_change (thread);
1805 ves_icall_System_Threading_Thread_VolatileRead1 (void *ptr)
1807 return *((volatile gint8 *) (ptr));
1811 ves_icall_System_Threading_Thread_VolatileRead2 (void *ptr)
1813 return *((volatile gint16 *) (ptr));
1817 ves_icall_System_Threading_Thread_VolatileRead4 (void *ptr)
1819 return *((volatile gint32 *) (ptr));
1823 ves_icall_System_Threading_Thread_VolatileRead8 (void *ptr)
1825 return *((volatile gint64 *) (ptr));
1829 ves_icall_System_Threading_Thread_VolatileReadIntPtr (void *ptr)
1831 return (void *) *((volatile void **) ptr);
1835 ves_icall_System_Threading_Thread_VolatileWrite1 (void *ptr, gint8 value)
1837 *((volatile gint8 *) ptr) = value;
1841 ves_icall_System_Threading_Thread_VolatileWrite2 (void *ptr, gint16 value)
1843 *((volatile gint16 *) ptr) = value;
1847 ves_icall_System_Threading_Thread_VolatileWrite4 (void *ptr, gint32 value)
1849 *((volatile gint32 *) ptr) = value;
1853 ves_icall_System_Threading_Thread_VolatileWrite8 (void *ptr, gint64 value)
1855 *((volatile gint64 *) ptr) = value;
1859 ves_icall_System_Threading_Thread_VolatileWriteIntPtr (void *ptr, void *value)
1861 *((volatile void **) ptr) = value;
1864 void mono_thread_init (MonoThreadStartCB start_cb,
1865 MonoThreadAttachCB attach_cb)
1867 InitializeCriticalSection(&threads_mutex);
1868 InitializeCriticalSection(&interlocked_mutex);
1869 InitializeCriticalSection(&contexts_mutex);
1870 background_change_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1871 g_assert(background_change_event != NULL);
1873 mono_init_static_data_info (&thread_static_info);
1874 mono_init_static_data_info (&context_static_info);
1876 current_object_key=TlsAlloc();
1877 THREAD_DEBUG (g_message ("%s: Allocated current_object_key %d", __func__, current_object_key));
1879 mono_thread_start_cb = start_cb;
1880 mono_thread_attach_cb = attach_cb;
1882 /* Get a pseudo handle to the current process. This is just a
1883 * kludge so that wapi can build a process handle if needed.
1884 * As a pseudo handle is returned, we don't need to clean
1887 GetCurrentProcess ();
1890 void mono_thread_cleanup (void)
1892 #if !defined(PLATFORM_WIN32) && !defined(RUN_IN_SUBTHREAD)
1893 /* The main thread must abandon any held mutexes (particularly
1894 * important for named mutexes as they are shared across
1895 * processes, see bug 74680.) This will happen when the
1896 * thread exits, but if it's not running in a subthread it
1897 * won't exit in time.
1899 /* Using non-w32 API is a nasty kludge, but I couldn't find
1900 * anything in the documentation that would let me do this
1901 * here yet still be safe to call on windows.
1903 _wapi_thread_signal_self (mono_environment_exitcode_get ());
1907 /* This stuff needs more testing, it seems one of these
1908 * critical sections can be locked when mono_thread_cleanup is
1911 DeleteCriticalSection (&threads_mutex);
1912 DeleteCriticalSection (&interlocked_mutex);
1913 DeleteCriticalSection (&contexts_mutex);
1914 CloseHandle (background_change_event);
1917 TlsFree (current_object_key);
1921 mono_threads_install_cleanup (MonoThreadCleanupFunc func)
1923 mono_thread_cleanup_fn = func;
1927 static void print_tids (gpointer key, gpointer value, gpointer user)
1929 /* GPOINTER_TO_UINT breaks horribly if sizeof(void *) >
1930 * sizeof(uint) and a cast to uint would overflow
1932 /* Older versions of glib don't have G_GSIZE_FORMAT, so just
1933 * print this as a pointer.
1935 g_message ("Waiting for: %p", key);
1940 HANDLE handles[MAXIMUM_WAIT_OBJECTS];
1941 MonoThread *threads[MAXIMUM_WAIT_OBJECTS];
1945 static void wait_for_tids (struct wait_data *wait, guint32 timeout)
1949 THREAD_DEBUG (g_message("%s: %d threads to wait for in this batch", __func__, wait->num));
1951 ret=WaitForMultipleObjectsEx(wait->num, wait->handles, TRUE, timeout, FALSE);
1953 if(ret==WAIT_FAILED) {
1954 /* See the comment in build_wait_tids() */
1955 THREAD_DEBUG (g_message ("%s: Wait failed", __func__));
1959 for(i=0; i<wait->num; i++)
1960 CloseHandle (wait->handles[i]);
1962 if (ret == WAIT_TIMEOUT)
1965 for(i=0; i<wait->num; i++) {
1966 gsize tid = wait->threads[i]->tid;
1968 if(mono_g_hash_table_lookup (threads, (gpointer)tid)!=NULL) {
1969 /* This thread must have been killed, because
1970 * it hasn't cleaned itself up. (It's just
1971 * possible that the thread exited before the
1972 * parent thread had a chance to store the
1973 * handle, and now there is another pointer to
1974 * the already-exited thread stored. In this
1975 * case, we'll just get two
1976 * mono_profiler_thread_end() calls for the
1980 THREAD_DEBUG (g_message ("%s: cleaning up after thread %"G_GSIZE_FORMAT, __func__, tid));
1981 thread_cleanup (wait->threads[i]);
1986 static void wait_for_tids_or_state_change (struct wait_data *wait, guint32 timeout)
1988 guint32 i, ret, count;
1990 THREAD_DEBUG (g_message("%s: %d threads to wait for in this batch", __func__, wait->num));
1992 /* Add the thread state change event, so it wakes up if a thread changes
1993 * to background mode.
1996 if (count < MAXIMUM_WAIT_OBJECTS) {
1997 wait->handles [count] = background_change_event;
2001 ret=WaitForMultipleObjectsEx (count, wait->handles, FALSE, timeout, FALSE);
2003 if(ret==WAIT_FAILED) {
2004 /* See the comment in build_wait_tids() */
2005 THREAD_DEBUG (g_message ("%s: Wait failed", __func__));
2009 for(i=0; i<wait->num; i++)
2010 CloseHandle (wait->handles[i]);
2012 if (ret == WAIT_TIMEOUT)
2015 if (ret < wait->num) {
2016 gsize tid = wait->threads[ret]->tid;
2017 mono_threads_lock ();
2018 if (mono_g_hash_table_lookup (threads, (gpointer)tid)!=NULL) {
2019 /* See comment in wait_for_tids about thread cleanup */
2020 mono_threads_unlock ();
2021 THREAD_DEBUG (g_message ("%s: cleaning up after thread %"G_GSIZE_FORMAT, __func__, tid));
2022 thread_cleanup (wait->threads [ret]);
2024 mono_threads_unlock ();
2028 static void build_wait_tids (gpointer key, gpointer value, gpointer user)
2030 struct wait_data *wait=(struct wait_data *)user;
2032 if(wait->num<MAXIMUM_WAIT_OBJECTS) {
2034 MonoThread *thread=(MonoThread *)value;
2036 /* Ignore background threads, we abort them later */
2037 mono_monitor_enter (thread->synch_lock);
2038 if (thread->state & ThreadState_Background) {
2039 THREAD_DEBUG (g_message ("%s: ignoring background thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2040 mono_monitor_exit (thread->synch_lock);
2041 return; /* just leave, ignore */
2043 mono_monitor_exit (thread->synch_lock);
2045 if (mono_gc_is_finalizer_thread (thread)) {
2046 THREAD_DEBUG (g_message ("%s: ignoring finalizer thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2050 if (thread == mono_thread_current ()) {
2051 THREAD_DEBUG (g_message ("%s: ignoring current thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2055 if (thread == mono_thread_get_main ()) {
2056 THREAD_DEBUG (g_message ("%s: ignoring main thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2060 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
2061 if (handle == NULL) {
2062 THREAD_DEBUG (g_message ("%s: ignoring unopenable thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2066 wait->handles[wait->num]=handle;
2067 wait->threads[wait->num]=thread;
2070 THREAD_DEBUG (g_message ("%s: adding thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2072 /* Just ignore the rest, we can't do anything with
2079 remove_and_abort_threads (gpointer key, gpointer value, gpointer user)
2081 struct wait_data *wait=(struct wait_data *)user;
2082 gsize self = GetCurrentThreadId ();
2083 MonoThread *thread = (MonoThread *) value;
2086 if (wait->num >= MAXIMUM_WAIT_OBJECTS)
2089 /* The finalizer thread is not a background thread */
2090 if (thread->tid != self && (thread->state & ThreadState_Background) != 0) {
2092 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
2096 if(thread->state & ThreadState_AbortRequested ||
2097 thread->state & ThreadState_Aborted) {
2098 THREAD_DEBUG (g_message ("%s: Thread id %"G_GSIZE_FORMAT" already aborting", __func__, (gsize)thread->tid));
2102 /* printf ("A: %d\n", wait->num); */
2103 wait->handles[wait->num]=thread->handle;
2104 wait->threads[wait->num]=thread;
2107 THREAD_DEBUG (g_print ("%s: Aborting id: %"G_GSIZE_FORMAT"\n", __func__, (gsize)thread->tid));
2108 mono_thread_stop (thread);
2112 return (thread->tid != self && !mono_gc_is_finalizer_thread (thread));
2115 void mono_thread_manage (void)
2117 struct wait_data *wait=g_new0 (struct wait_data, 1);
2119 /* join each thread that's still running */
2120 THREAD_DEBUG (g_message ("%s: Joining each running thread...", __func__));
2122 mono_threads_lock ();
2124 THREAD_DEBUG (g_message("%s: No threads", __func__));
2125 mono_threads_unlock ();
2128 mono_threads_unlock ();
2131 mono_threads_lock ();
2132 THREAD_DEBUG (g_message ("%s: There are %d threads to join", __func__, mono_g_hash_table_size (threads));
2133 mono_g_hash_table_foreach (threads, print_tids, NULL));
2135 ResetEvent (background_change_event);
2137 mono_g_hash_table_foreach (threads, build_wait_tids, wait);
2138 mono_threads_unlock ();
2140 /* Something to wait for */
2141 wait_for_tids_or_state_change (wait, INFINITE);
2143 THREAD_DEBUG (g_message ("%s: I have %d threads after waiting.", __func__, wait->num));
2144 } while(wait->num>0);
2146 mono_runtime_set_shutting_down ();
2148 THREAD_DEBUG (g_message ("%s: threadpool cleanup", __func__));
2149 mono_thread_pool_cleanup ();
2152 * Remove everything but the finalizer thread and self.
2153 * Also abort all the background threads
2156 mono_threads_lock ();
2159 mono_g_hash_table_foreach_remove (threads, remove_and_abort_threads, wait);
2161 mono_threads_unlock ();
2163 THREAD_DEBUG (g_message ("%s: wait->num is now %d", __func__, wait->num));
2165 /* Something to wait for */
2166 wait_for_tids (wait, INFINITE);
2168 } while (wait->num > 0);
2171 * give the subthreads a chance to really quit (this is mainly needed
2172 * to get correct user and system times from getrusage/wait/time(1)).
2173 * This could be removed if we avoid pthread_detach() and use pthread_join().
2175 #ifndef PLATFORM_WIN32
2182 static void terminate_thread (gpointer key, gpointer value, gpointer user)
2184 MonoThread *thread=(MonoThread *)value;
2186 if(thread->tid != (gsize)user) {
2187 /*TerminateThread (thread->handle, -1);*/
2191 void mono_thread_abort_all_other_threads (void)
2193 gsize self = GetCurrentThreadId ();
2195 mono_threads_lock ();
2196 THREAD_DEBUG (g_message ("%s: There are %d threads to abort", __func__,
2197 mono_g_hash_table_size (threads));
2198 mono_g_hash_table_foreach (threads, print_tids, NULL));
2200 mono_g_hash_table_foreach (threads, terminate_thread, (gpointer)self);
2202 mono_threads_unlock ();
2206 collect_threads (gpointer key, gpointer value, gpointer user_data)
2208 MonoThread *thread = (MonoThread*)value;
2209 struct wait_data *wait = (struct wait_data*)user_data;
2212 if (wait->num<MAXIMUM_WAIT_OBJECTS) {
2213 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
2217 wait->handles [wait->num] = handle;
2218 wait->threads [wait->num] = thread;
2224 * mono_thread_suspend_all_other_threads:
2226 * Suspend all managed threads except the finalizer thread and this thread.
2228 void mono_thread_suspend_all_other_threads (void)
2230 struct wait_data *wait = g_new0 (struct wait_data, 1);
2232 gsize self = GetCurrentThreadId ();
2234 guint32 eventidx = 0;
2237 * Make a copy of the hashtable since we can't do anything with
2238 * threads while threads_mutex is held.
2240 mono_threads_lock ();
2241 mono_g_hash_table_foreach (threads, collect_threads, wait);
2242 mono_threads_unlock ();
2244 events = g_new0 (gpointer, wait->num);
2246 /* Get the suspended events that we'll be waiting for */
2247 for (i = 0; i < wait->num; ++i) {
2248 MonoThread *thread = wait->threads [i];
2250 if ((thread->tid == self) || mono_gc_is_finalizer_thread (thread)) {
2251 //CloseHandle (wait->handles [i]);
2252 wait->threads [i] = NULL; /* ignore this thread in next loop */
2256 mono_monitor_enter (thread->synch_lock);
2258 if ((thread->state & ThreadState_Suspended) != 0 ||
2259 (thread->state & ThreadState_SuspendRequested) != 0 ||
2260 (thread->state & ThreadState_StopRequested) != 0 ||
2261 (thread->state & ThreadState_Stopped) != 0) {
2262 mono_monitor_exit (thread->synch_lock);
2263 CloseHandle (wait->handles [i]);
2264 wait->threads [i] = NULL; /* ignore this thread in next loop */
2268 /* Convert abort requests into suspend requests */
2269 if ((thread->state & ThreadState_AbortRequested) != 0)
2270 thread->state &= ~ThreadState_AbortRequested;
2272 thread->state |= ThreadState_SuspendRequested;
2274 if (thread->suspended_event == NULL) {
2275 thread->suspended_event = CreateEvent (NULL, TRUE, FALSE, NULL);
2276 if (thread->suspended_event == NULL) {
2277 /* Forget this one and go on to the next */
2278 mono_monitor_exit (thread->synch_lock);
2283 events [eventidx++] = thread->suspended_event;
2284 mono_monitor_exit (thread->synch_lock);
2286 /* Signal the thread to suspend */
2287 signal_thread_state_change (thread);
2290 WaitForMultipleObjectsEx (eventidx, events, TRUE, INFINITE, FALSE);
2291 for (i = 0; i < wait->num; ++i) {
2292 MonoThread *thread = wait->threads [i];
2297 mono_monitor_enter (thread->synch_lock);
2298 CloseHandle (thread->suspended_event);
2299 thread->suspended_event = NULL;
2300 mono_monitor_exit (thread->synch_lock);
2308 * mono_threads_request_thread_dump:
2310 * Ask all threads except the current to print their stacktrace to stdout.
2313 mono_threads_request_thread_dump (void)
2315 struct wait_data *wait = g_new0 (struct wait_data, 1);
2319 * Make a copy of the hashtable since we can't do anything with
2320 * threads while threads_mutex is held.
2322 mono_threads_lock ();
2323 mono_g_hash_table_foreach (threads, collect_threads, wait);
2324 mono_threads_unlock ();
2326 for (i = 0; i < wait->num; ++i) {
2327 MonoThread *thread = wait->threads [i];
2329 if (!mono_gc_is_finalizer_thread (thread) && (thread != mono_thread_current ()) && !thread->thread_dump_requested) {
2330 thread->thread_dump_requested = TRUE;
2332 signal_thread_state_change (thread);
2335 CloseHandle (wait->handles [i]);
2340 * mono_thread_push_appdomain_ref:
2342 * Register that the current thread may have references to objects in domain
2343 * @domain on its stack. Each call to this function should be paired with a
2344 * call to pop_appdomain_ref.
2347 mono_thread_push_appdomain_ref (MonoDomain *domain)
2349 MonoThread *thread = mono_thread_current ();
2352 /* printf ("PUSH REF: %"G_GSIZE_FORMAT" -> %s.\n", (gsize)thread->tid, domain->friendly_name); */
2353 mono_threads_lock ();
2354 thread->appdomain_refs = g_slist_prepend (thread->appdomain_refs, domain);
2355 mono_threads_unlock ();
2360 mono_thread_pop_appdomain_ref (void)
2362 MonoThread *thread = mono_thread_current ();
2365 /* printf ("POP REF: %"G_GSIZE_FORMAT" -> %s.\n", (gsize)thread->tid, ((MonoDomain*)(thread->appdomain_refs->data))->friendly_name); */
2366 mono_threads_lock ();
2367 /* FIXME: How can the list be empty ? */
2368 if (thread->appdomain_refs)
2369 thread->appdomain_refs = g_slist_remove (thread->appdomain_refs, thread->appdomain_refs->data);
2370 mono_threads_unlock ();
2375 mono_thread_has_appdomain_ref (MonoThread *thread, MonoDomain *domain)
2378 mono_threads_lock ();
2379 res = g_slist_find (thread->appdomain_refs, domain) != NULL;
2380 mono_threads_unlock ();
2384 typedef struct abort_appdomain_data {
2385 struct wait_data wait;
2387 } abort_appdomain_data;
2390 abort_appdomain_thread (gpointer key, gpointer value, gpointer user_data)
2392 MonoThread *thread = (MonoThread*)value;
2393 abort_appdomain_data *data = (abort_appdomain_data*)user_data;
2394 MonoDomain *domain = data->domain;
2396 if (mono_thread_has_appdomain_ref (thread, domain)) {
2397 /* printf ("ABORTING THREAD %p BECAUSE IT REFERENCES DOMAIN %s.\n", thread->tid, domain->friendly_name); */
2399 ves_icall_System_Threading_Thread_Abort (thread, NULL);
2401 if(data->wait.num<MAXIMUM_WAIT_OBJECTS) {
2402 HANDLE handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
2405 data->wait.handles [data->wait.num] = handle;
2406 data->wait.threads [data->wait.num] = thread;
2409 /* Just ignore the rest, we can't do anything with
2417 * mono_threads_abort_appdomain_threads:
2419 * Abort threads which has references to the given appdomain.
2422 mono_threads_abort_appdomain_threads (MonoDomain *domain, int timeout)
2424 abort_appdomain_data user_data;
2427 /* printf ("ABORT BEGIN.\n"); */
2429 start_time = GetTickCount ();
2431 mono_threads_lock ();
2433 user_data.domain = domain;
2434 user_data.wait.num = 0;
2435 mono_g_hash_table_foreach (threads, abort_appdomain_thread, &user_data);
2436 mono_threads_unlock ();
2438 if (user_data.wait.num > 0)
2440 * We should wait for the threads either to abort, or to leave the
2441 * domain. We can't do the latter, so we wait with a timeout.
2443 wait_for_tids (&user_data.wait, 100);
2445 /* Update remaining time */
2446 timeout -= GetTickCount () - start_time;
2447 start_time = GetTickCount ();
2452 while (user_data.wait.num > 0);
2454 /* printf ("ABORT DONE.\n"); */
2460 clear_cached_culture (gpointer key, gpointer value, gpointer user_data)
2462 MonoThread *thread = (MonoThread*)value;
2463 MonoDomain *domain = (MonoDomain*)user_data;
2466 /* No locking needed here */
2467 /* FIXME: why no locking? writes to the cache are protected with synch_lock above */
2469 if (thread->cached_culture_info) {
2470 for (i = 0; i < NUM_CACHED_CULTURES * 2; ++i) {
2471 MonoObject *obj = mono_array_get (thread->cached_culture_info, MonoObject*, i);
2472 if (obj && obj->vtable->domain == domain)
2473 mono_array_set (thread->cached_culture_info, MonoObject*, i, NULL);
2479 * mono_threads_clear_cached_culture:
2481 * Clear the cached_current_culture from all threads if it is in the
2485 mono_threads_clear_cached_culture (MonoDomain *domain)
2487 mono_threads_lock ();
2488 mono_g_hash_table_foreach (threads, clear_cached_culture, domain);
2489 mono_threads_unlock ();
2493 * mono_thread_get_pending_exception:
2495 * Return an exception which needs to be raised when leaving a catch clause.
2496 * This is used for undeniable exception propagation.
2499 mono_thread_get_pending_exception (void)
2501 MonoThread *thread = mono_thread_current ();
2503 MONO_ARCH_SAVE_REGS;
2505 if (thread && thread->abort_exc && !is_running_protected_wrapper ()) {
2507 * FIXME: Clear the abort exception and return an AppDomainUnloaded
2508 * exception if the thread no longer references a dying appdomain.
2510 thread->abort_exc->trace_ips = NULL;
2511 thread->abort_exc->stack_trace = NULL;
2512 return thread->abort_exc;
2518 #define NUM_STATIC_DATA_IDX 8
2519 static const int static_data_size [NUM_STATIC_DATA_IDX] = {
2520 1024, 4096, 16384, 65536, 262144, 1048576, 4194304, 16777216
2525 * mono_alloc_static_data
2527 * Allocate memory blocks for storing threads or context static data
2530 mono_alloc_static_data (gpointer **static_data_ptr, guint32 offset)
2532 guint idx = (offset >> 24) - 1;
2535 gpointer* static_data = *static_data_ptr;
2537 static_data = mono_gc_alloc_fixed (static_data_size [0], NULL);
2538 *static_data_ptr = static_data;
2539 static_data [0] = static_data;
2542 for (i = 1; i <= idx; ++i) {
2543 if (static_data [i])
2545 static_data [i] = mono_gc_alloc_fixed (static_data_size [i], NULL);
2550 * mono_init_static_data_info
2552 * Initializes static data counters
2554 static void mono_init_static_data_info (StaticDataInfo *static_data)
2556 static_data->idx = 0;
2557 static_data->offset = 0;
2561 * mono_alloc_static_data_slot
2563 * Generates an offset for static data. static_data contains the counters
2564 * used to generate it.
2567 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align)
2571 if (!static_data->idx && !static_data->offset) {
2573 * we use the first chunk of the first allocation also as
2574 * an array for the rest of the data
2576 static_data->offset = sizeof (gpointer) * NUM_STATIC_DATA_IDX;
2578 static_data->offset += align - 1;
2579 static_data->offset &= ~(align - 1);
2580 if (static_data->offset + size >= static_data_size [static_data->idx]) {
2581 static_data->idx ++;
2582 g_assert (size <= static_data_size [static_data->idx]);
2584 * massive unloading and reloading of domains with thread-static
2585 * data may eventually exceed the allocated storage...
2586 * Need to check what the MS runtime does in that case.
2587 * Note that for each appdomain, we need to allocate a separate
2588 * thread data slot for security reasons. We could keep track
2589 * of the slots per-domain and when the domain is unloaded
2590 * out the slots on a sort of free list.
2592 g_assert (static_data->idx < NUM_STATIC_DATA_IDX);
2593 static_data->offset = 0;
2595 offset = static_data->offset | ((static_data->idx + 1) << 24);
2596 static_data->offset += size;
2601 * ensure thread static fields already allocated are valid for thread
2602 * This function is called when a thread is created or on thread attach.
2605 thread_adjust_static_data (MonoThread *thread)
2609 mono_threads_lock ();
2610 if (thread_static_info.offset || thread_static_info.idx > 0) {
2611 /* get the current allocated size */
2612 offset = thread_static_info.offset | ((thread_static_info.idx + 1) << 24);
2613 mono_alloc_static_data (&(thread->static_data), offset);
2615 mono_threads_unlock ();
2619 alloc_thread_static_data_helper (gpointer key, gpointer value, gpointer user)
2621 MonoThread *thread = value;
2622 guint32 offset = GPOINTER_TO_UINT (user);
2624 mono_alloc_static_data (&(thread->static_data), offset);
2628 * The offset for a special static variable is composed of three parts:
2629 * a bit that indicates the type of static data (0:thread, 1:context),
2630 * an index in the array of chunks of memory for the thread (thread->static_data)
2631 * and an offset in that chunk of mem. This allows allocating less memory in the
2636 mono_alloc_special_static_data (guint32 static_type, guint32 size, guint32 align)
2639 if (static_type == SPECIAL_STATIC_THREAD)
2641 mono_threads_lock ();
2642 offset = mono_alloc_static_data_slot (&thread_static_info, size, align);
2643 /* This can be called during startup */
2644 if (threads != NULL)
2645 mono_g_hash_table_foreach (threads, alloc_thread_static_data_helper, GUINT_TO_POINTER (offset));
2646 mono_threads_unlock ();
2650 g_assert (static_type == SPECIAL_STATIC_CONTEXT);
2651 mono_contexts_lock ();
2652 offset = mono_alloc_static_data_slot (&context_static_info, size, align);
2653 mono_contexts_unlock ();
2654 offset |= 0x80000000; /* Set the high bit to indicate context static data */
2660 mono_get_special_static_data (guint32 offset)
2662 /* The high bit means either thread (0) or static (1) data. */
2664 guint32 static_type = (offset & 0x80000000);
2667 offset &= 0x7fffffff;
2668 idx = (offset >> 24) - 1;
2670 if (static_type == 0)
2672 MonoThread *thread = mono_thread_current ();
2673 return ((char*) thread->static_data [idx]) + (offset & 0xffffff);
2677 /* Allocate static data block under demand, since we don't have a list
2680 MonoAppContext *context = mono_context_get ();
2681 if (!context->static_data || !context->static_data [idx]) {
2682 mono_contexts_lock ();
2683 mono_alloc_static_data (&(context->static_data), offset);
2684 mono_contexts_unlock ();
2686 return ((char*) context->static_data [idx]) + (offset & 0xffffff);
2690 static MonoClassField *local_slots = NULL;
2693 /* local tls data to get locals_slot from a thread */
2696 /* index in the locals_slot array */
2701 clear_local_slot (gpointer key, gpointer value, gpointer user_data)
2703 LocalSlotID *sid = user_data;
2704 MonoThread *thread = (MonoThread*)value;
2705 MonoArray *slots_array;
2707 * the static field is stored at: ((char*) thread->static_data [idx]) + (offset & 0xffffff);
2708 * it is for the right domain, so we need to check if it is allocated an initialized
2709 * for the current thread.
2711 /*g_print ("handling thread %p\n", thread);*/
2712 if (!thread->static_data || !thread->static_data [sid->idx])
2714 slots_array = *(MonoArray **)(((char*) thread->static_data [sid->idx]) + (sid->offset & 0xffffff));
2715 if (!slots_array || sid->slot >= mono_array_length (slots_array))
2717 mono_array_set (slots_array, MonoObject*, sid->slot, NULL);
2721 mono_thread_free_local_slot_values (int slot, MonoBoolean thread_local)
2729 local_slots = mono_class_get_field_from_name (mono_defaults.thread_class, "local_slots");
2731 g_warning ("local_slots field not found in Thread class");
2735 domain = mono_domain_get ();
2736 mono_domain_lock (domain);
2737 if (domain->special_static_fields)
2738 addr = g_hash_table_lookup (domain->special_static_fields, local_slots);
2739 mono_domain_unlock (domain);
2742 /*g_print ("freeing slot %d at %p\n", slot, addr);*/
2743 sid.offset = GPOINTER_TO_UINT (addr);
2744 sid.offset &= 0x7fffffff;
2745 sid.idx = (sid.offset >> 24) - 1;
2746 mono_threads_lock ();
2747 mono_g_hash_table_foreach (threads, clear_local_slot, &sid);
2748 mono_threads_unlock ();
2750 /* FIXME: clear the slot for MonoAppContexts, too */
2754 #ifdef PLATFORM_WIN32
2755 static void CALLBACK dummy_apc (ULONG_PTR param)
2759 static guint32 dummy_apc (gpointer param)
2766 * mono_thread_execute_interruption
2768 * Performs the operation that the requested thread state requires (abort,
2771 static MonoException* mono_thread_execute_interruption (MonoThread *thread)
2773 mono_monitor_enter (thread->synch_lock);
2775 if (thread->interruption_requested) {
2776 /* this will consume pending APC calls */
2777 WaitForSingleObjectEx (GetCurrentThread(), 0, TRUE);
2778 InterlockedDecrement (&thread_interruption_requested);
2779 thread->interruption_requested = FALSE;
2782 if ((thread->state & ThreadState_AbortRequested) != 0) {
2783 if (thread->abort_exc == NULL)
2784 MONO_OBJECT_SETREF (thread, abort_exc, mono_get_exception_thread_abort ());
2785 mono_monitor_exit (thread->synch_lock);
2786 return thread->abort_exc;
2788 else if ((thread->state & ThreadState_SuspendRequested) != 0) {
2789 thread->state &= ~ThreadState_SuspendRequested;
2790 thread->state |= ThreadState_Suspended;
2791 thread->suspend_event = CreateEvent (NULL, TRUE, FALSE, NULL);
2792 if (thread->suspend_event == NULL) {
2793 mono_monitor_exit (thread->synch_lock);
2796 if (thread->suspended_event)
2797 SetEvent (thread->suspended_event);
2798 mono_monitor_exit (thread->synch_lock);
2800 WaitForSingleObject (thread->suspend_event, INFINITE);
2802 mono_monitor_enter (thread->synch_lock);
2803 CloseHandle (thread->suspend_event);
2804 thread->suspend_event = NULL;
2805 thread->state &= ~ThreadState_Suspended;
2807 /* The thread that requested the resume will have replaced this event
2808 * and will be waiting for it
2810 SetEvent (thread->resume_event);
2811 mono_monitor_exit (thread->synch_lock);
2814 else if ((thread->state & ThreadState_StopRequested) != 0) {
2815 /* FIXME: do this through the JIT? */
2816 mono_monitor_exit (thread->synch_lock);
2817 mono_thread_exit ();
2819 } else if (thread->thread_interrupt_requested) {
2820 mono_monitor_exit (thread->synch_lock);
2821 return(mono_get_exception_thread_interrupted ());
2824 mono_monitor_exit (thread->synch_lock);
2829 * mono_thread_request_interruption
2831 * A signal handler can call this method to request the interruption of a
2832 * thread. The result of the interruption will depend on the current state of
2833 * the thread. If the result is an exception that needs to be throw, it is
2834 * provided as return value.
2836 MonoException* mono_thread_request_interruption (gboolean running_managed)
2838 MonoThread *thread = mono_thread_current ();
2840 /* The thread may already be stopping */
2844 mono_monitor_enter (thread->synch_lock);
2846 if (thread->interruption_requested) {
2847 mono_monitor_exit (thread->synch_lock);
2851 if (!running_managed || is_running_protected_wrapper ()) {
2852 /* Can't stop while in unmanaged code. Increase the global interruption
2853 request count. When exiting the unmanaged method the count will be
2854 checked and the thread will be interrupted. */
2856 InterlockedIncrement (&thread_interruption_requested);
2857 thread->interruption_requested = TRUE;
2858 mono_monitor_exit (thread->synch_lock);
2860 /* this will awake the thread if it is in WaitForSingleObject
2862 QueueUserAPC ((PAPCFUNC)dummy_apc, thread->handle, NULL);
2866 mono_monitor_exit (thread->synch_lock);
2867 return mono_thread_execute_interruption (thread);
2871 gboolean mono_thread_interruption_requested ()
2873 if (thread_interruption_requested) {
2874 MonoThread *thread = mono_thread_current ();
2875 /* The thread may already be stopping */
2877 return (thread->interruption_requested);
2882 static void mono_thread_interruption_checkpoint_request (gboolean bypass_abort_protection)
2884 MonoThread *thread = mono_thread_current ();
2886 /* The thread may already be stopping */
2890 if (thread->interruption_requested && (bypass_abort_protection || !is_running_protected_wrapper ())) {
2891 MonoException* exc = mono_thread_execute_interruption (thread);
2892 if (exc) mono_raise_exception (exc);
2897 * Performs the interruption of the current thread, if one has been requested,
2898 * and the thread is not running a protected wrapper.
2900 void mono_thread_interruption_checkpoint ()
2902 mono_thread_interruption_checkpoint_request (FALSE);
2906 * Performs the interruption of the current thread, if one has been requested.
2908 void mono_thread_force_interruption_checkpoint ()
2910 mono_thread_interruption_checkpoint_request (TRUE);
2914 * mono_thread_interruption_request_flag:
2916 * Returns the address of a flag that will be non-zero if an interruption has
2917 * been requested for a thread. The thread to interrupt may not be the current
2918 * thread, so an additional call to mono_thread_interruption_requested() or
2919 * mono_thread_interruption_checkpoint() is allways needed if the flag is not
2922 gint32* mono_thread_interruption_request_flag ()
2924 return &thread_interruption_requested;