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