2009-03-04 Zoltan Varga <vargaz@gmail.com>
[mono-debugger.git] / mono / metadata / gc.c
blob3e7c9156e0af060e9a758e7031992842cc30aab0
1 /*
2 * metadata/gc.c: GC icalls.
4 * Author: Paolo Molaro <lupus@ximian.com>
6 * Copyright 2002-2003 Ximian, Inc (http://www.ximian.com)
7 * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
8 */
10 #include <config.h>
11 #include <glib.h>
12 #include <string.h>
14 #include <mono/metadata/gc-internal.h>
15 #include <mono/metadata/mono-gc.h>
16 #include <mono/metadata/threads.h>
17 #include <mono/metadata/tabledefs.h>
18 #include <mono/metadata/exception.h>
19 #include <mono/metadata/profiler-private.h>
20 #include <mono/metadata/domain-internals.h>
21 #include <mono/metadata/class-internals.h>
22 #include <mono/metadata/mono-mlist.h>
23 #include <mono/metadata/threadpool.h>
24 #include <mono/utils/mono-logger.h>
25 #include <mono/metadata/gc-internal.h>
26 #include <mono/metadata/marshal.h> /* for mono_delegate_free_ftnptr () */
27 #include <mono/metadata/attach.h>
28 #if HAVE_SEMAPHORE_H
29 #include <semaphore.h>
30 /* we do this only for known working systems (OSX for example
31 * has the header and functions, but they don't work at all): in other cases
32 * we fall back to the io-layer slightly slower and signal-unsafe Event.
34 #ifdef __linux__
35 #define USE_POSIX_SEM 1
36 #endif
37 #endif
39 #ifndef PLATFORM_WIN32
40 #include <pthread.h>
41 #endif
43 typedef struct DomainFinalizationReq {
44 MonoDomain *domain;
45 HANDLE done_event;
46 } DomainFinalizationReq;
48 #ifdef PLATFORM_WINCE /* FIXME: add accessors to gc.dll API */
49 extern void (*__imp_GC_finalizer_notifier)(void);
50 #define GC_finalizer_notifier __imp_GC_finalizer_notifier
51 extern int __imp_GC_finalize_on_demand;
52 #define GC_finalize_on_demand __imp_GC_finalize_on_demand
53 #endif
55 static gboolean gc_disabled = FALSE;
57 static gboolean finalizing_root_domain = FALSE;
59 #define mono_finalizer_lock() EnterCriticalSection (&finalizer_mutex)
60 #define mono_finalizer_unlock() LeaveCriticalSection (&finalizer_mutex)
61 static CRITICAL_SECTION finalizer_mutex;
63 static GSList *domains_to_finalize= NULL;
64 static MonoMList *threads_to_finalize = NULL;
66 static MonoThread *gc_thread;
68 static void object_register_finalizer (MonoObject *obj, void (*callback)(void *, void*));
70 #ifndef HAVE_NULL_GC
71 static HANDLE pending_done_event;
72 static HANDLE shutdown_event;
73 static HANDLE thread_started_event;
74 #endif
76 static void
77 add_thread_to_finalize (MonoThread *thread)
79 mono_finalizer_lock ();
80 if (!threads_to_finalize)
81 MONO_GC_REGISTER_ROOT (threads_to_finalize);
82 threads_to_finalize = mono_mlist_append (threads_to_finalize, (MonoObject*)thread);
83 mono_finalizer_unlock ();
86 static gboolean suspend_finalizers = FALSE;
87 /*
88 * actually, we might want to queue the finalize requests in a separate thread,
89 * but we need to be careful about the execution domain of the thread...
91 static void
92 run_finalize (void *obj, void *data)
94 MonoObject *exc = NULL;
95 MonoObject *o;
96 #ifndef HAVE_SGEN_GC
97 MonoObject *o2;
98 #endif
99 MonoMethod* finalizer = NULL;
100 MonoDomain *domain;
101 MonoObject *(*runtime_invoke) (MonoObject *this, void **params, MonoObject **exc, void* compiled_method);
103 o = (MonoObject*)((char*)obj + GPOINTER_TO_UINT (data));
105 if (suspend_finalizers)
106 return;
108 domain = o->vtable->domain;
110 #ifndef HAVE_SGEN_GC
111 EnterCriticalSection (&o->vtable->domain->finalizable_objects_hash_lock);
113 o2 = g_hash_table_lookup (o->vtable->domain->finalizable_objects_hash, o);
115 LeaveCriticalSection (&o->vtable->domain->finalizable_objects_hash_lock);
117 if (!o2)
118 /* Already finalized somehow */
119 return;
120 #endif
122 /* make sure the finalizer is not called again if the object is resurrected */
123 object_register_finalizer (obj, NULL);
125 if (o->vtable->klass == mono_get_thread_class ()) {
126 MonoThread *t = (MonoThread*)o;
128 if (mono_gc_is_finalizer_thread (t))
129 /* Avoid finalizing ourselves */
130 return;
132 if (t->threadpool_thread && finalizing_root_domain) {
133 /* Don't finalize threadpool threads when
134 shutting down - they're finalized when the
135 threadpool shuts down. */
136 add_thread_to_finalize (t);
137 return;
141 if (mono_runtime_get_no_exec ())
142 return;
144 /* speedup later... and use a timeout */
145 /* g_print ("Finalize run on %p %s.%s\n", o, mono_object_class (o)->name_space, mono_object_class (o)->name); */
147 /* Use _internal here, since this thread can enter a doomed appdomain */
148 mono_domain_set_internal (mono_object_domain (o));
150 /* delegates that have a native function pointer allocated are
151 * registered for finalization, but they don't have a Finalize
152 * method, because in most cases it's not needed and it's just a waste.
154 if (o->vtable->klass->delegate) {
155 MonoDelegate* del = (MonoDelegate*)o;
156 if (del->delegate_trampoline)
157 mono_delegate_free_ftnptr ((MonoDelegate*)o);
158 return;
161 finalizer = mono_class_get_finalizer (o->vtable->klass);
163 #ifndef DISABLE_COM
164 /* If object has a CCW but has no finalizer, it was only
165 * registered for finalization in order to free the CCW.
166 * Else it needs the regular finalizer run.
167 * FIXME: what to do about ressurection and suppression
168 * of finalizer on object with CCW.
170 if (mono_marshal_free_ccw (o) && !finalizer)
171 return;
172 #endif
175 * To avoid the locking plus the other overhead of mono_runtime_invoke (),
176 * create and precompile a wrapper which calls the finalize method using
177 * a CALLVIRT.
179 if (!domain->finalize_runtime_invoke) {
180 MonoMethod *invoke = mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE);
182 domain->finalize_runtime_invoke = mono_compile_method (invoke);
185 runtime_invoke = domain->finalize_runtime_invoke;
187 mono_runtime_class_init (o->vtable);
189 runtime_invoke (o, NULL, &exc, NULL);
191 if (exc) {
192 /* fixme: do something useful */
196 void
197 mono_gc_finalize_threadpool_threads (void)
199 while (threads_to_finalize) {
200 MonoThread *thread = (MonoThread*) mono_mlist_get_data (threads_to_finalize);
202 /* Force finalization of the thread. */
203 thread->threadpool_thread = FALSE;
204 mono_object_register_finalizer ((MonoObject*)thread);
206 run_finalize (thread, NULL);
208 threads_to_finalize = mono_mlist_next (threads_to_finalize);
212 gpointer
213 mono_gc_out_of_memory (size_t size)
216 * we could allocate at program startup some memory that we could release
217 * back to the system at this point if we're really low on memory (ie, size is
218 * lower than the memory we set apart)
220 mono_raise_exception (mono_domain_get ()->out_of_memory_ex);
222 return NULL;
226 * Some of our objects may point to a different address than the address returned by GC_malloc()
227 * (because of the GetHashCode hack), but we need to pass the real address to register_finalizer.
228 * This also means that in the callback we need to adjust the pointer to get back the real
229 * MonoObject*.
230 * We also need to be consistent in the use of the GC_debug* variants of malloc and register_finalizer,
231 * since that, too, can cause the underlying pointer to be offset.
233 static void
234 object_register_finalizer (MonoObject *obj, void (*callback)(void *, void*))
236 #if HAVE_BOEHM_GC
237 guint offset = 0;
238 MonoDomain *domain = obj->vtable->domain;
240 #ifndef GC_DEBUG
241 /* This assertion is not valid when GC_DEBUG is defined */
242 g_assert (GC_base (obj) == (char*)obj - offset);
243 #endif
245 if (mono_domain_is_unloading (domain) && (callback != NULL))
247 * Can't register finalizers in a dying appdomain, since they
248 * could be invoked after the appdomain has been unloaded.
250 return;
252 EnterCriticalSection (&domain->finalizable_objects_hash_lock);
254 if (callback)
255 g_hash_table_insert (domain->finalizable_objects_hash, obj, obj);
256 else
257 g_hash_table_remove (domain->finalizable_objects_hash, obj);
259 LeaveCriticalSection (&domain->finalizable_objects_hash_lock);
261 GC_REGISTER_FINALIZER_NO_ORDER ((char*)obj - offset, callback, GUINT_TO_POINTER (offset), NULL, NULL);
262 #elif defined(HAVE_SGEN_GC)
263 mono_gc_register_for_finalization (obj, callback);
264 #endif
268 * mono_object_register_finalizer:
269 * @obj: object to register
271 * Records that object @obj has a finalizer, this will call the
272 * Finalize method when the garbage collector disposes the object.
275 void
276 mono_object_register_finalizer (MonoObject *obj)
278 /* g_print ("Registered finalizer on %p %s.%s\n", obj, mono_object_class (obj)->name_space, mono_object_class (obj)->name); */
279 object_register_finalizer (obj, run_finalize);
283 * mono_domain_finalize:
284 * @domain: the domain to finalize
285 * @timeout: msects to wait for the finalization to complete, -1 to wait indefinitely
287 * Request finalization of all finalizable objects inside @domain. Wait
288 * @timeout msecs for the finalization to complete.
290 * Returns: TRUE if succeeded, FALSE if there was a timeout
293 gboolean
294 mono_domain_finalize (MonoDomain *domain, guint32 timeout)
296 DomainFinalizationReq *req;
297 guint32 res;
298 HANDLE done_event;
300 if (mono_thread_current () == gc_thread)
301 /* We are called from inside a finalizer, not much we can do here */
302 return FALSE;
305 * No need to create another thread 'cause the finalizer thread
306 * is still working and will take care of running the finalizers
309 #ifndef HAVE_NULL_GC
310 if (gc_disabled)
311 return TRUE;
313 mono_gc_collect (mono_gc_max_generation ());
315 done_event = CreateEvent (NULL, TRUE, FALSE, NULL);
316 if (done_event == NULL) {
317 return FALSE;
320 req = g_new0 (DomainFinalizationReq, 1);
321 req->domain = domain;
322 req->done_event = done_event;
324 if (domain == mono_get_root_domain ())
325 finalizing_root_domain = TRUE;
327 mono_finalizer_lock ();
329 domains_to_finalize = g_slist_append (domains_to_finalize, req);
331 mono_finalizer_unlock ();
333 /* Tell the finalizer thread to finalize this appdomain */
334 mono_gc_finalize_notify ();
336 if (timeout == -1)
337 timeout = INFINITE;
339 res = WaitForSingleObjectEx (done_event, timeout, TRUE);
341 /* printf ("WAIT RES: %d.\n", res); */
342 if (res == WAIT_TIMEOUT) {
343 /* We leak the handle here */
344 return FALSE;
347 CloseHandle (done_event);
349 if (domain == mono_get_root_domain ()) {
350 mono_thread_pool_cleanup ();
351 mono_gc_finalize_threadpool_threads ();
354 return TRUE;
355 #else
356 /* We don't support domain finalization without a GC */
357 return FALSE;
358 #endif
361 void
362 ves_icall_System_GC_InternalCollect (int generation)
364 mono_gc_collect (generation);
367 gint64
368 ves_icall_System_GC_GetTotalMemory (MonoBoolean forceCollection)
370 MONO_ARCH_SAVE_REGS;
372 if (forceCollection)
373 mono_gc_collect (mono_gc_max_generation ());
374 return mono_gc_get_used_size ();
377 void
378 ves_icall_System_GC_KeepAlive (MonoObject *obj)
380 MONO_ARCH_SAVE_REGS;
383 * Does nothing.
387 void
388 ves_icall_System_GC_ReRegisterForFinalize (MonoObject *obj)
390 MONO_ARCH_SAVE_REGS;
392 object_register_finalizer (obj, run_finalize);
395 void
396 ves_icall_System_GC_SuppressFinalize (MonoObject *obj)
398 MONO_ARCH_SAVE_REGS;
400 /* delegates have no finalizers, but we register them to deal with the
401 * unmanaged->managed trampoline. We don't let the user suppress it
402 * otherwise we'd leak it.
404 if (obj->vtable->klass->delegate)
405 return;
407 /* FIXME: Need to handle case where obj has COM Callable Wrapper
408 * generated for it that needs cleaned up, but user wants to suppress
409 * their derived object finalizer. */
411 object_register_finalizer (obj, NULL);
414 void
415 ves_icall_System_GC_WaitForPendingFinalizers (void)
417 #ifndef HAVE_NULL_GC
418 if (!mono_gc_pending_finalizers ())
419 return;
421 if (mono_thread_current () == gc_thread)
422 /* Avoid deadlocks */
423 return;
425 ResetEvent (pending_done_event);
426 mono_gc_finalize_notify ();
427 /* g_print ("Waiting for pending finalizers....\n"); */
428 WaitForSingleObjectEx (pending_done_event, INFINITE, TRUE);
429 /* g_print ("Done pending....\n"); */
430 #endif
433 #define mono_allocator_lock() EnterCriticalSection (&allocator_section)
434 #define mono_allocator_unlock() LeaveCriticalSection (&allocator_section)
435 static CRITICAL_SECTION allocator_section;
436 static CRITICAL_SECTION handle_section;
438 typedef enum {
439 HANDLE_WEAK,
440 HANDLE_WEAK_TRACK,
441 HANDLE_NORMAL,
442 HANDLE_PINNED
443 } HandleType;
445 static void mono_gchandle_set_target (guint32 gchandle, MonoObject *obj);
447 static HandleType mono_gchandle_get_type (guint32 gchandle);
449 MonoObject *
450 ves_icall_System_GCHandle_GetTarget (guint32 handle)
452 return mono_gchandle_get_target (handle);
456 * if type == -1, change the target of the handle, otherwise allocate a new handle.
458 guint32
459 ves_icall_System_GCHandle_GetTargetHandle (MonoObject *obj, guint32 handle, gint32 type)
461 if (type == -1) {
462 mono_gchandle_set_target (handle, obj);
463 /* the handle doesn't change */
464 return handle;
466 switch (type) {
467 case HANDLE_WEAK:
468 return mono_gchandle_new_weakref (obj, FALSE);
469 case HANDLE_WEAK_TRACK:
470 return mono_gchandle_new_weakref (obj, TRUE);
471 case HANDLE_NORMAL:
472 return mono_gchandle_new (obj, FALSE);
473 case HANDLE_PINNED:
474 return mono_gchandle_new (obj, TRUE);
475 default:
476 g_assert_not_reached ();
478 return 0;
481 void
482 ves_icall_System_GCHandle_FreeHandle (guint32 handle)
484 mono_gchandle_free (handle);
487 gpointer
488 ves_icall_System_GCHandle_GetAddrOfPinnedObject (guint32 handle)
490 MonoObject *obj;
492 if (mono_gchandle_get_type (handle) != HANDLE_PINNED)
493 return (gpointer)-2;
494 obj = mono_gchandle_get_target (handle);
495 if (obj) {
496 MonoClass *klass = mono_object_class (obj);
497 if (klass == mono_defaults.string_class) {
498 return mono_string_chars ((MonoString*)obj);
499 } else if (klass->rank) {
500 return mono_array_addr ((MonoArray*)obj, char, 0);
501 } else {
502 /* the C# code will check and throw the exception */
503 /* FIXME: missing !klass->blittable test, see bug #61134 */
504 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
505 return (gpointer)-1;
506 return (char*)obj + sizeof (MonoObject);
509 return NULL;
512 typedef struct {
513 guint32 *bitmap;
514 gpointer *entries;
515 guint32 size;
516 guint8 type;
517 guint slot_hint : 24; /* starting slot for search */
518 /* 2^16 appdomains should be enough for everyone (though I know I'll regret this in 20 years) */
519 /* we alloc this only for weak refs, since we can get the domain directly in the other cases */
520 guint16 *domain_ids;
521 } HandleData;
523 /* weak and weak-track arrays will be allocated in malloc memory
525 static HandleData gc_handles [] = {
526 {NULL, NULL, 0, HANDLE_WEAK, 0},
527 {NULL, NULL, 0, HANDLE_WEAK_TRACK, 0},
528 {NULL, NULL, 0, HANDLE_NORMAL, 0},
529 {NULL, NULL, 0, HANDLE_PINNED, 0}
532 #define lock_handles(handles) EnterCriticalSection (&handle_section)
533 #define unlock_handles(handles) LeaveCriticalSection (&handle_section)
535 static int
536 find_first_unset (guint32 bitmap)
538 int i;
539 for (i = 0; i < 32; ++i) {
540 if (!(bitmap & (1 << i)))
541 return i;
543 return -1;
546 static guint32
547 alloc_handle (HandleData *handles, MonoObject *obj)
549 gint slot, i;
550 lock_handles (handles);
551 if (!handles->size) {
552 handles->size = 32;
553 if (handles->type > HANDLE_WEAK_TRACK) {
554 handles->entries = mono_gc_alloc_fixed (sizeof (gpointer) * handles->size, NULL);
555 } else {
556 handles->entries = g_malloc0 (sizeof (gpointer) * handles->size);
557 handles->domain_ids = g_malloc0 (sizeof (guint16) * handles->size);
559 handles->bitmap = g_malloc0 (handles->size / 8);
561 i = -1;
562 for (slot = handles->slot_hint; slot < handles->size / 32; ++slot) {
563 if (handles->bitmap [slot] != 0xffffffff) {
564 i = find_first_unset (handles->bitmap [slot]);
565 handles->slot_hint = slot;
566 break;
569 if (i == -1 && handles->slot_hint != 0) {
570 for (slot = 0; slot < handles->slot_hint; ++slot) {
571 if (handles->bitmap [slot] != 0xffffffff) {
572 i = find_first_unset (handles->bitmap [slot]);
573 handles->slot_hint = slot;
574 break;
578 if (i == -1) {
579 guint32 *new_bitmap;
580 guint32 new_size = handles->size * 2; /* always double: we memset to 0 based on this below */
582 /* resize and copy the bitmap */
583 new_bitmap = g_malloc0 (new_size / 8);
584 memcpy (new_bitmap, handles->bitmap, handles->size / 8);
585 g_free (handles->bitmap);
586 handles->bitmap = new_bitmap;
588 /* resize and copy the entries */
589 if (handles->type > HANDLE_WEAK_TRACK) {
590 gpointer *entries;
591 entries = mono_gc_alloc_fixed (sizeof (gpointer) * new_size, NULL);
592 memcpy (entries, handles->entries, sizeof (gpointer) * handles->size);
593 handles->entries = entries;
594 } else {
595 gpointer *entries;
596 guint16 *domain_ids;
597 domain_ids = g_malloc0 (sizeof (guint16) * new_size);
598 entries = g_malloc (sizeof (gpointer) * new_size);
599 /* we disable GC because we could lose some disappearing link updates */
600 mono_gc_disable ();
601 memcpy (entries, handles->entries, sizeof (gpointer) * handles->size);
602 memset (entries + handles->size, 0, sizeof (gpointer) * handles->size);
603 memcpy (domain_ids, handles->domain_ids, sizeof (guint16) * handles->size);
604 for (i = 0; i < handles->size; ++i) {
605 MonoObject *obj = mono_gc_weak_link_get (&(handles->entries [i]));
606 if (handles->entries [i])
607 mono_gc_weak_link_remove (&(handles->entries [i]));
608 /*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]);*/
609 if (obj) {
610 mono_gc_weak_link_add (&(entries [i]), obj);
613 g_free (handles->entries);
614 g_free (handles->domain_ids);
615 handles->entries = entries;
616 handles->domain_ids = domain_ids;
617 mono_gc_enable ();
620 /* set i and slot to the next free position */
621 i = 0;
622 slot = (handles->size + 1) / 32;
623 handles->slot_hint = handles->size + 1;
624 handles->size = new_size;
626 handles->bitmap [slot] |= 1 << i;
627 slot = slot * 32 + i;
628 handles->entries [slot] = obj;
629 if (handles->type <= HANDLE_WEAK_TRACK) {
630 if (obj)
631 mono_gc_weak_link_add (&(handles->entries [slot]), obj);
634 mono_perfcounters->gc_num_handles++;
635 unlock_handles (handles);
636 /*g_print ("allocated entry %d of type %d to object %p (in slot: %p)\n", slot, handles->type, obj, handles->entries [slot]);*/
637 return (slot << 3) | (handles->type + 1);
641 * mono_gchandle_new:
642 * @obj: managed object to get a handle for
643 * @pinned: whether the object should be pinned
645 * This returns a handle that wraps the object, this is used to keep a
646 * reference to a managed object from the unmanaged world and preventing the
647 * object from being disposed.
649 * If @pinned is false the address of the object can not be obtained, if it is
650 * true the address of the object can be obtained. This will also pin the
651 * object so it will not be possible by a moving garbage collector to move the
652 * object.
654 * Returns: a handle that can be used to access the object from
655 * unmanaged code.
657 guint32
658 mono_gchandle_new (MonoObject *obj, gboolean pinned)
660 return alloc_handle (&gc_handles [pinned? HANDLE_PINNED: HANDLE_NORMAL], obj);
664 * mono_gchandle_new_weakref:
665 * @obj: managed object to get a handle for
666 * @pinned: whether the object should be pinned
668 * This returns a weak handle that wraps the object, this is used to
669 * keep a reference to a managed object from the unmanaged world.
670 * Unlike the mono_gchandle_new the object can be reclaimed by the
671 * garbage collector. In this case the value of the GCHandle will be
672 * set to zero.
674 * If @pinned is false the address of the object can not be obtained, if it is
675 * true the address of the object can be obtained. This will also pin the
676 * object so it will not be possible by a moving garbage collector to move the
677 * object.
679 * Returns: a handle that can be used to access the object from
680 * unmanaged code.
682 guint32
683 mono_gchandle_new_weakref (MonoObject *obj, gboolean track_resurrection)
685 return alloc_handle (&gc_handles [track_resurrection? HANDLE_WEAK_TRACK: HANDLE_WEAK], obj);
688 static HandleType
689 mono_gchandle_get_type (guint32 gchandle)
691 guint type = (gchandle & 7) - 1;
693 return type;
697 * mono_gchandle_get_target:
698 * @gchandle: a GCHandle's handle.
700 * The handle was previously created by calling mono_gchandle_new or
701 * mono_gchandle_new_weakref.
703 * Returns a pointer to the MonoObject represented by the handle or
704 * NULL for a collected object if using a weakref handle.
706 MonoObject*
707 mono_gchandle_get_target (guint32 gchandle)
709 guint slot = gchandle >> 3;
710 guint type = (gchandle & 7) - 1;
711 HandleData *handles = &gc_handles [type];
712 MonoObject *obj = NULL;
713 if (type > 3)
714 return NULL;
715 lock_handles (handles);
716 if (slot < handles->size && (handles->bitmap [slot / 32] & (1 << (slot % 32)))) {
717 if (handles->type <= HANDLE_WEAK_TRACK) {
718 obj = mono_gc_weak_link_get (&handles->entries [slot]);
719 } else {
720 obj = handles->entries [slot];
722 } else {
723 /* print a warning? */
725 unlock_handles (handles);
726 /*g_print ("get target of entry %d of type %d: %p\n", slot, handles->type, obj);*/
727 return obj;
730 static void
731 mono_gchandle_set_target (guint32 gchandle, MonoObject *obj)
733 guint slot = gchandle >> 3;
734 guint type = (gchandle & 7) - 1;
735 HandleData *handles = &gc_handles [type];
736 if (type > 3)
737 return;
738 lock_handles (handles);
739 if (slot < handles->size && (handles->bitmap [slot / 32] & (1 << (slot % 32)))) {
740 if (handles->type <= HANDLE_WEAK_TRACK) {
741 if (handles->entries [slot])
742 mono_gc_weak_link_remove (&handles->entries [slot]);
743 if (obj)
744 mono_gc_weak_link_add (&handles->entries [slot], obj);
745 } else {
746 handles->entries [slot] = obj;
748 } else {
749 /* print a warning? */
751 /*g_print ("changed entry %d of type %d to object %p (in slot: %p)\n", slot, handles->type, obj, handles->entries [slot]);*/
752 unlock_handles (handles);
756 * mono_gchandle_is_in_domain:
757 * @gchandle: a GCHandle's handle.
758 * @domain: An application domain.
760 * Returns: true if the object wrapped by the @gchandle belongs to the specific @domain.
762 gboolean
763 mono_gchandle_is_in_domain (guint32 gchandle, MonoDomain *domain)
765 guint slot = gchandle >> 3;
766 guint type = (gchandle & 7) - 1;
767 HandleData *handles = &gc_handles [type];
768 gboolean result = FALSE;
769 if (type > 3)
770 return FALSE;
771 lock_handles (handles);
772 if (slot < handles->size && (handles->bitmap [slot / 32] & (1 << (slot % 32)))) {
773 if (handles->type <= HANDLE_WEAK_TRACK) {
774 result = domain->domain_id == handles->domain_ids [slot];
775 } else {
776 MonoObject *obj;
777 obj = handles->entries [slot];
778 if (obj == NULL)
779 result = TRUE;
780 else
781 result = domain == mono_object_domain (obj);
783 } else {
784 /* print a warning? */
786 unlock_handles (handles);
787 return result;
791 * mono_gchandle_free:
792 * @gchandle: a GCHandle's handle.
794 * Frees the @gchandle handle. If there are no outstanding
795 * references, the garbage collector can reclaim the memory of the
796 * object wrapped.
798 void
799 mono_gchandle_free (guint32 gchandle)
801 guint slot = gchandle >> 3;
802 guint type = (gchandle & 7) - 1;
803 HandleData *handles = &gc_handles [type];
804 if (type > 3)
805 return;
806 lock_handles (handles);
807 if (slot < handles->size && (handles->bitmap [slot / 32] & (1 << (slot % 32)))) {
808 if (handles->type <= HANDLE_WEAK_TRACK) {
809 if (handles->entries [slot])
810 mono_gc_weak_link_remove (&handles->entries [slot]);
811 } else {
812 handles->entries [slot] = NULL;
814 handles->bitmap [slot / 32] &= ~(1 << (slot % 32));
815 } else {
816 /* print a warning? */
818 mono_perfcounters->gc_num_handles--;
819 /*g_print ("freed entry %d of type %d\n", slot, handles->type);*/
820 unlock_handles (handles);
824 * mono_gchandle_free_domain:
825 * @domain: domain that is unloading
827 * Function used internally to cleanup any GC handle for objects belonging
828 * to the specified domain during appdomain unload.
830 void
831 mono_gchandle_free_domain (MonoDomain *domain)
833 guint type;
835 for (type = 0; type < 3; ++type) {
836 guint slot;
837 HandleData *handles = &gc_handles [type];
838 lock_handles (handles);
839 for (slot = 0; slot < handles->size; ++slot) {
840 if (!(handles->bitmap [slot / 32] & (1 << (slot % 32))))
841 continue;
842 if (type <= HANDLE_WEAK_TRACK) {
843 if (domain->domain_id == handles->domain_ids [slot]) {
844 handles->bitmap [slot / 32] &= ~(1 << (slot % 32));
845 if (handles->entries [slot])
846 mono_gc_weak_link_remove (&handles->entries [slot]);
848 } else {
849 if (handles->entries [slot] && mono_object_domain (handles->entries [slot]) == domain) {
850 handles->bitmap [slot / 32] &= ~(1 << (slot % 32));
851 handles->entries [slot] = NULL;
855 unlock_handles (handles);
860 #ifndef HAVE_NULL_GC
862 #if USE_POSIX_SEM
863 static sem_t finalizer_sem;
864 #endif
865 static HANDLE finalizer_event;
866 static volatile gboolean finished=FALSE;
868 void
869 mono_gc_finalize_notify (void)
871 #ifdef DEBUG
872 g_message (G_GNUC_PRETTY_FUNCTION ": prodding finalizer");
873 #endif
875 #if USE_POSIX_SEM
876 sem_post (&finalizer_sem);
877 #else
878 SetEvent (finalizer_event);
879 #endif
882 #ifdef HAVE_BOEHM_GC
884 static void
885 collect_objects (gpointer key, gpointer value, gpointer user_data)
887 GPtrArray *arr = (GPtrArray*)user_data;
888 g_ptr_array_add (arr, key);
891 #endif
894 * finalize_domain_objects:
896 * Run the finalizers of all finalizable objects in req->domain.
898 static void
899 finalize_domain_objects (DomainFinalizationReq *req)
901 MonoDomain *domain = req->domain;
903 #ifdef HAVE_BOEHM_GC
904 while (g_hash_table_size (domain->finalizable_objects_hash) > 0) {
905 int i;
906 GPtrArray *objs;
908 * Since the domain is unloading, nobody is allowed to put
909 * new entries into the hash table. But finalize_object might
910 * remove entries from the hash table, so we make a copy.
912 objs = g_ptr_array_new ();
913 g_hash_table_foreach (domain->finalizable_objects_hash, collect_objects, objs);
914 /* printf ("FINALIZING %d OBJECTS.\n", objs->len); */
916 for (i = 0; i < objs->len; ++i) {
917 MonoObject *o = (MonoObject*)g_ptr_array_index (objs, i);
918 /* FIXME: Avoid finalizing threads, etc */
919 run_finalize (o, 0);
922 g_ptr_array_free (objs, TRUE);
924 #elif defined(HAVE_SGEN_GC)
925 #define NUM_FOBJECTS 64
926 MonoObject *to_finalize [NUM_FOBJECTS];
927 int count;
928 while ((count = mono_gc_finalizers_for_domain (domain, to_finalize, NUM_FOBJECTS))) {
929 int i;
930 for (i = 0; i < count; ++i) {
931 run_finalize (to_finalize [i], 0);
934 #endif
936 /* Process finalizers which are already in the queue */
937 mono_gc_invoke_finalizers ();
939 /* printf ("DONE.\n"); */
940 SetEvent (req->done_event);
942 /* The event is closed in mono_domain_finalize if we get here */
943 g_free (req);
946 static guint32
947 finalizer_thread (gpointer unused)
949 gc_thread = mono_thread_current ();
951 SetEvent (thread_started_event);
953 while (!finished) {
954 /* Wait to be notified that there's at least one
955 * finaliser to run
957 #if USE_POSIX_SEM
958 sem_wait (&finalizer_sem);
959 #else
960 /* Use alertable=FALSE since we will be asked to exit using the event too */
961 WaitForSingleObjectEx (finalizer_event, INFINITE, FALSE);
962 #endif
964 #ifndef DISABLE_ATTACH
965 mono_attach_maybe_start ();
966 #endif
968 if (domains_to_finalize) {
969 mono_finalizer_lock ();
970 if (domains_to_finalize) {
971 DomainFinalizationReq *req = domains_to_finalize->data;
972 domains_to_finalize = g_slist_remove (domains_to_finalize, req);
973 mono_finalizer_unlock ();
975 finalize_domain_objects (req);
976 } else {
977 mono_finalizer_unlock ();
981 /* If finished == TRUE, mono_gc_cleanup has been called (from mono_runtime_cleanup),
982 * before the domain is unloaded.
984 mono_gc_invoke_finalizers ();
986 SetEvent (pending_done_event);
989 SetEvent (shutdown_event);
990 return 0;
993 void
994 mono_gc_init (void)
996 InitializeCriticalSection (&handle_section);
997 InitializeCriticalSection (&allocator_section);
999 InitializeCriticalSection (&finalizer_mutex);
1001 MONO_GC_REGISTER_ROOT (gc_handles [HANDLE_NORMAL].entries);
1002 MONO_GC_REGISTER_ROOT (gc_handles [HANDLE_PINNED].entries);
1004 mono_gc_base_init ();
1006 if (g_getenv ("GC_DONT_GC")) {
1007 gc_disabled = TRUE;
1008 return;
1011 finalizer_event = CreateEvent (NULL, FALSE, FALSE, NULL);
1012 pending_done_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1013 shutdown_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1014 thread_started_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1015 if (finalizer_event == NULL || pending_done_event == NULL || shutdown_event == NULL || thread_started_event == NULL) {
1016 g_assert_not_reached ();
1018 #if USE_POSIX_SEM
1019 sem_init (&finalizer_sem, 0, 0);
1020 #endif
1022 mono_thread_create (mono_domain_get (), finalizer_thread, NULL);
1025 * Wait until the finalizer thread sets gc_thread since its value is needed
1026 * by mono_thread_attach ()
1028 * FIXME: Eliminate this as to avoid some deadlocks on windows.
1029 * Waiting for a new thread should result in a deadlock when the runtime is
1030 * initialized from _CorDllMain that is called while the OS loader lock is
1031 * held by LoadLibrary.
1033 WaitForSingleObjectEx (thread_started_event, INFINITE, FALSE);
1036 void
1037 mono_gc_cleanup (void)
1039 #ifdef DEBUG
1040 g_message (G_GNUC_PRETTY_FUNCTION ": cleaning up finalizer");
1041 #endif
1043 if (!gc_disabled) {
1044 ResetEvent (shutdown_event);
1045 finished = TRUE;
1046 if (mono_thread_current () != gc_thread) {
1047 mono_gc_finalize_notify ();
1048 /* Finishing the finalizer thread, so wait a little bit... */
1049 /* MS seems to wait for about 2 seconds */
1050 if (WaitForSingleObjectEx (shutdown_event, 2000, FALSE) == WAIT_TIMEOUT) {
1051 int ret;
1053 /* Set a flag which the finalizer thread can check */
1054 suspend_finalizers = TRUE;
1056 /* Try to abort the thread, in the hope that it is running managed code */
1057 mono_thread_stop (gc_thread);
1059 /* Wait for it to stop */
1060 ret = WaitForSingleObjectEx (gc_thread->handle, 100, TRUE);
1062 if (ret == WAIT_TIMEOUT) {
1064 * The finalizer thread refused to die. There is not much we
1065 * can do here, since the runtime is shutting down so the
1066 * state the finalizer thread depends on will vanish.
1068 g_warning ("Shutting down finalizer thread timed out.");
1069 } else {
1071 * FIXME: On unix, when the above wait returns, the thread
1072 * might still be running io-layer code, or pthreads code.
1074 Sleep (100);
1079 gc_thread = NULL;
1080 #ifdef HAVE_BOEHM_GC
1081 GC_finalizer_notifier = NULL;
1082 #endif
1085 DeleteCriticalSection (&handle_section);
1086 DeleteCriticalSection (&allocator_section);
1087 DeleteCriticalSection (&finalizer_mutex);
1090 #else
1092 /* Null GC dummy functions */
1093 void
1094 mono_gc_finalize_notify (void)
1098 void mono_gc_init (void)
1100 InitializeCriticalSection (&handle_section);
1103 void mono_gc_cleanup (void)
1107 #endif
1110 * mono_gc_is_finalizer_thread:
1111 * @thread: the thread to test.
1113 * In Mono objects are finalized asynchronously on a separate thread.
1114 * This routine tests whether the @thread argument represents the
1115 * finalization thread.
1117 * Returns true if @thread is the finalization thread.
1119 gboolean
1120 mono_gc_is_finalizer_thread (MonoThread *thread)
1122 return thread == gc_thread;