2 * metadata/gc.c: GC icalls.
4 * Author: Paolo Molaro <lupus@ximian.com>
6 * Copyright 2002-2003 Ximian, Inc (http://www.ximian.com)
7 * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
8 * Copyright 2012 Xamarin Inc (http://www.xamarin.com)
9 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
16 #include <mono/metadata/gc-internals.h>
17 #include <mono/metadata/mono-gc.h>
18 #include <mono/metadata/threads.h>
19 #include <mono/metadata/tabledefs.h>
20 #include <mono/metadata/exception.h>
21 #include <mono/metadata/profiler-private.h>
22 #include <mono/metadata/domain-internals.h>
23 #include <mono/metadata/class-internals.h>
24 #include <mono/metadata/metadata-internals.h>
25 #include <mono/metadata/mono-mlist.h>
26 #include <mono/metadata/threads-types.h>
27 #include <mono/metadata/threadpool-ms.h>
28 #include <mono/sgen/sgen-conf.h>
29 #include <mono/sgen/sgen-gc.h>
30 #include <mono/utils/mono-logger-internals.h>
31 #include <mono/metadata/gc-internals.h>
32 #include <mono/metadata/marshal.h> /* for mono_delegate_free_ftnptr () */
33 #include <mono/metadata/attach.h>
34 #include <mono/metadata/console-io.h>
35 #include <mono/utils/mono-os-semaphore.h>
36 #include <mono/utils/mono-memory-model.h>
37 #include <mono/utils/mono-counters.h>
38 #include <mono/utils/mono-time.h>
39 #include <mono/utils/dtrace.h>
40 #include <mono/utils/mono-threads.h>
41 #include <mono/utils/atomic.h>
42 #include <mono/utils/mono-coop-semaphore.h>
48 typedef struct DomainFinalizationReq {
51 } DomainFinalizationReq;
53 static gboolean gc_disabled = FALSE;
55 static gboolean finalizing_root_domain = FALSE;
57 gboolean log_finalizers = FALSE;
58 gboolean mono_do_not_finalize = FALSE;
59 gchar **mono_do_not_finalize_class_names = NULL;
61 #define mono_finalizer_lock() mono_coop_mutex_lock (&finalizer_mutex)
62 #define mono_finalizer_unlock() mono_coop_mutex_unlock (&finalizer_mutex)
63 static MonoCoopMutex finalizer_mutex;
64 static MonoCoopMutex reference_queue_mutex;
66 static GSList *domains_to_finalize= NULL;
67 static MonoMList *threads_to_finalize = NULL;
69 static gboolean finalizer_thread_exited;
70 /* Uses finalizer_mutex */
71 static MonoCoopCond exited_cond;
73 static MonoInternalThread *gc_thread;
75 static void object_register_finalizer (MonoObject *obj, void (*callback)(void *, void*), MonoError *error);
77 static void reference_queue_proccess_all (void);
78 static void mono_reference_queue_cleanup (void);
79 static void reference_queue_clear_for_domain (MonoDomain *domain);
80 static HANDLE pending_done_event;
83 guarded_wait (HANDLE handle, guint32 timeout, gboolean alertable)
87 MONO_PREPARE_BLOCKING;
88 result = WaitForSingleObjectEx (handle, timeout, alertable);
95 add_thread_to_finalize (MonoInternalThread *thread)
97 mono_finalizer_lock ();
98 if (!threads_to_finalize)
99 MONO_GC_REGISTER_ROOT_SINGLE (threads_to_finalize, MONO_ROOT_SOURCE_FINALIZER_QUEUE, "finalizable threads list");
100 threads_to_finalize = mono_mlist_append (threads_to_finalize, (MonoObject*)thread);
101 mono_finalizer_unlock ();
104 static gboolean suspend_finalizers = FALSE;
106 * actually, we might want to queue the finalize requests in a separate thread,
107 * but we need to be careful about the execution domain of the thread...
110 mono_gc_run_finalize (void *obj, void *data)
113 MonoObject *exc = NULL;
118 MonoMethod* finalizer = NULL;
119 MonoDomain *caller_domain = mono_domain_get ();
121 RuntimeInvokeFunction runtime_invoke;
123 // This function is called from the innards of the GC, so our best alternative for now is to do polling here
124 mono_threads_safepoint ();
126 o = (MonoObject*)((char*)obj + GPOINTER_TO_UINT (data));
128 if (mono_do_not_finalize) {
129 if (!mono_do_not_finalize_class_names)
132 size_t namespace_len = strlen (o->vtable->klass->name_space);
133 for (int i = 0; mono_do_not_finalize_class_names [i]; ++i) {
134 const char *name = mono_do_not_finalize_class_names [i];
135 if (strncmp (name, o->vtable->klass->name_space, namespace_len))
137 if (name [namespace_len] != '.')
139 if (strcmp (name + namespace_len + 1, o->vtable->klass->name))
146 g_log ("mono-gc-finalizers", G_LOG_LEVEL_DEBUG, "<%s at %p> Starting finalizer checks.", o->vtable->klass->name, o);
148 if (suspend_finalizers)
151 domain = o->vtable->domain;
154 mono_domain_finalizers_lock (domain);
156 o2 = (MonoObject *)g_hash_table_lookup (domain->finalizable_objects_hash, o);
158 mono_domain_finalizers_unlock (domain);
161 /* Already finalized somehow */
165 /* make sure the finalizer is not called again if the object is resurrected */
166 object_register_finalizer ((MonoObject *)obj, NULL, &error);
167 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
170 g_log ("mono-gc-finalizers", G_LOG_LEVEL_MESSAGE, "<%s at %p> Registered finalizer as processed.", o->vtable->klass->name, o);
172 if (o->vtable->klass == mono_defaults.internal_thread_class) {
173 MonoInternalThread *t = (MonoInternalThread*)o;
175 if (mono_gc_is_finalizer_internal_thread (t))
176 /* Avoid finalizing ourselves */
179 if (t->threadpool_thread && finalizing_root_domain) {
180 /* Don't finalize threadpool threads when
181 shutting down - they're finalized when the
182 threadpool shuts down. */
183 add_thread_to_finalize (t);
188 if (o->vtable->klass->image == mono_defaults.corlib && !strcmp (o->vtable->klass->name, "DynamicMethod") && finalizing_root_domain) {
190 * These can't be finalized during unloading/shutdown, since that would
191 * free the native code which can still be referenced by other
193 * FIXME: This is not perfect, objects dying at the same time as
194 * dynamic methods can still reference them even when !shutdown.
199 if (mono_runtime_get_no_exec ())
202 /* speedup later... and use a timeout */
203 /* g_print ("Finalize run on %p %s.%s\n", o, mono_object_class (o)->name_space, mono_object_class (o)->name); */
205 /* Use _internal here, since this thread can enter a doomed appdomain */
206 mono_domain_set_internal (mono_object_domain (o));
208 /* delegates that have a native function pointer allocated are
209 * registered for finalization, but they don't have a Finalize
210 * method, because in most cases it's not needed and it's just a waste.
212 if (o->vtable->klass->delegate) {
213 MonoDelegate* del = (MonoDelegate*)o;
214 if (del->delegate_trampoline)
215 mono_delegate_free_ftnptr ((MonoDelegate*)o);
216 mono_domain_set_internal (caller_domain);
220 finalizer = mono_class_get_finalizer (o->vtable->klass);
222 /* If object has a CCW but has no finalizer, it was only
223 * registered for finalization in order to free the CCW.
224 * Else it needs the regular finalizer run.
225 * FIXME: what to do about ressurection and suppression
226 * of finalizer on object with CCW.
228 if (mono_marshal_free_ccw (o) && !finalizer) {
229 mono_domain_set_internal (caller_domain);
234 * To avoid the locking plus the other overhead of mono_runtime_invoke_checked (),
235 * create and precompile a wrapper which calls the finalize method using
239 g_log ("mono-gc-finalizers", G_LOG_LEVEL_MESSAGE, "<%s at %p> Compiling finalizer.", o->vtable->klass->name, o);
241 if (!domain->finalize_runtime_invoke) {
242 MonoMethod *invoke = mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE);
244 domain->finalize_runtime_invoke = mono_compile_method (invoke);
247 runtime_invoke = (RuntimeInvokeFunction)domain->finalize_runtime_invoke;
249 mono_runtime_class_init_full (o->vtable, &error);
250 mono_error_raise_exception (&error); /* FIXME don't raise here */
252 if (G_UNLIKELY (MONO_GC_FINALIZE_INVOKE_ENABLED ())) {
253 MONO_GC_FINALIZE_INVOKE ((unsigned long)o, mono_object_get_size (o),
254 o->vtable->klass->name_space, o->vtable->klass->name);
258 g_log ("mono-gc-finalizers", G_LOG_LEVEL_MESSAGE, "<%s at %p> Calling finalizer.", o->vtable->klass->name, o);
260 runtime_invoke (o, NULL, &exc, NULL);
263 g_log ("mono-gc-finalizers", G_LOG_LEVEL_MESSAGE, "<%s at %p> Returned from finalizer.", o->vtable->klass->name, o);
266 mono_thread_internal_unhandled_exception (exc);
268 mono_domain_set_internal (caller_domain);
272 mono_gc_finalize_threadpool_threads (void)
275 while (threads_to_finalize) {
276 MonoInternalThread *thread = (MonoInternalThread*) mono_mlist_get_data (threads_to_finalize);
278 /* Force finalization of the thread. */
279 thread->threadpool_thread = FALSE;
280 mono_object_register_finalizer ((MonoObject*)thread, &error);
281 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
283 mono_gc_run_finalize (thread, NULL);
285 threads_to_finalize = mono_mlist_next (threads_to_finalize);
290 mono_gc_out_of_memory (size_t size)
293 * we could allocate at program startup some memory that we could release
294 * back to the system at this point if we're really low on memory (ie, size is
295 * lower than the memory we set apart)
297 mono_raise_exception (mono_domain_get ()->out_of_memory_ex);
303 * Some of our objects may point to a different address than the address returned by GC_malloc()
304 * (because of the GetHashCode hack), but we need to pass the real address to register_finalizer.
305 * This also means that in the callback we need to adjust the pointer to get back the real
307 * We also need to be consistent in the use of the GC_debug* variants of malloc and register_finalizer,
308 * since that, too, can cause the underlying pointer to be offset.
311 object_register_finalizer (MonoObject *obj, void (*callback)(void *, void*), MonoError *error)
315 mono_error_init (error);
318 mono_error_set_argument_null (error, "obj", "");
322 domain = obj->vtable->domain;
325 if (mono_domain_is_unloading (domain) && (callback != NULL))
327 * Can't register finalizers in a dying appdomain, since they
328 * could be invoked after the appdomain has been unloaded.
332 mono_domain_finalizers_lock (domain);
335 g_hash_table_insert (domain->finalizable_objects_hash, obj, obj);
337 g_hash_table_remove (domain->finalizable_objects_hash, obj);
339 mono_domain_finalizers_unlock (domain);
341 mono_gc_register_for_finalization (obj, callback);
342 #elif defined(HAVE_SGEN_GC)
344 * If we register finalizers for domains that are unloading we might
345 * end up running them while or after the domain is being cleared, so
346 * the objects will not be valid anymore.
348 if (!mono_domain_is_unloading (domain))
349 mono_gc_register_for_finalization (obj, callback);
354 * mono_object_register_finalizer:
355 * @obj: object to register
357 * Records that object @obj has a finalizer, this will call the
358 * Finalize method when the garbage collector disposes the object.
362 mono_object_register_finalizer (MonoObject *obj, MonoError *error)
364 /* g_print ("Registered finalizer on %p %s.%s\n", obj, mono_object_class (obj)->name_space, mono_object_class (obj)->name); */
365 object_register_finalizer (obj, mono_gc_run_finalize, error);
369 * mono_domain_finalize:
370 * @domain: the domain to finalize
371 * @timeout: msects to wait for the finalization to complete, -1 to wait indefinitely
373 * Request finalization of all finalizable objects inside @domain. Wait
374 * @timeout msecs for the finalization to complete.
376 * Returns: TRUE if succeeded, FALSE if there was a timeout
380 mono_domain_finalize (MonoDomain *domain, guint32 timeout)
382 DomainFinalizationReq *req;
385 MonoInternalThread *thread = mono_thread_internal_current ();
387 #if defined(__native_client__)
391 if (mono_thread_internal_current () == gc_thread)
392 /* We are called from inside a finalizer, not much we can do here */
396 * No need to create another thread 'cause the finalizer thread
397 * is still working and will take care of running the finalizers
403 /* We don't support domain finalization without a GC */
404 if (mono_gc_is_null ())
407 mono_gc_collect (mono_gc_max_generation ());
409 done_event = CreateEvent (NULL, TRUE, FALSE, NULL);
410 if (done_event == NULL) {
414 req = g_new0 (DomainFinalizationReq, 1);
415 req->domain = domain;
416 req->done_event = done_event;
418 if (domain == mono_get_root_domain ())
419 finalizing_root_domain = TRUE;
421 mono_finalizer_lock ();
423 domains_to_finalize = g_slist_append (domains_to_finalize, req);
425 mono_finalizer_unlock ();
427 /* Tell the finalizer thread to finalize this appdomain */
428 mono_gc_finalize_notify ();
434 res = guarded_wait (done_event, timeout, TRUE);
435 /* printf ("WAIT RES: %d.\n", res); */
437 if (res == WAIT_IO_COMPLETION) {
438 if ((thread->state & (ThreadState_StopRequested | ThreadState_SuspendRequested)) != 0)
440 } else if (res == WAIT_TIMEOUT) {
441 /* We leak the handle here */
448 CloseHandle (done_event);
450 if (domain == mono_get_root_domain ()) {
451 mono_threadpool_ms_cleanup ();
452 mono_gc_finalize_threadpool_threads ();
459 ves_icall_System_GC_InternalCollect (int generation)
461 mono_gc_collect (generation);
465 ves_icall_System_GC_GetTotalMemory (MonoBoolean forceCollection)
468 mono_gc_collect (mono_gc_max_generation ());
469 return mono_gc_get_used_size ();
473 ves_icall_System_GC_KeepAlive (MonoObject *obj)
481 ves_icall_System_GC_ReRegisterForFinalize (MonoObject *obj)
485 MONO_CHECK_ARG_NULL (obj,);
487 object_register_finalizer (obj, mono_gc_run_finalize, &error);
488 mono_error_set_pending_exception (&error);
492 ves_icall_System_GC_SuppressFinalize (MonoObject *obj)
496 MONO_CHECK_ARG_NULL (obj,);
498 /* delegates have no finalizers, but we register them to deal with the
499 * unmanaged->managed trampoline. We don't let the user suppress it
500 * otherwise we'd leak it.
502 if (obj->vtable->klass->delegate)
505 /* FIXME: Need to handle case where obj has COM Callable Wrapper
506 * generated for it that needs cleaned up, but user wants to suppress
507 * their derived object finalizer. */
509 object_register_finalizer (obj, NULL, &error);
510 mono_error_set_pending_exception (&error);
514 ves_icall_System_GC_WaitForPendingFinalizers (void)
516 if (mono_gc_is_null ())
519 if (!mono_gc_pending_finalizers ())
522 if (mono_thread_internal_current () == gc_thread)
523 /* Avoid deadlocks */
527 If the finalizer thread is not live, lets pretend no finalizers are pending since the current thread might
528 be the one responsible for starting it up.
530 if (gc_thread == NULL)
533 ResetEvent (pending_done_event);
534 mono_gc_finalize_notify ();
535 /* g_print ("Waiting for pending finalizers....\n"); */
536 guarded_wait (pending_done_event, INFINITE, TRUE);
537 /* g_print ("Done pending....\n"); */
541 ves_icall_System_GC_register_ephemeron_array (MonoObject *array)
544 if (!mono_gc_ephemeron_array_add (array)) {
545 mono_set_pending_exception (mono_object_domain (array)->out_of_memory_ex);
552 ves_icall_System_GC_get_ephemeron_tombstone (void)
554 return mono_domain_get ()->ephemeron_tombstone;
558 ves_icall_System_GCHandle_GetTarget (guint32 handle)
560 return mono_gchandle_get_target (handle);
564 * if type == -1, change the target of the handle, otherwise allocate a new handle.
567 ves_icall_System_GCHandle_GetTargetHandle (MonoObject *obj, guint32 handle, gint32 type)
570 mono_gchandle_set_target (handle, obj);
571 /* the handle doesn't change */
576 return mono_gchandle_new_weakref (obj, FALSE);
577 case HANDLE_WEAK_TRACK:
578 return mono_gchandle_new_weakref (obj, TRUE);
580 return mono_gchandle_new (obj, FALSE);
582 return mono_gchandle_new (obj, TRUE);
584 g_assert_not_reached ();
590 ves_icall_System_GCHandle_FreeHandle (guint32 handle)
592 mono_gchandle_free (handle);
596 ves_icall_System_GCHandle_GetAddrOfPinnedObject (guint32 handle)
600 if (MONO_GC_HANDLE_TYPE (handle) != HANDLE_PINNED)
602 obj = mono_gchandle_get_target (handle);
604 MonoClass *klass = mono_object_class (obj);
605 if (klass == mono_defaults.string_class) {
606 return mono_string_chars ((MonoString*)obj);
607 } else if (klass->rank) {
608 return mono_array_addr ((MonoArray*)obj, char, 0);
610 /* the C# code will check and throw the exception */
611 /* FIXME: missing !klass->blittable test, see bug #61134 */
612 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
614 return (char*)obj + sizeof (MonoObject);
621 mono_gc_GCHandle_CheckCurrentDomain (guint32 gchandle)
623 return mono_gchandle_is_in_domain (gchandle, mono_domain_get ());
626 static MonoCoopSem finalizer_sem;
627 static volatile gboolean finished=FALSE;
630 mono_gc_finalize_notify (void)
633 g_message ( "%s: prodding finalizer", __func__);
636 if (mono_gc_is_null ())
639 mono_coop_sem_post (&finalizer_sem);
645 collect_objects (gpointer key, gpointer value, gpointer user_data)
647 GPtrArray *arr = (GPtrArray*)user_data;
648 g_ptr_array_add (arr, key);
654 * finalize_domain_objects:
656 * Run the finalizers of all finalizable objects in req->domain.
659 finalize_domain_objects (DomainFinalizationReq *req)
661 MonoDomain *domain = req->domain;
664 #define NUM_FOBJECTS 64
665 MonoObject *to_finalize [NUM_FOBJECTS];
669 /* Process finalizers which are already in the queue */
670 mono_gc_invoke_finalizers ();
673 while (g_hash_table_size (domain->finalizable_objects_hash) > 0) {
677 * Since the domain is unloading, nobody is allowed to put
678 * new entries into the hash table. But finalize_object might
679 * remove entries from the hash table, so we make a copy.
681 objs = g_ptr_array_new ();
682 g_hash_table_foreach (domain->finalizable_objects_hash, collect_objects, objs);
683 /* printf ("FINALIZING %d OBJECTS.\n", objs->len); */
685 for (i = 0; i < objs->len; ++i) {
686 MonoObject *o = (MonoObject*)g_ptr_array_index (objs, i);
687 /* FIXME: Avoid finalizing threads, etc */
688 mono_gc_run_finalize (o, 0);
691 g_ptr_array_free (objs, TRUE);
693 #elif defined(HAVE_SGEN_GC)
694 while ((count = mono_gc_finalizers_for_domain (domain, to_finalize, NUM_FOBJECTS))) {
696 for (i = 0; i < count; ++i) {
697 mono_gc_run_finalize (to_finalize [i], 0);
702 /* cleanup the reference queue */
703 reference_queue_clear_for_domain (domain);
705 /* printf ("DONE.\n"); */
706 SetEvent (req->done_event);
708 /* The event is closed in mono_domain_finalize if we get here */
713 finalizer_thread (gpointer unused)
715 gboolean wait = TRUE;
718 /* Wait to be notified that there's at least one
722 g_assert (mono_domain_get () == mono_get_root_domain ());
723 mono_gc_set_skip_thread (TRUE);
726 /* An alertable wait is required so this thread can be suspended on windows */
727 mono_coop_sem_wait (&finalizer_sem, MONO_SEM_FLAGS_ALERTABLE);
731 mono_gc_set_skip_thread (FALSE);
733 mono_threads_perform_thread_dump ();
735 mono_console_handle_async_ops ();
737 mono_attach_maybe_start ();
739 if (domains_to_finalize) {
740 mono_finalizer_lock ();
741 if (domains_to_finalize) {
742 DomainFinalizationReq *req = (DomainFinalizationReq *)domains_to_finalize->data;
743 domains_to_finalize = g_slist_remove (domains_to_finalize, req);
744 mono_finalizer_unlock ();
746 finalize_domain_objects (req);
748 mono_finalizer_unlock ();
752 /* If finished == TRUE, mono_gc_cleanup has been called (from mono_runtime_cleanup),
753 * before the domain is unloaded.
755 mono_gc_invoke_finalizers ();
757 mono_threads_join_threads ();
759 reference_queue_proccess_all ();
761 /* Avoid posting the pending done event until there are pending finalizers */
762 if (mono_coop_sem_timedwait (&finalizer_sem, 0, MONO_SEM_FLAGS_NONE) == 0) {
763 /* Don't wait again at the start of the loop */
766 SetEvent (pending_done_event);
770 mono_finalizer_lock ();
771 finalizer_thread_exited = TRUE;
772 mono_coop_cond_signal (&exited_cond);
773 mono_finalizer_unlock ();
778 #ifndef LAZY_GC_THREAD_CREATION
782 mono_gc_init_finalizer_thread (void)
784 gc_thread = mono_thread_create_internal (mono_domain_get (), finalizer_thread, NULL, FALSE, 0);
785 ves_icall_System_Threading_Thread_SetName_internal (gc_thread, mono_string_new (mono_domain_get (), "Finalizer"));
791 mono_coop_mutex_init_recursive (&finalizer_mutex);
792 mono_coop_mutex_init_recursive (&reference_queue_mutex);
794 mono_counters_register ("Minor GC collections", MONO_COUNTER_GC | MONO_COUNTER_UINT, &gc_stats.minor_gc_count);
795 mono_counters_register ("Major GC collections", MONO_COUNTER_GC | MONO_COUNTER_UINT, &gc_stats.major_gc_count);
796 mono_counters_register ("Minor GC time", MONO_COUNTER_GC | MONO_COUNTER_ULONG | MONO_COUNTER_TIME, &gc_stats.minor_gc_time);
797 mono_counters_register ("Major GC time", MONO_COUNTER_GC | MONO_COUNTER_ULONG | MONO_COUNTER_TIME, &gc_stats.major_gc_time);
798 mono_counters_register ("Major GC time concurrent", MONO_COUNTER_GC | MONO_COUNTER_ULONG | MONO_COUNTER_TIME, &gc_stats.major_gc_time_concurrent);
800 mono_gc_base_init ();
802 if (mono_gc_is_disabled ()) {
807 pending_done_event = CreateEvent (NULL, TRUE, FALSE, NULL);
808 g_assert (pending_done_event);
809 mono_coop_cond_init (&exited_cond);
810 mono_coop_sem_init (&finalizer_sem, 0);
812 #ifndef LAZY_GC_THREAD_CREATION
813 mono_gc_init_finalizer_thread ();
818 mono_gc_cleanup (void)
821 g_message ("%s: cleaning up finalizer", __func__);
824 if (mono_gc_is_null ())
829 if (mono_thread_internal_current () != gc_thread) {
830 gboolean timed_out = FALSE;
831 guint32 start_ticks = mono_msec_ticks ();
832 guint32 end_ticks = start_ticks + 2000;
834 mono_gc_finalize_notify ();
835 /* Finishing the finalizer thread, so wait a little bit... */
836 /* MS seems to wait for about 2 seconds */
837 while (!finalizer_thread_exited) {
838 guint32 current_ticks = mono_msec_ticks ();
841 if (current_ticks >= end_ticks)
844 timeout = end_ticks - current_ticks;
845 mono_finalizer_lock ();
846 if (!finalizer_thread_exited)
847 mono_coop_cond_timedwait (&exited_cond, &finalizer_mutex, timeout);
848 mono_finalizer_unlock ();
851 if (!finalizer_thread_exited) {
854 /* Set a flag which the finalizer thread can check */
855 suspend_finalizers = TRUE;
857 /* Try to abort the thread, in the hope that it is running managed code */
858 mono_thread_internal_stop (gc_thread);
860 /* Wait for it to stop */
861 ret = guarded_wait (gc_thread->handle, 100, TRUE);
863 if (ret == WAIT_TIMEOUT) {
865 * The finalizer thread refused to die. There is not much we
866 * can do here, since the runtime is shutting down so the
867 * state the finalizer thread depends on will vanish.
869 g_warning ("Shutting down finalizer thread timed out.");
877 /* Wait for the thread to actually exit */
878 ret = guarded_wait (gc_thread->handle, INFINITE, TRUE);
879 g_assert (ret == WAIT_OBJECT_0);
881 mono_thread_join (GUINT_TO_POINTER (gc_thread->tid));
883 g_assert (finalizer_thread_exited);
886 mono_gc_base_cleanup ();
889 mono_reference_queue_cleanup ();
891 mono_coop_mutex_destroy (&finalizer_mutex);
892 mono_coop_mutex_destroy (&reference_queue_mutex);
896 mono_gc_is_finalizer_internal_thread (MonoInternalThread *thread)
898 return thread == gc_thread;
902 * mono_gc_is_finalizer_thread:
903 * @thread: the thread to test.
905 * In Mono objects are finalized asynchronously on a separate thread.
906 * This routine tests whether the @thread argument represents the
907 * finalization thread.
909 * Returns: TRUE if @thread is the finalization thread.
912 mono_gc_is_finalizer_thread (MonoThread *thread)
914 return mono_gc_is_finalizer_internal_thread (thread->internal_thread);
917 #if defined(__MACH__)
918 static pthread_t mach_exception_thread;
921 mono_gc_register_mach_exception_thread (pthread_t thread)
923 mach_exception_thread = thread;
927 mono_gc_get_mach_exception_thread (void)
929 return mach_exception_thread;
933 static MonoReferenceQueue *ref_queues;
936 ref_list_remove_element (RefQueueEntry **prev, RefQueueEntry *element)
939 /* Guard if head is changed concurrently. */
940 while (*prev != element)
941 prev = &(*prev)->next;
942 } while (prev && InterlockedCompareExchangePointer ((volatile gpointer *)prev, element->next, element) != element);
946 ref_list_push (RefQueueEntry **head, RefQueueEntry *value)
948 RefQueueEntry *current;
951 value->next = current;
952 STORE_STORE_FENCE; /*Must make sure the previous store is visible before the CAS. */
953 } while (InterlockedCompareExchangePointer ((volatile gpointer *)head, value, current) != current);
957 reference_queue_proccess (MonoReferenceQueue *queue)
959 RefQueueEntry **iter = &queue->queue;
960 RefQueueEntry *entry;
961 while ((entry = *iter)) {
962 if (queue->should_be_deleted || !mono_gchandle_get_target (entry->gchandle)) {
963 mono_gchandle_free ((guint32)entry->gchandle);
964 ref_list_remove_element (iter, entry);
965 queue->callback (entry->user_data);
974 reference_queue_proccess_all (void)
976 MonoReferenceQueue **iter;
977 MonoReferenceQueue *queue = ref_queues;
978 for (; queue; queue = queue->next)
979 reference_queue_proccess (queue);
982 mono_coop_mutex_lock (&reference_queue_mutex);
983 for (iter = &ref_queues; *iter;) {
985 if (!queue->should_be_deleted) {
990 mono_coop_mutex_unlock (&reference_queue_mutex);
991 reference_queue_proccess (queue);
997 mono_coop_mutex_unlock (&reference_queue_mutex);
1001 mono_reference_queue_cleanup (void)
1003 MonoReferenceQueue *queue = ref_queues;
1004 for (; queue; queue = queue->next)
1005 queue->should_be_deleted = TRUE;
1006 reference_queue_proccess_all ();
1010 reference_queue_clear_for_domain (MonoDomain *domain)
1012 MonoReferenceQueue *queue = ref_queues;
1013 for (; queue; queue = queue->next) {
1014 RefQueueEntry **iter = &queue->queue;
1015 RefQueueEntry *entry;
1016 while ((entry = *iter)) {
1017 if (entry->domain == domain) {
1018 mono_gchandle_free ((guint32)entry->gchandle);
1019 ref_list_remove_element (iter, entry);
1020 queue->callback (entry->user_data);
1023 iter = &entry->next;
1029 * mono_gc_reference_queue_new:
1030 * @callback callback used when processing collected entries.
1032 * Create a new reference queue used to process collected objects.
1033 * A reference queue let you add a pair of (managed object, user data)
1034 * using the mono_gc_reference_queue_add method.
1036 * Once the managed object is collected @callback will be called
1037 * in the finalizer thread with 'user data' as argument.
1039 * The callback is called from the finalizer thread without any locks held.
1040 * When a AppDomain is unloaded, all callbacks for objects belonging to it
1043 * @returns the new queue.
1046 mono_gc_reference_queue_new (mono_reference_queue_callback callback)
1048 MonoReferenceQueue *res = g_new0 (MonoReferenceQueue, 1);
1049 res->callback = callback;
1051 mono_coop_mutex_lock (&reference_queue_mutex);
1052 res->next = ref_queues;
1054 mono_coop_mutex_unlock (&reference_queue_mutex);
1060 * mono_gc_reference_queue_add:
1061 * @queue the queue to add the reference to.
1062 * @obj the object to be watched for collection
1063 * @user_data parameter to be passed to the queue callback
1065 * Queue an object to be watched for collection, when the @obj is
1066 * collected, the callback that was registered for the @queue will
1067 * be invoked with @user_data as argument.
1069 * @returns false if the queue is scheduled to be freed.
1072 mono_gc_reference_queue_add (MonoReferenceQueue *queue, MonoObject *obj, void *user_data)
1075 RefQueueEntry *entry;
1076 if (queue->should_be_deleted)
1079 entry = g_new0 (RefQueueEntry, 1);
1080 entry->user_data = user_data;
1081 entry->domain = mono_object_domain (obj);
1083 entry->gchandle = mono_gchandle_new_weakref (obj, TRUE);
1084 mono_object_register_finalizer (obj, &error);
1085 mono_error_assert_ok (&error);
1087 ref_list_push (&queue->queue, entry);
1092 * mono_gc_reference_queue_free:
1093 * @queue the queue that should be freed.
1095 * This operation signals that @queue should be freed. This operation is deferred
1096 * as it happens on the finalizer thread.
1098 * After this call, no further objects can be queued. It's the responsibility of the
1099 * caller to make sure that no further attempt to access queue will be made.
1102 mono_gc_reference_queue_free (MonoReferenceQueue *queue)
1104 queue->should_be_deleted = TRUE;