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