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)
14 #include <mono/metadata/gc-internal.h>
15 #include <mono/metadata/mono-gc.h>
16 #include <mono/metadata/threads.h>
17 #include <mono/metadata/tabledefs.h>
18 #include <mono/metadata/exception.h>
19 #include <mono/metadata/profiler-private.h>
20 #include <mono/metadata/domain-internals.h>
21 #include <mono/metadata/class-internals.h>
22 #include <mono/metadata/mono-mlist.h>
23 #include <mono/metadata/threadpool.h>
24 #include <mono/utils/mono-logger.h>
25 #include <mono/metadata/gc-internal.h>
26 #include <mono/metadata/marshal.h> /* for mono_delegate_free_ftnptr () */
27 #include <mono/metadata/attach.h>
29 #include <semaphore.h>
30 /* we do this only for known working systems (OSX for example
31 * has the header and functions, but they don't work at all): in other cases
32 * we fall back to the io-layer slightly slower and signal-unsafe Event.
35 #define USE_POSIX_SEM 1
39 #ifndef PLATFORM_WIN32
43 typedef struct DomainFinalizationReq {
46 } DomainFinalizationReq;
48 #ifdef PLATFORM_WINCE /* FIXME: add accessors to gc.dll API */
49 extern void (*__imp_GC_finalizer_notifier)(void);
50 #define GC_finalizer_notifier __imp_GC_finalizer_notifier
51 extern int __imp_GC_finalize_on_demand;
52 #define GC_finalize_on_demand __imp_GC_finalize_on_demand
55 static gboolean gc_disabled = FALSE;
57 static gboolean finalizing_root_domain = FALSE;
59 #define mono_finalizer_lock() EnterCriticalSection (&finalizer_mutex)
60 #define mono_finalizer_unlock() LeaveCriticalSection (&finalizer_mutex)
61 static CRITICAL_SECTION finalizer_mutex;
63 static GSList *domains_to_finalize= NULL;
64 static MonoMList *threads_to_finalize = NULL;
66 static MonoThread *gc_thread;
68 static void object_register_finalizer (MonoObject *obj, void (*callback)(void *, void*));
71 static HANDLE pending_done_event;
72 static HANDLE shutdown_event;
73 static HANDLE thread_started_event;
77 add_thread_to_finalize (MonoThread *thread)
79 mono_finalizer_lock ();
80 if (!threads_to_finalize)
81 MONO_GC_REGISTER_ROOT (threads_to_finalize);
82 threads_to_finalize = mono_mlist_append (threads_to_finalize, (MonoObject*)thread);
83 mono_finalizer_unlock ();
86 static gboolean suspend_finalizers = FALSE;
88 * actually, we might want to queue the finalize requests in a separate thread,
89 * but we need to be careful about the execution domain of the thread...
92 run_finalize (void *obj, void *data)
94 MonoObject *exc = NULL;
99 MonoMethod* finalizer = NULL;
100 o = (MonoObject*)((char*)obj + GPOINTER_TO_UINT (data));
102 if (suspend_finalizers)
106 mono_domain_lock (o->vtable->domain);
108 o2 = g_hash_table_lookup (o->vtable->domain->finalizable_objects_hash, o);
110 mono_domain_unlock (o->vtable->domain);
113 /* Already finalized somehow */
117 /* make sure the finalizer is not called again if the object is resurrected */
118 object_register_finalizer (obj, NULL);
120 if (o->vtable->klass == mono_get_thread_class ()) {
121 MonoThread *t = (MonoThread*)o;
123 if (mono_gc_is_finalizer_thread (t))
124 /* Avoid finalizing ourselves */
127 if (t->threadpool_thread && finalizing_root_domain) {
128 /* Don't finalize threadpool threads when
129 shutting down - they're finalized when the
130 threadpool shuts down. */
131 add_thread_to_finalize (t);
136 if (mono_runtime_get_no_exec ())
139 /* speedup later... and use a timeout */
140 /* g_print ("Finalize run on %p %s.%s\n", o, mono_object_class (o)->name_space, mono_object_class (o)->name); */
142 /* Use _internal here, since this thread can enter a doomed appdomain */
143 mono_domain_set_internal (mono_object_domain (o));
145 /* delegates that have a native function pointer allocated are
146 * registered for finalization, but they don't have a Finalize
147 * method, because in most cases it's not needed and it's just a waste.
149 if (o->vtable->klass->delegate) {
150 MonoDelegate* del = (MonoDelegate*)o;
151 if (del->delegate_trampoline)
152 mono_delegate_free_ftnptr ((MonoDelegate*)o);
156 finalizer = mono_class_get_finalizer (o->vtable->klass);
158 /* If object has a CCW but has no finalizer, it was only
159 * registered for finalization in order to free the CCW.
160 * Else it needs the regular finalizer run.
161 * FIXME: what to do about ressurection and suppression
162 * of finalizer on object with CCW.
164 if (mono_marshal_free_ccw (o) && !finalizer)
167 mono_runtime_invoke (finalizer, o, NULL, &exc);
170 /* fixme: do something useful */
175 mono_gc_finalize_threadpool_threads (void)
177 while (threads_to_finalize) {
178 MonoThread *thread = (MonoThread*) mono_mlist_get_data (threads_to_finalize);
180 /* Force finalization of the thread. */
181 thread->threadpool_thread = FALSE;
182 mono_object_register_finalizer ((MonoObject*)thread);
184 run_finalize (thread, NULL);
186 threads_to_finalize = mono_mlist_next (threads_to_finalize);
191 mono_gc_out_of_memory (size_t size)
194 * we could allocate at program startup some memory that we could release
195 * back to the system at this point if we're really low on memory (ie, size is
196 * lower than the memory we set apart)
198 mono_raise_exception (mono_domain_get ()->out_of_memory_ex);
204 * Some of our objects may point to a different address than the address returned by GC_malloc()
205 * (because of the GetHashCode hack), but we need to pass the real address to register_finalizer.
206 * This also means that in the callback we need to adjust the pointer to get back the real
208 * We also need to be consistent in the use of the GC_debug* variants of malloc and register_finalizer,
209 * since that, too, can cause the underlying pointer to be offset.
212 object_register_finalizer (MonoObject *obj, void (*callback)(void *, void*))
216 MonoDomain *domain = obj->vtable->domain;
219 /* This assertion is not valid when GC_DEBUG is defined */
220 g_assert (GC_base (obj) == (char*)obj - offset);
223 if (mono_domain_is_unloading (domain) && (callback != NULL))
225 * Can't register finalizers in a dying appdomain, since they
226 * could be invoked after the appdomain has been unloaded.
230 mono_domain_lock (domain);
233 g_hash_table_insert (domain->finalizable_objects_hash, obj, obj);
235 g_hash_table_remove (domain->finalizable_objects_hash, obj);
237 mono_domain_unlock (domain);
239 GC_REGISTER_FINALIZER_NO_ORDER ((char*)obj - offset, callback, GUINT_TO_POINTER (offset), NULL, NULL);
240 #elif defined(HAVE_SGEN_GC)
241 mono_gc_register_for_finalization (obj, callback);
246 * mono_object_register_finalizer:
247 * @obj: object to register
249 * Records that object @obj has a finalizer, this will call the
250 * Finalize method when the garbage collector disposes the object.
254 mono_object_register_finalizer (MonoObject *obj)
256 /* g_print ("Registered finalizer on %p %s.%s\n", obj, mono_object_class (obj)->name_space, mono_object_class (obj)->name); */
257 object_register_finalizer (obj, run_finalize);
261 * mono_domain_finalize:
262 * @domain: the domain to finalize
263 * @timeout: msects to wait for the finalization to complete, -1 to wait indefinitely
265 * Request finalization of all finalizable objects inside @domain. Wait
266 * @timeout msecs for the finalization to complete.
268 * Returns: TRUE if succeeded, FALSE if there was a timeout
272 mono_domain_finalize (MonoDomain *domain, guint32 timeout)
274 DomainFinalizationReq *req;
278 if (mono_thread_current () == gc_thread)
279 /* We are called from inside a finalizer, not much we can do here */
283 * No need to create another thread 'cause the finalizer thread
284 * is still working and will take care of running the finalizers
291 mono_gc_collect (mono_gc_max_generation ());
293 done_event = CreateEvent (NULL, TRUE, FALSE, NULL);
294 if (done_event == NULL) {
298 req = g_new0 (DomainFinalizationReq, 1);
299 req->domain = domain;
300 req->done_event = done_event;
302 if (domain == mono_get_root_domain ())
303 finalizing_root_domain = TRUE;
305 mono_finalizer_lock ();
307 domains_to_finalize = g_slist_append (domains_to_finalize, req);
309 mono_finalizer_unlock ();
311 /* Tell the finalizer thread to finalize this appdomain */
312 mono_gc_finalize_notify ();
317 res = WaitForSingleObjectEx (done_event, timeout, TRUE);
319 /* printf ("WAIT RES: %d.\n", res); */
320 if (res == WAIT_TIMEOUT) {
321 /* We leak the handle here */
325 CloseHandle (done_event);
327 if (domain == mono_get_root_domain ()) {
328 mono_thread_pool_cleanup ();
329 mono_gc_finalize_threadpool_threads ();
334 /* We don't support domain finalization without a GC */
340 ves_icall_System_GC_InternalCollect (int generation)
342 mono_gc_collect (generation);
346 ves_icall_System_GC_GetTotalMemory (MonoBoolean forceCollection)
351 mono_gc_collect (mono_gc_max_generation ());
352 return mono_gc_get_used_size ();
356 ves_icall_System_GC_KeepAlive (MonoObject *obj)
366 ves_icall_System_GC_ReRegisterForFinalize (MonoObject *obj)
370 object_register_finalizer (obj, run_finalize);
374 ves_icall_System_GC_SuppressFinalize (MonoObject *obj)
378 /* delegates have no finalizers, but we register them to deal with the
379 * unmanaged->managed trampoline. We don't let the user suppress it
380 * otherwise we'd leak it.
382 if (obj->vtable->klass->delegate)
385 /* FIXME: Need to handle case where obj has COM Callable Wrapper
386 * generated for it that needs cleaned up, but user wants to suppress
387 * their derived object finalizer. */
389 object_register_finalizer (obj, NULL);
393 ves_icall_System_GC_WaitForPendingFinalizers (void)
396 if (!mono_gc_pending_finalizers ())
399 if (mono_thread_current () == gc_thread)
400 /* Avoid deadlocks */
403 ResetEvent (pending_done_event);
404 mono_gc_finalize_notify ();
405 /* g_print ("Waiting for pending finalizers....\n"); */
406 WaitForSingleObjectEx (pending_done_event, INFINITE, TRUE);
407 /* g_print ("Done pending....\n"); */
411 #define mono_allocator_lock() EnterCriticalSection (&allocator_section)
412 #define mono_allocator_unlock() LeaveCriticalSection (&allocator_section)
413 static CRITICAL_SECTION allocator_section;
414 static CRITICAL_SECTION handle_section;
423 static void mono_gchandle_set_target (guint32 gchandle, MonoObject *obj);
425 static HandleType mono_gchandle_get_type (guint32 gchandle);
428 ves_icall_System_GCHandle_GetTarget (guint32 handle)
430 return mono_gchandle_get_target (handle);
434 * if type == -1, change the target of the handle, otherwise allocate a new handle.
437 ves_icall_System_GCHandle_GetTargetHandle (MonoObject *obj, guint32 handle, gint32 type)
440 mono_gchandle_set_target (handle, obj);
441 /* the handle doesn't change */
446 return mono_gchandle_new_weakref (obj, FALSE);
447 case HANDLE_WEAK_TRACK:
448 return mono_gchandle_new_weakref (obj, TRUE);
450 return mono_gchandle_new (obj, FALSE);
452 return mono_gchandle_new (obj, TRUE);
454 g_assert_not_reached ();
460 ves_icall_System_GCHandle_FreeHandle (guint32 handle)
462 mono_gchandle_free (handle);
466 ves_icall_System_GCHandle_GetAddrOfPinnedObject (guint32 handle)
470 if (mono_gchandle_get_type (handle) != HANDLE_PINNED)
472 obj = mono_gchandle_get_target (handle);
474 MonoClass *klass = mono_object_class (obj);
475 if (klass == mono_defaults.string_class) {
476 return mono_string_chars ((MonoString*)obj);
477 } else if (klass->rank) {
478 return mono_array_addr ((MonoArray*)obj, char, 0);
480 /* the C# code will check and throw the exception */
481 /* FIXME: missing !klass->blittable test, see bug #61134 */
482 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
484 return (char*)obj + sizeof (MonoObject);
495 guint slot_hint : 24; /* starting slot for search */
496 /* 2^16 appdomains should be enough for everyone (though I know I'll regret this in 20 years) */
497 /* we alloc this only for weak refs, since we can get the domain directly in the other cases */
501 /* weak and weak-track arrays will be allocated in malloc memory
503 static HandleData gc_handles [] = {
504 {NULL, NULL, 0, HANDLE_WEAK, 0},
505 {NULL, NULL, 0, HANDLE_WEAK_TRACK, 0},
506 {NULL, NULL, 0, HANDLE_NORMAL, 0},
507 {NULL, NULL, 0, HANDLE_PINNED, 0}
510 #define lock_handles(handles) EnterCriticalSection (&handle_section)
511 #define unlock_handles(handles) LeaveCriticalSection (&handle_section)
514 find_first_unset (guint32 bitmap)
517 for (i = 0; i < 32; ++i) {
518 if (!(bitmap & (1 << i)))
525 alloc_handle (HandleData *handles, MonoObject *obj)
528 lock_handles (handles);
529 if (!handles->size) {
531 if (handles->type > HANDLE_WEAK_TRACK) {
532 handles->entries = mono_gc_alloc_fixed (sizeof (gpointer) * handles->size, NULL);
534 handles->entries = g_malloc0 (sizeof (gpointer) * handles->size);
535 handles->domain_ids = g_malloc0 (sizeof (guint16) * handles->size);
537 handles->bitmap = g_malloc0 (handles->size / 8);
540 for (slot = handles->slot_hint; slot < handles->size / 32; ++slot) {
541 if (handles->bitmap [slot] != 0xffffffff) {
542 i = find_first_unset (handles->bitmap [slot]);
543 handles->slot_hint = slot;
547 if (i == -1 && handles->slot_hint != 0) {
548 for (slot = 0; slot < handles->slot_hint; ++slot) {
549 if (handles->bitmap [slot] != 0xffffffff) {
550 i = find_first_unset (handles->bitmap [slot]);
551 handles->slot_hint = slot;
558 guint32 new_size = handles->size * 2; /* always double: we memset to 0 based on this below */
560 /* resize and copy the bitmap */
561 new_bitmap = g_malloc0 (new_size / 8);
562 memcpy (new_bitmap, handles->bitmap, handles->size / 8);
563 g_free (handles->bitmap);
564 handles->bitmap = new_bitmap;
566 /* resize and copy the entries */
567 if (handles->type > HANDLE_WEAK_TRACK) {
569 entries = mono_gc_alloc_fixed (sizeof (gpointer) * new_size, NULL);
570 memcpy (entries, handles->entries, sizeof (gpointer) * handles->size);
571 handles->entries = entries;
575 domain_ids = g_malloc0 (sizeof (guint16) * new_size);
576 entries = g_malloc (sizeof (gpointer) * new_size);
577 /* we disable GC because we could lose some disappearing link updates */
579 memcpy (entries, handles->entries, sizeof (gpointer) * handles->size);
580 memset (entries + handles->size, 0, sizeof (gpointer) * handles->size);
581 memcpy (domain_ids, handles->domain_ids, sizeof (guint16) * handles->size);
582 for (i = 0; i < handles->size; ++i) {
583 MonoObject *obj = mono_gc_weak_link_get (&(handles->entries [i]));
584 if (handles->entries [i])
585 mono_gc_weak_link_remove (&(handles->entries [i]));
586 /*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]);*/
588 mono_gc_weak_link_add (&(entries [i]), obj);
591 g_free (handles->entries);
592 g_free (handles->domain_ids);
593 handles->entries = entries;
594 handles->domain_ids = domain_ids;
598 /* set i and slot to the next free position */
600 slot = (handles->size + 1) / 32;
601 handles->slot_hint = handles->size + 1;
602 handles->size = new_size;
604 handles->bitmap [slot] |= 1 << i;
605 slot = slot * 32 + i;
606 handles->entries [slot] = obj;
607 if (handles->type <= HANDLE_WEAK_TRACK) {
609 mono_gc_weak_link_add (&(handles->entries [slot]), obj);
612 mono_perfcounters->gc_num_handles++;
613 unlock_handles (handles);
614 /*g_print ("allocated entry %d of type %d to object %p (in slot: %p)\n", slot, handles->type, obj, handles->entries [slot]);*/
615 return (slot << 3) | (handles->type + 1);
620 * @obj: managed object to get a handle for
621 * @pinned: whether the object should be pinned
623 * This returns a handle that wraps the object, this is used to keep a
624 * reference to a managed object from the unmanaged world and preventing the
625 * object from being disposed.
627 * If @pinned is false the address of the object can not be obtained, if it is
628 * true the address of the object can be obtained. This will also pin the
629 * object so it will not be possible by a moving garbage collector to move the
632 * Returns: a handle that can be used to access the object from
636 mono_gchandle_new (MonoObject *obj, gboolean pinned)
638 return alloc_handle (&gc_handles [pinned? HANDLE_PINNED: HANDLE_NORMAL], obj);
642 * mono_gchandle_new_weakref:
643 * @obj: managed object to get a handle for
644 * @pinned: whether the object should be pinned
646 * This returns a weak handle that wraps the object, this is used to
647 * keep a reference to a managed object from the unmanaged world.
648 * Unlike the mono_gchandle_new the object can be reclaimed by the
649 * garbage collector. In this case the value of the GCHandle will be
652 * If @pinned is false the address of the object can not be obtained, if it is
653 * true the address of the object can be obtained. This will also pin the
654 * object so it will not be possible by a moving garbage collector to move the
657 * Returns: a handle that can be used to access the object from
661 mono_gchandle_new_weakref (MonoObject *obj, gboolean track_resurrection)
663 return alloc_handle (&gc_handles [track_resurrection? HANDLE_WEAK_TRACK: HANDLE_WEAK], obj);
667 mono_gchandle_get_type (guint32 gchandle)
669 guint type = (gchandle & 7) - 1;
675 * mono_gchandle_get_target:
676 * @gchandle: a GCHandle's handle.
678 * The handle was previously created by calling mono_gchandle_new or
679 * mono_gchandle_new_weakref.
681 * Returns a pointer to the MonoObject represented by the handle or
682 * NULL for a collected object if using a weakref handle.
685 mono_gchandle_get_target (guint32 gchandle)
687 guint slot = gchandle >> 3;
688 guint type = (gchandle & 7) - 1;
689 HandleData *handles = &gc_handles [type];
690 MonoObject *obj = NULL;
693 lock_handles (handles);
694 if (slot < handles->size && (handles->bitmap [slot / 32] & (1 << (slot % 32)))) {
695 if (handles->type <= HANDLE_WEAK_TRACK) {
696 obj = mono_gc_weak_link_get (&handles->entries [slot]);
698 obj = handles->entries [slot];
701 /* print a warning? */
703 unlock_handles (handles);
704 /*g_print ("get target of entry %d of type %d: %p\n", slot, handles->type, obj);*/
709 mono_gchandle_set_target (guint32 gchandle, MonoObject *obj)
711 guint slot = gchandle >> 3;
712 guint type = (gchandle & 7) - 1;
713 HandleData *handles = &gc_handles [type];
716 lock_handles (handles);
717 if (slot < handles->size && (handles->bitmap [slot / 32] & (1 << (slot % 32)))) {
718 if (handles->type <= HANDLE_WEAK_TRACK) {
719 if (handles->entries [slot])
720 mono_gc_weak_link_remove (&handles->entries [slot]);
722 mono_gc_weak_link_add (&handles->entries [slot], obj);
724 handles->entries [slot] = obj;
727 /* print a warning? */
729 /*g_print ("changed entry %d of type %d to object %p (in slot: %p)\n", slot, handles->type, obj, handles->entries [slot]);*/
730 unlock_handles (handles);
734 * mono_gchandle_is_in_domain:
735 * @gchandle: a GCHandle's handle.
736 * @domain: An application domain.
738 * Returns: true if the object wrapped by the @gchandle belongs to the specific @domain.
741 mono_gchandle_is_in_domain (guint32 gchandle, MonoDomain *domain)
743 guint slot = gchandle >> 3;
744 guint type = (gchandle & 7) - 1;
745 HandleData *handles = &gc_handles [type];
746 gboolean result = FALSE;
749 lock_handles (handles);
750 if (slot < handles->size && (handles->bitmap [slot / 32] & (1 << (slot % 32)))) {
751 if (handles->type <= HANDLE_WEAK_TRACK) {
752 result = domain->domain_id == handles->domain_ids [slot];
755 obj = handles->entries [slot];
759 result = domain == mono_object_domain (obj);
762 /* print a warning? */
764 unlock_handles (handles);
769 * mono_gchandle_free:
770 * @gchandle: a GCHandle's handle.
772 * Frees the @gchandle handle. If there are no outstanding
773 * references, the garbage collector can reclaim the memory of the
777 mono_gchandle_free (guint32 gchandle)
779 guint slot = gchandle >> 3;
780 guint type = (gchandle & 7) - 1;
781 HandleData *handles = &gc_handles [type];
784 lock_handles (handles);
785 if (slot < handles->size && (handles->bitmap [slot / 32] & (1 << (slot % 32)))) {
786 if (handles->type <= HANDLE_WEAK_TRACK) {
787 if (handles->entries [slot])
788 mono_gc_weak_link_remove (&handles->entries [slot]);
790 handles->entries [slot] = NULL;
792 handles->bitmap [slot / 32] &= ~(1 << (slot % 32));
794 /* print a warning? */
796 mono_perfcounters->gc_num_handles--;
797 /*g_print ("freed entry %d of type %d\n", slot, handles->type);*/
798 unlock_handles (handles);
802 * mono_gchandle_free_domain:
803 * @domain: domain that is unloading
805 * Function used internally to cleanup any GC handle for objects belonging
806 * to the specified domain during appdomain unload.
809 mono_gchandle_free_domain (MonoDomain *domain)
813 for (type = 0; type < 3; ++type) {
815 HandleData *handles = &gc_handles [type];
816 lock_handles (handles);
817 for (slot = 0; slot < handles->size; ++slot) {
818 if (!(handles->bitmap [slot / 32] & (1 << (slot % 32))))
820 if (type <= HANDLE_WEAK_TRACK) {
821 if (domain->domain_id == handles->domain_ids [slot]) {
822 handles->bitmap [slot / 32] &= ~(1 << (slot % 32));
823 if (handles->entries [slot])
824 mono_gc_weak_link_remove (&handles->entries [slot]);
827 if (handles->entries [slot] && mono_object_domain (handles->entries [slot]) == domain) {
828 handles->bitmap [slot / 32] &= ~(1 << (slot % 32));
829 handles->entries [slot] = NULL;
833 unlock_handles (handles);
841 static sem_t finalizer_sem;
843 static HANDLE finalizer_event;
844 static volatile gboolean finished=FALSE;
847 mono_gc_finalize_notify (void)
850 g_message (G_GNUC_PRETTY_FUNCTION ": prodding finalizer");
854 sem_post (&finalizer_sem);
856 SetEvent (finalizer_event);
863 collect_objects (gpointer key, gpointer value, gpointer user_data)
865 GPtrArray *arr = (GPtrArray*)user_data;
866 g_ptr_array_add (arr, key);
872 * finalize_domain_objects:
874 * Run the finalizers of all finalizable objects in req->domain.
877 finalize_domain_objects (DomainFinalizationReq *req)
879 MonoDomain *domain = req->domain;
882 while (g_hash_table_size (domain->finalizable_objects_hash) > 0) {
886 * Since the domain is unloading, nobody is allowed to put
887 * new entries into the hash table. But finalize_object might
888 * remove entries from the hash table, so we make a copy.
890 objs = g_ptr_array_new ();
891 g_hash_table_foreach (domain->finalizable_objects_hash, collect_objects, objs);
892 /* printf ("FINALIZING %d OBJECTS.\n", objs->len); */
894 for (i = 0; i < objs->len; ++i) {
895 MonoObject *o = (MonoObject*)g_ptr_array_index (objs, i);
896 /* FIXME: Avoid finalizing threads, etc */
900 g_ptr_array_free (objs, TRUE);
902 #elif defined(HAVE_SGEN_GC)
903 #define NUM_FOBJECTS 64
904 MonoObject *to_finalize [NUM_FOBJECTS];
906 while ((count = mono_gc_finalizers_for_domain (domain, to_finalize, NUM_FOBJECTS))) {
908 for (i = 0; i < count; ++i) {
909 run_finalize (to_finalize [i], 0);
914 /* Process finalizers which are already in the queue */
915 mono_gc_invoke_finalizers ();
917 /* printf ("DONE.\n"); */
918 SetEvent (req->done_event);
920 /* The event is closed in mono_domain_finalize if we get here */
925 finalizer_thread (gpointer unused)
927 gc_thread = mono_thread_current ();
929 SetEvent (thread_started_event);
932 /* Wait to be notified that there's at least one
936 sem_wait (&finalizer_sem);
938 /* Use alertable=FALSE since we will be asked to exit using the event too */
939 WaitForSingleObjectEx (finalizer_event, INFINITE, FALSE);
942 #ifndef DISABLE_ATTACH
943 mono_attach_maybe_start ();
946 if (domains_to_finalize) {
947 mono_finalizer_lock ();
948 if (domains_to_finalize) {
949 DomainFinalizationReq *req = domains_to_finalize->data;
950 domains_to_finalize = g_slist_remove (domains_to_finalize, req);
951 mono_finalizer_unlock ();
953 finalize_domain_objects (req);
955 mono_finalizer_unlock ();
959 /* If finished == TRUE, mono_gc_cleanup has been called (from mono_runtime_cleanup),
960 * before the domain is unloaded.
962 mono_gc_invoke_finalizers ();
964 SetEvent (pending_done_event);
967 SetEvent (shutdown_event);
974 InitializeCriticalSection (&handle_section);
975 InitializeCriticalSection (&allocator_section);
977 InitializeCriticalSection (&finalizer_mutex);
979 MONO_GC_REGISTER_ROOT (gc_handles [HANDLE_NORMAL].entries);
980 MONO_GC_REGISTER_ROOT (gc_handles [HANDLE_PINNED].entries);
982 mono_gc_base_init ();
984 if (g_getenv ("GC_DONT_GC")) {
989 finalizer_event = CreateEvent (NULL, FALSE, FALSE, NULL);
990 pending_done_event = CreateEvent (NULL, TRUE, FALSE, NULL);
991 shutdown_event = CreateEvent (NULL, TRUE, FALSE, NULL);
992 thread_started_event = CreateEvent (NULL, TRUE, FALSE, NULL);
993 if (finalizer_event == NULL || pending_done_event == NULL || shutdown_event == NULL || thread_started_event == NULL) {
994 g_assert_not_reached ();
997 sem_init (&finalizer_sem, 0, 0);
1000 mono_thread_create (mono_domain_get (), finalizer_thread, NULL);
1003 * Wait until the finalizer thread sets gc_thread since its value is needed
1004 * by mono_thread_attach ()
1006 * FIXME: Eliminate this as to avoid some deadlocks on windows.
1007 * Waiting for a new thread should result in a deadlock when the runtime is
1008 * initialized from _CorDllMain that is called while the OS loader lock is
1009 * held by LoadLibrary.
1011 WaitForSingleObjectEx (thread_started_event, INFINITE, FALSE);
1015 mono_gc_cleanup (void)
1018 g_message (G_GNUC_PRETTY_FUNCTION ": cleaning up finalizer");
1022 ResetEvent (shutdown_event);
1024 if (mono_thread_current () != gc_thread) {
1025 mono_gc_finalize_notify ();
1026 /* Finishing the finalizer thread, so wait a little bit... */
1027 /* MS seems to wait for about 2 seconds */
1028 if (WaitForSingleObjectEx (shutdown_event, 2000, FALSE) == WAIT_TIMEOUT) {
1031 /* Set a flag which the finalizer thread can check */
1032 suspend_finalizers = TRUE;
1034 /* Try to abort the thread, in the hope that it is running managed code */
1035 mono_thread_stop (gc_thread);
1037 /* Wait for it to stop */
1038 ret = WaitForSingleObjectEx (gc_thread->handle, 100, TRUE);
1040 if (ret == WAIT_TIMEOUT) {
1042 * The finalizer thread refused to die. There is not much we
1043 * can do here, since the runtime is shutting down so the
1044 * state the finalizer thread depends on will vanish.
1046 g_warning ("Shutting down finalizer thread timed out.");
1049 * FIXME: On unix, when the above wait returns, the thread
1050 * might still be running io-layer code, or pthreads code.
1058 #ifdef HAVE_BOEHM_GC
1059 GC_finalizer_notifier = NULL;
1063 DeleteCriticalSection (&handle_section);
1064 DeleteCriticalSection (&allocator_section);
1065 DeleteCriticalSection (&finalizer_mutex);
1070 /* Null GC dummy functions */
1072 mono_gc_finalize_notify (void)
1076 void mono_gc_init (void)
1078 InitializeCriticalSection (&handle_section);
1081 void mono_gc_cleanup (void)
1088 * mono_gc_is_finalizer_thread:
1089 * @thread: the thread to test.
1091 * In Mono objects are finalized asynchronously on a separate thread.
1092 * This routine tests whether the @thread argument represents the
1093 * finalization thread.
1095 * Returns true if @thread is the finalization thread.
1098 mono_gc_is_finalizer_thread (MonoThread *thread)
1100 return thread == gc_thread;