2 * metadata/gc.c: GC icalls.
4 * Author: Paolo Molaro <lupus@ximian.com>
6 * (C) 2002 Ximian, Inc.
13 #include <mono/metadata/gc-internal.h>
14 #include <mono/metadata/mono-gc.h>
15 #include <mono/metadata/threads.h>
16 #include <mono/metadata/tabledefs.h>
17 #include <mono/metadata/exception.h>
18 #include <mono/metadata/profiler-private.h>
19 #include <mono/metadata/domain-internals.h>
20 #include <mono/metadata/class-internals.h>
21 #include <mono/metadata/mono-mlist.h>
22 #include <mono/metadata/threadpool.h>
23 #include <mono/utils/mono-logger.h>
24 #include <mono/metadata/gc-internal.h>
25 #include <mono/metadata/marshal.h> /* for mono_delegate_free_ftnptr () */
26 #include <mono/metadata/attach.h>
28 #include <semaphore.h>
29 /* we do this only for known working systems (OSX for example
30 * has the header and functions, but they don't work at all): in other cases
31 * we fall back to the io-layer slightly slower and signal-unsafe Event.
34 #define USE_POSIX_SEM 1
38 #ifndef PLATFORM_WIN32
42 typedef struct DomainFinalizationReq {
45 } DomainFinalizationReq;
47 #ifdef PLATFORM_WINCE /* FIXME: add accessors to gc.dll API */
48 extern void (*__imp_GC_finalizer_notifier)(void);
49 #define GC_finalizer_notifier __imp_GC_finalizer_notifier
50 extern int __imp_GC_finalize_on_demand;
51 #define GC_finalize_on_demand __imp_GC_finalize_on_demand
54 static gboolean gc_disabled = FALSE;
56 static gboolean finalizing_root_domain = FALSE;
58 #define mono_finalizer_lock() EnterCriticalSection (&finalizer_mutex)
59 #define mono_finalizer_unlock() LeaveCriticalSection (&finalizer_mutex)
60 static CRITICAL_SECTION finalizer_mutex;
62 static GSList *domains_to_finalize= NULL;
63 static MonoMList *threads_to_finalize = NULL;
65 static MonoThread *gc_thread;
67 static void object_register_finalizer (MonoObject *obj, void (*callback)(void *, void*));
70 static HANDLE pending_done_event;
71 static HANDLE shutdown_event;
72 static HANDLE thread_started_event;
76 add_thread_to_finalize (MonoThread *thread)
78 mono_finalizer_lock ();
79 if (!threads_to_finalize)
80 MONO_GC_REGISTER_ROOT (threads_to_finalize);
81 threads_to_finalize = mono_mlist_append (threads_to_finalize, (MonoObject*)thread);
82 mono_finalizer_unlock ();
85 static gboolean suspend_finalizers = FALSE;
87 * actually, we might want to queue the finalize requests in a separate thread,
88 * but we need to be careful about the execution domain of the thread...
91 run_finalize (void *obj, void *data)
93 MonoObject *exc = NULL;
98 MonoMethod* finalizer = NULL;
99 o = (MonoObject*)((char*)obj + GPOINTER_TO_UINT (data));
101 if (suspend_finalizers)
105 mono_domain_lock (o->vtable->domain);
107 o2 = g_hash_table_lookup (o->vtable->domain->finalizable_objects_hash, o);
109 mono_domain_unlock (o->vtable->domain);
112 /* Already finalized somehow */
116 /* make sure the finalizer is not called again if the object is resurrected */
117 object_register_finalizer (obj, NULL);
119 if (o->vtable->klass == mono_get_thread_class ()) {
120 MonoThread *t = (MonoThread*)o;
122 if (mono_gc_is_finalizer_thread (t))
123 /* Avoid finalizing ourselves */
126 if (t->threadpool_thread && finalizing_root_domain) {
127 /* Don't finalize threadpool threads when
128 shutting down - they're finalized when the
129 threadpool shuts down. */
130 add_thread_to_finalize (t);
135 if (mono_runtime_get_no_exec ())
138 /* speedup later... and use a timeout */
139 /* g_print ("Finalize run on %p %s.%s\n", o, mono_object_class (o)->name_space, mono_object_class (o)->name); */
141 /* Use _internal here, since this thread can enter a doomed appdomain */
142 mono_domain_set_internal (mono_object_domain (o));
144 /* delegates that have a native function pointer allocated are
145 * registered for finalization, but they don't have a Finalize
146 * method, because in most cases it's not needed and it's just a waste.
148 if (o->vtable->klass->delegate) {
149 MonoDelegate* del = (MonoDelegate*)o;
150 if (del->delegate_trampoline)
151 mono_delegate_free_ftnptr ((MonoDelegate*)o);
155 finalizer = mono_class_get_finalizer (o->vtable->klass);
157 /* If object has a CCW but has no finalizer, it was only
158 * registered for finalization in order to free the CCW.
159 * Else it needs the regular finalizer run.
160 * FIXME: what to do about ressurection and suppression
161 * of finalizer on object with CCW.
163 if (mono_marshal_free_ccw (o) && !finalizer)
166 mono_runtime_invoke (finalizer, o, NULL, &exc);
169 /* fixme: do something useful */
174 mono_gc_finalize_threadpool_threads (void)
176 while (threads_to_finalize) {
177 MonoThread *thread = (MonoThread*) mono_mlist_get_data (threads_to_finalize);
179 /* Force finalization of the thread. */
180 thread->threadpool_thread = FALSE;
181 mono_object_register_finalizer ((MonoObject*)thread);
183 run_finalize (thread, NULL);
185 threads_to_finalize = mono_mlist_next (threads_to_finalize);
190 mono_gc_out_of_memory (size_t size)
193 * we could allocate at program startup some memory that we could release
194 * back to the system at this point if we're really low on memory (ie, size is
195 * lower than the memory we set apart)
197 mono_raise_exception (mono_domain_get ()->out_of_memory_ex);
203 * Some of our objects may point to a different address than the address returned by GC_malloc()
204 * (because of the GetHashCode hack), but we need to pass the real address to register_finalizer.
205 * This also means that in the callback we need to adjust the pointer to get back the real
207 * We also need to be consistent in the use of the GC_debug* variants of malloc and register_finalizer,
208 * since that, too, can cause the underlying pointer to be offset.
211 object_register_finalizer (MonoObject *obj, void (*callback)(void *, void*))
215 MonoDomain *domain = obj->vtable->domain;
218 /* This assertion is not valid when GC_DEBUG is defined */
219 g_assert (GC_base (obj) == (char*)obj - offset);
222 if (mono_domain_is_unloading (domain) && (callback != NULL))
224 * Can't register finalizers in a dying appdomain, since they
225 * could be invoked after the appdomain has been unloaded.
229 mono_domain_lock (domain);
232 g_hash_table_insert (domain->finalizable_objects_hash, obj, obj);
234 g_hash_table_remove (domain->finalizable_objects_hash, obj);
236 mono_domain_unlock (domain);
238 GC_REGISTER_FINALIZER_NO_ORDER ((char*)obj - offset, callback, GUINT_TO_POINTER (offset), NULL, NULL);
239 #elif defined(HAVE_SGEN_GC)
240 mono_gc_register_for_finalization (obj, callback);
245 * mono_object_register_finalizer:
246 * @obj: object to register
248 * Records that object @obj has a finalizer, this will call the
249 * Finalize method when the garbage collector disposes the object.
253 mono_object_register_finalizer (MonoObject *obj)
255 /* g_print ("Registered finalizer on %p %s.%s\n", obj, mono_object_class (obj)->name_space, mono_object_class (obj)->name); */
256 object_register_finalizer (obj, run_finalize);
260 * mono_domain_finalize:
261 * @domain: the domain to finalize
262 * @timeout: msects to wait for the finalization to complete, -1 to wait indefinitely
264 * Request finalization of all finalizable objects inside @domain. Wait
265 * @timeout msecs for the finalization to complete.
267 * Returns: TRUE if succeeded, FALSE if there was a timeout
271 mono_domain_finalize (MonoDomain *domain, guint32 timeout)
273 DomainFinalizationReq *req;
277 if (mono_thread_current () == gc_thread)
278 /* We are called from inside a finalizer, not much we can do here */
282 * No need to create another thread 'cause the finalizer thread
283 * is still working and will take care of running the finalizers
290 mono_gc_collect (mono_gc_max_generation ());
292 done_event = CreateEvent (NULL, TRUE, FALSE, NULL);
293 if (done_event == NULL) {
297 req = g_new0 (DomainFinalizationReq, 1);
298 req->domain = domain;
299 req->done_event = done_event;
301 if (domain == mono_get_root_domain ())
302 finalizing_root_domain = TRUE;
304 mono_finalizer_lock ();
306 domains_to_finalize = g_slist_append (domains_to_finalize, req);
308 mono_finalizer_unlock ();
310 /* Tell the finalizer thread to finalize this appdomain */
311 mono_gc_finalize_notify ();
316 res = WaitForSingleObjectEx (done_event, timeout, TRUE);
318 /* printf ("WAIT RES: %d.\n", res); */
319 if (res == WAIT_TIMEOUT) {
320 /* We leak the handle here */
324 CloseHandle (done_event);
326 if (domain == mono_get_root_domain ()) {
327 mono_thread_pool_cleanup ();
328 mono_gc_finalize_threadpool_threads ();
333 /* We don't support domain finalization without a GC */
339 ves_icall_System_GC_InternalCollect (int generation)
341 mono_gc_collect (generation);
345 ves_icall_System_GC_GetTotalMemory (MonoBoolean forceCollection)
350 mono_gc_collect (mono_gc_max_generation ());
351 return mono_gc_get_used_size ();
355 ves_icall_System_GC_KeepAlive (MonoObject *obj)
365 ves_icall_System_GC_ReRegisterForFinalize (MonoObject *obj)
369 object_register_finalizer (obj, run_finalize);
373 ves_icall_System_GC_SuppressFinalize (MonoObject *obj)
377 /* delegates have no finalizers, but we register them to deal with the
378 * unmanaged->managed trampoline. We don't let the user suppress it
379 * otherwise we'd leak it.
381 if (obj->vtable->klass->delegate)
384 /* FIXME: Need to handle case where obj has COM Callable Wrapper
385 * generated for it that needs cleaned up, but user wants to suppress
386 * their derived object finalizer. */
388 object_register_finalizer (obj, NULL);
392 ves_icall_System_GC_WaitForPendingFinalizers (void)
395 if (!mono_gc_pending_finalizers ())
398 if (mono_thread_current () == gc_thread)
399 /* Avoid deadlocks */
402 ResetEvent (pending_done_event);
403 mono_gc_finalize_notify ();
404 /* g_print ("Waiting for pending finalizers....\n"); */
405 WaitForSingleObjectEx (pending_done_event, INFINITE, TRUE);
406 /* g_print ("Done pending....\n"); */
410 #define mono_allocator_lock() EnterCriticalSection (&allocator_section)
411 #define mono_allocator_unlock() LeaveCriticalSection (&allocator_section)
412 static CRITICAL_SECTION allocator_section;
413 static CRITICAL_SECTION handle_section;
422 static void mono_gchandle_set_target (guint32 gchandle, MonoObject *obj);
424 static HandleType mono_gchandle_get_type (guint32 gchandle);
427 ves_icall_System_GCHandle_GetTarget (guint32 handle)
429 return mono_gchandle_get_target (handle);
433 * if type == -1, change the target of the handle, otherwise allocate a new handle.
436 ves_icall_System_GCHandle_GetTargetHandle (MonoObject *obj, guint32 handle, gint32 type)
439 mono_gchandle_set_target (handle, obj);
440 /* the handle doesn't change */
445 return mono_gchandle_new_weakref (obj, FALSE);
446 case HANDLE_WEAK_TRACK:
447 return mono_gchandle_new_weakref (obj, TRUE);
449 return mono_gchandle_new (obj, FALSE);
451 return mono_gchandle_new (obj, TRUE);
453 g_assert_not_reached ();
459 ves_icall_System_GCHandle_FreeHandle (guint32 handle)
461 mono_gchandle_free (handle);
465 ves_icall_System_GCHandle_GetAddrOfPinnedObject (guint32 handle)
469 if (mono_gchandle_get_type (handle) != HANDLE_PINNED)
471 obj = mono_gchandle_get_target (handle);
473 MonoClass *klass = mono_object_class (obj);
474 if (klass == mono_defaults.string_class) {
475 return mono_string_chars ((MonoString*)obj);
476 } else if (klass->rank) {
477 return mono_array_addr ((MonoArray*)obj, char, 0);
479 /* the C# code will check and throw the exception */
480 /* FIXME: missing !klass->blittable test, see bug #61134 */
481 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
483 return (char*)obj + sizeof (MonoObject);
494 guint slot_hint : 24; /* starting slot for search */
495 /* 2^16 appdomains should be enough for everyone (though I know I'll regret this in 20 years) */
496 /* we alloc this only for weak refs, since we can get the domain directly in the other cases */
500 /* weak and weak-track arrays will be allocated in malloc memory
502 static HandleData gc_handles [] = {
503 {NULL, NULL, 0, HANDLE_WEAK, 0},
504 {NULL, NULL, 0, HANDLE_WEAK_TRACK, 0},
505 {NULL, NULL, 0, HANDLE_NORMAL, 0},
506 {NULL, NULL, 0, HANDLE_PINNED, 0}
509 #define lock_handles(handles) EnterCriticalSection (&handle_section)
510 #define unlock_handles(handles) LeaveCriticalSection (&handle_section)
513 find_first_unset (guint32 bitmap)
516 for (i = 0; i < 32; ++i) {
517 if (!(bitmap & (1 << i)))
524 alloc_handle (HandleData *handles, MonoObject *obj)
527 lock_handles (handles);
528 if (!handles->size) {
530 if (handles->type > HANDLE_WEAK_TRACK) {
531 handles->entries = mono_gc_alloc_fixed (sizeof (gpointer) * handles->size, NULL);
533 handles->entries = g_malloc0 (sizeof (gpointer) * handles->size);
534 handles->domain_ids = g_malloc0 (sizeof (guint16) * handles->size);
536 handles->bitmap = g_malloc0 (handles->size / 8);
539 for (slot = handles->slot_hint; slot < handles->size / 32; ++slot) {
540 if (handles->bitmap [slot] != 0xffffffff) {
541 i = find_first_unset (handles->bitmap [slot]);
542 handles->slot_hint = slot;
546 if (i == -1 && handles->slot_hint != 0) {
547 for (slot = 0; slot < handles->slot_hint; ++slot) {
548 if (handles->bitmap [slot] != 0xffffffff) {
549 i = find_first_unset (handles->bitmap [slot]);
550 handles->slot_hint = slot;
557 guint32 new_size = handles->size * 2; /* always double: we memset to 0 based on this below */
559 /* resize and copy the bitmap */
560 new_bitmap = g_malloc0 (new_size / 8);
561 memcpy (new_bitmap, handles->bitmap, handles->size / 8);
562 g_free (handles->bitmap);
563 handles->bitmap = new_bitmap;
565 /* resize and copy the entries */
566 if (handles->type > HANDLE_WEAK_TRACK) {
568 entries = mono_gc_alloc_fixed (sizeof (gpointer) * new_size, NULL);
569 memcpy (entries, handles->entries, sizeof (gpointer) * handles->size);
570 handles->entries = entries;
574 domain_ids = g_malloc0 (sizeof (guint16) * new_size);
575 entries = g_malloc (sizeof (gpointer) * new_size);
576 /* we disable GC because we could lose some disappearing link updates */
578 memcpy (entries, handles->entries, sizeof (gpointer) * handles->size);
579 memset (entries + handles->size, 0, sizeof (gpointer) * handles->size);
580 memcpy (domain_ids, handles->domain_ids, sizeof (guint16) * handles->size);
581 for (i = 0; i < handles->size; ++i) {
582 MonoObject *obj = mono_gc_weak_link_get (&(handles->entries [i]));
583 if (handles->entries [i])
584 mono_gc_weak_link_remove (&(handles->entries [i]));
585 /*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]);*/
587 mono_gc_weak_link_add (&(entries [i]), obj);
590 g_free (handles->entries);
591 g_free (handles->domain_ids);
592 handles->entries = entries;
593 handles->domain_ids = domain_ids;
597 /* set i and slot to the next free position */
599 slot = (handles->size + 1) / 32;
600 handles->slot_hint = handles->size + 1;
601 handles->size = new_size;
603 handles->bitmap [slot] |= 1 << i;
604 slot = slot * 32 + i;
605 handles->entries [slot] = obj;
606 if (handles->type <= HANDLE_WEAK_TRACK) {
608 mono_gc_weak_link_add (&(handles->entries [slot]), obj);
611 mono_perfcounters->gc_num_handles++;
612 unlock_handles (handles);
613 /*g_print ("allocated entry %d of type %d to object %p (in slot: %p)\n", slot, handles->type, obj, handles->entries [slot]);*/
614 return (slot << 3) | (handles->type + 1);
619 * @obj: managed object to get a handle for
620 * @pinned: whether the object should be pinned
622 * This returns a handle that wraps the object, this is used to keep a
623 * reference to a managed object from the unmanaged world and preventing the
624 * object from being disposed.
626 * If @pinned is false the address of the object can not be obtained, if it is
627 * true the address of the object can be obtained. This will also pin the
628 * object so it will not be possible by a moving garbage collector to move the
631 * Returns: a handle that can be used to access the object from
635 mono_gchandle_new (MonoObject *obj, gboolean pinned)
637 return alloc_handle (&gc_handles [pinned? HANDLE_PINNED: HANDLE_NORMAL], obj);
641 * mono_gchandle_new_weakref:
642 * @obj: managed object to get a handle for
643 * @pinned: whether the object should be pinned
645 * This returns a weak handle that wraps the object, this is used to
646 * keep a reference to a managed object from the unmanaged world.
647 * Unlike the mono_gchandle_new the object can be reclaimed by the
648 * garbage collector. In this case the value of the GCHandle will be
651 * If @pinned is false the address of the object can not be obtained, if it is
652 * true the address of the object can be obtained. This will also pin the
653 * object so it will not be possible by a moving garbage collector to move the
656 * Returns: a handle that can be used to access the object from
660 mono_gchandle_new_weakref (MonoObject *obj, gboolean track_resurrection)
662 return alloc_handle (&gc_handles [track_resurrection? HANDLE_WEAK_TRACK: HANDLE_WEAK], obj);
666 mono_gchandle_get_type (guint32 gchandle)
668 guint type = (gchandle & 7) - 1;
674 * mono_gchandle_get_target:
675 * @gchandle: a GCHandle's handle.
677 * The handle was previously created by calling mono_gchandle_new or
678 * mono_gchandle_new_weakref.
680 * Returns a pointer to the MonoObject represented by the handle or
681 * NULL for a collected object if using a weakref handle.
684 mono_gchandle_get_target (guint32 gchandle)
686 guint slot = gchandle >> 3;
687 guint type = (gchandle & 7) - 1;
688 HandleData *handles = &gc_handles [type];
689 MonoObject *obj = NULL;
692 lock_handles (handles);
693 if (slot < handles->size && (handles->bitmap [slot / 32] & (1 << (slot % 32)))) {
694 if (handles->type <= HANDLE_WEAK_TRACK) {
695 obj = mono_gc_weak_link_get (&handles->entries [slot]);
697 obj = handles->entries [slot];
700 /* print a warning? */
702 unlock_handles (handles);
703 /*g_print ("get target of entry %d of type %d: %p\n", slot, handles->type, obj);*/
708 mono_gchandle_set_target (guint32 gchandle, MonoObject *obj)
710 guint slot = gchandle >> 3;
711 guint type = (gchandle & 7) - 1;
712 HandleData *handles = &gc_handles [type];
715 lock_handles (handles);
716 if (slot < handles->size && (handles->bitmap [slot / 32] & (1 << (slot % 32)))) {
717 if (handles->type <= HANDLE_WEAK_TRACK) {
718 if (handles->entries [slot])
719 mono_gc_weak_link_remove (&handles->entries [slot]);
721 mono_gc_weak_link_add (&handles->entries [slot], obj);
723 handles->entries [slot] = obj;
726 /* print a warning? */
728 /*g_print ("changed entry %d of type %d to object %p (in slot: %p)\n", slot, handles->type, obj, handles->entries [slot]);*/
729 unlock_handles (handles);
733 * mono_gchandle_is_in_domain:
734 * @gchandle: a GCHandle's handle.
735 * @domain: An application domain.
737 * Returns: true if the object wrapped by the @gchandle belongs to the specific @domain.
740 mono_gchandle_is_in_domain (guint32 gchandle, MonoDomain *domain)
742 guint slot = gchandle >> 3;
743 guint type = (gchandle & 7) - 1;
744 HandleData *handles = &gc_handles [type];
745 gboolean result = FALSE;
748 lock_handles (handles);
749 if (slot < handles->size && (handles->bitmap [slot / 32] & (1 << (slot % 32)))) {
750 if (handles->type <= HANDLE_WEAK_TRACK) {
751 result = domain->domain_id == handles->domain_ids [slot];
754 obj = handles->entries [slot];
758 result = domain == mono_object_domain (obj);
761 /* print a warning? */
763 unlock_handles (handles);
768 * mono_gchandle_free:
769 * @gchandle: a GCHandle's handle.
771 * Frees the @gchandle handle. If there are no outstanding
772 * references, the garbage collector can reclaim the memory of the
776 mono_gchandle_free (guint32 gchandle)
778 guint slot = gchandle >> 3;
779 guint type = (gchandle & 7) - 1;
780 HandleData *handles = &gc_handles [type];
783 lock_handles (handles);
784 if (slot < handles->size && (handles->bitmap [slot / 32] & (1 << (slot % 32)))) {
785 if (handles->type <= HANDLE_WEAK_TRACK) {
786 if (handles->entries [slot])
787 mono_gc_weak_link_remove (&handles->entries [slot]);
789 handles->entries [slot] = NULL;
791 handles->bitmap [slot / 32] &= ~(1 << (slot % 32));
793 /* print a warning? */
795 mono_perfcounters->gc_num_handles--;
796 /*g_print ("freed entry %d of type %d\n", slot, handles->type);*/
797 unlock_handles (handles);
801 * mono_gchandle_free_domain:
802 * @domain: domain that is unloading
804 * Function used internally to cleanup any GC handle for objects belonging
805 * to the specified domain during appdomain unload.
808 mono_gchandle_free_domain (MonoDomain *domain)
812 for (type = 0; type < 3; ++type) {
814 HandleData *handles = &gc_handles [type];
815 lock_handles (handles);
816 for (slot = 0; slot < handles->size; ++slot) {
817 if (!(handles->bitmap [slot / 32] & (1 << (slot % 32))))
819 if (type <= HANDLE_WEAK_TRACK) {
820 if (domain->domain_id == handles->domain_ids [slot]) {
821 handles->bitmap [slot / 32] &= ~(1 << (slot % 32));
822 if (handles->entries [slot])
823 mono_gc_weak_link_remove (&handles->entries [slot]);
826 if (handles->entries [slot] && mono_object_domain (handles->entries [slot]) == domain) {
827 handles->bitmap [slot / 32] &= ~(1 << (slot % 32));
828 handles->entries [slot] = NULL;
832 unlock_handles (handles);
840 static sem_t finalizer_sem;
842 static HANDLE finalizer_event;
843 static volatile gboolean finished=FALSE;
846 mono_gc_finalize_notify (void)
849 g_message (G_GNUC_PRETTY_FUNCTION ": prodding finalizer");
853 sem_post (&finalizer_sem);
855 SetEvent (finalizer_event);
862 collect_objects (gpointer key, gpointer value, gpointer user_data)
864 GPtrArray *arr = (GPtrArray*)user_data;
865 g_ptr_array_add (arr, key);
871 * finalize_domain_objects:
873 * Run the finalizers of all finalizable objects in req->domain.
876 finalize_domain_objects (DomainFinalizationReq *req)
878 MonoDomain *domain = req->domain;
881 while (g_hash_table_size (domain->finalizable_objects_hash) > 0) {
885 * Since the domain is unloading, nobody is allowed to put
886 * new entries into the hash table. But finalize_object might
887 * remove entries from the hash table, so we make a copy.
889 objs = g_ptr_array_new ();
890 g_hash_table_foreach (domain->finalizable_objects_hash, collect_objects, objs);
891 /* printf ("FINALIZING %d OBJECTS.\n", objs->len); */
893 for (i = 0; i < objs->len; ++i) {
894 MonoObject *o = (MonoObject*)g_ptr_array_index (objs, i);
895 /* FIXME: Avoid finalizing threads, etc */
899 g_ptr_array_free (objs, TRUE);
901 #elif defined(HAVE_SGEN_GC)
902 #define NUM_FOBJECTS 64
903 MonoObject *to_finalize [NUM_FOBJECTS];
905 while ((count = mono_gc_finalizers_for_domain (domain, to_finalize, NUM_FOBJECTS))) {
907 for (i = 0; i < count; ++i) {
908 run_finalize (to_finalize [i], 0);
913 /* Process finalizers which are already in the queue */
914 mono_gc_invoke_finalizers ();
916 /* printf ("DONE.\n"); */
917 SetEvent (req->done_event);
919 /* The event is closed in mono_domain_finalize if we get here */
924 finalizer_thread (gpointer unused)
926 gc_thread = mono_thread_current ();
928 SetEvent (thread_started_event);
931 /* Wait to be notified that there's at least one
935 sem_wait (&finalizer_sem);
937 /* Use alertable=FALSE since we will be asked to exit using the event too */
938 WaitForSingleObjectEx (finalizer_event, INFINITE, FALSE);
941 #ifndef DISABLE_ATTACH
942 mono_attach_maybe_start ();
945 if (domains_to_finalize) {
946 mono_finalizer_lock ();
947 if (domains_to_finalize) {
948 DomainFinalizationReq *req = domains_to_finalize->data;
949 domains_to_finalize = g_slist_remove (domains_to_finalize, req);
950 mono_finalizer_unlock ();
952 finalize_domain_objects (req);
954 mono_finalizer_unlock ();
958 /* If finished == TRUE, mono_gc_cleanup has been called (from mono_runtime_cleanup),
959 * before the domain is unloaded.
961 mono_gc_invoke_finalizers ();
963 SetEvent (pending_done_event);
966 SetEvent (shutdown_event);
973 InitializeCriticalSection (&handle_section);
974 InitializeCriticalSection (&allocator_section);
976 InitializeCriticalSection (&finalizer_mutex);
978 MONO_GC_REGISTER_ROOT (gc_handles [HANDLE_NORMAL].entries);
979 MONO_GC_REGISTER_ROOT (gc_handles [HANDLE_PINNED].entries);
981 mono_gc_base_init ();
983 if (g_getenv ("GC_DONT_GC")) {
988 finalizer_event = CreateEvent (NULL, FALSE, FALSE, NULL);
989 pending_done_event = CreateEvent (NULL, TRUE, FALSE, NULL);
990 shutdown_event = CreateEvent (NULL, TRUE, FALSE, NULL);
991 thread_started_event = CreateEvent (NULL, TRUE, FALSE, NULL);
992 if (finalizer_event == NULL || pending_done_event == NULL || shutdown_event == NULL || thread_started_event == NULL) {
993 g_assert_not_reached ();
996 sem_init (&finalizer_sem, 0, 0);
999 mono_thread_create (mono_domain_get (), finalizer_thread, NULL);
1002 * Wait until the finalizer thread sets gc_thread since its value is needed
1003 * by mono_thread_attach ()
1005 * FIXME: Eliminate this as to avoid some deadlocks on windows.
1006 * Waiting for a new thread should result in a deadlock when the runtime is
1007 * initialized from _CorDllMain that is called while the OS loader lock is
1008 * held by LoadLibrary.
1010 WaitForSingleObjectEx (thread_started_event, INFINITE, FALSE);
1014 mono_gc_cleanup (void)
1017 g_message (G_GNUC_PRETTY_FUNCTION ": cleaning up finalizer");
1021 ResetEvent (shutdown_event);
1023 if (mono_thread_current () != gc_thread) {
1024 mono_gc_finalize_notify ();
1025 /* Finishing the finalizer thread, so wait a little bit... */
1026 /* MS seems to wait for about 2 seconds */
1027 if (WaitForSingleObjectEx (shutdown_event, 2000, FALSE) == WAIT_TIMEOUT) {
1030 /* Set a flag which the finalizer thread can check */
1031 suspend_finalizers = TRUE;
1033 /* Try to abort the thread, in the hope that it is running managed code */
1034 mono_thread_stop (gc_thread);
1036 /* Wait for it to stop */
1037 ret = WaitForSingleObjectEx (gc_thread->handle, 100, TRUE);
1039 if (ret == WAIT_TIMEOUT) {
1041 * The finalizer thread refused to die. There is not much we
1042 * can do here, since the runtime is shutting down so the
1043 * state the finalizer thread depends on will vanish.
1045 g_warning ("Shutting down finalizer thread timed out.");
1048 * FIXME: On unix, when the above wait returns, the thread
1049 * might still be running io-layer code, or pthreads code.
1057 #ifdef HAVE_BOEHM_GC
1058 GC_finalizer_notifier = NULL;
1062 DeleteCriticalSection (&handle_section);
1063 DeleteCriticalSection (&allocator_section);
1064 DeleteCriticalSection (&finalizer_mutex);
1069 /* Null GC dummy functions */
1071 mono_gc_finalize_notify (void)
1075 void mono_gc_init (void)
1077 InitializeCriticalSection (&handle_section);
1080 void mono_gc_cleanup (void)
1087 * mono_gc_is_finalizer_thread:
1088 * @thread: the thread to test.
1090 * In Mono objects are finalized asynchronously on a separate thread.
1091 * This routine tests whether the @thread argument represents the
1092 * finalization thread.
1094 * Returns true if @thread is the finalization thread.
1097 mono_gc_is_finalizer_thread (MonoThread *thread)
1099 return thread == gc_thread;