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