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