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/threads.h>
15 #include <mono/metadata/tabledefs.h>
16 #include <mono/metadata/exception.h>
17 #include <mono/metadata/profiler-private.h>
18 #include <mono/metadata/domain-internals.h>
19 #include <mono/metadata/class-internals.h>
20 #include <mono/utils/mono-logger.h>
21 #define GC_I_HIDE_POINTERS
22 #include <mono/os/gc_wrapper.h>
25 #define HIDE_POINTER(v) (v)
26 #define REVEAL_POINTER(v) (v)
29 typedef struct DomainFinalizationReq {
32 } DomainFinalizationReq;
34 #ifdef PLATFORM_WINCE /* FIXME: add accessors to gc.dll API */
35 extern void (*__imp_GC_finalizer_notifier)(void);
36 #define GC_finalizer_notifier __imp_GC_finalizer_notifier
37 extern int __imp_GC_finalize_on_demand;
38 #define GC_finalize_on_demand __imp_GC_finalize_on_demand
41 #ifdef HAVE_VALGRIND_MEMCHECK_H
42 #include <valgrind/memcheck.h>
45 static int finalize_slot = -1;
47 static gboolean gc_disabled = FALSE;
49 static CRITICAL_SECTION finalizer_mutex;
51 static GSList *domains_to_finalize= NULL;
53 static MonoThread *gc_thread;
55 static void object_register_finalizer (MonoObject *obj, void (*callback)(void *, void*));
58 static void finalize_notify (void);
59 static HANDLE pending_done_event;
60 static HANDLE shutdown_event;
61 static HANDLE thread_started_event;
65 * actually, we might want to queue the finalize requests in a separate thread,
66 * but we need to be careful about the execution domain of the thread...
69 run_finalize (void *obj, void *data)
71 MonoObject *exc = NULL;
73 o = (MonoObject*)((char*)obj + GPOINTER_TO_UINT (data));
75 if (finalize_slot < 0) {
77 MonoClass* obj_class = mono_get_object_class ();
78 for (i = 0; i < obj_class->vtable_size; ++i) {
79 MonoMethod *cm = obj_class->vtable [i];
81 if (!strcmp (mono_method_get_name (cm), "Finalize")) {
88 mono_domain_lock (o->vtable->domain);
90 o2 = g_hash_table_lookup (o->vtable->domain->finalizable_objects_hash, o);
92 mono_domain_unlock (o->vtable->domain);
95 /* Already finalized somehow */
98 /* make sure the finalizer is not called again if the object is resurrected */
99 object_register_finalizer (obj, NULL);
101 if (o->vtable->klass == mono_get_thread_class ())
102 if (mono_gc_is_finalizer_thread ((MonoThread*)o))
103 /* Avoid finalizing ourselves */
106 /* speedup later... and use a timeout */
107 /* g_print ("Finalize run on %p %s.%s\n", o, mono_object_class (o)->name_space, mono_object_class (o)->name); */
109 /* Use _internal here, since this thread can enter a doomed appdomain */
110 mono_domain_set_internal (mono_object_domain (o));
112 mono_runtime_invoke (o->vtable->klass->vtable [finalize_slot], o, NULL, &exc);
115 /* fixme: do something useful */
120 mono_gc_out_of_memory (size_t size)
123 * we could allocate at program startup some memory that we could release
124 * back to the system at this point if we're really low on memory (ie, size is
125 * lower than the memory we set apart)
127 mono_raise_exception (mono_domain_get ()->out_of_memory_ex);
133 * Some of our objects may point to a different address than the address returned by GC_malloc()
134 * (because of the GetHashCode hack), but we need to pass the real address to register_finalizer.
135 * This also means that in the callback we need to adjust the pointer to get back the real
137 * We also need to be consistent in the use of the GC_debug* variants of malloc and register_finalizer,
138 * since that, too, can cause the underlying pointer to be offset.
141 object_register_finalizer (MonoObject *obj, void (*callback)(void *, void*))
147 /* This assertion is not valid when GC_DEBUG is defined */
148 g_assert (GC_base (obj) == (char*)obj - offset);
151 if (mono_domain_is_unloading (obj->vtable->domain) && (callback != NULL))
153 * Can't register finalizers in a dying appdomain, since they
154 * could be invoked after the appdomain has been unloaded.
158 mono_domain_lock (obj->vtable->domain);
161 g_hash_table_insert (obj->vtable->domain->finalizable_objects_hash, obj,
164 g_hash_table_remove (obj->vtable->domain->finalizable_objects_hash, obj);
166 mono_domain_unlock (obj->vtable->domain);
168 GC_REGISTER_FINALIZER_NO_ORDER ((char*)obj - offset, callback, GUINT_TO_POINTER (offset), NULL, NULL);
173 mono_object_register_finalizer (MonoObject *obj)
175 /* g_print ("Registered finalizer on %p %s.%s\n", obj, mono_object_class (obj)->name_space, mono_object_class (obj)->name); */
176 object_register_finalizer (obj, run_finalize);
180 * mono_domain_finalize:
182 * Request finalization of all finalizable objects inside @domain. Wait
183 * @timeout msecs for the finalization to complete.
184 * Returns: TRUE if succeeded, FALSE if there was a timeout
188 mono_domain_finalize (MonoDomain *domain, guint32 timeout)
190 DomainFinalizationReq *req;
194 if (mono_thread_current () == gc_thread)
195 /* We are called from inside a finalizer, not much we can do here */
198 mono_profiler_appdomain_event (domain, MONO_PROFILE_START_UNLOAD);
201 * No need to create another thread 'cause the finalizer thread
202 * is still working and will take care of running the finalizers
211 done_event = CreateEvent (NULL, TRUE, FALSE, NULL);
213 req = g_new0 (DomainFinalizationReq, 1);
214 req->domain = domain;
215 req->done_event = done_event;
217 EnterCriticalSection (&finalizer_mutex);
219 domains_to_finalize = g_slist_append (domains_to_finalize, req);
221 LeaveCriticalSection (&finalizer_mutex);
223 /* Tell the finalizer thread to finalize this appdomain */
226 res = WaitForSingleObjectEx (done_event, timeout, TRUE);
228 /* printf ("WAIT RES: %d.\n", res); */
229 if (res == WAIT_TIMEOUT) {
230 /* We leak the handle here */
234 CloseHandle (done_event);
237 /* We don't support domain finalization without a GC */
243 ves_icall_System_GC_InternalCollect (int generation)
253 ves_icall_System_GC_GetTotalMemory (MonoBoolean forceCollection)
260 return GC_get_heap_size () - GC_get_free_bytes ();
267 ves_icall_System_GC_KeepAlive (MonoObject *obj)
277 ves_icall_System_GC_ReRegisterForFinalize (MonoObject *obj)
281 object_register_finalizer (obj, run_finalize);
285 ves_icall_System_GC_SuppressFinalize (MonoObject *obj)
289 object_register_finalizer (obj, NULL);
293 ves_icall_System_GC_WaitForPendingFinalizers (void)
298 if (!GC_should_invoke_finalizers ())
301 if (mono_thread_current () == gc_thread)
302 /* Avoid deadlocks */
305 ResetEvent (pending_done_event);
307 /* g_print ("Waiting for pending finalizers....\n"); */
308 WaitForSingleObjectEx (pending_done_event, INFINITE, TRUE);
309 /* g_print ("Done pending....\n"); */
314 static CRITICAL_SECTION allocator_section;
315 static CRITICAL_SECTION handle_section;
316 static guint32 next_handle = 0;
317 static gpointer *gc_handles = NULL;
318 static guint8 *gc_handle_types = NULL;
319 static guint32 array_size = 0;
322 * The handle type is encoded in the lower two bits of the handle value:
336 * FIXME: make thread safe and reuse the array entries.
339 ves_icall_System_GCHandle_GetTarget (guint32 handle)
348 EnterCriticalSection (&handle_section);
349 g_assert (type == gc_handle_types [handle >> 2]);
350 obj = gc_handles [handle >> 2];
351 LeaveCriticalSection (&handle_section);
355 if ((type == HANDLE_WEAK) || (type == HANDLE_WEAK_TRACK))
356 return REVEAL_POINTER (obj);
364 ves_icall_System_GCHandle_GetTargetHandle (MonoObject *obj, guint32 handle, gint32 type)
371 EnterCriticalSection (&handle_section);
372 /* Indexes start from 1 since 0 means the handle is not allocated */
374 if (idx >= array_size) {
376 guint8 *new_type_array;
380 new_array = GC_MALLOC (sizeof (gpointer) * (array_size * 2));
381 new_type_array = GC_MALLOC (sizeof (guint8) * (array_size * 2));
383 new_array = g_malloc0 (sizeof (gpointer) * (array_size * 2));
384 new_type_array = g_malloc0 (sizeof (guint8) * (array_size * 2));
388 memcpy (new_array, gc_handles, sizeof (gpointer) * array_size);
389 memcpy (new_type_array, gc_handle_types, sizeof (guint8) * array_size);
390 /* need to re-register links for weak refs. test if GC_realloc needs the same */
391 for (i = 0; i < array_size; ++i) {
392 #if 0 /* This breaks the threaded finalizer, by causing segfaults deep
393 * inside libgc. I assume it will also break without the
394 * threaded finalizer, just that the stress test (bug 31333)
395 * deadlocks too early without it. Reverting to the previous
396 * version here stops the segfault.
398 if ((gc_handle_types[i] == HANDLE_WEAK) || (gc_handle_types[i] == HANDLE_WEAK_TRACK)) { /* all and only disguised pointers have it set */
400 if (((gulong)new_array [i]) & 0x1) {
403 if (gc_handles [i] != (gpointer)-1)
404 GC_unregister_disappearing_link (&(gc_handles [i]));
405 if (new_array [i] != (gpointer)-1)
406 GC_GENERAL_REGISTER_DISAPPEARING_LINK (&(new_array [i]), REVEAL_POINTER (new_array [i]));
412 #ifndef HAVE_BOEHM_GC
414 g_free (gc_handle_types);
416 gc_handles = new_array;
417 gc_handle_types = new_type_array;
420 /* resuse the type from the old target */
423 h = (idx << 2) | type;
426 case HANDLE_WEAK_TRACK:
427 val = (gpointer)HIDE_POINTER (val);
428 gc_handles [idx] = val;
429 gc_handle_types [idx] = type;
431 if (gc_handles [idx] != (gpointer)-1)
432 GC_GENERAL_REGISTER_DISAPPEARING_LINK (&(gc_handles [idx]), obj);
436 gc_handles [idx] = val;
437 gc_handle_types [idx] = type;
440 LeaveCriticalSection (&handle_section);
445 ves_icall_System_GCHandle_FreeHandle (guint32 handle)
447 int idx = handle >> 2;
448 int type = handle & 0x3;
452 EnterCriticalSection (&handle_section);
455 g_assert (type == gc_handle_types [idx]);
456 if ((type == HANDLE_WEAK) || (type == HANDLE_WEAK_TRACK)) {
457 if (gc_handles [idx] != (gpointer)-1)
458 GC_unregister_disappearing_link (&(gc_handles [idx]));
462 gc_handles [idx] = (gpointer)-1;
463 gc_handle_types [idx] = (guint8)-1;
464 LeaveCriticalSection (&handle_section);
468 ves_icall_System_GCHandle_GetAddrOfPinnedObject (guint32 handle)
471 int type = handle & 0x3;
476 EnterCriticalSection (&handle_section);
477 obj = gc_handles [handle >> 2];
478 g_assert (gc_handle_types [handle >> 2] == type);
479 LeaveCriticalSection (&handle_section);
480 if ((type == HANDLE_WEAK) || (type == HANDLE_WEAK_TRACK)) {
481 obj = REVEAL_POINTER (obj);
482 if (obj == (MonoObject *) -1)
486 MonoClass *klass = mono_object_class (obj);
487 if (klass == mono_defaults.string_class) {
488 return mono_string_chars ((MonoString*)obj);
489 } else if (klass->rank) {
490 return mono_array_addr ((MonoArray*)obj, char, 0);
492 /* the C# code will check and throw the exception */
493 /* FIXME: missing !klass->blittable test, see bug #61134 */
494 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
496 return (char*)obj + sizeof (MonoObject);
504 mono_gchandle_new (MonoObject *obj, gboolean pinned)
506 return ves_icall_System_GCHandle_GetTargetHandle (obj, 0, pinned? HANDLE_PINNED: HANDLE_NORMAL);
510 mono_gchandle_new_weakref (MonoObject *obj, gboolean track_resurrection)
512 return ves_icall_System_GCHandle_GetTargetHandle (obj, 0, track_resurrection? HANDLE_WEAK_TRACK: HANDLE_WEAK);
515 /* This will return NULL for a collected object if using a weakref handle */
517 mono_gchandle_get_target (guint32 gchandle)
519 return ves_icall_System_GCHandle_GetTarget (gchandle);
523 mono_gchandle_free (guint32 gchandle)
525 ves_icall_System_GCHandle_FreeHandle (gchandle);
530 static HANDLE finalizer_event;
531 static volatile gboolean finished=FALSE;
533 static void finalize_notify (void)
536 g_message (G_GNUC_PRETTY_FUNCTION ": prodding finalizer");
539 SetEvent (finalizer_event);
543 collect_objects (gpointer key, gpointer value, gpointer user_data)
545 GPtrArray *arr = (GPtrArray*)user_data;
546 g_ptr_array_add (arr, key);
550 * finalize_domain_objects:
552 * Run the finalizers of all finalizable objects in req->domain.
555 finalize_domain_objects (DomainFinalizationReq *req)
559 MonoDomain *domain = req->domain;
561 while (g_hash_table_size (domain->finalizable_objects_hash) > 0) {
563 * Since the domain is unloading, nobody is allowed to put
564 * new entries into the hash table. But finalize_object might
565 * remove entries from the hash table, so we make a copy.
567 objs = g_ptr_array_new ();
568 g_hash_table_foreach (domain->finalizable_objects_hash,
569 collect_objects, objs);
570 /* printf ("FINALIZING %d OBJECTS.\n", objs->len); */
572 for (i = 0; i < objs->len; ++i) {
573 MonoObject *o = (MonoObject*)g_ptr_array_index (objs, i);
574 /* FIXME: Avoid finalizing threads, etc */
578 g_ptr_array_free (objs, TRUE);
581 /* Process finalizers which are already in the queue */
582 GC_invoke_finalizers ();
584 /* printf ("DONE.\n"); */
585 SetEvent (req->done_event);
587 /* The event is closed in mono_domain_finalize if we get here */
591 static guint32 finalizer_thread (gpointer unused)
593 gc_thread = mono_thread_current ();
595 SetEvent (thread_started_event);
598 /* Wait to be notified that there's at least one
601 WaitForSingleObjectEx (finalizer_event, INFINITE, TRUE);
603 if (domains_to_finalize) {
604 EnterCriticalSection (&finalizer_mutex);
605 if (domains_to_finalize) {
606 DomainFinalizationReq *req = domains_to_finalize->data;
607 domains_to_finalize = g_slist_remove (domains_to_finalize, req);
608 LeaveCriticalSection (&finalizer_mutex);
610 finalize_domain_objects (req);
613 LeaveCriticalSection (&finalizer_mutex);
617 g_message (G_GNUC_PRETTY_FUNCTION ": invoking finalizers");
620 /* If finished == TRUE, mono_gc_cleanup has been called (from mono_runtime_cleanup),
621 * before the domain is unloaded.
623 * There is a bug in GC_invoke_finalizer () in versions <= 6.2alpha4:
624 * the 'mem_freed' variable is not initialized when there are no
625 * objects to finalize, which leads to strange behavior later on.
626 * The check is necessary to work around that bug.
628 if (GC_should_invoke_finalizers ()) {
629 GC_invoke_finalizers ();
632 SetEvent (pending_done_event);
635 SetEvent (shutdown_event);
640 * Enable or disable the separate finalizer thread.
641 * It's currently disabled because it still requires some
642 * work in the rest of the runtime.
644 #define ENABLE_FINALIZER_THREAD
646 #ifdef WITH_INCLUDED_LIBGC
648 extern void mono_gc_stop_world (void);
649 extern void mono_gc_start_world (void);
650 extern void mono_gc_push_all_stacks (void);
652 static void mono_gc_lock (void)
654 EnterCriticalSection (&allocator_section);
657 static void mono_gc_unlock (void)
659 LeaveCriticalSection (&allocator_section);
662 static GCThreadFunctions mono_gc_thread_vtable = {
670 mono_gc_push_all_stacks,
673 #endif /* WITH_INCLUDED_LIBGC */
676 mono_gc_warning (char *msg, GC_word arg)
678 mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_GC, msg, (unsigned long)arg);
682 mono_running_on_valgrind (void)
684 #ifdef HAVE_VALGRIND_MEMCHECK_H
685 if (RUNNING_ON_VALGRIND)
695 void mono_gc_init (void)
697 InitializeCriticalSection (&handle_section);
698 InitializeCriticalSection (&allocator_section);
700 InitializeCriticalSection (&finalizer_mutex);
702 #ifdef WITH_INCLUDED_LIBGC
703 gc_thread_vtable = &mono_gc_thread_vtable;
706 MONO_GC_REGISTER_ROOT (gc_handles);
707 MONO_GC_REGISTER_ROOT (gc_handle_types);
710 GC_oom_fn = mono_gc_out_of_memory;
712 GC_set_warn_proc (mono_gc_warning);
714 #ifdef ENABLE_FINALIZER_THREAD
716 if (g_getenv ("GC_DONT_GC")) {
721 /* valgrind does not play nicely with the GC,
722 * so, turn it off when we are under vg.
724 if (mono_running_on_valgrind ()) {
725 /* valgrind doesnt like g_warning for some reason... */
726 printf ("You are running under valgrind. Currently, valgrind does "
727 "not support the GC. This program will run with the GC "
728 "turned off. Your program may take up a fair amount of "
729 "memory. Also, finalizers will not be run.\n");
735 finalizer_event = CreateEvent (NULL, FALSE, FALSE, NULL);
736 pending_done_event = CreateEvent (NULL, TRUE, FALSE, NULL);
737 shutdown_event = CreateEvent (NULL, TRUE, FALSE, NULL);
738 thread_started_event = CreateEvent (NULL, TRUE, FALSE, NULL);
739 if (finalizer_event == NULL || pending_done_event == NULL || shutdown_event == NULL || thread_started_event == NULL) {
740 g_assert_not_reached ();
743 GC_finalize_on_demand = 1;
744 GC_finalizer_notifier = finalize_notify;
746 mono_thread_create (mono_domain_get (), finalizer_thread, NULL);
748 * Wait until the finalizer thread sets gc_thread since its value is needed
749 * by mono_thread_attach ()
751 WaitForSingleObjectEx (thread_started_event, INFINITE, FALSE);
755 void mono_gc_cleanup (void)
758 g_message (G_GNUC_PRETTY_FUNCTION ": cleaning up finalizer");
761 #ifdef ENABLE_FINALIZER_THREAD
763 ResetEvent (shutdown_event);
765 if (mono_thread_current () != gc_thread) {
767 /* Finishing the finalizer thread, so wait a little bit... */
768 /* MS seems to wait for about 2 seconds */
769 if (WaitForSingleObjectEx (shutdown_event, 2000000, FALSE) == WAIT_TIMEOUT) {
770 mono_thread_stop (gc_thread);
774 GC_finalizer_notifier = NULL;
781 mono_gc_disable (void)
783 #ifdef HAVE_GC_ENABLE
786 g_assert_not_reached ();
791 mono_gc_enable (void)
793 #ifdef HAVE_GC_ENABLE
796 g_assert_not_reached ();
802 /* no Boehm GC support. */
803 void mono_gc_init (void)
805 InitializeCriticalSection (&handle_section);
808 void mono_gc_cleanup (void)
813 mono_gc_disable (void)
818 mono_gc_enable (void)
825 mono_gc_is_finalizer_thread (MonoThread *thread)
827 return thread == gc_thread;