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 #define GC_I_HIDE_POINTERS
18 #include <mono/os/gc_wrapper.h>
21 #define HIDE_POINTER(v) (v)
22 #define REVEAL_POINTER(v) (v)
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 int finalize_slot = -1;
39 static gboolean gc_disabled = FALSE;
41 static CRITICAL_SECTION finalizer_mutex;
43 static GSList *domains_to_finalize= NULL;
45 static MonoThread *gc_thread;
47 static void object_register_finalizer (MonoObject *obj, void (*callback)(void *, void*));
50 static void finalize_notify (void);
51 static HANDLE pending_done_event;
52 static HANDLE shutdown_event;
53 static HANDLE thread_started_event;
57 * actually, we might want to queue the finalize requests in a separate thread,
58 * but we need to be careful about the execution domain of the thread...
61 run_finalize (void *obj, void *data)
63 MonoObject *exc = NULL;
65 o = (MonoObject*)((char*)obj + GPOINTER_TO_UINT (data));
67 if (finalize_slot < 0) {
69 for (i = 0; i < mono_defaults.object_class->vtable_size; ++i) {
70 MonoMethod *cm = mono_defaults.object_class->vtable [i];
72 if (!strcmp (cm->name, "Finalize")) {
79 mono_domain_lock (o->vtable->domain);
81 o2 = g_hash_table_lookup (o->vtable->domain->finalizable_objects_hash, o);
83 mono_domain_unlock (o->vtable->domain);
86 /* Already finalized somehow */
89 /* make sure the finalizer is not called again if the object is resurrected */
90 object_register_finalizer (obj, NULL);
91 /* speedup later... and use a timeout */
92 /* g_print ("Finalize run on %p %s.%s\n", o, mono_object_class (o)->name_space, mono_object_class (o)->name); */
94 /* Use _internal here, since this thread can enter a doomed appdomain */
95 mono_domain_set_internal (mono_object_domain (o));
97 mono_runtime_invoke (o->vtable->klass->vtable [finalize_slot], o, NULL, &exc);
100 /* fixme: do something useful */
105 * Some of our objects may point to a different address than the address returned by GC_malloc()
106 * (because of the GetHashCode hack), but we need to pass the real address to register_finalizer.
107 * This also means that in the callback we need to adjust the pointer to get back the real
109 * We also need to be consistent in the use of the GC_debug* variants of malloc and register_finalizer,
110 * since that, too, can cause the underlying pointer to be offset.
113 object_register_finalizer (MonoObject *obj, void (*callback)(void *, void*))
119 /* This assertion is not valid when GC_DEBUG is defined */
120 g_assert (GC_base (obj) == (char*)obj - offset);
123 if (mono_domain_is_unloading (obj->vtable->domain) && (callback != NULL))
125 * Can't register finalizers in a dying appdomain, since they
126 * could be invoked after the appdomain has been unloaded.
130 mono_domain_lock (obj->vtable->domain);
133 g_hash_table_insert (obj->vtable->domain->finalizable_objects_hash, obj,
136 g_hash_table_remove (obj->vtable->domain->finalizable_objects_hash, obj);
138 mono_domain_unlock (obj->vtable->domain);
140 GC_REGISTER_FINALIZER_NO_ORDER ((char*)obj - offset, callback, GUINT_TO_POINTER (offset), NULL, NULL);
145 mono_object_register_finalizer (MonoObject *obj)
147 /* g_print ("Registered finalizer on %p %s.%s\n", obj, mono_object_class (obj)->name_space, mono_object_class (obj)->name); */
148 object_register_finalizer (obj, run_finalize);
152 * mono_domain_finalize:
154 * Request finalization of all finalizable objects inside @domain. Wait
155 * @timeout msecs for the finalization to complete.
156 * Returns: TRUE if succeeded, FALSE if there was a timeout
160 mono_domain_finalize (MonoDomain *domain, guint32 timeout)
162 DomainFinalizationReq *req;
167 * No need to create another thread 'cause the finalizer thread
168 * is still working and will take care of running the finalizers
177 done_event = CreateEvent (NULL, TRUE, FALSE, NULL);
179 req = g_new0 (DomainFinalizationReq, 1);
180 req->domain = domain;
181 req->done_event = done_event;
183 EnterCriticalSection (&finalizer_mutex);
185 domains_to_finalize = g_slist_append (domains_to_finalize, req);
187 LeaveCriticalSection (&finalizer_mutex);
189 /* Tell the finalizer thread to finalize this appdomain */
192 res = WaitForSingleObject (done_event, timeout);
194 //printf ("WAIT RES: %d.\n", res);
195 if (res == WAIT_TIMEOUT)
200 /* We don't support domain finalization without a GC */
206 ves_icall_System_GC_InternalCollect (int generation)
216 ves_icall_System_GC_GetTotalMemory (MonoBoolean forceCollection)
223 return GC_get_heap_size () - GC_get_free_bytes ();
230 ves_icall_System_GC_KeepAlive (MonoObject *obj)
240 ves_icall_System_GC_ReRegisterForFinalize (MonoObject *obj)
244 object_register_finalizer (obj, run_finalize);
248 ves_icall_System_GC_SuppressFinalize (MonoObject *obj)
252 object_register_finalizer (obj, NULL);
256 ves_icall_System_GC_WaitForPendingFinalizers (void)
261 if (!GC_should_invoke_finalizers ())
264 if (mono_thread_current () == gc_thread)
265 /* Avoid deadlocks */
268 ResetEvent (pending_done_event);
270 /* g_print ("Waiting for pending finalizers....\n"); */
271 WaitForSingleObject (pending_done_event, INFINITE);
272 /* g_print ("Done pending....\n"); */
277 static CRITICAL_SECTION allocator_section;
278 static CRITICAL_SECTION handle_section;
279 static guint32 next_handle = 0;
280 static gpointer *gc_handles = NULL;
281 static guint8 *gc_handle_types = NULL;
282 static guint32 array_size = 0;
285 * The handle type is encoded in the lower two bits of the handle value:
299 * FIXME: make thread safe and reuse the array entries.
302 ves_icall_System_GCHandle_GetTarget (guint32 handle)
311 EnterCriticalSection (&handle_section);
312 g_assert (type == gc_handle_types [handle >> 2]);
313 obj = gc_handles [handle >> 2];
314 LeaveCriticalSection (&handle_section);
318 if ((type == HANDLE_WEAK) || (type == HANDLE_WEAK_TRACK))
319 return REVEAL_POINTER (obj);
327 ves_icall_System_GCHandle_GetTargetHandle (MonoObject *obj, guint32 handle, gint32 type)
334 EnterCriticalSection (&handle_section);
335 /* Indexes start from 1 since 0 means the handle is not allocated */
337 if (idx >= array_size) {
340 guint8 *new_type_array;
343 new_array = GC_MALLOC (sizeof (gpointer) * (array_size * 2));
344 new_type_array = GC_MALLOC (sizeof (guint8) * (array_size * 2));
347 memcpy (new_array, gc_handles, sizeof (gpointer) * array_size);
348 memcpy (new_type_array, gc_handle_types, sizeof (guint8) * array_size);
349 /* need to re-register links for weak refs. test if GC_realloc needs the same */
350 for (i = 0; i < array_size; ++i) {
351 #if 0 /* This breaks the threaded finalizer, by causing segfaults deep
352 * inside libgc. I assume it will also break without the
353 * threaded finalizer, just that the stress test (bug 31333)
354 * deadlocks too early without it. Reverting to the previous
355 * version here stops the segfault.
357 if ((gc_handle_types[i] == HANDLE_WEAK) || (gc_handle_types[i] == HANDLE_WEAK_TRACK)) { /* all and only disguised pointers have it set */
359 if (((gulong)new_array [i]) & 0x1) {
361 if (gc_handles [i] != (gpointer)-1)
362 GC_unregister_disappearing_link (&(gc_handles [i]));
363 if (new_array [i] != (gpointer)-1)
364 GC_GENERAL_REGISTER_DISAPPEARING_LINK (&(new_array [i]), REVEAL_POINTER (new_array [i]));
369 gc_handles = new_array;
370 gc_handle_types = new_type_array;
372 mono_raise_exception (mono_get_exception_execution_engine ("No GCHandle support built-in"));
376 /* resuse the type from the old target */
379 h = (idx << 2) | type;
382 case HANDLE_WEAK_TRACK:
383 val = (gpointer)HIDE_POINTER (val);
384 gc_handles [idx] = val;
385 gc_handle_types [idx] = type;
387 if (gc_handles [idx] != (gpointer)-1)
388 GC_GENERAL_REGISTER_DISAPPEARING_LINK (&(gc_handles [idx]), obj);
390 mono_raise_exception (mono_get_exception_execution_engine ("No weakref support"));
394 gc_handles [idx] = val;
395 gc_handle_types [idx] = type;
398 LeaveCriticalSection (&handle_section);
403 ves_icall_System_GCHandle_FreeHandle (guint32 handle)
405 int idx = handle >> 2;
406 int type = handle & 0x3;
410 EnterCriticalSection (&handle_section);
413 g_assert (type == gc_handle_types [idx]);
414 if ((type == HANDLE_WEAK) || (type == HANDLE_WEAK_TRACK)) {
415 if (gc_handles [idx] != (gpointer)-1)
416 GC_unregister_disappearing_link (&(gc_handles [idx]));
419 LeaveCriticalSection (&handle_section);
420 mono_raise_exception (mono_get_exception_execution_engine ("No GCHandle support"));
423 gc_handles [idx] = (gpointer)-1;
424 gc_handle_types [idx] = (guint8)-1;
425 LeaveCriticalSection (&handle_section);
429 ves_icall_System_GCHandle_GetAddrOfPinnedObject (guint32 handle)
432 int type = handle & 0x3;
437 EnterCriticalSection (&handle_section);
438 obj = gc_handles [handle >> 2];
439 g_assert (gc_handle_types [handle >> 2] == type);
440 LeaveCriticalSection (&handle_section);
441 if ((type == HANDLE_WEAK) || (type == HANDLE_WEAK_TRACK)) {
442 obj = REVEAL_POINTER (obj);
443 if (obj == (MonoObject *) -1)
453 static HANDLE finalizer_event;
454 static volatile gboolean finished=FALSE;
456 static void finalize_notify (void)
459 g_message (G_GNUC_PRETTY_FUNCTION ": prodding finalizer");
462 SetEvent (finalizer_event);
466 collect_objects (gpointer key, gpointer value, gpointer user_data)
468 GPtrArray *arr = (GPtrArray*)user_data;
469 g_ptr_array_add (arr, key);
473 * finalize_domain_objects:
475 * Run the finalizers of all finalizable objects in req->domain.
478 finalize_domain_objects (DomainFinalizationReq *req)
482 MonoDomain *domain = req->domain;
484 while (g_hash_table_size (domain->finalizable_objects_hash) > 0) {
486 * Since the domain is unloading, nobody is allowed to put
487 * new entries into the hash table. But finalize_object might
488 * remove entries from the hash table, so we make a copy.
490 objs = g_ptr_array_new ();
491 g_hash_table_foreach (domain->finalizable_objects_hash,
492 collect_objects, objs);
493 //printf ("FINALIZING %d OBJECTS.\n", objs->len);
495 for (i = 0; i < objs->len; ++i) {
496 MonoObject *o = (MonoObject*)g_ptr_array_index (objs, i);
497 /* FIXME: Avoid finalizing threads, etc */
501 g_ptr_array_free (objs, TRUE);
504 //printf ("DONE.\n");
505 SetEvent (req->done_event);
507 /* FIXME: How to delete the event ? */
511 static guint32 finalizer_thread (gpointer unused)
515 gc_thread = mono_thread_current ();
517 SetEvent (thread_started_event);
520 /* Wait to be notified that there's at least one
523 WaitForSingleObject (finalizer_event, INFINITE);
525 if (domains_to_finalize) {
526 EnterCriticalSection (&finalizer_mutex);
527 if (domains_to_finalize) {
528 DomainFinalizationReq *req = domains_to_finalize->data;
529 domains_to_finalize = g_slist_remove (domains_to_finalize, req);
530 LeaveCriticalSection (&finalizer_mutex);
532 finalize_domain_objects (req);
535 LeaveCriticalSection (&finalizer_mutex);
539 g_message (G_GNUC_PRETTY_FUNCTION ": invoking finalizers");
542 /* If finished == TRUE, mono_gc_cleanup has been called (from mono_runtime_cleanup),
543 * before the domain is unloaded.
545 * There is a bug in GC_invoke_finalizer () in versions <= 6.2alpha4:
546 * the 'mem_freed' variable is not initialized when there are no
547 * objects to finalize, which leads to strange behavior later on.
548 * The check is necessary to work around that bug.
550 if (GC_should_invoke_finalizers ()) {
551 GC_invoke_finalizers ();
554 SetEvent (pending_done_event);
557 SetEvent (shutdown_event);
563 * Enable or disable the separate finalizer thread.
564 * It's currently disabled because it still requires some
565 * work in the rest of the runtime.
567 #define ENABLE_FINALIZER_THREAD
569 #ifdef WITH_INCLUDED_LIBGC
571 extern void mono_gc_stop_world (void);
572 extern void mono_gc_start_world (void);
573 extern void mono_gc_push_all_stacks (void);
575 static void mono_gc_lock (void)
577 EnterCriticalSection (&allocator_section);
580 static void mono_gc_unlock (void)
582 LeaveCriticalSection (&allocator_section);
585 static GCThreadFunctions mono_gc_thread_vtable = {
593 mono_gc_push_all_stacks,
596 #endif /* WITH_INCLUDED_LIBGC */
598 void mono_gc_init (void)
600 InitializeCriticalSection (&handle_section);
601 InitializeCriticalSection (&allocator_section);
603 InitializeCriticalSection (&finalizer_mutex);
605 #ifdef WITH_INCLUDED_LIBGC
606 gc_thread_vtable = &mono_gc_thread_vtable;
609 #ifdef ENABLE_FINALIZER_THREAD
611 if (getenv ("GC_DONT_GC")) {
616 finalizer_event = CreateEvent (NULL, FALSE, FALSE, NULL);
617 pending_done_event = CreateEvent (NULL, TRUE, FALSE, NULL);
618 shutdown_event = CreateEvent (NULL, TRUE, FALSE, NULL);
619 thread_started_event = CreateEvent (NULL, TRUE, FALSE, NULL);
620 if (finalizer_event == NULL || pending_done_event == NULL || shutdown_event == NULL || thread_started_event == NULL) {
621 g_assert_not_reached ();
624 GC_finalize_on_demand = 1;
625 GC_finalizer_notifier = finalize_notify;
627 mono_thread_create (mono_domain_get (), finalizer_thread, NULL);
629 * Wait until the finalizer thread sets gc_thread since its value is needed
630 * by mono_thread_attach ()
632 WaitForSingleObject (thread_started_event, INFINITE);
636 void mono_gc_cleanup (void)
639 g_message (G_GNUC_PRETTY_FUNCTION ": cleaning up finalizer");
642 #ifdef ENABLE_FINALIZER_THREAD
644 ResetEvent (shutdown_event);
647 /* Finishing the finalizer thread, so wait a little bit... */
648 /* MS seems to wait for about 2 seconds */
650 * FIXME: This is not thread safe. If the finalizer thread keeps
651 * running, and the runtime is shut down, it will lead to a crash.
653 WaitForSingleObject (shutdown_event, 2000);
661 /* no Boehm GC support. */
662 void mono_gc_init (void)
664 InitializeCriticalSection (&handle_section);
667 void mono_gc_cleanup (void)
674 mono_gc_is_finalizer_thread (MonoThread *thread)
676 return thread == gc_thread;