2010-03-30 Rodrigo Kumpera <rkumpera@novell.com>
[mono.git] / mono / metadata / gc.c
blobc2e46175ae469236aad990d2b83820b069a5e9f9
1 /*
2 * metadata/gc.c: GC icalls.
4 * Author: Paolo Molaro <lupus@ximian.com>
6 * Copyright 2002-2003 Ximian, Inc (http://www.ximian.com)
7 * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
8 */
10 #include <config.h>
11 #include <glib.h>
12 #include <string.h>
14 #include <mono/metadata/gc-internal.h>
15 #include <mono/metadata/mono-gc.h>
16 #include <mono/metadata/threads.h>
17 #include <mono/metadata/tabledefs.h>
18 #include <mono/metadata/exception.h>
19 #include <mono/metadata/profiler-private.h>
20 #include <mono/metadata/domain-internals.h>
21 #include <mono/metadata/class-internals.h>
22 #include <mono/metadata/metadata-internals.h>
23 #include <mono/metadata/mono-mlist.h>
24 #include <mono/metadata/threadpool.h>
25 #include <mono/metadata/threads-types.h>
26 #include <mono/utils/mono-logger-internal.h>
27 #include <mono/metadata/gc-internal.h>
28 #include <mono/metadata/marshal.h> /* for mono_delegate_free_ftnptr () */
29 #include <mono/metadata/attach.h>
30 #include <mono/utils/mono-semaphore.h>
32 #ifndef HOST_WIN32
33 #include <pthread.h>
34 #endif
36 typedef struct DomainFinalizationReq {
37 MonoDomain *domain;
38 HANDLE done_event;
39 } DomainFinalizationReq;
41 #ifdef PLATFORM_WINCE /* FIXME: add accessors to gc.dll API */
42 extern void (*__imp_GC_finalizer_notifier)(void);
43 #define GC_finalizer_notifier __imp_GC_finalizer_notifier
44 extern int __imp_GC_finalize_on_demand;
45 #define GC_finalize_on_demand __imp_GC_finalize_on_demand
46 #endif
48 static gboolean gc_disabled = FALSE;
50 static gboolean finalizing_root_domain = FALSE;
52 #define mono_finalizer_lock() EnterCriticalSection (&finalizer_mutex)
53 #define mono_finalizer_unlock() LeaveCriticalSection (&finalizer_mutex)
54 static CRITICAL_SECTION finalizer_mutex;
56 static GSList *domains_to_finalize= NULL;
57 static MonoMList *threads_to_finalize = NULL;
59 static MonoInternalThread *gc_thread;
61 static void object_register_finalizer (MonoObject *obj, void (*callback)(void *, void*));
63 static void mono_gchandle_set_target (guint32 gchandle, MonoObject *obj);
65 #ifndef HAVE_NULL_GC
66 static HANDLE pending_done_event;
67 static HANDLE shutdown_event;
68 #endif
70 static void
71 add_thread_to_finalize (MonoInternalThread *thread)
73 mono_finalizer_lock ();
74 if (!threads_to_finalize)
75 MONO_GC_REGISTER_ROOT (threads_to_finalize);
76 threads_to_finalize = mono_mlist_append (threads_to_finalize, (MonoObject*)thread);
77 mono_finalizer_unlock ();
80 static gboolean suspend_finalizers = FALSE;
81 /*
82 * actually, we might want to queue the finalize requests in a separate thread,
83 * but we need to be careful about the execution domain of the thread...
85 void
86 mono_gc_run_finalize (void *obj, void *data)
88 MonoObject *exc = NULL;
89 MonoObject *o;
90 #ifndef HAVE_SGEN_GC
91 MonoObject *o2;
92 #endif
93 MonoMethod* finalizer = NULL;
94 MonoDomain *caller_domain = mono_domain_get ();
95 MonoDomain *domain;
96 RuntimeInvokeFunction runtime_invoke;
97 GSList *l, *refs = NULL;
99 o = (MonoObject*)((char*)obj + GPOINTER_TO_UINT (data));
101 if (suspend_finalizers)
102 return;
104 domain = o->vtable->domain;
106 #ifndef HAVE_SGEN_GC
107 mono_domain_finalizers_lock (domain);
109 o2 = g_hash_table_lookup (domain->finalizable_objects_hash, o);
111 refs = mono_gc_remove_weak_track_object (domain, o);
113 mono_domain_finalizers_unlock (domain);
115 if (!o2)
116 /* Already finalized somehow */
117 return;
118 #endif
120 if (refs) {
122 * Support for GCHandles of type WeakTrackResurrection:
124 * Its not exactly clear how these are supposed to work, or how their
125 * semantics can be implemented. We only implement one crucial thing:
126 * these handles are only cleared after the finalizer has ran.
128 for (l = refs; l; l = l->next) {
129 guint32 gchandle = GPOINTER_TO_UINT (l->data);
131 mono_gchandle_set_target (gchandle, o);
134 g_slist_free (refs);
137 /* make sure the finalizer is not called again if the object is resurrected */
138 object_register_finalizer (obj, NULL);
140 if (o->vtable->klass == mono_defaults.internal_thread_class) {
141 MonoInternalThread *t = (MonoInternalThread*)o;
143 if (mono_gc_is_finalizer_internal_thread (t))
144 /* Avoid finalizing ourselves */
145 return;
147 if (t->threadpool_thread && finalizing_root_domain) {
148 /* Don't finalize threadpool threads when
149 shutting down - they're finalized when the
150 threadpool shuts down. */
151 add_thread_to_finalize (t);
152 return;
156 if (o->vtable->klass->image == mono_defaults.corlib && !strcmp (o->vtable->klass->name, "DynamicMethod") && finalizing_root_domain) {
158 * These can't be finalized during unloading/shutdown, since that would
159 * free the native code which can still be referenced by other
160 * finalizers.
161 * FIXME: This is not perfect, objects dying at the same time as
162 * dynamic methods can still reference them even when !shutdown.
164 return;
167 if (mono_runtime_get_no_exec ())
168 return;
170 /* speedup later... and use a timeout */
171 /* g_print ("Finalize run on %p %s.%s\n", o, mono_object_class (o)->name_space, mono_object_class (o)->name); */
173 /* Use _internal here, since this thread can enter a doomed appdomain */
174 mono_domain_set_internal (mono_object_domain (o));
176 /* delegates that have a native function pointer allocated are
177 * registered for finalization, but they don't have a Finalize
178 * method, because in most cases it's not needed and it's just a waste.
180 if (o->vtable->klass->delegate) {
181 MonoDelegate* del = (MonoDelegate*)o;
182 if (del->delegate_trampoline)
183 mono_delegate_free_ftnptr ((MonoDelegate*)o);
184 mono_domain_set_internal (caller_domain);
185 return;
188 finalizer = mono_class_get_finalizer (o->vtable->klass);
190 #ifndef DISABLE_COM
191 /* If object has a CCW but has no finalizer, it was only
192 * registered for finalization in order to free the CCW.
193 * Else it needs the regular finalizer run.
194 * FIXME: what to do about ressurection and suppression
195 * of finalizer on object with CCW.
197 if (mono_marshal_free_ccw (o) && !finalizer) {
198 mono_domain_set_internal (caller_domain);
199 return;
201 #endif
204 * To avoid the locking plus the other overhead of mono_runtime_invoke (),
205 * create and precompile a wrapper which calls the finalize method using
206 * a CALLVIRT.
208 if (!domain->finalize_runtime_invoke) {
209 MonoMethod *invoke = mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE);
211 domain->finalize_runtime_invoke = mono_compile_method (invoke);
214 runtime_invoke = domain->finalize_runtime_invoke;
216 mono_runtime_class_init (o->vtable);
218 runtime_invoke (o, NULL, &exc, NULL);
220 if (exc) {
221 /* fixme: do something useful */
224 mono_domain_set_internal (caller_domain);
227 void
228 mono_gc_finalize_threadpool_threads (void)
230 while (threads_to_finalize) {
231 MonoInternalThread *thread = (MonoInternalThread*) mono_mlist_get_data (threads_to_finalize);
233 /* Force finalization of the thread. */
234 thread->threadpool_thread = FALSE;
235 mono_object_register_finalizer ((MonoObject*)thread);
237 mono_gc_run_finalize (thread, NULL);
239 threads_to_finalize = mono_mlist_next (threads_to_finalize);
243 gpointer
244 mono_gc_out_of_memory (size_t size)
247 * we could allocate at program startup some memory that we could release
248 * back to the system at this point if we're really low on memory (ie, size is
249 * lower than the memory we set apart)
251 mono_raise_exception (mono_domain_get ()->out_of_memory_ex);
253 return NULL;
257 * Some of our objects may point to a different address than the address returned by GC_malloc()
258 * (because of the GetHashCode hack), but we need to pass the real address to register_finalizer.
259 * This also means that in the callback we need to adjust the pointer to get back the real
260 * MonoObject*.
261 * We also need to be consistent in the use of the GC_debug* variants of malloc and register_finalizer,
262 * since that, too, can cause the underlying pointer to be offset.
264 static void
265 object_register_finalizer (MonoObject *obj, void (*callback)(void *, void*))
267 #if HAVE_BOEHM_GC
268 guint offset = 0;
269 MonoDomain *domain;
271 if (obj == NULL)
272 mono_raise_exception (mono_get_exception_argument_null ("obj"));
274 domain = obj->vtable->domain;
276 #ifndef GC_DEBUG
277 /* This assertion is not valid when GC_DEBUG is defined */
278 g_assert (GC_base (obj) == (char*)obj - offset);
279 #endif
281 if (mono_domain_is_unloading (domain) && (callback != NULL))
283 * Can't register finalizers in a dying appdomain, since they
284 * could be invoked after the appdomain has been unloaded.
286 return;
288 mono_domain_finalizers_lock (domain);
290 if (callback)
291 g_hash_table_insert (domain->finalizable_objects_hash, obj, obj);
292 else
293 g_hash_table_remove (domain->finalizable_objects_hash, obj);
295 mono_domain_finalizers_unlock (domain);
297 GC_REGISTER_FINALIZER_NO_ORDER ((char*)obj - offset, callback, GUINT_TO_POINTER (offset), NULL, NULL);
298 #elif defined(HAVE_SGEN_GC)
299 if (obj == NULL)
300 mono_raise_exception (mono_get_exception_argument_null ("obj"));
302 mono_gc_register_for_finalization (obj, callback);
303 #endif
307 * mono_object_register_finalizer:
308 * @obj: object to register
310 * Records that object @obj has a finalizer, this will call the
311 * Finalize method when the garbage collector disposes the object.
314 void
315 mono_object_register_finalizer (MonoObject *obj)
317 /* g_print ("Registered finalizer on %p %s.%s\n", obj, mono_object_class (obj)->name_space, mono_object_class (obj)->name); */
318 object_register_finalizer (obj, mono_gc_run_finalize);
322 * mono_domain_finalize:
323 * @domain: the domain to finalize
324 * @timeout: msects to wait for the finalization to complete, -1 to wait indefinitely
326 * Request finalization of all finalizable objects inside @domain. Wait
327 * @timeout msecs for the finalization to complete.
329 * Returns: TRUE if succeeded, FALSE if there was a timeout
332 gboolean
333 mono_domain_finalize (MonoDomain *domain, guint32 timeout)
335 DomainFinalizationReq *req;
336 guint32 res;
337 HANDLE done_event;
339 if (mono_thread_internal_current () == gc_thread)
340 /* We are called from inside a finalizer, not much we can do here */
341 return FALSE;
344 * No need to create another thread 'cause the finalizer thread
345 * is still working and will take care of running the finalizers
348 #ifndef HAVE_NULL_GC
349 if (gc_disabled)
350 return TRUE;
352 mono_gc_collect (mono_gc_max_generation ());
354 done_event = CreateEvent (NULL, TRUE, FALSE, NULL);
355 if (done_event == NULL) {
356 return FALSE;
359 req = g_new0 (DomainFinalizationReq, 1);
360 req->domain = domain;
361 req->done_event = done_event;
363 if (domain == mono_get_root_domain ())
364 finalizing_root_domain = TRUE;
366 mono_finalizer_lock ();
368 domains_to_finalize = g_slist_append (domains_to_finalize, req);
370 mono_finalizer_unlock ();
372 /* Tell the finalizer thread to finalize this appdomain */
373 mono_gc_finalize_notify ();
375 if (timeout == -1)
376 timeout = INFINITE;
378 res = WaitForSingleObjectEx (done_event, timeout, TRUE);
380 /* printf ("WAIT RES: %d.\n", res); */
381 if (res == WAIT_TIMEOUT) {
382 /* We leak the handle here */
383 return FALSE;
386 CloseHandle (done_event);
388 if (domain == mono_get_root_domain ()) {
389 mono_thread_pool_cleanup ();
390 mono_gc_finalize_threadpool_threads ();
393 return TRUE;
394 #else
395 /* We don't support domain finalization without a GC */
396 return FALSE;
397 #endif
400 void
401 ves_icall_System_GC_InternalCollect (int generation)
403 mono_gc_collect (generation);
406 gint64
407 ves_icall_System_GC_GetTotalMemory (MonoBoolean forceCollection)
409 MONO_ARCH_SAVE_REGS;
411 if (forceCollection)
412 mono_gc_collect (mono_gc_max_generation ());
413 return mono_gc_get_used_size ();
416 void
417 ves_icall_System_GC_KeepAlive (MonoObject *obj)
419 MONO_ARCH_SAVE_REGS;
422 * Does nothing.
426 void
427 ves_icall_System_GC_ReRegisterForFinalize (MonoObject *obj)
429 if (!obj)
430 mono_raise_exception (mono_get_exception_argument_null ("obj"));
432 object_register_finalizer (obj, mono_gc_run_finalize);
435 void
436 ves_icall_System_GC_SuppressFinalize (MonoObject *obj)
438 if (!obj)
439 mono_raise_exception (mono_get_exception_argument_null ("obj"));
441 /* delegates have no finalizers, but we register them to deal with the
442 * unmanaged->managed trampoline. We don't let the user suppress it
443 * otherwise we'd leak it.
445 if (obj->vtable->klass->delegate)
446 return;
448 /* FIXME: Need to handle case where obj has COM Callable Wrapper
449 * generated for it that needs cleaned up, but user wants to suppress
450 * their derived object finalizer. */
452 object_register_finalizer (obj, NULL);
455 void
456 ves_icall_System_GC_WaitForPendingFinalizers (void)
458 #ifndef HAVE_NULL_GC
459 if (!mono_gc_pending_finalizers ())
460 return;
462 if (mono_thread_internal_current () == gc_thread)
463 /* Avoid deadlocks */
464 return;
466 ResetEvent (pending_done_event);
467 mono_gc_finalize_notify ();
468 /* g_print ("Waiting for pending finalizers....\n"); */
469 WaitForSingleObjectEx (pending_done_event, INFINITE, TRUE);
470 /* g_print ("Done pending....\n"); */
471 #endif
474 #define mono_allocator_lock() EnterCriticalSection (&allocator_section)
475 #define mono_allocator_unlock() LeaveCriticalSection (&allocator_section)
476 static CRITICAL_SECTION allocator_section;
477 static CRITICAL_SECTION handle_section;
479 typedef enum {
480 HANDLE_WEAK,
481 HANDLE_WEAK_TRACK,
482 HANDLE_NORMAL,
483 HANDLE_PINNED
484 } HandleType;
486 static HandleType mono_gchandle_get_type (guint32 gchandle);
488 MonoObject *
489 ves_icall_System_GCHandle_GetTarget (guint32 handle)
491 return mono_gchandle_get_target (handle);
495 * if type == -1, change the target of the handle, otherwise allocate a new handle.
497 guint32
498 ves_icall_System_GCHandle_GetTargetHandle (MonoObject *obj, guint32 handle, gint32 type)
500 if (type == -1) {
501 mono_gchandle_set_target (handle, obj);
502 /* the handle doesn't change */
503 return handle;
505 switch (type) {
506 case HANDLE_WEAK:
507 return mono_gchandle_new_weakref (obj, FALSE);
508 case HANDLE_WEAK_TRACK:
509 return mono_gchandle_new_weakref (obj, TRUE);
510 case HANDLE_NORMAL:
511 return mono_gchandle_new (obj, FALSE);
512 case HANDLE_PINNED:
513 return mono_gchandle_new (obj, TRUE);
514 default:
515 g_assert_not_reached ();
517 return 0;
520 void
521 ves_icall_System_GCHandle_FreeHandle (guint32 handle)
523 mono_gchandle_free (handle);
526 gpointer
527 ves_icall_System_GCHandle_GetAddrOfPinnedObject (guint32 handle)
529 MonoObject *obj;
531 if (mono_gchandle_get_type (handle) != HANDLE_PINNED)
532 return (gpointer)-2;
533 obj = mono_gchandle_get_target (handle);
534 if (obj) {
535 MonoClass *klass = mono_object_class (obj);
536 if (klass == mono_defaults.string_class) {
537 return mono_string_chars ((MonoString*)obj);
538 } else if (klass->rank) {
539 return mono_array_addr ((MonoArray*)obj, char, 0);
540 } else {
541 /* the C# code will check and throw the exception */
542 /* FIXME: missing !klass->blittable test, see bug #61134 */
543 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
544 return (gpointer)-1;
545 return (char*)obj + sizeof (MonoObject);
548 return NULL;
551 typedef struct {
552 guint32 *bitmap;
553 gpointer *entries;
554 guint32 size;
555 guint8 type;
556 guint slot_hint : 24; /* starting slot for search */
557 /* 2^16 appdomains should be enough for everyone (though I know I'll regret this in 20 years) */
558 /* we alloc this only for weak refs, since we can get the domain directly in the other cases */
559 guint16 *domain_ids;
560 } HandleData;
562 /* weak and weak-track arrays will be allocated in malloc memory
564 static HandleData gc_handles [] = {
565 {NULL, NULL, 0, HANDLE_WEAK, 0},
566 {NULL, NULL, 0, HANDLE_WEAK_TRACK, 0},
567 {NULL, NULL, 0, HANDLE_NORMAL, 0},
568 {NULL, NULL, 0, HANDLE_PINNED, 0}
571 #define lock_handles(handles) EnterCriticalSection (&handle_section)
572 #define unlock_handles(handles) LeaveCriticalSection (&handle_section)
574 static int
575 find_first_unset (guint32 bitmap)
577 int i;
578 for (i = 0; i < 32; ++i) {
579 if (!(bitmap & (1 << i)))
580 return i;
582 return -1;
585 static guint32
586 alloc_handle (HandleData *handles, MonoObject *obj, gboolean track)
588 gint slot, i;
589 lock_handles (handles);
590 if (!handles->size) {
591 handles->size = 32;
592 if (handles->type > HANDLE_WEAK_TRACK) {
593 handles->entries = mono_gc_alloc_fixed (sizeof (gpointer) * handles->size, NULL);
594 } else {
595 handles->entries = g_malloc0 (sizeof (gpointer) * handles->size);
596 handles->domain_ids = g_malloc0 (sizeof (guint16) * handles->size);
598 handles->bitmap = g_malloc0 (handles->size / 8);
600 i = -1;
601 for (slot = handles->slot_hint; slot < handles->size / 32; ++slot) {
602 if (handles->bitmap [slot] != 0xffffffff) {
603 i = find_first_unset (handles->bitmap [slot]);
604 handles->slot_hint = slot;
605 break;
608 if (i == -1 && handles->slot_hint != 0) {
609 for (slot = 0; slot < handles->slot_hint; ++slot) {
610 if (handles->bitmap [slot] != 0xffffffff) {
611 i = find_first_unset (handles->bitmap [slot]);
612 handles->slot_hint = slot;
613 break;
617 if (i == -1) {
618 guint32 *new_bitmap;
619 guint32 new_size = handles->size * 2; /* always double: we memset to 0 based on this below */
621 /* resize and copy the bitmap */
622 new_bitmap = g_malloc0 (new_size / 8);
623 memcpy (new_bitmap, handles->bitmap, handles->size / 8);
624 g_free (handles->bitmap);
625 handles->bitmap = new_bitmap;
627 /* resize and copy the entries */
628 if (handles->type > HANDLE_WEAK_TRACK) {
629 gsize *gc_bitmap;
630 gpointer *entries;
631 void *descr;
633 /* Create a GC descriptor */
634 gc_bitmap = g_malloc (new_size / 8);
635 memset (gc_bitmap, 0xff, new_size / 8);
636 descr = mono_gc_make_descr_from_bitmap (gc_bitmap, new_size);
637 g_free (gc_bitmap);
639 entries = mono_gc_alloc_fixed (sizeof (gpointer) * new_size, descr);
640 memcpy (entries, handles->entries, sizeof (gpointer) * handles->size);
642 mono_gc_free_fixed (handles->entries);
643 handles->entries = entries;
644 } else {
645 gpointer *entries;
646 guint16 *domain_ids;
647 domain_ids = g_malloc0 (sizeof (guint16) * new_size);
648 entries = g_malloc (sizeof (gpointer) * new_size);
649 /* we disable GC because we could lose some disappearing link updates */
650 mono_gc_disable ();
651 memcpy (entries, handles->entries, sizeof (gpointer) * handles->size);
652 memset (entries + handles->size, 0, sizeof (gpointer) * handles->size);
653 memcpy (domain_ids, handles->domain_ids, sizeof (guint16) * handles->size);
654 for (i = 0; i < handles->size; ++i) {
655 MonoObject *obj = mono_gc_weak_link_get (&(handles->entries [i]));
656 if (handles->entries [i])
657 mono_gc_weak_link_remove (&(handles->entries [i]));
658 /*g_print ("reg/unreg entry %d of type %d at %p to object %p (%p), was: %p\n", i, handles->type, &(entries [i]), obj, entries [i], handles->entries [i]);*/
659 if (obj) {
660 mono_gc_weak_link_add (&(entries [i]), obj, track);
663 g_free (handles->entries);
664 g_free (handles->domain_ids);
665 handles->entries = entries;
666 handles->domain_ids = domain_ids;
667 mono_gc_enable ();
670 /* set i and slot to the next free position */
671 i = 0;
672 slot = (handles->size + 1) / 32;
673 handles->slot_hint = handles->size + 1;
674 handles->size = new_size;
676 handles->bitmap [slot] |= 1 << i;
677 slot = slot * 32 + i;
678 handles->entries [slot] = obj;
679 if (handles->type <= HANDLE_WEAK_TRACK) {
680 if (obj)
681 mono_gc_weak_link_add (&(handles->entries [slot]), obj, track);
684 mono_perfcounters->gc_num_handles++;
685 unlock_handles (handles);
686 /*g_print ("allocated entry %d of type %d to object %p (in slot: %p)\n", slot, handles->type, obj, handles->entries [slot]);*/
687 return (slot << 3) | (handles->type + 1);
691 * mono_gchandle_new:
692 * @obj: managed object to get a handle for
693 * @pinned: whether the object should be pinned
695 * This returns a handle that wraps the object, this is used to keep a
696 * reference to a managed object from the unmanaged world and preventing the
697 * object from being disposed.
699 * If @pinned is false the address of the object can not be obtained, if it is
700 * true the address of the object can be obtained. This will also pin the
701 * object so it will not be possible by a moving garbage collector to move the
702 * object.
704 * Returns: a handle that can be used to access the object from
705 * unmanaged code.
707 guint32
708 mono_gchandle_new (MonoObject *obj, gboolean pinned)
710 return alloc_handle (&gc_handles [pinned? HANDLE_PINNED: HANDLE_NORMAL], obj, FALSE);
714 * mono_gchandle_new_weakref:
715 * @obj: managed object to get a handle for
716 * @pinned: whether the object should be pinned
718 * This returns a weak handle that wraps the object, this is used to
719 * keep a reference to a managed object from the unmanaged world.
720 * Unlike the mono_gchandle_new the object can be reclaimed by the
721 * garbage collector. In this case the value of the GCHandle will be
722 * set to zero.
724 * If @pinned is false the address of the object can not be obtained, if it is
725 * true the address of the object can be obtained. This will also pin the
726 * object so it will not be possible by a moving garbage collector to move the
727 * object.
729 * Returns: a handle that can be used to access the object from
730 * unmanaged code.
732 guint32
733 mono_gchandle_new_weakref (MonoObject *obj, gboolean track_resurrection)
735 guint32 handle = alloc_handle (&gc_handles [track_resurrection? HANDLE_WEAK_TRACK: HANDLE_WEAK], obj, track_resurrection);
737 #ifndef HAVE_SGEN_GC
738 if (track_resurrection)
739 mono_gc_add_weak_track_handle (obj, handle);
740 #endif
742 return handle;
745 static HandleType
746 mono_gchandle_get_type (guint32 gchandle)
748 guint type = (gchandle & 7) - 1;
750 return type;
754 * mono_gchandle_get_target:
755 * @gchandle: a GCHandle's handle.
757 * The handle was previously created by calling mono_gchandle_new or
758 * mono_gchandle_new_weakref.
760 * Returns a pointer to the MonoObject represented by the handle or
761 * NULL for a collected object if using a weakref handle.
763 MonoObject*
764 mono_gchandle_get_target (guint32 gchandle)
766 guint slot = gchandle >> 3;
767 guint type = (gchandle & 7) - 1;
768 HandleData *handles = &gc_handles [type];
769 MonoObject *obj = NULL;
770 if (type > 3)
771 return NULL;
772 lock_handles (handles);
773 if (slot < handles->size && (handles->bitmap [slot / 32] & (1 << (slot % 32)))) {
774 if (handles->type <= HANDLE_WEAK_TRACK) {
775 obj = mono_gc_weak_link_get (&handles->entries [slot]);
776 } else {
777 obj = handles->entries [slot];
779 } else {
780 /* print a warning? */
782 unlock_handles (handles);
783 /*g_print ("get target of entry %d of type %d: %p\n", slot, handles->type, obj);*/
784 return obj;
787 static void
788 mono_gchandle_set_target (guint32 gchandle, MonoObject *obj)
790 guint slot = gchandle >> 3;
791 guint type = (gchandle & 7) - 1;
792 HandleData *handles = &gc_handles [type];
793 MonoObject *old_obj = NULL;
795 if (type > 3)
796 return;
797 lock_handles (handles);
798 if (slot < handles->size && (handles->bitmap [slot / 32] & (1 << (slot % 32)))) {
799 if (handles->type <= HANDLE_WEAK_TRACK) {
800 old_obj = handles->entries [slot];
801 if (handles->entries [slot])
802 mono_gc_weak_link_remove (&handles->entries [slot]);
803 if (obj)
804 mono_gc_weak_link_add (&handles->entries [slot], obj, handles->type == HANDLE_WEAK_TRACK);
805 } else {
806 handles->entries [slot] = obj;
808 } else {
809 /* print a warning? */
811 /*g_print ("changed entry %d of type %d to object %p (in slot: %p)\n", slot, handles->type, obj, handles->entries [slot]);*/
812 unlock_handles (handles);
814 #ifndef HAVE_SGEN_GC
815 if (type == HANDLE_WEAK_TRACK)
816 mono_gc_change_weak_track_handle (old_obj, obj, gchandle);
817 #endif
821 * mono_gchandle_is_in_domain:
822 * @gchandle: a GCHandle's handle.
823 * @domain: An application domain.
825 * Returns: true if the object wrapped by the @gchandle belongs to the specific @domain.
827 gboolean
828 mono_gchandle_is_in_domain (guint32 gchandle, MonoDomain *domain)
830 guint slot = gchandle >> 3;
831 guint type = (gchandle & 7) - 1;
832 HandleData *handles = &gc_handles [type];
833 gboolean result = FALSE;
834 if (type > 3)
835 return FALSE;
836 lock_handles (handles);
837 if (slot < handles->size && (handles->bitmap [slot / 32] & (1 << (slot % 32)))) {
838 if (handles->type <= HANDLE_WEAK_TRACK) {
839 result = domain->domain_id == handles->domain_ids [slot];
840 } else {
841 MonoObject *obj;
842 obj = handles->entries [slot];
843 if (obj == NULL)
844 result = TRUE;
845 else
846 result = domain == mono_object_domain (obj);
848 } else {
849 /* print a warning? */
851 unlock_handles (handles);
852 return result;
856 * mono_gchandle_free:
857 * @gchandle: a GCHandle's handle.
859 * Frees the @gchandle handle. If there are no outstanding
860 * references, the garbage collector can reclaim the memory of the
861 * object wrapped.
863 void
864 mono_gchandle_free (guint32 gchandle)
866 guint slot = gchandle >> 3;
867 guint type = (gchandle & 7) - 1;
868 HandleData *handles = &gc_handles [type];
869 if (type > 3)
870 return;
871 #ifndef HAVE_SGEN_GC
872 if (type == HANDLE_WEAK_TRACK)
873 mono_gc_remove_weak_track_handle (gchandle);
874 #endif
876 lock_handles (handles);
877 if (slot < handles->size && (handles->bitmap [slot / 32] & (1 << (slot % 32)))) {
878 if (handles->type <= HANDLE_WEAK_TRACK) {
879 if (handles->entries [slot])
880 mono_gc_weak_link_remove (&handles->entries [slot]);
881 } else {
882 handles->entries [slot] = NULL;
884 handles->bitmap [slot / 32] &= ~(1 << (slot % 32));
885 } else {
886 /* print a warning? */
888 mono_perfcounters->gc_num_handles--;
889 /*g_print ("freed entry %d of type %d\n", slot, handles->type);*/
890 unlock_handles (handles);
894 * mono_gchandle_free_domain:
895 * @domain: domain that is unloading
897 * Function used internally to cleanup any GC handle for objects belonging
898 * to the specified domain during appdomain unload.
900 void
901 mono_gchandle_free_domain (MonoDomain *domain)
903 guint type;
905 for (type = 0; type < 3; ++type) {
906 guint slot;
907 HandleData *handles = &gc_handles [type];
908 lock_handles (handles);
909 for (slot = 0; slot < handles->size; ++slot) {
910 if (!(handles->bitmap [slot / 32] & (1 << (slot % 32))))
911 continue;
912 if (type <= HANDLE_WEAK_TRACK) {
913 if (domain->domain_id == handles->domain_ids [slot]) {
914 handles->bitmap [slot / 32] &= ~(1 << (slot % 32));
915 if (handles->entries [slot])
916 mono_gc_weak_link_remove (&handles->entries [slot]);
918 } else {
919 if (handles->entries [slot] && mono_object_domain (handles->entries [slot]) == domain) {
920 handles->bitmap [slot / 32] &= ~(1 << (slot % 32));
921 handles->entries [slot] = NULL;
925 unlock_handles (handles);
930 MonoBoolean
931 GCHandle_CheckCurrentDomain (guint32 gchandle)
933 return mono_gchandle_is_in_domain (gchandle, mono_domain_get ());
936 #ifndef HAVE_NULL_GC
938 #ifdef MONO_HAS_SEMAPHORES
939 static MonoSemType finalizer_sem;
940 #endif
941 static HANDLE finalizer_event;
942 static volatile gboolean finished=FALSE;
944 void
945 mono_gc_finalize_notify (void)
947 #ifdef DEBUG
948 g_message ( "%s: prodding finalizer", __func__);
949 #endif
951 #ifdef MONO_HAS_SEMAPHORES
952 MONO_SEM_POST (&finalizer_sem);
953 #else
954 SetEvent (finalizer_event);
955 #endif
958 #ifdef HAVE_BOEHM_GC
960 static void
961 collect_objects (gpointer key, gpointer value, gpointer user_data)
963 GPtrArray *arr = (GPtrArray*)user_data;
964 g_ptr_array_add (arr, key);
967 #endif
970 * finalize_domain_objects:
972 * Run the finalizers of all finalizable objects in req->domain.
974 static void
975 finalize_domain_objects (DomainFinalizationReq *req)
977 MonoDomain *domain = req->domain;
979 #ifdef HAVE_BOEHM_GC
980 while (g_hash_table_size (domain->finalizable_objects_hash) > 0) {
981 int i;
982 GPtrArray *objs;
984 * Since the domain is unloading, nobody is allowed to put
985 * new entries into the hash table. But finalize_object might
986 * remove entries from the hash table, so we make a copy.
988 objs = g_ptr_array_new ();
989 g_hash_table_foreach (domain->finalizable_objects_hash, collect_objects, objs);
990 /* printf ("FINALIZING %d OBJECTS.\n", objs->len); */
992 for (i = 0; i < objs->len; ++i) {
993 MonoObject *o = (MonoObject*)g_ptr_array_index (objs, i);
994 /* FIXME: Avoid finalizing threads, etc */
995 mono_gc_run_finalize (o, 0);
998 g_ptr_array_free (objs, TRUE);
1000 #elif defined(HAVE_SGEN_GC)
1001 #define NUM_FOBJECTS 64
1002 MonoObject *to_finalize [NUM_FOBJECTS];
1003 int count;
1004 while ((count = mono_gc_finalizers_for_domain (domain, to_finalize, NUM_FOBJECTS))) {
1005 int i;
1006 for (i = 0; i < count; ++i) {
1007 mono_gc_run_finalize (to_finalize [i], 0);
1010 #endif
1012 /* Process finalizers which are already in the queue */
1013 mono_gc_invoke_finalizers ();
1015 /* printf ("DONE.\n"); */
1016 SetEvent (req->done_event);
1018 /* The event is closed in mono_domain_finalize if we get here */
1019 g_free (req);
1022 static guint32
1023 finalizer_thread (gpointer unused)
1025 while (!finished) {
1026 /* Wait to be notified that there's at least one
1027 * finaliser to run
1030 g_assert (mono_domain_get () == mono_get_root_domain ());
1032 #ifdef MONO_HAS_SEMAPHORES
1033 MONO_SEM_WAIT (&finalizer_sem);
1034 #else
1035 /* Use alertable=FALSE since we will be asked to exit using the event too */
1036 WaitForSingleObjectEx (finalizer_event, INFINITE, FALSE);
1037 #endif
1039 #ifndef DISABLE_ATTACH
1040 mono_attach_maybe_start ();
1041 #endif
1043 if (domains_to_finalize) {
1044 mono_finalizer_lock ();
1045 if (domains_to_finalize) {
1046 DomainFinalizationReq *req = domains_to_finalize->data;
1047 domains_to_finalize = g_slist_remove (domains_to_finalize, req);
1048 mono_finalizer_unlock ();
1050 finalize_domain_objects (req);
1051 } else {
1052 mono_finalizer_unlock ();
1056 /* If finished == TRUE, mono_gc_cleanup has been called (from mono_runtime_cleanup),
1057 * before the domain is unloaded.
1059 mono_gc_invoke_finalizers ();
1061 SetEvent (pending_done_event);
1064 SetEvent (shutdown_event);
1065 return 0;
1068 #ifdef HAVE_SGEN_GC
1069 #define GC_dont_gc 0
1070 #endif
1072 void
1073 mono_gc_init (void)
1075 InitializeCriticalSection (&handle_section);
1076 InitializeCriticalSection (&allocator_section);
1078 InitializeCriticalSection (&finalizer_mutex);
1080 MONO_GC_REGISTER_ROOT (gc_handles [HANDLE_NORMAL].entries);
1081 MONO_GC_REGISTER_ROOT (gc_handles [HANDLE_PINNED].entries);
1083 mono_gc_base_init ();
1085 if (GC_dont_gc || g_getenv ("GC_DONT_GC")) {
1086 gc_disabled = TRUE;
1087 return;
1090 finalizer_event = CreateEvent (NULL, FALSE, FALSE, NULL);
1091 pending_done_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1092 shutdown_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1093 if (finalizer_event == NULL || pending_done_event == NULL || shutdown_event == NULL) {
1094 g_assert_not_reached ();
1096 #ifdef MONO_HAS_SEMAPHORES
1097 MONO_SEM_INIT (&finalizer_sem, 0);
1098 #endif
1100 gc_thread = mono_thread_create_internal (mono_domain_get (), finalizer_thread, NULL, FALSE);
1103 void
1104 mono_gc_cleanup (void)
1106 #ifdef DEBUG
1107 g_message ("%s: cleaning up finalizer", __func__);
1108 #endif
1110 if (!gc_disabled) {
1111 ResetEvent (shutdown_event);
1112 finished = TRUE;
1113 if (mono_thread_internal_current () != gc_thread) {
1114 mono_gc_finalize_notify ();
1115 /* Finishing the finalizer thread, so wait a little bit... */
1116 /* MS seems to wait for about 2 seconds */
1117 if (WaitForSingleObjectEx (shutdown_event, 2000, FALSE) == WAIT_TIMEOUT) {
1118 int ret;
1120 /* Set a flag which the finalizer thread can check */
1121 suspend_finalizers = TRUE;
1123 /* Try to abort the thread, in the hope that it is running managed code */
1124 mono_thread_internal_stop (gc_thread);
1126 /* Wait for it to stop */
1127 ret = WaitForSingleObjectEx (gc_thread->handle, 100, TRUE);
1129 if (ret == WAIT_TIMEOUT) {
1131 * The finalizer thread refused to die. There is not much we
1132 * can do here, since the runtime is shutting down so the
1133 * state the finalizer thread depends on will vanish.
1135 g_warning ("Shutting down finalizer thread timed out.");
1136 } else {
1138 * FIXME: On unix, when the above wait returns, the thread
1139 * might still be running io-layer code, or pthreads code.
1141 Sleep (100);
1146 gc_thread = NULL;
1147 #ifdef HAVE_BOEHM_GC
1148 GC_finalizer_notifier = NULL;
1149 #endif
1152 DeleteCriticalSection (&handle_section);
1153 DeleteCriticalSection (&allocator_section);
1154 DeleteCriticalSection (&finalizer_mutex);
1157 #else
1159 /* Null GC dummy functions */
1160 void
1161 mono_gc_finalize_notify (void)
1165 void mono_gc_init (void)
1167 InitializeCriticalSection (&handle_section);
1170 void mono_gc_cleanup (void)
1174 #endif
1176 gboolean
1177 mono_gc_is_finalizer_internal_thread (MonoInternalThread *thread)
1179 return thread == gc_thread;
1183 * mono_gc_is_finalizer_thread:
1184 * @thread: the thread to test.
1186 * In Mono objects are finalized asynchronously on a separate thread.
1187 * This routine tests whether the @thread argument represents the
1188 * finalization thread.
1190 * Returns true if @thread is the finalization thread.
1192 gboolean
1193 mono_gc_is_finalizer_thread (MonoThread *thread)
1195 return mono_gc_is_finalizer_internal_thread (thread->internal_thread);