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