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 #define GC_I_HIDE_POINTERS
20 #include <mono/os/gc_wrapper.h>
23 #define HIDE_POINTER(v) (v)
24 #define REVEAL_POINTER(v) (v)
27 typedef struct DomainFinalizationReq {
30 } DomainFinalizationReq;
32 #ifdef PLATFORM_WINCE /* FIXME: add accessors to gc.dll API */
33 extern void (*__imp_GC_finalizer_notifier)(void);
34 #define GC_finalizer_notifier __imp_GC_finalizer_notifier
35 extern int __imp_GC_finalize_on_demand;
36 #define GC_finalize_on_demand __imp_GC_finalize_on_demand
39 static int finalize_slot = -1;
41 static gboolean gc_disabled = FALSE;
43 static CRITICAL_SECTION finalizer_mutex;
45 static GSList *domains_to_finalize= NULL;
47 static MonoThread *gc_thread;
49 static void object_register_finalizer (MonoObject *obj, void (*callback)(void *, void*));
52 static void finalize_notify (void);
53 static HANDLE pending_done_event;
54 static HANDLE shutdown_event;
55 static HANDLE thread_started_event;
59 * actually, we might want to queue the finalize requests in a separate thread,
60 * but we need to be careful about the execution domain of the thread...
63 run_finalize (void *obj, void *data)
65 MonoObject *exc = NULL;
67 o = (MonoObject*)((char*)obj + GPOINTER_TO_UINT (data));
69 if (finalize_slot < 0) {
71 MonoClass* obj_class = mono_get_object_class ();
72 for (i = 0; i < obj_class->vtable_size; ++i) {
73 MonoMethod *cm = obj_class->vtable [i];
75 if (!strcmp (mono_method_get_name (cm), "Finalize")) {
82 mono_domain_lock (o->vtable->domain);
84 o2 = g_hash_table_lookup (o->vtable->domain->finalizable_objects_hash, o);
86 mono_domain_unlock (o->vtable->domain);
89 /* Already finalized somehow */
92 /* make sure the finalizer is not called again if the object is resurrected */
93 object_register_finalizer (obj, NULL);
95 if (o->vtable->klass == mono_get_thread_class ())
96 if (mono_gc_is_finalizer_thread ((MonoThread*)o))
97 /* Avoid finalizing ourselves */
100 /* speedup later... and use a timeout */
101 /* g_print ("Finalize run on %p %s.%s\n", o, mono_object_class (o)->name_space, mono_object_class (o)->name); */
103 /* Use _internal here, since this thread can enter a doomed appdomain */
104 mono_domain_set_internal (mono_object_domain (o));
106 mono_runtime_invoke (o->vtable->klass->vtable [finalize_slot], o, NULL, &exc);
109 /* fixme: do something useful */
114 * Some of our objects may point to a different address than the address returned by GC_malloc()
115 * (because of the GetHashCode hack), but we need to pass the real address to register_finalizer.
116 * This also means that in the callback we need to adjust the pointer to get back the real
118 * We also need to be consistent in the use of the GC_debug* variants of malloc and register_finalizer,
119 * since that, too, can cause the underlying pointer to be offset.
122 object_register_finalizer (MonoObject *obj, void (*callback)(void *, void*))
128 /* This assertion is not valid when GC_DEBUG is defined */
129 g_assert (GC_base (obj) == (char*)obj - offset);
132 if (mono_domain_is_unloading (obj->vtable->domain) && (callback != NULL))
134 * Can't register finalizers in a dying appdomain, since they
135 * could be invoked after the appdomain has been unloaded.
139 mono_domain_lock (obj->vtable->domain);
142 g_hash_table_insert (obj->vtable->domain->finalizable_objects_hash, obj,
145 g_hash_table_remove (obj->vtable->domain->finalizable_objects_hash, obj);
147 mono_domain_unlock (obj->vtable->domain);
149 GC_REGISTER_FINALIZER_NO_ORDER ((char*)obj - offset, callback, GUINT_TO_POINTER (offset), NULL, NULL);
154 mono_object_register_finalizer (MonoObject *obj)
156 /* g_print ("Registered finalizer on %p %s.%s\n", obj, mono_object_class (obj)->name_space, mono_object_class (obj)->name); */
157 object_register_finalizer (obj, run_finalize);
161 * mono_domain_finalize:
163 * Request finalization of all finalizable objects inside @domain. Wait
164 * @timeout msecs for the finalization to complete.
165 * Returns: TRUE if succeeded, FALSE if there was a timeout
169 mono_domain_finalize (MonoDomain *domain, guint32 timeout)
171 DomainFinalizationReq *req;
176 * No need to create another thread 'cause the finalizer thread
177 * is still working and will take care of running the finalizers
186 done_event = CreateEvent (NULL, TRUE, FALSE, NULL);
188 req = g_new0 (DomainFinalizationReq, 1);
189 req->domain = domain;
190 req->done_event = done_event;
192 EnterCriticalSection (&finalizer_mutex);
194 domains_to_finalize = g_slist_append (domains_to_finalize, req);
196 LeaveCriticalSection (&finalizer_mutex);
198 /* Tell the finalizer thread to finalize this appdomain */
201 res = WaitForSingleObjectEx (done_event, timeout, TRUE);
203 /* printf ("WAIT RES: %d.\n", res); */
204 if (res == WAIT_TIMEOUT) {
205 /* We leak the handle here */
209 CloseHandle (done_event);
212 /* We don't support domain finalization without a GC */
218 ves_icall_System_GC_InternalCollect (int generation)
228 ves_icall_System_GC_GetTotalMemory (MonoBoolean forceCollection)
235 return GC_get_heap_size () - GC_get_free_bytes ();
242 ves_icall_System_GC_KeepAlive (MonoObject *obj)
252 ves_icall_System_GC_ReRegisterForFinalize (MonoObject *obj)
256 object_register_finalizer (obj, run_finalize);
260 ves_icall_System_GC_SuppressFinalize (MonoObject *obj)
264 object_register_finalizer (obj, NULL);
268 ves_icall_System_GC_WaitForPendingFinalizers (void)
273 if (!GC_should_invoke_finalizers ())
276 if (mono_thread_current () == gc_thread)
277 /* Avoid deadlocks */
280 ResetEvent (pending_done_event);
282 /* g_print ("Waiting for pending finalizers....\n"); */
283 WaitForSingleObjectEx (pending_done_event, INFINITE, TRUE);
284 /* g_print ("Done pending....\n"); */
289 static CRITICAL_SECTION allocator_section;
290 static CRITICAL_SECTION handle_section;
291 static guint32 next_handle = 0;
292 static gpointer *gc_handles = NULL;
293 static guint8 *gc_handle_types = NULL;
294 static guint32 array_size = 0;
297 * The handle type is encoded in the lower two bits of the handle value:
311 * FIXME: make thread safe and reuse the array entries.
314 ves_icall_System_GCHandle_GetTarget (guint32 handle)
323 EnterCriticalSection (&handle_section);
324 g_assert (type == gc_handle_types [handle >> 2]);
325 obj = gc_handles [handle >> 2];
326 LeaveCriticalSection (&handle_section);
330 if ((type == HANDLE_WEAK) || (type == HANDLE_WEAK_TRACK))
331 return REVEAL_POINTER (obj);
339 ves_icall_System_GCHandle_GetTargetHandle (MonoObject *obj, guint32 handle, gint32 type)
346 EnterCriticalSection (&handle_section);
347 /* Indexes start from 1 since 0 means the handle is not allocated */
349 if (idx >= array_size) {
351 guint8 *new_type_array;
355 new_array = GC_MALLOC (sizeof (gpointer) * (array_size * 2));
356 new_type_array = GC_MALLOC (sizeof (guint8) * (array_size * 2));
358 new_array = g_malloc0 (sizeof (gpointer) * (array_size * 2));
359 new_type_array = g_malloc0 (sizeof (guint8) * (array_size * 2));
363 memcpy (new_array, gc_handles, sizeof (gpointer) * array_size);
364 memcpy (new_type_array, gc_handle_types, sizeof (guint8) * array_size);
365 /* need to re-register links for weak refs. test if GC_realloc needs the same */
366 for (i = 0; i < array_size; ++i) {
367 #if 0 /* This breaks the threaded finalizer, by causing segfaults deep
368 * inside libgc. I assume it will also break without the
369 * threaded finalizer, just that the stress test (bug 31333)
370 * deadlocks too early without it. Reverting to the previous
371 * version here stops the segfault.
373 if ((gc_handle_types[i] == HANDLE_WEAK) || (gc_handle_types[i] == HANDLE_WEAK_TRACK)) { /* all and only disguised pointers have it set */
375 if (((gulong)new_array [i]) & 0x1) {
378 if (gc_handles [i] != (gpointer)-1)
379 GC_unregister_disappearing_link (&(gc_handles [i]));
380 if (new_array [i] != (gpointer)-1)
381 GC_GENERAL_REGISTER_DISAPPEARING_LINK (&(new_array [i]), REVEAL_POINTER (new_array [i]));
387 #ifndef HAVE_BOEHM_GC
389 g_free (gc_handle_types);
391 gc_handles = new_array;
392 gc_handle_types = new_type_array;
395 /* resuse the type from the old target */
398 h = (idx << 2) | type;
401 case HANDLE_WEAK_TRACK:
402 val = (gpointer)HIDE_POINTER (val);
403 gc_handles [idx] = val;
404 gc_handle_types [idx] = type;
406 if (gc_handles [idx] != (gpointer)-1)
407 GC_GENERAL_REGISTER_DISAPPEARING_LINK (&(gc_handles [idx]), obj);
411 gc_handles [idx] = val;
412 gc_handle_types [idx] = type;
415 LeaveCriticalSection (&handle_section);
420 ves_icall_System_GCHandle_FreeHandle (guint32 handle)
422 int idx = handle >> 2;
423 int type = handle & 0x3;
427 EnterCriticalSection (&handle_section);
430 g_assert (type == gc_handle_types [idx]);
431 if ((type == HANDLE_WEAK) || (type == HANDLE_WEAK_TRACK)) {
432 if (gc_handles [idx] != (gpointer)-1)
433 GC_unregister_disappearing_link (&(gc_handles [idx]));
437 gc_handles [idx] = (gpointer)-1;
438 gc_handle_types [idx] = (guint8)-1;
439 LeaveCriticalSection (&handle_section);
443 ves_icall_System_GCHandle_GetAddrOfPinnedObject (guint32 handle)
446 int type = handle & 0x3;
451 EnterCriticalSection (&handle_section);
452 obj = gc_handles [handle >> 2];
453 g_assert (gc_handle_types [handle >> 2] == type);
454 LeaveCriticalSection (&handle_section);
455 if ((type == HANDLE_WEAK) || (type == HANDLE_WEAK_TRACK)) {
456 obj = REVEAL_POINTER (obj);
457 if (obj == (MonoObject *) -1)
461 MonoClass *klass = mono_object_class (obj);
462 if (klass == mono_defaults.string_class) {
463 return mono_string_chars ((MonoString*)obj);
464 } else if (klass->rank) {
465 return mono_array_addr ((MonoArray*)obj, char, 0);
467 /* the C# code will check and throw the exception */
468 /* FIXME: missing !klass->blittable test, see bug #61134 */
469 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
471 return (char*)obj + sizeof (MonoObject);
479 mono_gchandle_new (MonoObject *obj, gboolean pinned)
481 return ves_icall_System_GCHandle_GetTargetHandle (obj, 0, pinned? HANDLE_PINNED: HANDLE_NORMAL);
485 mono_gchandle_new_weakref (MonoObject *obj, gboolean track_resurrection)
487 return ves_icall_System_GCHandle_GetTargetHandle (obj, 0, track_resurrection? HANDLE_WEAK_TRACK: HANDLE_WEAK);
490 /* This will return NULL for a collected object if using a weakref handle */
492 mono_gchandle_get_target (guint32 gchandle)
494 return ves_icall_System_GCHandle_GetTarget (gchandle);
498 mono_gchandle_free (guint32 gchandle)
500 ves_icall_System_GCHandle_FreeHandle (gchandle);
505 static HANDLE finalizer_event;
506 static volatile gboolean finished=FALSE;
508 static void finalize_notify (void)
511 g_message (G_GNUC_PRETTY_FUNCTION ": prodding finalizer");
514 SetEvent (finalizer_event);
518 collect_objects (gpointer key, gpointer value, gpointer user_data)
520 GPtrArray *arr = (GPtrArray*)user_data;
521 g_ptr_array_add (arr, key);
525 * finalize_domain_objects:
527 * Run the finalizers of all finalizable objects in req->domain.
530 finalize_domain_objects (DomainFinalizationReq *req)
534 MonoDomain *domain = req->domain;
536 while (g_hash_table_size (domain->finalizable_objects_hash) > 0) {
538 * Since the domain is unloading, nobody is allowed to put
539 * new entries into the hash table. But finalize_object might
540 * remove entries from the hash table, so we make a copy.
542 objs = g_ptr_array_new ();
543 g_hash_table_foreach (domain->finalizable_objects_hash,
544 collect_objects, objs);
545 /* printf ("FINALIZING %d OBJECTS.\n", objs->len); */
547 for (i = 0; i < objs->len; ++i) {
548 MonoObject *o = (MonoObject*)g_ptr_array_index (objs, i);
549 /* FIXME: Avoid finalizing threads, etc */
553 g_ptr_array_free (objs, TRUE);
556 /* printf ("DONE.\n"); */
557 SetEvent (req->done_event);
559 /* The event is closed in mono_domain_finalize if we get here */
563 static guint32 finalizer_thread (gpointer unused)
565 gc_thread = mono_thread_current ();
567 SetEvent (thread_started_event);
570 /* Wait to be notified that there's at least one
573 WaitForSingleObjectEx (finalizer_event, INFINITE, TRUE);
575 if (domains_to_finalize) {
576 EnterCriticalSection (&finalizer_mutex);
577 if (domains_to_finalize) {
578 DomainFinalizationReq *req = domains_to_finalize->data;
579 domains_to_finalize = g_slist_remove (domains_to_finalize, req);
580 LeaveCriticalSection (&finalizer_mutex);
582 finalize_domain_objects (req);
585 LeaveCriticalSection (&finalizer_mutex);
589 g_message (G_GNUC_PRETTY_FUNCTION ": invoking finalizers");
592 /* If finished == TRUE, mono_gc_cleanup has been called (from mono_runtime_cleanup),
593 * before the domain is unloaded.
595 * There is a bug in GC_invoke_finalizer () in versions <= 6.2alpha4:
596 * the 'mem_freed' variable is not initialized when there are no
597 * objects to finalize, which leads to strange behavior later on.
598 * The check is necessary to work around that bug.
600 if (GC_should_invoke_finalizers ()) {
601 GC_invoke_finalizers ();
604 SetEvent (pending_done_event);
607 SetEvent (shutdown_event);
612 * Enable or disable the separate finalizer thread.
613 * It's currently disabled because it still requires some
614 * work in the rest of the runtime.
616 #define ENABLE_FINALIZER_THREAD
618 #ifdef WITH_INCLUDED_LIBGC
620 extern void mono_gc_stop_world (void);
621 extern void mono_gc_start_world (void);
622 extern void mono_gc_push_all_stacks (void);
624 static void mono_gc_lock (void)
626 EnterCriticalSection (&allocator_section);
629 static void mono_gc_unlock (void)
631 LeaveCriticalSection (&allocator_section);
634 static GCThreadFunctions mono_gc_thread_vtable = {
642 mono_gc_push_all_stacks,
645 #endif /* WITH_INCLUDED_LIBGC */
647 void mono_gc_init (void)
649 InitializeCriticalSection (&handle_section);
650 InitializeCriticalSection (&allocator_section);
652 InitializeCriticalSection (&finalizer_mutex);
654 #ifdef WITH_INCLUDED_LIBGC
655 gc_thread_vtable = &mono_gc_thread_vtable;
658 MONO_GC_REGISTER_ROOT (gc_handles);
659 MONO_GC_REGISTER_ROOT (gc_handle_types);
662 #ifdef ENABLE_FINALIZER_THREAD
664 if (g_getenv ("GC_DONT_GC")) {
669 finalizer_event = CreateEvent (NULL, FALSE, FALSE, NULL);
670 pending_done_event = CreateEvent (NULL, TRUE, FALSE, NULL);
671 shutdown_event = CreateEvent (NULL, TRUE, FALSE, NULL);
672 thread_started_event = CreateEvent (NULL, TRUE, FALSE, NULL);
673 if (finalizer_event == NULL || pending_done_event == NULL || shutdown_event == NULL || thread_started_event == NULL) {
674 g_assert_not_reached ();
677 GC_finalize_on_demand = 1;
678 GC_finalizer_notifier = finalize_notify;
680 mono_thread_create (mono_domain_get (), finalizer_thread, NULL);
682 * Wait until the finalizer thread sets gc_thread since its value is needed
683 * by mono_thread_attach ()
685 WaitForSingleObjectEx (thread_started_event, INFINITE, FALSE);
689 void mono_gc_cleanup (void)
692 g_message (G_GNUC_PRETTY_FUNCTION ": cleaning up finalizer");
695 #ifdef ENABLE_FINALIZER_THREAD
697 ResetEvent (shutdown_event);
700 /* Finishing the finalizer thread, so wait a little bit... */
701 /* MS seems to wait for about 2 seconds */
702 if (WaitForSingleObjectEx (shutdown_event, 2000, FALSE) == WAIT_TIMEOUT) {
703 mono_thread_stop (gc_thread);
711 mono_gc_disable (void)
713 #ifdef HAVE_GC_ENABLE
716 g_assert_not_reached ();
721 mono_gc_enable (void)
723 #ifdef HAVE_GC_ENABLE
726 g_assert_not_reached ();
732 /* no Boehm GC support. */
733 void mono_gc_init (void)
735 InitializeCriticalSection (&handle_section);
738 void mono_gc_cleanup (void)
743 mono_gc_disable (void)
748 mono_gc_enable (void)
755 mono_gc_is_finalizer_thread (MonoThread *thread)
757 return thread == gc_thread;