In .:
[mono.git] / mono / metadata / gc.c
1 /*
2  * metadata/gc.c: GC icalls.
3  *
4  * Author: Paolo Molaro <lupus@ximian.com>
5  *
6  * Copyright 2002-2003 Ximian, Inc (http://www.ximian.com)
7  * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
8  */
9
10 #include <config.h>
11 #include <glib.h>
12 #include <string.h>
13
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.
33  */
34 #ifdef __linux__
35 #define USE_POSIX_SEM 1
36 #endif
37 #endif
38
39 #ifndef PLATFORM_WIN32
40 #include <pthread.h>
41 #endif
42
43 typedef struct DomainFinalizationReq {
44         MonoDomain *domain;
45         HANDLE done_event;
46 } DomainFinalizationReq;
47
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
54
55 static gboolean gc_disabled = FALSE;
56
57 static gboolean finalizing_root_domain = FALSE;
58
59 #define mono_finalizer_lock() EnterCriticalSection (&finalizer_mutex)
60 #define mono_finalizer_unlock() LeaveCriticalSection (&finalizer_mutex)
61 static CRITICAL_SECTION finalizer_mutex;
62
63 static GSList *domains_to_finalize= NULL;
64 static MonoMList *threads_to_finalize = NULL;
65
66 static MonoThread *gc_thread;
67
68 static void object_register_finalizer (MonoObject *obj, void (*callback)(void *, void*));
69
70 #ifndef HAVE_NULL_GC
71 static HANDLE pending_done_event;
72 static HANDLE shutdown_event;
73 static HANDLE thread_started_event;
74 #endif
75
76 static void
77 add_thread_to_finalize (MonoThread *thread)
78 {
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 ();
84 }
85
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...
90  */
91 static void
92 run_finalize (void *obj, void *data)
93 {
94         MonoObject *exc = NULL;
95         MonoObject *o;
96 #ifndef HAVE_SGEN_GC
97         MonoObject *o2;
98 #endif
99         MonoMethod* finalizer = NULL;
100         o = (MonoObject*)((char*)obj + GPOINTER_TO_UINT (data));
101
102         if (suspend_finalizers)
103                 return;
104
105 #ifndef HAVE_SGEN_GC
106         mono_domain_lock (o->vtable->domain);
107
108         o2 = g_hash_table_lookup (o->vtable->domain->finalizable_objects_hash, o);
109
110         mono_domain_unlock (o->vtable->domain);
111
112         if (!o2)
113                 /* Already finalized somehow */
114                 return;
115 #endif
116
117         /* make sure the finalizer is not called again if the object is resurrected */
118         object_register_finalizer (obj, NULL);
119
120         if (o->vtable->klass == mono_get_thread_class ()) {
121                 MonoThread *t = (MonoThread*)o;
122
123                 if (mono_gc_is_finalizer_thread (t))
124                         /* Avoid finalizing ourselves */
125                         return;
126
127                 if (t->threadpool_thread && finalizing_root_domain) {
128                         /* Don't finalize threadpool threads when
129                            shutting down - they're finalized when the
130                            threadpool shuts down. */
131                         add_thread_to_finalize (t);
132                         return;
133                 }
134         }
135
136         if (mono_runtime_get_no_exec ())
137                 return;
138
139         /* speedup later... and use a timeout */
140         /* g_print ("Finalize run on %p %s.%s\n", o, mono_object_class (o)->name_space, mono_object_class (o)->name); */
141
142         /* Use _internal here, since this thread can enter a doomed appdomain */
143         mono_domain_set_internal (mono_object_domain (o));              
144
145         /* delegates that have a native function pointer allocated are
146          * registered for finalization, but they don't have a Finalize
147          * method, because in most cases it's not needed and it's just a waste.
148          */
149         if (o->vtable->klass->delegate) {
150                 MonoDelegate* del = (MonoDelegate*)o;
151                 if (del->delegate_trampoline)
152                         mono_delegate_free_ftnptr ((MonoDelegate*)o);
153                 return;
154         }
155
156         finalizer = mono_class_get_finalizer (o->vtable->klass);
157
158         /* If object has a CCW but has no finalizer, it was only
159          * registered for finalization in order to free the CCW.
160          * Else it needs the regular finalizer run.
161          * FIXME: what to do about ressurection and suppression
162          * of finalizer on object with CCW.
163          */
164         if (mono_marshal_free_ccw (o) && !finalizer)
165                 return;
166
167         mono_runtime_invoke (finalizer, o, NULL, &exc);
168
169         if (exc) {
170                 /* fixme: do something useful */
171         }
172 }
173
174 void
175 mono_gc_finalize_threadpool_threads (void)
176 {
177         while (threads_to_finalize) {
178                 MonoThread *thread = (MonoThread*) mono_mlist_get_data (threads_to_finalize);
179
180                 /* Force finalization of the thread. */
181                 thread->threadpool_thread = FALSE;
182                 mono_object_register_finalizer ((MonoObject*)thread);
183
184                 run_finalize (thread, NULL);
185
186                 threads_to_finalize = mono_mlist_next (threads_to_finalize);
187         }
188 }
189
190 gpointer
191 mono_gc_out_of_memory (size_t size)
192 {
193         /* 
194          * we could allocate at program startup some memory that we could release 
195          * back to the system at this point if we're really low on memory (ie, size is
196          * lower than the memory we set apart)
197          */
198         mono_raise_exception (mono_domain_get ()->out_of_memory_ex);
199
200         return NULL;
201 }
202
203 /*
204  * Some of our objects may point to a different address than the address returned by GC_malloc()
205  * (because of the GetHashCode hack), but we need to pass the real address to register_finalizer.
206  * This also means that in the callback we need to adjust the pointer to get back the real
207  * MonoObject*.
208  * We also need to be consistent in the use of the GC_debug* variants of malloc and register_finalizer, 
209  * since that, too, can cause the underlying pointer to be offset.
210  */
211 static void
212 object_register_finalizer (MonoObject *obj, void (*callback)(void *, void*))
213 {
214 #if HAVE_BOEHM_GC
215         guint offset = 0;
216         MonoDomain *domain = obj->vtable->domain;
217
218 #ifndef GC_DEBUG
219         /* This assertion is not valid when GC_DEBUG is defined */
220         g_assert (GC_base (obj) == (char*)obj - offset);
221 #endif
222
223         if (mono_domain_is_unloading (domain) && (callback != NULL))
224                 /*
225                  * Can't register finalizers in a dying appdomain, since they
226                  * could be invoked after the appdomain has been unloaded.
227                  */
228                 return;
229
230         mono_domain_lock (domain);
231
232         if (callback)
233                 g_hash_table_insert (domain->finalizable_objects_hash, obj, obj);
234         else
235                 g_hash_table_remove (domain->finalizable_objects_hash, obj);
236
237         mono_domain_unlock (domain);
238
239         GC_REGISTER_FINALIZER_NO_ORDER ((char*)obj - offset, callback, GUINT_TO_POINTER (offset), NULL, NULL);
240 #elif defined(HAVE_SGEN_GC)
241         mono_gc_register_for_finalization (obj, callback);
242 #endif
243 }
244
245 /**
246  * mono_object_register_finalizer:
247  * @obj: object to register
248  *
249  * Records that object @obj has a finalizer, this will call the
250  * Finalize method when the garbage collector disposes the object.
251  * 
252  */
253 void
254 mono_object_register_finalizer (MonoObject *obj)
255 {
256         /* g_print ("Registered finalizer on %p %s.%s\n", obj, mono_object_class (obj)->name_space, mono_object_class (obj)->name); */
257         object_register_finalizer (obj, run_finalize);
258 }
259
260 /**
261  * mono_domain_finalize:
262  * @domain: the domain to finalize
263  * @timeout: msects to wait for the finalization to complete, -1 to wait indefinitely
264  *
265  *  Request finalization of all finalizable objects inside @domain. Wait
266  * @timeout msecs for the finalization to complete.
267  *
268  * Returns: TRUE if succeeded, FALSE if there was a timeout
269  */
270
271 gboolean
272 mono_domain_finalize (MonoDomain *domain, guint32 timeout) 
273 {
274         DomainFinalizationReq *req;
275         guint32 res;
276         HANDLE done_event;
277
278         if (mono_thread_current () == gc_thread)
279                 /* We are called from inside a finalizer, not much we can do here */
280                 return FALSE;
281
282         /* 
283          * No need to create another thread 'cause the finalizer thread
284          * is still working and will take care of running the finalizers
285          */ 
286         
287 #ifndef HAVE_NULL_GC
288         if (gc_disabled)
289                 return TRUE;
290
291         mono_gc_collect (mono_gc_max_generation ());
292
293         done_event = CreateEvent (NULL, TRUE, FALSE, NULL);
294         if (done_event == NULL) {
295                 return FALSE;
296         }
297
298         req = g_new0 (DomainFinalizationReq, 1);
299         req->domain = domain;
300         req->done_event = done_event;
301
302         if (domain == mono_get_root_domain ())
303                 finalizing_root_domain = TRUE;
304         
305         mono_finalizer_lock ();
306
307         domains_to_finalize = g_slist_append (domains_to_finalize, req);
308
309         mono_finalizer_unlock ();
310
311         /* Tell the finalizer thread to finalize this appdomain */
312         mono_gc_finalize_notify ();
313
314         if (timeout == -1)
315                 timeout = INFINITE;
316
317         res = WaitForSingleObjectEx (done_event, timeout, TRUE);
318
319         /* printf ("WAIT RES: %d.\n", res); */
320         if (res == WAIT_TIMEOUT) {
321                 /* We leak the handle here */
322                 return FALSE;
323         }
324
325         CloseHandle (done_event);
326
327         if (domain == mono_get_root_domain ()) {
328                 mono_thread_pool_cleanup ();
329                 mono_gc_finalize_threadpool_threads ();
330         }
331
332         return TRUE;
333 #else
334         /* We don't support domain finalization without a GC */
335         return FALSE;
336 #endif
337 }
338
339 void
340 ves_icall_System_GC_InternalCollect (int generation)
341 {
342         mono_gc_collect (generation);
343 }
344
345 gint64
346 ves_icall_System_GC_GetTotalMemory (MonoBoolean forceCollection)
347 {
348         MONO_ARCH_SAVE_REGS;
349
350         if (forceCollection)
351                 mono_gc_collect (mono_gc_max_generation ());
352         return mono_gc_get_used_size ();
353 }
354
355 void
356 ves_icall_System_GC_KeepAlive (MonoObject *obj)
357 {
358         MONO_ARCH_SAVE_REGS;
359
360         /*
361          * Does nothing.
362          */
363 }
364
365 void
366 ves_icall_System_GC_ReRegisterForFinalize (MonoObject *obj)
367 {
368         MONO_ARCH_SAVE_REGS;
369
370         object_register_finalizer (obj, run_finalize);
371 }
372
373 void
374 ves_icall_System_GC_SuppressFinalize (MonoObject *obj)
375 {
376         MONO_ARCH_SAVE_REGS;
377
378         /* delegates have no finalizers, but we register them to deal with the
379          * unmanaged->managed trampoline. We don't let the user suppress it
380          * otherwise we'd leak it.
381          */
382         if (obj->vtable->klass->delegate)
383                 return;
384
385         /* FIXME: Need to handle case where obj has COM Callable Wrapper
386          * generated for it that needs cleaned up, but user wants to suppress
387          * their derived object finalizer. */
388
389         object_register_finalizer (obj, NULL);
390 }
391
392 void
393 ves_icall_System_GC_WaitForPendingFinalizers (void)
394 {
395 #ifndef HAVE_NULL_GC
396         if (!mono_gc_pending_finalizers ())
397                 return;
398
399         if (mono_thread_current () == gc_thread)
400                 /* Avoid deadlocks */
401                 return;
402
403         ResetEvent (pending_done_event);
404         mono_gc_finalize_notify ();
405         /* g_print ("Waiting for pending finalizers....\n"); */
406         WaitForSingleObjectEx (pending_done_event, INFINITE, TRUE);
407         /* g_print ("Done pending....\n"); */
408 #endif
409 }
410
411 #define mono_allocator_lock() EnterCriticalSection (&allocator_section)
412 #define mono_allocator_unlock() LeaveCriticalSection (&allocator_section)
413 static CRITICAL_SECTION allocator_section;
414 static CRITICAL_SECTION handle_section;
415
416 typedef enum {
417         HANDLE_WEAK,
418         HANDLE_WEAK_TRACK,
419         HANDLE_NORMAL,
420         HANDLE_PINNED
421 } HandleType;
422
423 static void mono_gchandle_set_target (guint32 gchandle, MonoObject *obj);
424
425 static HandleType mono_gchandle_get_type (guint32 gchandle);
426
427 MonoObject *
428 ves_icall_System_GCHandle_GetTarget (guint32 handle)
429 {
430         return mono_gchandle_get_target (handle);
431 }
432
433 /*
434  * if type == -1, change the target of the handle, otherwise allocate a new handle.
435  */
436 guint32
437 ves_icall_System_GCHandle_GetTargetHandle (MonoObject *obj, guint32 handle, gint32 type)
438 {
439         if (type == -1) {
440                 mono_gchandle_set_target (handle, obj);
441                 /* the handle doesn't change */
442                 return handle;
443         }
444         switch (type) {
445         case HANDLE_WEAK:
446                 return mono_gchandle_new_weakref (obj, FALSE);
447         case HANDLE_WEAK_TRACK:
448                 return mono_gchandle_new_weakref (obj, TRUE);
449         case HANDLE_NORMAL:
450                 return mono_gchandle_new (obj, FALSE);
451         case HANDLE_PINNED:
452                 return mono_gchandle_new (obj, TRUE);
453         default:
454                 g_assert_not_reached ();
455         }
456         return 0;
457 }
458
459 void
460 ves_icall_System_GCHandle_FreeHandle (guint32 handle)
461 {
462         mono_gchandle_free (handle);
463 }
464
465 gpointer
466 ves_icall_System_GCHandle_GetAddrOfPinnedObject (guint32 handle)
467 {
468         MonoObject *obj;
469
470         if (mono_gchandle_get_type (handle) != HANDLE_PINNED)
471                 return (gpointer)-2;
472         obj = mono_gchandle_get_target (handle);
473         if (obj) {
474                 MonoClass *klass = mono_object_class (obj);
475                 if (klass == mono_defaults.string_class) {
476                         return mono_string_chars ((MonoString*)obj);
477                 } else if (klass->rank) {
478                         return mono_array_addr ((MonoArray*)obj, char, 0);
479                 } else {
480                         /* the C# code will check and throw the exception */
481                         /* FIXME: missing !klass->blittable test, see bug #61134 */
482                         if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
483                                 return (gpointer)-1;
484                         return (char*)obj + sizeof (MonoObject);
485                 }
486         }
487         return NULL;
488 }
489
490 typedef struct {
491         guint32  *bitmap;
492         gpointer *entries;
493         guint32   size;
494         guint8    type;
495         guint     slot_hint : 24; /* starting slot for search */
496         /* 2^16 appdomains should be enough for everyone (though I know I'll regret this in 20 years) */
497         /* we alloc this only for weak refs, since we can get the domain directly in the other cases */
498         guint16  *domain_ids;
499 } HandleData;
500
501 /* weak and weak-track arrays will be allocated in malloc memory 
502  */
503 static HandleData gc_handles [] = {
504         {NULL, NULL, 0, HANDLE_WEAK, 0},
505         {NULL, NULL, 0, HANDLE_WEAK_TRACK, 0},
506         {NULL, NULL, 0, HANDLE_NORMAL, 0},
507         {NULL, NULL, 0, HANDLE_PINNED, 0}
508 };
509
510 #define lock_handles(handles) EnterCriticalSection (&handle_section)
511 #define unlock_handles(handles) LeaveCriticalSection (&handle_section)
512
513 static int
514 find_first_unset (guint32 bitmap)
515 {
516         int i;
517         for (i = 0; i < 32; ++i) {
518                 if (!(bitmap & (1 << i)))
519                         return i;
520         }
521         return -1;
522 }
523
524 static guint32
525 alloc_handle (HandleData *handles, MonoObject *obj)
526 {
527         gint slot, i;
528         lock_handles (handles);
529         if (!handles->size) {
530                 handles->size = 32;
531                 if (handles->type > HANDLE_WEAK_TRACK) {
532                         handles->entries = mono_gc_alloc_fixed (sizeof (gpointer) * handles->size, NULL);
533                 } else {
534                         handles->entries = g_malloc0 (sizeof (gpointer) * handles->size);
535                         handles->domain_ids = g_malloc0 (sizeof (guint16) * handles->size);
536                 }
537                 handles->bitmap = g_malloc0 (handles->size / 8);
538         }
539         i = -1;
540         for (slot = handles->slot_hint; slot < handles->size / 32; ++slot) {
541                 if (handles->bitmap [slot] != 0xffffffff) {
542                         i = find_first_unset (handles->bitmap [slot]);
543                         handles->slot_hint = slot;
544                         break;
545                 }
546         }
547         if (i == -1 && handles->slot_hint != 0) {
548                 for (slot = 0; slot < handles->slot_hint; ++slot) {
549                         if (handles->bitmap [slot] != 0xffffffff) {
550                                 i = find_first_unset (handles->bitmap [slot]);
551                                 handles->slot_hint = slot;
552                                 break;
553                         }
554                 }
555         }
556         if (i == -1) {
557                 guint32 *new_bitmap;
558                 guint32 new_size = handles->size * 2; /* always double: we memset to 0 based on this below */
559
560                 /* resize and copy the bitmap */
561                 new_bitmap = g_malloc0 (new_size / 8);
562                 memcpy (new_bitmap, handles->bitmap, handles->size / 8);
563                 g_free (handles->bitmap);
564                 handles->bitmap = new_bitmap;
565
566                 /* resize and copy the entries */
567                 if (handles->type > HANDLE_WEAK_TRACK) {
568                         gpointer *entries;
569                         entries = mono_gc_alloc_fixed (sizeof (gpointer) * new_size, NULL);
570                         memcpy (entries, handles->entries, sizeof (gpointer) * handles->size);
571                         handles->entries = entries;
572                 } else {
573                         gpointer *entries;
574                         guint16 *domain_ids;
575                         domain_ids = g_malloc0 (sizeof (guint16) * new_size);
576                         entries = g_malloc (sizeof (gpointer) * new_size);
577                         /* we disable GC because we could lose some disappearing link updates */
578                         mono_gc_disable ();
579                         memcpy (entries, handles->entries, sizeof (gpointer) * handles->size);
580                         memset (entries + handles->size, 0, sizeof (gpointer) * handles->size);
581                         memcpy (domain_ids, handles->domain_ids, sizeof (guint16) * handles->size);
582                         for (i = 0; i < handles->size; ++i) {
583                                 MonoObject *obj = mono_gc_weak_link_get (&(handles->entries [i]));
584                                 if (handles->entries [i])
585                                         mono_gc_weak_link_remove (&(handles->entries [i]));
586                                 /*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                                 if (obj) {
588                                         mono_gc_weak_link_add (&(entries [i]), obj);
589                                 }
590                         }
591                         g_free (handles->entries);
592                         g_free (handles->domain_ids);
593                         handles->entries = entries;
594                         handles->domain_ids = domain_ids;
595                         mono_gc_enable ();
596                 }
597
598                 /* set i and slot to the next free position */
599                 i = 0;
600                 slot = (handles->size + 1) / 32;
601                 handles->slot_hint = handles->size + 1;
602                 handles->size = new_size;
603         }
604         handles->bitmap [slot] |= 1 << i;
605         slot = slot * 32 + i;
606         handles->entries [slot] = obj;
607         if (handles->type <= HANDLE_WEAK_TRACK) {
608                 if (obj)
609                         mono_gc_weak_link_add (&(handles->entries [slot]), obj);
610         }
611
612         mono_perfcounters->gc_num_handles++;
613         unlock_handles (handles);
614         /*g_print ("allocated entry %d of type %d to object %p (in slot: %p)\n", slot, handles->type, obj, handles->entries [slot]);*/
615         return (slot << 3) | (handles->type + 1);
616 }
617
618 /**
619  * mono_gchandle_new:
620  * @obj: managed object to get a handle for
621  * @pinned: whether the object should be pinned
622  *
623  * This returns a handle that wraps the object, this is used to keep a
624  * reference to a managed object from the unmanaged world and preventing the
625  * object from being disposed.
626  * 
627  * If @pinned is false the address of the object can not be obtained, if it is
628  * true the address of the object can be obtained.  This will also pin the
629  * object so it will not be possible by a moving garbage collector to move the
630  * object. 
631  * 
632  * Returns: a handle that can be used to access the object from
633  * unmanaged code.
634  */
635 guint32
636 mono_gchandle_new (MonoObject *obj, gboolean pinned)
637 {
638         return alloc_handle (&gc_handles [pinned? HANDLE_PINNED: HANDLE_NORMAL], obj);
639 }
640
641 /**
642  * mono_gchandle_new_weakref:
643  * @obj: managed object to get a handle for
644  * @pinned: whether the object should be pinned
645  *
646  * This returns a weak handle that wraps the object, this is used to
647  * keep a reference to a managed object from the unmanaged world.
648  * Unlike the mono_gchandle_new the object can be reclaimed by the
649  * garbage collector.  In this case the value of the GCHandle will be
650  * set to zero.
651  * 
652  * If @pinned is false the address of the object can not be obtained, if it is
653  * true the address of the object can be obtained.  This will also pin the
654  * object so it will not be possible by a moving garbage collector to move the
655  * object. 
656  * 
657  * Returns: a handle that can be used to access the object from
658  * unmanaged code.
659  */
660 guint32
661 mono_gchandle_new_weakref (MonoObject *obj, gboolean track_resurrection)
662 {
663         return alloc_handle (&gc_handles [track_resurrection? HANDLE_WEAK_TRACK: HANDLE_WEAK], obj);
664 }
665
666 static HandleType
667 mono_gchandle_get_type (guint32 gchandle)
668 {
669         guint type = (gchandle & 7) - 1;
670
671         return type;
672 }
673
674 /**
675  * mono_gchandle_get_target:
676  * @gchandle: a GCHandle's handle.
677  *
678  * The handle was previously created by calling mono_gchandle_new or
679  * mono_gchandle_new_weakref. 
680  *
681  * Returns a pointer to the MonoObject represented by the handle or
682  * NULL for a collected object if using a weakref handle.
683  */
684 MonoObject*
685 mono_gchandle_get_target (guint32 gchandle)
686 {
687         guint slot = gchandle >> 3;
688         guint type = (gchandle & 7) - 1;
689         HandleData *handles = &gc_handles [type];
690         MonoObject *obj = NULL;
691         if (type > 3)
692                 return NULL;
693         lock_handles (handles);
694         if (slot < handles->size && (handles->bitmap [slot / 32] & (1 << (slot % 32)))) {
695                 if (handles->type <= HANDLE_WEAK_TRACK) {
696                         obj = mono_gc_weak_link_get (&handles->entries [slot]);
697                 } else {
698                         obj = handles->entries [slot];
699                 }
700         } else {
701                 /* print a warning? */
702         }
703         unlock_handles (handles);
704         /*g_print ("get target of entry %d of type %d: %p\n", slot, handles->type, obj);*/
705         return obj;
706 }
707
708 static void
709 mono_gchandle_set_target (guint32 gchandle, MonoObject *obj)
710 {
711         guint slot = gchandle >> 3;
712         guint type = (gchandle & 7) - 1;
713         HandleData *handles = &gc_handles [type];
714         if (type > 3)
715                 return;
716         lock_handles (handles);
717         if (slot < handles->size && (handles->bitmap [slot / 32] & (1 << (slot % 32)))) {
718                 if (handles->type <= HANDLE_WEAK_TRACK) {
719                         if (handles->entries [slot])
720                                 mono_gc_weak_link_remove (&handles->entries [slot]);
721                         if (obj)
722                                 mono_gc_weak_link_add (&handles->entries [slot], obj);
723                 } else {
724                         handles->entries [slot] = obj;
725                 }
726         } else {
727                 /* print a warning? */
728         }
729         /*g_print ("changed entry %d of type %d to object %p (in slot: %p)\n", slot, handles->type, obj, handles->entries [slot]);*/
730         unlock_handles (handles);
731 }
732
733 /**
734  * mono_gchandle_is_in_domain:
735  * @gchandle: a GCHandle's handle.
736  * @domain: An application domain.
737  *
738  * Returns: true if the object wrapped by the @gchandle belongs to the specific @domain.
739  */
740 gboolean
741 mono_gchandle_is_in_domain (guint32 gchandle, MonoDomain *domain)
742 {
743         guint slot = gchandle >> 3;
744         guint type = (gchandle & 7) - 1;
745         HandleData *handles = &gc_handles [type];
746         gboolean result = FALSE;
747         if (type > 3)
748                 return FALSE;
749         lock_handles (handles);
750         if (slot < handles->size && (handles->bitmap [slot / 32] & (1 << (slot % 32)))) {
751                 if (handles->type <= HANDLE_WEAK_TRACK) {
752                         result = domain->domain_id == handles->domain_ids [slot];
753                 } else {
754                         MonoObject *obj;
755                         obj = handles->entries [slot];
756                         if (obj == NULL)
757                                 result = TRUE;
758                         else
759                                 result = domain == mono_object_domain (obj);
760                 }
761         } else {
762                 /* print a warning? */
763         }
764         unlock_handles (handles);
765         return result;
766 }
767
768 /**
769  * mono_gchandle_free:
770  * @gchandle: a GCHandle's handle.
771  *
772  * Frees the @gchandle handle.  If there are no outstanding
773  * references, the garbage collector can reclaim the memory of the
774  * object wrapped. 
775  */
776 void
777 mono_gchandle_free (guint32 gchandle)
778 {
779         guint slot = gchandle >> 3;
780         guint type = (gchandle & 7) - 1;
781         HandleData *handles = &gc_handles [type];
782         if (type > 3)
783                 return;
784         lock_handles (handles);
785         if (slot < handles->size && (handles->bitmap [slot / 32] & (1 << (slot % 32)))) {
786                 if (handles->type <= HANDLE_WEAK_TRACK) {
787                         if (handles->entries [slot])
788                                 mono_gc_weak_link_remove (&handles->entries [slot]);
789                 } else {
790                         handles->entries [slot] = NULL;
791                 }
792                 handles->bitmap [slot / 32] &= ~(1 << (slot % 32));
793         } else {
794                 /* print a warning? */
795         }
796         mono_perfcounters->gc_num_handles--;
797         /*g_print ("freed entry %d of type %d\n", slot, handles->type);*/
798         unlock_handles (handles);
799 }
800
801 /**
802  * mono_gchandle_free_domain:
803  * @domain: domain that is unloading
804  *
805  * Function used internally to cleanup any GC handle for objects belonging
806  * to the specified domain during appdomain unload.
807  */
808 void
809 mono_gchandle_free_domain (MonoDomain *domain)
810 {
811         guint type;
812
813         for (type = 0; type < 3; ++type) {
814                 guint slot;
815                 HandleData *handles = &gc_handles [type];
816                 lock_handles (handles);
817                 for (slot = 0; slot < handles->size; ++slot) {
818                         if (!(handles->bitmap [slot / 32] & (1 << (slot % 32))))
819                                 continue;
820                         if (type <= HANDLE_WEAK_TRACK) {
821                                 if (domain->domain_id == handles->domain_ids [slot]) {
822                                         handles->bitmap [slot / 32] &= ~(1 << (slot % 32));
823                                         if (handles->entries [slot])
824                                                 mono_gc_weak_link_remove (&handles->entries [slot]);
825                                 }
826                         } else {
827                                 if (handles->entries [slot] && mono_object_domain (handles->entries [slot]) == domain) {
828                                         handles->bitmap [slot / 32] &= ~(1 << (slot % 32));
829                                         handles->entries [slot] = NULL;
830                                 }
831                         }
832                 }
833                 unlock_handles (handles);
834         }
835
836 }
837
838 #ifndef HAVE_NULL_GC
839
840 #if USE_POSIX_SEM
841 static sem_t finalizer_sem;
842 #endif
843 static HANDLE finalizer_event;
844 static volatile gboolean finished=FALSE;
845
846 void
847 mono_gc_finalize_notify (void)
848 {
849 #ifdef DEBUG
850         g_message (G_GNUC_PRETTY_FUNCTION ": prodding finalizer");
851 #endif
852
853 #if USE_POSIX_SEM
854         sem_post (&finalizer_sem);
855 #else
856         SetEvent (finalizer_event);
857 #endif
858 }
859
860 #ifdef HAVE_BOEHM_GC
861
862 static void
863 collect_objects (gpointer key, gpointer value, gpointer user_data)
864 {
865         GPtrArray *arr = (GPtrArray*)user_data;
866         g_ptr_array_add (arr, key);
867 }
868
869 #endif
870
871 /*
872  * finalize_domain_objects:
873  *
874  *  Run the finalizers of all finalizable objects in req->domain.
875  */
876 static void
877 finalize_domain_objects (DomainFinalizationReq *req)
878 {
879         MonoDomain *domain = req->domain;
880
881 #ifdef HAVE_BOEHM_GC
882         while (g_hash_table_size (domain->finalizable_objects_hash) > 0) {
883                 int i;
884                 GPtrArray *objs;
885                 /* 
886                  * Since the domain is unloading, nobody is allowed to put
887                  * new entries into the hash table. But finalize_object might
888                  * remove entries from the hash table, so we make a copy.
889                  */
890                 objs = g_ptr_array_new ();
891                 g_hash_table_foreach (domain->finalizable_objects_hash, collect_objects, objs);
892                 /* printf ("FINALIZING %d OBJECTS.\n", objs->len); */
893
894                 for (i = 0; i < objs->len; ++i) {
895                         MonoObject *o = (MonoObject*)g_ptr_array_index (objs, i);
896                         /* FIXME: Avoid finalizing threads, etc */
897                         run_finalize (o, 0);
898                 }
899
900                 g_ptr_array_free (objs, TRUE);
901         }
902 #elif defined(HAVE_SGEN_GC)
903 #define NUM_FOBJECTS 64
904         MonoObject *to_finalize [NUM_FOBJECTS];
905         int count;
906         while ((count = mono_gc_finalizers_for_domain (domain, to_finalize, NUM_FOBJECTS))) {
907                 int i;
908                 for (i = 0; i < count; ++i) {
909                         run_finalize (to_finalize [i], 0);
910                 }
911         }
912 #endif
913
914         /* Process finalizers which are already in the queue */
915         mono_gc_invoke_finalizers ();
916
917         /* printf ("DONE.\n"); */
918         SetEvent (req->done_event);
919
920         /* The event is closed in mono_domain_finalize if we get here */
921         g_free (req);
922 }
923
924 static guint32
925 finalizer_thread (gpointer unused)
926 {
927         gc_thread = mono_thread_current ();
928
929         SetEvent (thread_started_event);
930
931         while (!finished) {
932                 /* Wait to be notified that there's at least one
933                  * finaliser to run
934                  */
935 #if USE_POSIX_SEM
936                 sem_wait (&finalizer_sem);
937 #else
938                 /* Use alertable=FALSE since we will be asked to exit using the event too */
939                 WaitForSingleObjectEx (finalizer_event, INFINITE, FALSE);
940 #endif
941
942 #ifndef DISABLE_ATTACH
943                 mono_attach_maybe_start ();
944 #endif
945
946                 if (domains_to_finalize) {
947                         mono_finalizer_lock ();
948                         if (domains_to_finalize) {
949                                 DomainFinalizationReq *req = domains_to_finalize->data;
950                                 domains_to_finalize = g_slist_remove (domains_to_finalize, req);
951                                 mono_finalizer_unlock ();
952
953                                 finalize_domain_objects (req);
954                         } else {
955                                 mono_finalizer_unlock ();
956                         }
957                 }                               
958
959                 /* If finished == TRUE, mono_gc_cleanup has been called (from mono_runtime_cleanup),
960                  * before the domain is unloaded.
961                  */
962                 mono_gc_invoke_finalizers ();
963
964                 SetEvent (pending_done_event);
965         }
966
967         SetEvent (shutdown_event);
968         return 0;
969 }
970
971 void
972 mono_gc_init (void)
973 {
974         InitializeCriticalSection (&handle_section);
975         InitializeCriticalSection (&allocator_section);
976
977         InitializeCriticalSection (&finalizer_mutex);
978
979         MONO_GC_REGISTER_ROOT (gc_handles [HANDLE_NORMAL].entries);
980         MONO_GC_REGISTER_ROOT (gc_handles [HANDLE_PINNED].entries);
981
982         mono_gc_base_init ();
983
984         if (g_getenv ("GC_DONT_GC")) {
985                 gc_disabled = TRUE;
986                 return;
987         }
988         
989         finalizer_event = CreateEvent (NULL, FALSE, FALSE, NULL);
990         pending_done_event = CreateEvent (NULL, TRUE, FALSE, NULL);
991         shutdown_event = CreateEvent (NULL, TRUE, FALSE, NULL);
992         thread_started_event = CreateEvent (NULL, TRUE, FALSE, NULL);
993         if (finalizer_event == NULL || pending_done_event == NULL || shutdown_event == NULL || thread_started_event == NULL) {
994                 g_assert_not_reached ();
995         }
996 #if USE_POSIX_SEM
997         sem_init (&finalizer_sem, 0, 0);
998 #endif
999
1000         mono_thread_create (mono_domain_get (), finalizer_thread, NULL);
1001
1002         /*
1003          * Wait until the finalizer thread sets gc_thread since its value is needed
1004          * by mono_thread_attach ()
1005          *
1006          * FIXME: Eliminate this as to avoid some deadlocks on windows. 
1007          * Waiting for a new thread should result in a deadlock when the runtime is
1008          * initialized from _CorDllMain that is called while the OS loader lock is
1009          * held by LoadLibrary.
1010          */
1011         WaitForSingleObjectEx (thread_started_event, INFINITE, FALSE);
1012 }
1013
1014 void
1015 mono_gc_cleanup (void)
1016 {
1017 #ifdef DEBUG
1018         g_message (G_GNUC_PRETTY_FUNCTION ": cleaning up finalizer");
1019 #endif
1020
1021         if (!gc_disabled) {
1022                 ResetEvent (shutdown_event);
1023                 finished = TRUE;
1024                 if (mono_thread_current () != gc_thread) {
1025                         mono_gc_finalize_notify ();
1026                         /* Finishing the finalizer thread, so wait a little bit... */
1027                         /* MS seems to wait for about 2 seconds */
1028                         if (WaitForSingleObjectEx (shutdown_event, 2000, FALSE) == WAIT_TIMEOUT) {
1029                                 int ret;
1030
1031                                 /* Set a flag which the finalizer thread can check */
1032                                 suspend_finalizers = TRUE;
1033
1034                                 /* Try to abort the thread, in the hope that it is running managed code */
1035                                 mono_thread_stop (gc_thread);
1036
1037                                 /* Wait for it to stop */
1038                                 ret = WaitForSingleObjectEx (gc_thread->handle, 100, TRUE);
1039
1040                                 if (ret == WAIT_TIMEOUT) {
1041                                         /* 
1042                                          * The finalizer thread refused to die. There is not much we 
1043                                          * can do here, since the runtime is shutting down so the 
1044                                          * state the finalizer thread depends on will vanish.
1045                                          */
1046                                         g_warning ("Shutting down finalizer thread timed out.");
1047                                 } else {
1048                                         /*
1049                                          * FIXME: On unix, when the above wait returns, the thread 
1050                                          * might still be running io-layer code, or pthreads code.
1051                                          */
1052                                         Sleep (100);
1053                                 }
1054
1055                         }
1056                 }
1057                 gc_thread = NULL;
1058 #ifdef HAVE_BOEHM_GC
1059                 GC_finalizer_notifier = NULL;
1060 #endif
1061         }
1062
1063         DeleteCriticalSection (&handle_section);
1064         DeleteCriticalSection (&allocator_section);
1065         DeleteCriticalSection (&finalizer_mutex);
1066 }
1067
1068 #else
1069
1070 /* Null GC dummy functions */
1071 void
1072 mono_gc_finalize_notify (void)
1073 {
1074 }
1075
1076 void mono_gc_init (void)
1077 {
1078         InitializeCriticalSection (&handle_section);
1079 }
1080
1081 void mono_gc_cleanup (void)
1082 {
1083 }
1084
1085 #endif
1086
1087 /**
1088  * mono_gc_is_finalizer_thread:
1089  * @thread: the thread to test.
1090  *
1091  * In Mono objects are finalized asynchronously on a separate thread.
1092  * This routine tests whether the @thread argument represents the
1093  * finalization thread.
1094  * 
1095  * Returns true if @thread is the finalization thread.
1096  */
1097 gboolean
1098 mono_gc_is_finalizer_thread (MonoThread *thread)
1099 {
1100         return thread == gc_thread;
1101 }
1102
1103