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