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 * actually, we might want to queue the finalize requests in a separate thread,
31 * but we need to be careful about the execution domain of the thread...
34 run_finalize (void *obj, void *data)
36 MonoObject *exc = NULL;
38 o = (MonoObject*)((char*)obj + GPOINTER_TO_UINT (data));
40 if (finalize_slot < 0) {
42 for (i = 0; i < mono_defaults.object_class->vtable_size; ++i) {
43 MonoMethod *cm = mono_defaults.object_class->vtable [i];
45 if (!strcmp (cm->name, "Finalize")) {
52 /* make sure the finalizer is not called again if the object is resurrected */
53 object_register_finalizer (obj, NULL);
54 /* speedup later... and use a timeout */
55 /*g_print ("Finalize run on %p %s.%s\n", o, mono_object_class (o)->name_space, mono_object_class (o)->name);*/
56 mono_domain_set (mono_object_domain (o));
58 mono_runtime_invoke (o->vtable->klass->vtable [finalize_slot], o, NULL, &exc);
61 /* fixme: do something useful */
66 * Some of our objects may point to a different address than the address returned by GC_malloc()
67 * (because of the GetHashCode hack), but we need to pass the real address to register_finalizer.
68 * This also means that in the callback we need to adjust the pointer to get back the real
70 * We also need to be consistent in the use of the GC_debug* variants of malloc and register_finalizer,
71 * since that, too, can cause the underlying pointer to be offset.
74 object_register_finalizer (MonoObject *obj, void (*callback)(void *, void*))
79 g_assert (GC_base (obj) == (char*)obj - offset);
80 GC_REGISTER_FINALIZER_NO_ORDER ((char*)obj - offset, callback, GUINT_TO_POINTER (offset), NULL, NULL);
85 mono_object_register_finalizer (MonoObject *obj)
87 /*g_print ("Registered finalizer on %p %s.%s\n", obj, mono_object_class (obj)->name_space, mono_object_class (obj)->name);*/
88 object_register_finalizer (obj, run_finalize);
92 * to speedup, at class init time, check if a class or struct
93 * have fields that need to be finalized and set a flag.
96 finalize_fields (MonoClass *class, char *data, gboolean instance, GHashTable *todo) {
98 MonoClassField *field;
102 g_print ("Finalize statics on on %s\n", class->name);*/
103 if (instance && class->valuetype)
104 data -= sizeof (MonoObject);
106 for (i = 0; i < class->field.count; ++i) {
107 field = &class->fields [i];
109 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
112 if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC))
115 switch (field->type->type) {
116 case MONO_TYPE_OBJECT:
117 case MONO_TYPE_CLASS:
118 obj = *((MonoObject**)(data + field->offset));
120 if (mono_object_class (obj)->has_finalize) {
121 /* disable the registered finalizer */
122 object_register_finalizer (obj, NULL);
123 run_finalize (obj, NULL);
126 * if the type doesn't have a finalizer, we finalize
127 * the fields ourselves just like we do for structs.
128 * Disabled for now: how do we handle loops?
130 /*finalize_fields (mono_object_class (obj), obj, TRUE, todo);*/
134 case MONO_TYPE_VALUETYPE: {
135 MonoClass *fclass = mono_class_from_mono_type (field->type);
136 if (fclass->enumtype)
138 /*finalize_fields (fclass, data + field->offset, TRUE, todo);*/
141 case MONO_TYPE_ARRAY:
142 case MONO_TYPE_SZARRAY:
143 /* FIXME: foreach item... */
149 class = class->parent;
154 finalize_static_data (MonoClass *class, MonoVTable *vtable, GHashTable *todo) {
156 if (class->enumtype || !vtable->data)
158 finalize_fields (class, vtable->data, FALSE, todo);
162 internal_domain_finalize (gpointer data) {
163 MonoDomain *domain=(MonoDomain *)data;
164 GHashTable *todo = g_hash_table_new (NULL, NULL);
166 mono_new_thread_init (GetCurrentThreadId (), todo, NULL);
171 mono_g_hash_table_foreach (domain->class_vtable_hash, (GHFunc)finalize_static_data, todo);
172 /* FIXME: finalize objects in todo... */
173 g_hash_table_destroy (todo);
179 mono_domain_finalize (MonoDomain *domain)
181 HANDLE finalize_thread;
183 /* Need to run managed code in a subthread.
184 * Mono_domain_finalize() is called from the main thread in
185 * the jit and the embedded example, hence the thread creation
188 finalize_thread=CreateThread (NULL, 0, internal_domain_finalize, domain, 0, NULL);
189 if(finalize_thread==NULL) {
190 g_assert_not_reached ();
192 WaitForSingleObject (finalize_thread, INFINITE);
193 CloseHandle (finalize_thread);
197 ves_icall_System_GC_InternalCollect (int generation)
207 ves_icall_System_GC_GetTotalMemory (MonoBoolean forceCollection)
214 return GC_get_heap_size ();
221 ves_icall_System_GC_KeepAlive (MonoObject *obj)
231 ves_icall_System_GC_ReRegisterForFinalize (MonoObject *obj)
235 object_register_finalizer (obj, run_finalize);
239 ves_icall_System_GC_SuppressFinalize (MonoObject *obj)
243 object_register_finalizer (obj, NULL);
247 ves_icall_System_GC_WaitForPendingFinalizers (void)
252 static CRITICAL_SECTION handle_section;
253 static guint32 next_handle = 0;
254 static gpointer *gc_handles = NULL;
255 static guint8 *gc_handle_types = NULL;
256 static guint32 array_size = 0;
259 * The handle type is encoded in the lower two bits of the handle value:
273 * FIXME: make thread safe and reuse the array entries.
276 ves_icall_System_GCHandle_GetTarget (guint32 handle)
285 EnterCriticalSection (&handle_section);
286 g_assert (type == gc_handle_types [handle >> 2]);
287 obj = gc_handles [handle >> 2];
288 LeaveCriticalSection (&handle_section);
292 if ((type == HANDLE_WEAK) || (type == HANDLE_WEAK_TRACK))
293 return REVEAL_POINTER (obj);
301 ves_icall_System_GCHandle_GetTargetHandle (MonoObject *obj, guint32 handle, gint32 type)
308 EnterCriticalSection (&handle_section);
310 if (idx >= array_size) {
313 guint8 *new_type_array;
316 new_array = GC_MALLOC (sizeof (gpointer) * (array_size * 2));
317 new_type_array = GC_MALLOC (sizeof (guint8) * (array_size * 2));
320 memcpy (new_array, gc_handles, sizeof (gpointer) * array_size);
321 memcpy (new_type_array, gc_handle_types, sizeof (guint8) * array_size);
322 /* need to re-register links for weak refs. test if GC_realloc needs the same */
323 for (i = 0; i < array_size; ++i) {
324 #if 0 /* This breaks the threaded finalizer, by causing segfaults deep
325 * inside libgc. I assume it will also break without the
326 * threaded finalizer, just that the stress test (bug 31333)
327 * deadlocks too early without it. Reverting to the previous
328 * version here stops the segfault.
330 if ((gc_handle_types[i] == HANDLE_WEAK) || (gc_handle_types[i] == HANDLE_WEAK_TRACK)) { /* all and only disguised pointers have it set */
332 if (((gulong)new_array [i]) & 0x1) {
334 if (gc_handles [i] != (gpointer)-1)
335 GC_unregister_disappearing_link (&(gc_handles [i]));
336 if (new_array [i] != (gpointer)-1)
337 GC_GENERAL_REGISTER_DISAPPEARING_LINK (&(new_array [i]), REVEAL_POINTER (new_array [i]));
342 gc_handles = new_array;
343 gc_handle_types = new_type_array;
345 mono_raise_exception (mono_get_exception_execution_engine ("No GCHandle support built-in"));
349 /* resuse the type from the old target */
352 h = (idx << 2) | type;
355 case HANDLE_WEAK_TRACK:
356 val = (gpointer)HIDE_POINTER (val);
357 gc_handles [idx] = val;
358 gc_handle_types [idx] = type;
360 if (gc_handles [idx] != (gpointer)-1)
361 GC_GENERAL_REGISTER_DISAPPEARING_LINK (&(gc_handles [idx]), obj);
363 mono_raise_exception (mono_get_exception_execution_engine ("No weakref support"));
367 gc_handles [idx] = val;
368 gc_handle_types [idx] = type;
371 LeaveCriticalSection (&handle_section);
376 ves_icall_System_GCHandle_FreeHandle (guint32 handle)
378 int idx = handle >> 2;
379 int type = handle & 0x3;
383 EnterCriticalSection (&handle_section);
386 g_assert (type == gc_handle_types [idx]);
387 if ((type == HANDLE_WEAK) || (type == HANDLE_WEAK_TRACK)) {
388 if (gc_handles [idx] != (gpointer)-1)
389 GC_unregister_disappearing_link (&(gc_handles [idx]));
392 mono_raise_exception (mono_get_exception_execution_engine ("No GCHandle support"));
395 gc_handles [idx] = (gpointer)-1;
396 gc_handle_types [idx] = (guint8)-1;
397 LeaveCriticalSection (&handle_section);
401 ves_icall_System_GCHandle_GetAddrOfPinnedObject (guint32 handle)
404 int type = handle & 0x3;
409 EnterCriticalSection (&handle_section);
410 obj = gc_handles [handle >> 2];
411 g_assert (gc_handle_types [handle >> 2] == type);
412 LeaveCriticalSection (&handle_section);
413 if ((type == HANDLE_WEAK) || (type == HANDLE_WEAK_TRACK)) {
414 obj = REVEAL_POINTER (obj);
415 if (obj == (MonoObject *) -1)
425 static HANDLE finalizer_event;
426 static volatile gboolean finished=FALSE;
428 static void finalize_notify (void)
431 g_message (G_GNUC_PRETTY_FUNCTION ": prodding finalizer");
434 SetEvent (finalizer_event);
437 static guint32 finalizer_thread (gpointer unused)
441 mono_new_thread_init (GetCurrentThreadId (), &stack_start, NULL);
444 /* Wait to be notified that there's at least one
447 WaitForSingleObject (finalizer_event, INFINITE);
450 g_message (G_GNUC_PRETTY_FUNCTION ": invoking finalizers");
453 GC_invoke_finalizers ();
460 * Enable or disable the separate finalizer thread.
461 * It's currently disabled because it still requires some
462 * work in the rest of the runtime.
464 #define ENABLE_FINALIZER_THREAD
466 void mono_gc_init (void)
470 InitializeCriticalSection (&handle_section);
472 #ifdef ENABLE_FINALIZER_THREAD
474 if (getenv ("GC_DONT_GC"))
477 finalizer_event = CreateEvent (NULL, FALSE, FALSE, NULL);
478 if (finalizer_event == NULL) {
479 g_assert_not_reached ();
482 GC_finalize_on_demand = 1;
483 GC_finalizer_notifier = finalize_notify;
485 /* Don't use mono_thread_create here, because we don't want
486 * the runtime to wait for this thread to exit when it's
489 gc_thread = CreateThread (NULL, 0, finalizer_thread, NULL, 0, NULL);
490 if (gc_thread == NULL) {
491 g_assert_not_reached ();
496 void mono_gc_cleanup (void)
499 g_message (G_GNUC_PRETTY_FUNCTION ": cleaning up finalizer");
502 #ifdef ENABLE_FINALIZER_THREAD
510 /* no Boehm GC support. */
511 void mono_gc_init (void)
513 InitializeCriticalSection (&handle_section);
516 void mono_gc_cleanup (void)