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 #ifdef PLATFORM_WINCE /* FIXME: add accessors to gc.dll API */
26 extern void (*__imp_GC_finalizer_notifier)(void);
27 #define GC_finalizer_notifier __imp_GC_finalizer_notifier
28 extern int __imp_GC_finalize_on_demand;
29 #define GC_finalize_on_demand __imp_GC_finalize_on_demand
32 static int finalize_slot = -1;
34 static gboolean gc_disabled = FALSE;
36 static void object_register_finalizer (MonoObject *obj, void (*callback)(void *, void*));
39 static void finalize_notify (void);
40 static HANDLE pending_done_event;
44 * actually, we might want to queue the finalize requests in a separate thread,
45 * but we need to be careful about the execution domain of the thread...
48 run_finalize (void *obj, void *data)
50 MonoObject *exc = NULL;
52 o = (MonoObject*)((char*)obj + GPOINTER_TO_UINT (data));
54 if (finalize_slot < 0) {
56 for (i = 0; i < mono_defaults.object_class->vtable_size; ++i) {
57 MonoMethod *cm = mono_defaults.object_class->vtable [i];
59 if (!strcmp (cm->name, "Finalize")) {
66 /* make sure the finalizer is not called again if the object is resurrected */
67 object_register_finalizer (obj, NULL);
68 /* speedup later... and use a timeout */
69 /*g_print ("Finalize run on %p %s.%s\n", o, mono_object_class (o)->name_space, mono_object_class (o)->name);*/
70 mono_domain_set (mono_object_domain (o));
72 mono_runtime_invoke (o->vtable->klass->vtable [finalize_slot], o, NULL, &exc);
75 /* fixme: do something useful */
80 * Some of our objects may point to a different address than the address returned by GC_malloc()
81 * (because of the GetHashCode hack), but we need to pass the real address to register_finalizer.
82 * This also means that in the callback we need to adjust the pointer to get back the real
84 * We also need to be consistent in the use of the GC_debug* variants of malloc and register_finalizer,
85 * since that, too, can cause the underlying pointer to be offset.
88 object_register_finalizer (MonoObject *obj, void (*callback)(void *, void*))
94 /* This assertion is not valid when GC_DEBUG is defined */
95 g_assert (GC_base (obj) == (char*)obj - offset);
97 GC_REGISTER_FINALIZER_NO_ORDER ((char*)obj - offset, callback, GUINT_TO_POINTER (offset), NULL, NULL);
102 mono_object_register_finalizer (MonoObject *obj)
104 /*g_print ("Registered finalizer on %p %s.%s\n", obj, mono_object_class (obj)->name_space, mono_object_class (obj)->name);*/
105 object_register_finalizer (obj, run_finalize);
109 * to speedup, at class init time, check if a class or struct
110 * have fields that need to be finalized and set a flag.
113 finalize_fields (MonoClass *class, char *data, gboolean instance, GHashTable *todo) {
115 MonoClassField *field;
119 g_print ("Finalize statics on on %s\n", class->name);*/
120 if (instance && class->valuetype)
121 data -= sizeof (MonoObject);
123 for (i = 0; i < class->field.count; ++i) {
124 field = &class->fields [i];
126 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
129 if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC))
132 switch (field->type->type) {
133 case MONO_TYPE_OBJECT:
134 case MONO_TYPE_CLASS:
135 obj = *((MonoObject**)(data + field->offset));
137 if (mono_object_class (obj)->has_finalize) {
138 /* disable the registered finalizer */
139 object_register_finalizer (obj, NULL);
140 run_finalize (obj, NULL);
143 * if the type doesn't have a finalizer, we finalize
144 * the fields ourselves just like we do for structs.
145 * Disabled for now: how do we handle loops?
147 /*finalize_fields (mono_object_class (obj), obj, TRUE, todo);*/
151 case MONO_TYPE_VALUETYPE: {
152 MonoClass *fclass = mono_class_from_mono_type (field->type);
153 if (fclass->enumtype)
155 /*finalize_fields (fclass, data + field->offset, TRUE, todo);*/
158 case MONO_TYPE_ARRAY:
159 case MONO_TYPE_SZARRAY:
160 /* FIXME: foreach item... */
166 class = class->parent;
171 finalize_static_data (MonoClass *class, MonoVTable *vtable, GHashTable *todo) {
173 if (class->enumtype || !vtable->data)
175 finalize_fields (class, vtable->data, FALSE, todo);
179 mono_domain_finalize (MonoDomain *domain)
181 GHashTable *todo = g_hash_table_new (NULL, NULL);
184 * No need to create another thread 'cause the finalizer thread
185 * is still working and will take care of running the finalizers
191 mono_g_hash_table_foreach (domain->class_vtable_hash, (GHFunc)finalize_static_data, todo);
192 /* FIXME: finalize objects in todo... */
193 g_hash_table_destroy (todo);
199 ves_icall_System_GC_InternalCollect (int generation)
209 ves_icall_System_GC_GetTotalMemory (MonoBoolean forceCollection)
216 return GC_get_heap_size ();
223 ves_icall_System_GC_KeepAlive (MonoObject *obj)
233 ves_icall_System_GC_ReRegisterForFinalize (MonoObject *obj)
237 object_register_finalizer (obj, run_finalize);
241 ves_icall_System_GC_SuppressFinalize (MonoObject *obj)
245 object_register_finalizer (obj, NULL);
249 ves_icall_System_GC_WaitForPendingFinalizers (void)
254 if (!GC_should_invoke_finalizers ())
257 ResetEvent (pending_done_event);
259 /* g_print ("Waiting for pending finalizers....\n"); */
260 WaitForSingleObject (pending_done_event, INFINITE);
261 /* g_print ("Done pending....\n"); */
266 static CRITICAL_SECTION allocator_section;
267 static CRITICAL_SECTION handle_section;
268 static guint32 next_handle = 0;
269 static gpointer *gc_handles = NULL;
270 static guint8 *gc_handle_types = NULL;
271 static guint32 array_size = 0;
274 * The handle type is encoded in the lower two bits of the handle value:
288 * FIXME: make thread safe and reuse the array entries.
291 ves_icall_System_GCHandle_GetTarget (guint32 handle)
300 EnterCriticalSection (&handle_section);
301 g_assert (type == gc_handle_types [handle >> 2]);
302 obj = gc_handles [handle >> 2];
303 LeaveCriticalSection (&handle_section);
307 if ((type == HANDLE_WEAK) || (type == HANDLE_WEAK_TRACK))
308 return REVEAL_POINTER (obj);
316 ves_icall_System_GCHandle_GetTargetHandle (MonoObject *obj, guint32 handle, gint32 type)
323 EnterCriticalSection (&handle_section);
324 /* Indexes start from 1 since 0 means the handle is not allocated */
326 if (idx >= array_size) {
329 guint8 *new_type_array;
332 new_array = GC_MALLOC (sizeof (gpointer) * (array_size * 2));
333 new_type_array = GC_MALLOC (sizeof (guint8) * (array_size * 2));
336 memcpy (new_array, gc_handles, sizeof (gpointer) * array_size);
337 memcpy (new_type_array, gc_handle_types, sizeof (guint8) * array_size);
338 /* need to re-register links for weak refs. test if GC_realloc needs the same */
339 for (i = 0; i < array_size; ++i) {
340 #if 0 /* This breaks the threaded finalizer, by causing segfaults deep
341 * inside libgc. I assume it will also break without the
342 * threaded finalizer, just that the stress test (bug 31333)
343 * deadlocks too early without it. Reverting to the previous
344 * version here stops the segfault.
346 if ((gc_handle_types[i] == HANDLE_WEAK) || (gc_handle_types[i] == HANDLE_WEAK_TRACK)) { /* all and only disguised pointers have it set */
348 if (((gulong)new_array [i]) & 0x1) {
350 if (gc_handles [i] != (gpointer)-1)
351 GC_unregister_disappearing_link (&(gc_handles [i]));
352 if (new_array [i] != (gpointer)-1)
353 GC_GENERAL_REGISTER_DISAPPEARING_LINK (&(new_array [i]), REVEAL_POINTER (new_array [i]));
358 gc_handles = new_array;
359 gc_handle_types = new_type_array;
361 mono_raise_exception (mono_get_exception_execution_engine ("No GCHandle support built-in"));
365 /* resuse the type from the old target */
368 h = (idx << 2) | type;
371 case HANDLE_WEAK_TRACK:
372 val = (gpointer)HIDE_POINTER (val);
373 gc_handles [idx] = val;
374 gc_handle_types [idx] = type;
376 if (gc_handles [idx] != (gpointer)-1)
377 GC_GENERAL_REGISTER_DISAPPEARING_LINK (&(gc_handles [idx]), obj);
379 mono_raise_exception (mono_get_exception_execution_engine ("No weakref support"));
383 gc_handles [idx] = val;
384 gc_handle_types [idx] = type;
387 LeaveCriticalSection (&handle_section);
392 ves_icall_System_GCHandle_FreeHandle (guint32 handle)
394 int idx = handle >> 2;
395 int type = handle & 0x3;
399 EnterCriticalSection (&handle_section);
402 g_assert (type == gc_handle_types [idx]);
403 if ((type == HANDLE_WEAK) || (type == HANDLE_WEAK_TRACK)) {
404 if (gc_handles [idx] != (gpointer)-1)
405 GC_unregister_disappearing_link (&(gc_handles [idx]));
408 mono_raise_exception (mono_get_exception_execution_engine ("No GCHandle support"));
411 gc_handles [idx] = (gpointer)-1;
412 gc_handle_types [idx] = (guint8)-1;
413 LeaveCriticalSection (&handle_section);
417 ves_icall_System_GCHandle_GetAddrOfPinnedObject (guint32 handle)
420 int type = handle & 0x3;
425 EnterCriticalSection (&handle_section);
426 obj = gc_handles [handle >> 2];
427 g_assert (gc_handle_types [handle >> 2] == type);
428 LeaveCriticalSection (&handle_section);
429 if ((type == HANDLE_WEAK) || (type == HANDLE_WEAK_TRACK)) {
430 obj = REVEAL_POINTER (obj);
431 if (obj == (MonoObject *) -1)
441 static HANDLE finalizer_event;
442 static volatile gboolean finished=FALSE;
444 static void finalize_notify (void)
446 gboolean pending = GC_should_invoke_finalizers ();
448 g_message (G_GNUC_PRETTY_FUNCTION ": prodding finalizer");
451 SetEvent (finalizer_event);
452 if (finished && pending) {
453 /* Finishing the finalizer thread, so wait a little bit... */
454 /* MS seems to wait for about 2 seconds */
455 ResetEvent (pending_done_event);
456 WaitForSingleObject (pending_done_event, 2000);
460 static guint32 finalizer_thread (gpointer unused)
464 mono_thread_new_init (GetCurrentThreadId (), &stack_start, NULL);
467 /* Wait to be notified that there's at least one
470 WaitForSingleObject (finalizer_event, INFINITE);
473 g_message (G_GNUC_PRETTY_FUNCTION ": invoking finalizers");
476 /* Can't run finalizers if we're finishing up, because the
477 * domain has already been destroyed
479 * There is a bug in GC_invoke_finalizer () in versions <= 6.2alpha4:
480 * the 'mem_freed' variable is not initialized when there are no
481 * objects to finalize, which leads to strange behavior later on.
482 * The check is necessary to work around that bug.
484 if(!finished && GC_should_invoke_finalizers ()) {
485 GC_invoke_finalizers ();
487 SetEvent (pending_done_event);
494 * Enable or disable the separate finalizer thread.
495 * It's currently disabled because it still requires some
496 * work in the rest of the runtime.
498 #define ENABLE_FINALIZER_THREAD
500 #ifdef WITH_INCLUDED_LIBGC
502 extern void mono_gc_stop_world (void);
503 extern void mono_gc_start_world (void);
504 extern void mono_gc_push_all_stacks (void);
506 static void mono_gc_lock (void)
508 EnterCriticalSection (&allocator_section);
511 static void mono_gc_unlock (void)
513 LeaveCriticalSection (&allocator_section);
516 static GCThreadFunctions mono_gc_thread_vtable = {
524 mono_gc_push_all_stacks,
527 #endif /* WITH_INCLUDED_LIBGC */
529 void mono_gc_init (void)
533 InitializeCriticalSection (&handle_section);
534 InitializeCriticalSection (&allocator_section);
536 #ifdef WITH_INCLUDED_LIBGC
537 gc_thread_vtable = &mono_gc_thread_vtable;
540 #ifdef ENABLE_FINALIZER_THREAD
542 if (getenv ("GC_DONT_GC")) {
547 finalizer_event = CreateEvent (NULL, FALSE, FALSE, NULL);
548 pending_done_event = CreateEvent (NULL, TRUE, FALSE, NULL);
549 if (finalizer_event == NULL || pending_done_event == NULL) {
550 g_assert_not_reached ();
553 GC_finalize_on_demand = 1;
554 GC_finalizer_notifier = finalize_notify;
556 /* Don't use mono_thread_create here, because we don't want
557 * the runtime to wait for this thread to exit when it's
560 gc_thread = CreateThread (NULL, 0, finalizer_thread, NULL, 0, NULL);
561 if (gc_thread == NULL) {
562 g_assert_not_reached ();
567 void mono_gc_cleanup (void)
570 g_message (G_GNUC_PRETTY_FUNCTION ": cleaning up finalizer");
573 #ifdef ENABLE_FINALIZER_THREAD
582 /* no Boehm GC support. */
583 void mono_gc_init (void)
585 InitializeCriticalSection (&handle_section);
588 void mono_gc_cleanup (void)