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.
16 #include <mono/metadata/object.h>
17 #include <mono/metadata/appdomain.h>
18 #include <mono/metadata/profiler-private.h>
19 #include <mono/metadata/threads.h>
20 #include <mono/metadata/threadpool.h>
21 #include <mono/metadata/threads-types.h>
22 #include <mono/metadata/exception.h>
23 #include <mono/metadata/environment.h>
24 #include <mono/metadata/monitor.h>
25 #include <mono/metadata/gc-internal.h>
26 #include <mono/io-layer/io-layer.h>
28 #include <mono/os/gc_wrapper.h>
31 #undef THREAD_WAIT_DEBUG
35 guint32 (*func)(void *);
52 * The "os_handle" field of the WaitHandle class.
54 static MonoClassField *wait_handle_os_handle_field = NULL;
56 /* Controls access to the 'threads' hash table */
57 static CRITICAL_SECTION threads_mutex;
59 /* Controls access to context static data */
60 static CRITICAL_SECTION contexts_mutex;
62 /* Holds current status of static data heap */
63 static StaticDataInfo thread_static_info;
64 static StaticDataInfo context_static_info;
66 /* The hash of existing threads (key is thread ID) that need joining
69 static MonoGHashTable *threads=NULL;
71 /* The TLS key that holds the MonoObject assigned to each thread */
72 static guint32 current_object_key = -1;
74 /* function called at thread start */
75 static MonoThreadStartCB mono_thread_start_cb = NULL;
77 /* function called at thread attach */
78 static MonoThreadAttachCB mono_thread_attach_cb = NULL;
80 /* function called at thread cleanup */
81 static MonoThreadCleanupFunc mono_thread_cleanup = NULL;
83 /* function called when a new thread has been created */
84 static MonoThreadCallbacks *mono_thread_callbacks = NULL;
86 /* The TLS key that holds the LocalDataStoreSlot hash in each thread */
87 static guint32 slothash_key = -1;
89 /* The default stack size for each thread */
90 static guint32 default_stacksize = 0;
92 static void thread_adjust_static_data (MonoThread *thread);
93 static void mono_init_static_data_info (StaticDataInfo *static_data);
94 static guint32 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align);
96 /* Spin lock for InterlockedXXX 64 bit functions */
97 static CRITICAL_SECTION interlocked_mutex;
99 /* handle_store() and handle_remove() manage the array of threads that
100 * still need to be waited for when the main thread exits.
102 static void handle_store(MonoThread *thread)
104 EnterCriticalSection(&threads_mutex);
107 g_message(G_GNUC_PRETTY_FUNCTION ": thread %p ID %d", thread,
112 threads=mono_g_hash_table_new(NULL, NULL);
115 /* We don't need to duplicate thread->handle, because it is
116 * only closed when the thread object is finalized by the GC.
118 mono_g_hash_table_insert(threads, GUINT_TO_POINTER(thread->tid), thread);
119 LeaveCriticalSection(&threads_mutex);
122 static void handle_remove(guint32 tid)
125 g_message(G_GNUC_PRETTY_FUNCTION ": thread ID %d", tid);
128 EnterCriticalSection(&threads_mutex);
131 mono_g_hash_table_remove (threads, GUINT_TO_POINTER(tid));
133 LeaveCriticalSection(&threads_mutex);
135 /* Don't close the handle here, wait for the object finalizer
136 * to do it. Otherwise, the following race condition applies:
138 * 1) Thread exits (and handle_remove() closes the handle)
140 * 2) Some other handle is reassigned the same slot
142 * 3) Another thread tries to join the first thread, and
143 * blocks waiting for the reassigned handle to be signalled
144 * (which might never happen). This is possible, because the
145 * thread calling Join() still has a reference to the first
150 static void thread_cleanup (MonoThread *thread)
152 mono_monitor_try_enter ((MonoObject *)thread, INFINITE);
153 thread->state |= ThreadState_Stopped;
154 mono_monitor_exit ((MonoObject *)thread);
156 mono_profiler_thread_end (thread->tid);
157 handle_remove (thread->tid);
159 mono_thread_pop_appdomain_ref ();
161 if (mono_thread_cleanup)
162 mono_thread_cleanup (thread);
165 static guint32 start_wrapper(void *data)
167 struct StartInfo *start_info=(struct StartInfo *)data;
168 guint32 (*start_func)(void *);
171 MonoThread *thread=start_info->obj;
174 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Start wrapper",
175 GetCurrentThreadId ());
178 /* We can be sure start_info->obj->tid and
179 * start_info->obj->handle have been set, because the thread
180 * was created suspended, and these values were set before the
186 TlsSetValue (current_object_key, thread);
188 if (!mono_domain_set (start_info->domain, FALSE)) {
189 /* No point in raising an appdomain_unloaded exception here */
190 /* FIXME: Cleanup here */
194 start_func = start_info->func;
195 this = start_info->this;
197 /* This MUST be called before any managed code can be
198 * executed, as it calls the callback function that (for the
199 * jit) sets the lmf marker.
201 mono_thread_new_init (tid, &tid, start_func);
202 thread->stack_ptr = &tid;
205 g_message (G_GNUC_PRETTY_FUNCTION
206 ": (%d,%d) Setting thread stack to %p",
207 GetCurrentThreadId (), getpid (), thread->stack_ptr);
211 g_message (G_GNUC_PRETTY_FUNCTION
212 ": (%d) Setting current_object_key to %p",
213 GetCurrentThreadId (), thread);
216 mono_profiler_thread_start (tid);
218 if(thread->start_notify!=NULL) {
219 /* Let the thread that called Start() know we're
222 ReleaseSemaphore (thread->start_notify, 1, NULL);
227 /* Every thread references the appdomain which created it */
228 mono_thread_push_appdomain_ref (mono_domain_get ());
230 thread_adjust_static_data (thread);
234 /* If the thread calls ExitThread at all, this remaining code
235 * will not be executed, but the main thread will eventually
236 * call thread_cleanup() on this thread's behalf.
240 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Start wrapper terminating",
241 GetCurrentThreadId ());
244 /* Remove the reference to the thread object in the TLS data,
245 * so the thread object can be finalized. This won't be
246 * reached if the thread threw an uncaught exception, so those
247 * thread handles will stay referenced :-( (This is due to
248 * missing support for scanning thread-specific data in the
249 * Boehm GC - the io-layer keeps a GC-visible hash of pointers
252 TlsSetValue (current_object_key, NULL);
254 thread_cleanup (thread);
259 void mono_thread_new_init (guint32 tid, gpointer stack_start, gpointer func)
261 if (mono_thread_start_cb) {
262 mono_thread_start_cb (tid, stack_start, func);
265 if (mono_thread_callbacks)
266 (* mono_thread_callbacks->thread_created) (tid, stack_start, func);
269 void mono_threads_set_default_stacksize (guint32 stacksize)
271 default_stacksize = stacksize;
274 guint32 mono_threads_get_default_stacksize (void)
276 return default_stacksize;
279 void mono_thread_create (MonoDomain *domain, gpointer func, gpointer arg)
282 HANDLE thread_handle;
283 struct StartInfo *start_info;
286 thread=(MonoThread *)mono_object_new (domain,
287 mono_defaults.thread_class);
289 start_info=g_new0 (struct StartInfo, 1);
290 start_info->func = func;
291 start_info->obj = thread;
292 start_info->domain = domain;
293 start_info->this = arg;
295 /* Create suspended, so we can do some housekeeping before the thread
298 thread_handle = CreateThread(NULL, default_stacksize, start_wrapper, start_info,
299 CREATE_SUSPENDED, &tid);
301 g_message(G_GNUC_PRETTY_FUNCTION ": Started thread ID %d (handle %p)",
304 g_assert (thread_handle);
306 thread->handle=thread_handle;
309 handle_store(thread);
311 ResumeThread (thread_handle);
315 mono_thread_attach (MonoDomain *domain)
318 HANDLE thread_handle;
321 if ((thread = mono_thread_current ())) {
322 g_warning ("mono_thread_attach called for an already attached thread");
323 if (mono_thread_attach_cb) {
324 mono_thread_attach_cb (tid, &tid);
329 thread = (MonoThread *)mono_object_new (domain,
330 mono_defaults.thread_class);
332 thread_handle = GetCurrentThread ();
333 g_assert (thread_handle);
335 tid=GetCurrentThreadId ();
337 thread->handle=thread_handle;
341 g_message(G_GNUC_PRETTY_FUNCTION ": Attached thread ID %d (handle %p)",
345 handle_store(thread);
348 g_message (G_GNUC_PRETTY_FUNCTION
349 ": (%d) Setting current_object_key to %p",
350 GetCurrentThreadId (), thread);
353 TlsSetValue (current_object_key, thread);
354 mono_domain_set (domain, TRUE);
356 thread_adjust_static_data (thread);
358 if (mono_thread_attach_cb) {
359 mono_thread_attach_cb (tid, &tid);
366 ves_icall_System_Threading_ThreadPool_GetAvailableThreads (int *workerThreads, int *completionPortThreads)
372 busy = (int) InterlockedCompareExchange (&busy_worker_threads, 0, -1);
373 *workerThreads = mono_max_worker_threads - busy;
374 *completionPortThreads = 0;
378 ves_icall_System_Threading_ThreadPool_GetMaxThreads (int *workerThreads, int *completionPortThreads)
383 *workerThreads = mono_max_worker_threads;
384 *completionPortThreads = 0;
387 HANDLE ves_icall_System_Threading_Thread_Thread_internal(MonoThread *this,
390 MonoMulticastDelegate *delegate = (MonoMulticastDelegate*)start;
391 guint32 (*start_func)(void *);
392 struct StartInfo *start_info;
400 g_message(G_GNUC_PRETTY_FUNCTION
401 ": Trying to start a new thread: this (%p) start (%p)",
405 im = mono_get_delegate_invoke (start->vtable->klass);
406 if (mono_thread_callbacks)
407 start_func = (* mono_thread_callbacks->thread_start_compile_func) (im);
409 start_func = mono_compile_method (im);
411 if(start_func==NULL) {
412 g_warning(G_GNUC_PRETTY_FUNCTION
413 ": Can't locate start method!");
416 /* This is freed in start_wrapper */
417 start_info = g_new0 (struct StartInfo, 1);
418 start_info->func = start_func;
419 start_info->this = delegate;
420 start_info->obj = this;
421 start_info->domain = mono_domain_get ();
423 this->start_notify=CreateSemaphore (NULL, 0, 0x7fffffff, NULL);
424 if(this->start_notify==NULL) {
425 g_warning (G_GNUC_PRETTY_FUNCTION ": CreateSemaphore error 0x%x", GetLastError ());
429 thread=CreateThread(NULL, default_stacksize, start_wrapper, start_info,
430 CREATE_SUSPENDED, &tid);
432 g_warning(G_GNUC_PRETTY_FUNCTION
433 ": CreateThread error 0x%x", GetLastError());
440 /* Don't call handle_store() here, delay it to Start.
441 * We can't join a thread (trying to will just block
442 * forever) until it actually starts running, so don't
443 * store the handle till then.
447 g_message(G_GNUC_PRETTY_FUNCTION
448 ": Started thread ID %d (handle %p)", tid, thread);
455 void ves_icall_System_Threading_Thread_Thread_free_internal (MonoThread *this,
461 g_message (G_GNUC_PRETTY_FUNCTION ": Closing thread %p, handle %p",
465 CloseHandle (thread);
468 void ves_icall_System_Threading_Thread_Start_internal(MonoThread *this,
474 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Launching thread %p (%d)",
475 GetCurrentThreadId (), this, this->tid);
478 /* Only store the handle when the thread is about to be
479 * launched, to avoid the main thread deadlocking while trying
480 * to clean up a thread that will never be signalled.
484 if (mono_thread_callbacks)
485 (* mono_thread_callbacks->start_resume) (this->tid);
487 ResumeThread(thread);
489 if (mono_thread_callbacks)
490 (* mono_thread_callbacks->end_resume) (this->tid);
492 if(this->start_notify!=NULL) {
493 /* Wait for the thread to set up its TLS data etc, so
494 * theres no potential race condition if someone tries
495 * to look up the data believing the thread has
500 g_message(G_GNUC_PRETTY_FUNCTION
501 ": (%d) waiting for thread %p (%d) to start",
502 GetCurrentThreadId (), this, this->tid);
505 WaitForSingleObject (this->start_notify, INFINITE);
506 CloseHandle (this->start_notify);
507 this->start_notify=NULL;
511 g_message(G_GNUC_PRETTY_FUNCTION
512 ": (%d) Done launching thread %p (%d)",
513 GetCurrentThreadId (), this, this->tid);
517 void ves_icall_System_Threading_Thread_Sleep_internal(gint32 ms)
522 g_message(G_GNUC_PRETTY_FUNCTION ": Sleeping for %d ms", ms);
529 ves_icall_System_Threading_Thread_GetDomainID (void)
533 return mono_domain_get()->domain_id;
537 mono_thread_current (void)
543 /* Find the current thread object */
544 thread=TlsGetValue (current_object_key);
547 g_message (G_GNUC_PRETTY_FUNCTION ": returning %p", thread);
553 gboolean ves_icall_System_Threading_Thread_Join_internal(MonoThread *this,
554 int ms, HANDLE thread)
564 g_message (G_GNUC_PRETTY_FUNCTION ": joining thread handle %p, %d ms",
568 ret=WaitForSingleObject(thread, ms);
569 if(ret==WAIT_OBJECT_0) {
571 g_message (G_GNUC_PRETTY_FUNCTION ": join successful");
578 g_message (G_GNUC_PRETTY_FUNCTION ": join failed");
584 void ves_icall_System_Threading_Thread_SlotHash_store(MonoObject *data)
589 g_message(G_GNUC_PRETTY_FUNCTION ": Storing key %p", data);
592 /* Object location stored here */
593 TlsSetValue(slothash_key, data);
596 MonoObject *ves_icall_System_Threading_Thread_SlotHash_lookup(void)
602 data=TlsGetValue(slothash_key);
605 g_message(G_GNUC_PRETTY_FUNCTION ": Retrieved key %p", data);
611 /* FIXME: exitContext isnt documented */
612 gboolean ves_icall_System_Threading_WaitHandle_WaitAll_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext)
618 MonoObject *waitHandle;
623 numhandles = mono_array_length(mono_handles);
624 handles = g_new0(HANDLE, numhandles);
626 if (wait_handle_os_handle_field == 0) {
627 /* Get the field os_handle which will contain the actual handle */
628 klass = mono_class_from_name(mono_defaults.corlib, "System.Threading", "WaitHandle");
629 wait_handle_os_handle_field = mono_class_get_field_from_name(klass, "os_handle");
632 for(i = 0; i < numhandles; i++) {
633 waitHandle = mono_array_get(mono_handles, MonoObject*, i);
634 mono_field_get_value(waitHandle, wait_handle_os_handle_field, &handles[i]);
641 ret=WaitForMultipleObjects(numhandles, handles, TRUE, ms);
645 if(ret==WAIT_FAILED) {
646 #ifdef THREAD_WAIT_DEBUG
647 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Wait failed",
648 GetCurrentThreadId ());
651 } else if(ret==WAIT_TIMEOUT) {
652 #ifdef THREAD_WAIT_DEBUG
653 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Wait timed out",
654 GetCurrentThreadId ());
662 /* FIXME: exitContext isnt documented */
663 gint32 ves_icall_System_Threading_WaitHandle_WaitAny_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext)
669 MonoObject *waitHandle;
674 numhandles = mono_array_length(mono_handles);
675 handles = g_new0(HANDLE, numhandles);
677 if (wait_handle_os_handle_field == 0) {
678 /* Get the field os_handle which will contain the actual handle */
679 klass = mono_class_from_name(mono_defaults.corlib, "System.Threading", "WaitHandle");
680 wait_handle_os_handle_field = mono_class_get_field_from_name(klass, "os_handle");
683 for(i = 0; i < numhandles; i++) {
684 waitHandle = mono_array_get(mono_handles, MonoObject*, i);
685 mono_field_get_value(waitHandle, wait_handle_os_handle_field, &handles[i]);
692 ret=WaitForMultipleObjects(numhandles, handles, FALSE, ms);
696 #ifdef THREAD_WAIT_DEBUG
697 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) returning %d",
698 GetCurrentThreadId (), ret);
702 * These need to be here. See MSDN dos on WaitForMultipleObjects.
704 if (ret >= WAIT_OBJECT_0 && ret <= WAIT_OBJECT_0 + numhandles - 1) {
705 return ret - WAIT_OBJECT_0;
707 else if (ret >= WAIT_ABANDONED_0 && ret <= WAIT_ABANDONED_0 + numhandles - 1) {
708 return ret - WAIT_ABANDONED_0;
715 /* FIXME: exitContext isnt documented */
716 gboolean ves_icall_System_Threading_WaitHandle_WaitOne_internal(MonoObject *this, HANDLE handle, gint32 ms, gboolean exitContext)
722 #ifdef THREAD_WAIT_DEBUG
723 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) waiting for %p, %d ms",
724 GetCurrentThreadId (), handle, ms);
731 ret=WaitForSingleObject(handle, ms);
732 if(ret==WAIT_FAILED) {
733 #ifdef THREAD_WAIT_DEBUG
734 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Wait failed",
735 GetCurrentThreadId ());
738 } else if(ret==WAIT_TIMEOUT) {
739 #ifdef THREAD_WAIT_DEBUG
740 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Wait timed out",
741 GetCurrentThreadId ());
749 HANDLE ves_icall_System_Threading_Mutex_CreateMutex_internal (MonoBoolean owned, MonoString *name)
753 return(CreateMutex (NULL, owned,
754 name==NULL?NULL:mono_string_chars (name)));
757 void ves_icall_System_Threading_Mutex_ReleaseMutex_internal (HANDLE handle ) {
760 ReleaseMutex(handle);
763 HANDLE ves_icall_System_Threading_Events_CreateEvent_internal (MonoBoolean manual, MonoBoolean initial, MonoString *name) {
766 return(CreateEvent (NULL, manual, initial,
767 name==NULL?NULL:mono_string_chars (name)));
770 gboolean ves_icall_System_Threading_Events_SetEvent_internal (HANDLE handle) {
773 return (SetEvent(handle));
776 gboolean ves_icall_System_Threading_Events_ResetEvent_internal (HANDLE handle) {
779 return (ResetEvent(handle));
783 ves_icall_System_Threading_Events_CloseEvent_internal (HANDLE handle) {
786 CloseHandle (handle);
789 gint32 ves_icall_System_Threading_Interlocked_Increment_Int (gint32 *location)
793 return InterlockedIncrement (location);
796 gint64 ves_icall_System_Threading_Interlocked_Increment_Long (gint64 *location)
803 EnterCriticalSection(&interlocked_mutex);
805 lowret = InterlockedIncrement((gint32 *) location);
807 highret = InterlockedIncrement((gint32 *) location + 1);
809 highret = *((gint32 *) location + 1);
811 LeaveCriticalSection(&interlocked_mutex);
813 return (gint64) highret << 32 | (gint64) lowret;
816 gint32 ves_icall_System_Threading_Interlocked_Decrement_Int (gint32 *location)
820 return InterlockedDecrement(location);
823 gint64 ves_icall_System_Threading_Interlocked_Decrement_Long (gint64 * location)
830 EnterCriticalSection(&interlocked_mutex);
832 lowret = InterlockedDecrement((gint32 *) location);
834 highret = InterlockedDecrement((gint32 *) location + 1);
836 highret = *((gint32 *) location + 1);
838 LeaveCriticalSection(&interlocked_mutex);
840 return (gint64) highret << 32 | (gint64) lowret;
843 gint32 ves_icall_System_Threading_Interlocked_Exchange_Int (gint32 *location1, gint32 value)
847 return InterlockedExchange(location1, value);
850 MonoObject * ves_icall_System_Threading_Interlocked_Exchange_Object (MonoObject **location1, MonoObject *value)
854 return (MonoObject *) InterlockedExchangePointer((gpointer *) location1, value);
857 gfloat ves_icall_System_Threading_Interlocked_Exchange_Single (gfloat *location1, gfloat value)
859 IntFloatUnion val, ret;
864 ret.ival = InterlockedExchange((gint32 *) location1, val.ival);
869 gint32 ves_icall_System_Threading_Interlocked_CompareExchange_Int(gint32 *location1, gint32 value, gint32 comparand)
873 return InterlockedCompareExchange(location1, value, comparand);
876 MonoObject * ves_icall_System_Threading_Interlocked_CompareExchange_Object (MonoObject **location1, MonoObject *value, MonoObject *comparand)
880 return (MonoObject *) InterlockedCompareExchangePointer((gpointer *) location1, value, comparand);
883 gfloat ves_icall_System_Threading_Interlocked_CompareExchange_Single (gfloat *location1, gfloat value, gfloat comparand)
885 IntFloatUnion val, ret, cmp;
890 cmp.fval = comparand;
891 ret.ival = InterlockedCompareExchange((gint32 *) location1, val.ival, cmp.ival);
897 mono_thread_get_abort_signal (void)
907 #endif /* __MINGW32__ */
911 ves_icall_System_Threading_Thread_Abort (MonoThread *thread, MonoObject *state)
915 thread->abort_state = state;
916 thread->abort_exc = NULL;
919 g_message (G_GNUC_PRETTY_FUNCTION
920 ": (%d) Abort requested for %p (%d)", GetCurrentThreadId (),
921 thread, thread->tid);
925 g_assert_not_reached ();
927 /* fixme: store the state somewhere */
928 #ifdef PTHREAD_POINTER_ID
929 pthread_kill (GUINT_TO_POINTER(thread->tid), mono_thread_get_abort_signal ());
931 pthread_kill (thread->tid, mono_thread_get_abort_signal ());
933 #endif /* __MINGW32__ */
937 ves_icall_System_Threading_Thread_ResetAbort (void)
939 MonoThread *thread = mono_thread_current ();
943 if (!thread->abort_exc) {
944 const char *msg = "Unable to reset abort because no abort was requested";
945 mono_raise_exception (mono_get_exception_thread_state (msg));
947 thread->abort_exc = NULL;
948 thread->abort_state = NULL;
953 ves_icall_System_Threading_Thread_VolatileRead1 (void *ptr)
955 return *((volatile gint8 *) (ptr));
959 ves_icall_System_Threading_Thread_VolatileRead2 (void *ptr)
961 return *((volatile gint16 *) (ptr));
965 ves_icall_System_Threading_Thread_VolatileRead4 (void *ptr)
967 return *((volatile gint32 *) (ptr));
971 ves_icall_System_Threading_Thread_VolatileRead8 (void *ptr)
973 return *((volatile gint64 *) (ptr));
977 ves_icall_System_Threading_Thread_VolatileReadIntPtr (void *ptr)
979 return (void *) *((volatile void **) ptr);
983 ves_icall_System_Threading_Thread_VolatileWrite1 (void *ptr, gint8 value)
985 *((volatile gint8 *) ptr) = value;
989 ves_icall_System_Threading_Thread_VolatileWrite2 (void *ptr, gint16 value)
991 *((volatile gint16 *) ptr) = value;
995 ves_icall_System_Threading_Thread_VolatileWrite4 (void *ptr, gint32 value)
997 *((volatile gint32 *) ptr) = value;
1001 ves_icall_System_Threading_Thread_VolatileWrite8 (void *ptr, gint64 value)
1003 *((volatile gint64 *) ptr) = value;
1007 ves_icall_System_Threading_Thread_VolatileWriteIntPtr (void *ptr, void *value)
1009 *((volatile void **) ptr) = value;
1012 void mono_thread_init (MonoThreadStartCB start_cb,
1013 MonoThreadAttachCB attach_cb)
1015 InitializeCriticalSection(&threads_mutex);
1016 InitializeCriticalSection(&interlocked_mutex);
1017 InitializeCriticalSection(&contexts_mutex);
1019 mono_init_static_data_info (&thread_static_info);
1020 mono_init_static_data_info (&context_static_info);
1022 current_object_key=TlsAlloc();
1024 g_message (G_GNUC_PRETTY_FUNCTION ": Allocated current_object_key %d",
1025 current_object_key);
1028 mono_thread_start_cb = start_cb;
1029 mono_thread_attach_cb = attach_cb;
1031 slothash_key=TlsAlloc();
1033 /* Get a pseudo handle to the current process. This is just a
1034 * kludge so that wapi can build a process handle if needed.
1035 * As a pseudo handle is returned, we don't need to clean
1038 GetCurrentProcess ();
1042 mono_threads_install_cleanup (MonoThreadCleanupFunc func)
1044 mono_thread_cleanup = func;
1047 void mono_install_thread_callbacks (MonoThreadCallbacks *callbacks)
1049 mono_thread_callbacks = callbacks;
1053 static void print_tids (gpointer key, gpointer value, gpointer user)
1055 g_message ("Waiting for: %d", GPOINTER_TO_UINT(key));
1061 HANDLE handles[MAXIMUM_WAIT_OBJECTS];
1062 MonoThread *threads[MAXIMUM_WAIT_OBJECTS];
1066 static void wait_for_tids (struct wait_data *wait, guint32 timeout)
1071 g_message(G_GNUC_PRETTY_FUNCTION
1072 ": %d threads to wait for in this batch", wait->num);
1075 ret=WaitForMultipleObjects(wait->num, wait->handles, TRUE, timeout);
1076 if(ret==WAIT_FAILED) {
1077 /* See the comment in build_wait_tids() */
1079 g_message (G_GNUC_PRETTY_FUNCTION ": Wait failed");
1085 for(i=0; i<wait->num; i++) {
1086 guint32 tid=wait->threads[i]->tid;
1088 if(mono_g_hash_table_lookup (threads, GUINT_TO_POINTER(tid))!=NULL) {
1089 /* This thread must have been killed, because
1090 * it hasn't cleaned itself up. (It's just
1091 * possible that the thread exited before the
1092 * parent thread had a chance to store the
1093 * handle, and now there is another pointer to
1094 * the already-exited thread stored. In this
1095 * case, we'll just get two
1096 * mono_profiler_thread_end() calls for the
1101 g_message (G_GNUC_PRETTY_FUNCTION
1102 ": cleaning up after thread %d", tid);
1104 thread_cleanup (wait->threads[i]);
1109 static void build_wait_tids (gpointer key, gpointer value, gpointer user)
1111 struct wait_data *wait=(struct wait_data *)user;
1113 if(wait->num<MAXIMUM_WAIT_OBJECTS) {
1114 MonoThread *thread=(MonoThread *)value;
1116 /* BUG: For now we just ignore background threads, we should abort them
1118 if (thread->state & ThreadState_Background)
1119 return; /* just leave, ignore */
1121 if (mono_gc_is_finalizer_thread (thread))
1124 wait->handles[wait->num]=thread->handle;
1125 wait->threads[wait->num]=thread;
1128 /* Just ignore the rest, we can't do anything with
1134 void mono_thread_manage (void)
1136 struct wait_data *wait=g_new0 (struct wait_data, 1);
1138 /* join each thread that's still running */
1140 g_message(G_GNUC_PRETTY_FUNCTION ": Joining each running thread...");
1145 g_message(G_GNUC_PRETTY_FUNCTION ": No threads");
1151 EnterCriticalSection (&threads_mutex);
1153 g_message(G_GNUC_PRETTY_FUNCTION
1154 ":There are %d threads to join",
1155 mono_g_hash_table_size (threads));
1156 mono_g_hash_table_foreach (threads, print_tids, NULL);
1160 mono_g_hash_table_foreach (threads, build_wait_tids, wait);
1162 LeaveCriticalSection (&threads_mutex);
1164 /* Something to wait for */
1165 wait_for_tids (wait, INFINITE);
1167 } while(wait->num>0);
1171 EnterCriticalSection(&threads_mutex);
1173 mono_g_hash_table_destroy(threads);
1176 LeaveCriticalSection(&threads_mutex);
1179 static void terminate_thread (gpointer key, gpointer value, gpointer user)
1181 MonoThread *thread=(MonoThread *)value;
1182 guint32 self=GPOINTER_TO_UINT (user);
1184 if(thread->tid!=self) {
1185 /*TerminateThread (thread->handle, -1);*/
1189 void mono_thread_abort_all_other_threads (void)
1191 guint32 self=GetCurrentThreadId ();
1193 EnterCriticalSection (&threads_mutex);
1195 g_message(G_GNUC_PRETTY_FUNCTION ":There are %d threads to abort",
1196 mono_g_hash_table_size (threads));
1197 mono_g_hash_table_foreach (threads, print_tids, NULL);
1200 mono_g_hash_table_foreach (threads, terminate_thread,
1201 GUINT_TO_POINTER (self));
1203 LeaveCriticalSection (&threads_mutex);
1207 * mono_thread_push_appdomain_ref:
1209 * Register that the current thread may have references to objects in domain
1210 * @domain on its stack. Each call to this function should be paired with a
1211 * call to pop_appdomain_ref.
1214 mono_thread_push_appdomain_ref (MonoDomain *domain)
1216 MonoThread *thread = mono_thread_current ();
1219 //printf ("PUSH REF: %p -> %s.\n", thread, domain->friendly_name);
1220 EnterCriticalSection (&threads_mutex);
1221 thread->appdomain_refs = g_slist_prepend (thread->appdomain_refs, domain);
1222 LeaveCriticalSection (&threads_mutex);
1227 mono_thread_pop_appdomain_ref (void)
1229 MonoThread *thread = mono_thread_current ();
1232 //printf ("POP REF: %p -> %s.\n", thread, ((MonoDomain*)(thread->appdomain_refs->data))->friendly_name);
1233 EnterCriticalSection (&threads_mutex);
1234 thread->appdomain_refs = g_slist_remove (thread->appdomain_refs, thread->appdomain_refs->data);
1235 LeaveCriticalSection (&threads_mutex);
1240 mono_thread_has_appdomain_ref (MonoThread *thread, MonoDomain *domain)
1243 EnterCriticalSection (&threads_mutex);
1244 res = g_slist_find (thread->appdomain_refs, domain) != NULL;
1245 LeaveCriticalSection (&threads_mutex);
1249 typedef struct abort_appdomain_data {
1250 struct wait_data wait;
1252 } abort_appdomain_data;
1255 abort_appdomain_thread (gpointer key, gpointer value, gpointer user_data)
1257 MonoThread *thread = (MonoThread*)value;
1258 abort_appdomain_data *data = (abort_appdomain_data*)user_data;
1259 MonoDomain *domain = data->domain;
1261 if (mono_thread_has_appdomain_ref (thread, domain)) {
1262 //printf ("ABORTING THREAD %p BECAUSE IT REFERENCES DOMAIN %s.\n", thread, domain->friendly_name);
1263 ves_icall_System_Threading_Thread_Abort (thread, (MonoObject*)domain->domain);
1265 if(data->wait.num<MAXIMUM_WAIT_OBJECTS) {
1266 data->wait.handles [data->wait.num] = thread->handle;
1267 data->wait.threads [data->wait.num] = thread;
1270 /* Just ignore the rest, we can't do anything with
1278 * mono_threads_abort_appdomain_threads:
1280 * Abort threads which has references to the given appdomain.
1283 mono_threads_abort_appdomain_threads (MonoDomain *domain, int timeout)
1285 abort_appdomain_data user_data;
1288 //printf ("ABORT BEGIN.\n");
1290 start_time = GetTickCount ();
1292 EnterCriticalSection (&threads_mutex);
1294 user_data.domain = domain;
1295 user_data.wait.num = 0;
1296 mono_g_hash_table_foreach (threads, abort_appdomain_thread, &user_data);
1297 LeaveCriticalSection (&threads_mutex);
1299 if (user_data.wait.num > 0)
1300 wait_for_tids (&user_data.wait, timeout);
1302 /* Update remaining time */
1303 timeout -= GetTickCount () - start_time;
1304 start_time = GetTickCount ();
1309 while (user_data.wait.num > 0);
1311 //printf ("ABORT DONE.\n");
1317 * mono_thread_get_pending_exception:
1319 * Return an exception which needs to be raised when leaving a catch clause.
1320 * This is used for undeniable exception propagation.
1323 mono_thread_get_pending_exception (void)
1325 MonoThread *thread = mono_thread_current ();
1327 MONO_ARCH_SAVE_REGS;
1329 if (thread && thread->abort_exc) {
1331 * FIXME: Clear the abort exception and return an AppDomainUnloaded
1332 * exception if the thread no longer references a dying appdomain.
1334 thread->abort_exc->trace_ips = NULL;
1335 thread->abort_exc->stack_trace = NULL;
1336 return thread->abort_exc;
1342 #define NUM_STATIC_DATA_IDX 8
1343 static const int static_data_size [NUM_STATIC_DATA_IDX] = {
1344 1024, 4096, 16384, 65536, 262144, 1048576, 4194304, 16777216
1349 * mono_alloc_static_data
1351 * Allocate memory blocks for storing threads or context static data
1354 mono_alloc_static_data (gpointer **static_data_ptr, guint32 offset)
1356 guint idx = (offset >> 24) - 1;
1359 gpointer* static_data = *static_data_ptr;
1362 static_data = GC_MALLOC (static_data_size [0]);
1364 static_data = g_malloc0 (static_data_size [0]);
1366 *static_data_ptr = static_data;
1367 static_data [0] = static_data;
1370 for (i = 1; i < idx; ++i) {
1371 if (static_data [i])
1374 static_data [i] = GC_MALLOC (static_data_size [i]);
1376 static_data [i] = g_malloc0 (static_data_size [i]);
1382 * mono_init_static_data_info
1384 * Initializes static data counters
1386 static void mono_init_static_data_info (StaticDataInfo *static_data)
1388 static_data->idx = 0;
1389 static_data->offset = 0;
1393 * mono_alloc_static_data_slot
1395 * Generates an offset for static data. static_data contains the counters
1396 * used to generate it.
1399 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align)
1403 if (!static_data->idx && !static_data->offset) {
1405 * we use the first chunk of the first allocation also as
1406 * an array for the rest of the data
1408 static_data->offset = sizeof (gpointer) * NUM_STATIC_DATA_IDX;
1410 static_data->offset += align - 1;
1411 static_data->offset &= ~(align - 1);
1412 if (static_data->offset + size >= static_data_size [static_data->idx]) {
1413 static_data->idx ++;
1414 g_assert (size <= static_data_size [static_data->idx]);
1416 * massive unloading and reloading of domains with thread-static
1417 * data may eventually exceed the allocated storage...
1418 * Need to check what the MS runtime does in that case.
1419 * Note that for each appdomain, we need to allocate a separate
1420 * thread data slot for security reasons. We could keep track
1421 * of the slots per-domain and when the domain is unloaded
1422 * out the slots on a sort of free list.
1424 g_assert (static_data->idx < NUM_STATIC_DATA_IDX);
1425 static_data->offset = 0;
1427 offset = static_data->offset | ((static_data->idx + 1) << 24);
1428 static_data->offset += size;
1433 * ensure thread static fields already allocated are valid for thread
1434 * This function is called when a thread is created or on thread attach.
1437 thread_adjust_static_data (MonoThread *thread)
1441 EnterCriticalSection (&threads_mutex);
1442 if (thread_static_info.offset || thread_static_info.idx > 0) {
1443 /* get the current allocated size */
1444 offset = thread_static_info.offset | ((thread_static_info.idx + 1) << 24);
1445 mono_alloc_static_data (&(thread->static_data), offset);
1447 LeaveCriticalSection (&threads_mutex);
1451 alloc_thread_static_data_helper (gpointer key, gpointer value, gpointer user)
1453 MonoThread *thread = value;
1454 guint32 offset = GPOINTER_TO_UINT (user);
1456 mono_alloc_static_data (&(thread->static_data), offset);
1460 * The offset for a special static variable is composed of three parts:
1461 * a bit that indicates the type of static data (0:thread, 1:context),
1462 * an index in the array of chunks of memory for the thread (thread->static_data)
1463 * and an offset in that chunk of mem. This allows allocating less memory in the
1468 mono_alloc_special_static_data (guint32 static_type, guint32 size, guint32 align)
1471 if (static_type == SPECIAL_STATIC_THREAD)
1473 EnterCriticalSection (&threads_mutex);
1474 offset = mono_alloc_static_data_slot (&thread_static_info, size, align);
1475 mono_g_hash_table_foreach (threads, alloc_thread_static_data_helper, GUINT_TO_POINTER (offset));
1476 LeaveCriticalSection (&threads_mutex);
1480 g_assert (static_type == SPECIAL_STATIC_CONTEXT);
1481 EnterCriticalSection (&contexts_mutex);
1482 offset = mono_alloc_static_data_slot (&context_static_info, size, align);
1483 LeaveCriticalSection (&contexts_mutex);
1484 offset |= 0x80000000; // Set the high bit to indicate context static data
1490 mono_get_special_static_data (guint32 offset)
1492 // The high bit means either thread (0) or static (1) data.
1494 guint32 static_type = (offset & 0x80000000);
1497 offset &= 0x7fffffff;
1498 idx = (offset >> 24) - 1;
1500 if (static_type == 0)
1502 MonoThread *thread = mono_thread_current ();
1503 return ((char*) thread->static_data [idx]) + (offset & 0xffffff);
1507 // Allocate static data block under demand, since we don't have a list
1509 MonoAppContext *context = mono_context_get ();
1510 if (!context->static_data || !context->static_data [idx]) {
1511 EnterCriticalSection (&contexts_mutex);
1512 mono_alloc_static_data (&(context->static_data), offset);
1513 LeaveCriticalSection (&contexts_mutex);
1515 return ((char*) context->static_data [idx]) + (offset & 0xffffff);
1519 static void gc_stop_world (gpointer key, gpointer value, gpointer user)
1521 MonoThread *thread=(MonoThread *)value;
1522 guint32 self=GPOINTER_TO_UINT (user);
1525 g_message (G_GNUC_PRETTY_FUNCTION ": %d - %d", self, thread->tid);
1528 if(thread->tid==self)
1531 SuspendThread (thread->handle);
1534 void mono_gc_stop_world (void)
1536 guint32 self=GetCurrentThreadId ();
1539 g_message (G_GNUC_PRETTY_FUNCTION ": %d - %p", self, threads);
1542 EnterCriticalSection (&threads_mutex);
1544 if (threads != NULL)
1545 mono_g_hash_table_foreach (threads, gc_stop_world, GUINT_TO_POINTER (self));
1547 LeaveCriticalSection (&threads_mutex);
1550 static void gc_start_world (gpointer key, gpointer value, gpointer user)
1552 MonoThread *thread=(MonoThread *)value;
1553 guint32 self=GPOINTER_TO_UINT (user);
1556 g_message (G_GNUC_PRETTY_FUNCTION ": %d - %d", self, thread->tid);
1559 if(thread->tid==self)
1562 ResumeThread (thread->handle);
1565 void mono_gc_start_world (void)
1567 guint32 self=GetCurrentThreadId ();
1570 g_message (G_GNUC_PRETTY_FUNCTION ": %d - %p", self, threads);
1573 EnterCriticalSection (&threads_mutex);
1575 if (threads != NULL)
1576 mono_g_hash_table_foreach (threads, gc_start_world, GUINT_TO_POINTER (self));
1578 LeaveCriticalSection (&threads_mutex);
1581 #ifdef WITH_INCLUDED_LIBGC
1583 static void gc_push_all_stacks (gpointer key, gpointer value, gpointer user)
1585 MonoThread *thread=(MonoThread *)value;
1586 guint32 *selfp=(guint32 *)user, self = *selfp;
1589 g_message (G_GNUC_PRETTY_FUNCTION ": %d - %d - %p", self, thread->tid, thread->stack_ptr);
1592 if(thread->tid==self) {
1594 g_message (G_GNUC_PRETTY_FUNCTION ": %p - %p", selfp, thread->stack_ptr);
1596 GC_push_all_stack (selfp, thread->stack_ptr);
1600 #ifdef PLATFORM_WIN32
1601 GC_win32_push_thread_stack (thread->handle, thread->stack_ptr);
1603 mono_wapi_push_thread_stack (thread->handle, thread->stack_ptr);
1607 void mono_gc_push_all_stacks (void)
1609 guint32 self=GetCurrentThreadId ();
1612 g_message (G_GNUC_PRETTY_FUNCTION ": %d - %p", self, threads);
1615 EnterCriticalSection (&threads_mutex);
1617 if (threads != NULL)
1618 mono_g_hash_table_foreach (threads, gc_push_all_stacks, &self);
1620 LeaveCriticalSection (&threads_mutex);
1623 #endif /* WITH_INCLUDED_LIBGC */