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