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/domain-internals.h>
18 #include <mono/metadata/class-internals.h>
19 #include <mono/utils/mono-logger.h>
20 #define GC_I_HIDE_POINTERS
21 #include <mono/os/gc_wrapper.h>
24 #define HIDE_POINTER(v) (v)
25 #define REVEAL_POINTER(v) (v)
28 typedef struct DomainFinalizationReq {
31 } DomainFinalizationReq;
33 #ifdef PLATFORM_WINCE /* FIXME: add accessors to gc.dll API */
34 extern void (*__imp_GC_finalizer_notifier)(void);
35 #define GC_finalizer_notifier __imp_GC_finalizer_notifier
36 extern int __imp_GC_finalize_on_demand;
37 #define GC_finalize_on_demand __imp_GC_finalize_on_demand
40 static int finalize_slot = -1;
42 static gboolean gc_disabled = FALSE;
44 static CRITICAL_SECTION finalizer_mutex;
46 static GSList *domains_to_finalize= NULL;
48 static MonoThread *gc_thread;
50 static void object_register_finalizer (MonoObject *obj, void (*callback)(void *, void*));
53 static void finalize_notify (void);
54 static HANDLE pending_done_event;
55 static HANDLE shutdown_event;
56 static HANDLE thread_started_event;
60 * actually, we might want to queue the finalize requests in a separate thread,
61 * but we need to be careful about the execution domain of the thread...
64 run_finalize (void *obj, void *data)
66 MonoObject *exc = NULL;
68 o = (MonoObject*)((char*)obj + GPOINTER_TO_UINT (data));
70 if (finalize_slot < 0) {
72 MonoClass* obj_class = mono_get_object_class ();
73 for (i = 0; i < obj_class->vtable_size; ++i) {
74 MonoMethod *cm = obj_class->vtable [i];
76 if (!strcmp (mono_method_get_name (cm), "Finalize")) {
83 mono_domain_lock (o->vtable->domain);
85 o2 = g_hash_table_lookup (o->vtable->domain->finalizable_objects_hash, o);
87 mono_domain_unlock (o->vtable->domain);
90 /* Already finalized somehow */
93 /* make sure the finalizer is not called again if the object is resurrected */
94 object_register_finalizer (obj, NULL);
96 if (o->vtable->klass == mono_get_thread_class ())
97 if (mono_gc_is_finalizer_thread ((MonoThread*)o))
98 /* Avoid finalizing ourselves */
101 /* speedup later... and use a timeout */
102 /* g_print ("Finalize run on %p %s.%s\n", o, mono_object_class (o)->name_space, mono_object_class (o)->name); */
104 /* Use _internal here, since this thread can enter a doomed appdomain */
105 mono_domain_set_internal (mono_object_domain (o));
107 mono_runtime_invoke (o->vtable->klass->vtable [finalize_slot], o, NULL, &exc);
110 /* fixme: do something useful */
115 mono_gc_out_of_memory (size_t size)
118 * we could allocate at program startup some memory that we could release
119 * back to the system at this point if we're really low on memory (ie, size is
120 * lower than the memory we set apart)
122 mono_raise_exception (mono_domain_get ()->out_of_memory_ex);
128 * Some of our objects may point to a different address than the address returned by GC_malloc()
129 * (because of the GetHashCode hack), but we need to pass the real address to register_finalizer.
130 * This also means that in the callback we need to adjust the pointer to get back the real
132 * We also need to be consistent in the use of the GC_debug* variants of malloc and register_finalizer,
133 * since that, too, can cause the underlying pointer to be offset.
136 object_register_finalizer (MonoObject *obj, void (*callback)(void *, void*))
142 /* This assertion is not valid when GC_DEBUG is defined */
143 g_assert (GC_base (obj) == (char*)obj - offset);
146 if (mono_domain_is_unloading (obj->vtable->domain) && (callback != NULL))
148 * Can't register finalizers in a dying appdomain, since they
149 * could be invoked after the appdomain has been unloaded.
153 mono_domain_lock (obj->vtable->domain);
156 g_hash_table_insert (obj->vtable->domain->finalizable_objects_hash, obj,
159 g_hash_table_remove (obj->vtable->domain->finalizable_objects_hash, obj);
161 mono_domain_unlock (obj->vtable->domain);
163 GC_REGISTER_FINALIZER_NO_ORDER ((char*)obj - offset, callback, GUINT_TO_POINTER (offset), NULL, NULL);
168 mono_object_register_finalizer (MonoObject *obj)
170 /* g_print ("Registered finalizer on %p %s.%s\n", obj, mono_object_class (obj)->name_space, mono_object_class (obj)->name); */
171 object_register_finalizer (obj, run_finalize);
175 * mono_domain_finalize:
177 * Request finalization of all finalizable objects inside @domain. Wait
178 * @timeout msecs for the finalization to complete.
179 * Returns: TRUE if succeeded, FALSE if there was a timeout
183 mono_domain_finalize (MonoDomain *domain, guint32 timeout)
185 DomainFinalizationReq *req;
190 * No need to create another thread 'cause the finalizer thread
191 * is still working and will take care of running the finalizers
200 done_event = CreateEvent (NULL, TRUE, FALSE, NULL);
202 req = g_new0 (DomainFinalizationReq, 1);
203 req->domain = domain;
204 req->done_event = done_event;
206 EnterCriticalSection (&finalizer_mutex);
208 domains_to_finalize = g_slist_append (domains_to_finalize, req);
210 LeaveCriticalSection (&finalizer_mutex);
212 /* Tell the finalizer thread to finalize this appdomain */
215 res = WaitForSingleObjectEx (done_event, timeout, TRUE);
217 /* printf ("WAIT RES: %d.\n", res); */
218 if (res == WAIT_TIMEOUT) {
219 /* We leak the handle here */
223 CloseHandle (done_event);
226 /* We don't support domain finalization without a GC */
232 ves_icall_System_GC_InternalCollect (int generation)
242 ves_icall_System_GC_GetTotalMemory (MonoBoolean forceCollection)
249 return GC_get_heap_size () - GC_get_free_bytes ();
256 ves_icall_System_GC_KeepAlive (MonoObject *obj)
266 ves_icall_System_GC_ReRegisterForFinalize (MonoObject *obj)
270 object_register_finalizer (obj, run_finalize);
274 ves_icall_System_GC_SuppressFinalize (MonoObject *obj)
278 object_register_finalizer (obj, NULL);
282 ves_icall_System_GC_WaitForPendingFinalizers (void)
287 if (!GC_should_invoke_finalizers ())
290 if (mono_thread_current () == gc_thread)
291 /* Avoid deadlocks */
294 ResetEvent (pending_done_event);
296 /* g_print ("Waiting for pending finalizers....\n"); */
297 WaitForSingleObjectEx (pending_done_event, INFINITE, TRUE);
298 /* g_print ("Done pending....\n"); */
303 static CRITICAL_SECTION allocator_section;
304 static CRITICAL_SECTION handle_section;
305 static guint32 next_handle = 0;
306 static gpointer *gc_handles = NULL;
307 static guint8 *gc_handle_types = NULL;
308 static guint32 array_size = 0;
311 * The handle type is encoded in the lower two bits of the handle value:
325 * FIXME: make thread safe and reuse the array entries.
328 ves_icall_System_GCHandle_GetTarget (guint32 handle)
337 EnterCriticalSection (&handle_section);
338 g_assert (type == gc_handle_types [handle >> 2]);
339 obj = gc_handles [handle >> 2];
340 LeaveCriticalSection (&handle_section);
344 if ((type == HANDLE_WEAK) || (type == HANDLE_WEAK_TRACK))
345 return REVEAL_POINTER (obj);
353 ves_icall_System_GCHandle_GetTargetHandle (MonoObject *obj, guint32 handle, gint32 type)
360 EnterCriticalSection (&handle_section);
361 /* Indexes start from 1 since 0 means the handle is not allocated */
363 if (idx >= array_size) {
365 guint8 *new_type_array;
369 new_array = GC_MALLOC (sizeof (gpointer) * (array_size * 2));
370 new_type_array = GC_MALLOC (sizeof (guint8) * (array_size * 2));
372 new_array = g_malloc0 (sizeof (gpointer) * (array_size * 2));
373 new_type_array = g_malloc0 (sizeof (guint8) * (array_size * 2));
377 memcpy (new_array, gc_handles, sizeof (gpointer) * array_size);
378 memcpy (new_type_array, gc_handle_types, sizeof (guint8) * array_size);
379 /* need to re-register links for weak refs. test if GC_realloc needs the same */
380 for (i = 0; i < array_size; ++i) {
381 #if 0 /* This breaks the threaded finalizer, by causing segfaults deep
382 * inside libgc. I assume it will also break without the
383 * threaded finalizer, just that the stress test (bug 31333)
384 * deadlocks too early without it. Reverting to the previous
385 * version here stops the segfault.
387 if ((gc_handle_types[i] == HANDLE_WEAK) || (gc_handle_types[i] == HANDLE_WEAK_TRACK)) { /* all and only disguised pointers have it set */
389 if (((gulong)new_array [i]) & 0x1) {
392 if (gc_handles [i] != (gpointer)-1)
393 GC_unregister_disappearing_link (&(gc_handles [i]));
394 if (new_array [i] != (gpointer)-1)
395 GC_GENERAL_REGISTER_DISAPPEARING_LINK (&(new_array [i]), REVEAL_POINTER (new_array [i]));
401 #ifndef HAVE_BOEHM_GC
403 g_free (gc_handle_types);
405 gc_handles = new_array;
406 gc_handle_types = new_type_array;
409 /* resuse the type from the old target */
412 h = (idx << 2) | type;
415 case HANDLE_WEAK_TRACK:
416 val = (gpointer)HIDE_POINTER (val);
417 gc_handles [idx] = val;
418 gc_handle_types [idx] = type;
420 if (gc_handles [idx] != (gpointer)-1)
421 GC_GENERAL_REGISTER_DISAPPEARING_LINK (&(gc_handles [idx]), obj);
425 gc_handles [idx] = val;
426 gc_handle_types [idx] = type;
429 LeaveCriticalSection (&handle_section);
434 ves_icall_System_GCHandle_FreeHandle (guint32 handle)
436 int idx = handle >> 2;
437 int type = handle & 0x3;
441 EnterCriticalSection (&handle_section);
444 g_assert (type == gc_handle_types [idx]);
445 if ((type == HANDLE_WEAK) || (type == HANDLE_WEAK_TRACK)) {
446 if (gc_handles [idx] != (gpointer)-1)
447 GC_unregister_disappearing_link (&(gc_handles [idx]));
451 gc_handles [idx] = (gpointer)-1;
452 gc_handle_types [idx] = (guint8)-1;
453 LeaveCriticalSection (&handle_section);
457 ves_icall_System_GCHandle_GetAddrOfPinnedObject (guint32 handle)
460 int type = handle & 0x3;
465 EnterCriticalSection (&handle_section);
466 obj = gc_handles [handle >> 2];
467 g_assert (gc_handle_types [handle >> 2] == type);
468 LeaveCriticalSection (&handle_section);
469 if ((type == HANDLE_WEAK) || (type == HANDLE_WEAK_TRACK)) {
470 obj = REVEAL_POINTER (obj);
471 if (obj == (MonoObject *) -1)
475 MonoClass *klass = mono_object_class (obj);
476 if (klass == mono_defaults.string_class) {
477 return mono_string_chars ((MonoString*)obj);
478 } else if (klass->rank) {
479 return mono_array_addr ((MonoArray*)obj, char, 0);
481 /* the C# code will check and throw the exception */
482 /* FIXME: missing !klass->blittable test, see bug #61134 */
483 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
485 return (char*)obj + sizeof (MonoObject);
493 mono_gchandle_new (MonoObject *obj, gboolean pinned)
495 return ves_icall_System_GCHandle_GetTargetHandle (obj, 0, pinned? HANDLE_PINNED: HANDLE_NORMAL);
499 mono_gchandle_new_weakref (MonoObject *obj, gboolean track_resurrection)
501 return ves_icall_System_GCHandle_GetTargetHandle (obj, 0, track_resurrection? HANDLE_WEAK_TRACK: HANDLE_WEAK);
504 /* This will return NULL for a collected object if using a weakref handle */
506 mono_gchandle_get_target (guint32 gchandle)
508 return ves_icall_System_GCHandle_GetTarget (gchandle);
512 mono_gchandle_free (guint32 gchandle)
514 ves_icall_System_GCHandle_FreeHandle (gchandle);
519 static HANDLE finalizer_event;
520 static volatile gboolean finished=FALSE;
522 static void finalize_notify (void)
525 g_message (G_GNUC_PRETTY_FUNCTION ": prodding finalizer");
528 SetEvent (finalizer_event);
532 collect_objects (gpointer key, gpointer value, gpointer user_data)
534 GPtrArray *arr = (GPtrArray*)user_data;
535 g_ptr_array_add (arr, key);
539 * finalize_domain_objects:
541 * Run the finalizers of all finalizable objects in req->domain.
544 finalize_domain_objects (DomainFinalizationReq *req)
548 MonoDomain *domain = req->domain;
550 while (g_hash_table_size (domain->finalizable_objects_hash) > 0) {
552 * Since the domain is unloading, nobody is allowed to put
553 * new entries into the hash table. But finalize_object might
554 * remove entries from the hash table, so we make a copy.
556 objs = g_ptr_array_new ();
557 g_hash_table_foreach (domain->finalizable_objects_hash,
558 collect_objects, objs);
559 /* printf ("FINALIZING %d OBJECTS.\n", objs->len); */
561 for (i = 0; i < objs->len; ++i) {
562 MonoObject *o = (MonoObject*)g_ptr_array_index (objs, i);
563 /* FIXME: Avoid finalizing threads, etc */
567 g_ptr_array_free (objs, TRUE);
570 /* printf ("DONE.\n"); */
571 SetEvent (req->done_event);
573 /* The event is closed in mono_domain_finalize if we get here */
577 static guint32 finalizer_thread (gpointer unused)
579 gc_thread = mono_thread_current ();
581 SetEvent (thread_started_event);
584 /* Wait to be notified that there's at least one
587 WaitForSingleObjectEx (finalizer_event, INFINITE, TRUE);
589 if (domains_to_finalize) {
590 EnterCriticalSection (&finalizer_mutex);
591 if (domains_to_finalize) {
592 DomainFinalizationReq *req = domains_to_finalize->data;
593 domains_to_finalize = g_slist_remove (domains_to_finalize, req);
594 LeaveCriticalSection (&finalizer_mutex);
596 finalize_domain_objects (req);
599 LeaveCriticalSection (&finalizer_mutex);
603 g_message (G_GNUC_PRETTY_FUNCTION ": invoking finalizers");
606 /* If finished == TRUE, mono_gc_cleanup has been called (from mono_runtime_cleanup),
607 * before the domain is unloaded.
609 * There is a bug in GC_invoke_finalizer () in versions <= 6.2alpha4:
610 * the 'mem_freed' variable is not initialized when there are no
611 * objects to finalize, which leads to strange behavior later on.
612 * The check is necessary to work around that bug.
614 if (GC_should_invoke_finalizers ()) {
615 GC_invoke_finalizers ();
618 SetEvent (pending_done_event);
621 SetEvent (shutdown_event);
626 * Enable or disable the separate finalizer thread.
627 * It's currently disabled because it still requires some
628 * work in the rest of the runtime.
630 #define ENABLE_FINALIZER_THREAD
632 #ifdef WITH_INCLUDED_LIBGC
634 extern void mono_gc_stop_world (void);
635 extern void mono_gc_start_world (void);
636 extern void mono_gc_push_all_stacks (void);
638 static void mono_gc_lock (void)
640 EnterCriticalSection (&allocator_section);
643 static void mono_gc_unlock (void)
645 LeaveCriticalSection (&allocator_section);
648 static GCThreadFunctions mono_gc_thread_vtable = {
656 mono_gc_push_all_stacks,
659 #endif /* WITH_INCLUDED_LIBGC */
662 mono_gc_warning (char *msg, GC_word arg)
664 mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_GC, msg, (unsigned long)arg);
667 void mono_gc_init (void)
669 InitializeCriticalSection (&handle_section);
670 InitializeCriticalSection (&allocator_section);
672 InitializeCriticalSection (&finalizer_mutex);
674 #ifdef WITH_INCLUDED_LIBGC
675 gc_thread_vtable = &mono_gc_thread_vtable;
678 MONO_GC_REGISTER_ROOT (gc_handles);
679 MONO_GC_REGISTER_ROOT (gc_handle_types);
682 GC_oom_fn = mono_gc_out_of_memory;
684 GC_set_warn_proc (mono_gc_warning);
686 #ifdef ENABLE_FINALIZER_THREAD
688 if (g_getenv ("GC_DONT_GC")) {
693 finalizer_event = CreateEvent (NULL, FALSE, FALSE, NULL);
694 pending_done_event = CreateEvent (NULL, TRUE, FALSE, NULL);
695 shutdown_event = CreateEvent (NULL, TRUE, FALSE, NULL);
696 thread_started_event = CreateEvent (NULL, TRUE, FALSE, NULL);
697 if (finalizer_event == NULL || pending_done_event == NULL || shutdown_event == NULL || thread_started_event == NULL) {
698 g_assert_not_reached ();
701 GC_finalize_on_demand = 1;
702 GC_finalizer_notifier = finalize_notify;
704 mono_thread_create (mono_domain_get (), finalizer_thread, NULL);
706 * Wait until the finalizer thread sets gc_thread since its value is needed
707 * by mono_thread_attach ()
709 WaitForSingleObjectEx (thread_started_event, INFINITE, FALSE);
713 void mono_gc_cleanup (void)
716 g_message (G_GNUC_PRETTY_FUNCTION ": cleaning up finalizer");
719 #ifdef ENABLE_FINALIZER_THREAD
721 ResetEvent (shutdown_event);
724 /* Finishing the finalizer thread, so wait a little bit... */
725 /* MS seems to wait for about 2 seconds */
726 if (WaitForSingleObjectEx (shutdown_event, 2000, FALSE) == WAIT_TIMEOUT) {
727 mono_thread_stop (gc_thread);
735 mono_gc_disable (void)
737 #ifdef HAVE_GC_ENABLE
740 g_assert_not_reached ();
745 mono_gc_enable (void)
747 #ifdef HAVE_GC_ENABLE
750 g_assert_not_reached ();
756 /* no Boehm GC support. */
757 void mono_gc_init (void)
759 InitializeCriticalSection (&handle_section);
762 void mono_gc_cleanup (void)
767 mono_gc_disable (void)
772 mono_gc_enable (void)
779 mono_gc_is_finalizer_thread (MonoThread *thread)
781 return thread == gc_thread;