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