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