2 * metadata/gc.c: GC icalls.
4 * Author: Paolo Molaro <lupus@ximian.com>
6 * (C) 2002 Ximian, Inc.
13 #include <mono/metadata/gc-internal.h>
14 #include <mono/metadata/mono-gc.h>
15 #include <mono/metadata/threads.h>
16 #include <mono/metadata/tabledefs.h>
17 #include <mono/metadata/exception.h>
18 #include <mono/metadata/profiler-private.h>
19 #include <mono/metadata/domain-internals.h>
20 #include <mono/metadata/class-internals.h>
21 #include <mono/metadata/mono-mlist.h>
22 #include <mono/metadata/threadpool.h>
23 #include <mono/utils/mono-logger.h>
24 #include <mono/metadata/gc-internal.h>
25 #include <mono/metadata/marshal.h> /* for mono_delegate_free_ftnptr () */
26 #include <mono/metadata/attach.h>
28 #ifndef PLATFORM_WIN32
32 typedef struct DomainFinalizationReq {
35 } DomainFinalizationReq;
37 #ifdef PLATFORM_WINCE /* FIXME: add accessors to gc.dll API */
38 extern void (*__imp_GC_finalizer_notifier)(void);
39 #define GC_finalizer_notifier __imp_GC_finalizer_notifier
40 extern int __imp_GC_finalize_on_demand;
41 #define GC_finalize_on_demand __imp_GC_finalize_on_demand
44 static gboolean gc_disabled = FALSE;
46 static gboolean finalizing_root_domain = FALSE;
48 #define mono_finalizer_lock() EnterCriticalSection (&finalizer_mutex)
49 #define mono_finalizer_unlock() LeaveCriticalSection (&finalizer_mutex)
50 static CRITICAL_SECTION finalizer_mutex;
52 static GSList *domains_to_finalize= NULL;
53 static MonoMList *threads_to_finalize = NULL;
55 static MonoThread *gc_thread;
57 static void object_register_finalizer (MonoObject *obj, void (*callback)(void *, void*));
60 static HANDLE pending_done_event;
61 static HANDLE shutdown_event;
62 static HANDLE thread_started_event;
66 add_thread_to_finalize (MonoThread *thread)
68 mono_finalizer_lock ();
69 if (!threads_to_finalize)
70 MONO_GC_REGISTER_ROOT (threads_to_finalize);
71 threads_to_finalize = mono_mlist_append (threads_to_finalize, (MonoObject*)thread);
72 mono_finalizer_unlock ();
75 static gboolean suspend_finalizers = FALSE;
77 * actually, we might want to queue the finalize requests in a separate thread,
78 * but we need to be careful about the execution domain of the thread...
81 run_finalize (void *obj, void *data)
83 MonoObject *exc = NULL;
85 MonoMethod* finalizer = NULL;
86 o = (MonoObject*)((char*)obj + GPOINTER_TO_UINT (data));
88 if (suspend_finalizers)
92 mono_domain_lock (o->vtable->domain);
94 o2 = g_hash_table_lookup (o->vtable->domain->finalizable_objects_hash, o);
96 mono_domain_unlock (o->vtable->domain);
99 /* Already finalized somehow */
103 /* make sure the finalizer is not called again if the object is resurrected */
104 object_register_finalizer (obj, NULL);
106 if (o->vtable->klass == mono_get_thread_class ()) {
107 MonoThread *t = (MonoThread*)o;
109 if (mono_gc_is_finalizer_thread (t))
110 /* Avoid finalizing ourselves */
113 if (t->threadpool_thread && finalizing_root_domain) {
114 /* Don't finalize threadpool threads when
115 shutting down - they're finalized when the
116 threadpool shuts down. */
117 add_thread_to_finalize (t);
122 if (mono_runtime_get_no_exec ())
125 /* speedup later... and use a timeout */
126 /* g_print ("Finalize run on %p %s.%s\n", o, mono_object_class (o)->name_space, mono_object_class (o)->name); */
128 /* Use _internal here, since this thread can enter a doomed appdomain */
129 mono_domain_set_internal (mono_object_domain (o));
131 /* delegates that have a native function pointer allocated are
132 * registered for finalization, but they don't have a Finalize
133 * method, because in most cases it's not needed and it's just a waste.
135 if (o->vtable->klass->delegate) {
136 MonoDelegate* del = (MonoDelegate*)o;
137 if (del->delegate_trampoline)
138 mono_delegate_free_ftnptr ((MonoDelegate*)o);
142 finalizer = mono_class_get_finalizer (o->vtable->klass);
144 /* If object has a CCW but has no finalizer, it was only
145 * registered for finalization in order to free the CCW.
146 * Else it needs the regular finalizer run.
147 * FIXME: what to do about ressurection and suppression
148 * of finalizer on object with CCW.
150 if (mono_marshal_free_ccw (o) && !finalizer)
153 mono_runtime_invoke (finalizer, o, NULL, &exc);
156 /* fixme: do something useful */
161 mono_gc_finalize_threadpool_threads (void)
163 while (threads_to_finalize) {
164 MonoThread *thread = (MonoThread*) mono_mlist_get_data (threads_to_finalize);
166 /* Force finalization of the thread. */
167 thread->threadpool_thread = FALSE;
168 mono_object_register_finalizer ((MonoObject*)thread);
170 run_finalize (thread, NULL);
172 threads_to_finalize = mono_mlist_next (threads_to_finalize);
177 mono_gc_out_of_memory (size_t size)
180 * we could allocate at program startup some memory that we could release
181 * back to the system at this point if we're really low on memory (ie, size is
182 * lower than the memory we set apart)
184 mono_raise_exception (mono_domain_get ()->out_of_memory_ex);
190 * Some of our objects may point to a different address than the address returned by GC_malloc()
191 * (because of the GetHashCode hack), but we need to pass the real address to register_finalizer.
192 * This also means that in the callback we need to adjust the pointer to get back the real
194 * We also need to be consistent in the use of the GC_debug* variants of malloc and register_finalizer,
195 * since that, too, can cause the underlying pointer to be offset.
198 object_register_finalizer (MonoObject *obj, void (*callback)(void *, void*))
202 MonoDomain *domain = obj->vtable->domain;
205 /* This assertion is not valid when GC_DEBUG is defined */
206 g_assert (GC_base (obj) == (char*)obj - offset);
209 if (mono_domain_is_unloading (domain) && (callback != NULL))
211 * Can't register finalizers in a dying appdomain, since they
212 * could be invoked after the appdomain has been unloaded.
216 mono_domain_lock (domain);
219 g_hash_table_insert (domain->finalizable_objects_hash, obj, obj);
221 g_hash_table_remove (domain->finalizable_objects_hash, obj);
223 mono_domain_unlock (domain);
225 GC_REGISTER_FINALIZER_NO_ORDER ((char*)obj - offset, callback, GUINT_TO_POINTER (offset), NULL, NULL);
226 #elif defined(HAVE_SGEN_GC)
227 mono_gc_register_for_finalization (obj, callback);
232 * mono_object_register_finalizer:
233 * @obj: object to register
235 * Records that object @obj has a finalizer, this will call the
236 * Finalize method when the garbage collector disposes the object.
240 mono_object_register_finalizer (MonoObject *obj)
242 /* g_print ("Registered finalizer on %p %s.%s\n", obj, mono_object_class (obj)->name_space, mono_object_class (obj)->name); */
243 object_register_finalizer (obj, run_finalize);
247 * mono_domain_finalize:
248 * @domain: the domain to finalize
249 * @timeout: msects to wait for the finalization to complete, -1 to wait indefinitely
251 * Request finalization of all finalizable objects inside @domain. Wait
252 * @timeout msecs for the finalization to complete.
254 * Returns: TRUE if succeeded, FALSE if there was a timeout
258 mono_domain_finalize (MonoDomain *domain, guint32 timeout)
260 DomainFinalizationReq *req;
264 if (mono_thread_current () == gc_thread)
265 /* We are called from inside a finalizer, not much we can do here */
269 * No need to create another thread 'cause the finalizer thread
270 * is still working and will take care of running the finalizers
277 mono_gc_collect (mono_gc_max_generation ());
279 done_event = CreateEvent (NULL, TRUE, FALSE, NULL);
280 if (done_event == NULL) {
284 req = g_new0 (DomainFinalizationReq, 1);
285 req->domain = domain;
286 req->done_event = done_event;
288 if (domain == mono_get_root_domain ())
289 finalizing_root_domain = TRUE;
291 mono_finalizer_lock ();
293 domains_to_finalize = g_slist_append (domains_to_finalize, req);
295 mono_finalizer_unlock ();
297 /* Tell the finalizer thread to finalize this appdomain */
298 mono_gc_finalize_notify ();
303 res = WaitForSingleObjectEx (done_event, timeout, TRUE);
305 /* printf ("WAIT RES: %d.\n", res); */
306 if (res == WAIT_TIMEOUT) {
307 /* We leak the handle here */
311 CloseHandle (done_event);
313 if (domain == mono_get_root_domain ()) {
314 mono_thread_pool_cleanup ();
315 mono_gc_finalize_threadpool_threads ();
320 /* We don't support domain finalization without a GC */
326 ves_icall_System_GC_InternalCollect (int generation)
328 mono_gc_collect (generation);
332 ves_icall_System_GC_GetTotalMemory (MonoBoolean forceCollection)
337 mono_gc_collect (mono_gc_max_generation ());
338 return mono_gc_get_used_size ();
342 ves_icall_System_GC_KeepAlive (MonoObject *obj)
352 ves_icall_System_GC_ReRegisterForFinalize (MonoObject *obj)
356 object_register_finalizer (obj, run_finalize);
360 ves_icall_System_GC_SuppressFinalize (MonoObject *obj)
364 /* delegates have no finalizers, but we register them to deal with the
365 * unmanaged->managed trampoline. We don't let the user suppress it
366 * otherwise we'd leak it.
368 if (obj->vtable->klass->delegate)
371 /* FIXME: Need to handle case where obj has COM Callable Wrapper
372 * generated for it that needs cleaned up, but user wants to suppress
373 * their derived object finalizer. */
375 object_register_finalizer (obj, NULL);
379 ves_icall_System_GC_WaitForPendingFinalizers (void)
382 if (!mono_gc_pending_finalizers ())
385 if (mono_thread_current () == gc_thread)
386 /* Avoid deadlocks */
389 ResetEvent (pending_done_event);
390 mono_gc_finalize_notify ();
391 /* g_print ("Waiting for pending finalizers....\n"); */
392 WaitForSingleObjectEx (pending_done_event, INFINITE, TRUE);
393 /* g_print ("Done pending....\n"); */
397 #define mono_allocator_lock() EnterCriticalSection (&allocator_section)
398 #define mono_allocator_unlock() LeaveCriticalSection (&allocator_section)
399 static CRITICAL_SECTION allocator_section;
400 static CRITICAL_SECTION handle_section;
409 static void mono_gchandle_set_target (guint32 gchandle, MonoObject *obj);
411 static HandleType mono_gchandle_get_type (guint32 gchandle);
414 ves_icall_System_GCHandle_GetTarget (guint32 handle)
416 return mono_gchandle_get_target (handle);
420 * if type == -1, change the target of the handle, otherwise allocate a new handle.
423 ves_icall_System_GCHandle_GetTargetHandle (MonoObject *obj, guint32 handle, gint32 type)
426 mono_gchandle_set_target (handle, obj);
427 /* the handle doesn't change */
432 return mono_gchandle_new_weakref (obj, FALSE);
433 case HANDLE_WEAK_TRACK:
434 return mono_gchandle_new_weakref (obj, TRUE);
436 return mono_gchandle_new (obj, FALSE);
438 return mono_gchandle_new (obj, TRUE);
440 g_assert_not_reached ();
446 ves_icall_System_GCHandle_FreeHandle (guint32 handle)
448 mono_gchandle_free (handle);
452 ves_icall_System_GCHandle_GetAddrOfPinnedObject (guint32 handle)
456 if (mono_gchandle_get_type (handle) != HANDLE_PINNED)
458 obj = mono_gchandle_get_target (handle);
460 MonoClass *klass = mono_object_class (obj);
461 if (klass == mono_defaults.string_class) {
462 return mono_string_chars ((MonoString*)obj);
463 } else if (klass->rank) {
464 return mono_array_addr ((MonoArray*)obj, char, 0);
466 /* the C# code will check and throw the exception */
467 /* FIXME: missing !klass->blittable test, see bug #61134 */
468 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
470 return (char*)obj + sizeof (MonoObject);
481 guint slot_hint : 24; /* starting slot for search */
482 /* 2^16 appdomains should be enough for everyone (though I know I'll regret this in 20 years) */
483 /* we alloc this only for weak refs, since we can get the domain directly in the other cases */
487 /* weak and weak-track arrays will be allocated in malloc memory
489 static HandleData gc_handles [] = {
490 {NULL, NULL, 0, HANDLE_WEAK, 0},
491 {NULL, NULL, 0, HANDLE_WEAK_TRACK, 0},
492 {NULL, NULL, 0, HANDLE_NORMAL, 0},
493 {NULL, NULL, 0, HANDLE_PINNED, 0}
496 #define lock_handles(handles) EnterCriticalSection (&handle_section)
497 #define unlock_handles(handles) LeaveCriticalSection (&handle_section)
500 find_first_unset (guint32 bitmap)
503 for (i = 0; i < 32; ++i) {
504 if (!(bitmap & (1 << i)))
511 alloc_handle (HandleData *handles, MonoObject *obj)
514 lock_handles (handles);
515 if (!handles->size) {
517 if (handles->type > HANDLE_WEAK_TRACK) {
518 handles->entries = mono_gc_alloc_fixed (sizeof (gpointer) * handles->size, NULL);
520 handles->entries = g_malloc0 (sizeof (gpointer) * handles->size);
521 handles->domain_ids = g_malloc0 (sizeof (guint16) * handles->size);
523 handles->bitmap = g_malloc0 (handles->size / 8);
526 for (slot = handles->slot_hint; slot < handles->size / 32; ++slot) {
527 if (handles->bitmap [slot] != 0xffffffff) {
528 i = find_first_unset (handles->bitmap [slot]);
529 handles->slot_hint = slot;
533 if (i == -1 && handles->slot_hint != 0) {
534 for (slot = 0; slot < handles->slot_hint; ++slot) {
535 if (handles->bitmap [slot] != 0xffffffff) {
536 i = find_first_unset (handles->bitmap [slot]);
537 handles->slot_hint = slot;
544 guint32 new_size = handles->size * 2; /* always double: we memset to 0 based on this below */
546 /* resize and copy the bitmap */
547 new_bitmap = g_malloc0 (new_size / 8);
548 memcpy (new_bitmap, handles->bitmap, handles->size / 8);
549 g_free (handles->bitmap);
550 handles->bitmap = new_bitmap;
552 /* resize and copy the entries */
553 if (handles->type > HANDLE_WEAK_TRACK) {
555 entries = mono_gc_alloc_fixed (sizeof (gpointer) * new_size, NULL);
556 memcpy (entries, handles->entries, sizeof (gpointer) * handles->size);
557 handles->entries = entries;
561 domain_ids = g_malloc0 (sizeof (guint16) * new_size);
562 entries = g_malloc (sizeof (gpointer) * new_size);
563 /* we disable GC because we could lose some disappearing link updates */
565 memcpy (entries, handles->entries, sizeof (gpointer) * handles->size);
566 memset (entries + handles->size, 0, sizeof (gpointer) * handles->size);
567 memcpy (domain_ids, handles->domain_ids, sizeof (guint16) * handles->size);
568 for (i = 0; i < handles->size; ++i) {
569 MonoObject *obj = mono_gc_weak_link_get (&(handles->entries [i]));
570 if (handles->entries [i])
571 mono_gc_weak_link_remove (&(handles->entries [i]));
572 /*g_print ("reg/unreg entry %d of type %d at %p to object %p (%p), was: %p\n", i, handles->type, &(entries [i]), obj, entries [i], handles->entries [i]);*/
574 mono_gc_weak_link_add (&(entries [i]), obj);
577 g_free (handles->entries);
578 g_free (handles->domain_ids);
579 handles->entries = entries;
580 handles->domain_ids = domain_ids;
584 /* set i and slot to the next free position */
586 slot = (handles->size + 1) / 32;
587 handles->slot_hint = handles->size + 1;
588 handles->size = new_size;
590 handles->bitmap [slot] |= 1 << i;
591 slot = slot * 32 + i;
592 handles->entries [slot] = obj;
593 if (handles->type <= HANDLE_WEAK_TRACK) {
595 mono_gc_weak_link_add (&(handles->entries [slot]), obj);
598 mono_perfcounters->gc_num_handles++;
599 unlock_handles (handles);
600 /*g_print ("allocated entry %d of type %d to object %p (in slot: %p)\n", slot, handles->type, obj, handles->entries [slot]);*/
601 return (slot << 3) | (handles->type + 1);
606 * @obj: managed object to get a handle for
607 * @pinned: whether the object should be pinned
609 * This returns a handle that wraps the object, this is used to keep a
610 * reference to a managed object from the unmanaged world and preventing the
611 * object from being disposed.
613 * If @pinned is false the address of the object can not be obtained, if it is
614 * true the address of the object can be obtained. This will also pin the
615 * object so it will not be possible by a moving garbage collector to move the
618 * Returns: a handle that can be used to access the object from
622 mono_gchandle_new (MonoObject *obj, gboolean pinned)
624 return alloc_handle (&gc_handles [pinned? HANDLE_PINNED: HANDLE_NORMAL], obj);
628 * mono_gchandle_new_weakref:
629 * @obj: managed object to get a handle for
630 * @pinned: whether the object should be pinned
632 * This returns a weak handle that wraps the object, this is used to
633 * keep a reference to a managed object from the unmanaged world.
634 * Unlike the mono_gchandle_new the object can be reclaimed by the
635 * garbage collector. In this case the value of the GCHandle will be
638 * If @pinned is false the address of the object can not be obtained, if it is
639 * true the address of the object can be obtained. This will also pin the
640 * object so it will not be possible by a moving garbage collector to move the
643 * Returns: a handle that can be used to access the object from
647 mono_gchandle_new_weakref (MonoObject *obj, gboolean track_resurrection)
649 return alloc_handle (&gc_handles [track_resurrection? HANDLE_WEAK_TRACK: HANDLE_WEAK], obj);
653 mono_gchandle_get_type (guint32 gchandle)
655 guint type = (gchandle & 7) - 1;
661 * mono_gchandle_get_target:
662 * @gchandle: a GCHandle's handle.
664 * The handle was previously created by calling mono_gchandle_new or
665 * mono_gchandle_new_weakref.
667 * Returns a pointer to the MonoObject represented by the handle or
668 * NULL for a collected object if using a weakref handle.
671 mono_gchandle_get_target (guint32 gchandle)
673 guint slot = gchandle >> 3;
674 guint type = (gchandle & 7) - 1;
675 HandleData *handles = &gc_handles [type];
676 MonoObject *obj = NULL;
679 lock_handles (handles);
680 if (slot < handles->size && (handles->bitmap [slot / 32] & (1 << (slot % 32)))) {
681 if (handles->type <= HANDLE_WEAK_TRACK) {
682 obj = mono_gc_weak_link_get (&handles->entries [slot]);
684 obj = handles->entries [slot];
687 /* print a warning? */
689 unlock_handles (handles);
690 /*g_print ("get target of entry %d of type %d: %p\n", slot, handles->type, obj);*/
695 mono_gchandle_set_target (guint32 gchandle, MonoObject *obj)
697 guint slot = gchandle >> 3;
698 guint type = (gchandle & 7) - 1;
699 HandleData *handles = &gc_handles [type];
702 lock_handles (handles);
703 if (slot < handles->size && (handles->bitmap [slot / 32] & (1 << (slot % 32)))) {
704 if (handles->type <= HANDLE_WEAK_TRACK) {
705 if (handles->entries [slot])
706 mono_gc_weak_link_remove (&handles->entries [slot]);
708 mono_gc_weak_link_add (&handles->entries [slot], obj);
710 handles->entries [slot] = obj;
713 /* print a warning? */
715 /*g_print ("changed entry %d of type %d to object %p (in slot: %p)\n", slot, handles->type, obj, handles->entries [slot]);*/
716 unlock_handles (handles);
720 * mono_gchandle_is_in_domain:
721 * @gchandle: a GCHandle's handle.
722 * @domain: An application domain.
724 * Returns: true if the object wrapped by the @gchandle belongs to the specific @domain.
727 mono_gchandle_is_in_domain (guint32 gchandle, MonoDomain *domain)
729 guint slot = gchandle >> 3;
730 guint type = (gchandle & 7) - 1;
731 HandleData *handles = &gc_handles [type];
732 gboolean result = FALSE;
735 lock_handles (handles);
736 if (slot < handles->size && (handles->bitmap [slot / 32] & (1 << (slot % 32)))) {
737 if (handles->type <= HANDLE_WEAK_TRACK) {
738 result = domain->domain_id == handles->domain_ids [slot];
741 obj = handles->entries [slot];
745 result = domain == mono_object_domain (obj);
748 /* print a warning? */
750 unlock_handles (handles);
755 * mono_gchandle_free:
756 * @gchandle: a GCHandle's handle.
758 * Frees the @gchandle handle. If there are no outstanding
759 * references, the garbage collector can reclaim the memory of the
763 mono_gchandle_free (guint32 gchandle)
765 guint slot = gchandle >> 3;
766 guint type = (gchandle & 7) - 1;
767 HandleData *handles = &gc_handles [type];
770 lock_handles (handles);
771 if (slot < handles->size && (handles->bitmap [slot / 32] & (1 << (slot % 32)))) {
772 if (handles->type <= HANDLE_WEAK_TRACK) {
773 if (handles->entries [slot])
774 mono_gc_weak_link_remove (&handles->entries [slot]);
776 handles->entries [slot] = NULL;
778 handles->bitmap [slot / 32] &= ~(1 << (slot % 32));
780 /* print a warning? */
782 mono_perfcounters->gc_num_handles--;
783 /*g_print ("freed entry %d of type %d\n", slot, handles->type);*/
784 unlock_handles (handles);
788 * mono_gchandle_free_domain:
789 * @domain: domain that is unloading
791 * Function used internally to cleanup any GC handle for objects belonging
792 * to the specified domain during appdomain unload.
795 mono_gchandle_free_domain (MonoDomain *domain)
799 for (type = 0; type < 3; ++type) {
801 HandleData *handles = &gc_handles [type];
802 lock_handles (handles);
803 for (slot = 0; slot < handles->size; ++slot) {
804 if (!(handles->bitmap [slot / 32] & (1 << (slot % 32))))
806 if (type <= HANDLE_WEAK_TRACK) {
807 if (domain->domain_id == handles->domain_ids [slot]) {
808 handles->bitmap [slot / 32] &= ~(1 << (slot % 32));
809 if (handles->entries [slot])
810 mono_gc_weak_link_remove (&handles->entries [slot]);
813 if (handles->entries [slot] && mono_object_domain (handles->entries [slot]) == domain) {
814 handles->bitmap [slot / 32] &= ~(1 << (slot % 32));
815 handles->entries [slot] = NULL;
819 unlock_handles (handles);
826 static HANDLE finalizer_event;
827 static volatile gboolean finished=FALSE;
830 mono_gc_finalize_notify (void)
833 g_message (G_GNUC_PRETTY_FUNCTION ": prodding finalizer");
836 SetEvent (finalizer_event);
840 collect_objects (gpointer key, gpointer value, gpointer user_data)
842 GPtrArray *arr = (GPtrArray*)user_data;
843 g_ptr_array_add (arr, key);
847 * finalize_domain_objects:
849 * Run the finalizers of all finalizable objects in req->domain.
852 finalize_domain_objects (DomainFinalizationReq *req)
854 MonoDomain *domain = req->domain;
857 while (g_hash_table_size (domain->finalizable_objects_hash) > 0) {
861 * Since the domain is unloading, nobody is allowed to put
862 * new entries into the hash table. But finalize_object might
863 * remove entries from the hash table, so we make a copy.
865 objs = g_ptr_array_new ();
866 g_hash_table_foreach (domain->finalizable_objects_hash, collect_objects, objs);
867 /* printf ("FINALIZING %d OBJECTS.\n", objs->len); */
869 for (i = 0; i < objs->len; ++i) {
870 MonoObject *o = (MonoObject*)g_ptr_array_index (objs, i);
871 /* FIXME: Avoid finalizing threads, etc */
875 g_ptr_array_free (objs, TRUE);
877 #elif defined(HAVE_SGEN_GC)
878 #define NUM_FOBJECTS 64
879 MonoObject *to_finalize [NUM_FOBJECTS];
881 while ((count = mono_gc_finalizers_for_domain (domain, to_finalize, NUM_FOBJECTS))) {
883 for (i = 0; i < count; ++i) {
884 run_finalize (to_finalize [i], 0);
889 /* Process finalizers which are already in the queue */
890 mono_gc_invoke_finalizers ();
892 /* printf ("DONE.\n"); */
893 SetEvent (req->done_event);
895 /* The event is closed in mono_domain_finalize if we get here */
900 finalizer_thread (gpointer unused)
902 gc_thread = mono_thread_current ();
904 SetEvent (thread_started_event);
907 /* Wait to be notified that there's at least one
910 /* Use alertable=FALSE since we will be asked to exit using the event too */
911 WaitForSingleObjectEx (finalizer_event, INFINITE, FALSE);
913 #ifndef DISABLE_ATTACH
914 mono_attach_maybe_start ();
917 if (domains_to_finalize) {
918 mono_finalizer_lock ();
919 if (domains_to_finalize) {
920 DomainFinalizationReq *req = domains_to_finalize->data;
921 domains_to_finalize = g_slist_remove (domains_to_finalize, req);
922 mono_finalizer_unlock ();
924 finalize_domain_objects (req);
926 mono_finalizer_unlock ();
930 /* If finished == TRUE, mono_gc_cleanup has been called (from mono_runtime_cleanup),
931 * before the domain is unloaded.
933 mono_gc_invoke_finalizers ();
935 SetEvent (pending_done_event);
938 SetEvent (shutdown_event);
945 InitializeCriticalSection (&handle_section);
946 InitializeCriticalSection (&allocator_section);
948 InitializeCriticalSection (&finalizer_mutex);
950 MONO_GC_REGISTER_ROOT (gc_handles [HANDLE_NORMAL].entries);
951 MONO_GC_REGISTER_ROOT (gc_handles [HANDLE_PINNED].entries);
953 mono_gc_base_init ();
955 if (g_getenv ("GC_DONT_GC")) {
960 finalizer_event = CreateEvent (NULL, FALSE, FALSE, NULL);
961 pending_done_event = CreateEvent (NULL, TRUE, FALSE, NULL);
962 shutdown_event = CreateEvent (NULL, TRUE, FALSE, NULL);
963 thread_started_event = CreateEvent (NULL, TRUE, FALSE, NULL);
964 if (finalizer_event == NULL || pending_done_event == NULL || shutdown_event == NULL || thread_started_event == NULL) {
965 g_assert_not_reached ();
968 mono_thread_create (mono_domain_get (), finalizer_thread, NULL);
971 * Waiting for a new thread would result in a deadlock when the runtime is
972 * initialized from _CorDllMain that is called while the OS loader lock is
973 * held by LoadLibrary. Avoiding waiting for the finalizer thread being
974 * created should not cause any issues on Windows.
976 #ifndef PLATFORM_WIN32
978 * Wait until the finalizer thread sets gc_thread since its value is needed
979 * by mono_thread_attach ()
981 WaitForSingleObjectEx (thread_started_event, INFINITE, FALSE);
986 mono_gc_cleanup (void)
989 g_message (G_GNUC_PRETTY_FUNCTION ": cleaning up finalizer");
993 ResetEvent (shutdown_event);
995 if (mono_thread_current () != gc_thread) {
996 mono_gc_finalize_notify ();
997 /* Finishing the finalizer thread, so wait a little bit... */
998 /* MS seems to wait for about 2 seconds */
999 if (WaitForSingleObjectEx (shutdown_event, 2000, FALSE) == WAIT_TIMEOUT) {
1002 /* Set a flag which the finalizer thread can check */
1003 suspend_finalizers = TRUE;
1005 /* Try to abort the thread, in the hope that it is running managed code */
1006 mono_thread_stop (gc_thread);
1008 /* Wait for it to stop */
1009 ret = WaitForSingleObjectEx (gc_thread->handle, 100, TRUE);
1011 if (ret == WAIT_TIMEOUT) {
1013 * The finalizer thread refused to die. There is not much we
1014 * can do here, since the runtime is shutting down so the
1015 * state the finalizer thread depends on will vanish.
1017 g_warning ("Shutting down finalizer thread timed out.");
1020 * FIXME: On unix, when the above wait returns, the thread
1021 * might still be running io-layer code, or pthreads code.
1029 #ifdef HAVE_BOEHM_GC
1030 GC_finalizer_notifier = NULL;
1034 DeleteCriticalSection (&handle_section);
1035 DeleteCriticalSection (&allocator_section);
1036 DeleteCriticalSection (&finalizer_mutex);
1041 /* Null GC dummy functions */
1043 mono_gc_finalize_notify (void)
1047 void mono_gc_init (void)
1049 InitializeCriticalSection (&handle_section);
1052 void mono_gc_cleanup (void)
1059 * mono_gc_is_finalizer_thread:
1060 * @thread: the thread to test.
1062 * In Mono objects are finalized asynchronously on a separate thread.
1063 * This routine tests whether the @thread argument represents the
1064 * finalization thread.
1066 * Returns true if @thread is the finalization thread.
1069 mono_gc_is_finalizer_thread (MonoThread *thread)
1071 return thread == gc_thread;