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 static CRITICAL_SECTION finalizer_mutex;
41 static GSList *domains_to_finalize= NULL;
43 static MonoThread *gc_thread;
45 static void object_register_finalizer (MonoObject *obj, void (*callback)(void *, void*));
48 static void finalize_notify (void);
49 static HANDLE pending_done_event;
50 static HANDLE shutdown_event;
51 static HANDLE thread_started_event;
55 * actually, we might want to queue the finalize requests in a separate thread,
56 * but we need to be careful about the execution domain of the thread...
59 run_finalize (void *obj, void *data)
61 MonoObject *exc = NULL;
63 o = (MonoObject*)((char*)obj + GPOINTER_TO_UINT (data));
65 mono_domain_lock (o->vtable->domain);
67 o2 = g_hash_table_lookup (o->vtable->domain->finalizable_objects_hash, o);
69 mono_domain_unlock (o->vtable->domain);
72 /* Already finalized somehow */
75 /* make sure the finalizer is not called again if the object is resurrected */
76 object_register_finalizer (obj, NULL);
78 if (o->vtable->klass == mono_get_thread_class ())
79 if (mono_gc_is_finalizer_thread ((MonoThread*)o))
80 /* Avoid finalizing ourselves */
83 /* speedup later... and use a timeout */
84 /* g_print ("Finalize run on %p %s.%s\n", o, mono_object_class (o)->name_space, mono_object_class (o)->name); */
86 /* Use _internal here, since this thread can enter a doomed appdomain */
87 mono_domain_set_internal (mono_object_domain (o));
89 /* delegates that have a native function pointer allocated are
90 * registered for finalization, but they don't have a Finalize
91 * method, because in most cases it's not needed and it's just a waste.
93 if (o->vtable->klass->delegate) {
94 MonoDelegate* del = (MonoDelegate*)o;
95 if (del->delegate_trampoline)
96 mono_delegate_free_ftnptr ((MonoDelegate*)o);
100 mono_runtime_invoke (mono_class_get_finalizer (o->vtable->klass), o, NULL, &exc);
103 /* fixme: do something useful */
108 mono_gc_out_of_memory (size_t size)
111 * we could allocate at program startup some memory that we could release
112 * back to the system at this point if we're really low on memory (ie, size is
113 * lower than the memory we set apart)
115 mono_raise_exception (mono_domain_get ()->out_of_memory_ex);
121 * Some of our objects may point to a different address than the address returned by GC_malloc()
122 * (because of the GetHashCode hack), but we need to pass the real address to register_finalizer.
123 * This also means that in the callback we need to adjust the pointer to get back the real
125 * We also need to be consistent in the use of the GC_debug* variants of malloc and register_finalizer,
126 * since that, too, can cause the underlying pointer to be offset.
129 object_register_finalizer (MonoObject *obj, void (*callback)(void *, void*))
135 /* This assertion is not valid when GC_DEBUG is defined */
136 g_assert (GC_base (obj) == (char*)obj - offset);
139 if (mono_domain_is_unloading (obj->vtable->domain) && (callback != NULL))
141 * Can't register finalizers in a dying appdomain, since they
142 * could be invoked after the appdomain has been unloaded.
146 mono_domain_lock (obj->vtable->domain);
149 g_hash_table_insert (obj->vtable->domain->finalizable_objects_hash, obj,
152 g_hash_table_remove (obj->vtable->domain->finalizable_objects_hash, obj);
154 mono_domain_unlock (obj->vtable->domain);
156 GC_REGISTER_FINALIZER_NO_ORDER ((char*)obj - offset, callback, GUINT_TO_POINTER (offset), NULL, NULL);
161 mono_object_register_finalizer (MonoObject *obj)
163 /* g_print ("Registered finalizer on %p %s.%s\n", obj, mono_object_class (obj)->name_space, mono_object_class (obj)->name); */
164 object_register_finalizer (obj, run_finalize);
168 * mono_domain_finalize:
170 * Request finalization of all finalizable objects inside @domain. Wait
171 * @timeout msecs for the finalization to complete.
172 * Returns: TRUE if succeeded, FALSE if there was a timeout
176 mono_domain_finalize (MonoDomain *domain, guint32 timeout)
178 DomainFinalizationReq *req;
182 if (mono_thread_current () == gc_thread)
183 /* We are called from inside a finalizer, not much we can do here */
186 mono_profiler_appdomain_event (domain, MONO_PROFILE_START_UNLOAD);
189 * No need to create another thread 'cause the finalizer thread
190 * is still working and will take care of running the finalizers
199 done_event = CreateEvent (NULL, TRUE, FALSE, NULL);
201 req = g_new0 (DomainFinalizationReq, 1);
202 req->domain = domain;
203 req->done_event = done_event;
205 EnterCriticalSection (&finalizer_mutex);
207 domains_to_finalize = g_slist_append (domains_to_finalize, req);
209 LeaveCriticalSection (&finalizer_mutex);
211 /* Tell the finalizer thread to finalize this appdomain */
214 res = WaitForSingleObjectEx (done_event, timeout, TRUE);
216 /* printf ("WAIT RES: %d.\n", res); */
217 if (res == WAIT_TIMEOUT) {
218 /* We leak the handle here */
222 CloseHandle (done_event);
225 /* We don't support domain finalization without a GC */
231 ves_icall_System_GC_InternalCollect (int generation)
233 mono_gc_collect (generation);
237 ves_icall_System_GC_GetTotalMemory (MonoBoolean forceCollection)
242 mono_gc_collect (mono_gc_max_generation ());
243 return mono_gc_get_used_size ();
247 ves_icall_System_GC_KeepAlive (MonoObject *obj)
257 ves_icall_System_GC_ReRegisterForFinalize (MonoObject *obj)
261 object_register_finalizer (obj, run_finalize);
265 ves_icall_System_GC_SuppressFinalize (MonoObject *obj)
269 object_register_finalizer (obj, NULL);
273 ves_icall_System_GC_WaitForPendingFinalizers (void)
278 if (!GC_should_invoke_finalizers ())
281 if (mono_thread_current () == gc_thread)
282 /* Avoid deadlocks */
285 ResetEvent (pending_done_event);
287 /* g_print ("Waiting for pending finalizers....\n"); */
288 WaitForSingleObjectEx (pending_done_event, INFINITE, TRUE);
289 /* g_print ("Done pending....\n"); */
294 static CRITICAL_SECTION allocator_section;
295 static CRITICAL_SECTION handle_section;
304 static void mono_gchandle_set_target (guint32 gchandle, MonoObject *obj);
307 ves_icall_System_GCHandle_GetTarget (guint32 handle)
309 return mono_gchandle_get_target (handle);
313 * if type == -1, change the target of the handle, otherwise allocate a new handle.
316 ves_icall_System_GCHandle_GetTargetHandle (MonoObject *obj, guint32 handle, gint32 type)
319 mono_gchandle_set_target (handle, obj);
320 /* the handle doesn't change */
325 return mono_gchandle_new_weakref (obj, FALSE);
326 case HANDLE_WEAK_TRACK:
327 return mono_gchandle_new_weakref (obj, TRUE);
329 return mono_gchandle_new (obj, FALSE);
331 return mono_gchandle_new (obj, TRUE);
333 g_assert_not_reached ();
339 ves_icall_System_GCHandle_FreeHandle (guint32 handle)
341 mono_gchandle_free (handle);
345 ves_icall_System_GCHandle_GetAddrOfPinnedObject (guint32 handle)
349 obj = mono_gchandle_get_target (handle);
351 MonoClass *klass = mono_object_class (obj);
352 if (klass == mono_defaults.string_class) {
353 return mono_string_chars ((MonoString*)obj);
354 } else if (klass->rank) {
355 return mono_array_addr ((MonoArray*)obj, char, 0);
357 /* the C# code will check and throw the exception */
358 /* FIXME: missing !klass->blittable test, see bug #61134 */
359 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
361 return (char*)obj + sizeof (MonoObject);
372 guint slot_hint : 24; /* starting slot for search */
373 /* 2^16 appdomains should be enough for everyone (though I know I'll regret this in 20 years) */
374 /* we alloc this only for weak refs, since we can get the domain directly in the other cases */
378 /* weak and weak-track arrays will be allocated in malloc memory
380 static HandleData gc_handles [] = {
381 {NULL, NULL, 0, HANDLE_WEAK, 0},
382 {NULL, NULL, 0, HANDLE_WEAK_TRACK, 0},
383 {NULL, NULL, 0, HANDLE_NORMAL, 0},
384 {NULL, NULL, 0, HANDLE_PINNED, 0}
387 #define lock_handles(handles) EnterCriticalSection (&handle_section)
388 #define unlock_handles(handles) LeaveCriticalSection (&handle_section)
391 find_first_unset (guint32 bitmap)
394 for (i = 0; i < 32; ++i) {
395 if (!(bitmap & (1 << i)))
402 alloc_handle (HandleData *handles, MonoObject *obj)
405 lock_handles (handles);
406 if (!handles->size) {
408 if (handles->type > HANDLE_WEAK_TRACK) {
409 handles->entries = mono_gc_alloc_fixed (sizeof (gpointer) * handles->size, NULL);
411 handles->entries = g_malloc0 (sizeof (gpointer) * handles->size);
412 handles->domain_ids = g_malloc0 (sizeof (guint16) * handles->size);
414 handles->bitmap = g_malloc0 (handles->size / 8);
417 for (slot = handles->slot_hint; slot < handles->size / 32; ++slot) {
418 if (handles->bitmap [slot] != 0xffffffff) {
419 i = find_first_unset (handles->bitmap [slot]);
420 handles->slot_hint = slot;
424 if (i == -1 && handles->slot_hint != 0) {
425 for (slot = 0; slot < handles->slot_hint; ++slot) {
426 if (handles->bitmap [slot] != 0xffffffff) {
427 i = find_first_unset (handles->bitmap [slot]);
428 handles->slot_hint = slot;
435 guint32 new_size = handles->size * 2; /* always double: we memset to 0 based on this below */
437 /* resize and copy the bitmap */
438 new_bitmap = g_malloc0 (new_size / 8);
439 memcpy (new_bitmap, handles->bitmap, handles->size / 8);
440 g_free (handles->bitmap);
441 handles->bitmap = new_bitmap;
443 /* resize and copy the entries */
444 if (handles->type > HANDLE_WEAK_TRACK) {
446 entries = mono_gc_alloc_fixed (sizeof (gpointer) * new_size, NULL);
447 memcpy (entries, handles->entries, sizeof (gpointer) * handles->size);
448 handles->entries = entries;
452 domain_ids = g_malloc0 (sizeof (guint16) * new_size);
453 entries = g_malloc (sizeof (gpointer) * new_size);
454 /* we disable GC because we could lose some disappearing link updates */
456 memcpy (entries, handles->entries, sizeof (gpointer) * handles->size);
457 memset (entries + handles->size, 0, sizeof (gpointer) * handles->size);
458 memcpy (domain_ids, handles->domain_ids, sizeof (guint16) * handles->size);
459 for (i = 0; i < handles->size; ++i) {
460 MonoObject *obj = mono_gc_weak_link_get (&(handles->entries [i]));
461 mono_gc_weak_link_remove (&(handles->entries [i]));
462 /*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]);*/
464 mono_gc_weak_link_add (&(entries [i]), obj);
467 g_free (handles->entries);
468 g_free (handles->domain_ids);
469 handles->entries = entries;
470 handles->domain_ids = domain_ids;
474 /* set i and slot to the next free position */
476 slot = (handles->size + 1) / 32;
477 handles->slot_hint = handles->size + 1;
478 handles->size = new_size;
480 handles->bitmap [slot] |= 1 << i;
481 slot = slot * 32 + i;
482 handles->entries [slot] = obj;
483 if (handles->type <= HANDLE_WEAK_TRACK) {
485 mono_gc_weak_link_add (&(handles->entries [slot]), obj);
488 unlock_handles (handles);
489 /*g_print ("allocated entry %d of type %d to object %p (in slot: %p)\n", slot, handles->type, obj, handles->entries [slot]);*/
490 return (slot << 3) | (handles->type + 1);
494 mono_gchandle_new (MonoObject *obj, gboolean pinned)
496 return alloc_handle (&gc_handles [pinned? HANDLE_PINNED: HANDLE_NORMAL], obj);
500 mono_gchandle_new_weakref (MonoObject *obj, gboolean track_resurrection)
502 return alloc_handle (&gc_handles [track_resurrection? HANDLE_WEAK_TRACK: HANDLE_WEAK], obj);
505 /* This will return NULL for a collected object if using a weakref handle */
507 mono_gchandle_get_target (guint32 gchandle)
509 guint slot = gchandle >> 3;
510 guint type = (gchandle & 7) - 1;
511 HandleData *handles = &gc_handles [type];
512 MonoObject *obj = NULL;
515 lock_handles (handles);
516 if (slot < handles->size && (handles->bitmap [slot / 32] & (1 << (slot % 32)))) {
517 if (handles->type <= HANDLE_WEAK_TRACK) {
518 obj = mono_gc_weak_link_get (&handles->entries [slot]);
520 obj = handles->entries [slot];
523 /* print a warning? */
525 unlock_handles (handles);
526 /*g_print ("get target of entry %d of type %d: %p\n", slot, handles->type, obj);*/
531 mono_gchandle_set_target (guint32 gchandle, MonoObject *obj)
533 guint slot = gchandle >> 3;
534 guint type = (gchandle & 7) - 1;
535 HandleData *handles = &gc_handles [type];
538 lock_handles (handles);
539 if (slot < handles->size && (handles->bitmap [slot / 32] & (1 << (slot % 32)))) {
540 if (handles->type <= HANDLE_WEAK_TRACK) {
541 mono_gc_weak_link_remove (&handles->entries [slot]);
543 mono_gc_weak_link_add (&handles->entries [slot], obj);
545 handles->entries [slot] = obj;
548 /* print a warning? */
550 /*g_print ("changed entry %d of type %d to object %p (in slot: %p)\n", slot, handles->type, obj, handles->entries [slot]);*/
551 unlock_handles (handles);
555 mono_gchandle_is_in_domain (guint32 gchandle, MonoDomain *domain)
557 guint slot = gchandle >> 3;
558 guint type = (gchandle & 7) - 1;
559 HandleData *handles = &gc_handles [type];
560 gboolean result = FALSE;
563 lock_handles (handles);
564 if (slot < handles->size && (handles->bitmap [slot / 32] & (1 << (slot % 32)))) {
565 if (handles->type <= HANDLE_WEAK_TRACK) {
566 result = domain->domain_id == handles->domain_ids [slot];
569 obj = handles->entries [slot];
573 result = domain == mono_object_domain (obj);
576 /* print a warning? */
578 unlock_handles (handles);
583 mono_gchandle_free (guint32 gchandle)
585 guint slot = gchandle >> 3;
586 guint type = (gchandle & 7) - 1;
587 HandleData *handles = &gc_handles [type];
590 lock_handles (handles);
591 if (slot < handles->size && (handles->bitmap [slot / 32] & (1 << (slot % 32)))) {
592 if (handles->type <= HANDLE_WEAK_TRACK)
593 mono_gc_weak_link_remove (&handles->entries [slot]);
594 handles->entries [slot] = NULL;
595 handles->bitmap [slot / 32] &= ~(1 << (slot % 32));
597 /* print a warning? */
599 /*g_print ("freed entry %d of type %d\n", slot, handles->type);*/
600 unlock_handles (handles);
605 static HANDLE finalizer_event;
606 static volatile gboolean finished=FALSE;
608 static void finalize_notify (void)
611 g_message (G_GNUC_PRETTY_FUNCTION ": prodding finalizer");
614 SetEvent (finalizer_event);
618 collect_objects (gpointer key, gpointer value, gpointer user_data)
620 GPtrArray *arr = (GPtrArray*)user_data;
621 g_ptr_array_add (arr, key);
625 * finalize_domain_objects:
627 * Run the finalizers of all finalizable objects in req->domain.
630 finalize_domain_objects (DomainFinalizationReq *req)
634 MonoDomain *domain = req->domain;
636 while (g_hash_table_size (domain->finalizable_objects_hash) > 0) {
638 * Since the domain is unloading, nobody is allowed to put
639 * new entries into the hash table. But finalize_object might
640 * remove entries from the hash table, so we make a copy.
642 objs = g_ptr_array_new ();
643 g_hash_table_foreach (domain->finalizable_objects_hash,
644 collect_objects, objs);
645 /* printf ("FINALIZING %d OBJECTS.\n", objs->len); */
647 for (i = 0; i < objs->len; ++i) {
648 MonoObject *o = (MonoObject*)g_ptr_array_index (objs, i);
649 /* FIXME: Avoid finalizing threads, etc */
653 g_ptr_array_free (objs, TRUE);
656 /* Process finalizers which are already in the queue */
657 GC_invoke_finalizers ();
659 /* printf ("DONE.\n"); */
660 SetEvent (req->done_event);
662 /* The event is closed in mono_domain_finalize if we get here */
666 static guint32 finalizer_thread (gpointer unused)
668 gc_thread = mono_thread_current ();
670 SetEvent (thread_started_event);
673 /* Wait to be notified that there's at least one
676 WaitForSingleObjectEx (finalizer_event, INFINITE, TRUE);
678 if (domains_to_finalize) {
679 EnterCriticalSection (&finalizer_mutex);
680 if (domains_to_finalize) {
681 DomainFinalizationReq *req = domains_to_finalize->data;
682 domains_to_finalize = g_slist_remove (domains_to_finalize, req);
683 LeaveCriticalSection (&finalizer_mutex);
685 finalize_domain_objects (req);
688 LeaveCriticalSection (&finalizer_mutex);
692 g_message (G_GNUC_PRETTY_FUNCTION ": invoking finalizers");
695 /* If finished == TRUE, mono_gc_cleanup has been called (from mono_runtime_cleanup),
696 * before the domain is unloaded.
698 * There is a bug in GC_invoke_finalizer () in versions <= 6.2alpha4:
699 * the 'mem_freed' variable is not initialized when there are no
700 * objects to finalize, which leads to strange behavior later on.
701 * The check is necessary to work around that bug.
703 if (GC_should_invoke_finalizers ()) {
704 GC_invoke_finalizers ();
707 SetEvent (pending_done_event);
710 SetEvent (shutdown_event);
715 * Enable or disable the separate finalizer thread.
716 * It's currently disabled because it still requires some
717 * work in the rest of the runtime.
719 #define ENABLE_FINALIZER_THREAD
721 #ifdef WITH_INCLUDED_LIBGC
723 extern void mono_gc_stop_world (void);
724 extern void mono_gc_start_world (void);
725 extern void mono_gc_push_all_stacks (void);
727 static void mono_gc_lock (void)
729 EnterCriticalSection (&allocator_section);
732 static void mono_gc_unlock (void)
734 LeaveCriticalSection (&allocator_section);
737 static GCThreadFunctions mono_gc_thread_vtable = {
745 mono_gc_push_all_stacks,
748 #endif /* WITH_INCLUDED_LIBGC */
751 mono_gc_warning (char *msg, GC_word arg)
753 mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_GC, msg, (unsigned long)arg);
756 void mono_gc_init (void)
758 InitializeCriticalSection (&handle_section);
759 InitializeCriticalSection (&allocator_section);
761 InitializeCriticalSection (&finalizer_mutex);
763 #ifdef WITH_INCLUDED_LIBGC
764 gc_thread_vtable = &mono_gc_thread_vtable;
767 MONO_GC_REGISTER_ROOT (gc_handles [HANDLE_NORMAL].entries);
768 MONO_GC_REGISTER_ROOT (gc_handles [HANDLE_PINNED].entries);
771 GC_oom_fn = mono_gc_out_of_memory;
773 GC_set_warn_proc (mono_gc_warning);
775 #ifdef ENABLE_FINALIZER_THREAD
777 if (g_getenv ("GC_DONT_GC")) {
782 finalizer_event = CreateEvent (NULL, FALSE, FALSE, NULL);
783 pending_done_event = CreateEvent (NULL, TRUE, FALSE, NULL);
784 shutdown_event = CreateEvent (NULL, TRUE, FALSE, NULL);
785 thread_started_event = CreateEvent (NULL, TRUE, FALSE, NULL);
786 if (finalizer_event == NULL || pending_done_event == NULL || shutdown_event == NULL || thread_started_event == NULL) {
787 g_assert_not_reached ();
790 GC_finalize_on_demand = 1;
791 GC_finalizer_notifier = finalize_notify;
793 mono_thread_create (mono_domain_get (), finalizer_thread, NULL);
795 * Wait until the finalizer thread sets gc_thread since its value is needed
796 * by mono_thread_attach ()
798 WaitForSingleObjectEx (thread_started_event, INFINITE, FALSE);
802 void mono_gc_cleanup (void)
805 g_message (G_GNUC_PRETTY_FUNCTION ": cleaning up finalizer");
808 #ifdef ENABLE_FINALIZER_THREAD
810 ResetEvent (shutdown_event);
812 if (mono_thread_current () != gc_thread) {
814 /* Finishing the finalizer thread, so wait a little bit... */
815 /* MS seems to wait for about 2 seconds */
816 if (WaitForSingleObjectEx (shutdown_event, 2000, FALSE) == WAIT_TIMEOUT) {
817 mono_thread_stop (gc_thread);
821 GC_finalizer_notifier = NULL;
829 /* no Boehm GC support. */
830 void mono_gc_init (void)
832 InitializeCriticalSection (&handle_section);
835 void mono_gc_cleanup (void)
842 mono_gc_is_finalizer_thread (MonoThread *thread)
844 return thread == gc_thread;