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