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