2 * metadata/gc.c: GC icalls.
4 * Author: Paolo Molaro <lupus@ximian.com>
6 * (C) 2002 Ximian, Inc.
13 #include <mono/metadata/gc-internal.h>
14 #include <mono/metadata/mono-gc.h>
15 #include <mono/metadata/threads.h>
16 #include <mono/metadata/tabledefs.h>
17 #include <mono/metadata/exception.h>
18 #include <mono/metadata/profiler-private.h>
19 #include <mono/metadata/domain-internals.h>
20 #include <mono/metadata/class-internals.h>
21 #include <mono/utils/mono-logger.h>
22 #include <mono/os/gc_wrapper.h>
23 #include <mono/metadata/marshal.h> /* for mono_delegate_free_ftnptr () */
25 typedef struct DomainFinalizationReq {
28 } DomainFinalizationReq;
30 #ifdef PLATFORM_WINCE /* FIXME: add accessors to gc.dll API */
31 extern void (*__imp_GC_finalizer_notifier)(void);
32 #define GC_finalizer_notifier __imp_GC_finalizer_notifier
33 extern int __imp_GC_finalize_on_demand;
34 #define GC_finalize_on_demand __imp_GC_finalize_on_demand
37 static gboolean gc_disabled = FALSE;
39 #define mono_finalizer_lock() EnterCriticalSection (&finalizer_mutex)
40 #define mono_finalizer_unlock() LeaveCriticalSection (&finalizer_mutex)
41 static CRITICAL_SECTION finalizer_mutex;
43 static GSList *domains_to_finalize= NULL;
45 static MonoThread *gc_thread;
47 static void object_register_finalizer (MonoObject *obj, void (*callback)(void *, void*));
50 static HANDLE pending_done_event;
51 static HANDLE shutdown_event;
52 static HANDLE thread_started_event;
56 * actually, we might want to queue the finalize requests in a separate thread,
57 * but we need to be careful about the execution domain of the thread...
60 run_finalize (void *obj, void *data)
62 MonoObject *exc = NULL;
64 o = (MonoObject*)((char*)obj + GPOINTER_TO_UINT (data));
67 mono_domain_lock (o->vtable->domain);
69 o2 = g_hash_table_lookup (o->vtable->domain->finalizable_objects_hash, o);
71 mono_domain_unlock (o->vtable->domain);
74 /* Already finalized somehow */
78 /* make sure the finalizer is not called again if the object is resurrected */
79 object_register_finalizer (obj, NULL);
81 if (o->vtable->klass == mono_get_thread_class ())
82 if (mono_gc_is_finalizer_thread ((MonoThread*)o))
83 /* Avoid finalizing ourselves */
86 /* speedup later... and use a timeout */
87 /* g_print ("Finalize run on %p %s.%s\n", o, mono_object_class (o)->name_space, mono_object_class (o)->name); */
89 /* Use _internal here, since this thread can enter a doomed appdomain */
90 mono_domain_set_internal (mono_object_domain (o));
92 /* delegates that have a native function pointer allocated are
93 * registered for finalization, but they don't have a Finalize
94 * method, because in most cases it's not needed and it's just a waste.
96 if (o->vtable->klass->delegate) {
97 MonoDelegate* del = (MonoDelegate*)o;
98 if (del->delegate_trampoline)
99 mono_delegate_free_ftnptr ((MonoDelegate*)o);
103 mono_runtime_invoke (mono_class_get_finalizer (o->vtable->klass), o, NULL, &exc);
106 /* fixme: do something useful */
111 mono_gc_out_of_memory (size_t size)
114 * we could allocate at program startup some memory that we could release
115 * back to the system at this point if we're really low on memory (ie, size is
116 * lower than the memory we set apart)
118 mono_raise_exception (mono_domain_get ()->out_of_memory_ex);
124 * Some of our objects may point to a different address than the address returned by GC_malloc()
125 * (because of the GetHashCode hack), but we need to pass the real address to register_finalizer.
126 * This also means that in the callback we need to adjust the pointer to get back the real
128 * We also need to be consistent in the use of the GC_debug* variants of malloc and register_finalizer,
129 * since that, too, can cause the underlying pointer to be offset.
132 object_register_finalizer (MonoObject *obj, void (*callback)(void *, void*))
138 /* This assertion is not valid when GC_DEBUG is defined */
139 g_assert (GC_base (obj) == (char*)obj - offset);
142 if (mono_domain_is_unloading (obj->vtable->domain) && (callback != NULL))
144 * Can't register finalizers in a dying appdomain, since they
145 * could be invoked after the appdomain has been unloaded.
149 mono_domain_lock (obj->vtable->domain);
152 g_hash_table_insert (obj->vtable->domain->finalizable_objects_hash, obj,
155 g_hash_table_remove (obj->vtable->domain->finalizable_objects_hash, obj);
157 mono_domain_unlock (obj->vtable->domain);
159 GC_REGISTER_FINALIZER_NO_ORDER ((char*)obj - offset, callback, GUINT_TO_POINTER (offset), NULL, NULL);
160 #elif defined(HAVE_SGEN_GC)
161 mono_gc_register_for_finalization (obj, callback);
166 * mono_object_register_finalizer:
167 * @obj: object to register
169 * Records that object @obj has a finalizer, this will call the
170 * Finalize method when the garbage collector disposes the object.
174 mono_object_register_finalizer (MonoObject *obj)
176 /* g_print ("Registered finalizer on %p %s.%s\n", obj, mono_object_class (obj)->name_space, mono_object_class (obj)->name); */
177 object_register_finalizer (obj, run_finalize);
181 * mono_domain_finalize:
182 * @domain: the domain to finalize
183 * @timeout: msects to wait for the finalization to complete
185 * Request finalization of all finalizable objects inside @domain. Wait
186 * @timeout msecs for the finalization to complete.
188 * Returns: TRUE if succeeded, FALSE if there was a timeout
192 mono_domain_finalize (MonoDomain *domain, guint32 timeout)
194 DomainFinalizationReq *req;
198 if (mono_thread_current () == gc_thread)
199 /* We are called from inside a finalizer, not much we can do here */
202 mono_profiler_appdomain_event (domain, MONO_PROFILE_START_UNLOAD);
205 * No need to create another thread 'cause the finalizer thread
206 * is still working and will take care of running the finalizers
213 mono_gc_collect (mono_gc_max_generation ());
215 done_event = CreateEvent (NULL, TRUE, FALSE, NULL);
217 req = g_new0 (DomainFinalizationReq, 1);
218 req->domain = domain;
219 req->done_event = done_event;
221 mono_finalizer_lock ();
223 domains_to_finalize = g_slist_append (domains_to_finalize, req);
225 mono_finalizer_unlock ();
227 /* Tell the finalizer thread to finalize this appdomain */
228 mono_gc_finalize_notify ();
230 res = WaitForSingleObjectEx (done_event, timeout, TRUE);
232 /* printf ("WAIT RES: %d.\n", res); */
233 if (res == WAIT_TIMEOUT) {
234 /* We leak the handle here */
238 CloseHandle (done_event);
241 /* We don't support domain finalization without a GC */
247 ves_icall_System_GC_InternalCollect (int generation)
249 mono_gc_collect (generation);
253 ves_icall_System_GC_GetTotalMemory (MonoBoolean forceCollection)
258 mono_gc_collect (mono_gc_max_generation ());
259 return mono_gc_get_used_size ();
263 ves_icall_System_GC_KeepAlive (MonoObject *obj)
273 ves_icall_System_GC_ReRegisterForFinalize (MonoObject *obj)
277 object_register_finalizer (obj, run_finalize);
281 ves_icall_System_GC_SuppressFinalize (MonoObject *obj)
285 object_register_finalizer (obj, NULL);
289 ves_icall_System_GC_WaitForPendingFinalizers (void)
294 if (!mono_gc_pending_finalizers ())
297 if (mono_thread_current () == gc_thread)
298 /* Avoid deadlocks */
301 ResetEvent (pending_done_event);
302 mono_gc_finalize_notify ();
303 /* g_print ("Waiting for pending finalizers....\n"); */
304 WaitForSingleObjectEx (pending_done_event, INFINITE, TRUE);
305 /* g_print ("Done pending....\n"); */
309 #define mono_allocator_lock() EnterCriticalSection (&allocator_section)
310 #define mono_allocator_unlock() LeaveCriticalSection (&allocator_section)
311 static CRITICAL_SECTION allocator_section;
312 static CRITICAL_SECTION handle_section;
321 static void mono_gchandle_set_target (guint32 gchandle, MonoObject *obj);
324 ves_icall_System_GCHandle_GetTarget (guint32 handle)
326 return mono_gchandle_get_target (handle);
330 * if type == -1, change the target of the handle, otherwise allocate a new handle.
333 ves_icall_System_GCHandle_GetTargetHandle (MonoObject *obj, guint32 handle, gint32 type)
336 mono_gchandle_set_target (handle, obj);
337 /* the handle doesn't change */
342 return mono_gchandle_new_weakref (obj, FALSE);
343 case HANDLE_WEAK_TRACK:
344 return mono_gchandle_new_weakref (obj, TRUE);
346 return mono_gchandle_new (obj, FALSE);
348 return mono_gchandle_new (obj, TRUE);
350 g_assert_not_reached ();
356 ves_icall_System_GCHandle_FreeHandle (guint32 handle)
358 mono_gchandle_free (handle);
362 ves_icall_System_GCHandle_GetAddrOfPinnedObject (guint32 handle)
366 obj = mono_gchandle_get_target (handle);
368 MonoClass *klass = mono_object_class (obj);
369 if (klass == mono_defaults.string_class) {
370 return mono_string_chars ((MonoString*)obj);
371 } else if (klass->rank) {
372 return mono_array_addr ((MonoArray*)obj, char, 0);
374 /* the C# code will check and throw the exception */
375 /* FIXME: missing !klass->blittable test, see bug #61134 */
376 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
378 return (char*)obj + sizeof (MonoObject);
389 guint slot_hint : 24; /* starting slot for search */
390 /* 2^16 appdomains should be enough for everyone (though I know I'll regret this in 20 years) */
391 /* we alloc this only for weak refs, since we can get the domain directly in the other cases */
395 /* weak and weak-track arrays will be allocated in malloc memory
397 static HandleData gc_handles [] = {
398 {NULL, NULL, 0, HANDLE_WEAK, 0},
399 {NULL, NULL, 0, HANDLE_WEAK_TRACK, 0},
400 {NULL, NULL, 0, HANDLE_NORMAL, 0},
401 {NULL, NULL, 0, HANDLE_PINNED, 0}
404 #define lock_handles(handles) EnterCriticalSection (&handle_section)
405 #define unlock_handles(handles) LeaveCriticalSection (&handle_section)
408 find_first_unset (guint32 bitmap)
411 for (i = 0; i < 32; ++i) {
412 if (!(bitmap & (1 << i)))
419 alloc_handle (HandleData *handles, MonoObject *obj)
422 lock_handles (handles);
423 if (!handles->size) {
425 if (handles->type > HANDLE_WEAK_TRACK) {
426 handles->entries = mono_gc_alloc_fixed (sizeof (gpointer) * handles->size, NULL);
428 handles->entries = g_malloc0 (sizeof (gpointer) * handles->size);
429 handles->domain_ids = g_malloc0 (sizeof (guint16) * handles->size);
431 handles->bitmap = g_malloc0 (handles->size / 8);
434 for (slot = handles->slot_hint; slot < handles->size / 32; ++slot) {
435 if (handles->bitmap [slot] != 0xffffffff) {
436 i = find_first_unset (handles->bitmap [slot]);
437 handles->slot_hint = slot;
441 if (i == -1 && handles->slot_hint != 0) {
442 for (slot = 0; slot < handles->slot_hint; ++slot) {
443 if (handles->bitmap [slot] != 0xffffffff) {
444 i = find_first_unset (handles->bitmap [slot]);
445 handles->slot_hint = slot;
452 guint32 new_size = handles->size * 2; /* always double: we memset to 0 based on this below */
454 /* resize and copy the bitmap */
455 new_bitmap = g_malloc0 (new_size / 8);
456 memcpy (new_bitmap, handles->bitmap, handles->size / 8);
457 g_free (handles->bitmap);
458 handles->bitmap = new_bitmap;
460 /* resize and copy the entries */
461 if (handles->type > HANDLE_WEAK_TRACK) {
463 entries = mono_gc_alloc_fixed (sizeof (gpointer) * new_size, NULL);
464 memcpy (entries, handles->entries, sizeof (gpointer) * handles->size);
465 handles->entries = entries;
469 domain_ids = g_malloc0 (sizeof (guint16) * new_size);
470 entries = g_malloc (sizeof (gpointer) * new_size);
471 /* we disable GC because we could lose some disappearing link updates */
473 memcpy (entries, handles->entries, sizeof (gpointer) * handles->size);
474 memset (entries + handles->size, 0, sizeof (gpointer) * handles->size);
475 memcpy (domain_ids, handles->domain_ids, sizeof (guint16) * handles->size);
476 for (i = 0; i < handles->size; ++i) {
477 MonoObject *obj = mono_gc_weak_link_get (&(handles->entries [i]));
478 mono_gc_weak_link_remove (&(handles->entries [i]));
479 /*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]);*/
481 mono_gc_weak_link_add (&(entries [i]), obj);
484 g_free (handles->entries);
485 g_free (handles->domain_ids);
486 handles->entries = entries;
487 handles->domain_ids = domain_ids;
491 /* set i and slot to the next free position */
493 slot = (handles->size + 1) / 32;
494 handles->slot_hint = handles->size + 1;
495 handles->size = new_size;
497 handles->bitmap [slot] |= 1 << i;
498 slot = slot * 32 + i;
499 handles->entries [slot] = obj;
500 if (handles->type <= HANDLE_WEAK_TRACK) {
502 mono_gc_weak_link_add (&(handles->entries [slot]), obj);
505 unlock_handles (handles);
506 /*g_print ("allocated entry %d of type %d to object %p (in slot: %p)\n", slot, handles->type, obj, handles->entries [slot]);*/
507 return (slot << 3) | (handles->type + 1);
512 * @obj: managed object to get a handle for
513 * @pinned: whether the object should be pinned
515 * This returns a handle that wraps the object, this is used to keep a
516 * reference to a managed object from the unmanaged world and preventing the
517 * object from being disposed.
519 * If @pinned is false the address of the object can not be obtained, if it is
520 * true the address of the object can be obtained. This will also pin the
521 * object so it will not be possible by a moving garbage collector to move the
524 * Returns: a handle that can be used to access the object from
528 mono_gchandle_new (MonoObject *obj, gboolean pinned)
530 return alloc_handle (&gc_handles [pinned? HANDLE_PINNED: HANDLE_NORMAL], obj);
534 * mono_gchandle_new_weakref:
535 * @obj: managed object to get a handle for
536 * @pinned: whether the object should be pinned
538 * This returns a weak handle that wraps the object, this is used to
539 * keep a reference to a managed object from the unmanaged world.
540 * Unlike the mono_gchandle_new the object can be reclaimed by the
541 * garbage collector. In this case the value of the GCHandle will be
544 * If @pinned is false the address of the object can not be obtained, if it is
545 * true the address of the object can be obtained. This will also pin the
546 * object so it will not be possible by a moving garbage collector to move the
549 * Returns: a handle that can be used to access the object from
553 mono_gchandle_new_weakref (MonoObject *obj, gboolean track_resurrection)
555 return alloc_handle (&gc_handles [track_resurrection? HANDLE_WEAK_TRACK: HANDLE_WEAK], obj);
559 * mono_gchandle_get_target:
560 * @gchandle: a GCHandle's handle.
562 * The handle was previously created by calling mono_gchandle_new or
563 * mono_gchandle_new_weakref.
565 * Returns a pointer to the MonoObject represented by the handle or
566 * NULL for a collected object if using a weakref handle.
569 mono_gchandle_get_target (guint32 gchandle)
571 guint slot = gchandle >> 3;
572 guint type = (gchandle & 7) - 1;
573 HandleData *handles = &gc_handles [type];
574 MonoObject *obj = NULL;
577 lock_handles (handles);
578 if (slot < handles->size && (handles->bitmap [slot / 32] & (1 << (slot % 32)))) {
579 if (handles->type <= HANDLE_WEAK_TRACK) {
580 obj = mono_gc_weak_link_get (&handles->entries [slot]);
582 obj = handles->entries [slot];
585 /* print a warning? */
587 unlock_handles (handles);
588 /*g_print ("get target of entry %d of type %d: %p\n", slot, handles->type, obj);*/
593 mono_gchandle_set_target (guint32 gchandle, MonoObject *obj)
595 guint slot = gchandle >> 3;
596 guint type = (gchandle & 7) - 1;
597 HandleData *handles = &gc_handles [type];
600 lock_handles (handles);
601 if (slot < handles->size && (handles->bitmap [slot / 32] & (1 << (slot % 32)))) {
602 if (handles->type <= HANDLE_WEAK_TRACK) {
603 mono_gc_weak_link_remove (&handles->entries [slot]);
605 mono_gc_weak_link_add (&handles->entries [slot], obj);
607 handles->entries [slot] = obj;
610 /* print a warning? */
612 /*g_print ("changed entry %d of type %d to object %p (in slot: %p)\n", slot, handles->type, obj, handles->entries [slot]);*/
613 unlock_handles (handles);
617 * mono_gchandle_is_in_domain:
618 * @gchandle: a GCHandle's handle.
619 * @domain: An application domain.
621 * Returns: true if the object wrapped by the @gchandle belongs to the specific @domain.
624 mono_gchandle_is_in_domain (guint32 gchandle, MonoDomain *domain)
626 guint slot = gchandle >> 3;
627 guint type = (gchandle & 7) - 1;
628 HandleData *handles = &gc_handles [type];
629 gboolean result = FALSE;
632 lock_handles (handles);
633 if (slot < handles->size && (handles->bitmap [slot / 32] & (1 << (slot % 32)))) {
634 if (handles->type <= HANDLE_WEAK_TRACK) {
635 result = domain->domain_id == handles->domain_ids [slot];
638 obj = handles->entries [slot];
642 result = domain == mono_object_domain (obj);
645 /* print a warning? */
647 unlock_handles (handles);
652 * mono_gchandle_free:
653 * @gchandle: a GCHandle's handle.
655 * Frees the @gchandle handle. If there are no outstanding
656 * references, the garbage collector can reclaim the memory of the
660 mono_gchandle_free (guint32 gchandle)
662 guint slot = gchandle >> 3;
663 guint type = (gchandle & 7) - 1;
664 HandleData *handles = &gc_handles [type];
667 lock_handles (handles);
668 if (slot < handles->size && (handles->bitmap [slot / 32] & (1 << (slot % 32)))) {
669 if (handles->type <= HANDLE_WEAK_TRACK)
670 mono_gc_weak_link_remove (&handles->entries [slot]);
672 handles->entries [slot] = NULL;
673 handles->bitmap [slot / 32] &= ~(1 << (slot % 32));
675 /* print a warning? */
677 /*g_print ("freed entry %d of type %d\n", slot, handles->type);*/
678 unlock_handles (handles);
683 static HANDLE finalizer_event;
684 static volatile gboolean finished=FALSE;
687 mono_gc_finalize_notify (void)
690 g_message (G_GNUC_PRETTY_FUNCTION ": prodding finalizer");
693 SetEvent (finalizer_event);
697 collect_objects (gpointer key, gpointer value, gpointer user_data)
699 GPtrArray *arr = (GPtrArray*)user_data;
700 g_ptr_array_add (arr, key);
704 * finalize_domain_objects:
706 * Run the finalizers of all finalizable objects in req->domain.
709 finalize_domain_objects (DomainFinalizationReq *req)
713 MonoDomain *domain = req->domain;
715 while (g_hash_table_size (domain->finalizable_objects_hash) > 0) {
717 * Since the domain is unloading, nobody is allowed to put
718 * new entries into the hash table. But finalize_object might
719 * remove entries from the hash table, so we make a copy.
721 objs = g_ptr_array_new ();
722 g_hash_table_foreach (domain->finalizable_objects_hash,
723 collect_objects, objs);
724 /* printf ("FINALIZING %d OBJECTS.\n", objs->len); */
726 for (i = 0; i < objs->len; ++i) {
727 MonoObject *o = (MonoObject*)g_ptr_array_index (objs, i);
728 /* FIXME: Avoid finalizing threads, etc */
732 g_ptr_array_free (objs, TRUE);
735 /* Process finalizers which are already in the queue */
736 mono_gc_invoke_finalizers ();
738 /* printf ("DONE.\n"); */
739 SetEvent (req->done_event);
741 /* The event is closed in mono_domain_finalize if we get here */
745 static guint32 finalizer_thread (gpointer unused)
747 gc_thread = mono_thread_current ();
749 SetEvent (thread_started_event);
752 /* Wait to be notified that there's at least one
755 WaitForSingleObjectEx (finalizer_event, INFINITE, TRUE);
757 if (domains_to_finalize) {
758 mono_finalizer_lock ();
759 if (domains_to_finalize) {
760 DomainFinalizationReq *req = domains_to_finalize->data;
761 domains_to_finalize = g_slist_remove (domains_to_finalize, req);
762 mono_finalizer_unlock ();
764 finalize_domain_objects (req);
767 mono_finalizer_unlock ();
771 g_message (G_GNUC_PRETTY_FUNCTION ": invoking finalizers");
774 /* If finished == TRUE, mono_gc_cleanup has been called (from mono_runtime_cleanup),
775 * before the domain is unloaded.
777 mono_gc_invoke_finalizers ();
779 SetEvent (pending_done_event);
782 SetEvent (shutdown_event);
787 * Enable or disable the separate finalizer thread.
788 * It's currently disabled because it still requires some
789 * work in the rest of the runtime.
791 #define ENABLE_FINALIZER_THREAD
796 InitializeCriticalSection (&handle_section);
797 InitializeCriticalSection (&allocator_section);
799 InitializeCriticalSection (&finalizer_mutex);
801 MONO_GC_REGISTER_ROOT (gc_handles [HANDLE_NORMAL].entries);
802 MONO_GC_REGISTER_ROOT (gc_handles [HANDLE_PINNED].entries);
804 mono_gc_base_init ();
806 #ifdef ENABLE_FINALIZER_THREAD
808 if (g_getenv ("GC_DONT_GC")) {
813 finalizer_event = CreateEvent (NULL, FALSE, FALSE, NULL);
814 pending_done_event = CreateEvent (NULL, TRUE, FALSE, NULL);
815 shutdown_event = CreateEvent (NULL, TRUE, FALSE, NULL);
816 thread_started_event = CreateEvent (NULL, TRUE, FALSE, NULL);
817 if (finalizer_event == NULL || pending_done_event == NULL || shutdown_event == NULL || thread_started_event == NULL) {
818 g_assert_not_reached ();
821 mono_thread_create (mono_domain_get (), finalizer_thread, NULL);
823 * Wait until the finalizer thread sets gc_thread since its value is needed
824 * by mono_thread_attach ()
826 WaitForSingleObjectEx (thread_started_event, INFINITE, FALSE);
830 void mono_gc_cleanup (void)
833 g_message (G_GNUC_PRETTY_FUNCTION ": cleaning up finalizer");
836 #ifdef ENABLE_FINALIZER_THREAD
838 ResetEvent (shutdown_event);
840 if (mono_thread_current () != gc_thread) {
841 mono_gc_finalize_notify ();
842 /* Finishing the finalizer thread, so wait a little bit... */
843 /* MS seems to wait for about 2 seconds */
844 if (WaitForSingleObjectEx (shutdown_event, 2000, FALSE) == WAIT_TIMEOUT) {
845 mono_thread_stop (gc_thread);
850 GC_finalizer_notifier = NULL;
859 /* no Boehm GC support. */
860 void mono_gc_init (void)
862 InitializeCriticalSection (&handle_section);
865 void mono_gc_cleanup (void)
872 * mono_gc_is_finalizer_thread:
873 * @thread: the thread to test.
875 * In Mono objects are finalized asynchronously on a separate thread.
876 * This routine tests whether the @thread argument represents the
877 * finalization thread.
879 * Returns true if @thread is the finalization thread.
882 mono_gc_is_finalizer_thread (MonoThread *thread)
884 return thread == gc_thread;