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>
32 #ifndef PLATFORM_WIN32
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 MonoThread *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 (MonoThread *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_get_thread_class ()) {
141 MonoThread *t = (MonoThread*)o;
143 if (mono_gc_is_finalizer_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);
187 finalizer = mono_class_get_finalizer (o->vtable->klass);
190 /* If object has a CCW but has no finalizer, it was only
191 * registered for finalization in order to free the CCW.
192 * Else it needs the regular finalizer run.
193 * FIXME: what to do about ressurection and suppression
194 * of finalizer on object with CCW.
196 if (mono_marshal_free_ccw (o) && !finalizer) {
197 mono_domain_set_internal (caller_domain);
203 * To avoid the locking plus the other overhead of mono_runtime_invoke (),
204 * create and precompile a wrapper which calls the finalize method using
207 if (!domain->finalize_runtime_invoke) {
208 MonoMethod *invoke = mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE);
210 domain->finalize_runtime_invoke = mono_compile_method (invoke);
213 runtime_invoke = domain->finalize_runtime_invoke;
215 mono_runtime_class_init (o->vtable);
217 runtime_invoke (o, NULL, &exc, NULL);
220 /* fixme: do something useful */
223 mono_domain_set_internal (caller_domain);
227 mono_gc_finalize_threadpool_threads (void)
229 while (threads_to_finalize) {
230 MonoThread *thread = (MonoThread*) mono_mlist_get_data (threads_to_finalize);
232 /* Force finalization of the thread. */
233 thread->threadpool_thread = FALSE;
234 mono_object_register_finalizer ((MonoObject*)thread);
236 mono_gc_run_finalize (thread, NULL);
238 threads_to_finalize = mono_mlist_next (threads_to_finalize);
243 mono_gc_out_of_memory (size_t size)
246 * we could allocate at program startup some memory that we could release
247 * back to the system at this point if we're really low on memory (ie, size is
248 * lower than the memory we set apart)
250 mono_raise_exception (mono_domain_get ()->out_of_memory_ex);
256 * Some of our objects may point to a different address than the address returned by GC_malloc()
257 * (because of the GetHashCode hack), but we need to pass the real address to register_finalizer.
258 * This also means that in the callback we need to adjust the pointer to get back the real
260 * We also need to be consistent in the use of the GC_debug* variants of malloc and register_finalizer,
261 * since that, too, can cause the underlying pointer to be offset.
264 object_register_finalizer (MonoObject *obj, void (*callback)(void *, void*))
268 MonoDomain *domain = obj->vtable->domain;
271 /* This assertion is not valid when GC_DEBUG is defined */
272 g_assert (GC_base (obj) == (char*)obj - offset);
275 if (mono_domain_is_unloading (domain) && (callback != NULL))
277 * Can't register finalizers in a dying appdomain, since they
278 * could be invoked after the appdomain has been unloaded.
282 mono_domain_finalizers_lock (domain);
285 g_hash_table_insert (domain->finalizable_objects_hash, obj, obj);
287 g_hash_table_remove (domain->finalizable_objects_hash, obj);
289 mono_domain_finalizers_unlock (domain);
291 GC_REGISTER_FINALIZER_NO_ORDER ((char*)obj - offset, callback, GUINT_TO_POINTER (offset), NULL, NULL);
292 #elif defined(HAVE_SGEN_GC)
293 mono_gc_register_for_finalization (obj, callback);
298 * mono_object_register_finalizer:
299 * @obj: object to register
301 * Records that object @obj has a finalizer, this will call the
302 * Finalize method when the garbage collector disposes the object.
306 mono_object_register_finalizer (MonoObject *obj)
308 /* g_print ("Registered finalizer on %p %s.%s\n", obj, mono_object_class (obj)->name_space, mono_object_class (obj)->name); */
309 object_register_finalizer (obj, mono_gc_run_finalize);
313 * mono_domain_finalize:
314 * @domain: the domain to finalize
315 * @timeout: msects to wait for the finalization to complete, -1 to wait indefinitely
317 * Request finalization of all finalizable objects inside @domain. Wait
318 * @timeout msecs for the finalization to complete.
320 * Returns: TRUE if succeeded, FALSE if there was a timeout
324 mono_domain_finalize (MonoDomain *domain, guint32 timeout)
326 DomainFinalizationReq *req;
330 if (mono_thread_current () == gc_thread)
331 /* We are called from inside a finalizer, not much we can do here */
335 * No need to create another thread 'cause the finalizer thread
336 * is still working and will take care of running the finalizers
343 mono_gc_collect (mono_gc_max_generation ());
345 done_event = CreateEvent (NULL, TRUE, FALSE, NULL);
346 if (done_event == NULL) {
350 req = g_new0 (DomainFinalizationReq, 1);
351 req->domain = domain;
352 req->done_event = done_event;
354 if (domain == mono_get_root_domain ())
355 finalizing_root_domain = TRUE;
357 mono_finalizer_lock ();
359 domains_to_finalize = g_slist_append (domains_to_finalize, req);
361 mono_finalizer_unlock ();
363 /* Tell the finalizer thread to finalize this appdomain */
364 mono_gc_finalize_notify ();
369 res = WaitForSingleObjectEx (done_event, timeout, TRUE);
371 /* printf ("WAIT RES: %d.\n", res); */
372 if (res == WAIT_TIMEOUT) {
373 /* We leak the handle here */
377 CloseHandle (done_event);
379 if (domain == mono_get_root_domain ()) {
380 mono_thread_pool_cleanup ();
381 mono_gc_finalize_threadpool_threads ();
386 /* We don't support domain finalization without a GC */
392 ves_icall_System_GC_InternalCollect (int generation)
394 mono_gc_collect (generation);
398 ves_icall_System_GC_GetTotalMemory (MonoBoolean forceCollection)
403 mono_gc_collect (mono_gc_max_generation ());
404 return mono_gc_get_used_size ();
408 ves_icall_System_GC_KeepAlive (MonoObject *obj)
418 ves_icall_System_GC_ReRegisterForFinalize (MonoObject *obj)
421 mono_raise_exception (mono_get_exception_argument_null ("obj"));
423 object_register_finalizer (obj, mono_gc_run_finalize);
427 ves_icall_System_GC_SuppressFinalize (MonoObject *obj)
430 mono_raise_exception (mono_get_exception_argument_null ("obj"));
432 /* delegates have no finalizers, but we register them to deal with the
433 * unmanaged->managed trampoline. We don't let the user suppress it
434 * otherwise we'd leak it.
436 if (obj->vtable->klass->delegate)
439 /* FIXME: Need to handle case where obj has COM Callable Wrapper
440 * generated for it that needs cleaned up, but user wants to suppress
441 * their derived object finalizer. */
443 object_register_finalizer (obj, NULL);
447 ves_icall_System_GC_WaitForPendingFinalizers (void)
450 if (!mono_gc_pending_finalizers ())
453 if (mono_thread_current () == gc_thread)
454 /* Avoid deadlocks */
457 ResetEvent (pending_done_event);
458 mono_gc_finalize_notify ();
459 /* g_print ("Waiting for pending finalizers....\n"); */
460 WaitForSingleObjectEx (pending_done_event, INFINITE, TRUE);
461 /* g_print ("Done pending....\n"); */
465 #define mono_allocator_lock() EnterCriticalSection (&allocator_section)
466 #define mono_allocator_unlock() LeaveCriticalSection (&allocator_section)
467 static CRITICAL_SECTION allocator_section;
468 static CRITICAL_SECTION handle_section;
477 static HandleType mono_gchandle_get_type (guint32 gchandle);
480 ves_icall_System_GCHandle_GetTarget (guint32 handle)
482 return mono_gchandle_get_target (handle);
486 * if type == -1, change the target of the handle, otherwise allocate a new handle.
489 ves_icall_System_GCHandle_GetTargetHandle (MonoObject *obj, guint32 handle, gint32 type)
492 mono_gchandle_set_target (handle, obj);
493 /* the handle doesn't change */
498 return mono_gchandle_new_weakref (obj, FALSE);
499 case HANDLE_WEAK_TRACK:
500 return mono_gchandle_new_weakref (obj, TRUE);
502 return mono_gchandle_new (obj, FALSE);
504 return mono_gchandle_new (obj, TRUE);
506 g_assert_not_reached ();
512 ves_icall_System_GCHandle_FreeHandle (guint32 handle)
514 mono_gchandle_free (handle);
518 ves_icall_System_GCHandle_GetAddrOfPinnedObject (guint32 handle)
522 if (mono_gchandle_get_type (handle) != HANDLE_PINNED)
524 obj = mono_gchandle_get_target (handle);
526 MonoClass *klass = mono_object_class (obj);
527 if (klass == mono_defaults.string_class) {
528 return mono_string_chars ((MonoString*)obj);
529 } else if (klass->rank) {
530 return mono_array_addr ((MonoArray*)obj, char, 0);
532 /* the C# code will check and throw the exception */
533 /* FIXME: missing !klass->blittable test, see bug #61134 */
534 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
536 return (char*)obj + sizeof (MonoObject);
547 guint slot_hint : 24; /* starting slot for search */
548 /* 2^16 appdomains should be enough for everyone (though I know I'll regret this in 20 years) */
549 /* we alloc this only for weak refs, since we can get the domain directly in the other cases */
553 /* weak and weak-track arrays will be allocated in malloc memory
555 static HandleData gc_handles [] = {
556 {NULL, NULL, 0, HANDLE_WEAK, 0},
557 {NULL, NULL, 0, HANDLE_WEAK_TRACK, 0},
558 {NULL, NULL, 0, HANDLE_NORMAL, 0},
559 {NULL, NULL, 0, HANDLE_PINNED, 0}
562 #define lock_handles(handles) EnterCriticalSection (&handle_section)
563 #define unlock_handles(handles) LeaveCriticalSection (&handle_section)
566 find_first_unset (guint32 bitmap)
569 for (i = 0; i < 32; ++i) {
570 if (!(bitmap & (1 << i)))
577 alloc_handle (HandleData *handles, MonoObject *obj, gboolean track)
580 lock_handles (handles);
581 if (!handles->size) {
583 if (handles->type > HANDLE_WEAK_TRACK) {
584 handles->entries = mono_gc_alloc_fixed (sizeof (gpointer) * handles->size, NULL);
586 handles->entries = g_malloc0 (sizeof (gpointer) * handles->size);
587 handles->domain_ids = g_malloc0 (sizeof (guint16) * handles->size);
589 handles->bitmap = g_malloc0 (handles->size / 8);
592 for (slot = handles->slot_hint; slot < handles->size / 32; ++slot) {
593 if (handles->bitmap [slot] != 0xffffffff) {
594 i = find_first_unset (handles->bitmap [slot]);
595 handles->slot_hint = slot;
599 if (i == -1 && handles->slot_hint != 0) {
600 for (slot = 0; slot < handles->slot_hint; ++slot) {
601 if (handles->bitmap [slot] != 0xffffffff) {
602 i = find_first_unset (handles->bitmap [slot]);
603 handles->slot_hint = slot;
610 guint32 new_size = handles->size * 2; /* always double: we memset to 0 based on this below */
612 /* resize and copy the bitmap */
613 new_bitmap = g_malloc0 (new_size / 8);
614 memcpy (new_bitmap, handles->bitmap, handles->size / 8);
615 g_free (handles->bitmap);
616 handles->bitmap = new_bitmap;
618 /* resize and copy the entries */
619 if (handles->type > HANDLE_WEAK_TRACK) {
621 entries = mono_gc_alloc_fixed (sizeof (gpointer) * new_size, NULL);
622 memcpy (entries, handles->entries, sizeof (gpointer) * handles->size);
623 handles->entries = entries;
627 domain_ids = g_malloc0 (sizeof (guint16) * new_size);
628 entries = g_malloc (sizeof (gpointer) * new_size);
629 /* we disable GC because we could lose some disappearing link updates */
631 memcpy (entries, handles->entries, sizeof (gpointer) * handles->size);
632 memset (entries + handles->size, 0, sizeof (gpointer) * handles->size);
633 memcpy (domain_ids, handles->domain_ids, sizeof (guint16) * handles->size);
634 for (i = 0; i < handles->size; ++i) {
635 MonoObject *obj = mono_gc_weak_link_get (&(handles->entries [i]));
636 if (handles->entries [i])
637 mono_gc_weak_link_remove (&(handles->entries [i]));
638 /*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]);*/
640 mono_gc_weak_link_add (&(entries [i]), obj, track);
643 g_free (handles->entries);
644 g_free (handles->domain_ids);
645 handles->entries = entries;
646 handles->domain_ids = domain_ids;
650 /* set i and slot to the next free position */
652 slot = (handles->size + 1) / 32;
653 handles->slot_hint = handles->size + 1;
654 handles->size = new_size;
656 handles->bitmap [slot] |= 1 << i;
657 slot = slot * 32 + i;
658 handles->entries [slot] = obj;
659 if (handles->type <= HANDLE_WEAK_TRACK) {
661 mono_gc_weak_link_add (&(handles->entries [slot]), obj, track);
664 mono_perfcounters->gc_num_handles++;
665 unlock_handles (handles);
666 /*g_print ("allocated entry %d of type %d to object %p (in slot: %p)\n", slot, handles->type, obj, handles->entries [slot]);*/
667 return (slot << 3) | (handles->type + 1);
672 * @obj: managed object to get a handle for
673 * @pinned: whether the object should be pinned
675 * This returns a handle that wraps the object, this is used to keep a
676 * reference to a managed object from the unmanaged world and preventing the
677 * object from being disposed.
679 * If @pinned is false the address of the object can not be obtained, if it is
680 * true the address of the object can be obtained. This will also pin the
681 * object so it will not be possible by a moving garbage collector to move the
684 * Returns: a handle that can be used to access the object from
688 mono_gchandle_new (MonoObject *obj, gboolean pinned)
690 return alloc_handle (&gc_handles [pinned? HANDLE_PINNED: HANDLE_NORMAL], obj, FALSE);
694 * mono_gchandle_new_weakref:
695 * @obj: managed object to get a handle for
696 * @pinned: whether the object should be pinned
698 * This returns a weak handle that wraps the object, this is used to
699 * keep a reference to a managed object from the unmanaged world.
700 * Unlike the mono_gchandle_new the object can be reclaimed by the
701 * garbage collector. In this case the value of the GCHandle will be
704 * If @pinned is false the address of the object can not be obtained, if it is
705 * true the address of the object can be obtained. This will also pin the
706 * object so it will not be possible by a moving garbage collector to move the
709 * Returns: a handle that can be used to access the object from
713 mono_gchandle_new_weakref (MonoObject *obj, gboolean track_resurrection)
715 guint32 handle = alloc_handle (&gc_handles [track_resurrection? HANDLE_WEAK_TRACK: HANDLE_WEAK], obj, track_resurrection);
718 if (track_resurrection)
719 mono_gc_add_weak_track_handle (obj, handle);
726 mono_gchandle_get_type (guint32 gchandle)
728 guint type = (gchandle & 7) - 1;
734 * mono_gchandle_get_target:
735 * @gchandle: a GCHandle's handle.
737 * The handle was previously created by calling mono_gchandle_new or
738 * mono_gchandle_new_weakref.
740 * Returns a pointer to the MonoObject represented by the handle or
741 * NULL for a collected object if using a weakref handle.
744 mono_gchandle_get_target (guint32 gchandle)
746 guint slot = gchandle >> 3;
747 guint type = (gchandle & 7) - 1;
748 HandleData *handles = &gc_handles [type];
749 MonoObject *obj = NULL;
752 lock_handles (handles);
753 if (slot < handles->size && (handles->bitmap [slot / 32] & (1 << (slot % 32)))) {
754 if (handles->type <= HANDLE_WEAK_TRACK) {
755 obj = mono_gc_weak_link_get (&handles->entries [slot]);
757 obj = handles->entries [slot];
760 /* print a warning? */
762 unlock_handles (handles);
763 /*g_print ("get target of entry %d of type %d: %p\n", slot, handles->type, obj);*/
768 mono_gchandle_set_target (guint32 gchandle, MonoObject *obj)
770 guint slot = gchandle >> 3;
771 guint type = (gchandle & 7) - 1;
772 HandleData *handles = &gc_handles [type];
773 MonoObject *old_obj = NULL;
777 lock_handles (handles);
778 if (slot < handles->size && (handles->bitmap [slot / 32] & (1 << (slot % 32)))) {
779 if (handles->type <= HANDLE_WEAK_TRACK) {
780 old_obj = handles->entries [slot];
781 if (handles->entries [slot])
782 mono_gc_weak_link_remove (&handles->entries [slot]);
784 mono_gc_weak_link_add (&handles->entries [slot], obj, handles->type == HANDLE_WEAK_TRACK);
786 handles->entries [slot] = obj;
789 /* print a warning? */
791 /*g_print ("changed entry %d of type %d to object %p (in slot: %p)\n", slot, handles->type, obj, handles->entries [slot]);*/
792 unlock_handles (handles);
795 if (type == HANDLE_WEAK_TRACK)
796 mono_gc_change_weak_track_handle (old_obj, obj, gchandle);
801 * mono_gchandle_is_in_domain:
802 * @gchandle: a GCHandle's handle.
803 * @domain: An application domain.
805 * Returns: true if the object wrapped by the @gchandle belongs to the specific @domain.
808 mono_gchandle_is_in_domain (guint32 gchandle, MonoDomain *domain)
810 guint slot = gchandle >> 3;
811 guint type = (gchandle & 7) - 1;
812 HandleData *handles = &gc_handles [type];
813 gboolean result = FALSE;
816 lock_handles (handles);
817 if (slot < handles->size && (handles->bitmap [slot / 32] & (1 << (slot % 32)))) {
818 if (handles->type <= HANDLE_WEAK_TRACK) {
819 result = domain->domain_id == handles->domain_ids [slot];
822 obj = handles->entries [slot];
826 result = domain == mono_object_domain (obj);
829 /* print a warning? */
831 unlock_handles (handles);
836 * mono_gchandle_free:
837 * @gchandle: a GCHandle's handle.
839 * Frees the @gchandle handle. If there are no outstanding
840 * references, the garbage collector can reclaim the memory of the
844 mono_gchandle_free (guint32 gchandle)
846 guint slot = gchandle >> 3;
847 guint type = (gchandle & 7) - 1;
848 HandleData *handles = &gc_handles [type];
852 if (type == HANDLE_WEAK_TRACK)
853 mono_gc_remove_weak_track_handle (gchandle);
856 lock_handles (handles);
857 if (slot < handles->size && (handles->bitmap [slot / 32] & (1 << (slot % 32)))) {
858 if (handles->type <= HANDLE_WEAK_TRACK) {
859 if (handles->entries [slot])
860 mono_gc_weak_link_remove (&handles->entries [slot]);
862 handles->entries [slot] = NULL;
864 handles->bitmap [slot / 32] &= ~(1 << (slot % 32));
866 /* print a warning? */
868 mono_perfcounters->gc_num_handles--;
869 /*g_print ("freed entry %d of type %d\n", slot, handles->type);*/
870 unlock_handles (handles);
874 * mono_gchandle_free_domain:
875 * @domain: domain that is unloading
877 * Function used internally to cleanup any GC handle for objects belonging
878 * to the specified domain during appdomain unload.
881 mono_gchandle_free_domain (MonoDomain *domain)
885 for (type = 0; type < 3; ++type) {
887 HandleData *handles = &gc_handles [type];
888 lock_handles (handles);
889 for (slot = 0; slot < handles->size; ++slot) {
890 if (!(handles->bitmap [slot / 32] & (1 << (slot % 32))))
892 if (type <= HANDLE_WEAK_TRACK) {
893 if (domain->domain_id == handles->domain_ids [slot]) {
894 handles->bitmap [slot / 32] &= ~(1 << (slot % 32));
895 if (handles->entries [slot])
896 mono_gc_weak_link_remove (&handles->entries [slot]);
899 if (handles->entries [slot] && mono_object_domain (handles->entries [slot]) == domain) {
900 handles->bitmap [slot / 32] &= ~(1 << (slot % 32));
901 handles->entries [slot] = NULL;
905 unlock_handles (handles);
912 #ifdef MONO_HAS_SEMAPHORES
913 static MonoSemType finalizer_sem;
915 static HANDLE finalizer_event;
916 static volatile gboolean finished=FALSE;
919 mono_gc_finalize_notify (void)
922 g_message (G_GNUC_PRETTY_FUNCTION ": prodding finalizer");
925 #ifdef MONO_HAS_SEMAPHORES
926 MONO_SEM_POST (&finalizer_sem);
928 SetEvent (finalizer_event);
935 collect_objects (gpointer key, gpointer value, gpointer user_data)
937 GPtrArray *arr = (GPtrArray*)user_data;
938 g_ptr_array_add (arr, key);
944 * finalize_domain_objects:
946 * Run the finalizers of all finalizable objects in req->domain.
949 finalize_domain_objects (DomainFinalizationReq *req)
951 MonoDomain *domain = req->domain;
954 while (g_hash_table_size (domain->finalizable_objects_hash) > 0) {
958 * Since the domain is unloading, nobody is allowed to put
959 * new entries into the hash table. But finalize_object might
960 * remove entries from the hash table, so we make a copy.
962 objs = g_ptr_array_new ();
963 g_hash_table_foreach (domain->finalizable_objects_hash, collect_objects, objs);
964 /* printf ("FINALIZING %d OBJECTS.\n", objs->len); */
966 for (i = 0; i < objs->len; ++i) {
967 MonoObject *o = (MonoObject*)g_ptr_array_index (objs, i);
968 /* FIXME: Avoid finalizing threads, etc */
969 mono_gc_run_finalize (o, 0);
972 g_ptr_array_free (objs, TRUE);
974 #elif defined(HAVE_SGEN_GC)
975 #define NUM_FOBJECTS 64
976 MonoObject *to_finalize [NUM_FOBJECTS];
978 while ((count = mono_gc_finalizers_for_domain (domain, to_finalize, NUM_FOBJECTS))) {
980 for (i = 0; i < count; ++i) {
981 mono_gc_run_finalize (to_finalize [i], 0);
986 /* Process finalizers which are already in the queue */
987 mono_gc_invoke_finalizers ();
989 /* printf ("DONE.\n"); */
990 SetEvent (req->done_event);
992 /* The event is closed in mono_domain_finalize if we get here */
997 finalizer_thread (gpointer unused)
1000 /* Wait to be notified that there's at least one
1003 #ifdef MONO_HAS_SEMAPHORES
1004 MONO_SEM_WAIT (&finalizer_sem);
1006 /* Use alertable=FALSE since we will be asked to exit using the event too */
1007 WaitForSingleObjectEx (finalizer_event, INFINITE, FALSE);
1010 #ifndef DISABLE_ATTACH
1011 mono_attach_maybe_start ();
1014 if (domains_to_finalize) {
1015 mono_finalizer_lock ();
1016 if (domains_to_finalize) {
1017 DomainFinalizationReq *req = domains_to_finalize->data;
1018 domains_to_finalize = g_slist_remove (domains_to_finalize, req);
1019 mono_finalizer_unlock ();
1021 finalize_domain_objects (req);
1023 mono_finalizer_unlock ();
1027 /* If finished == TRUE, mono_gc_cleanup has been called (from mono_runtime_cleanup),
1028 * before the domain is unloaded.
1030 mono_gc_invoke_finalizers ();
1032 SetEvent (pending_done_event);
1035 SetEvent (shutdown_event);
1042 InitializeCriticalSection (&handle_section);
1043 InitializeCriticalSection (&allocator_section);
1045 InitializeCriticalSection (&finalizer_mutex);
1047 MONO_GC_REGISTER_ROOT (gc_handles [HANDLE_NORMAL].entries);
1048 MONO_GC_REGISTER_ROOT (gc_handles [HANDLE_PINNED].entries);
1050 mono_gc_base_init ();
1052 if (g_getenv ("GC_DONT_GC")) {
1057 finalizer_event = CreateEvent (NULL, FALSE, FALSE, NULL);
1058 pending_done_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1059 shutdown_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1060 if (finalizer_event == NULL || pending_done_event == NULL || shutdown_event == NULL) {
1061 g_assert_not_reached ();
1063 #ifdef MONO_HAS_SEMAPHORES
1064 MONO_SEM_INIT (&finalizer_sem, 0);
1067 gc_thread = mono_thread_create_internal (mono_domain_get (), finalizer_thread, NULL, FALSE);
1071 mono_gc_cleanup (void)
1074 g_message (G_GNUC_PRETTY_FUNCTION ": cleaning up finalizer");
1078 ResetEvent (shutdown_event);
1080 if (mono_thread_current () != gc_thread) {
1081 mono_gc_finalize_notify ();
1082 /* Finishing the finalizer thread, so wait a little bit... */
1083 /* MS seems to wait for about 2 seconds */
1084 if (WaitForSingleObjectEx (shutdown_event, 2000, FALSE) == WAIT_TIMEOUT) {
1087 /* Set a flag which the finalizer thread can check */
1088 suspend_finalizers = TRUE;
1090 /* Try to abort the thread, in the hope that it is running managed code */
1091 mono_thread_stop (gc_thread);
1093 /* Wait for it to stop */
1094 ret = WaitForSingleObjectEx (gc_thread->handle, 100, TRUE);
1096 if (ret == WAIT_TIMEOUT) {
1098 * The finalizer thread refused to die. There is not much we
1099 * can do here, since the runtime is shutting down so the
1100 * state the finalizer thread depends on will vanish.
1102 g_warning ("Shutting down finalizer thread timed out.");
1105 * FIXME: On unix, when the above wait returns, the thread
1106 * might still be running io-layer code, or pthreads code.
1114 #ifdef HAVE_BOEHM_GC
1115 GC_finalizer_notifier = NULL;
1119 DeleteCriticalSection (&handle_section);
1120 DeleteCriticalSection (&allocator_section);
1121 DeleteCriticalSection (&finalizer_mutex);
1126 /* Null GC dummy functions */
1128 mono_gc_finalize_notify (void)
1132 void mono_gc_init (void)
1134 InitializeCriticalSection (&handle_section);
1137 void mono_gc_cleanup (void)
1144 * mono_gc_is_finalizer_thread:
1145 * @thread: the thread to test.
1147 * In Mono objects are finalized asynchronously on a separate thread.
1148 * This routine tests whether the @thread argument represents the
1149 * finalization thread.
1151 * Returns true if @thread is the finalization thread.
1154 mono_gc_is_finalizer_thread (MonoThread *thread)
1156 return thread == gc_thread;
1159 static MonoGetIPFromSigCtxFunc get_ip_from_sigctx = NULL;
1162 mono_install_get_ip_from_sigctx (MonoGetIPFromSigCtxFunc func)
1164 get_ip_from_sigctx = func;
1168 mono_gc_get_ip_from_sigctx (gpointer ctx)
1170 g_assert (get_ip_from_sigctx);
1171 return get_ip_from_sigctx (ctx);