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