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