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