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)
15 #include <mono/metadata/gc-internal.h>
16 #include <mono/metadata/mono-gc.h>
17 #include <mono/metadata/threads.h>
18 #include <mono/metadata/tabledefs.h>
19 #include <mono/metadata/exception.h>
20 #include <mono/metadata/profiler-private.h>
21 #include <mono/metadata/domain-internals.h>
22 #include <mono/metadata/class-internals.h>
23 #include <mono/metadata/metadata-internals.h>
24 #include <mono/metadata/mono-mlist.h>
25 #include <mono/metadata/threadpool.h>
26 #include <mono/metadata/threads-types.h>
27 #include <mono/utils/mono-logger-internal.h>
28 #include <mono/metadata/gc-internal.h>
29 #include <mono/metadata/marshal.h> /* for mono_delegate_free_ftnptr () */
30 #include <mono/metadata/attach.h>
31 #include <mono/metadata/console-io.h>
32 #include <mono/utils/mono-semaphore.h>
33 #include <mono/utils/mono-memory-model.h>
39 typedef struct DomainFinalizationReq {
42 } DomainFinalizationReq;
44 #ifdef PLATFORM_WINCE /* FIXME: add accessors to gc.dll API */
45 extern void (*__imp_GC_finalizer_notifier)(void);
46 #define GC_finalizer_notifier __imp_GC_finalizer_notifier
47 extern int __imp_GC_finalize_on_demand;
48 #define GC_finalize_on_demand __imp_GC_finalize_on_demand
51 static gboolean gc_disabled = FALSE;
53 static gboolean finalizing_root_domain = FALSE;
55 #define mono_finalizer_lock() EnterCriticalSection (&finalizer_mutex)
56 #define mono_finalizer_unlock() LeaveCriticalSection (&finalizer_mutex)
57 static CRITICAL_SECTION finalizer_mutex;
58 static CRITICAL_SECTION reference_queue_mutex;
60 static GSList *domains_to_finalize= NULL;
61 static MonoMList *threads_to_finalize = NULL;
63 static MonoInternalThread *gc_thread;
65 static void object_register_finalizer (MonoObject *obj, void (*callback)(void *, void*));
67 static void mono_gchandle_set_target (guint32 gchandle, MonoObject *obj);
69 static void reference_queue_proccess_all (void);
70 static void mono_reference_queue_cleanup (void);
71 static void reference_queue_clear_for_domain (MonoDomain *domain);
73 static HANDLE pending_done_event;
74 static HANDLE shutdown_event;
78 add_thread_to_finalize (MonoInternalThread *thread)
80 mono_finalizer_lock ();
81 if (!threads_to_finalize)
82 MONO_GC_REGISTER_ROOT_SINGLE (threads_to_finalize);
83 threads_to_finalize = mono_mlist_append (threads_to_finalize, (MonoObject*)thread);
84 mono_finalizer_unlock ();
87 static gboolean suspend_finalizers = FALSE;
89 * actually, we might want to queue the finalize requests in a separate thread,
90 * but we need to be careful about the execution domain of the thread...
93 mono_gc_run_finalize (void *obj, void *data)
95 MonoObject *exc = NULL;
100 MonoMethod* finalizer = NULL;
101 MonoDomain *caller_domain = mono_domain_get ();
103 RuntimeInvokeFunction runtime_invoke;
104 GSList *l, *refs = NULL;
106 o = (MonoObject*)((char*)obj + GPOINTER_TO_UINT (data));
108 if (suspend_finalizers)
111 domain = o->vtable->domain;
114 mono_domain_finalizers_lock (domain);
116 o2 = g_hash_table_lookup (domain->finalizable_objects_hash, o);
118 refs = mono_gc_remove_weak_track_object (domain, o);
120 mono_domain_finalizers_unlock (domain);
123 /* Already finalized somehow */
129 * Support for GCHandles of type WeakTrackResurrection:
131 * Its not exactly clear how these are supposed to work, or how their
132 * semantics can be implemented. We only implement one crucial thing:
133 * these handles are only cleared after the finalizer has ran.
135 for (l = refs; l; l = l->next) {
136 guint32 gchandle = GPOINTER_TO_UINT (l->data);
138 mono_gchandle_set_target (gchandle, o);
144 /* make sure the finalizer is not called again if the object is resurrected */
145 object_register_finalizer (obj, NULL);
147 if (o->vtable->klass == mono_defaults.internal_thread_class) {
148 MonoInternalThread *t = (MonoInternalThread*)o;
150 if (mono_gc_is_finalizer_internal_thread (t))
151 /* Avoid finalizing ourselves */
154 if (t->threadpool_thread && finalizing_root_domain) {
155 /* Don't finalize threadpool threads when
156 shutting down - they're finalized when the
157 threadpool shuts down. */
158 add_thread_to_finalize (t);
163 if (o->vtable->klass->image == mono_defaults.corlib && !strcmp (o->vtable->klass->name, "DynamicMethod") && finalizing_root_domain) {
165 * These can't be finalized during unloading/shutdown, since that would
166 * free the native code which can still be referenced by other
168 * FIXME: This is not perfect, objects dying at the same time as
169 * dynamic methods can still reference them even when !shutdown.
174 if (mono_runtime_get_no_exec ())
177 /* speedup later... and use a timeout */
178 /* g_print ("Finalize run on %p %s.%s\n", o, mono_object_class (o)->name_space, mono_object_class (o)->name); */
180 /* Use _internal here, since this thread can enter a doomed appdomain */
181 mono_domain_set_internal (mono_object_domain (o));
183 /* delegates that have a native function pointer allocated are
184 * registered for finalization, but they don't have a Finalize
185 * method, because in most cases it's not needed and it's just a waste.
187 if (o->vtable->klass->delegate) {
188 MonoDelegate* del = (MonoDelegate*)o;
189 if (del->delegate_trampoline)
190 mono_delegate_free_ftnptr ((MonoDelegate*)o);
191 mono_domain_set_internal (caller_domain);
195 finalizer = mono_class_get_finalizer (o->vtable->klass);
198 /* If object has a CCW but has no finalizer, it was only
199 * registered for finalization in order to free the CCW.
200 * Else it needs the regular finalizer run.
201 * FIXME: what to do about ressurection and suppression
202 * of finalizer on object with CCW.
204 if (mono_marshal_free_ccw (o) && !finalizer) {
205 mono_domain_set_internal (caller_domain);
211 * To avoid the locking plus the other overhead of mono_runtime_invoke (),
212 * create and precompile a wrapper which calls the finalize method using
215 if (!domain->finalize_runtime_invoke) {
216 MonoMethod *invoke = mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE);
218 domain->finalize_runtime_invoke = mono_compile_method (invoke);
221 runtime_invoke = domain->finalize_runtime_invoke;
223 mono_runtime_class_init (o->vtable);
225 runtime_invoke (o, NULL, &exc, NULL);
228 /* fixme: do something useful */
231 mono_domain_set_internal (caller_domain);
235 mono_gc_finalize_threadpool_threads (void)
237 while (threads_to_finalize) {
238 MonoInternalThread *thread = (MonoInternalThread*) mono_mlist_get_data (threads_to_finalize);
240 /* Force finalization of the thread. */
241 thread->threadpool_thread = FALSE;
242 mono_object_register_finalizer ((MonoObject*)thread);
244 mono_gc_run_finalize (thread, NULL);
246 threads_to_finalize = mono_mlist_next (threads_to_finalize);
251 mono_gc_out_of_memory (size_t size)
254 * we could allocate at program startup some memory that we could release
255 * back to the system at this point if we're really low on memory (ie, size is
256 * lower than the memory we set apart)
258 mono_raise_exception (mono_domain_get ()->out_of_memory_ex);
264 * Some of our objects may point to a different address than the address returned by GC_malloc()
265 * (because of the GetHashCode hack), but we need to pass the real address to register_finalizer.
266 * This also means that in the callback we need to adjust the pointer to get back the real
268 * We also need to be consistent in the use of the GC_debug* variants of malloc and register_finalizer,
269 * since that, too, can cause the underlying pointer to be offset.
272 object_register_finalizer (MonoObject *obj, void (*callback)(void *, void*))
279 mono_raise_exception (mono_get_exception_argument_null ("obj"));
281 domain = obj->vtable->domain;
284 /* This assertion is not valid when GC_DEBUG is defined */
285 g_assert (GC_base (obj) == (char*)obj - offset);
288 if (mono_domain_is_unloading (domain) && (callback != NULL))
290 * Can't register finalizers in a dying appdomain, since they
291 * could be invoked after the appdomain has been unloaded.
295 mono_domain_finalizers_lock (domain);
298 g_hash_table_insert (domain->finalizable_objects_hash, obj, obj);
300 g_hash_table_remove (domain->finalizable_objects_hash, obj);
302 mono_domain_finalizers_unlock (domain);
304 GC_REGISTER_FINALIZER_NO_ORDER ((char*)obj - offset, callback, GUINT_TO_POINTER (offset), NULL, NULL);
305 #elif defined(HAVE_SGEN_GC)
307 mono_raise_exception (mono_get_exception_argument_null ("obj"));
310 * If we register finalizers for domains that are unloading we might
311 * end up running them while or after the domain is being cleared, so
312 * the objects will not be valid anymore.
314 if (!mono_domain_is_unloading (obj->vtable->domain))
315 mono_gc_register_for_finalization (obj, callback);
320 * mono_object_register_finalizer:
321 * @obj: object to register
323 * Records that object @obj has a finalizer, this will call the
324 * Finalize method when the garbage collector disposes the object.
328 mono_object_register_finalizer (MonoObject *obj)
330 /* g_print ("Registered finalizer on %p %s.%s\n", obj, mono_object_class (obj)->name_space, mono_object_class (obj)->name); */
331 object_register_finalizer (obj, mono_gc_run_finalize);
335 * mono_domain_finalize:
336 * @domain: the domain to finalize
337 * @timeout: msects to wait for the finalization to complete, -1 to wait indefinitely
339 * Request finalization of all finalizable objects inside @domain. Wait
340 * @timeout msecs for the finalization to complete.
342 * Returns: TRUE if succeeded, FALSE if there was a timeout
346 mono_domain_finalize (MonoDomain *domain, guint32 timeout)
348 DomainFinalizationReq *req;
351 MonoInternalThread *thread = mono_thread_internal_current ();
353 if (mono_thread_internal_current () == gc_thread)
354 /* We are called from inside a finalizer, not much we can do here */
358 * No need to create another thread 'cause the finalizer thread
359 * is still working and will take care of running the finalizers
366 mono_gc_collect (mono_gc_max_generation ());
368 done_event = CreateEvent (NULL, TRUE, FALSE, NULL);
369 if (done_event == NULL) {
373 req = g_new0 (DomainFinalizationReq, 1);
374 req->domain = domain;
375 req->done_event = done_event;
377 if (domain == mono_get_root_domain ())
378 finalizing_root_domain = TRUE;
380 mono_finalizer_lock ();
382 domains_to_finalize = g_slist_append (domains_to_finalize, req);
384 mono_finalizer_unlock ();
386 /* Tell the finalizer thread to finalize this appdomain */
387 mono_gc_finalize_notify ();
393 res = WaitForSingleObjectEx (done_event, timeout, TRUE);
394 /* printf ("WAIT RES: %d.\n", res); */
396 if (res == WAIT_IO_COMPLETION) {
397 if ((thread->state & (ThreadState_StopRequested | ThreadState_SuspendRequested)) != 0)
399 } else if (res == WAIT_TIMEOUT) {
400 /* We leak the handle here */
407 CloseHandle (done_event);
409 if (domain == mono_get_root_domain ()) {
410 mono_thread_pool_cleanup ();
411 mono_gc_finalize_threadpool_threads ();
416 /* We don't support domain finalization without a GC */
422 ves_icall_System_GC_InternalCollect (int generation)
424 mono_gc_collect (generation);
428 ves_icall_System_GC_GetTotalMemory (MonoBoolean forceCollection)
433 mono_gc_collect (mono_gc_max_generation ());
434 return mono_gc_get_used_size ();
438 ves_icall_System_GC_KeepAlive (MonoObject *obj)
448 ves_icall_System_GC_ReRegisterForFinalize (MonoObject *obj)
451 mono_raise_exception (mono_get_exception_argument_null ("obj"));
453 object_register_finalizer (obj, mono_gc_run_finalize);
457 ves_icall_System_GC_SuppressFinalize (MonoObject *obj)
460 mono_raise_exception (mono_get_exception_argument_null ("obj"));
462 /* delegates have no finalizers, but we register them to deal with the
463 * unmanaged->managed trampoline. We don't let the user suppress it
464 * otherwise we'd leak it.
466 if (obj->vtable->klass->delegate)
469 /* FIXME: Need to handle case where obj has COM Callable Wrapper
470 * generated for it that needs cleaned up, but user wants to suppress
471 * their derived object finalizer. */
473 object_register_finalizer (obj, NULL);
477 ves_icall_System_GC_WaitForPendingFinalizers (void)
480 if (!mono_gc_pending_finalizers ())
483 if (mono_thread_internal_current () == gc_thread)
484 /* Avoid deadlocks */
487 ResetEvent (pending_done_event);
488 mono_gc_finalize_notify ();
489 /* g_print ("Waiting for pending finalizers....\n"); */
490 WaitForSingleObjectEx (pending_done_event, INFINITE, TRUE);
491 /* g_print ("Done pending....\n"); */
496 ves_icall_System_GC_register_ephemeron_array (MonoObject *array)
499 if (!mono_gc_ephemeron_array_add (array))
500 mono_raise_exception (mono_object_domain (array)->out_of_memory_ex);
505 ves_icall_System_GC_get_ephemeron_tombstone (void)
507 return mono_domain_get ()->ephemeron_tombstone;
510 #define mono_allocator_lock() EnterCriticalSection (&allocator_section)
511 #define mono_allocator_unlock() LeaveCriticalSection (&allocator_section)
512 static CRITICAL_SECTION allocator_section;
513 static CRITICAL_SECTION handle_section;
522 static HandleType mono_gchandle_get_type (guint32 gchandle);
525 ves_icall_System_GCHandle_GetTarget (guint32 handle)
527 return mono_gchandle_get_target (handle);
531 * if type == -1, change the target of the handle, otherwise allocate a new handle.
534 ves_icall_System_GCHandle_GetTargetHandle (MonoObject *obj, guint32 handle, gint32 type)
537 mono_gchandle_set_target (handle, obj);
538 /* the handle doesn't change */
543 return mono_gchandle_new_weakref (obj, FALSE);
544 case HANDLE_WEAK_TRACK:
545 return mono_gchandle_new_weakref (obj, TRUE);
547 return mono_gchandle_new (obj, FALSE);
549 return mono_gchandle_new (obj, TRUE);
551 g_assert_not_reached ();
557 ves_icall_System_GCHandle_FreeHandle (guint32 handle)
559 mono_gchandle_free (handle);
563 ves_icall_System_GCHandle_GetAddrOfPinnedObject (guint32 handle)
567 if (mono_gchandle_get_type (handle) != HANDLE_PINNED)
569 obj = mono_gchandle_get_target (handle);
571 MonoClass *klass = mono_object_class (obj);
572 if (klass == mono_defaults.string_class) {
573 return mono_string_chars ((MonoString*)obj);
574 } else if (klass->rank) {
575 return mono_array_addr ((MonoArray*)obj, char, 0);
577 /* the C# code will check and throw the exception */
578 /* FIXME: missing !klass->blittable test, see bug #61134 */
579 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
581 return (char*)obj + sizeof (MonoObject);
592 guint slot_hint : 24; /* starting slot for search */
593 /* 2^16 appdomains should be enough for everyone (though I know I'll regret this in 20 years) */
594 /* we alloc this only for weak refs, since we can get the domain directly in the other cases */
598 /* weak and weak-track arrays will be allocated in malloc memory
600 static HandleData gc_handles [] = {
601 {NULL, NULL, 0, HANDLE_WEAK, 0},
602 {NULL, NULL, 0, HANDLE_WEAK_TRACK, 0},
603 {NULL, NULL, 0, HANDLE_NORMAL, 0},
604 {NULL, NULL, 0, HANDLE_PINNED, 0}
607 #define lock_handles(handles) EnterCriticalSection (&handle_section)
608 #define unlock_handles(handles) LeaveCriticalSection (&handle_section)
611 find_first_unset (guint32 bitmap)
614 for (i = 0; i < 32; ++i) {
615 if (!(bitmap & (1 << i)))
622 alloc_handle (HandleData *handles, MonoObject *obj, gboolean track)
626 lock_handles (handles);
627 if (!handles->size) {
629 if (handles->type > HANDLE_WEAK_TRACK) {
630 handles->entries = mono_gc_alloc_fixed (sizeof (gpointer) * handles->size, mono_gc_make_root_descr_all_refs (handles->size));
632 handles->entries = g_malloc0 (sizeof (gpointer) * handles->size);
633 handles->domain_ids = g_malloc0 (sizeof (guint16) * handles->size);
635 handles->bitmap = g_malloc0 (handles->size / 8);
638 for (slot = handles->slot_hint; slot < handles->size / 32; ++slot) {
639 if (handles->bitmap [slot] != 0xffffffff) {
640 i = find_first_unset (handles->bitmap [slot]);
641 handles->slot_hint = slot;
645 if (i == -1 && handles->slot_hint != 0) {
646 for (slot = 0; slot < handles->slot_hint; ++slot) {
647 if (handles->bitmap [slot] != 0xffffffff) {
648 i = find_first_unset (handles->bitmap [slot]);
649 handles->slot_hint = slot;
656 guint32 new_size = handles->size * 2; /* always double: we memset to 0 based on this below */
658 /* resize and copy the bitmap */
659 new_bitmap = g_malloc0 (new_size / 8);
660 memcpy (new_bitmap, handles->bitmap, handles->size / 8);
661 g_free (handles->bitmap);
662 handles->bitmap = new_bitmap;
664 /* resize and copy the entries */
665 if (handles->type > HANDLE_WEAK_TRACK) {
668 entries = mono_gc_alloc_fixed (sizeof (gpointer) * new_size, mono_gc_make_root_descr_all_refs (new_size));
669 memcpy (entries, handles->entries, sizeof (gpointer) * handles->size);
671 mono_gc_free_fixed (handles->entries);
672 handles->entries = entries;
676 domain_ids = g_malloc0 (sizeof (guint16) * new_size);
677 entries = g_malloc (sizeof (gpointer) * new_size);
678 /* we disable GC because we could lose some disappearing link updates */
680 memcpy (entries, handles->entries, sizeof (gpointer) * handles->size);
681 memset (entries + handles->size, 0, sizeof (gpointer) * handles->size);
682 memcpy (domain_ids, handles->domain_ids, sizeof (guint16) * handles->size);
683 for (i = 0; i < handles->size; ++i) {
684 MonoObject *obj = mono_gc_weak_link_get (&(handles->entries [i]));
685 if (handles->entries [i])
686 mono_gc_weak_link_remove (&(handles->entries [i]));
687 /*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]);*/
689 mono_gc_weak_link_add (&(entries [i]), obj, track);
692 g_free (handles->entries);
693 g_free (handles->domain_ids);
694 handles->entries = entries;
695 handles->domain_ids = domain_ids;
699 /* set i and slot to the next free position */
701 slot = (handles->size + 1) / 32;
702 handles->slot_hint = handles->size + 1;
703 handles->size = new_size;
705 handles->bitmap [slot] |= 1 << i;
706 slot = slot * 32 + i;
707 handles->entries [slot] = obj;
708 if (handles->type <= HANDLE_WEAK_TRACK) {
709 /*FIXME, what to use when obj == null?*/
710 handles->domain_ids [slot] = (obj ? mono_object_get_domain (obj) : mono_domain_get ())->domain_id;
712 mono_gc_weak_link_add (&(handles->entries [slot]), obj, track);
715 mono_perfcounters->gc_num_handles++;
716 unlock_handles (handles);
717 /*g_print ("allocated entry %d of type %d to object %p (in slot: %p)\n", slot, handles->type, obj, handles->entries [slot]);*/
718 res = (slot << 3) | (handles->type + 1);
719 mono_profiler_gc_handle (MONO_PROFILER_GC_HANDLE_CREATED, handles->type, res, obj);
725 * @obj: managed object to get a handle for
726 * @pinned: whether the object should be pinned
728 * This returns a handle that wraps the object, this is used to keep a
729 * reference to a managed object from the unmanaged world and preventing the
730 * object from being disposed.
732 * If @pinned is false the address of the object can not be obtained, if it is
733 * true the address of the object can be obtained. This will also pin the
734 * object so it will not be possible by a moving garbage collector to move the
737 * Returns: a handle that can be used to access the object from
741 mono_gchandle_new (MonoObject *obj, gboolean pinned)
743 return alloc_handle (&gc_handles [pinned? HANDLE_PINNED: HANDLE_NORMAL], obj, FALSE);
747 * mono_gchandle_new_weakref:
748 * @obj: managed object to get a handle for
749 * @pinned: whether the object should be pinned
751 * This returns a weak handle that wraps the object, this is used to
752 * keep a reference to a managed object from the unmanaged world.
753 * Unlike the mono_gchandle_new the object can be reclaimed by the
754 * garbage collector. In this case the value of the GCHandle will be
757 * If @pinned is false the address of the object can not be obtained, if it is
758 * true the address of the object can be obtained. This will also pin the
759 * object so it will not be possible by a moving garbage collector to move the
762 * Returns: a handle that can be used to access the object from
766 mono_gchandle_new_weakref (MonoObject *obj, gboolean track_resurrection)
768 guint32 handle = alloc_handle (&gc_handles [track_resurrection? HANDLE_WEAK_TRACK: HANDLE_WEAK], obj, track_resurrection);
771 if (track_resurrection)
772 mono_gc_add_weak_track_handle (obj, handle);
779 mono_gchandle_get_type (guint32 gchandle)
781 guint type = (gchandle & 7) - 1;
787 * mono_gchandle_get_target:
788 * @gchandle: a GCHandle's handle.
790 * The handle was previously created by calling mono_gchandle_new or
791 * mono_gchandle_new_weakref.
793 * Returns a pointer to the MonoObject represented by the handle or
794 * NULL for a collected object if using a weakref handle.
797 mono_gchandle_get_target (guint32 gchandle)
799 guint slot = gchandle >> 3;
800 guint type = (gchandle & 7) - 1;
801 HandleData *handles = &gc_handles [type];
802 MonoObject *obj = NULL;
805 lock_handles (handles);
806 if (slot < handles->size && (handles->bitmap [slot / 32] & (1 << (slot % 32)))) {
807 if (handles->type <= HANDLE_WEAK_TRACK) {
808 obj = mono_gc_weak_link_get (&handles->entries [slot]);
810 obj = handles->entries [slot];
813 /* print a warning? */
815 unlock_handles (handles);
816 /*g_print ("get target of entry %d of type %d: %p\n", slot, handles->type, obj);*/
821 mono_gchandle_set_target (guint32 gchandle, MonoObject *obj)
823 guint slot = gchandle >> 3;
824 guint type = (gchandle & 7) - 1;
825 HandleData *handles = &gc_handles [type];
826 MonoObject *old_obj = NULL;
830 lock_handles (handles);
831 if (slot < handles->size && (handles->bitmap [slot / 32] & (1 << (slot % 32)))) {
832 if (handles->type <= HANDLE_WEAK_TRACK) {
833 old_obj = handles->entries [slot];
834 if (handles->entries [slot])
835 mono_gc_weak_link_remove (&handles->entries [slot]);
837 mono_gc_weak_link_add (&handles->entries [slot], obj, handles->type == HANDLE_WEAK_TRACK);
838 /*FIXME, what to use when obj == null?*/
839 handles->domain_ids [slot] = (obj ? mono_object_get_domain (obj) : mono_domain_get ())->domain_id;
841 handles->entries [slot] = obj;
844 /* print a warning? */
846 /*g_print ("changed entry %d of type %d to object %p (in slot: %p)\n", slot, handles->type, obj, handles->entries [slot]);*/
847 unlock_handles (handles);
850 if (type == HANDLE_WEAK_TRACK)
851 mono_gc_change_weak_track_handle (old_obj, obj, gchandle);
856 * mono_gchandle_is_in_domain:
857 * @gchandle: a GCHandle's handle.
858 * @domain: An application domain.
860 * Returns: true if the object wrapped by the @gchandle belongs to the specific @domain.
863 mono_gchandle_is_in_domain (guint32 gchandle, MonoDomain *domain)
865 guint slot = gchandle >> 3;
866 guint type = (gchandle & 7) - 1;
867 HandleData *handles = &gc_handles [type];
868 gboolean result = FALSE;
871 lock_handles (handles);
872 if (slot < handles->size && (handles->bitmap [slot / 32] & (1 << (slot % 32)))) {
873 if (handles->type <= HANDLE_WEAK_TRACK) {
874 result = domain->domain_id == handles->domain_ids [slot];
877 obj = handles->entries [slot];
881 result = domain == mono_object_domain (obj);
884 /* print a warning? */
886 unlock_handles (handles);
891 * mono_gchandle_free:
892 * @gchandle: a GCHandle's handle.
894 * Frees the @gchandle handle. If there are no outstanding
895 * references, the garbage collector can reclaim the memory of the
899 mono_gchandle_free (guint32 gchandle)
901 guint slot = gchandle >> 3;
902 guint type = (gchandle & 7) - 1;
903 HandleData *handles = &gc_handles [type];
907 if (type == HANDLE_WEAK_TRACK)
908 mono_gc_remove_weak_track_handle (gchandle);
911 lock_handles (handles);
912 if (slot < handles->size && (handles->bitmap [slot / 32] & (1 << (slot % 32)))) {
913 if (handles->type <= HANDLE_WEAK_TRACK) {
914 if (handles->entries [slot])
915 mono_gc_weak_link_remove (&handles->entries [slot]);
917 handles->entries [slot] = NULL;
919 handles->bitmap [slot / 32] &= ~(1 << (slot % 32));
921 /* print a warning? */
923 mono_perfcounters->gc_num_handles--;
924 /*g_print ("freed entry %d of type %d\n", slot, handles->type);*/
925 unlock_handles (handles);
926 mono_profiler_gc_handle (MONO_PROFILER_GC_HANDLE_DESTROYED, handles->type, gchandle, NULL);
930 * mono_gchandle_free_domain:
931 * @domain: domain that is unloading
933 * Function used internally to cleanup any GC handle for objects belonging
934 * to the specified domain during appdomain unload.
937 mono_gchandle_free_domain (MonoDomain *domain)
941 for (type = 0; type < 3; ++type) {
943 HandleData *handles = &gc_handles [type];
944 lock_handles (handles);
945 for (slot = 0; slot < handles->size; ++slot) {
946 if (!(handles->bitmap [slot / 32] & (1 << (slot % 32))))
948 if (type <= HANDLE_WEAK_TRACK) {
949 if (domain->domain_id == handles->domain_ids [slot]) {
950 handles->bitmap [slot / 32] &= ~(1 << (slot % 32));
951 if (handles->entries [slot])
952 mono_gc_weak_link_remove (&handles->entries [slot]);
955 if (handles->entries [slot] && mono_object_domain (handles->entries [slot]) == domain) {
956 handles->bitmap [slot / 32] &= ~(1 << (slot % 32));
957 handles->entries [slot] = NULL;
961 unlock_handles (handles);
967 GCHandle_CheckCurrentDomain (guint32 gchandle)
969 return mono_gchandle_is_in_domain (gchandle, mono_domain_get ());
974 #ifdef MONO_HAS_SEMAPHORES
975 static MonoSemType finalizer_sem;
977 static HANDLE finalizer_event;
978 static volatile gboolean finished=FALSE;
981 mono_gc_finalize_notify (void)
984 g_message ( "%s: prodding finalizer", __func__);
987 #ifdef MONO_HAS_SEMAPHORES
988 MONO_SEM_POST (&finalizer_sem);
990 SetEvent (finalizer_event);
997 collect_objects (gpointer key, gpointer value, gpointer user_data)
999 GPtrArray *arr = (GPtrArray*)user_data;
1000 g_ptr_array_add (arr, key);
1006 * finalize_domain_objects:
1008 * Run the finalizers of all finalizable objects in req->domain.
1011 finalize_domain_objects (DomainFinalizationReq *req)
1013 MonoDomain *domain = req->domain;
1015 #ifdef HAVE_BOEHM_GC
1016 while (g_hash_table_size (domain->finalizable_objects_hash) > 0) {
1020 * Since the domain is unloading, nobody is allowed to put
1021 * new entries into the hash table. But finalize_object might
1022 * remove entries from the hash table, so we make a copy.
1024 objs = g_ptr_array_new ();
1025 g_hash_table_foreach (domain->finalizable_objects_hash, collect_objects, objs);
1026 /* printf ("FINALIZING %d OBJECTS.\n", objs->len); */
1028 for (i = 0; i < objs->len; ++i) {
1029 MonoObject *o = (MonoObject*)g_ptr_array_index (objs, i);
1030 /* FIXME: Avoid finalizing threads, etc */
1031 mono_gc_run_finalize (o, 0);
1034 g_ptr_array_free (objs, TRUE);
1036 #elif defined(HAVE_SGEN_GC)
1037 #define NUM_FOBJECTS 64
1038 MonoObject *to_finalize [NUM_FOBJECTS];
1040 while ((count = mono_gc_finalizers_for_domain (domain, to_finalize, NUM_FOBJECTS))) {
1042 for (i = 0; i < count; ++i) {
1043 mono_gc_run_finalize (to_finalize [i], 0);
1048 /* Process finalizers which are already in the queue */
1049 mono_gc_invoke_finalizers ();
1051 /* cleanup the reference queue */
1052 reference_queue_clear_for_domain (domain);
1054 /* printf ("DONE.\n"); */
1055 SetEvent (req->done_event);
1057 /* The event is closed in mono_domain_finalize if we get here */
1062 finalizer_thread (gpointer unused)
1065 /* Wait to be notified that there's at least one
1069 g_assert (mono_domain_get () == mono_get_root_domain ());
1071 /* An alertable wait is required so this thread can be suspended on windows */
1072 #ifdef MONO_HAS_SEMAPHORES
1073 MONO_SEM_WAIT_ALERTABLE (&finalizer_sem, TRUE);
1075 WaitForSingleObjectEx (finalizer_event, INFINITE, TRUE);
1078 mono_threads_perform_thread_dump ();
1080 mono_console_handle_async_ops ();
1082 #ifndef DISABLE_ATTACH
1083 mono_attach_maybe_start ();
1086 if (domains_to_finalize) {
1087 mono_finalizer_lock ();
1088 if (domains_to_finalize) {
1089 DomainFinalizationReq *req = domains_to_finalize->data;
1090 domains_to_finalize = g_slist_remove (domains_to_finalize, req);
1091 mono_finalizer_unlock ();
1093 finalize_domain_objects (req);
1095 mono_finalizer_unlock ();
1099 /* If finished == TRUE, mono_gc_cleanup has been called (from mono_runtime_cleanup),
1100 * before the domain is unloaded.
1102 mono_gc_invoke_finalizers ();
1104 reference_queue_proccess_all ();
1106 SetEvent (pending_done_event);
1109 SetEvent (shutdown_event);
1116 InitializeCriticalSection (&handle_section);
1117 InitializeCriticalSection (&allocator_section);
1119 InitializeCriticalSection (&finalizer_mutex);
1120 InitializeCriticalSection (&reference_queue_mutex);
1122 MONO_GC_REGISTER_ROOT_FIXED (gc_handles [HANDLE_NORMAL].entries);
1123 MONO_GC_REGISTER_ROOT_FIXED (gc_handles [HANDLE_PINNED].entries);
1125 mono_gc_base_init ();
1127 if (mono_gc_is_disabled ()) {
1132 finalizer_event = CreateEvent (NULL, FALSE, FALSE, NULL);
1133 pending_done_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1134 shutdown_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1135 if (finalizer_event == NULL || pending_done_event == NULL || shutdown_event == NULL) {
1136 g_assert_not_reached ();
1138 #ifdef MONO_HAS_SEMAPHORES
1139 MONO_SEM_INIT (&finalizer_sem, 0);
1142 gc_thread = mono_thread_create_internal (mono_domain_get (), finalizer_thread, NULL, FALSE, 0);
1143 ves_icall_System_Threading_Thread_SetName_internal (gc_thread, mono_string_new (mono_domain_get (), "Finalizer"));
1147 mono_gc_cleanup (void)
1150 g_message ("%s: cleaning up finalizer", __func__);
1154 ResetEvent (shutdown_event);
1156 if (mono_thread_internal_current () != gc_thread) {
1157 mono_gc_finalize_notify ();
1158 /* Finishing the finalizer thread, so wait a little bit... */
1159 /* MS seems to wait for about 2 seconds */
1160 if (WaitForSingleObjectEx (shutdown_event, 2000, FALSE) == WAIT_TIMEOUT) {
1163 /* Set a flag which the finalizer thread can check */
1164 suspend_finalizers = TRUE;
1166 /* Try to abort the thread, in the hope that it is running managed code */
1167 mono_thread_internal_stop (gc_thread);
1169 /* Wait for it to stop */
1170 ret = WaitForSingleObjectEx (gc_thread->handle, 100, TRUE);
1172 if (ret == WAIT_TIMEOUT) {
1174 * The finalizer thread refused to die. There is not much we
1175 * can do here, since the runtime is shutting down so the
1176 * state the finalizer thread depends on will vanish.
1178 g_warning ("Shutting down finalizer thread timed out.");
1181 * FIXME: On unix, when the above wait returns, the thread
1182 * might still be running io-layer code, or pthreads code.
1190 #ifdef HAVE_BOEHM_GC
1191 GC_finalizer_notifier = NULL;
1195 mono_reference_queue_cleanup ();
1197 DeleteCriticalSection (&handle_section);
1198 DeleteCriticalSection (&allocator_section);
1199 DeleteCriticalSection (&finalizer_mutex);
1200 DeleteCriticalSection (&reference_queue_mutex);
1205 /* Null GC dummy functions */
1207 mono_gc_finalize_notify (void)
1211 void mono_gc_init (void)
1213 InitializeCriticalSection (&handle_section);
1216 void mono_gc_cleanup (void)
1223 mono_gc_is_finalizer_internal_thread (MonoInternalThread *thread)
1225 return thread == gc_thread;
1229 * mono_gc_is_finalizer_thread:
1230 * @thread: the thread to test.
1232 * In Mono objects are finalized asynchronously on a separate thread.
1233 * This routine tests whether the @thread argument represents the
1234 * finalization thread.
1236 * Returns true if @thread is the finalization thread.
1239 mono_gc_is_finalizer_thread (MonoThread *thread)
1241 return mono_gc_is_finalizer_internal_thread (thread->internal_thread);
1244 #if defined(__MACH__)
1245 static pthread_t mach_exception_thread;
1248 mono_gc_register_mach_exception_thread (pthread_t thread)
1250 mach_exception_thread = thread;
1254 mono_gc_get_mach_exception_thread (void)
1256 return mach_exception_thread;
1261 * mono_gc_parse_environment_string_extract_number:
1263 * @str: points to the first digit of the number
1264 * @out: pointer to the variable that will receive the value
1266 * Tries to extract a number from the passed string, taking in to account m, k
1269 * Returns true if passing was successful
1272 mono_gc_parse_environment_string_extract_number (const char *str, glong *out)
1275 int len = strlen (str), shift = 0;
1277 gboolean is_suffix = FALSE;
1283 suffix = str [len - 1];
1298 if (!isdigit (suffix))
1304 val = strtol (str, &endptr, 10);
1306 if ((errno == ERANGE && (val == LONG_MAX || val == LONG_MIN))
1307 || (errno != 0 && val == 0) || (endptr == str))
1311 if (*(endptr + 1)) /* Invalid string. */
1320 #ifndef HAVE_SGEN_GC
1322 mono_gc_alloc_mature (MonoVTable *vtable)
1324 return mono_object_new_specific (vtable);
1329 static MonoReferenceQueue *ref_queues;
1332 ref_list_remove_element (RefQueueEntry **prev, RefQueueEntry *element)
1335 /* Guard if head is changed concurrently. */
1336 while (*prev != element)
1337 prev = &(*prev)->next;
1338 } while (prev && InterlockedCompareExchangePointer ((void*)prev, element->next, element) != element);
1342 ref_list_push (RefQueueEntry **head, RefQueueEntry *value)
1344 RefQueueEntry *current;
1347 value->next = current;
1348 STORE_STORE_FENCE; /*Must make sure the previous store is visible before the CAS. */
1349 } while (InterlockedCompareExchangePointer ((void*)head, value, current) != current);
1353 reference_queue_proccess (MonoReferenceQueue *queue)
1355 RefQueueEntry **iter = &queue->queue;
1356 RefQueueEntry *entry;
1357 while ((entry = *iter)) {
1359 if (queue->should_be_deleted || !mono_gc_weak_link_get (&entry->dis_link)) {
1360 mono_gc_weak_link_remove (&entry->dis_link);
1362 if (queue->should_be_deleted || !mono_gchandle_get_target (entry->gchandle)) {
1363 mono_gchandle_free ((guint32)entry->gchandle);
1365 ref_list_remove_element (iter, entry);
1366 queue->callback (entry->user_data);
1369 iter = &entry->next;
1375 reference_queue_proccess_all (void)
1377 MonoReferenceQueue **iter;
1378 MonoReferenceQueue *queue = ref_queues;
1379 for (; queue; queue = queue->next)
1380 reference_queue_proccess (queue);
1383 EnterCriticalSection (&reference_queue_mutex);
1384 for (iter = &ref_queues; *iter;) {
1386 if (!queue->should_be_deleted) {
1387 iter = &queue->next;
1391 LeaveCriticalSection (&reference_queue_mutex);
1392 reference_queue_proccess (queue);
1395 *iter = queue->next;
1398 LeaveCriticalSection (&reference_queue_mutex);
1402 mono_reference_queue_cleanup (void)
1404 MonoReferenceQueue *queue = ref_queues;
1405 for (; queue; queue = queue->next)
1406 queue->should_be_deleted = TRUE;
1407 reference_queue_proccess_all ();
1411 reference_queue_clear_for_domain (MonoDomain *domain)
1413 MonoReferenceQueue *queue = ref_queues;
1414 for (; queue; queue = queue->next) {
1415 RefQueueEntry **iter = &queue->queue;
1416 RefQueueEntry *entry;
1417 while ((entry = *iter)) {
1420 obj = mono_gc_weak_link_get (&entry->dis_link);
1421 if (obj && mono_object_domain (obj) == domain) {
1422 mono_gc_weak_link_remove (&entry->dis_link);
1424 obj = mono_gchandle_get_target (entry->gchandle);
1425 if (obj && mono_object_domain (obj) == domain) {
1426 mono_gchandle_free ((guint32)entry->gchandle);
1428 ref_list_remove_element (iter, entry);
1429 queue->callback (entry->user_data);
1432 iter = &entry->next;
1438 * mono_gc_reference_queue_new:
1439 * @callback callback used when processing dead entries.
1441 * Create a new reference queue used to process collected objects.
1442 * A reference queue let you queue a pair (managed object, user data)
1443 * using the mono_gc_reference_queue_add method.
1445 * Once the managed object is collected @callback will be called
1446 * in the finalizer thread with 'user data' as argument.
1448 * The callback is called without any locks held.
1451 mono_gc_reference_queue_new (mono_reference_queue_callback callback)
1453 MonoReferenceQueue *res = g_new0 (MonoReferenceQueue, 1);
1454 res->callback = callback;
1456 EnterCriticalSection (&reference_queue_mutex);
1457 res->next = ref_queues;
1459 LeaveCriticalSection (&reference_queue_mutex);
1465 * mono_gc_reference_queue_add:
1466 * @queue the queue to add the reference to.
1467 * @obj the object to be watched for collection
1468 * @user_data parameter to be passed to the queue callback
1470 * Queue an object to be watched for collection, when the @obj is
1471 * collected, the callback that was registered for the @queue will
1472 * be invoked with the @obj and @user_data arguments.
1474 * @returns false if the queue is scheduled to be freed.
1477 mono_gc_reference_queue_add (MonoReferenceQueue *queue, MonoObject *obj, void *user_data)
1479 RefQueueEntry *entry;
1480 if (queue->should_be_deleted)
1483 entry = g_new0 (RefQueueEntry, 1);
1484 entry->user_data = user_data;
1487 mono_gc_weak_link_add (&entry->dis_link, obj, TRUE);
1489 entry->gchandle = mono_gchandle_new_weakref (obj, TRUE);
1490 mono_object_register_finalizer (obj);
1493 ref_list_push (&queue->queue, entry);
1498 * mono_gc_reference_queue_free:
1499 * @queue the queue that should be deleted.
1501 * This operation signals that @queue should be deleted. This operation is deferred
1502 * as it happens on the finalizer thread.
1504 * After this call, no further objects can be queued. It's the responsibility of the
1505 * caller to make sure that no further attempt to access queue will be made.
1508 mono_gc_reference_queue_free (MonoReferenceQueue *queue)
1510 queue->should_be_deleted = TRUE;
1513 #define ptr_mask ((sizeof (void*) - 1))
1514 #define _toi(ptr) ((size_t)ptr)
1515 #define unaligned_bytes(ptr) (_toi(ptr) & ptr_mask)
1516 #define align_down(ptr) ((void*)(_toi(ptr) & ~ptr_mask))
1517 #define align_up(ptr) ((void*) ((_toi(ptr) + ptr_mask) & ~ptr_mask))
1521 * @dest: address to start to clear
1522 * @size: size of the region to clear
1524 * Zero @size bytes starting at @dest.
1526 * Use this to zero memory that can hold managed pointers.
1528 * FIXME borrow faster code from some BSD libc or bionic
1531 mono_gc_bzero (void *dest, size_t size)
1533 char *p = (char*)dest;
1534 char *end = p + size;
1535 char *align_end = p + unaligned_bytes (p);
1538 while (p < align_end)
1541 word_end = align_down (end);
1542 while (p < word_end) {
1543 *((void**)p) = NULL;
1544 p += sizeof (void*);
1554 * @dest: destination of the move
1556 * @size: size of the block to move
1558 * Move @size bytes from @src to @dest.
1559 * size MUST be a multiple of sizeof (gpointer)
1561 * FIXME borrow faster code from some BSD libc or bionic
1564 mono_gc_memmove (void *dest, const void *src, size_t size)
1567 * If dest and src are differently aligned with respect to
1568 * pointer size then it makes no sense to do aligned copying.
1569 * In fact, we would end up with unaligned loads which is
1570 * incorrect on some architectures.
1572 if ((char*)dest - (char*)align_down (dest) != (char*)src - (char*)align_down (src)) {
1573 memmove (dest, src, size);
1578 * A bit of explanation on why we align only dest before doing word copies.
1579 * Pointers to managed objects must always be stored in word aligned addresses, so
1580 * even if dest is misaligned, src will be by the same amount - this ensure proper atomicity of reads.
1582 if (dest > src && ((size_t)((char*)dest - (char*)src) < size)) {
1583 char *p = (char*)dest + size;
1584 char *s = (char*)src + size;
1585 char *start = (char*)dest;
1586 char *align_end = MAX((char*)dest, (char*)align_down (p));
1589 while (p > align_end)
1592 word_start = align_up (start);
1593 while (p > word_start) {
1594 p -= sizeof (void*);
1595 s -= sizeof (void*);
1596 *((void**)p) = *((void**)s);
1602 char *p = (char*)dest;
1603 char *s = (char*)src;
1604 char *end = p + size;
1605 char *align_end = MIN ((char*)end, (char*)align_up (p));
1608 while (p < align_end)
1611 word_end = align_down (end);
1612 while (p < word_end) {
1613 *((void**)p) = *((void**)s);
1614 p += sizeof (void*);
1615 s += sizeof (void*);