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>
30 #include <mono/utils/mono-semaphore.h>
36 typedef struct DomainFinalizationReq {
39 } DomainFinalizationReq;
41 #ifdef PLATFORM_WINCE /* FIXME: add accessors to gc.dll API */
42 extern void (*__imp_GC_finalizer_notifier)(void);
43 #define GC_finalizer_notifier __imp_GC_finalizer_notifier
44 extern int __imp_GC_finalize_on_demand;
45 #define GC_finalize_on_demand __imp_GC_finalize_on_demand
48 static gboolean gc_disabled = FALSE;
50 static gboolean finalizing_root_domain = FALSE;
52 #define mono_finalizer_lock() EnterCriticalSection (&finalizer_mutex)
53 #define mono_finalizer_unlock() LeaveCriticalSection (&finalizer_mutex)
54 static CRITICAL_SECTION finalizer_mutex;
56 static GSList *domains_to_finalize= NULL;
57 static MonoMList *threads_to_finalize = NULL;
59 static MonoInternalThread *gc_thread;
61 static void object_register_finalizer (MonoObject *obj, void (*callback)(void *, void*));
63 static void mono_gchandle_set_target (guint32 gchandle, MonoObject *obj);
66 static HANDLE pending_done_event;
67 static HANDLE shutdown_event;
71 add_thread_to_finalize (MonoInternalThread *thread)
73 mono_finalizer_lock ();
74 if (!threads_to_finalize)
75 MONO_GC_REGISTER_ROOT (threads_to_finalize);
76 threads_to_finalize = mono_mlist_append (threads_to_finalize, (MonoObject*)thread);
77 mono_finalizer_unlock ();
80 static gboolean suspend_finalizers = FALSE;
82 * actually, we might want to queue the finalize requests in a separate thread,
83 * but we need to be careful about the execution domain of the thread...
86 mono_gc_run_finalize (void *obj, void *data)
88 MonoObject *exc = NULL;
93 MonoMethod* finalizer = NULL;
94 MonoDomain *caller_domain = mono_domain_get ();
96 RuntimeInvokeFunction runtime_invoke;
97 GSList *l, *refs = NULL;
99 o = (MonoObject*)((char*)obj + GPOINTER_TO_UINT (data));
101 if (suspend_finalizers)
104 domain = o->vtable->domain;
107 mono_domain_finalizers_lock (domain);
109 o2 = g_hash_table_lookup (domain->finalizable_objects_hash, o);
111 refs = mono_gc_remove_weak_track_object (domain, o);
113 mono_domain_finalizers_unlock (domain);
116 /* Already finalized somehow */
122 * Support for GCHandles of type WeakTrackResurrection:
124 * Its not exactly clear how these are supposed to work, or how their
125 * semantics can be implemented. We only implement one crucial thing:
126 * these handles are only cleared after the finalizer has ran.
128 for (l = refs; l; l = l->next) {
129 guint32 gchandle = GPOINTER_TO_UINT (l->data);
131 mono_gchandle_set_target (gchandle, o);
137 /* make sure the finalizer is not called again if the object is resurrected */
138 object_register_finalizer (obj, NULL);
140 if (o->vtable->klass == mono_defaults.internal_thread_class) {
141 MonoInternalThread *t = (MonoInternalThread*)o;
143 if (mono_gc_is_finalizer_internal_thread (t))
144 /* Avoid finalizing ourselves */
147 if (t->threadpool_thread && finalizing_root_domain) {
148 /* Don't finalize threadpool threads when
149 shutting down - they're finalized when the
150 threadpool shuts down. */
151 add_thread_to_finalize (t);
156 if (o->vtable->klass->image == mono_defaults.corlib && !strcmp (o->vtable->klass->name, "DynamicMethod") && finalizing_root_domain) {
158 * These can't be finalized during unloading/shutdown, since that would
159 * free the native code which can still be referenced by other
161 * FIXME: This is not perfect, objects dying at the same time as
162 * dynamic methods can still reference them even when !shutdown.
167 if (mono_runtime_get_no_exec ())
170 /* speedup later... and use a timeout */
171 /* g_print ("Finalize run on %p %s.%s\n", o, mono_object_class (o)->name_space, mono_object_class (o)->name); */
173 /* Use _internal here, since this thread can enter a doomed appdomain */
174 mono_domain_set_internal (mono_object_domain (o));
176 /* delegates that have a native function pointer allocated are
177 * registered for finalization, but they don't have a Finalize
178 * method, because in most cases it's not needed and it's just a waste.
180 if (o->vtable->klass->delegate) {
181 MonoDelegate* del = (MonoDelegate*)o;
182 if (del->delegate_trampoline)
183 mono_delegate_free_ftnptr ((MonoDelegate*)o);
184 mono_domain_set_internal (caller_domain);
188 finalizer = mono_class_get_finalizer (o->vtable->klass);
191 /* If object has a CCW but has no finalizer, it was only
192 * registered for finalization in order to free the CCW.
193 * Else it needs the regular finalizer run.
194 * FIXME: what to do about ressurection and suppression
195 * of finalizer on object with CCW.
197 if (mono_marshal_free_ccw (o) && !finalizer) {
198 mono_domain_set_internal (caller_domain);
204 * To avoid the locking plus the other overhead of mono_runtime_invoke (),
205 * create and precompile a wrapper which calls the finalize method using
208 if (!domain->finalize_runtime_invoke) {
209 MonoMethod *invoke = mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE);
211 domain->finalize_runtime_invoke = mono_compile_method (invoke);
214 runtime_invoke = domain->finalize_runtime_invoke;
216 mono_runtime_class_init (o->vtable);
218 runtime_invoke (o, NULL, &exc, NULL);
221 /* fixme: do something useful */
224 mono_domain_set_internal (caller_domain);
228 mono_gc_finalize_threadpool_threads (void)
230 while (threads_to_finalize) {
231 MonoInternalThread *thread = (MonoInternalThread*) mono_mlist_get_data (threads_to_finalize);
233 /* Force finalization of the thread. */
234 thread->threadpool_thread = FALSE;
235 mono_object_register_finalizer ((MonoObject*)thread);
237 mono_gc_run_finalize (thread, NULL);
239 threads_to_finalize = mono_mlist_next (threads_to_finalize);
244 mono_gc_out_of_memory (size_t size)
247 * we could allocate at program startup some memory that we could release
248 * back to the system at this point if we're really low on memory (ie, size is
249 * lower than the memory we set apart)
251 mono_raise_exception (mono_domain_get ()->out_of_memory_ex);
257 * Some of our objects may point to a different address than the address returned by GC_malloc()
258 * (because of the GetHashCode hack), but we need to pass the real address to register_finalizer.
259 * This also means that in the callback we need to adjust the pointer to get back the real
261 * We also need to be consistent in the use of the GC_debug* variants of malloc and register_finalizer,
262 * since that, too, can cause the underlying pointer to be offset.
265 object_register_finalizer (MonoObject *obj, void (*callback)(void *, void*))
272 mono_raise_exception (mono_get_exception_argument_null ("obj"));
274 domain = obj->vtable->domain;
277 /* This assertion is not valid when GC_DEBUG is defined */
278 g_assert (GC_base (obj) == (char*)obj - offset);
281 if (mono_domain_is_unloading (domain) && (callback != NULL))
283 * Can't register finalizers in a dying appdomain, since they
284 * could be invoked after the appdomain has been unloaded.
288 mono_domain_finalizers_lock (domain);
291 g_hash_table_insert (domain->finalizable_objects_hash, obj, obj);
293 g_hash_table_remove (domain->finalizable_objects_hash, obj);
295 mono_domain_finalizers_unlock (domain);
297 GC_REGISTER_FINALIZER_NO_ORDER ((char*)obj - offset, callback, GUINT_TO_POINTER (offset), NULL, NULL);
298 #elif defined(HAVE_SGEN_GC)
300 mono_raise_exception (mono_get_exception_argument_null ("obj"));
302 mono_gc_register_for_finalization (obj, callback);
307 * mono_object_register_finalizer:
308 * @obj: object to register
310 * Records that object @obj has a finalizer, this will call the
311 * Finalize method when the garbage collector disposes the object.
315 mono_object_register_finalizer (MonoObject *obj)
317 /* g_print ("Registered finalizer on %p %s.%s\n", obj, mono_object_class (obj)->name_space, mono_object_class (obj)->name); */
318 object_register_finalizer (obj, mono_gc_run_finalize);
322 * mono_domain_finalize:
323 * @domain: the domain to finalize
324 * @timeout: msects to wait for the finalization to complete, -1 to wait indefinitely
326 * Request finalization of all finalizable objects inside @domain. Wait
327 * @timeout msecs for the finalization to complete.
329 * Returns: TRUE if succeeded, FALSE if there was a timeout
333 mono_domain_finalize (MonoDomain *domain, guint32 timeout)
335 DomainFinalizationReq *req;
339 if (mono_thread_internal_current () == gc_thread)
340 /* We are called from inside a finalizer, not much we can do here */
344 * No need to create another thread 'cause the finalizer thread
345 * is still working and will take care of running the finalizers
352 mono_gc_collect (mono_gc_max_generation ());
354 done_event = CreateEvent (NULL, TRUE, FALSE, NULL);
355 if (done_event == NULL) {
359 req = g_new0 (DomainFinalizationReq, 1);
360 req->domain = domain;
361 req->done_event = done_event;
363 if (domain == mono_get_root_domain ())
364 finalizing_root_domain = TRUE;
366 mono_finalizer_lock ();
368 domains_to_finalize = g_slist_append (domains_to_finalize, req);
370 mono_finalizer_unlock ();
372 /* Tell the finalizer thread to finalize this appdomain */
373 mono_gc_finalize_notify ();
378 res = WaitForSingleObjectEx (done_event, timeout, TRUE);
380 /* printf ("WAIT RES: %d.\n", res); */
381 if (res == WAIT_TIMEOUT) {
382 /* We leak the handle here */
386 CloseHandle (done_event);
388 if (domain == mono_get_root_domain ()) {
389 mono_thread_pool_cleanup ();
390 mono_gc_finalize_threadpool_threads ();
395 /* We don't support domain finalization without a GC */
401 ves_icall_System_GC_InternalCollect (int generation)
403 mono_gc_collect (generation);
407 ves_icall_System_GC_GetTotalMemory (MonoBoolean forceCollection)
412 mono_gc_collect (mono_gc_max_generation ());
413 return mono_gc_get_used_size ();
417 ves_icall_System_GC_KeepAlive (MonoObject *obj)
427 ves_icall_System_GC_ReRegisterForFinalize (MonoObject *obj)
430 mono_raise_exception (mono_get_exception_argument_null ("obj"));
432 object_register_finalizer (obj, mono_gc_run_finalize);
436 ves_icall_System_GC_SuppressFinalize (MonoObject *obj)
439 mono_raise_exception (mono_get_exception_argument_null ("obj"));
441 /* delegates have no finalizers, but we register them to deal with the
442 * unmanaged->managed trampoline. We don't let the user suppress it
443 * otherwise we'd leak it.
445 if (obj->vtable->klass->delegate)
448 /* FIXME: Need to handle case where obj has COM Callable Wrapper
449 * generated for it that needs cleaned up, but user wants to suppress
450 * their derived object finalizer. */
452 object_register_finalizer (obj, NULL);
456 ves_icall_System_GC_WaitForPendingFinalizers (void)
459 if (!mono_gc_pending_finalizers ())
462 if (mono_thread_internal_current () == gc_thread)
463 /* Avoid deadlocks */
466 ResetEvent (pending_done_event);
467 mono_gc_finalize_notify ();
468 /* g_print ("Waiting for pending finalizers....\n"); */
469 WaitForSingleObjectEx (pending_done_event, INFINITE, TRUE);
470 /* g_print ("Done pending....\n"); */
474 #define mono_allocator_lock() EnterCriticalSection (&allocator_section)
475 #define mono_allocator_unlock() LeaveCriticalSection (&allocator_section)
476 static CRITICAL_SECTION allocator_section;
477 static CRITICAL_SECTION handle_section;
486 static HandleType mono_gchandle_get_type (guint32 gchandle);
489 ves_icall_System_GCHandle_GetTarget (guint32 handle)
491 return mono_gchandle_get_target (handle);
495 * if type == -1, change the target of the handle, otherwise allocate a new handle.
498 ves_icall_System_GCHandle_GetTargetHandle (MonoObject *obj, guint32 handle, gint32 type)
501 mono_gchandle_set_target (handle, obj);
502 /* the handle doesn't change */
507 return mono_gchandle_new_weakref (obj, FALSE);
508 case HANDLE_WEAK_TRACK:
509 return mono_gchandle_new_weakref (obj, TRUE);
511 return mono_gchandle_new (obj, FALSE);
513 return mono_gchandle_new (obj, TRUE);
515 g_assert_not_reached ();
521 ves_icall_System_GCHandle_FreeHandle (guint32 handle)
523 mono_gchandle_free (handle);
527 ves_icall_System_GCHandle_GetAddrOfPinnedObject (guint32 handle)
531 if (mono_gchandle_get_type (handle) != HANDLE_PINNED)
533 obj = mono_gchandle_get_target (handle);
535 MonoClass *klass = mono_object_class (obj);
536 if (klass == mono_defaults.string_class) {
537 return mono_string_chars ((MonoString*)obj);
538 } else if (klass->rank) {
539 return mono_array_addr ((MonoArray*)obj, char, 0);
541 /* the C# code will check and throw the exception */
542 /* FIXME: missing !klass->blittable test, see bug #61134 */
543 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
545 return (char*)obj + sizeof (MonoObject);
556 guint slot_hint : 24; /* starting slot for search */
557 /* 2^16 appdomains should be enough for everyone (though I know I'll regret this in 20 years) */
558 /* we alloc this only for weak refs, since we can get the domain directly in the other cases */
562 /* weak and weak-track arrays will be allocated in malloc memory
564 static HandleData gc_handles [] = {
565 {NULL, NULL, 0, HANDLE_WEAK, 0},
566 {NULL, NULL, 0, HANDLE_WEAK_TRACK, 0},
567 {NULL, NULL, 0, HANDLE_NORMAL, 0},
568 {NULL, NULL, 0, HANDLE_PINNED, 0}
571 #define lock_handles(handles) EnterCriticalSection (&handle_section)
572 #define unlock_handles(handles) LeaveCriticalSection (&handle_section)
575 find_first_unset (guint32 bitmap)
578 for (i = 0; i < 32; ++i) {
579 if (!(bitmap & (1 << i)))
586 alloc_handle (HandleData *handles, MonoObject *obj, gboolean track)
589 lock_handles (handles);
590 if (!handles->size) {
592 if (handles->type > HANDLE_WEAK_TRACK) {
593 handles->entries = mono_gc_alloc_fixed (sizeof (gpointer) * handles->size, NULL);
595 handles->entries = g_malloc0 (sizeof (gpointer) * handles->size);
596 handles->domain_ids = g_malloc0 (sizeof (guint16) * handles->size);
598 handles->bitmap = g_malloc0 (handles->size / 8);
601 for (slot = handles->slot_hint; slot < handles->size / 32; ++slot) {
602 if (handles->bitmap [slot] != 0xffffffff) {
603 i = find_first_unset (handles->bitmap [slot]);
604 handles->slot_hint = slot;
608 if (i == -1 && handles->slot_hint != 0) {
609 for (slot = 0; slot < handles->slot_hint; ++slot) {
610 if (handles->bitmap [slot] != 0xffffffff) {
611 i = find_first_unset (handles->bitmap [slot]);
612 handles->slot_hint = slot;
619 guint32 new_size = handles->size * 2; /* always double: we memset to 0 based on this below */
621 /* resize and copy the bitmap */
622 new_bitmap = g_malloc0 (new_size / 8);
623 memcpy (new_bitmap, handles->bitmap, handles->size / 8);
624 g_free (handles->bitmap);
625 handles->bitmap = new_bitmap;
627 /* resize and copy the entries */
628 if (handles->type > HANDLE_WEAK_TRACK) {
630 entries = mono_gc_alloc_fixed (sizeof (gpointer) * new_size, NULL);
631 memcpy (entries, handles->entries, sizeof (gpointer) * handles->size);
632 handles->entries = entries;
636 domain_ids = g_malloc0 (sizeof (guint16) * new_size);
637 entries = g_malloc (sizeof (gpointer) * new_size);
638 /* we disable GC because we could lose some disappearing link updates */
640 memcpy (entries, handles->entries, sizeof (gpointer) * handles->size);
641 memset (entries + handles->size, 0, sizeof (gpointer) * handles->size);
642 memcpy (domain_ids, handles->domain_ids, sizeof (guint16) * handles->size);
643 for (i = 0; i < handles->size; ++i) {
644 MonoObject *obj = mono_gc_weak_link_get (&(handles->entries [i]));
645 if (handles->entries [i])
646 mono_gc_weak_link_remove (&(handles->entries [i]));
647 /*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]);*/
649 mono_gc_weak_link_add (&(entries [i]), obj, track);
652 g_free (handles->entries);
653 g_free (handles->domain_ids);
654 handles->entries = entries;
655 handles->domain_ids = domain_ids;
659 /* set i and slot to the next free position */
661 slot = (handles->size + 1) / 32;
662 handles->slot_hint = handles->size + 1;
663 handles->size = new_size;
665 handles->bitmap [slot] |= 1 << i;
666 slot = slot * 32 + i;
667 handles->entries [slot] = obj;
668 if (handles->type <= HANDLE_WEAK_TRACK) {
670 mono_gc_weak_link_add (&(handles->entries [slot]), obj, track);
673 mono_perfcounters->gc_num_handles++;
674 unlock_handles (handles);
675 /*g_print ("allocated entry %d of type %d to object %p (in slot: %p)\n", slot, handles->type, obj, handles->entries [slot]);*/
676 return (slot << 3) | (handles->type + 1);
681 * @obj: managed object to get a handle for
682 * @pinned: whether the object should be pinned
684 * This returns a handle that wraps the object, this is used to keep a
685 * reference to a managed object from the unmanaged world and preventing the
686 * object from being disposed.
688 * If @pinned is false the address of the object can not be obtained, if it is
689 * true the address of the object can be obtained. This will also pin the
690 * object so it will not be possible by a moving garbage collector to move the
693 * Returns: a handle that can be used to access the object from
697 mono_gchandle_new (MonoObject *obj, gboolean pinned)
699 return alloc_handle (&gc_handles [pinned? HANDLE_PINNED: HANDLE_NORMAL], obj, FALSE);
703 * mono_gchandle_new_weakref:
704 * @obj: managed object to get a handle for
705 * @pinned: whether the object should be pinned
707 * This returns a weak handle that wraps the object, this is used to
708 * keep a reference to a managed object from the unmanaged world.
709 * Unlike the mono_gchandle_new the object can be reclaimed by the
710 * garbage collector. In this case the value of the GCHandle will be
713 * If @pinned is false the address of the object can not be obtained, if it is
714 * true the address of the object can be obtained. This will also pin the
715 * object so it will not be possible by a moving garbage collector to move the
718 * Returns: a handle that can be used to access the object from
722 mono_gchandle_new_weakref (MonoObject *obj, gboolean track_resurrection)
724 guint32 handle = alloc_handle (&gc_handles [track_resurrection? HANDLE_WEAK_TRACK: HANDLE_WEAK], obj, track_resurrection);
727 if (track_resurrection)
728 mono_gc_add_weak_track_handle (obj, handle);
735 mono_gchandle_get_type (guint32 gchandle)
737 guint type = (gchandle & 7) - 1;
743 * mono_gchandle_get_target:
744 * @gchandle: a GCHandle's handle.
746 * The handle was previously created by calling mono_gchandle_new or
747 * mono_gchandle_new_weakref.
749 * Returns a pointer to the MonoObject represented by the handle or
750 * NULL for a collected object if using a weakref handle.
753 mono_gchandle_get_target (guint32 gchandle)
755 guint slot = gchandle >> 3;
756 guint type = (gchandle & 7) - 1;
757 HandleData *handles = &gc_handles [type];
758 MonoObject *obj = NULL;
761 lock_handles (handles);
762 if (slot < handles->size && (handles->bitmap [slot / 32] & (1 << (slot % 32)))) {
763 if (handles->type <= HANDLE_WEAK_TRACK) {
764 obj = mono_gc_weak_link_get (&handles->entries [slot]);
766 obj = handles->entries [slot];
769 /* print a warning? */
771 unlock_handles (handles);
772 /*g_print ("get target of entry %d of type %d: %p\n", slot, handles->type, obj);*/
777 mono_gchandle_set_target (guint32 gchandle, MonoObject *obj)
779 guint slot = gchandle >> 3;
780 guint type = (gchandle & 7) - 1;
781 HandleData *handles = &gc_handles [type];
782 MonoObject *old_obj = NULL;
786 lock_handles (handles);
787 if (slot < handles->size && (handles->bitmap [slot / 32] & (1 << (slot % 32)))) {
788 if (handles->type <= HANDLE_WEAK_TRACK) {
789 old_obj = handles->entries [slot];
790 if (handles->entries [slot])
791 mono_gc_weak_link_remove (&handles->entries [slot]);
793 mono_gc_weak_link_add (&handles->entries [slot], obj, handles->type == HANDLE_WEAK_TRACK);
795 handles->entries [slot] = obj;
798 /* print a warning? */
800 /*g_print ("changed entry %d of type %d to object %p (in slot: %p)\n", slot, handles->type, obj, handles->entries [slot]);*/
801 unlock_handles (handles);
804 if (type == HANDLE_WEAK_TRACK)
805 mono_gc_change_weak_track_handle (old_obj, obj, gchandle);
810 * mono_gchandle_is_in_domain:
811 * @gchandle: a GCHandle's handle.
812 * @domain: An application domain.
814 * Returns: true if the object wrapped by the @gchandle belongs to the specific @domain.
817 mono_gchandle_is_in_domain (guint32 gchandle, MonoDomain *domain)
819 guint slot = gchandle >> 3;
820 guint type = (gchandle & 7) - 1;
821 HandleData *handles = &gc_handles [type];
822 gboolean result = FALSE;
825 lock_handles (handles);
826 if (slot < handles->size && (handles->bitmap [slot / 32] & (1 << (slot % 32)))) {
827 if (handles->type <= HANDLE_WEAK_TRACK) {
828 result = domain->domain_id == handles->domain_ids [slot];
831 obj = handles->entries [slot];
835 result = domain == mono_object_domain (obj);
838 /* print a warning? */
840 unlock_handles (handles);
845 * mono_gchandle_free:
846 * @gchandle: a GCHandle's handle.
848 * Frees the @gchandle handle. If there are no outstanding
849 * references, the garbage collector can reclaim the memory of the
853 mono_gchandle_free (guint32 gchandle)
855 guint slot = gchandle >> 3;
856 guint type = (gchandle & 7) - 1;
857 HandleData *handles = &gc_handles [type];
861 if (type == HANDLE_WEAK_TRACK)
862 mono_gc_remove_weak_track_handle (gchandle);
865 lock_handles (handles);
866 if (slot < handles->size && (handles->bitmap [slot / 32] & (1 << (slot % 32)))) {
867 if (handles->type <= HANDLE_WEAK_TRACK) {
868 if (handles->entries [slot])
869 mono_gc_weak_link_remove (&handles->entries [slot]);
871 handles->entries [slot] = NULL;
873 handles->bitmap [slot / 32] &= ~(1 << (slot % 32));
875 /* print a warning? */
877 mono_perfcounters->gc_num_handles--;
878 /*g_print ("freed entry %d of type %d\n", slot, handles->type);*/
879 unlock_handles (handles);
883 * mono_gchandle_free_domain:
884 * @domain: domain that is unloading
886 * Function used internally to cleanup any GC handle for objects belonging
887 * to the specified domain during appdomain unload.
890 mono_gchandle_free_domain (MonoDomain *domain)
894 for (type = 0; type < 3; ++type) {
896 HandleData *handles = &gc_handles [type];
897 lock_handles (handles);
898 for (slot = 0; slot < handles->size; ++slot) {
899 if (!(handles->bitmap [slot / 32] & (1 << (slot % 32))))
901 if (type <= HANDLE_WEAK_TRACK) {
902 if (domain->domain_id == handles->domain_ids [slot]) {
903 handles->bitmap [slot / 32] &= ~(1 << (slot % 32));
904 if (handles->entries [slot])
905 mono_gc_weak_link_remove (&handles->entries [slot]);
908 if (handles->entries [slot] && mono_object_domain (handles->entries [slot]) == domain) {
909 handles->bitmap [slot / 32] &= ~(1 << (slot % 32));
910 handles->entries [slot] = NULL;
914 unlock_handles (handles);
920 GCHandle_CheckCurrentDomain (guint32 gchandle)
922 return mono_gchandle_is_in_domain (gchandle, mono_domain_get ());
927 #ifdef MONO_HAS_SEMAPHORES
928 static MonoSemType finalizer_sem;
930 static HANDLE finalizer_event;
931 static volatile gboolean finished=FALSE;
934 mono_gc_finalize_notify (void)
937 g_message ( "%s: prodding finalizer", __func__);
940 #ifdef MONO_HAS_SEMAPHORES
941 MONO_SEM_POST (&finalizer_sem);
943 SetEvent (finalizer_event);
950 collect_objects (gpointer key, gpointer value, gpointer user_data)
952 GPtrArray *arr = (GPtrArray*)user_data;
953 g_ptr_array_add (arr, key);
959 * finalize_domain_objects:
961 * Run the finalizers of all finalizable objects in req->domain.
964 finalize_domain_objects (DomainFinalizationReq *req)
966 MonoDomain *domain = req->domain;
969 while (g_hash_table_size (domain->finalizable_objects_hash) > 0) {
973 * Since the domain is unloading, nobody is allowed to put
974 * new entries into the hash table. But finalize_object might
975 * remove entries from the hash table, so we make a copy.
977 objs = g_ptr_array_new ();
978 g_hash_table_foreach (domain->finalizable_objects_hash, collect_objects, objs);
979 /* printf ("FINALIZING %d OBJECTS.\n", objs->len); */
981 for (i = 0; i < objs->len; ++i) {
982 MonoObject *o = (MonoObject*)g_ptr_array_index (objs, i);
983 /* FIXME: Avoid finalizing threads, etc */
984 mono_gc_run_finalize (o, 0);
987 g_ptr_array_free (objs, TRUE);
989 #elif defined(HAVE_SGEN_GC)
990 #define NUM_FOBJECTS 64
991 MonoObject *to_finalize [NUM_FOBJECTS];
993 while ((count = mono_gc_finalizers_for_domain (domain, to_finalize, NUM_FOBJECTS))) {
995 for (i = 0; i < count; ++i) {
996 mono_gc_run_finalize (to_finalize [i], 0);
1001 /* Process finalizers which are already in the queue */
1002 mono_gc_invoke_finalizers ();
1004 /* printf ("DONE.\n"); */
1005 SetEvent (req->done_event);
1007 /* The event is closed in mono_domain_finalize if we get here */
1012 finalizer_thread (gpointer unused)
1015 /* Wait to be notified that there's at least one
1019 g_assert (mono_domain_get () == mono_get_root_domain ());
1021 #ifdef MONO_HAS_SEMAPHORES
1022 MONO_SEM_WAIT (&finalizer_sem);
1024 /* Use alertable=FALSE since we will be asked to exit using the event too */
1025 WaitForSingleObjectEx (finalizer_event, INFINITE, FALSE);
1028 #ifndef DISABLE_ATTACH
1029 mono_attach_maybe_start ();
1032 if (domains_to_finalize) {
1033 mono_finalizer_lock ();
1034 if (domains_to_finalize) {
1035 DomainFinalizationReq *req = domains_to_finalize->data;
1036 domains_to_finalize = g_slist_remove (domains_to_finalize, req);
1037 mono_finalizer_unlock ();
1039 finalize_domain_objects (req);
1041 mono_finalizer_unlock ();
1045 /* If finished == TRUE, mono_gc_cleanup has been called (from mono_runtime_cleanup),
1046 * before the domain is unloaded.
1048 mono_gc_invoke_finalizers ();
1050 SetEvent (pending_done_event);
1053 SetEvent (shutdown_event);
1058 #define GC_dont_gc 0
1064 InitializeCriticalSection (&handle_section);
1065 InitializeCriticalSection (&allocator_section);
1067 InitializeCriticalSection (&finalizer_mutex);
1069 MONO_GC_REGISTER_ROOT (gc_handles [HANDLE_NORMAL].entries);
1070 MONO_GC_REGISTER_ROOT (gc_handles [HANDLE_PINNED].entries);
1072 mono_gc_base_init ();
1074 if (GC_dont_gc || g_getenv ("GC_DONT_GC")) {
1079 finalizer_event = CreateEvent (NULL, FALSE, FALSE, NULL);
1080 pending_done_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1081 shutdown_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1082 if (finalizer_event == NULL || pending_done_event == NULL || shutdown_event == NULL) {
1083 g_assert_not_reached ();
1085 #ifdef MONO_HAS_SEMAPHORES
1086 MONO_SEM_INIT (&finalizer_sem, 0);
1089 gc_thread = mono_thread_create_internal (mono_domain_get (), finalizer_thread, NULL, FALSE);
1093 mono_gc_cleanup (void)
1096 g_message ("%s: cleaning up finalizer", __func__);
1100 ResetEvent (shutdown_event);
1102 if (mono_thread_internal_current () != gc_thread) {
1103 mono_gc_finalize_notify ();
1104 /* Finishing the finalizer thread, so wait a little bit... */
1105 /* MS seems to wait for about 2 seconds */
1106 if (WaitForSingleObjectEx (shutdown_event, 2000, FALSE) == WAIT_TIMEOUT) {
1109 /* Set a flag which the finalizer thread can check */
1110 suspend_finalizers = TRUE;
1112 /* Try to abort the thread, in the hope that it is running managed code */
1113 mono_thread_internal_stop (gc_thread);
1115 /* Wait for it to stop */
1116 ret = WaitForSingleObjectEx (gc_thread->handle, 100, TRUE);
1118 if (ret == WAIT_TIMEOUT) {
1120 * The finalizer thread refused to die. There is not much we
1121 * can do here, since the runtime is shutting down so the
1122 * state the finalizer thread depends on will vanish.
1124 g_warning ("Shutting down finalizer thread timed out.");
1127 * FIXME: On unix, when the above wait returns, the thread
1128 * might still be running io-layer code, or pthreads code.
1136 #ifdef HAVE_BOEHM_GC
1137 GC_finalizer_notifier = NULL;
1141 DeleteCriticalSection (&handle_section);
1142 DeleteCriticalSection (&allocator_section);
1143 DeleteCriticalSection (&finalizer_mutex);
1148 /* Null GC dummy functions */
1150 mono_gc_finalize_notify (void)
1154 void mono_gc_init (void)
1156 InitializeCriticalSection (&handle_section);
1159 void mono_gc_cleanup (void)
1166 mono_gc_is_finalizer_internal_thread (MonoInternalThread *thread)
1168 return thread == gc_thread;
1172 * mono_gc_is_finalizer_thread:
1173 * @thread: the thread to test.
1175 * In Mono objects are finalized asynchronously on a separate thread.
1176 * This routine tests whether the @thread argument represents the
1177 * finalization thread.
1179 * Returns true if @thread is the finalization thread.
1182 mono_gc_is_finalizer_thread (MonoThread *thread)
1184 return mono_gc_is_finalizer_internal_thread (thread->internal_thread);