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 * Some of our objects may point to a different address than the address returned by GC_malloc()
116 * (because of the GetHashCode hack), but we need to pass the real address to register_finalizer.
117 * This also means that in the callback we need to adjust the pointer to get back the real
119 * We also need to be consistent in the use of the GC_debug* variants of malloc and register_finalizer,
120 * since that, too, can cause the underlying pointer to be offset.
123 object_register_finalizer (MonoObject *obj, void (*callback)(void *, void*))
129 /* This assertion is not valid when GC_DEBUG is defined */
130 g_assert (GC_base (obj) == (char*)obj - offset);
133 if (mono_domain_is_unloading (obj->vtable->domain) && (callback != NULL))
135 * Can't register finalizers in a dying appdomain, since they
136 * could be invoked after the appdomain has been unloaded.
140 mono_domain_lock (obj->vtable->domain);
143 g_hash_table_insert (obj->vtable->domain->finalizable_objects_hash, obj,
146 g_hash_table_remove (obj->vtable->domain->finalizable_objects_hash, obj);
148 mono_domain_unlock (obj->vtable->domain);
150 GC_REGISTER_FINALIZER_NO_ORDER ((char*)obj - offset, callback, GUINT_TO_POINTER (offset), NULL, NULL);
155 mono_object_register_finalizer (MonoObject *obj)
157 /* g_print ("Registered finalizer on %p %s.%s\n", obj, mono_object_class (obj)->name_space, mono_object_class (obj)->name); */
158 object_register_finalizer (obj, run_finalize);
162 * mono_domain_finalize:
164 * Request finalization of all finalizable objects inside @domain. Wait
165 * @timeout msecs for the finalization to complete.
166 * Returns: TRUE if succeeded, FALSE if there was a timeout
170 mono_domain_finalize (MonoDomain *domain, guint32 timeout)
172 DomainFinalizationReq *req;
177 * No need to create another thread 'cause the finalizer thread
178 * is still working and will take care of running the finalizers
187 done_event = CreateEvent (NULL, TRUE, FALSE, NULL);
189 req = g_new0 (DomainFinalizationReq, 1);
190 req->domain = domain;
191 req->done_event = done_event;
193 EnterCriticalSection (&finalizer_mutex);
195 domains_to_finalize = g_slist_append (domains_to_finalize, req);
197 LeaveCriticalSection (&finalizer_mutex);
199 /* Tell the finalizer thread to finalize this appdomain */
202 res = WaitForSingleObjectEx (done_event, timeout, TRUE);
204 /* printf ("WAIT RES: %d.\n", res); */
205 if (res == WAIT_TIMEOUT) {
206 /* We leak the handle here */
210 CloseHandle (done_event);
213 /* We don't support domain finalization without a GC */
219 ves_icall_System_GC_InternalCollect (int generation)
229 ves_icall_System_GC_GetTotalMemory (MonoBoolean forceCollection)
236 return GC_get_heap_size () - GC_get_free_bytes ();
243 ves_icall_System_GC_KeepAlive (MonoObject *obj)
253 ves_icall_System_GC_ReRegisterForFinalize (MonoObject *obj)
257 object_register_finalizer (obj, run_finalize);
261 ves_icall_System_GC_SuppressFinalize (MonoObject *obj)
265 object_register_finalizer (obj, NULL);
269 ves_icall_System_GC_WaitForPendingFinalizers (void)
274 if (!GC_should_invoke_finalizers ())
277 if (mono_thread_current () == gc_thread)
278 /* Avoid deadlocks */
281 ResetEvent (pending_done_event);
283 /* g_print ("Waiting for pending finalizers....\n"); */
284 WaitForSingleObjectEx (pending_done_event, INFINITE, TRUE);
285 /* g_print ("Done pending....\n"); */
290 static CRITICAL_SECTION allocator_section;
291 static CRITICAL_SECTION handle_section;
292 static guint32 next_handle = 0;
293 static gpointer *gc_handles = NULL;
294 static guint8 *gc_handle_types = NULL;
295 static guint32 array_size = 0;
298 * The handle type is encoded in the lower two bits of the handle value:
312 * FIXME: make thread safe and reuse the array entries.
315 ves_icall_System_GCHandle_GetTarget (guint32 handle)
324 EnterCriticalSection (&handle_section);
325 g_assert (type == gc_handle_types [handle >> 2]);
326 obj = gc_handles [handle >> 2];
327 LeaveCriticalSection (&handle_section);
331 if ((type == HANDLE_WEAK) || (type == HANDLE_WEAK_TRACK))
332 return REVEAL_POINTER (obj);
340 ves_icall_System_GCHandle_GetTargetHandle (MonoObject *obj, guint32 handle, gint32 type)
347 EnterCriticalSection (&handle_section);
348 /* Indexes start from 1 since 0 means the handle is not allocated */
350 if (idx >= array_size) {
352 guint8 *new_type_array;
356 new_array = GC_MALLOC (sizeof (gpointer) * (array_size * 2));
357 new_type_array = GC_MALLOC (sizeof (guint8) * (array_size * 2));
359 new_array = g_malloc0 (sizeof (gpointer) * (array_size * 2));
360 new_type_array = g_malloc0 (sizeof (guint8) * (array_size * 2));
364 memcpy (new_array, gc_handles, sizeof (gpointer) * array_size);
365 memcpy (new_type_array, gc_handle_types, sizeof (guint8) * array_size);
366 /* need to re-register links for weak refs. test if GC_realloc needs the same */
367 for (i = 0; i < array_size; ++i) {
368 #if 0 /* This breaks the threaded finalizer, by causing segfaults deep
369 * inside libgc. I assume it will also break without the
370 * threaded finalizer, just that the stress test (bug 31333)
371 * deadlocks too early without it. Reverting to the previous
372 * version here stops the segfault.
374 if ((gc_handle_types[i] == HANDLE_WEAK) || (gc_handle_types[i] == HANDLE_WEAK_TRACK)) { /* all and only disguised pointers have it set */
376 if (((gulong)new_array [i]) & 0x1) {
379 if (gc_handles [i] != (gpointer)-1)
380 GC_unregister_disappearing_link (&(gc_handles [i]));
381 if (new_array [i] != (gpointer)-1)
382 GC_GENERAL_REGISTER_DISAPPEARING_LINK (&(new_array [i]), REVEAL_POINTER (new_array [i]));
388 #ifndef HAVE_BOEHM_GC
390 g_free (gc_handle_types);
392 gc_handles = new_array;
393 gc_handle_types = new_type_array;
396 /* resuse the type from the old target */
399 h = (idx << 2) | type;
402 case HANDLE_WEAK_TRACK:
403 val = (gpointer)HIDE_POINTER (val);
404 gc_handles [idx] = val;
405 gc_handle_types [idx] = type;
407 if (gc_handles [idx] != (gpointer)-1)
408 GC_GENERAL_REGISTER_DISAPPEARING_LINK (&(gc_handles [idx]), obj);
412 gc_handles [idx] = val;
413 gc_handle_types [idx] = type;
416 LeaveCriticalSection (&handle_section);
421 ves_icall_System_GCHandle_FreeHandle (guint32 handle)
423 int idx = handle >> 2;
424 int type = handle & 0x3;
428 EnterCriticalSection (&handle_section);
431 g_assert (type == gc_handle_types [idx]);
432 if ((type == HANDLE_WEAK) || (type == HANDLE_WEAK_TRACK)) {
433 if (gc_handles [idx] != (gpointer)-1)
434 GC_unregister_disappearing_link (&(gc_handles [idx]));
438 gc_handles [idx] = (gpointer)-1;
439 gc_handle_types [idx] = (guint8)-1;
440 LeaveCriticalSection (&handle_section);
444 ves_icall_System_GCHandle_GetAddrOfPinnedObject (guint32 handle)
447 int type = handle & 0x3;
452 EnterCriticalSection (&handle_section);
453 obj = gc_handles [handle >> 2];
454 g_assert (gc_handle_types [handle >> 2] == type);
455 LeaveCriticalSection (&handle_section);
456 if ((type == HANDLE_WEAK) || (type == HANDLE_WEAK_TRACK)) {
457 obj = REVEAL_POINTER (obj);
458 if (obj == (MonoObject *) -1)
462 MonoClass *klass = mono_object_class (obj);
463 if (klass == mono_defaults.string_class) {
464 return mono_string_chars ((MonoString*)obj);
465 } else if (klass->rank) {
466 return mono_array_addr ((MonoArray*)obj, char, 0);
468 /* the C# code will check and throw the exception */
469 /* FIXME: missing !klass->blittable test, see bug #61134,
470 * disabled in 1.0 untill the blittable-using code is audited.
471 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
472 return (gpointer)-1; */
473 return (char*)obj + sizeof (MonoObject);
481 mono_gchandle_new (MonoObject *obj, gboolean pinned)
483 return ves_icall_System_GCHandle_GetTargetHandle (obj, 0, pinned? HANDLE_PINNED: HANDLE_NORMAL);
487 mono_gchandle_new_weakref (MonoObject *obj, gboolean track_resurrection)
489 return ves_icall_System_GCHandle_GetTargetHandle (obj, 0, track_resurrection? HANDLE_WEAK_TRACK: HANDLE_WEAK);
492 /* This will return NULL for a collected object if using a weakref handle */
494 mono_gchandle_get_target (guint32 gchandle)
496 return ves_icall_System_GCHandle_GetTarget (gchandle);
500 mono_gchandle_free (guint32 gchandle)
502 ves_icall_System_GCHandle_FreeHandle (gchandle);
507 static HANDLE finalizer_event;
508 static volatile gboolean finished=FALSE;
510 static void finalize_notify (void)
513 g_message (G_GNUC_PRETTY_FUNCTION ": prodding finalizer");
516 SetEvent (finalizer_event);
520 collect_objects (gpointer key, gpointer value, gpointer user_data)
522 GPtrArray *arr = (GPtrArray*)user_data;
523 g_ptr_array_add (arr, key);
527 * finalize_domain_objects:
529 * Run the finalizers of all finalizable objects in req->domain.
532 finalize_domain_objects (DomainFinalizationReq *req)
536 MonoDomain *domain = req->domain;
538 while (g_hash_table_size (domain->finalizable_objects_hash) > 0) {
540 * Since the domain is unloading, nobody is allowed to put
541 * new entries into the hash table. But finalize_object might
542 * remove entries from the hash table, so we make a copy.
544 objs = g_ptr_array_new ();
545 g_hash_table_foreach (domain->finalizable_objects_hash,
546 collect_objects, objs);
547 /* printf ("FINALIZING %d OBJECTS.\n", objs->len); */
549 for (i = 0; i < objs->len; ++i) {
550 MonoObject *o = (MonoObject*)g_ptr_array_index (objs, i);
551 /* FIXME: Avoid finalizing threads, etc */
555 g_ptr_array_free (objs, TRUE);
558 /* Process finalizers which are already in the queue */
559 GC_invoke_finalizers ();
561 /* printf ("DONE.\n"); */
562 SetEvent (req->done_event);
564 /* The event is closed in mono_domain_finalize if we get here */
568 static guint32 finalizer_thread (gpointer unused)
570 gc_thread = mono_thread_current ();
572 SetEvent (thread_started_event);
575 /* Wait to be notified that there's at least one
578 WaitForSingleObjectEx (finalizer_event, INFINITE, TRUE);
580 if (domains_to_finalize) {
581 EnterCriticalSection (&finalizer_mutex);
582 if (domains_to_finalize) {
583 DomainFinalizationReq *req = domains_to_finalize->data;
584 domains_to_finalize = g_slist_remove (domains_to_finalize, req);
585 LeaveCriticalSection (&finalizer_mutex);
587 finalize_domain_objects (req);
590 LeaveCriticalSection (&finalizer_mutex);
594 g_message (G_GNUC_PRETTY_FUNCTION ": invoking finalizers");
597 /* If finished == TRUE, mono_gc_cleanup has been called (from mono_runtime_cleanup),
598 * before the domain is unloaded.
600 * There is a bug in GC_invoke_finalizer () in versions <= 6.2alpha4:
601 * the 'mem_freed' variable is not initialized when there are no
602 * objects to finalize, which leads to strange behavior later on.
603 * The check is necessary to work around that bug.
605 if (GC_should_invoke_finalizers ()) {
606 GC_invoke_finalizers ();
609 SetEvent (pending_done_event);
612 SetEvent (shutdown_event);
617 * Enable or disable the separate finalizer thread.
618 * It's currently disabled because it still requires some
619 * work in the rest of the runtime.
621 #define ENABLE_FINALIZER_THREAD
623 #ifdef WITH_INCLUDED_LIBGC
625 extern void mono_gc_stop_world (void);
626 extern void mono_gc_start_world (void);
627 extern void mono_gc_push_all_stacks (void);
629 static void mono_gc_lock (void)
631 EnterCriticalSection (&allocator_section);
634 static void mono_gc_unlock (void)
636 LeaveCriticalSection (&allocator_section);
639 static GCThreadFunctions mono_gc_thread_vtable = {
647 mono_gc_push_all_stacks,
650 #endif /* WITH_INCLUDED_LIBGC */
653 mono_gc_warning (char *msg, GC_word arg)
655 mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_GC, msg, (unsigned long)arg);
658 void mono_gc_init (void)
660 InitializeCriticalSection (&handle_section);
661 InitializeCriticalSection (&allocator_section);
663 InitializeCriticalSection (&finalizer_mutex);
665 #ifdef WITH_INCLUDED_LIBGC
666 gc_thread_vtable = &mono_gc_thread_vtable;
669 GC_set_warn_proc (mono_gc_warning);
671 #ifdef ENABLE_FINALIZER_THREAD
673 if (g_getenv ("GC_DONT_GC")) {
678 finalizer_event = CreateEvent (NULL, FALSE, FALSE, NULL);
679 pending_done_event = CreateEvent (NULL, TRUE, FALSE, NULL);
680 shutdown_event = CreateEvent (NULL, TRUE, FALSE, NULL);
681 thread_started_event = CreateEvent (NULL, TRUE, FALSE, NULL);
682 if (finalizer_event == NULL || pending_done_event == NULL || shutdown_event == NULL || thread_started_event == NULL) {
683 g_assert_not_reached ();
686 GC_finalize_on_demand = 1;
687 GC_finalizer_notifier = finalize_notify;
689 mono_thread_create (mono_domain_get (), finalizer_thread, NULL);
691 * Wait until the finalizer thread sets gc_thread since its value is needed
692 * by mono_thread_attach ()
694 WaitForSingleObjectEx (thread_started_event, INFINITE, FALSE);
698 void mono_gc_cleanup (void)
701 g_message (G_GNUC_PRETTY_FUNCTION ": cleaning up finalizer");
704 #ifdef ENABLE_FINALIZER_THREAD
706 ResetEvent (shutdown_event);
709 /* Finishing the finalizer thread, so wait a little bit... */
710 /* MS seems to wait for about 2 seconds */
711 if (WaitForSingleObjectEx (shutdown_event, 2000, FALSE) == WAIT_TIMEOUT) {
712 mono_thread_stop (gc_thread);
720 mono_gc_disable (void)
722 #ifdef HAVE_GC_ENABLE
725 g_assert_not_reached ();
730 mono_gc_enable (void)
732 #ifdef HAVE_GC_ENABLE
735 g_assert_not_reached ();
741 /* no Boehm GC support. */
742 void mono_gc_init (void)
744 InitializeCriticalSection (&handle_section);
747 void mono_gc_cleanup (void)
752 mono_gc_disable (void)
757 mono_gc_enable (void)
764 mono_gc_is_finalizer_thread (MonoThread *thread)
766 return thread == gc_thread;