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 * Copyright 2012 Xamarin Inc (http://www.xamarin.com)
16 #include <mono/metadata/gc-internal.h>
17 #include <mono/metadata/mono-gc.h>
18 #include <mono/metadata/threads.h>
19 #include <mono/metadata/tabledefs.h>
20 #include <mono/metadata/exception.h>
21 #include <mono/metadata/profiler-private.h>
22 #include <mono/metadata/domain-internals.h>
23 #include <mono/metadata/class-internals.h>
24 #include <mono/metadata/metadata-internals.h>
25 #include <mono/metadata/mono-mlist.h>
26 #include <mono/metadata/threadpool.h>
27 #include <mono/metadata/threads-types.h>
28 #include <mono/utils/mono-logger-internal.h>
29 #include <mono/metadata/gc-internal.h>
30 #include <mono/metadata/marshal.h> /* for mono_delegate_free_ftnptr () */
31 #include <mono/metadata/attach.h>
32 #include <mono/metadata/console-io.h>
33 #include <mono/utils/mono-semaphore.h>
34 #include <mono/utils/mono-memory-model.h>
40 typedef struct DomainFinalizationReq {
43 } DomainFinalizationReq;
45 #ifdef PLATFORM_WINCE /* FIXME: add accessors to gc.dll API */
46 extern void (*__imp_GC_finalizer_notifier)(void);
47 #define GC_finalizer_notifier __imp_GC_finalizer_notifier
48 extern int __imp_GC_finalize_on_demand;
49 #define GC_finalize_on_demand __imp_GC_finalize_on_demand
52 static gboolean gc_disabled = FALSE;
54 static gboolean finalizing_root_domain = FALSE;
56 #define mono_finalizer_lock() EnterCriticalSection (&finalizer_mutex)
57 #define mono_finalizer_unlock() LeaveCriticalSection (&finalizer_mutex)
58 static CRITICAL_SECTION finalizer_mutex;
59 static CRITICAL_SECTION reference_queue_mutex;
61 static GSList *domains_to_finalize= NULL;
62 static MonoMList *threads_to_finalize = NULL;
64 static MonoInternalThread *gc_thread;
66 static void object_register_finalizer (MonoObject *obj, void (*callback)(void *, void*));
68 static void mono_gchandle_set_target (guint32 gchandle, MonoObject *obj);
70 static void reference_queue_proccess_all (void);
71 static void mono_reference_queue_cleanup (void);
72 static void reference_queue_clear_for_domain (MonoDomain *domain);
74 static HANDLE pending_done_event;
75 static HANDLE shutdown_event;
79 add_thread_to_finalize (MonoInternalThread *thread)
81 mono_finalizer_lock ();
82 if (!threads_to_finalize)
83 MONO_GC_REGISTER_ROOT_SINGLE (threads_to_finalize);
84 threads_to_finalize = mono_mlist_append (threads_to_finalize, (MonoObject*)thread);
85 mono_finalizer_unlock ();
88 static gboolean suspend_finalizers = FALSE;
90 * actually, we might want to queue the finalize requests in a separate thread,
91 * but we need to be careful about the execution domain of the thread...
94 mono_gc_run_finalize (void *obj, void *data)
96 MonoObject *exc = NULL;
101 MonoMethod* finalizer = NULL;
102 MonoDomain *caller_domain = mono_domain_get ();
104 RuntimeInvokeFunction runtime_invoke;
105 GSList *l, *refs = NULL;
107 o = (MonoObject*)((char*)obj + GPOINTER_TO_UINT (data));
109 if (suspend_finalizers)
112 domain = o->vtable->domain;
115 mono_domain_finalizers_lock (domain);
117 o2 = g_hash_table_lookup (domain->finalizable_objects_hash, o);
119 refs = mono_gc_remove_weak_track_object (domain, o);
121 mono_domain_finalizers_unlock (domain);
124 /* Already finalized somehow */
130 * Support for GCHandles of type WeakTrackResurrection:
132 * Its not exactly clear how these are supposed to work, or how their
133 * semantics can be implemented. We only implement one crucial thing:
134 * these handles are only cleared after the finalizer has ran.
136 for (l = refs; l; l = l->next) {
137 guint32 gchandle = GPOINTER_TO_UINT (l->data);
139 mono_gchandle_set_target (gchandle, o);
145 /* make sure the finalizer is not called again if the object is resurrected */
146 object_register_finalizer (obj, NULL);
148 if (o->vtable->klass == mono_defaults.internal_thread_class) {
149 MonoInternalThread *t = (MonoInternalThread*)o;
151 if (mono_gc_is_finalizer_internal_thread (t))
152 /* Avoid finalizing ourselves */
155 if (t->threadpool_thread && finalizing_root_domain) {
156 /* Don't finalize threadpool threads when
157 shutting down - they're finalized when the
158 threadpool shuts down. */
159 add_thread_to_finalize (t);
164 if (o->vtable->klass->image == mono_defaults.corlib && !strcmp (o->vtable->klass->name, "DynamicMethod") && finalizing_root_domain) {
166 * These can't be finalized during unloading/shutdown, since that would
167 * free the native code which can still be referenced by other
169 * FIXME: This is not perfect, objects dying at the same time as
170 * dynamic methods can still reference them even when !shutdown.
175 if (mono_runtime_get_no_exec ())
178 /* speedup later... and use a timeout */
179 /* g_print ("Finalize run on %p %s.%s\n", o, mono_object_class (o)->name_space, mono_object_class (o)->name); */
181 /* Use _internal here, since this thread can enter a doomed appdomain */
182 mono_domain_set_internal (mono_object_domain (o));
184 /* delegates that have a native function pointer allocated are
185 * registered for finalization, but they don't have a Finalize
186 * method, because in most cases it's not needed and it's just a waste.
188 if (o->vtable->klass->delegate) {
189 MonoDelegate* del = (MonoDelegate*)o;
190 if (del->delegate_trampoline)
191 mono_delegate_free_ftnptr ((MonoDelegate*)o);
192 mono_domain_set_internal (caller_domain);
196 finalizer = mono_class_get_finalizer (o->vtable->klass);
199 /* If object has a CCW but has no finalizer, it was only
200 * registered for finalization in order to free the CCW.
201 * Else it needs the regular finalizer run.
202 * FIXME: what to do about ressurection and suppression
203 * of finalizer on object with CCW.
205 if (mono_marshal_free_ccw (o) && !finalizer) {
206 mono_domain_set_internal (caller_domain);
212 * To avoid the locking plus the other overhead of mono_runtime_invoke (),
213 * create and precompile a wrapper which calls the finalize method using
216 if (!domain->finalize_runtime_invoke) {
217 MonoMethod *invoke = mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE);
219 domain->finalize_runtime_invoke = mono_compile_method (invoke);
222 runtime_invoke = domain->finalize_runtime_invoke;
224 mono_runtime_class_init (o->vtable);
226 runtime_invoke (o, NULL, &exc, NULL);
229 /* fixme: do something useful */
232 mono_domain_set_internal (caller_domain);
236 mono_gc_finalize_threadpool_threads (void)
238 while (threads_to_finalize) {
239 MonoInternalThread *thread = (MonoInternalThread*) mono_mlist_get_data (threads_to_finalize);
241 /* Force finalization of the thread. */
242 thread->threadpool_thread = FALSE;
243 mono_object_register_finalizer ((MonoObject*)thread);
245 mono_gc_run_finalize (thread, NULL);
247 threads_to_finalize = mono_mlist_next (threads_to_finalize);
252 mono_gc_out_of_memory (size_t size)
255 * we could allocate at program startup some memory that we could release
256 * back to the system at this point if we're really low on memory (ie, size is
257 * lower than the memory we set apart)
259 mono_raise_exception (mono_domain_get ()->out_of_memory_ex);
265 * Some of our objects may point to a different address than the address returned by GC_malloc()
266 * (because of the GetHashCode hack), but we need to pass the real address to register_finalizer.
267 * This also means that in the callback we need to adjust the pointer to get back the real
269 * We also need to be consistent in the use of the GC_debug* variants of malloc and register_finalizer,
270 * since that, too, can cause the underlying pointer to be offset.
273 object_register_finalizer (MonoObject *obj, void (*callback)(void *, void*))
280 mono_raise_exception (mono_get_exception_argument_null ("obj"));
282 domain = obj->vtable->domain;
285 /* This assertion is not valid when GC_DEBUG is defined */
286 g_assert (GC_base (obj) == (char*)obj - offset);
289 if (mono_domain_is_unloading (domain) && (callback != NULL))
291 * Can't register finalizers in a dying appdomain, since they
292 * could be invoked after the appdomain has been unloaded.
296 mono_domain_finalizers_lock (domain);
299 g_hash_table_insert (domain->finalizable_objects_hash, obj, obj);
301 g_hash_table_remove (domain->finalizable_objects_hash, obj);
303 mono_domain_finalizers_unlock (domain);
305 GC_REGISTER_FINALIZER_NO_ORDER ((char*)obj - offset, callback, GUINT_TO_POINTER (offset), NULL, NULL);
306 #elif defined(HAVE_SGEN_GC)
308 mono_raise_exception (mono_get_exception_argument_null ("obj"));
311 * If we register finalizers for domains that are unloading we might
312 * end up running them while or after the domain is being cleared, so
313 * the objects will not be valid anymore.
315 if (!mono_domain_is_unloading (obj->vtable->domain))
316 mono_gc_register_for_finalization (obj, callback);
321 * mono_object_register_finalizer:
322 * @obj: object to register
324 * Records that object @obj has a finalizer, this will call the
325 * Finalize method when the garbage collector disposes the object.
329 mono_object_register_finalizer (MonoObject *obj)
331 /* g_print ("Registered finalizer on %p %s.%s\n", obj, mono_object_class (obj)->name_space, mono_object_class (obj)->name); */
332 object_register_finalizer (obj, mono_gc_run_finalize);
336 * mono_domain_finalize:
337 * @domain: the domain to finalize
338 * @timeout: msects to wait for the finalization to complete, -1 to wait indefinitely
340 * Request finalization of all finalizable objects inside @domain. Wait
341 * @timeout msecs for the finalization to complete.
343 * Returns: TRUE if succeeded, FALSE if there was a timeout
347 mono_domain_finalize (MonoDomain *domain, guint32 timeout)
349 DomainFinalizationReq *req;
352 MonoInternalThread *thread = mono_thread_internal_current ();
354 if (mono_thread_internal_current () == gc_thread)
355 /* We are called from inside a finalizer, not much we can do here */
359 * No need to create another thread 'cause the finalizer thread
360 * is still working and will take care of running the finalizers
367 mono_gc_collect (mono_gc_max_generation ());
369 done_event = CreateEvent (NULL, TRUE, FALSE, NULL);
370 if (done_event == NULL) {
374 req = g_new0 (DomainFinalizationReq, 1);
375 req->domain = domain;
376 req->done_event = done_event;
378 if (domain == mono_get_root_domain ())
379 finalizing_root_domain = TRUE;
381 mono_finalizer_lock ();
383 domains_to_finalize = g_slist_append (domains_to_finalize, req);
385 mono_finalizer_unlock ();
387 /* Tell the finalizer thread to finalize this appdomain */
388 mono_gc_finalize_notify ();
394 res = WaitForSingleObjectEx (done_event, timeout, TRUE);
395 /* printf ("WAIT RES: %d.\n", res); */
397 if (res == WAIT_IO_COMPLETION) {
398 if ((thread->state & (ThreadState_StopRequested | ThreadState_SuspendRequested)) != 0)
400 } else if (res == WAIT_TIMEOUT) {
401 /* We leak the handle here */
408 CloseHandle (done_event);
410 if (domain == mono_get_root_domain ()) {
411 mono_thread_pool_cleanup ();
412 mono_gc_finalize_threadpool_threads ();
417 /* We don't support domain finalization without a GC */
423 ves_icall_System_GC_InternalCollect (int generation)
425 mono_gc_collect (generation);
429 ves_icall_System_GC_GetTotalMemory (MonoBoolean forceCollection)
434 mono_gc_collect (mono_gc_max_generation ());
435 return mono_gc_get_used_size ();
439 ves_icall_System_GC_KeepAlive (MonoObject *obj)
449 ves_icall_System_GC_ReRegisterForFinalize (MonoObject *obj)
452 mono_raise_exception (mono_get_exception_argument_null ("obj"));
454 object_register_finalizer (obj, mono_gc_run_finalize);
458 ves_icall_System_GC_SuppressFinalize (MonoObject *obj)
461 mono_raise_exception (mono_get_exception_argument_null ("obj"));
463 /* delegates have no finalizers, but we register them to deal with the
464 * unmanaged->managed trampoline. We don't let the user suppress it
465 * otherwise we'd leak it.
467 if (obj->vtable->klass->delegate)
470 /* FIXME: Need to handle case where obj has COM Callable Wrapper
471 * generated for it that needs cleaned up, but user wants to suppress
472 * their derived object finalizer. */
474 object_register_finalizer (obj, NULL);
478 ves_icall_System_GC_WaitForPendingFinalizers (void)
481 if (!mono_gc_pending_finalizers ())
484 if (mono_thread_internal_current () == gc_thread)
485 /* Avoid deadlocks */
488 ResetEvent (pending_done_event);
489 mono_gc_finalize_notify ();
490 /* g_print ("Waiting for pending finalizers....\n"); */
491 WaitForSingleObjectEx (pending_done_event, INFINITE, TRUE);
492 /* g_print ("Done pending....\n"); */
497 ves_icall_System_GC_register_ephemeron_array (MonoObject *array)
500 if (!mono_gc_ephemeron_array_add (array))
501 mono_raise_exception (mono_object_domain (array)->out_of_memory_ex);
506 ves_icall_System_GC_get_ephemeron_tombstone (void)
508 return mono_domain_get ()->ephemeron_tombstone;
511 #define mono_allocator_lock() EnterCriticalSection (&allocator_section)
512 #define mono_allocator_unlock() LeaveCriticalSection (&allocator_section)
513 static CRITICAL_SECTION allocator_section;
514 static CRITICAL_SECTION handle_section;
523 static HandleType mono_gchandle_get_type (guint32 gchandle);
526 ves_icall_System_GCHandle_GetTarget (guint32 handle)
528 return mono_gchandle_get_target (handle);
532 * if type == -1, change the target of the handle, otherwise allocate a new handle.
535 ves_icall_System_GCHandle_GetTargetHandle (MonoObject *obj, guint32 handle, gint32 type)
538 mono_gchandle_set_target (handle, obj);
539 /* the handle doesn't change */
544 return mono_gchandle_new_weakref (obj, FALSE);
545 case HANDLE_WEAK_TRACK:
546 return mono_gchandle_new_weakref (obj, TRUE);
548 return mono_gchandle_new (obj, FALSE);
550 return mono_gchandle_new (obj, TRUE);
552 g_assert_not_reached ();
558 ves_icall_System_GCHandle_FreeHandle (guint32 handle)
560 mono_gchandle_free (handle);
564 ves_icall_System_GCHandle_GetAddrOfPinnedObject (guint32 handle)
568 if (mono_gchandle_get_type (handle) != HANDLE_PINNED)
570 obj = mono_gchandle_get_target (handle);
572 MonoClass *klass = mono_object_class (obj);
573 if (klass == mono_defaults.string_class) {
574 return mono_string_chars ((MonoString*)obj);
575 } else if (klass->rank) {
576 return mono_array_addr ((MonoArray*)obj, char, 0);
578 /* the C# code will check and throw the exception */
579 /* FIXME: missing !klass->blittable test, see bug #61134 */
580 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
582 return (char*)obj + sizeof (MonoObject);
593 guint slot_hint : 24; /* starting slot for search */
594 /* 2^16 appdomains should be enough for everyone (though I know I'll regret this in 20 years) */
595 /* we alloc this only for weak refs, since we can get the domain directly in the other cases */
599 /* weak and weak-track arrays will be allocated in malloc memory
601 static HandleData gc_handles [] = {
602 {NULL, NULL, 0, HANDLE_WEAK, 0},
603 {NULL, NULL, 0, HANDLE_WEAK_TRACK, 0},
604 {NULL, NULL, 0, HANDLE_NORMAL, 0},
605 {NULL, NULL, 0, HANDLE_PINNED, 0}
608 #define lock_handles(handles) EnterCriticalSection (&handle_section)
609 #define unlock_handles(handles) LeaveCriticalSection (&handle_section)
612 find_first_unset (guint32 bitmap)
615 for (i = 0; i < 32; ++i) {
616 if (!(bitmap & (1 << i)))
623 alloc_handle (HandleData *handles, MonoObject *obj, gboolean track)
627 lock_handles (handles);
628 if (!handles->size) {
630 if (handles->type > HANDLE_WEAK_TRACK) {
631 handles->entries = mono_gc_alloc_fixed (sizeof (gpointer) * handles->size, mono_gc_make_root_descr_all_refs (handles->size));
633 handles->entries = g_malloc0 (sizeof (gpointer) * handles->size);
634 handles->domain_ids = g_malloc0 (sizeof (guint16) * handles->size);
636 handles->bitmap = g_malloc0 (handles->size / 8);
639 for (slot = handles->slot_hint; slot < handles->size / 32; ++slot) {
640 if (handles->bitmap [slot] != 0xffffffff) {
641 i = find_first_unset (handles->bitmap [slot]);
642 handles->slot_hint = slot;
646 if (i == -1 && handles->slot_hint != 0) {
647 for (slot = 0; slot < handles->slot_hint; ++slot) {
648 if (handles->bitmap [slot] != 0xffffffff) {
649 i = find_first_unset (handles->bitmap [slot]);
650 handles->slot_hint = slot;
657 guint32 new_size = handles->size * 2; /* always double: we memset to 0 based on this below */
659 /* resize and copy the bitmap */
660 new_bitmap = g_malloc0 (new_size / 8);
661 memcpy (new_bitmap, handles->bitmap, handles->size / 8);
662 g_free (handles->bitmap);
663 handles->bitmap = new_bitmap;
665 /* resize and copy the entries */
666 if (handles->type > HANDLE_WEAK_TRACK) {
669 entries = mono_gc_alloc_fixed (sizeof (gpointer) * new_size, mono_gc_make_root_descr_all_refs (new_size));
670 memcpy (entries, handles->entries, sizeof (gpointer) * handles->size);
672 mono_gc_free_fixed (handles->entries);
673 handles->entries = entries;
677 domain_ids = g_malloc0 (sizeof (guint16) * new_size);
678 entries = g_malloc (sizeof (gpointer) * new_size);
679 /* we disable GC because we could lose some disappearing link updates */
681 memcpy (entries, handles->entries, sizeof (gpointer) * handles->size);
682 memset (entries + handles->size, 0, sizeof (gpointer) * handles->size);
683 memcpy (domain_ids, handles->domain_ids, sizeof (guint16) * handles->size);
684 for (i = 0; i < handles->size; ++i) {
685 MonoObject *obj = mono_gc_weak_link_get (&(handles->entries [i]));
686 if (handles->entries [i])
687 mono_gc_weak_link_remove (&(handles->entries [i]));
688 /*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]);*/
690 mono_gc_weak_link_add (&(entries [i]), obj, track);
693 g_free (handles->entries);
694 g_free (handles->domain_ids);
695 handles->entries = entries;
696 handles->domain_ids = domain_ids;
700 /* set i and slot to the next free position */
702 slot = (handles->size + 1) / 32;
703 handles->slot_hint = handles->size + 1;
704 handles->size = new_size;
706 handles->bitmap [slot] |= 1 << i;
707 slot = slot * 32 + i;
708 handles->entries [slot] = obj;
709 if (handles->type <= HANDLE_WEAK_TRACK) {
710 /*FIXME, what to use when obj == null?*/
711 handles->domain_ids [slot] = (obj ? mono_object_get_domain (obj) : mono_domain_get ())->domain_id;
713 mono_gc_weak_link_add (&(handles->entries [slot]), obj, track);
716 mono_perfcounters->gc_num_handles++;
717 unlock_handles (handles);
718 /*g_print ("allocated entry %d of type %d to object %p (in slot: %p)\n", slot, handles->type, obj, handles->entries [slot]);*/
719 res = (slot << 3) | (handles->type + 1);
720 mono_profiler_gc_handle (MONO_PROFILER_GC_HANDLE_CREATED, handles->type, res, obj);
726 * @obj: managed object to get a handle for
727 * @pinned: whether the object should be pinned
729 * This returns a handle that wraps the object, this is used to keep a
730 * reference to a managed object from the unmanaged world and preventing the
731 * object from being disposed.
733 * If @pinned is false the address of the object can not be obtained, if it is
734 * true the address of the object can be obtained. This will also pin the
735 * object so it will not be possible by a moving garbage collector to move the
738 * Returns: a handle that can be used to access the object from
742 mono_gchandle_new (MonoObject *obj, gboolean pinned)
744 return alloc_handle (&gc_handles [pinned? HANDLE_PINNED: HANDLE_NORMAL], obj, FALSE);
748 * mono_gchandle_new_weakref:
749 * @obj: managed object to get a handle for
750 * @pinned: whether the object should be pinned
752 * This returns a weak handle that wraps the object, this is used to
753 * keep a reference to a managed object from the unmanaged world.
754 * Unlike the mono_gchandle_new the object can be reclaimed by the
755 * garbage collector. In this case the value of the GCHandle will be
758 * If @pinned is false the address of the object can not be obtained, if it is
759 * true the address of the object can be obtained. This will also pin the
760 * object so it will not be possible by a moving garbage collector to move the
763 * Returns: a handle that can be used to access the object from
767 mono_gchandle_new_weakref (MonoObject *obj, gboolean track_resurrection)
769 guint32 handle = alloc_handle (&gc_handles [track_resurrection? HANDLE_WEAK_TRACK: HANDLE_WEAK], obj, track_resurrection);
772 if (track_resurrection)
773 mono_gc_add_weak_track_handle (obj, handle);
780 mono_gchandle_get_type (guint32 gchandle)
782 guint type = (gchandle & 7) - 1;
788 * mono_gchandle_get_target:
789 * @gchandle: a GCHandle's handle.
791 * The handle was previously created by calling mono_gchandle_new or
792 * mono_gchandle_new_weakref.
794 * Returns a pointer to the MonoObject represented by the handle or
795 * NULL for a collected object if using a weakref handle.
798 mono_gchandle_get_target (guint32 gchandle)
800 guint slot = gchandle >> 3;
801 guint type = (gchandle & 7) - 1;
802 HandleData *handles = &gc_handles [type];
803 MonoObject *obj = NULL;
806 lock_handles (handles);
807 if (slot < handles->size && (handles->bitmap [slot / 32] & (1 << (slot % 32)))) {
808 if (handles->type <= HANDLE_WEAK_TRACK) {
809 obj = mono_gc_weak_link_get (&handles->entries [slot]);
811 obj = handles->entries [slot];
814 /* print a warning? */
816 unlock_handles (handles);
817 /*g_print ("get target of entry %d of type %d: %p\n", slot, handles->type, obj);*/
822 mono_gchandle_set_target (guint32 gchandle, MonoObject *obj)
824 guint slot = gchandle >> 3;
825 guint type = (gchandle & 7) - 1;
826 HandleData *handles = &gc_handles [type];
827 MonoObject *old_obj = NULL;
831 lock_handles (handles);
832 if (slot < handles->size && (handles->bitmap [slot / 32] & (1 << (slot % 32)))) {
833 if (handles->type <= HANDLE_WEAK_TRACK) {
834 old_obj = handles->entries [slot];
835 if (handles->entries [slot])
836 mono_gc_weak_link_remove (&handles->entries [slot]);
838 mono_gc_weak_link_add (&handles->entries [slot], obj, handles->type == HANDLE_WEAK_TRACK);
839 /*FIXME, what to use when obj == null?*/
840 handles->domain_ids [slot] = (obj ? mono_object_get_domain (obj) : mono_domain_get ())->domain_id;
842 handles->entries [slot] = obj;
845 /* print a warning? */
847 /*g_print ("changed entry %d of type %d to object %p (in slot: %p)\n", slot, handles->type, obj, handles->entries [slot]);*/
848 unlock_handles (handles);
851 if (type == HANDLE_WEAK_TRACK)
852 mono_gc_change_weak_track_handle (old_obj, obj, gchandle);
857 * mono_gchandle_is_in_domain:
858 * @gchandle: a GCHandle's handle.
859 * @domain: An application domain.
861 * Returns: true if the object wrapped by the @gchandle belongs to the specific @domain.
864 mono_gchandle_is_in_domain (guint32 gchandle, MonoDomain *domain)
866 guint slot = gchandle >> 3;
867 guint type = (gchandle & 7) - 1;
868 HandleData *handles = &gc_handles [type];
869 gboolean result = FALSE;
872 lock_handles (handles);
873 if (slot < handles->size && (handles->bitmap [slot / 32] & (1 << (slot % 32)))) {
874 if (handles->type <= HANDLE_WEAK_TRACK) {
875 result = domain->domain_id == handles->domain_ids [slot];
878 obj = handles->entries [slot];
882 result = domain == mono_object_domain (obj);
885 /* print a warning? */
887 unlock_handles (handles);
892 * mono_gchandle_free:
893 * @gchandle: a GCHandle's handle.
895 * Frees the @gchandle handle. If there are no outstanding
896 * references, the garbage collector can reclaim the memory of the
900 mono_gchandle_free (guint32 gchandle)
902 guint slot = gchandle >> 3;
903 guint type = (gchandle & 7) - 1;
904 HandleData *handles = &gc_handles [type];
908 if (type == HANDLE_WEAK_TRACK)
909 mono_gc_remove_weak_track_handle (gchandle);
912 lock_handles (handles);
913 if (slot < handles->size && (handles->bitmap [slot / 32] & (1 << (slot % 32)))) {
914 if (handles->type <= HANDLE_WEAK_TRACK) {
915 if (handles->entries [slot])
916 mono_gc_weak_link_remove (&handles->entries [slot]);
918 handles->entries [slot] = NULL;
920 handles->bitmap [slot / 32] &= ~(1 << (slot % 32));
922 /* print a warning? */
924 mono_perfcounters->gc_num_handles--;
925 /*g_print ("freed entry %d of type %d\n", slot, handles->type);*/
926 unlock_handles (handles);
927 mono_profiler_gc_handle (MONO_PROFILER_GC_HANDLE_DESTROYED, handles->type, gchandle, NULL);
931 * mono_gchandle_free_domain:
932 * @domain: domain that is unloading
934 * Function used internally to cleanup any GC handle for objects belonging
935 * to the specified domain during appdomain unload.
938 mono_gchandle_free_domain (MonoDomain *domain)
942 for (type = 0; type < 3; ++type) {
944 HandleData *handles = &gc_handles [type];
945 lock_handles (handles);
946 for (slot = 0; slot < handles->size; ++slot) {
947 if (!(handles->bitmap [slot / 32] & (1 << (slot % 32))))
949 if (type <= HANDLE_WEAK_TRACK) {
950 if (domain->domain_id == handles->domain_ids [slot]) {
951 handles->bitmap [slot / 32] &= ~(1 << (slot % 32));
952 if (handles->entries [slot])
953 mono_gc_weak_link_remove (&handles->entries [slot]);
956 if (handles->entries [slot] && mono_object_domain (handles->entries [slot]) == domain) {
957 handles->bitmap [slot / 32] &= ~(1 << (slot % 32));
958 handles->entries [slot] = NULL;
962 unlock_handles (handles);
968 GCHandle_CheckCurrentDomain (guint32 gchandle)
970 return mono_gchandle_is_in_domain (gchandle, mono_domain_get ());
975 #ifdef MONO_HAS_SEMAPHORES
976 static MonoSemType finalizer_sem;
978 static HANDLE finalizer_event;
979 static volatile gboolean finished=FALSE;
982 mono_gc_finalize_notify (void)
985 g_message ( "%s: prodding finalizer", __func__);
988 #ifdef MONO_HAS_SEMAPHORES
989 MONO_SEM_POST (&finalizer_sem);
991 SetEvent (finalizer_event);
998 collect_objects (gpointer key, gpointer value, gpointer user_data)
1000 GPtrArray *arr = (GPtrArray*)user_data;
1001 g_ptr_array_add (arr, key);
1007 * finalize_domain_objects:
1009 * Run the finalizers of all finalizable objects in req->domain.
1012 finalize_domain_objects (DomainFinalizationReq *req)
1014 MonoDomain *domain = req->domain;
1016 #ifdef HAVE_BOEHM_GC
1017 while (g_hash_table_size (domain->finalizable_objects_hash) > 0) {
1021 * Since the domain is unloading, nobody is allowed to put
1022 * new entries into the hash table. But finalize_object might
1023 * remove entries from the hash table, so we make a copy.
1025 objs = g_ptr_array_new ();
1026 g_hash_table_foreach (domain->finalizable_objects_hash, collect_objects, objs);
1027 /* printf ("FINALIZING %d OBJECTS.\n", objs->len); */
1029 for (i = 0; i < objs->len; ++i) {
1030 MonoObject *o = (MonoObject*)g_ptr_array_index (objs, i);
1031 /* FIXME: Avoid finalizing threads, etc */
1032 mono_gc_run_finalize (o, 0);
1035 g_ptr_array_free (objs, TRUE);
1037 #elif defined(HAVE_SGEN_GC)
1038 #define NUM_FOBJECTS 64
1039 MonoObject *to_finalize [NUM_FOBJECTS];
1041 while ((count = mono_gc_finalizers_for_domain (domain, to_finalize, NUM_FOBJECTS))) {
1043 for (i = 0; i < count; ++i) {
1044 mono_gc_run_finalize (to_finalize [i], 0);
1049 /* Process finalizers which are already in the queue */
1050 mono_gc_invoke_finalizers ();
1052 /* cleanup the reference queue */
1053 reference_queue_clear_for_domain (domain);
1055 /* printf ("DONE.\n"); */
1056 SetEvent (req->done_event);
1058 /* The event is closed in mono_domain_finalize if we get here */
1063 finalizer_thread (gpointer unused)
1066 /* Wait to be notified that there's at least one
1070 g_assert (mono_domain_get () == mono_get_root_domain ());
1072 /* An alertable wait is required so this thread can be suspended on windows */
1073 #ifdef MONO_HAS_SEMAPHORES
1074 MONO_SEM_WAIT_ALERTABLE (&finalizer_sem, TRUE);
1076 WaitForSingleObjectEx (finalizer_event, INFINITE, TRUE);
1079 mono_threads_perform_thread_dump ();
1081 mono_console_handle_async_ops ();
1083 #ifndef DISABLE_ATTACH
1084 mono_attach_maybe_start ();
1087 if (domains_to_finalize) {
1088 mono_finalizer_lock ();
1089 if (domains_to_finalize) {
1090 DomainFinalizationReq *req = domains_to_finalize->data;
1091 domains_to_finalize = g_slist_remove (domains_to_finalize, req);
1092 mono_finalizer_unlock ();
1094 finalize_domain_objects (req);
1096 mono_finalizer_unlock ();
1100 /* If finished == TRUE, mono_gc_cleanup has been called (from mono_runtime_cleanup),
1101 * before the domain is unloaded.
1103 mono_gc_invoke_finalizers ();
1105 reference_queue_proccess_all ();
1107 SetEvent (pending_done_event);
1110 SetEvent (shutdown_event);
1117 InitializeCriticalSection (&handle_section);
1118 InitializeCriticalSection (&allocator_section);
1120 InitializeCriticalSection (&finalizer_mutex);
1121 InitializeCriticalSection (&reference_queue_mutex);
1123 MONO_GC_REGISTER_ROOT_FIXED (gc_handles [HANDLE_NORMAL].entries);
1124 MONO_GC_REGISTER_ROOT_FIXED (gc_handles [HANDLE_PINNED].entries);
1126 mono_gc_base_init ();
1128 if (mono_gc_is_disabled ()) {
1133 finalizer_event = CreateEvent (NULL, FALSE, FALSE, NULL);
1134 pending_done_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1135 shutdown_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1136 if (finalizer_event == NULL || pending_done_event == NULL || shutdown_event == NULL) {
1137 g_assert_not_reached ();
1139 #ifdef MONO_HAS_SEMAPHORES
1140 MONO_SEM_INIT (&finalizer_sem, 0);
1143 gc_thread = mono_thread_create_internal (mono_domain_get (), finalizer_thread, NULL, FALSE, 0);
1144 ves_icall_System_Threading_Thread_SetName_internal (gc_thread, mono_string_new (mono_domain_get (), "Finalizer"));
1148 mono_gc_cleanup (void)
1151 g_message ("%s: cleaning up finalizer", __func__);
1155 ResetEvent (shutdown_event);
1157 if (mono_thread_internal_current () != gc_thread) {
1158 mono_gc_finalize_notify ();
1159 /* Finishing the finalizer thread, so wait a little bit... */
1160 /* MS seems to wait for about 2 seconds */
1161 if (WaitForSingleObjectEx (shutdown_event, 2000, FALSE) == WAIT_TIMEOUT) {
1164 /* Set a flag which the finalizer thread can check */
1165 suspend_finalizers = TRUE;
1167 /* Try to abort the thread, in the hope that it is running managed code */
1168 mono_thread_internal_stop (gc_thread);
1170 /* Wait for it to stop */
1171 ret = WaitForSingleObjectEx (gc_thread->handle, 100, TRUE);
1173 if (ret == WAIT_TIMEOUT) {
1175 * The finalizer thread refused to die. There is not much we
1176 * can do here, since the runtime is shutting down so the
1177 * state the finalizer thread depends on will vanish.
1179 g_warning ("Shutting down finalizer thread timed out.");
1182 * FIXME: On unix, when the above wait returns, the thread
1183 * might still be running io-layer code, or pthreads code.
1191 #ifdef HAVE_BOEHM_GC
1192 GC_finalizer_notifier = NULL;
1196 mono_reference_queue_cleanup ();
1198 DeleteCriticalSection (&handle_section);
1199 DeleteCriticalSection (&allocator_section);
1200 DeleteCriticalSection (&finalizer_mutex);
1201 DeleteCriticalSection (&reference_queue_mutex);
1206 /* Null GC dummy functions */
1208 mono_gc_finalize_notify (void)
1212 void mono_gc_init (void)
1214 InitializeCriticalSection (&handle_section);
1217 void mono_gc_cleanup (void)
1224 mono_gc_is_finalizer_internal_thread (MonoInternalThread *thread)
1226 return thread == gc_thread;
1230 * mono_gc_is_finalizer_thread:
1231 * @thread: the thread to test.
1233 * In Mono objects are finalized asynchronously on a separate thread.
1234 * This routine tests whether the @thread argument represents the
1235 * finalization thread.
1237 * Returns true if @thread is the finalization thread.
1240 mono_gc_is_finalizer_thread (MonoThread *thread)
1242 return mono_gc_is_finalizer_internal_thread (thread->internal_thread);
1245 #if defined(__MACH__)
1246 static pthread_t mach_exception_thread;
1249 mono_gc_register_mach_exception_thread (pthread_t thread)
1251 mach_exception_thread = thread;
1255 mono_gc_get_mach_exception_thread (void)
1257 return mach_exception_thread;
1262 * mono_gc_parse_environment_string_extract_number:
1264 * @str: points to the first digit of the number
1265 * @out: pointer to the variable that will receive the value
1267 * Tries to extract a number from the passed string, taking in to account m, k
1270 * Returns true if passing was successful
1273 mono_gc_parse_environment_string_extract_number (const char *str, glong *out)
1276 int len = strlen (str), shift = 0;
1278 gboolean is_suffix = FALSE;
1284 suffix = str [len - 1];
1299 if (!isdigit (suffix))
1305 val = strtol (str, &endptr, 10);
1307 if ((errno == ERANGE && (val == LONG_MAX || val == LONG_MIN))
1308 || (errno != 0 && val == 0) || (endptr == str))
1312 if (*(endptr + 1)) /* Invalid string. */
1321 #ifndef HAVE_SGEN_GC
1323 mono_gc_alloc_mature (MonoVTable *vtable)
1325 return mono_object_new_specific (vtable);
1330 static MonoReferenceQueue *ref_queues;
1333 ref_list_remove_element (RefQueueEntry **prev, RefQueueEntry *element)
1336 /* Guard if head is changed concurrently. */
1337 while (*prev != element)
1338 prev = &(*prev)->next;
1339 } while (prev && InterlockedCompareExchangePointer ((void*)prev, element->next, element) != element);
1343 ref_list_push (RefQueueEntry **head, RefQueueEntry *value)
1345 RefQueueEntry *current;
1348 value->next = current;
1349 STORE_STORE_FENCE; /*Must make sure the previous store is visible before the CAS. */
1350 } while (InterlockedCompareExchangePointer ((void*)head, value, current) != current);
1354 reference_queue_proccess (MonoReferenceQueue *queue)
1356 RefQueueEntry **iter = &queue->queue;
1357 RefQueueEntry *entry;
1358 while ((entry = *iter)) {
1360 if (queue->should_be_deleted || !mono_gc_weak_link_get (&entry->dis_link)) {
1361 mono_gc_weak_link_remove (&entry->dis_link);
1363 if (queue->should_be_deleted || !mono_gchandle_get_target (entry->gchandle)) {
1364 mono_gchandle_free ((guint32)entry->gchandle);
1366 ref_list_remove_element (iter, entry);
1367 queue->callback (entry->user_data);
1370 iter = &entry->next;
1376 reference_queue_proccess_all (void)
1378 MonoReferenceQueue **iter;
1379 MonoReferenceQueue *queue = ref_queues;
1380 for (; queue; queue = queue->next)
1381 reference_queue_proccess (queue);
1384 EnterCriticalSection (&reference_queue_mutex);
1385 for (iter = &ref_queues; *iter;) {
1387 if (!queue->should_be_deleted) {
1388 iter = &queue->next;
1392 LeaveCriticalSection (&reference_queue_mutex);
1393 reference_queue_proccess (queue);
1396 *iter = queue->next;
1399 LeaveCriticalSection (&reference_queue_mutex);
1403 mono_reference_queue_cleanup (void)
1405 MonoReferenceQueue *queue = ref_queues;
1406 for (; queue; queue = queue->next)
1407 queue->should_be_deleted = TRUE;
1408 reference_queue_proccess_all ();
1412 reference_queue_clear_for_domain (MonoDomain *domain)
1414 MonoReferenceQueue *queue = ref_queues;
1415 for (; queue; queue = queue->next) {
1416 RefQueueEntry **iter = &queue->queue;
1417 RefQueueEntry *entry;
1418 while ((entry = *iter)) {
1421 obj = mono_gc_weak_link_get (&entry->dis_link);
1422 if (obj && mono_object_domain (obj) == domain) {
1423 mono_gc_weak_link_remove (&entry->dis_link);
1425 obj = mono_gchandle_get_target (entry->gchandle);
1426 if (obj && mono_object_domain (obj) == domain) {
1427 mono_gchandle_free ((guint32)entry->gchandle);
1429 ref_list_remove_element (iter, entry);
1430 queue->callback (entry->user_data);
1433 iter = &entry->next;
1439 * mono_gc_reference_queue_new:
1440 * @callback callback used when processing dead entries.
1442 * Create a new reference queue used to process collected objects.
1443 * A reference queue let you queue a pair (managed object, user data)
1444 * using the mono_gc_reference_queue_add method.
1446 * Once the managed object is collected @callback will be called
1447 * in the finalizer thread with 'user data' as argument.
1449 * The callback is called without any locks held.
1452 mono_gc_reference_queue_new (mono_reference_queue_callback callback)
1454 MonoReferenceQueue *res = g_new0 (MonoReferenceQueue, 1);
1455 res->callback = callback;
1457 EnterCriticalSection (&reference_queue_mutex);
1458 res->next = ref_queues;
1460 LeaveCriticalSection (&reference_queue_mutex);
1466 * mono_gc_reference_queue_add:
1467 * @queue the queue to add the reference to.
1468 * @obj the object to be watched for collection
1469 * @user_data parameter to be passed to the queue callback
1471 * Queue an object to be watched for collection, when the @obj is
1472 * collected, the callback that was registered for the @queue will
1473 * be invoked with the @obj and @user_data arguments.
1475 * @returns false if the queue is scheduled to be freed.
1478 mono_gc_reference_queue_add (MonoReferenceQueue *queue, MonoObject *obj, void *user_data)
1480 RefQueueEntry *entry;
1481 if (queue->should_be_deleted)
1484 entry = g_new0 (RefQueueEntry, 1);
1485 entry->user_data = user_data;
1488 mono_gc_weak_link_add (&entry->dis_link, obj, TRUE);
1490 entry->gchandle = mono_gchandle_new_weakref (obj, TRUE);
1491 mono_object_register_finalizer (obj);
1494 ref_list_push (&queue->queue, entry);
1499 * mono_gc_reference_queue_free:
1500 * @queue the queue that should be deleted.
1502 * This operation signals that @queue should be deleted. This operation is deferred
1503 * as it happens on the finalizer thread.
1505 * After this call, no further objects can be queued. It's the responsibility of the
1506 * caller to make sure that no further attempt to access queue will be made.
1509 mono_gc_reference_queue_free (MonoReferenceQueue *queue)
1511 queue->should_be_deleted = TRUE;
1514 #define ptr_mask ((sizeof (void*) - 1))
1515 #define _toi(ptr) ((size_t)ptr)
1516 #define unaligned_bytes(ptr) (_toi(ptr) & ptr_mask)
1517 #define align_down(ptr) ((void*)(_toi(ptr) & ~ptr_mask))
1518 #define align_up(ptr) ((void*) ((_toi(ptr) + ptr_mask) & ~ptr_mask))
1522 * @dest: address to start to clear
1523 * @size: size of the region to clear
1525 * Zero @size bytes starting at @dest.
1527 * Use this to zero memory that can hold managed pointers.
1529 * FIXME borrow faster code from some BSD libc or bionic
1532 mono_gc_bzero (void *dest, size_t size)
1534 char *p = (char*)dest;
1535 char *end = p + size;
1536 char *align_end = align_up (p);
1539 while (p < align_end)
1542 word_end = align_down (end);
1543 while (p < word_end) {
1544 *((void**)p) = NULL;
1545 p += sizeof (void*);
1555 * @dest: destination of the move
1557 * @size: size of the block to move
1559 * Move @size bytes from @src to @dest.
1560 * size MUST be a multiple of sizeof (gpointer)
1562 * FIXME borrow faster code from some BSD libc or bionic
1565 mono_gc_memmove (void *dest, const void *src, size_t size)
1568 * If dest and src are differently aligned with respect to
1569 * pointer size then it makes no sense to do aligned copying.
1570 * In fact, we would end up with unaligned loads which is
1571 * incorrect on some architectures.
1573 if ((char*)dest - (char*)align_down (dest) != (char*)src - (char*)align_down (src)) {
1574 memmove (dest, src, size);
1579 * A bit of explanation on why we align only dest before doing word copies.
1580 * Pointers to managed objects must always be stored in word aligned addresses, so
1581 * even if dest is misaligned, src will be by the same amount - this ensure proper atomicity of reads.
1583 if (dest > src && ((size_t)((char*)dest - (char*)src) < size)) {
1584 char *p = (char*)dest + size;
1585 char *s = (char*)src + size;
1586 char *start = (char*)dest;
1587 char *align_end = MAX((char*)dest, (char*)align_down (p));
1590 while (p > align_end)
1593 word_start = align_up (start);
1594 while (p > word_start) {
1595 p -= sizeof (void*);
1596 s -= sizeof (void*);
1597 *((void**)p) = *((void**)s);
1603 char *p = (char*)dest;
1604 char *s = (char*)src;
1605 char *end = p + size;
1606 char *align_end = MIN ((char*)end, (char*)align_up (p));
1609 while (p < align_end)
1612 word_end = align_down (end);
1613 while (p < word_end) {
1614 *((void**)p) = *((void**)s);
1615 p += sizeof (void*);
1616 s += sizeof (void*);