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/metadata-internals.h>
23 #include <mono/metadata/mono-mlist.h>
24 #include <mono/metadata/threadpool.h>
25 #include <mono/metadata/threads-types.h>
26 #include <mono/utils/mono-logger.h>
27 #include <mono/metadata/gc-internal.h>
28 #include <mono/metadata/marshal.h> /* for mono_delegate_free_ftnptr () */
29 #include <mono/metadata/attach.h>
31 #include <semaphore.h>
32 /* we do this only for known working systems (OSX for example
33 * has the header and functions, but they don't work at all): in other cases
34 * we fall back to the io-layer slightly slower and signal-unsafe Event.
37 #define USE_POSIX_SEM 1
41 #ifndef PLATFORM_WIN32
45 typedef struct DomainFinalizationReq {
48 } DomainFinalizationReq;
50 #ifdef PLATFORM_WINCE /* FIXME: add accessors to gc.dll API */
51 extern void (*__imp_GC_finalizer_notifier)(void);
52 #define GC_finalizer_notifier __imp_GC_finalizer_notifier
53 extern int __imp_GC_finalize_on_demand;
54 #define GC_finalize_on_demand __imp_GC_finalize_on_demand
57 static gboolean gc_disabled = FALSE;
59 static gboolean finalizing_root_domain = FALSE;
61 #define mono_finalizer_lock() EnterCriticalSection (&finalizer_mutex)
62 #define mono_finalizer_unlock() LeaveCriticalSection (&finalizer_mutex)
63 static CRITICAL_SECTION finalizer_mutex;
65 static GSList *domains_to_finalize= NULL;
66 static MonoMList *threads_to_finalize = NULL;
68 static MonoThread *gc_thread;
70 static void object_register_finalizer (MonoObject *obj, void (*callback)(void *, void*));
72 static void mono_gchandle_set_target (guint32 gchandle, MonoObject *obj);
75 static HANDLE pending_done_event;
76 static HANDLE shutdown_event;
80 add_thread_to_finalize (MonoThread *thread)
82 mono_finalizer_lock ();
83 if (!threads_to_finalize)
84 MONO_GC_REGISTER_ROOT (threads_to_finalize);
85 threads_to_finalize = mono_mlist_append (threads_to_finalize, (MonoObject*)thread);
86 mono_finalizer_unlock ();
89 static gboolean suspend_finalizers = FALSE;
91 * actually, we might want to queue the finalize requests in a separate thread,
92 * but we need to be careful about the execution domain of the thread...
95 mono_gc_run_finalize (void *obj, void *data)
97 MonoObject *exc = NULL;
102 MonoMethod* finalizer = NULL;
103 MonoDomain *caller_domain = mono_domain_get ();
105 RuntimeInvokeFunction runtime_invoke;
106 GSList *l, *refs = NULL;
108 o = (MonoObject*)((char*)obj + GPOINTER_TO_UINT (data));
110 if (suspend_finalizers)
113 domain = o->vtable->domain;
116 mono_domain_finalizers_lock (domain);
118 o2 = g_hash_table_lookup (domain->finalizable_objects_hash, o);
120 refs = mono_gc_remove_weak_track_object (domain, o);
122 mono_domain_finalizers_unlock (domain);
125 /* Already finalized somehow */
131 * Support for GCHandles of type WeakTrackResurrection:
133 * Its not exactly clear how these are supposed to work, or how their
134 * semantics can be implemented. We only implement one crucial thing:
135 * these handles are only cleared after the finalizer has ran.
137 for (l = refs; l; l = l->next) {
138 guint32 gchandle = GPOINTER_TO_UINT (l->data);
140 mono_gchandle_set_target (gchandle, o);
146 /* make sure the finalizer is not called again if the object is resurrected */
147 object_register_finalizer (obj, NULL);
149 if (o->vtable->klass == mono_get_thread_class ()) {
150 MonoThread *t = (MonoThread*)o;
152 if (mono_gc_is_finalizer_thread (t))
153 /* Avoid finalizing ourselves */
156 if (t->threadpool_thread && finalizing_root_domain) {
157 /* Don't finalize threadpool threads when
158 shutting down - they're finalized when the
159 threadpool shuts down. */
160 add_thread_to_finalize (t);
165 if (mono_runtime_get_no_exec ())
168 /* speedup later... and use a timeout */
169 /* g_print ("Finalize run on %p %s.%s\n", o, mono_object_class (o)->name_space, mono_object_class (o)->name); */
171 /* Use _internal here, since this thread can enter a doomed appdomain */
172 mono_domain_set_internal (mono_object_domain (o));
174 /* delegates that have a native function pointer allocated are
175 * registered for finalization, but they don't have a Finalize
176 * method, because in most cases it's not needed and it's just a waste.
178 if (o->vtable->klass->delegate) {
179 MonoDelegate* del = (MonoDelegate*)o;
180 if (del->delegate_trampoline)
181 mono_delegate_free_ftnptr ((MonoDelegate*)o);
185 finalizer = mono_class_get_finalizer (o->vtable->klass);
188 /* If object has a CCW but has no finalizer, it was only
189 * registered for finalization in order to free the CCW.
190 * Else it needs the regular finalizer run.
191 * FIXME: what to do about ressurection and suppression
192 * of finalizer on object with CCW.
194 if (mono_marshal_free_ccw (o) && !finalizer) {
195 mono_domain_set_internal (caller_domain);
201 * To avoid the locking plus the other overhead of mono_runtime_invoke (),
202 * create and precompile a wrapper which calls the finalize method using
205 if (!domain->finalize_runtime_invoke) {
206 MonoMethod *invoke = mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE);
208 domain->finalize_runtime_invoke = mono_compile_method (invoke);
211 runtime_invoke = domain->finalize_runtime_invoke;
213 mono_runtime_class_init (o->vtable);
215 runtime_invoke (o, NULL, &exc, NULL);
218 /* fixme: do something useful */
221 mono_domain_set_internal (caller_domain);
225 mono_gc_finalize_threadpool_threads (void)
227 while (threads_to_finalize) {
228 MonoThread *thread = (MonoThread*) mono_mlist_get_data (threads_to_finalize);
230 /* Force finalization of the thread. */
231 thread->threadpool_thread = FALSE;
232 mono_object_register_finalizer ((MonoObject*)thread);
234 mono_gc_run_finalize (thread, NULL);
236 threads_to_finalize = mono_mlist_next (threads_to_finalize);
241 mono_gc_out_of_memory (size_t size)
244 * we could allocate at program startup some memory that we could release
245 * back to the system at this point if we're really low on memory (ie, size is
246 * lower than the memory we set apart)
248 mono_raise_exception (mono_domain_get ()->out_of_memory_ex);
254 * Some of our objects may point to a different address than the address returned by GC_malloc()
255 * (because of the GetHashCode hack), but we need to pass the real address to register_finalizer.
256 * This also means that in the callback we need to adjust the pointer to get back the real
258 * We also need to be consistent in the use of the GC_debug* variants of malloc and register_finalizer,
259 * since that, too, can cause the underlying pointer to be offset.
262 object_register_finalizer (MonoObject *obj, void (*callback)(void *, void*))
266 MonoDomain *domain = obj->vtable->domain;
269 /* This assertion is not valid when GC_DEBUG is defined */
270 g_assert (GC_base (obj) == (char*)obj - offset);
273 if (mono_domain_is_unloading (domain) && (callback != NULL))
275 * Can't register finalizers in a dying appdomain, since they
276 * could be invoked after the appdomain has been unloaded.
280 mono_domain_finalizers_lock (domain);
283 g_hash_table_insert (domain->finalizable_objects_hash, obj, obj);
285 g_hash_table_remove (domain->finalizable_objects_hash, obj);
287 mono_domain_finalizers_unlock (domain);
289 GC_REGISTER_FINALIZER_NO_ORDER ((char*)obj - offset, callback, GUINT_TO_POINTER (offset), NULL, NULL);
290 #elif defined(HAVE_SGEN_GC)
291 mono_gc_register_for_finalization (obj, callback);
296 * mono_object_register_finalizer:
297 * @obj: object to register
299 * Records that object @obj has a finalizer, this will call the
300 * Finalize method when the garbage collector disposes the object.
304 mono_object_register_finalizer (MonoObject *obj)
306 /* g_print ("Registered finalizer on %p %s.%s\n", obj, mono_object_class (obj)->name_space, mono_object_class (obj)->name); */
307 object_register_finalizer (obj, mono_gc_run_finalize);
311 * mono_domain_finalize:
312 * @domain: the domain to finalize
313 * @timeout: msects to wait for the finalization to complete, -1 to wait indefinitely
315 * Request finalization of all finalizable objects inside @domain. Wait
316 * @timeout msecs for the finalization to complete.
318 * Returns: TRUE if succeeded, FALSE if there was a timeout
322 mono_domain_finalize (MonoDomain *domain, guint32 timeout)
324 DomainFinalizationReq *req;
328 if (mono_thread_current () == gc_thread)
329 /* We are called from inside a finalizer, not much we can do here */
333 * No need to create another thread 'cause the finalizer thread
334 * is still working and will take care of running the finalizers
341 mono_gc_collect (mono_gc_max_generation ());
343 done_event = CreateEvent (NULL, TRUE, FALSE, NULL);
344 if (done_event == NULL) {
348 req = g_new0 (DomainFinalizationReq, 1);
349 req->domain = domain;
350 req->done_event = done_event;
352 if (domain == mono_get_root_domain ())
353 finalizing_root_domain = TRUE;
355 mono_finalizer_lock ();
357 domains_to_finalize = g_slist_append (domains_to_finalize, req);
359 mono_finalizer_unlock ();
361 /* Tell the finalizer thread to finalize this appdomain */
362 mono_gc_finalize_notify ();
367 res = WaitForSingleObjectEx (done_event, timeout, TRUE);
369 /* printf ("WAIT RES: %d.\n", res); */
370 if (res == WAIT_TIMEOUT) {
371 /* We leak the handle here */
375 CloseHandle (done_event);
377 if (domain == mono_get_root_domain ()) {
378 mono_thread_pool_cleanup ();
379 mono_gc_finalize_threadpool_threads ();
384 /* We don't support domain finalization without a GC */
390 ves_icall_System_GC_InternalCollect (int generation)
392 mono_gc_collect (generation);
396 ves_icall_System_GC_GetTotalMemory (MonoBoolean forceCollection)
401 mono_gc_collect (mono_gc_max_generation ());
402 return mono_gc_get_used_size ();
406 ves_icall_System_GC_KeepAlive (MonoObject *obj)
416 ves_icall_System_GC_ReRegisterForFinalize (MonoObject *obj)
420 object_register_finalizer (obj, mono_gc_run_finalize);
424 ves_icall_System_GC_SuppressFinalize (MonoObject *obj)
428 /* delegates have no finalizers, but we register them to deal with the
429 * unmanaged->managed trampoline. We don't let the user suppress it
430 * otherwise we'd leak it.
432 if (obj->vtable->klass->delegate)
435 /* FIXME: Need to handle case where obj has COM Callable Wrapper
436 * generated for it that needs cleaned up, but user wants to suppress
437 * their derived object finalizer. */
439 object_register_finalizer (obj, NULL);
443 ves_icall_System_GC_WaitForPendingFinalizers (void)
446 if (!mono_gc_pending_finalizers ())
449 if (mono_thread_current () == gc_thread)
450 /* Avoid deadlocks */
453 ResetEvent (pending_done_event);
454 mono_gc_finalize_notify ();
455 /* g_print ("Waiting for pending finalizers....\n"); */
456 WaitForSingleObjectEx (pending_done_event, INFINITE, TRUE);
457 /* g_print ("Done pending....\n"); */
461 #define mono_allocator_lock() EnterCriticalSection (&allocator_section)
462 #define mono_allocator_unlock() LeaveCriticalSection (&allocator_section)
463 static CRITICAL_SECTION allocator_section;
464 static CRITICAL_SECTION handle_section;
473 static HandleType mono_gchandle_get_type (guint32 gchandle);
476 ves_icall_System_GCHandle_GetTarget (guint32 handle)
478 return mono_gchandle_get_target (handle);
482 * if type == -1, change the target of the handle, otherwise allocate a new handle.
485 ves_icall_System_GCHandle_GetTargetHandle (MonoObject *obj, guint32 handle, gint32 type)
488 mono_gchandle_set_target (handle, obj);
489 /* the handle doesn't change */
494 return mono_gchandle_new_weakref (obj, FALSE);
495 case HANDLE_WEAK_TRACK:
496 return mono_gchandle_new_weakref (obj, TRUE);
498 return mono_gchandle_new (obj, FALSE);
500 return mono_gchandle_new (obj, TRUE);
502 g_assert_not_reached ();
508 ves_icall_System_GCHandle_FreeHandle (guint32 handle)
510 mono_gchandle_free (handle);
514 ves_icall_System_GCHandle_GetAddrOfPinnedObject (guint32 handle)
518 if (mono_gchandle_get_type (handle) != HANDLE_PINNED)
520 obj = mono_gchandle_get_target (handle);
522 MonoClass *klass = mono_object_class (obj);
523 if (klass == mono_defaults.string_class) {
524 return mono_string_chars ((MonoString*)obj);
525 } else if (klass->rank) {
526 return mono_array_addr ((MonoArray*)obj, char, 0);
528 /* the C# code will check and throw the exception */
529 /* FIXME: missing !klass->blittable test, see bug #61134 */
530 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
532 return (char*)obj + sizeof (MonoObject);
543 guint slot_hint : 24; /* starting slot for search */
544 /* 2^16 appdomains should be enough for everyone (though I know I'll regret this in 20 years) */
545 /* we alloc this only for weak refs, since we can get the domain directly in the other cases */
549 /* weak and weak-track arrays will be allocated in malloc memory
551 static HandleData gc_handles [] = {
552 {NULL, NULL, 0, HANDLE_WEAK, 0},
553 {NULL, NULL, 0, HANDLE_WEAK_TRACK, 0},
554 {NULL, NULL, 0, HANDLE_NORMAL, 0},
555 {NULL, NULL, 0, HANDLE_PINNED, 0}
558 #define lock_handles(handles) EnterCriticalSection (&handle_section)
559 #define unlock_handles(handles) LeaveCriticalSection (&handle_section)
562 find_first_unset (guint32 bitmap)
565 for (i = 0; i < 32; ++i) {
566 if (!(bitmap & (1 << i)))
573 alloc_handle (HandleData *handles, MonoObject *obj, gboolean track)
576 lock_handles (handles);
577 if (!handles->size) {
579 if (handles->type > HANDLE_WEAK_TRACK) {
580 handles->entries = mono_gc_alloc_fixed (sizeof (gpointer) * handles->size, NULL);
582 handles->entries = g_malloc0 (sizeof (gpointer) * handles->size);
583 handles->domain_ids = g_malloc0 (sizeof (guint16) * handles->size);
585 handles->bitmap = g_malloc0 (handles->size / 8);
588 for (slot = handles->slot_hint; slot < handles->size / 32; ++slot) {
589 if (handles->bitmap [slot] != 0xffffffff) {
590 i = find_first_unset (handles->bitmap [slot]);
591 handles->slot_hint = slot;
595 if (i == -1 && handles->slot_hint != 0) {
596 for (slot = 0; slot < handles->slot_hint; ++slot) {
597 if (handles->bitmap [slot] != 0xffffffff) {
598 i = find_first_unset (handles->bitmap [slot]);
599 handles->slot_hint = slot;
606 guint32 new_size = handles->size * 2; /* always double: we memset to 0 based on this below */
608 /* resize and copy the bitmap */
609 new_bitmap = g_malloc0 (new_size / 8);
610 memcpy (new_bitmap, handles->bitmap, handles->size / 8);
611 g_free (handles->bitmap);
612 handles->bitmap = new_bitmap;
614 /* resize and copy the entries */
615 if (handles->type > HANDLE_WEAK_TRACK) {
617 entries = mono_gc_alloc_fixed (sizeof (gpointer) * new_size, NULL);
618 memcpy (entries, handles->entries, sizeof (gpointer) * handles->size);
619 handles->entries = entries;
623 domain_ids = g_malloc0 (sizeof (guint16) * new_size);
624 entries = g_malloc (sizeof (gpointer) * new_size);
625 /* we disable GC because we could lose some disappearing link updates */
627 memcpy (entries, handles->entries, sizeof (gpointer) * handles->size);
628 memset (entries + handles->size, 0, sizeof (gpointer) * handles->size);
629 memcpy (domain_ids, handles->domain_ids, sizeof (guint16) * handles->size);
630 for (i = 0; i < handles->size; ++i) {
631 MonoObject *obj = mono_gc_weak_link_get (&(handles->entries [i]));
632 if (handles->entries [i])
633 mono_gc_weak_link_remove (&(handles->entries [i]));
634 /*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]);*/
636 mono_gc_weak_link_add (&(entries [i]), obj, track);
639 g_free (handles->entries);
640 g_free (handles->domain_ids);
641 handles->entries = entries;
642 handles->domain_ids = domain_ids;
646 /* set i and slot to the next free position */
648 slot = (handles->size + 1) / 32;
649 handles->slot_hint = handles->size + 1;
650 handles->size = new_size;
652 handles->bitmap [slot] |= 1 << i;
653 slot = slot * 32 + i;
654 handles->entries [slot] = obj;
655 if (handles->type <= HANDLE_WEAK_TRACK) {
657 mono_gc_weak_link_add (&(handles->entries [slot]), obj, track);
660 mono_perfcounters->gc_num_handles++;
661 unlock_handles (handles);
662 /*g_print ("allocated entry %d of type %d to object %p (in slot: %p)\n", slot, handles->type, obj, handles->entries [slot]);*/
663 return (slot << 3) | (handles->type + 1);
668 * @obj: managed object to get a handle for
669 * @pinned: whether the object should be pinned
671 * This returns a handle that wraps the object, this is used to keep a
672 * reference to a managed object from the unmanaged world and preventing the
673 * object from being disposed.
675 * If @pinned is false the address of the object can not be obtained, if it is
676 * true the address of the object can be obtained. This will also pin the
677 * object so it will not be possible by a moving garbage collector to move the
680 * Returns: a handle that can be used to access the object from
684 mono_gchandle_new (MonoObject *obj, gboolean pinned)
686 return alloc_handle (&gc_handles [pinned? HANDLE_PINNED: HANDLE_NORMAL], obj, FALSE);
690 * mono_gchandle_new_weakref:
691 * @obj: managed object to get a handle for
692 * @pinned: whether the object should be pinned
694 * This returns a weak handle that wraps the object, this is used to
695 * keep a reference to a managed object from the unmanaged world.
696 * Unlike the mono_gchandle_new the object can be reclaimed by the
697 * garbage collector. In this case the value of the GCHandle will be
700 * If @pinned is false the address of the object can not be obtained, if it is
701 * true the address of the object can be obtained. This will also pin the
702 * object so it will not be possible by a moving garbage collector to move the
705 * Returns: a handle that can be used to access the object from
709 mono_gchandle_new_weakref (MonoObject *obj, gboolean track_resurrection)
711 guint32 handle = alloc_handle (&gc_handles [track_resurrection? HANDLE_WEAK_TRACK: HANDLE_WEAK], obj, track_resurrection);
714 if (track_resurrection)
715 mono_gc_add_weak_track_handle (obj, handle);
722 mono_gchandle_get_type (guint32 gchandle)
724 guint type = (gchandle & 7) - 1;
730 * mono_gchandle_get_target:
731 * @gchandle: a GCHandle's handle.
733 * The handle was previously created by calling mono_gchandle_new or
734 * mono_gchandle_new_weakref.
736 * Returns a pointer to the MonoObject represented by the handle or
737 * NULL for a collected object if using a weakref handle.
740 mono_gchandle_get_target (guint32 gchandle)
742 guint slot = gchandle >> 3;
743 guint type = (gchandle & 7) - 1;
744 HandleData *handles = &gc_handles [type];
745 MonoObject *obj = NULL;
748 lock_handles (handles);
749 if (slot < handles->size && (handles->bitmap [slot / 32] & (1 << (slot % 32)))) {
750 if (handles->type <= HANDLE_WEAK_TRACK) {
751 obj = mono_gc_weak_link_get (&handles->entries [slot]);
753 obj = handles->entries [slot];
756 /* print a warning? */
758 unlock_handles (handles);
759 /*g_print ("get target of entry %d of type %d: %p\n", slot, handles->type, obj);*/
764 mono_gchandle_set_target (guint32 gchandle, MonoObject *obj)
766 guint slot = gchandle >> 3;
767 guint type = (gchandle & 7) - 1;
768 HandleData *handles = &gc_handles [type];
769 MonoObject *old_obj = NULL;
773 lock_handles (handles);
774 if (slot < handles->size && (handles->bitmap [slot / 32] & (1 << (slot % 32)))) {
775 if (handles->type <= HANDLE_WEAK_TRACK) {
776 old_obj = handles->entries [slot];
777 if (handles->entries [slot])
778 mono_gc_weak_link_remove (&handles->entries [slot]);
780 mono_gc_weak_link_add (&handles->entries [slot], obj, handles->type == HANDLE_WEAK_TRACK);
782 handles->entries [slot] = obj;
785 /* print a warning? */
787 /*g_print ("changed entry %d of type %d to object %p (in slot: %p)\n", slot, handles->type, obj, handles->entries [slot]);*/
788 unlock_handles (handles);
791 if (type == HANDLE_WEAK_TRACK)
792 mono_gc_change_weak_track_handle (old_obj, obj, gchandle);
797 * mono_gchandle_is_in_domain:
798 * @gchandle: a GCHandle's handle.
799 * @domain: An application domain.
801 * Returns: true if the object wrapped by the @gchandle belongs to the specific @domain.
804 mono_gchandle_is_in_domain (guint32 gchandle, MonoDomain *domain)
806 guint slot = gchandle >> 3;
807 guint type = (gchandle & 7) - 1;
808 HandleData *handles = &gc_handles [type];
809 gboolean result = FALSE;
812 lock_handles (handles);
813 if (slot < handles->size && (handles->bitmap [slot / 32] & (1 << (slot % 32)))) {
814 if (handles->type <= HANDLE_WEAK_TRACK) {
815 result = domain->domain_id == handles->domain_ids [slot];
818 obj = handles->entries [slot];
822 result = domain == mono_object_domain (obj);
825 /* print a warning? */
827 unlock_handles (handles);
832 * mono_gchandle_free:
833 * @gchandle: a GCHandle's handle.
835 * Frees the @gchandle handle. If there are no outstanding
836 * references, the garbage collector can reclaim the memory of the
840 mono_gchandle_free (guint32 gchandle)
842 guint slot = gchandle >> 3;
843 guint type = (gchandle & 7) - 1;
844 HandleData *handles = &gc_handles [type];
848 if (type == HANDLE_WEAK_TRACK)
849 mono_gc_remove_weak_track_handle (gchandle);
852 lock_handles (handles);
853 if (slot < handles->size && (handles->bitmap [slot / 32] & (1 << (slot % 32)))) {
854 if (handles->type <= HANDLE_WEAK_TRACK) {
855 if (handles->entries [slot])
856 mono_gc_weak_link_remove (&handles->entries [slot]);
858 handles->entries [slot] = NULL;
860 handles->bitmap [slot / 32] &= ~(1 << (slot % 32));
862 /* print a warning? */
864 mono_perfcounters->gc_num_handles--;
865 /*g_print ("freed entry %d of type %d\n", slot, handles->type);*/
866 unlock_handles (handles);
870 * mono_gchandle_free_domain:
871 * @domain: domain that is unloading
873 * Function used internally to cleanup any GC handle for objects belonging
874 * to the specified domain during appdomain unload.
877 mono_gchandle_free_domain (MonoDomain *domain)
881 for (type = 0; type < 3; ++type) {
883 HandleData *handles = &gc_handles [type];
884 lock_handles (handles);
885 for (slot = 0; slot < handles->size; ++slot) {
886 if (!(handles->bitmap [slot / 32] & (1 << (slot % 32))))
888 if (type <= HANDLE_WEAK_TRACK) {
889 if (domain->domain_id == handles->domain_ids [slot]) {
890 handles->bitmap [slot / 32] &= ~(1 << (slot % 32));
891 if (handles->entries [slot])
892 mono_gc_weak_link_remove (&handles->entries [slot]);
895 if (handles->entries [slot] && mono_object_domain (handles->entries [slot]) == domain) {
896 handles->bitmap [slot / 32] &= ~(1 << (slot % 32));
897 handles->entries [slot] = NULL;
901 unlock_handles (handles);
909 static sem_t finalizer_sem;
911 static HANDLE finalizer_event;
912 static volatile gboolean finished=FALSE;
915 mono_gc_finalize_notify (void)
918 g_message (G_GNUC_PRETTY_FUNCTION ": prodding finalizer");
922 sem_post (&finalizer_sem);
924 SetEvent (finalizer_event);
931 collect_objects (gpointer key, gpointer value, gpointer user_data)
933 GPtrArray *arr = (GPtrArray*)user_data;
934 g_ptr_array_add (arr, key);
940 * finalize_domain_objects:
942 * Run the finalizers of all finalizable objects in req->domain.
945 finalize_domain_objects (DomainFinalizationReq *req)
947 MonoDomain *domain = req->domain;
950 while (g_hash_table_size (domain->finalizable_objects_hash) > 0) {
954 * Since the domain is unloading, nobody is allowed to put
955 * new entries into the hash table. But finalize_object might
956 * remove entries from the hash table, so we make a copy.
958 objs = g_ptr_array_new ();
959 g_hash_table_foreach (domain->finalizable_objects_hash, collect_objects, objs);
960 /* printf ("FINALIZING %d OBJECTS.\n", objs->len); */
962 for (i = 0; i < objs->len; ++i) {
963 MonoObject *o = (MonoObject*)g_ptr_array_index (objs, i);
964 /* FIXME: Avoid finalizing threads, etc */
965 mono_gc_run_finalize (o, 0);
968 g_ptr_array_free (objs, TRUE);
970 #elif defined(HAVE_SGEN_GC)
971 #define NUM_FOBJECTS 64
972 MonoObject *to_finalize [NUM_FOBJECTS];
974 while ((count = mono_gc_finalizers_for_domain (domain, to_finalize, NUM_FOBJECTS))) {
976 for (i = 0; i < count; ++i) {
977 mono_gc_run_finalize (to_finalize [i], 0);
982 /* Process finalizers which are already in the queue */
983 mono_gc_invoke_finalizers ();
985 /* printf ("DONE.\n"); */
986 SetEvent (req->done_event);
988 /* The event is closed in mono_domain_finalize if we get here */
993 finalizer_thread (gpointer unused)
996 /* Wait to be notified that there's at least one
1000 sem_wait (&finalizer_sem);
1002 /* Use alertable=FALSE since we will be asked to exit using the event too */
1003 WaitForSingleObjectEx (finalizer_event, INFINITE, FALSE);
1006 #ifndef DISABLE_ATTACH
1007 mono_attach_maybe_start ();
1010 if (domains_to_finalize) {
1011 mono_finalizer_lock ();
1012 if (domains_to_finalize) {
1013 DomainFinalizationReq *req = domains_to_finalize->data;
1014 domains_to_finalize = g_slist_remove (domains_to_finalize, req);
1015 mono_finalizer_unlock ();
1017 finalize_domain_objects (req);
1019 mono_finalizer_unlock ();
1023 /* If finished == TRUE, mono_gc_cleanup has been called (from mono_runtime_cleanup),
1024 * before the domain is unloaded.
1026 mono_gc_invoke_finalizers ();
1028 SetEvent (pending_done_event);
1031 SetEvent (shutdown_event);
1038 InitializeCriticalSection (&handle_section);
1039 InitializeCriticalSection (&allocator_section);
1041 InitializeCriticalSection (&finalizer_mutex);
1043 MONO_GC_REGISTER_ROOT (gc_handles [HANDLE_NORMAL].entries);
1044 MONO_GC_REGISTER_ROOT (gc_handles [HANDLE_PINNED].entries);
1046 mono_gc_base_init ();
1048 if (g_getenv ("GC_DONT_GC")) {
1053 finalizer_event = CreateEvent (NULL, FALSE, FALSE, NULL);
1054 pending_done_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1055 shutdown_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1056 if (finalizer_event == NULL || pending_done_event == NULL || shutdown_event == NULL) {
1057 g_assert_not_reached ();
1060 sem_init (&finalizer_sem, 0, 0);
1063 gc_thread = mono_thread_create_internal (mono_domain_get (), finalizer_thread, NULL, FALSE);
1067 mono_gc_cleanup (void)
1070 g_message (G_GNUC_PRETTY_FUNCTION ": cleaning up finalizer");
1074 ResetEvent (shutdown_event);
1076 if (mono_thread_current () != gc_thread) {
1077 mono_gc_finalize_notify ();
1078 /* Finishing the finalizer thread, so wait a little bit... */
1079 /* MS seems to wait for about 2 seconds */
1080 if (WaitForSingleObjectEx (shutdown_event, 2000, FALSE) == WAIT_TIMEOUT) {
1083 /* Set a flag which the finalizer thread can check */
1084 suspend_finalizers = TRUE;
1086 /* Try to abort the thread, in the hope that it is running managed code */
1087 mono_thread_stop (gc_thread);
1089 /* Wait for it to stop */
1090 ret = WaitForSingleObjectEx (gc_thread->handle, 100, TRUE);
1092 if (ret == WAIT_TIMEOUT) {
1094 * The finalizer thread refused to die. There is not much we
1095 * can do here, since the runtime is shutting down so the
1096 * state the finalizer thread depends on will vanish.
1098 g_warning ("Shutting down finalizer thread timed out.");
1101 * FIXME: On unix, when the above wait returns, the thread
1102 * might still be running io-layer code, or pthreads code.
1110 #ifdef HAVE_BOEHM_GC
1111 GC_finalizer_notifier = NULL;
1115 DeleteCriticalSection (&handle_section);
1116 DeleteCriticalSection (&allocator_section);
1117 DeleteCriticalSection (&finalizer_mutex);
1122 /* Null GC dummy functions */
1124 mono_gc_finalize_notify (void)
1128 void mono_gc_init (void)
1130 InitializeCriticalSection (&handle_section);
1133 void mono_gc_cleanup (void)
1140 * mono_gc_is_finalizer_thread:
1141 * @thread: the thread to test.
1143 * In Mono objects are finalized asynchronously on a separate thread.
1144 * This routine tests whether the @thread argument represents the
1145 * finalization thread.
1147 * Returns true if @thread is the finalization thread.
1150 mono_gc_is_finalizer_thread (MonoThread *thread)
1152 return thread == gc_thread;