[utils] Move mutex and semaphore to mono_os_*
[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
15 #include <mono/metadata/gc-internals.h>
16 #include <mono/metadata/mono-gc.h>
17 #include <mono/metadata/threads.h>
18 #include <mono/metadata/tabledefs.h>
19 #include <mono/metadata/exception.h>
20 #include <mono/metadata/profiler-private.h>
21 #include <mono/metadata/domain-internals.h>
22 #include <mono/metadata/class-internals.h>
23 #include <mono/metadata/metadata-internals.h>
24 #include <mono/metadata/mono-mlist.h>
25 #include <mono/metadata/threads-types.h>
26 #include <mono/metadata/threadpool-ms.h>
27 #include <mono/sgen/sgen-conf.h>
28 #include <mono/sgen/sgen-gc.h>
29 #include <mono/utils/mono-logger-internals.h>
30 #include <mono/metadata/gc-internals.h>
31 #include <mono/metadata/marshal.h> /* for mono_delegate_free_ftnptr () */
32 #include <mono/metadata/attach.h>
33 #include <mono/metadata/console-io.h>
34 #include <mono/utils/mono-os-semaphore.h>
35 #include <mono/utils/mono-memory-model.h>
36 #include <mono/utils/mono-counters.h>
37 #include <mono/utils/mono-time.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 static gboolean gc_disabled = FALSE;
52
53 static gboolean finalizing_root_domain = FALSE;
54
55 gboolean log_finalizers = FALSE;
56 gboolean mono_do_not_finalize = FALSE;
57 gchar **mono_do_not_finalize_class_names = NULL;
58
59 #define mono_finalizer_lock() mono_os_mutex_lock (&finalizer_mutex)
60 #define mono_finalizer_unlock() mono_os_mutex_unlock (&finalizer_mutex)
61 static mono_mutex_t finalizer_mutex;
62 static mono_mutex_t reference_queue_mutex;
63
64 static GSList *domains_to_finalize= NULL;
65 static MonoMList *threads_to_finalize = NULL;
66
67 static gboolean finalizer_thread_exited;
68 /* Uses finalizer_mutex */
69 static mono_cond_t exited_cond;
70
71 static MonoInternalThread *gc_thread;
72
73 static void object_register_finalizer (MonoObject *obj, void (*callback)(void *, void*));
74
75 static void reference_queue_proccess_all (void);
76 static void mono_reference_queue_cleanup (void);
77 static void reference_queue_clear_for_domain (MonoDomain *domain);
78 static HANDLE pending_done_event;
79
80 static guint32
81 guarded_wait (HANDLE handle, guint32 timeout, gboolean alertable)
82 {
83         guint32 result;
84
85         MONO_PREPARE_BLOCKING;
86         result = WaitForSingleObjectEx (handle, timeout, alertable);
87         MONO_FINISH_BLOCKING;
88
89         return result;
90 }
91
92 static void
93 add_thread_to_finalize (MonoInternalThread *thread)
94 {
95         mono_finalizer_lock ();
96         if (!threads_to_finalize)
97                 MONO_GC_REGISTER_ROOT_SINGLE (threads_to_finalize, MONO_ROOT_SOURCE_FINALIZER_QUEUE, "finalizable threads list");
98         threads_to_finalize = mono_mlist_append (threads_to_finalize, (MonoObject*)thread);
99         mono_finalizer_unlock ();
100 }
101
102 static gboolean suspend_finalizers = FALSE;
103 /* 
104  * actually, we might want to queue the finalize requests in a separate thread,
105  * but we need to be careful about the execution domain of the thread...
106  */
107 void
108 mono_gc_run_finalize (void *obj, void *data)
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         // This function is called from the innards of the GC, so our best alternative for now is to do polling here
121         mono_threads_safepoint ();
122
123         o = (MonoObject*)((char*)obj + GPOINTER_TO_UINT (data));
124
125         if (mono_do_not_finalize) {
126                 if (!mono_do_not_finalize_class_names)
127                         return;
128
129                 size_t namespace_len = strlen (o->vtable->klass->name_space);
130                 for (int i = 0; mono_do_not_finalize_class_names [i]; ++i) {
131                         const char *name = mono_do_not_finalize_class_names [i];
132                         if (strncmp (name, o->vtable->klass->name_space, namespace_len))
133                                 break;
134                         if (name [namespace_len] != '.')
135                                 break;
136                         if (strcmp (name + namespace_len + 1, o->vtable->klass->name))
137                                 break;
138                         return;
139                 }
140         }
141
142         if (log_finalizers)
143                 g_log ("mono-gc-finalizers", G_LOG_LEVEL_DEBUG, "<%s at %p> Starting finalizer checks.", o->vtable->klass->name, o);
144
145         if (suspend_finalizers)
146                 return;
147
148         domain = o->vtable->domain;
149
150 #ifndef HAVE_SGEN_GC
151         mono_domain_finalizers_lock (domain);
152
153         o2 = g_hash_table_lookup (domain->finalizable_objects_hash, o);
154
155         mono_domain_finalizers_unlock (domain);
156
157         if (!o2)
158                 /* Already finalized somehow */
159                 return;
160 #endif
161
162         /* make sure the finalizer is not called again if the object is resurrected */
163         object_register_finalizer (obj, NULL);
164
165         if (log_finalizers)
166                 g_log ("mono-gc-finalizers", G_LOG_LEVEL_MESSAGE, "<%s at %p> Registered finalizer as processed.", o->vtable->klass->name, o);
167
168         if (o->vtable->klass == mono_defaults.internal_thread_class) {
169                 MonoInternalThread *t = (MonoInternalThread*)o;
170
171                 if (mono_gc_is_finalizer_internal_thread (t))
172                         /* Avoid finalizing ourselves */
173                         return;
174
175                 if (t->threadpool_thread && finalizing_root_domain) {
176                         /* Don't finalize threadpool threads when
177                            shutting down - they're finalized when the
178                            threadpool shuts down. */
179                         add_thread_to_finalize (t);
180                         return;
181                 }
182         }
183
184         if (o->vtable->klass->image == mono_defaults.corlib && !strcmp (o->vtable->klass->name, "DynamicMethod") && finalizing_root_domain) {
185                 /*
186                  * These can't be finalized during unloading/shutdown, since that would
187                  * free the native code which can still be referenced by other
188                  * finalizers.
189                  * FIXME: This is not perfect, objects dying at the same time as 
190                  * dynamic methods can still reference them even when !shutdown.
191                  */
192                 return;
193         }
194
195         if (mono_runtime_get_no_exec ())
196                 return;
197
198         /* speedup later... and use a timeout */
199         /* g_print ("Finalize run on %p %s.%s\n", o, mono_object_class (o)->name_space, mono_object_class (o)->name); */
200
201         /* Use _internal here, since this thread can enter a doomed appdomain */
202         mono_domain_set_internal (mono_object_domain (o));
203
204         /* delegates that have a native function pointer allocated are
205          * registered for finalization, but they don't have a Finalize
206          * method, because in most cases it's not needed and it's just a waste.
207          */
208         if (o->vtable->klass->delegate) {
209                 MonoDelegate* del = (MonoDelegate*)o;
210                 if (del->delegate_trampoline)
211                         mono_delegate_free_ftnptr ((MonoDelegate*)o);
212                 mono_domain_set_internal (caller_domain);
213                 return;
214         }
215
216         finalizer = mono_class_get_finalizer (o->vtable->klass);
217
218         /* If object has a CCW but has no finalizer, it was only
219          * registered for finalization in order to free the CCW.
220          * Else it needs the regular finalizer run.
221          * FIXME: what to do about ressurection and suppression
222          * of finalizer on object with CCW.
223          */
224         if (mono_marshal_free_ccw (o) && !finalizer) {
225                 mono_domain_set_internal (caller_domain);
226                 return;
227         }
228
229         /* 
230          * To avoid the locking plus the other overhead of mono_runtime_invoke (),
231          * create and precompile a wrapper which calls the finalize method using
232          * a CALLVIRT.
233          */
234         if (log_finalizers)
235                 g_log ("mono-gc-finalizers", G_LOG_LEVEL_MESSAGE, "<%s at %p> Compiling finalizer.", o->vtable->klass->name, o);
236
237         if (!domain->finalize_runtime_invoke) {
238                 MonoMethod *invoke = mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE, FALSE);
239
240                 domain->finalize_runtime_invoke = mono_compile_method (invoke);
241         }
242
243         runtime_invoke = domain->finalize_runtime_invoke;
244
245         mono_runtime_class_init (o->vtable);
246
247         if (G_UNLIKELY (MONO_GC_FINALIZE_INVOKE_ENABLED ())) {
248                 MONO_GC_FINALIZE_INVOKE ((unsigned long)o, mono_object_get_size (o),
249                                 o->vtable->klass->name_space, o->vtable->klass->name);
250         }
251
252         if (log_finalizers)
253                 g_log ("mono-gc-finalizers", G_LOG_LEVEL_MESSAGE, "<%s at %p> Calling finalizer.", o->vtable->klass->name, o);
254
255         runtime_invoke (o, NULL, &exc, NULL);
256
257         if (log_finalizers)
258                 g_log ("mono-gc-finalizers", G_LOG_LEVEL_MESSAGE, "<%s at %p> Returned from finalizer.", o->vtable->klass->name, o);
259
260         if (exc)
261                 mono_thread_internal_unhandled_exception (exc);
262
263         mono_domain_set_internal (caller_domain);
264 }
265
266 void
267 mono_gc_finalize_threadpool_threads (void)
268 {
269         while (threads_to_finalize) {
270                 MonoInternalThread *thread = (MonoInternalThread*) mono_mlist_get_data (threads_to_finalize);
271
272                 /* Force finalization of the thread. */
273                 thread->threadpool_thread = FALSE;
274                 mono_object_register_finalizer ((MonoObject*)thread);
275
276                 mono_gc_run_finalize (thread, NULL);
277
278                 threads_to_finalize = mono_mlist_next (threads_to_finalize);
279         }
280 }
281
282 gpointer
283 mono_gc_out_of_memory (size_t size)
284 {
285         /* 
286          * we could allocate at program startup some memory that we could release 
287          * back to the system at this point if we're really low on memory (ie, size is
288          * lower than the memory we set apart)
289          */
290         mono_raise_exception (mono_domain_get ()->out_of_memory_ex);
291
292         return NULL;
293 }
294
295 /*
296  * Some of our objects may point to a different address than the address returned by GC_malloc()
297  * (because of the GetHashCode hack), but we need to pass the real address to register_finalizer.
298  * This also means that in the callback we need to adjust the pointer to get back the real
299  * MonoObject*.
300  * We also need to be consistent in the use of the GC_debug* variants of malloc and register_finalizer, 
301  * since that, too, can cause the underlying pointer to be offset.
302  */
303 static void
304 object_register_finalizer (MonoObject *obj, void (*callback)(void *, void*))
305 {
306         MonoDomain *domain;
307
308         if (obj == NULL)
309                 mono_raise_exception (mono_get_exception_argument_null ("obj"));
310
311         domain = obj->vtable->domain;
312
313 #if HAVE_BOEHM_GC
314         if (mono_domain_is_unloading (domain) && (callback != NULL))
315                 /*
316                  * Can't register finalizers in a dying appdomain, since they
317                  * could be invoked after the appdomain has been unloaded.
318                  */
319                 return;
320
321         mono_domain_finalizers_lock (domain);
322
323         if (callback)
324                 g_hash_table_insert (domain->finalizable_objects_hash, obj, obj);
325         else
326                 g_hash_table_remove (domain->finalizable_objects_hash, obj);
327
328         mono_domain_finalizers_unlock (domain);
329
330         mono_gc_register_for_finalization (obj, callback);
331 #elif defined(HAVE_SGEN_GC)
332         /*
333          * If we register finalizers for domains that are unloading we might
334          * end up running them while or after the domain is being cleared, so
335          * the objects will not be valid anymore.
336          */
337         if (!mono_domain_is_unloading (domain)) {
338                 MONO_TRY_BLOCKING;
339                 mono_gc_register_for_finalization (obj, callback);
340                 MONO_FINISH_TRY_BLOCKING;
341         }
342 #endif
343 }
344
345 /**
346  * mono_object_register_finalizer:
347  * @obj: object to register
348  *
349  * Records that object @obj has a finalizer, this will call the
350  * Finalize method when the garbage collector disposes the object.
351  * 
352  */
353 void
354 mono_object_register_finalizer (MonoObject *obj)
355 {
356         /* g_print ("Registered finalizer on %p %s.%s\n", obj, mono_object_class (obj)->name_space, mono_object_class (obj)->name); */
357         object_register_finalizer (obj, mono_gc_run_finalize);
358 }
359
360 /**
361  * mono_domain_finalize:
362  * @domain: the domain to finalize
363  * @timeout: msects to wait for the finalization to complete, -1 to wait indefinitely
364  *
365  *  Request finalization of all finalizable objects inside @domain. Wait
366  * @timeout msecs for the finalization to complete.
367  *
368  * Returns: TRUE if succeeded, FALSE if there was a timeout
369  */
370
371 gboolean
372 mono_domain_finalize (MonoDomain *domain, guint32 timeout) 
373 {
374         DomainFinalizationReq *req;
375         guint32 res;
376         HANDLE done_event;
377         MonoInternalThread *thread = mono_thread_internal_current ();
378
379 #if defined(__native_client__)
380         return FALSE;
381 #endif
382
383         if (mono_thread_internal_current () == gc_thread)
384                 /* We are called from inside a finalizer, not much we can do here */
385                 return FALSE;
386
387         /* 
388          * No need to create another thread 'cause the finalizer thread
389          * is still working and will take care of running the finalizers
390          */ 
391         
392         if (gc_disabled)
393                 return TRUE;
394
395         /* We don't support domain finalization without a GC */
396         if (mono_gc_is_null ())
397                 return FALSE;
398
399         mono_gc_collect (mono_gc_max_generation ());
400
401         done_event = CreateEvent (NULL, TRUE, FALSE, NULL);
402         if (done_event == NULL) {
403                 return FALSE;
404         }
405
406         req = g_new0 (DomainFinalizationReq, 1);
407         req->domain = domain;
408         req->done_event = done_event;
409
410         if (domain == mono_get_root_domain ())
411                 finalizing_root_domain = TRUE;
412         
413         mono_finalizer_lock ();
414
415         domains_to_finalize = g_slist_append (domains_to_finalize, req);
416
417         mono_finalizer_unlock ();
418
419         /* Tell the finalizer thread to finalize this appdomain */
420         mono_gc_finalize_notify ();
421
422         if (timeout == -1)
423                 timeout = INFINITE;
424
425         while (TRUE) {
426                 res = guarded_wait (done_event, timeout, TRUE);
427                 /* printf ("WAIT RES: %d.\n", res); */
428
429                 if (res == WAIT_IO_COMPLETION) {
430                         if ((thread->state & (ThreadState_StopRequested | ThreadState_SuspendRequested)) != 0)
431                                 return FALSE;
432                 } else if (res == WAIT_TIMEOUT) {
433                         /* We leak the handle here */
434                         return FALSE;
435                 } else {
436                         break;
437                 }
438         }
439
440         CloseHandle (done_event);
441
442         if (domain == mono_get_root_domain ()) {
443                 mono_threadpool_ms_cleanup ();
444                 mono_gc_finalize_threadpool_threads ();
445         }
446
447         return TRUE;
448 }
449
450 void
451 ves_icall_System_GC_InternalCollect (int generation)
452 {
453         mono_gc_collect (generation);
454 }
455
456 gint64
457 ves_icall_System_GC_GetTotalMemory (MonoBoolean forceCollection)
458 {
459         if (forceCollection)
460                 mono_gc_collect (mono_gc_max_generation ());
461         return mono_gc_get_used_size ();
462 }
463
464 void
465 ves_icall_System_GC_KeepAlive (MonoObject *obj)
466 {
467         /*
468          * Does nothing.
469          */
470 }
471
472 void
473 ves_icall_System_GC_ReRegisterForFinalize (MonoObject *obj)
474 {
475         MONO_CHECK_ARG_NULL (obj,);
476
477         object_register_finalizer (obj, mono_gc_run_finalize);
478 }
479
480 void
481 ves_icall_System_GC_SuppressFinalize (MonoObject *obj)
482 {
483         MONO_CHECK_ARG_NULL (obj,);
484
485         /* delegates have no finalizers, but we register them to deal with the
486          * unmanaged->managed trampoline. We don't let the user suppress it
487          * otherwise we'd leak it.
488          */
489         if (obj->vtable->klass->delegate)
490                 return;
491
492         /* FIXME: Need to handle case where obj has COM Callable Wrapper
493          * generated for it that needs cleaned up, but user wants to suppress
494          * their derived object finalizer. */
495
496         object_register_finalizer (obj, NULL);
497 }
498
499 void
500 ves_icall_System_GC_WaitForPendingFinalizers (void)
501 {
502         if (mono_gc_is_null ())
503                 return;
504
505         if (!mono_gc_pending_finalizers ())
506                 return;
507
508         if (mono_thread_internal_current () == gc_thread)
509                 /* Avoid deadlocks */
510                 return;
511
512         /*
513         If the finalizer thread is not live, lets pretend no finalizers are pending since the current thread might
514         be the one responsible for starting it up.
515         */
516         if (gc_thread == NULL)
517                 return;
518
519         ResetEvent (pending_done_event);
520         mono_gc_finalize_notify ();
521         /* g_print ("Waiting for pending finalizers....\n"); */
522         guarded_wait (pending_done_event, INFINITE, TRUE);
523         /* g_print ("Done pending....\n"); */
524 }
525
526 void
527 ves_icall_System_GC_register_ephemeron_array (MonoObject *array)
528 {
529 #ifdef HAVE_SGEN_GC
530         if (!mono_gc_ephemeron_array_add (array)) {
531                 mono_set_pending_exception (mono_object_domain (array)->out_of_memory_ex);
532                 return;
533         }
534 #endif
535 }
536
537 MonoObject*
538 ves_icall_System_GC_get_ephemeron_tombstone (void)
539 {
540         return mono_domain_get ()->ephemeron_tombstone;
541 }
542
543 #define mono_allocator_lock() mono_os_mutex_lock (&allocator_section)
544 #define mono_allocator_unlock() mono_os_mutex_unlock (&allocator_section)
545 static mono_mutex_t allocator_section;
546
547 MonoObject *
548 ves_icall_System_GCHandle_GetTarget (guint32 handle)
549 {
550         return mono_gchandle_get_target (handle);
551 }
552
553 /*
554  * if type == -1, change the target of the handle, otherwise allocate a new handle.
555  */
556 guint32
557 ves_icall_System_GCHandle_GetTargetHandle (MonoObject *obj, guint32 handle, gint32 type)
558 {
559         if (type == -1) {
560                 mono_gchandle_set_target (handle, obj);
561                 /* the handle doesn't change */
562                 return handle;
563         }
564         switch (type) {
565         case HANDLE_WEAK:
566                 return mono_gchandle_new_weakref (obj, FALSE);
567         case HANDLE_WEAK_TRACK:
568                 return mono_gchandle_new_weakref (obj, TRUE);
569         case HANDLE_NORMAL:
570                 return mono_gchandle_new (obj, FALSE);
571         case HANDLE_PINNED:
572                 return mono_gchandle_new (obj, TRUE);
573         default:
574                 g_assert_not_reached ();
575         }
576         return 0;
577 }
578
579 void
580 ves_icall_System_GCHandle_FreeHandle (guint32 handle)
581 {
582         mono_gchandle_free (handle);
583 }
584
585 gpointer
586 ves_icall_System_GCHandle_GetAddrOfPinnedObject (guint32 handle)
587 {
588         MonoObject *obj;
589
590         if (MONO_GC_HANDLE_TYPE (handle) != HANDLE_PINNED)
591                 return (gpointer)-2;
592         obj = mono_gchandle_get_target (handle);
593         if (obj) {
594                 MonoClass *klass = mono_object_class (obj);
595                 if (klass == mono_defaults.string_class) {
596                         return mono_string_chars ((MonoString*)obj);
597                 } else if (klass->rank) {
598                         return mono_array_addr ((MonoArray*)obj, char, 0);
599                 } else {
600                         /* the C# code will check and throw the exception */
601                         /* FIXME: missing !klass->blittable test, see bug #61134 */
602                         if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
603                                 return (gpointer)-1;
604                         return (char*)obj + sizeof (MonoObject);
605                 }
606         }
607         return NULL;
608 }
609
610 MonoBoolean
611 ves_icall_Mono_Runtime_SetGCAllowSynchronousMajor (MonoBoolean flag)
612 {
613         return mono_gc_set_allow_synchronous_major (flag);
614 }
615
616 MonoBoolean
617 mono_gc_GCHandle_CheckCurrentDomain (guint32 gchandle)
618 {
619         return mono_gchandle_is_in_domain (gchandle, mono_domain_get ());
620 }
621
622 #ifdef MONO_HAS_SEMAPHORES
623 static MonoSemType finalizer_sem;
624 #endif
625 static HANDLE finalizer_event;
626 static volatile gboolean finished=FALSE;
627
628 void
629 mono_gc_finalize_notify (void)
630 {
631 #ifdef DEBUG
632         g_message ( "%s: prodding finalizer", __func__);
633 #endif
634
635         if (mono_gc_is_null ())
636                 return;
637
638 #ifdef MONO_HAS_SEMAPHORES
639         mono_os_sem_post (&finalizer_sem);
640 #else
641         SetEvent (finalizer_event);
642 #endif
643 }
644
645 #ifdef HAVE_BOEHM_GC
646
647 static void
648 collect_objects (gpointer key, gpointer value, gpointer user_data)
649 {
650         GPtrArray *arr = (GPtrArray*)user_data;
651         g_ptr_array_add (arr, key);
652 }
653
654 #endif
655
656 /*
657  * finalize_domain_objects:
658  *
659  *  Run the finalizers of all finalizable objects in req->domain.
660  */
661 static void
662 finalize_domain_objects (DomainFinalizationReq *req)
663 {
664         MonoDomain *domain = req->domain;
665
666 #if HAVE_SGEN_GC
667 #define NUM_FOBJECTS 64
668         MonoObject *to_finalize [NUM_FOBJECTS];
669         int count;
670 #endif
671
672         /* Process finalizers which are already in the queue */
673         mono_gc_invoke_finalizers ();
674
675 #ifdef HAVE_BOEHM_GC
676         while (g_hash_table_size (domain->finalizable_objects_hash) > 0) {
677                 int i;
678                 GPtrArray *objs;
679                 /* 
680                  * Since the domain is unloading, nobody is allowed to put
681                  * new entries into the hash table. But finalize_object might
682                  * remove entries from the hash table, so we make a copy.
683                  */
684                 objs = g_ptr_array_new ();
685                 g_hash_table_foreach (domain->finalizable_objects_hash, collect_objects, objs);
686                 /* printf ("FINALIZING %d OBJECTS.\n", objs->len); */
687
688                 for (i = 0; i < objs->len; ++i) {
689                         MonoObject *o = (MonoObject*)g_ptr_array_index (objs, i);
690                         /* FIXME: Avoid finalizing threads, etc */
691                         mono_gc_run_finalize (o, 0);
692                 }
693
694                 g_ptr_array_free (objs, TRUE);
695         }
696 #elif defined(HAVE_SGEN_GC)
697         while ((count = mono_gc_finalizers_for_domain (domain, to_finalize, NUM_FOBJECTS))) {
698                 int i;
699                 for (i = 0; i < count; ++i) {
700                         mono_gc_run_finalize (to_finalize [i], 0);
701                 }
702         }
703 #endif
704
705         /* cleanup the reference queue */
706         reference_queue_clear_for_domain (domain);
707         
708         /* printf ("DONE.\n"); */
709         SetEvent (req->done_event);
710
711         /* The event is closed in mono_domain_finalize if we get here */
712         g_free (req);
713 }
714
715 static guint32
716 finalizer_thread (gpointer unused)
717 {
718         gboolean wait = TRUE;
719
720         while (!finished) {
721                 /* Wait to be notified that there's at least one
722                  * finaliser to run
723                  */
724
725                 g_assert (mono_domain_get () == mono_get_root_domain ());
726                 mono_gc_set_skip_thread (TRUE);
727                 MONO_PREPARE_BLOCKING;
728
729                 if (wait) {
730                 /* An alertable wait is required so this thread can be suspended on windows */
731 #ifdef MONO_HAS_SEMAPHORES
732                         mono_os_sem_wait (&finalizer_sem, MONO_SEM_FLAGS_ALERTABLE);
733 #else
734                         WaitForSingleObjectEx (finalizer_event, INFINITE, TRUE);
735 #endif
736                 }
737                 wait = TRUE;
738                 MONO_FINISH_BLOCKING;
739                 mono_gc_set_skip_thread (FALSE);
740
741                 mono_threads_perform_thread_dump ();
742
743                 mono_console_handle_async_ops ();
744
745                 mono_attach_maybe_start ();
746
747                 if (domains_to_finalize) {
748                         mono_finalizer_lock ();
749                         if (domains_to_finalize) {
750                                 DomainFinalizationReq *req = domains_to_finalize->data;
751                                 domains_to_finalize = g_slist_remove (domains_to_finalize, req);
752                                 mono_finalizer_unlock ();
753
754                                 finalize_domain_objects (req);
755                         } else {
756                                 mono_finalizer_unlock ();
757                         }
758                 }                               
759
760                 /* If finished == TRUE, mono_gc_cleanup has been called (from mono_runtime_cleanup),
761                  * before the domain is unloaded.
762                  */
763                 mono_gc_invoke_finalizers ();
764
765                 mono_threads_join_threads ();
766
767                 reference_queue_proccess_all ();
768
769 #ifdef MONO_HAS_SEMAPHORES
770                 /* Avoid posting the pending done event until there are pending finalizers */
771                 if (mono_os_sem_timedwait (&finalizer_sem, 0, MONO_SEM_FLAGS_NONE) == 0)
772                         /* Don't wait again at the start of the loop */
773                         wait = FALSE;
774                 else
775                         SetEvent (pending_done_event);
776 #else
777                         SetEvent (pending_done_event);
778 #endif
779         }
780
781         mono_finalizer_lock ();
782         finalizer_thread_exited = TRUE;
783         mono_os_cond_signal (&exited_cond);
784         mono_finalizer_unlock ();
785
786         return 0;
787 }
788
789 #ifndef LAZY_GC_THREAD_CREATION
790 static
791 #endif
792 void
793 mono_gc_init_finalizer_thread (void)
794 {
795         gc_thread = mono_thread_create_internal (mono_domain_get (), finalizer_thread, NULL, FALSE, 0);
796         ves_icall_System_Threading_Thread_SetName_internal (gc_thread, mono_string_new (mono_domain_get (), "Finalizer"));
797 }
798
799 void
800 mono_gc_init (void)
801 {
802         mono_os_mutex_init_recursive (&allocator_section);
803
804         mono_os_mutex_init_recursive (&finalizer_mutex);
805         mono_os_mutex_init_recursive (&reference_queue_mutex);
806
807         mono_counters_register ("Minor GC collections", MONO_COUNTER_GC | MONO_COUNTER_UINT, &gc_stats.minor_gc_count);
808         mono_counters_register ("Major GC collections", MONO_COUNTER_GC | MONO_COUNTER_UINT, &gc_stats.major_gc_count);
809         mono_counters_register ("Minor GC time", MONO_COUNTER_GC | MONO_COUNTER_ULONG | MONO_COUNTER_TIME, &gc_stats.minor_gc_time);
810         mono_counters_register ("Major GC time", MONO_COUNTER_GC | MONO_COUNTER_ULONG | MONO_COUNTER_TIME, &gc_stats.major_gc_time);
811         mono_counters_register ("Major GC time concurrent", MONO_COUNTER_GC | MONO_COUNTER_ULONG | MONO_COUNTER_TIME, &gc_stats.major_gc_time_concurrent);
812
813         mono_gc_base_init ();
814
815         if (mono_gc_is_disabled ()) {
816                 gc_disabled = TRUE;
817                 return;
818         }
819         
820         finalizer_event = CreateEvent (NULL, FALSE, FALSE, NULL);
821         g_assert (finalizer_event);
822         pending_done_event = CreateEvent (NULL, TRUE, FALSE, NULL);
823         g_assert (pending_done_event);
824         mono_os_cond_init (&exited_cond);
825 #ifdef MONO_HAS_SEMAPHORES
826         mono_os_sem_init (&finalizer_sem, 0);
827 #endif
828
829 #ifndef LAZY_GC_THREAD_CREATION
830         mono_gc_init_finalizer_thread ();
831 #endif
832 }
833
834 void
835 mono_gc_cleanup (void)
836 {
837 #ifdef DEBUG
838         g_message ("%s: cleaning up finalizer", __func__);
839 #endif
840
841         if (mono_gc_is_null ())
842                 return;
843
844         if (!gc_disabled) {
845                 finished = TRUE;
846                 if (mono_thread_internal_current () != gc_thread) {
847                         gboolean timed_out = FALSE;
848                         guint32 start_ticks = mono_msec_ticks ();
849                         guint32 end_ticks = start_ticks + 2000;
850
851                         mono_gc_finalize_notify ();
852                         /* Finishing the finalizer thread, so wait a little bit... */
853                         /* MS seems to wait for about 2 seconds */
854                         while (!finalizer_thread_exited) {
855                                 guint32 current_ticks = mono_msec_ticks ();
856                                 guint32 timeout;
857
858                                 if (current_ticks >= end_ticks)
859                                         break;
860                                 else
861                                         timeout = end_ticks - current_ticks;
862                                 MONO_PREPARE_BLOCKING;
863                                 mono_finalizer_lock ();
864                                 if (!finalizer_thread_exited)
865                                         mono_os_cond_timedwait_ms (&exited_cond, &finalizer_mutex, timeout);
866                                 mono_finalizer_unlock ();
867                                 MONO_FINISH_BLOCKING;
868                         }
869
870                         if (!finalizer_thread_exited) {
871                                 int ret;
872
873                                 /* Set a flag which the finalizer thread can check */
874                                 suspend_finalizers = TRUE;
875
876                                 /* Try to abort the thread, in the hope that it is running managed code */
877                                 mono_thread_internal_stop (gc_thread);
878
879                                 /* Wait for it to stop */
880                                 ret = guarded_wait (gc_thread->handle, 100, TRUE);
881
882                                 if (ret == WAIT_TIMEOUT) {
883                                         /* 
884                                          * The finalizer thread refused to die. There is not much we 
885                                          * can do here, since the runtime is shutting down so the 
886                                          * state the finalizer thread depends on will vanish.
887                                          */
888                                         g_warning ("Shutting down finalizer thread timed out.");
889                                         timed_out = TRUE;
890                                 }
891                         }
892
893                         if (!timed_out) {
894                                 int ret;
895
896                                 /* Wait for the thread to actually exit */
897                                 ret = guarded_wait (gc_thread->handle, INFINITE, TRUE);
898                                 g_assert (ret == WAIT_OBJECT_0);
899
900                                 mono_thread_join (GUINT_TO_POINTER (gc_thread->tid));
901                         }
902                 }
903                 gc_thread = NULL;
904                 mono_gc_base_cleanup ();
905         }
906
907         mono_reference_queue_cleanup ();
908
909         mono_os_mutex_destroy (&allocator_section);
910         mono_os_mutex_destroy (&finalizer_mutex);
911         mono_os_mutex_destroy (&reference_queue_mutex);
912 }
913
914 gboolean
915 mono_gc_is_finalizer_internal_thread (MonoInternalThread *thread)
916 {
917         return thread == gc_thread;
918 }
919
920 /**
921  * mono_gc_is_finalizer_thread:
922  * @thread: the thread to test.
923  *
924  * In Mono objects are finalized asynchronously on a separate thread.
925  * This routine tests whether the @thread argument represents the
926  * finalization thread.
927  * 
928  * Returns true if @thread is the finalization thread.
929  */
930 gboolean
931 mono_gc_is_finalizer_thread (MonoThread *thread)
932 {
933         return mono_gc_is_finalizer_internal_thread (thread->internal_thread);
934 }
935
936 #if defined(__MACH__)
937 static pthread_t mach_exception_thread;
938
939 void
940 mono_gc_register_mach_exception_thread (pthread_t thread)
941 {
942         mach_exception_thread = thread;
943 }
944
945 pthread_t
946 mono_gc_get_mach_exception_thread (void)
947 {
948         return mach_exception_thread;
949 }
950 #endif
951
952 #ifndef HAVE_SGEN_GC
953 void*
954 mono_gc_alloc_mature (MonoVTable *vtable)
955 {
956         return mono_object_new_specific (vtable);
957 }
958 #endif
959
960
961 static MonoReferenceQueue *ref_queues;
962
963 static void
964 ref_list_remove_element (RefQueueEntry **prev, RefQueueEntry *element)
965 {
966         do {
967                 /* Guard if head is changed concurrently. */
968                 while (*prev != element)
969                         prev = &(*prev)->next;
970         } while (prev && InterlockedCompareExchangePointer ((void*)prev, element->next, element) != element);
971 }
972
973 static void
974 ref_list_push (RefQueueEntry **head, RefQueueEntry *value)
975 {
976         RefQueueEntry *current;
977         do {
978                 current = *head;
979                 value->next = current;
980                 STORE_STORE_FENCE; /*Must make sure the previous store is visible before the CAS. */
981         } while (InterlockedCompareExchangePointer ((void*)head, value, current) != current);
982 }
983
984 static void
985 reference_queue_proccess (MonoReferenceQueue *queue)
986 {
987         RefQueueEntry **iter = &queue->queue;
988         RefQueueEntry *entry;
989         while ((entry = *iter)) {
990                 if (queue->should_be_deleted || !mono_gchandle_get_target (entry->gchandle)) {
991                         mono_gchandle_free ((guint32)entry->gchandle);
992                         ref_list_remove_element (iter, entry);
993                         queue->callback (entry->user_data);
994                         g_free (entry);
995                 } else {
996                         iter = &entry->next;
997                 }
998         }
999 }
1000
1001 static void
1002 reference_queue_proccess_all (void)
1003 {
1004         MonoReferenceQueue **iter;
1005         MonoReferenceQueue *queue = ref_queues;
1006         for (; queue; queue = queue->next)
1007                 reference_queue_proccess (queue);
1008
1009 restart:
1010         mono_os_mutex_lock (&reference_queue_mutex);
1011         for (iter = &ref_queues; *iter;) {
1012                 queue = *iter;
1013                 if (!queue->should_be_deleted) {
1014                         iter = &queue->next;
1015                         continue;
1016                 }
1017                 if (queue->queue) {
1018                         mono_os_mutex_unlock (&reference_queue_mutex);
1019                         reference_queue_proccess (queue);
1020                         goto restart;
1021                 }
1022                 *iter = queue->next;
1023                 g_free (queue);
1024         }
1025         mono_os_mutex_unlock (&reference_queue_mutex);
1026 }
1027
1028 static void
1029 mono_reference_queue_cleanup (void)
1030 {
1031         MonoReferenceQueue *queue = ref_queues;
1032         for (; queue; queue = queue->next)
1033                 queue->should_be_deleted = TRUE;
1034         reference_queue_proccess_all ();
1035 }
1036
1037 static void
1038 reference_queue_clear_for_domain (MonoDomain *domain)
1039 {
1040         MonoReferenceQueue *queue = ref_queues;
1041         for (; queue; queue = queue->next) {
1042                 RefQueueEntry **iter = &queue->queue;
1043                 RefQueueEntry *entry;
1044                 while ((entry = *iter)) {
1045                         if (entry->domain == domain) {
1046                                 mono_gchandle_free ((guint32)entry->gchandle);
1047                                 ref_list_remove_element (iter, entry);
1048                                 queue->callback (entry->user_data);
1049                                 g_free (entry);
1050                         } else {
1051                                 iter = &entry->next;
1052                         }
1053                 }
1054         }
1055 }
1056 /**
1057  * mono_gc_reference_queue_new:
1058  * @callback callback used when processing collected entries.
1059  *
1060  * Create a new reference queue used to process collected objects.
1061  * A reference queue let you add a pair of (managed object, user data)
1062  * using the mono_gc_reference_queue_add method.
1063  *
1064  * Once the managed object is collected @callback will be called
1065  * in the finalizer thread with 'user data' as argument.
1066  *
1067  * The callback is called from the finalizer thread without any locks held.
1068  * When a AppDomain is unloaded, all callbacks for objects belonging to it
1069  * will be invoked.
1070  *
1071  * @returns the new queue.
1072  */
1073 MonoReferenceQueue*
1074 mono_gc_reference_queue_new (mono_reference_queue_callback callback)
1075 {
1076         MonoReferenceQueue *res = g_new0 (MonoReferenceQueue, 1);
1077         res->callback = callback;
1078
1079         mono_os_mutex_lock (&reference_queue_mutex);
1080         res->next = ref_queues;
1081         ref_queues = res;
1082         mono_os_mutex_unlock (&reference_queue_mutex);
1083
1084         return res;
1085 }
1086
1087 /**
1088  * mono_gc_reference_queue_add:
1089  * @queue the queue to add the reference to.
1090  * @obj the object to be watched for collection
1091  * @user_data parameter to be passed to the queue callback
1092  *
1093  * Queue an object to be watched for collection, when the @obj is
1094  * collected, the callback that was registered for the @queue will
1095  * be invoked with @user_data as argument.
1096  *
1097  * @returns false if the queue is scheduled to be freed.
1098  */
1099 gboolean
1100 mono_gc_reference_queue_add (MonoReferenceQueue *queue, MonoObject *obj, void *user_data)
1101 {
1102         RefQueueEntry *entry;
1103         if (queue->should_be_deleted)
1104                 return FALSE;
1105
1106         entry = g_new0 (RefQueueEntry, 1);
1107         entry->user_data = user_data;
1108         entry->domain = mono_object_domain (obj);
1109
1110         entry->gchandle = mono_gchandle_new_weakref (obj, TRUE);
1111         mono_object_register_finalizer (obj);
1112
1113         ref_list_push (&queue->queue, entry);
1114         return TRUE;
1115 }
1116
1117 /**
1118  * mono_gc_reference_queue_free:
1119  * @queue the queue that should be freed.
1120  *
1121  * This operation signals that @queue should be freed. This operation is deferred
1122  * as it happens on the finalizer thread.
1123  *
1124  * After this call, no further objects can be queued. It's the responsibility of the
1125  * caller to make sure that no further attempt to access queue will be made.
1126  */
1127 void
1128 mono_gc_reference_queue_free (MonoReferenceQueue *queue)
1129 {
1130         queue->should_be_deleted = TRUE;
1131 }