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