98436f45413dcff9dc11a6893a3b664ffbd7f199
[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
217         req = g_new0 (DomainFinalizationReq, 1);
218         req->domain = domain;
219         req->done_event = done_event;
220         
221         mono_finalizer_lock ();
222
223         domains_to_finalize = g_slist_append (domains_to_finalize, req);
224
225         mono_finalizer_unlock ();
226
227         /* Tell the finalizer thread to finalize this appdomain */
228         mono_gc_finalize_notify ();
229
230         res = WaitForSingleObjectEx (done_event, timeout, TRUE);
231
232         /* printf ("WAIT RES: %d.\n", res); */
233         if (res == WAIT_TIMEOUT) {
234                 /* We leak the handle here */
235                 return FALSE;
236         }
237
238         CloseHandle (done_event);
239         return TRUE;
240 #else
241         /* We don't support domain finalization without a GC */
242         return FALSE;
243 #endif
244 }
245
246 void
247 ves_icall_System_GC_InternalCollect (int generation)
248 {
249         mono_gc_collect (generation);
250 }
251
252 gint64
253 ves_icall_System_GC_GetTotalMemory (MonoBoolean forceCollection)
254 {
255         MONO_ARCH_SAVE_REGS;
256
257         if (forceCollection)
258                 mono_gc_collect (mono_gc_max_generation ());
259         return mono_gc_get_used_size ();
260 }
261
262 void
263 ves_icall_System_GC_KeepAlive (MonoObject *obj)
264 {
265         MONO_ARCH_SAVE_REGS;
266
267         /*
268          * Does nothing.
269          */
270 }
271
272 void
273 ves_icall_System_GC_ReRegisterForFinalize (MonoObject *obj)
274 {
275         MONO_ARCH_SAVE_REGS;
276
277         object_register_finalizer (obj, run_finalize);
278 }
279
280 void
281 ves_icall_System_GC_SuppressFinalize (MonoObject *obj)
282 {
283         MONO_ARCH_SAVE_REGS;
284
285         /* delegates have no finalizers, but we register them to deal with the
286          * unmanaged->managed trampoline. We don't let the user suppress it
287          * otherwise we'd leak it.
288          */
289         if (obj->vtable->klass->delegate)
290                 return;
291
292         object_register_finalizer (obj, NULL);
293 }
294
295 void
296 ves_icall_System_GC_WaitForPendingFinalizers (void)
297 {
298         MONO_ARCH_SAVE_REGS;
299         
300 #ifndef HAVE_NULL_GC
301         if (!mono_gc_pending_finalizers ())
302                 return;
303
304         if (mono_thread_current () == gc_thread)
305                 /* Avoid deadlocks */
306                 return;
307
308         ResetEvent (pending_done_event);
309         mono_gc_finalize_notify ();
310         /* g_print ("Waiting for pending finalizers....\n"); */
311         WaitForSingleObjectEx (pending_done_event, INFINITE, TRUE);
312         /* g_print ("Done pending....\n"); */
313 #else
314 #endif
315 }
316 #define mono_allocator_lock() EnterCriticalSection (&allocator_section)
317 #define mono_allocator_unlock() LeaveCriticalSection (&allocator_section)
318 static CRITICAL_SECTION allocator_section;
319 static CRITICAL_SECTION handle_section;
320
321 typedef enum {
322         HANDLE_WEAK,
323         HANDLE_WEAK_TRACK,
324         HANDLE_NORMAL,
325         HANDLE_PINNED
326 } HandleType;
327
328 static void mono_gchandle_set_target (guint32 gchandle, MonoObject *obj);
329
330 MonoObject *
331 ves_icall_System_GCHandle_GetTarget (guint32 handle)
332 {
333         return mono_gchandle_get_target (handle);
334 }
335
336 /*
337  * if type == -1, change the target of the handle, otherwise allocate a new handle.
338  */
339 guint32
340 ves_icall_System_GCHandle_GetTargetHandle (MonoObject *obj, guint32 handle, gint32 type)
341 {
342         if (type == -1) {
343                 mono_gchandle_set_target (handle, obj);
344                 /* the handle doesn't change */
345                 return handle;
346         }
347         switch (type) {
348         case HANDLE_WEAK:
349                 return mono_gchandle_new_weakref (obj, FALSE);
350         case HANDLE_WEAK_TRACK:
351                 return mono_gchandle_new_weakref (obj, TRUE);
352         case HANDLE_NORMAL:
353                 return mono_gchandle_new (obj, FALSE);
354         case HANDLE_PINNED:
355                 return mono_gchandle_new (obj, TRUE);
356         default:
357                 g_assert_not_reached ();
358         }
359         return 0;
360 }
361
362 void
363 ves_icall_System_GCHandle_FreeHandle (guint32 handle)
364 {
365         mono_gchandle_free (handle);
366 }
367
368 gpointer
369 ves_icall_System_GCHandle_GetAddrOfPinnedObject (guint32 handle)
370 {
371         MonoObject *obj;
372
373         obj = mono_gchandle_get_target (handle);
374         if (obj) {
375                 MonoClass *klass = mono_object_class (obj);
376                 if (klass == mono_defaults.string_class) {
377                         return mono_string_chars ((MonoString*)obj);
378                 } else if (klass->rank) {
379                         return mono_array_addr ((MonoArray*)obj, char, 0);
380                 } else {
381                         /* the C# code will check and throw the exception */
382                         /* FIXME: missing !klass->blittable test, see bug #61134 */
383                         if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
384                                 return (gpointer)-1;
385                         return (char*)obj + sizeof (MonoObject);
386                 }
387         }
388         return NULL;
389 }
390
391 typedef struct {
392         guint32  *bitmap;
393         gpointer *entries;
394         guint32   size;
395         guint8    type;
396         guint     slot_hint : 24; /* starting slot for search */
397         /* 2^16 appdomains should be enough for everyone (though I know I'll regret this in 20 years) */
398         /* we alloc this only for weak refs, since we can get the domain directly in the other cases */
399         guint16  *domain_ids;
400 } HandleData;
401
402 /* weak and weak-track arrays will be allocated in malloc memory 
403  */
404 static HandleData gc_handles [] = {
405         {NULL, NULL, 0, HANDLE_WEAK, 0},
406         {NULL, NULL, 0, HANDLE_WEAK_TRACK, 0},
407         {NULL, NULL, 0, HANDLE_NORMAL, 0},
408         {NULL, NULL, 0, HANDLE_PINNED, 0}
409 };
410
411 #define lock_handles(handles) EnterCriticalSection (&handle_section)
412 #define unlock_handles(handles) LeaveCriticalSection (&handle_section)
413
414 static int
415 find_first_unset (guint32 bitmap)
416 {
417         int i;
418         for (i = 0; i < 32; ++i) {
419                 if (!(bitmap & (1 << i)))
420                         return i;
421         }
422         return -1;
423 }
424
425 static guint32
426 alloc_handle (HandleData *handles, MonoObject *obj)
427 {
428         gint slot, i;
429         lock_handles (handles);
430         if (!handles->size) {
431                 handles->size = 32;
432                 if (handles->type > HANDLE_WEAK_TRACK) {
433                         handles->entries = mono_gc_alloc_fixed (sizeof (gpointer) * handles->size, NULL);
434                 } else {
435                         handles->entries = g_malloc0 (sizeof (gpointer) * handles->size);
436                         handles->domain_ids = g_malloc0 (sizeof (guint16) * handles->size);
437                 }
438                 handles->bitmap = g_malloc0 (handles->size / 8);
439         }
440         i = -1;
441         for (slot = handles->slot_hint; slot < handles->size / 32; ++slot) {
442                 if (handles->bitmap [slot] != 0xffffffff) {
443                         i = find_first_unset (handles->bitmap [slot]);
444                         handles->slot_hint = slot;
445                         break;
446                 }
447         }
448         if (i == -1 && handles->slot_hint != 0) {
449                 for (slot = 0; slot < handles->slot_hint; ++slot) {
450                         if (handles->bitmap [slot] != 0xffffffff) {
451                                 i = find_first_unset (handles->bitmap [slot]);
452                                 handles->slot_hint = slot;
453                                 break;
454                         }
455                 }
456         }
457         if (i == -1) {
458                 guint32 *new_bitmap;
459                 guint32 new_size = handles->size * 2; /* always double: we memset to 0 based on this below */
460
461                 /* resize and copy the bitmap */
462                 new_bitmap = g_malloc0 (new_size / 8);
463                 memcpy (new_bitmap, handles->bitmap, handles->size / 8);
464                 g_free (handles->bitmap);
465                 handles->bitmap = new_bitmap;
466
467                 /* resize and copy the entries */
468                 if (handles->type > HANDLE_WEAK_TRACK) {
469                         gpointer *entries;
470                         entries = mono_gc_alloc_fixed (sizeof (gpointer) * new_size, NULL);
471                         memcpy (entries, handles->entries, sizeof (gpointer) * handles->size);
472                         handles->entries = entries;
473                 } else {
474                         gpointer *entries;
475                         guint16 *domain_ids;
476                         domain_ids = g_malloc0 (sizeof (guint16) * new_size);
477                         entries = g_malloc (sizeof (gpointer) * new_size);
478                         /* we disable GC because we could lose some disappearing link updates */
479                         mono_gc_disable ();
480                         memcpy (entries, handles->entries, sizeof (gpointer) * handles->size);
481                         memset (entries + handles->size, 0, sizeof (gpointer) * handles->size);
482                         memcpy (domain_ids, handles->domain_ids, sizeof (guint16) * handles->size);
483                         for (i = 0; i < handles->size; ++i) {
484                                 MonoObject *obj = mono_gc_weak_link_get (&(handles->entries [i]));
485                                 if (handles->entries [i])
486                                         mono_gc_weak_link_remove (&(handles->entries [i]));
487                                 /*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]);*/
488                                 if (obj) {
489                                         mono_gc_weak_link_add (&(entries [i]), obj);
490                                 }
491                         }
492                         g_free (handles->entries);
493                         g_free (handles->domain_ids);
494                         handles->entries = entries;
495                         handles->domain_ids = domain_ids;
496                         mono_gc_enable ();
497                 }
498
499                 /* set i and slot to the next free position */
500                 i = 0;
501                 slot = (handles->size + 1) / 32;
502                 handles->slot_hint = handles->size + 1;
503                 handles->size = new_size;
504         }
505         handles->bitmap [slot] |= 1 << i;
506         slot = slot * 32 + i;
507         handles->entries [slot] = obj;
508         if (handles->type <= HANDLE_WEAK_TRACK) {
509                 if (obj)
510                         mono_gc_weak_link_add (&(handles->entries [slot]), obj);
511         }
512
513         unlock_handles (handles);
514         /*g_print ("allocated entry %d of type %d to object %p (in slot: %p)\n", slot, handles->type, obj, handles->entries [slot]);*/
515         return (slot << 3) | (handles->type + 1);
516 }
517
518 /**
519  * mono_gchandle_new:
520  * @obj: managed object to get a handle for
521  * @pinned: whether the object should be pinned
522  *
523  * This returns a handle that wraps the object, this is used to keep a
524  * reference to a managed object from the unmanaged world and preventing the
525  * object from being disposed.
526  * 
527  * If @pinned is false the address of the object can not be obtained, if it is
528  * true the address of the object can be obtained.  This will also pin the
529  * object so it will not be possible by a moving garbage collector to move the
530  * object. 
531  * 
532  * Returns: a handle that can be used to access the object from
533  * unmanaged code.
534  */
535 guint32
536 mono_gchandle_new (MonoObject *obj, gboolean pinned)
537 {
538         return alloc_handle (&gc_handles [pinned? HANDLE_PINNED: HANDLE_NORMAL], obj);
539 }
540
541 /**
542  * mono_gchandle_new_weakref:
543  * @obj: managed object to get a handle for
544  * @pinned: whether the object should be pinned
545  *
546  * This returns a weak handle that wraps the object, this is used to
547  * keep a reference to a managed object from the unmanaged world.
548  * Unlike the mono_gchandle_new the object can be reclaimed by the
549  * garbage collector.  In this case the value of the GCHandle will be
550  * set to zero.
551  * 
552  * If @pinned is false the address of the object can not be obtained, if it is
553  * true the address of the object can be obtained.  This will also pin the
554  * object so it will not be possible by a moving garbage collector to move the
555  * object. 
556  * 
557  * Returns: a handle that can be used to access the object from
558  * unmanaged code.
559  */
560 guint32
561 mono_gchandle_new_weakref (MonoObject *obj, gboolean track_resurrection)
562 {
563         return alloc_handle (&gc_handles [track_resurrection? HANDLE_WEAK_TRACK: HANDLE_WEAK], obj);
564 }
565
566 /**
567  * mono_gchandle_get_target:
568  * @gchandle: a GCHandle's handle.
569  *
570  * The handle was previously created by calling mono_gchandle_new or
571  * mono_gchandle_new_weakref. 
572  *
573  * Returns a pointer to the MonoObject represented by the handle or
574  * NULL for a collected object if using a weakref handle.
575  */
576 MonoObject*
577 mono_gchandle_get_target (guint32 gchandle)
578 {
579         guint slot = gchandle >> 3;
580         guint type = (gchandle & 7) - 1;
581         HandleData *handles = &gc_handles [type];
582         MonoObject *obj = NULL;
583         if (type > 3)
584                 return NULL;
585         lock_handles (handles);
586         if (slot < handles->size && (handles->bitmap [slot / 32] & (1 << (slot % 32)))) {
587                 if (handles->type <= HANDLE_WEAK_TRACK) {
588                         obj = mono_gc_weak_link_get (&handles->entries [slot]);
589                 } else {
590                         obj = handles->entries [slot];
591                 }
592         } else {
593                 /* print a warning? */
594         }
595         unlock_handles (handles);
596         /*g_print ("get target of entry %d of type %d: %p\n", slot, handles->type, obj);*/
597         return obj;
598 }
599
600 static void
601 mono_gchandle_set_target (guint32 gchandle, MonoObject *obj)
602 {
603         guint slot = gchandle >> 3;
604         guint type = (gchandle & 7) - 1;
605         HandleData *handles = &gc_handles [type];
606         if (type > 3)
607                 return;
608         lock_handles (handles);
609         if (slot < handles->size && (handles->bitmap [slot / 32] & (1 << (slot % 32)))) {
610                 if (handles->type <= HANDLE_WEAK_TRACK) {
611                         if (handles->entries [slot])
612                                 mono_gc_weak_link_remove (&handles->entries [slot]);
613                         if (obj)
614                                 mono_gc_weak_link_add (&handles->entries [slot], obj);
615                 } else {
616                         handles->entries [slot] = obj;
617                 }
618         } else {
619                 /* print a warning? */
620         }
621         /*g_print ("changed entry %d of type %d to object %p (in slot: %p)\n", slot, handles->type, obj, handles->entries [slot]);*/
622         unlock_handles (handles);
623 }
624
625 /**
626  * mono_gchandle_is_in_domain:
627  * @gchandle: a GCHandle's handle.
628  * @domain: An application domain.
629  *
630  * Returns: true if the object wrapped by the @gchandle belongs to the specific @domain.
631  */
632 gboolean
633 mono_gchandle_is_in_domain (guint32 gchandle, MonoDomain *domain)
634 {
635         guint slot = gchandle >> 3;
636         guint type = (gchandle & 7) - 1;
637         HandleData *handles = &gc_handles [type];
638         gboolean result = FALSE;
639         if (type > 3)
640                 return FALSE;
641         lock_handles (handles);
642         if (slot < handles->size && (handles->bitmap [slot / 32] & (1 << (slot % 32)))) {
643                 if (handles->type <= HANDLE_WEAK_TRACK) {
644                         result = domain->domain_id == handles->domain_ids [slot];
645                 } else {
646                         MonoObject *obj;
647                         obj = handles->entries [slot];
648                         if (obj == NULL)
649                                 result = TRUE;
650                         else
651                                 result = domain == mono_object_domain (obj);
652                 }
653         } else {
654                 /* print a warning? */
655         }
656         unlock_handles (handles);
657         return result;
658 }
659
660 /**
661  * mono_gchandle_free:
662  * @gchandle: a GCHandle's handle.
663  *
664  * Frees the @gchandle handle.  If there are no outstanding
665  * references, the garbage collector can reclaim the memory of the
666  * object wrapped. 
667  */
668 void
669 mono_gchandle_free (guint32 gchandle)
670 {
671         guint slot = gchandle >> 3;
672         guint type = (gchandle & 7) - 1;
673         HandleData *handles = &gc_handles [type];
674         if (type > 3)
675                 return;
676         lock_handles (handles);
677         if (slot < handles->size && (handles->bitmap [slot / 32] & (1 << (slot % 32)))) {
678                 if (handles->type <= HANDLE_WEAK_TRACK) {
679                         if (handles->entries [slot])
680                                 mono_gc_weak_link_remove (&handles->entries [slot]);
681                 } else {
682                         handles->entries [slot] = NULL;
683                 }
684                 handles->bitmap [slot / 32] &= ~(1 << (slot % 32));
685         } else {
686                 /* print a warning? */
687         }
688         /*g_print ("freed entry %d of type %d\n", slot, handles->type);*/
689         unlock_handles (handles);
690 }
691
692 /**
693  * mono_gchandle_free_domain:
694  * @domain: domain that is unloading
695  *
696  * Function used internally to cleanup any GC handle for objects belonging
697  * to the specified domain during appdomain unload.
698  */
699 void
700 mono_gchandle_free_domain (MonoDomain *domain)
701 {
702         guint type;
703
704         for (type = 0; type < 3; ++type) {
705                 guint slot;
706                 HandleData *handles = &gc_handles [type];
707                 lock_handles (handles);
708                 for (slot = 0; slot < handles->size; ++slot) {
709                         if (!(handles->bitmap [slot / 32] & (1 << (slot % 32))))
710                                 continue;
711                         if (type <= HANDLE_WEAK_TRACK) {
712                                 if (domain->domain_id == handles->domain_ids [slot]) {
713                                         handles->bitmap [slot / 32] &= ~(1 << (slot % 32));
714                                         if (handles->entries [slot])
715                                                 mono_gc_weak_link_remove (&handles->entries [slot]);
716                                 }
717                         } else {
718                                 if (handles->entries [slot] && mono_object_domain (handles->entries [slot]) == domain) {
719                                         handles->bitmap [slot / 32] &= ~(1 << (slot % 32));
720                                         handles->entries [slot] = NULL;
721                                 }
722                         }
723                 }
724                 unlock_handles (handles);
725         }
726
727 }
728
729 #ifndef HAVE_NULL_GC
730
731 static HANDLE finalizer_event;
732 static volatile gboolean finished=FALSE;
733
734 void
735 mono_gc_finalize_notify (void)
736 {
737 #ifdef DEBUG
738         g_message (G_GNUC_PRETTY_FUNCTION ": prodding finalizer");
739 #endif
740
741         SetEvent (finalizer_event);
742 }
743
744 static void
745 collect_objects (gpointer key, gpointer value, gpointer user_data)
746 {
747         GPtrArray *arr = (GPtrArray*)user_data;
748         g_ptr_array_add (arr, key);
749 }
750
751 /*
752  * finalize_domain_objects:
753  *
754  *  Run the finalizers of all finalizable objects in req->domain.
755  */
756 static void
757 finalize_domain_objects (DomainFinalizationReq *req)
758 {
759         int i;
760         GPtrArray *objs;
761         MonoDomain *domain = req->domain;
762         
763         while (g_hash_table_size (domain->finalizable_objects_hash) > 0) {
764                 /* 
765                  * Since the domain is unloading, nobody is allowed to put
766                  * new entries into the hash table. But finalize_object might
767                  * remove entries from the hash table, so we make a copy.
768                  */
769                 objs = g_ptr_array_new ();
770                 g_hash_table_foreach (domain->finalizable_objects_hash, 
771                                                           collect_objects, objs);
772                 /* printf ("FINALIZING %d OBJECTS.\n", objs->len); */
773
774                 for (i = 0; i < objs->len; ++i) {
775                         MonoObject *o = (MonoObject*)g_ptr_array_index (objs, i);
776                         /* FIXME: Avoid finalizing threads, etc */
777                         run_finalize (o, 0);
778                 }
779
780                 g_ptr_array_free (objs, TRUE);
781         }
782
783         /* Process finalizers which are already in the queue */
784         mono_gc_invoke_finalizers ();
785
786         /* printf ("DONE.\n"); */
787         SetEvent (req->done_event);
788
789         /* The event is closed in mono_domain_finalize if we get here */
790         g_free (req);
791 }
792
793 static guint32 finalizer_thread (gpointer unused)
794 {
795         gc_thread = mono_thread_current ();
796
797         SetEvent (thread_started_event);
798
799         while(!finished) {
800                 /* Wait to be notified that there's at least one
801                  * finaliser to run
802                  */
803                 /* Use alertable=FALSE since we will be asked to exit using the event too */
804                 WaitForSingleObjectEx (finalizer_event, INFINITE, FALSE);
805
806                 if (domains_to_finalize) {
807                         mono_finalizer_lock ();
808                         if (domains_to_finalize) {
809                                 DomainFinalizationReq *req = domains_to_finalize->data;
810                                 domains_to_finalize = g_slist_remove (domains_to_finalize, req);
811                                 mono_finalizer_unlock ();
812
813                                 finalize_domain_objects (req);
814                         }
815                         else
816                                 mono_finalizer_unlock ();
817                 }                               
818
819 #ifdef DEBUG
820                 g_message (G_GNUC_PRETTY_FUNCTION ": invoking finalizers");
821 #endif
822
823                 /* If finished == TRUE, mono_gc_cleanup has been called (from mono_runtime_cleanup),
824                  * before the domain is unloaded.
825                  */
826                 mono_gc_invoke_finalizers ();
827
828                 SetEvent (pending_done_event);
829         }
830
831         SetEvent (shutdown_event);
832         return(0);
833 }
834
835 /* 
836  * Enable or disable the separate finalizer thread.
837  * It's currently disabled because it still requires some
838  * work in the rest of the runtime.
839  */
840 #define ENABLE_FINALIZER_THREAD
841
842 void
843 mono_gc_init (void)
844 {
845         InitializeCriticalSection (&handle_section);
846         InitializeCriticalSection (&allocator_section);
847
848         InitializeCriticalSection (&finalizer_mutex);
849
850         MONO_GC_REGISTER_ROOT (gc_handles [HANDLE_NORMAL].entries);
851         MONO_GC_REGISTER_ROOT (gc_handles [HANDLE_PINNED].entries);
852
853         mono_gc_base_init ();
854
855 #ifdef ENABLE_FINALIZER_THREAD
856
857         if (g_getenv ("GC_DONT_GC")) {
858                 gc_disabled = TRUE;
859                 return;
860         }
861         
862         finalizer_event = CreateEvent (NULL, FALSE, FALSE, NULL);
863         pending_done_event = CreateEvent (NULL, TRUE, FALSE, NULL);
864         shutdown_event = CreateEvent (NULL, TRUE, FALSE, NULL);
865         thread_started_event = CreateEvent (NULL, TRUE, FALSE, NULL);
866         if (finalizer_event == NULL || pending_done_event == NULL || shutdown_event == NULL || thread_started_event == NULL) {
867                 g_assert_not_reached ();
868         }
869
870         mono_thread_create (mono_domain_get (), finalizer_thread, NULL);
871         /*
872          * Wait until the finalizer thread sets gc_thread since its value is needed
873          * by mono_thread_attach ()
874          */
875         WaitForSingleObjectEx (thread_started_event, INFINITE, FALSE);
876 #endif
877 }
878
879 void mono_gc_cleanup (void)
880 {
881 #ifdef DEBUG
882         g_message (G_GNUC_PRETTY_FUNCTION ": cleaning up finalizer");
883 #endif
884
885 #ifdef ENABLE_FINALIZER_THREAD
886         if (!gc_disabled) {
887                 ResetEvent (shutdown_event);
888                 finished = TRUE;
889                 if (mono_thread_current () != gc_thread) {
890                         mono_gc_finalize_notify ();
891                         /* Finishing the finalizer thread, so wait a little bit... */
892                         /* MS seems to wait for about 2 seconds */
893                         if (WaitForSingleObjectEx (shutdown_event, 2000, FALSE) == WAIT_TIMEOUT) {
894                                 mono_thread_stop (gc_thread);
895                         }
896                 }
897                 gc_thread = NULL;
898 #ifdef HAVE_BOEHM_GC
899                 GC_finalizer_notifier = NULL;
900 #endif
901         }
902
903 #endif
904
905         DeleteCriticalSection (&handle_section);
906         DeleteCriticalSection (&allocator_section);
907         DeleteCriticalSection (&finalizer_mutex);
908 }
909
910 #else
911
912 /* no Boehm GC support. */
913 void mono_gc_init (void)
914 {
915         InitializeCriticalSection (&handle_section);
916 }
917
918 void mono_gc_cleanup (void)
919 {
920 }
921
922 #endif
923
924 /**
925  * mono_gc_is_finalizer_thread:
926  * @thread: the thread to test.
927  *
928  * In Mono objects are finalized asynchronously on a separate thread.
929  * This routine tests whether the @thread argument represents the
930  * finalization thread.
931  * 
932  * Returns true if @thread is the finalization thread.
933  */
934 gboolean
935 mono_gc_is_finalizer_thread (MonoThread *thread)
936 {
937         return thread == gc_thread;
938 }
939
940