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 static int finalize_slot = -1;
27 static void object_register_finalizer (MonoObject *obj, void (*callback)(void *, void*));
30 static void finalize_notify (void);
31 static HANDLE pending_done_event;
35 * actually, we might want to queue the finalize requests in a separate thread,
36 * but we need to be careful about the execution domain of the thread...
39 run_finalize (void *obj, void *data)
41 MonoObject *exc = NULL;
43 o = (MonoObject*)((char*)obj + GPOINTER_TO_UINT (data));
45 if (finalize_slot < 0) {
47 for (i = 0; i < mono_defaults.object_class->vtable_size; ++i) {
48 MonoMethod *cm = mono_defaults.object_class->vtable [i];
50 if (!strcmp (cm->name, "Finalize")) {
57 /* make sure the finalizer is not called again if the object is resurrected */
58 object_register_finalizer (obj, NULL);
59 /* speedup later... and use a timeout */
60 /*g_print ("Finalize run on %p %s.%s\n", o, mono_object_class (o)->name_space, mono_object_class (o)->name);*/
61 mono_domain_set (mono_object_domain (o));
63 mono_runtime_invoke (o->vtable->klass->vtable [finalize_slot], o, NULL, &exc);
66 /* fixme: do something useful */
71 * Some of our objects may point to a different address than the address returned by GC_malloc()
72 * (because of the GetHashCode hack), but we need to pass the real address to register_finalizer.
73 * This also means that in the callback we need to adjust the pointer to get back the real
75 * We also need to be consistent in the use of the GC_debug* variants of malloc and register_finalizer,
76 * since that, too, can cause the underlying pointer to be offset.
79 object_register_finalizer (MonoObject *obj, void (*callback)(void *, void*))
84 g_assert (GC_base (obj) == (char*)obj - offset);
85 GC_REGISTER_FINALIZER_NO_ORDER ((char*)obj - offset, callback, GUINT_TO_POINTER (offset), NULL, NULL);
90 mono_object_register_finalizer (MonoObject *obj)
92 /*g_print ("Registered finalizer on %p %s.%s\n", obj, mono_object_class (obj)->name_space, mono_object_class (obj)->name);*/
93 object_register_finalizer (obj, run_finalize);
97 * to speedup, at class init time, check if a class or struct
98 * have fields that need to be finalized and set a flag.
101 finalize_fields (MonoClass *class, char *data, gboolean instance, GHashTable *todo) {
103 MonoClassField *field;
107 g_print ("Finalize statics on on %s\n", class->name);*/
108 if (instance && class->valuetype)
109 data -= sizeof (MonoObject);
111 for (i = 0; i < class->field.count; ++i) {
112 field = &class->fields [i];
114 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
117 if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC))
120 switch (field->type->type) {
121 case MONO_TYPE_OBJECT:
122 case MONO_TYPE_CLASS:
123 obj = *((MonoObject**)(data + field->offset));
125 if (mono_object_class (obj)->has_finalize) {
126 /* disable the registered finalizer */
127 object_register_finalizer (obj, NULL);
128 run_finalize (obj, NULL);
131 * if the type doesn't have a finalizer, we finalize
132 * the fields ourselves just like we do for structs.
133 * Disabled for now: how do we handle loops?
135 /*finalize_fields (mono_object_class (obj), obj, TRUE, todo);*/
139 case MONO_TYPE_VALUETYPE: {
140 MonoClass *fclass = mono_class_from_mono_type (field->type);
141 if (fclass->enumtype)
143 /*finalize_fields (fclass, data + field->offset, TRUE, todo);*/
146 case MONO_TYPE_ARRAY:
147 case MONO_TYPE_SZARRAY:
148 /* FIXME: foreach item... */
154 class = class->parent;
159 finalize_static_data (MonoClass *class, MonoVTable *vtable, GHashTable *todo) {
161 if (class->enumtype || !vtable->data)
163 finalize_fields (class, vtable->data, FALSE, todo);
167 mono_domain_finalize (MonoDomain *domain)
169 GHashTable *todo = g_hash_table_new (NULL, NULL);
172 * No need to create another thread 'cause the finalizer thread
173 * is still working and will take care of running the finalizers
175 mono_thread_new_init (GetCurrentThreadId (), todo, NULL);
180 mono_g_hash_table_foreach (domain->class_vtable_hash, (GHFunc)finalize_static_data, todo);
181 /* FIXME: finalize objects in todo... */
182 g_hash_table_destroy (todo);
188 ves_icall_System_GC_InternalCollect (int generation)
198 ves_icall_System_GC_GetTotalMemory (MonoBoolean forceCollection)
205 return GC_get_heap_size ();
212 ves_icall_System_GC_KeepAlive (MonoObject *obj)
222 ves_icall_System_GC_ReRegisterForFinalize (MonoObject *obj)
226 object_register_finalizer (obj, run_finalize);
230 ves_icall_System_GC_SuppressFinalize (MonoObject *obj)
234 object_register_finalizer (obj, NULL);
238 ves_icall_System_GC_WaitForPendingFinalizers (void)
243 if (!GC_should_invoke_finalizers ())
246 ResetEvent (pending_done_event);
248 /* g_print ("Waiting for pending finalizers....\n"); */
249 WaitForSingleObject (pending_done_event, INFINITE);
250 /* g_print ("Done pending....\n"); */
255 static CRITICAL_SECTION allocator_section;
256 static CRITICAL_SECTION handle_section;
257 static guint32 next_handle = 0;
258 static gpointer *gc_handles = NULL;
259 static guint8 *gc_handle_types = NULL;
260 static guint32 array_size = 0;
263 * The handle type is encoded in the lower two bits of the handle value:
277 * FIXME: make thread safe and reuse the array entries.
280 ves_icall_System_GCHandle_GetTarget (guint32 handle)
289 EnterCriticalSection (&handle_section);
290 g_assert (type == gc_handle_types [handle >> 2]);
291 obj = gc_handles [handle >> 2];
292 LeaveCriticalSection (&handle_section);
296 if ((type == HANDLE_WEAK) || (type == HANDLE_WEAK_TRACK))
297 return REVEAL_POINTER (obj);
305 ves_icall_System_GCHandle_GetTargetHandle (MonoObject *obj, guint32 handle, gint32 type)
312 EnterCriticalSection (&handle_section);
314 if (idx >= array_size) {
317 guint8 *new_type_array;
320 new_array = GC_MALLOC (sizeof (gpointer) * (array_size * 2));
321 new_type_array = GC_MALLOC (sizeof (guint8) * (array_size * 2));
324 memcpy (new_array, gc_handles, sizeof (gpointer) * array_size);
325 memcpy (new_type_array, gc_handle_types, sizeof (guint8) * array_size);
326 /* need to re-register links for weak refs. test if GC_realloc needs the same */
327 for (i = 0; i < array_size; ++i) {
328 #if 0 /* This breaks the threaded finalizer, by causing segfaults deep
329 * inside libgc. I assume it will also break without the
330 * threaded finalizer, just that the stress test (bug 31333)
331 * deadlocks too early without it. Reverting to the previous
332 * version here stops the segfault.
334 if ((gc_handle_types[i] == HANDLE_WEAK) || (gc_handle_types[i] == HANDLE_WEAK_TRACK)) { /* all and only disguised pointers have it set */
336 if (((gulong)new_array [i]) & 0x1) {
338 if (gc_handles [i] != (gpointer)-1)
339 GC_unregister_disappearing_link (&(gc_handles [i]));
340 if (new_array [i] != (gpointer)-1)
341 GC_GENERAL_REGISTER_DISAPPEARING_LINK (&(new_array [i]), REVEAL_POINTER (new_array [i]));
346 gc_handles = new_array;
347 gc_handle_types = new_type_array;
349 mono_raise_exception (mono_get_exception_execution_engine ("No GCHandle support built-in"));
353 /* resuse the type from the old target */
356 h = (idx << 2) | type;
359 case HANDLE_WEAK_TRACK:
360 val = (gpointer)HIDE_POINTER (val);
361 gc_handles [idx] = val;
362 gc_handle_types [idx] = type;
364 if (gc_handles [idx] != (gpointer)-1)
365 GC_GENERAL_REGISTER_DISAPPEARING_LINK (&(gc_handles [idx]), obj);
367 mono_raise_exception (mono_get_exception_execution_engine ("No weakref support"));
371 gc_handles [idx] = val;
372 gc_handle_types [idx] = type;
375 LeaveCriticalSection (&handle_section);
380 ves_icall_System_GCHandle_FreeHandle (guint32 handle)
382 int idx = handle >> 2;
383 int type = handle & 0x3;
387 EnterCriticalSection (&handle_section);
390 g_assert (type == gc_handle_types [idx]);
391 if ((type == HANDLE_WEAK) || (type == HANDLE_WEAK_TRACK)) {
392 if (gc_handles [idx] != (gpointer)-1)
393 GC_unregister_disappearing_link (&(gc_handles [idx]));
396 mono_raise_exception (mono_get_exception_execution_engine ("No GCHandle support"));
399 gc_handles [idx] = (gpointer)-1;
400 gc_handle_types [idx] = (guint8)-1;
401 LeaveCriticalSection (&handle_section);
405 ves_icall_System_GCHandle_GetAddrOfPinnedObject (guint32 handle)
408 int type = handle & 0x3;
413 EnterCriticalSection (&handle_section);
414 obj = gc_handles [handle >> 2];
415 g_assert (gc_handle_types [handle >> 2] == type);
416 LeaveCriticalSection (&handle_section);
417 if ((type == HANDLE_WEAK) || (type == HANDLE_WEAK_TRACK)) {
418 obj = REVEAL_POINTER (obj);
419 if (obj == (MonoObject *) -1)
429 static HANDLE finalizer_event;
430 static volatile gboolean finished=FALSE;
432 static void finalize_notify (void)
434 gboolean pending = GC_should_invoke_finalizers ();
436 g_message (G_GNUC_PRETTY_FUNCTION ": prodding finalizer");
439 SetEvent (finalizer_event);
440 if (finished && pending) {
441 /* Finishing the finalizer thread, so wait a little bit... */
442 /* MS seems to wait for about 2 seconds */
443 ResetEvent (pending_done_event);
444 WaitForSingleObject (pending_done_event, 2000);
448 static guint32 finalizer_thread (gpointer unused)
452 mono_thread_new_init (GetCurrentThreadId (), &stack_start, NULL);
455 /* Wait to be notified that there's at least one
458 WaitForSingleObject (finalizer_event, INFINITE);
461 g_message (G_GNUC_PRETTY_FUNCTION ": invoking finalizers");
464 GC_invoke_finalizers ();
465 SetEvent (pending_done_event);
472 * Enable or disable the separate finalizer thread.
473 * It's currently disabled because it still requires some
474 * work in the rest of the runtime.
476 #define ENABLE_FINALIZER_THREAD
478 #ifdef WITH_INCLUDED_LIBGC
480 extern void mono_gc_stop_world (void);
481 extern void mono_gc_start_world (void);
482 extern void mono_gc_push_all_stacks (void);
484 static void mono_gc_lock (void)
486 EnterCriticalSection (&allocator_section);
489 static void mono_gc_unlock (void)
491 LeaveCriticalSection (&allocator_section);
494 static GCThreadFunctions mono_gc_thread_vtable = {
502 mono_gc_push_all_stacks,
505 #endif /* WITH_INCLUDED_LIBGC */
507 void mono_gc_init (void)
511 InitializeCriticalSection (&handle_section);
512 InitializeCriticalSection (&allocator_section);
514 #ifdef WITH_INCLUDED_LIBGC
515 gc_thread_vtable = &mono_gc_thread_vtable;
518 #ifdef ENABLE_FINALIZER_THREAD
520 if (getenv ("GC_DONT_GC"))
523 finalizer_event = CreateEvent (NULL, FALSE, FALSE, NULL);
524 pending_done_event = CreateEvent (NULL, TRUE, FALSE, NULL);
525 if (finalizer_event == NULL || pending_done_event == NULL) {
526 g_assert_not_reached ();
529 GC_finalize_on_demand = 1;
530 GC_finalizer_notifier = finalize_notify;
532 /* Don't use mono_thread_create here, because we don't want
533 * the runtime to wait for this thread to exit when it's
536 gc_thread = CreateThread (NULL, 0, finalizer_thread, NULL, 0, NULL);
537 if (gc_thread == NULL) {
538 g_assert_not_reached ();
543 void mono_gc_cleanup (void)
546 g_message (G_GNUC_PRETTY_FUNCTION ": cleaning up finalizer");
549 #ifdef ENABLE_FINALIZER_THREAD
557 /* no Boehm GC support. */
558 void mono_gc_init (void)
560 InitializeCriticalSection (&handle_section);
563 void mono_gc_cleanup (void)