66d5e99f5362c008f6589e80c4faf53bb8ac3b82
[mono.git] / mono / metadata / gc.c
1 /*
2  * metadata/gc.c: GC icalls.
3  *
4  * Author: Paolo Molaro <lupus@ximian.com>
5  *
6  * (C) 2002 Ximian, Inc.
7  */
8
9 #include <config.h>
10 #include <glib.h>
11 #include <string.h>
12
13 #include <mono/metadata/gc-internal.h>
14 #include <mono/metadata/threads.h>
15 #include <mono/metadata/tabledefs.h>
16 #include <mono/metadata/exception.h>
17 #include <mono/metadata/profiler-private.h>
18 #include <mono/metadata/domain-internals.h>
19 #include <mono/metadata/class-internals.h>
20 #include <mono/utils/mono-logger.h>
21 #define GC_I_HIDE_POINTERS
22 #include <mono/os/gc_wrapper.h>
23
24 #ifndef HIDE_POINTER
25 #define HIDE_POINTER(v)         (v)
26 #define REVEAL_POINTER(v)       (v)
27 #endif
28
29 typedef struct DomainFinalizationReq {
30         MonoDomain *domain;
31         HANDLE done_event;
32 } DomainFinalizationReq;
33
34 #ifdef PLATFORM_WINCE /* FIXME: add accessors to gc.dll API */
35 extern void (*__imp_GC_finalizer_notifier)(void);
36 #define GC_finalizer_notifier __imp_GC_finalizer_notifier
37 extern int __imp_GC_finalize_on_demand;
38 #define GC_finalize_on_demand __imp_GC_finalize_on_demand
39 #endif
40
41 #ifdef HAVE_VALGRIND_MEMCHECK_H
42 #include <valgrind/memcheck.h>
43 #endif
44
45 static int finalize_slot = -1;
46
47 static gboolean gc_disabled = FALSE;
48
49 static CRITICAL_SECTION finalizer_mutex;
50
51 static GSList *domains_to_finalize= NULL;
52
53 static MonoThread *gc_thread;
54
55 static void object_register_finalizer (MonoObject *obj, void (*callback)(void *, void*));
56
57 #if HAVE_BOEHM_GC
58 static void finalize_notify (void);
59 static HANDLE pending_done_event;
60 static HANDLE shutdown_event;
61 static HANDLE thread_started_event;
62 #endif
63
64 /* 
65  * actually, we might want to queue the finalize requests in a separate thread,
66  * but we need to be careful about the execution domain of the thread...
67  */
68 static void
69 run_finalize (void *obj, void *data)
70 {
71         MonoObject *exc = NULL;
72         MonoObject *o, *o2;
73         o = (MonoObject*)((char*)obj + GPOINTER_TO_UINT (data));
74
75         if (finalize_slot < 0) {
76                 int i;
77                 MonoClass* obj_class = mono_get_object_class ();
78                 for (i = 0; i < obj_class->vtable_size; ++i) {
79                         MonoMethod *cm = obj_class->vtable [i];
80                
81                         if (!strcmp (mono_method_get_name (cm), "Finalize")) {
82                                 finalize_slot = i;
83                                 break;
84                         }
85                 }
86         }
87
88         mono_domain_lock (o->vtable->domain);
89
90         o2 = g_hash_table_lookup (o->vtable->domain->finalizable_objects_hash, o);
91
92         mono_domain_unlock (o->vtable->domain);
93
94         if (!o2)
95                 /* Already finalized somehow */
96                 return;
97
98         /* make sure the finalizer is not called again if the object is resurrected */
99         object_register_finalizer (obj, NULL);
100
101         if (o->vtable->klass == mono_get_thread_class ())
102                 if (mono_gc_is_finalizer_thread ((MonoThread*)o))
103                         /* Avoid finalizing ourselves */
104                         return;
105
106         /* speedup later... and use a timeout */
107         /* g_print ("Finalize run on %p %s.%s\n", o, mono_object_class (o)->name_space, mono_object_class (o)->name); */
108
109         /* Use _internal here, since this thread can enter a doomed appdomain */
110         mono_domain_set_internal (mono_object_domain (o));              
111
112         mono_runtime_invoke (o->vtable->klass->vtable [finalize_slot], o, NULL, &exc);
113
114         if (exc) {
115                 /* fixme: do something useful */
116         }
117 }
118
119 gpointer
120 mono_gc_out_of_memory (size_t size)
121 {
122         /* 
123          * we could allocate at program startup some memory that we could release 
124          * back to the system at this point if we're really low on memory (ie, size is
125          * lower than the memory we set apart)
126          */
127         mono_raise_exception (mono_domain_get ()->out_of_memory_ex);
128
129         return NULL;
130 }
131
132 /*
133  * Some of our objects may point to a different address than the address returned by GC_malloc()
134  * (because of the GetHashCode hack), but we need to pass the real address to register_finalizer.
135  * This also means that in the callback we need to adjust the pointer to get back the real
136  * MonoObject*.
137  * We also need to be consistent in the use of the GC_debug* variants of malloc and register_finalizer, 
138  * since that, too, can cause the underlying pointer to be offset.
139  */
140 static void
141 object_register_finalizer (MonoObject *obj, void (*callback)(void *, void*))
142 {
143 #if HAVE_BOEHM_GC
144         guint offset = 0;
145
146 #ifndef GC_DEBUG
147         /* This assertion is not valid when GC_DEBUG is defined */
148         g_assert (GC_base (obj) == (char*)obj - offset);
149 #endif
150
151         if (mono_domain_is_unloading (obj->vtable->domain) && (callback != NULL))
152                 /*
153                  * Can't register finalizers in a dying appdomain, since they
154                  * could be invoked after the appdomain has been unloaded.
155                  */
156                 return;
157
158         mono_domain_lock (obj->vtable->domain);
159
160         if (callback)
161                 g_hash_table_insert (obj->vtable->domain->finalizable_objects_hash, obj,
162                                                          obj);
163         else
164                 g_hash_table_remove (obj->vtable->domain->finalizable_objects_hash, obj);
165
166         mono_domain_unlock (obj->vtable->domain);
167
168         GC_REGISTER_FINALIZER_NO_ORDER ((char*)obj - offset, callback, GUINT_TO_POINTER (offset), NULL, NULL);
169 #endif
170 }
171
172 void
173 mono_object_register_finalizer (MonoObject *obj)
174 {
175         /* g_print ("Registered finalizer on %p %s.%s\n", obj, mono_object_class (obj)->name_space, mono_object_class (obj)->name); */
176         object_register_finalizer (obj, run_finalize);
177 }
178
179 /*
180  * mono_domain_finalize:
181  *
182  *  Request finalization of all finalizable objects inside @domain. Wait
183  * @timeout msecs for the finalization to complete.
184  * Returns: TRUE if succeeded, FALSE if there was a timeout
185  */
186
187 gboolean
188 mono_domain_finalize (MonoDomain *domain, guint32 timeout) 
189 {
190         DomainFinalizationReq *req;
191         guint32 res;
192         HANDLE done_event;
193
194         if (mono_thread_current () == gc_thread)
195                 /* We are called from inside a finalizer, not much we can do here */
196                 return FALSE;
197
198         mono_profiler_appdomain_event (domain, MONO_PROFILE_START_UNLOAD);
199
200         /* 
201          * No need to create another thread 'cause the finalizer thread
202          * is still working and will take care of running the finalizers
203          */ 
204         
205 #if HAVE_BOEHM_GC
206         if (gc_disabled)
207                 return TRUE;
208
209         GC_gcollect ();
210
211         done_event = CreateEvent (NULL, TRUE, FALSE, NULL);
212
213         req = g_new0 (DomainFinalizationReq, 1);
214         req->domain = domain;
215         req->done_event = done_event;
216         
217         EnterCriticalSection (&finalizer_mutex);
218
219         domains_to_finalize = g_slist_append (domains_to_finalize, req);
220
221         LeaveCriticalSection (&finalizer_mutex);
222
223         /* Tell the finalizer thread to finalize this appdomain */
224         finalize_notify ();
225
226         res = WaitForSingleObjectEx (done_event, timeout, TRUE);
227
228         /* printf ("WAIT RES: %d.\n", res); */
229         if (res == WAIT_TIMEOUT) {
230                 /* We leak the handle here */
231                 return FALSE;
232         }
233
234         CloseHandle (done_event);
235         return TRUE;
236 #else
237         /* We don't support domain finalization without a GC */
238         return FALSE;
239 #endif
240 }
241
242 void
243 ves_icall_System_GC_InternalCollect (int generation)
244 {
245         MONO_ARCH_SAVE_REGS;
246
247 #if HAVE_BOEHM_GC
248         GC_gcollect ();
249 #endif
250 }
251
252 gint64
253 ves_icall_System_GC_GetTotalMemory (MonoBoolean forceCollection)
254 {
255         MONO_ARCH_SAVE_REGS;
256
257 #if HAVE_BOEHM_GC
258         if (forceCollection)
259                 GC_gcollect ();
260         return GC_get_heap_size () - GC_get_free_bytes ();
261 #else
262         return 0;
263 #endif
264 }
265
266 void
267 ves_icall_System_GC_KeepAlive (MonoObject *obj)
268 {
269         MONO_ARCH_SAVE_REGS;
270
271         /*
272          * Does nothing.
273          */
274 }
275
276 void
277 ves_icall_System_GC_ReRegisterForFinalize (MonoObject *obj)
278 {
279         MONO_ARCH_SAVE_REGS;
280
281         object_register_finalizer (obj, run_finalize);
282 }
283
284 void
285 ves_icall_System_GC_SuppressFinalize (MonoObject *obj)
286 {
287         MONO_ARCH_SAVE_REGS;
288
289         object_register_finalizer (obj, NULL);
290 }
291
292 void
293 ves_icall_System_GC_WaitForPendingFinalizers (void)
294 {
295         MONO_ARCH_SAVE_REGS;
296         
297 #if HAVE_BOEHM_GC
298         if (!GC_should_invoke_finalizers ())
299                 return;
300
301         if (mono_thread_current () == gc_thread)
302                 /* Avoid deadlocks */
303                 return;
304
305         ResetEvent (pending_done_event);
306         finalize_notify ();
307         /* g_print ("Waiting for pending finalizers....\n"); */
308         WaitForSingleObjectEx (pending_done_event, INFINITE, TRUE);
309         /* g_print ("Done pending....\n"); */
310 #else
311 #endif
312 }
313
314 static CRITICAL_SECTION allocator_section;
315 static CRITICAL_SECTION handle_section;
316 static guint32 next_handle = 0;
317 static gpointer *gc_handles = NULL;
318 static guint8 *gc_handle_types = NULL;
319 static guint32 array_size = 0;
320
321 /*
322  * The handle type is encoded in the lower two bits of the handle value:
323  * 0 -> normal
324  * 1 -> pinned
325  * 2 -> weak
326  */
327
328 typedef enum {
329         HANDLE_WEAK,
330         HANDLE_WEAK_TRACK,
331         HANDLE_NORMAL,
332         HANDLE_PINNED
333 } HandleType;
334
335 /*
336  * FIXME: make thread safe and reuse the array entries.
337  */
338 MonoObject *
339 ves_icall_System_GCHandle_GetTarget (guint32 handle)
340 {
341         MonoObject *obj;
342         gint32 type;
343
344         MONO_ARCH_SAVE_REGS;
345
346         if (gc_handles) {
347                 type = handle & 0x3;
348                 EnterCriticalSection (&handle_section);
349                 g_assert (type == gc_handle_types [handle >> 2]);
350                 obj = gc_handles [handle >> 2];
351                 LeaveCriticalSection (&handle_section);
352                 if (!obj)
353                         return NULL;
354
355                 if ((type == HANDLE_WEAK) || (type == HANDLE_WEAK_TRACK))
356                         return REVEAL_POINTER (obj);
357                 else
358                         return obj;
359         }
360         return NULL;
361 }
362
363 guint32
364 ves_icall_System_GCHandle_GetTargetHandle (MonoObject *obj, guint32 handle, gint32 type)
365 {
366         gpointer val = obj;
367         guint32 h, idx;
368
369         MONO_ARCH_SAVE_REGS;
370
371         EnterCriticalSection (&handle_section);
372         /* Indexes start from 1 since 0 means the handle is not allocated */
373         idx = ++next_handle;
374         if (idx >= array_size) {
375                 gpointer *new_array;
376                 guint8 *new_type_array;
377                 if (!array_size)
378                         array_size = 16;
379 #if HAVE_BOEHM_GC
380                 new_array = GC_MALLOC (sizeof (gpointer) * (array_size * 2));
381                 new_type_array = GC_MALLOC (sizeof (guint8) * (array_size * 2));
382 #else
383                 new_array = g_malloc0 (sizeof (gpointer) * (array_size * 2));
384                 new_type_array = g_malloc0 (sizeof (guint8) * (array_size * 2));
385 #endif
386                 if (gc_handles) {
387                         int i;
388                         memcpy (new_array, gc_handles, sizeof (gpointer) * array_size);
389                         memcpy (new_type_array, gc_handle_types, sizeof (guint8) * array_size);
390                         /* need to re-register links for weak refs. test if GC_realloc needs the same */
391                         for (i = 0; i < array_size; ++i) {
392 #if 0 /* This breaks the threaded finalizer, by causing segfaults deep
393        * inside libgc.  I assume it will also break without the
394        * threaded finalizer, just that the stress test (bug 31333)
395        * deadlocks too early without it.  Reverting to the previous
396        * version here stops the segfault.
397        */
398                                 if ((gc_handle_types[i] == HANDLE_WEAK) || (gc_handle_types[i] == HANDLE_WEAK_TRACK)) { /* all and only disguised pointers have it set */
399 #else
400                                 if (((gulong)new_array [i]) & 0x1) {
401 #endif
402 #if HAVE_BOEHM_GC
403                                         if (gc_handles [i] != (gpointer)-1)
404                                                 GC_unregister_disappearing_link (&(gc_handles [i]));
405                                         if (new_array [i] != (gpointer)-1)
406                                                 GC_GENERAL_REGISTER_DISAPPEARING_LINK (&(new_array [i]), REVEAL_POINTER (new_array [i]));
407 #endif
408                                 }
409                         }
410                 }
411                 array_size *= 2;
412 #ifndef HAVE_BOEHM_GC
413                 g_free (gc_handles);
414                 g_free (gc_handle_types);
415 #endif
416                 gc_handles = new_array;
417                 gc_handle_types = new_type_array;
418         }
419
420         /* resuse the type from the old target */
421         if (type == -1)
422                 type =  handle & 0x3;
423         h = (idx << 2) | type;
424         switch (type) {
425         case HANDLE_WEAK:
426         case HANDLE_WEAK_TRACK:
427                 val = (gpointer)HIDE_POINTER (val);
428                 gc_handles [idx] = val;
429                 gc_handle_types [idx] = type;
430 #if HAVE_BOEHM_GC
431                 if (gc_handles [idx] != (gpointer)-1)
432                         GC_GENERAL_REGISTER_DISAPPEARING_LINK (&(gc_handles [idx]), obj);
433 #endif
434                 break;
435         default:
436                 gc_handles [idx] = val;
437                 gc_handle_types [idx] = type;
438                 break;
439         }
440         LeaveCriticalSection (&handle_section);
441         return h;
442 }
443
444 void
445 ves_icall_System_GCHandle_FreeHandle (guint32 handle)
446 {
447         int idx = handle >> 2;
448         int type = handle & 0x3;
449
450         MONO_ARCH_SAVE_REGS;
451
452         EnterCriticalSection (&handle_section);
453
454 #ifdef HAVE_BOEHM_GC
455         g_assert (type == gc_handle_types [idx]);
456         if ((type == HANDLE_WEAK) || (type == HANDLE_WEAK_TRACK)) {
457                 if (gc_handles [idx] != (gpointer)-1)
458                         GC_unregister_disappearing_link (&(gc_handles [idx]));
459         }
460 #endif
461
462         gc_handles [idx] = (gpointer)-1;
463         gc_handle_types [idx] = (guint8)-1;
464         LeaveCriticalSection (&handle_section);
465 }
466
467 gpointer
468 ves_icall_System_GCHandle_GetAddrOfPinnedObject (guint32 handle)
469 {
470         MonoObject *obj;
471         int type = handle & 0x3;
472
473         MONO_ARCH_SAVE_REGS;
474
475         if (gc_handles) {
476                 EnterCriticalSection (&handle_section);
477                 obj = gc_handles [handle >> 2];
478                 g_assert (gc_handle_types [handle >> 2] == type);
479                 LeaveCriticalSection (&handle_section);
480                 if ((type == HANDLE_WEAK) || (type == HANDLE_WEAK_TRACK)) {
481                         obj = REVEAL_POINTER (obj);
482                         if (obj == (MonoObject *) -1)
483                                 return NULL;
484                 }
485                 if (obj) {
486                         MonoClass *klass = mono_object_class (obj);
487                         if (klass == mono_defaults.string_class) {
488                                 return mono_string_chars ((MonoString*)obj);
489                         } else if (klass->rank) {
490                                 return mono_array_addr ((MonoArray*)obj, char, 0);
491                         } else {
492                                 /* the C# code will check and throw the exception */
493                                 /* FIXME: missing !klass->blittable test, see bug #61134 */
494                                 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
495                                         return (gpointer)-1;
496                                 return (char*)obj + sizeof (MonoObject);
497                         }
498                 }
499         }
500         return NULL;
501 }
502
503 guint32
504 mono_gchandle_new (MonoObject *obj, gboolean pinned)
505 {
506         return ves_icall_System_GCHandle_GetTargetHandle (obj, 0, pinned? HANDLE_PINNED: HANDLE_NORMAL);
507 }
508
509 guint32
510 mono_gchandle_new_weakref (MonoObject *obj, gboolean track_resurrection)
511 {
512         return ves_icall_System_GCHandle_GetTargetHandle (obj, 0, track_resurrection? HANDLE_WEAK_TRACK: HANDLE_WEAK);
513 }
514
515 /* This will return NULL for a collected object if using a weakref handle */
516 MonoObject*
517 mono_gchandle_get_target (guint32 gchandle)
518 {
519         return ves_icall_System_GCHandle_GetTarget (gchandle);
520 }
521
522 void
523 mono_gchandle_free (guint32 gchandle)
524 {
525         ves_icall_System_GCHandle_FreeHandle (gchandle);
526 }
527
528 #if HAVE_BOEHM_GC
529
530 static HANDLE finalizer_event;
531 static volatile gboolean finished=FALSE;
532
533 static void finalize_notify (void)
534 {
535 #ifdef DEBUG
536         g_message (G_GNUC_PRETTY_FUNCTION ": prodding finalizer");
537 #endif
538
539         SetEvent (finalizer_event);
540 }
541
542 static void
543 collect_objects (gpointer key, gpointer value, gpointer user_data)
544 {
545         GPtrArray *arr = (GPtrArray*)user_data;
546         g_ptr_array_add (arr, key);
547 }
548
549 /*
550  * finalize_domain_objects:
551  *
552  *  Run the finalizers of all finalizable objects in req->domain.
553  */
554 static void
555 finalize_domain_objects (DomainFinalizationReq *req)
556 {
557         int i;
558         GPtrArray *objs;
559         MonoDomain *domain = req->domain;
560         
561         while (g_hash_table_size (domain->finalizable_objects_hash) > 0) {
562                 /* 
563                  * Since the domain is unloading, nobody is allowed to put
564                  * new entries into the hash table. But finalize_object might
565                  * remove entries from the hash table, so we make a copy.
566                  */
567                 objs = g_ptr_array_new ();
568                 g_hash_table_foreach (domain->finalizable_objects_hash, 
569                                                           collect_objects, objs);
570                 /* printf ("FINALIZING %d OBJECTS.\n", objs->len); */
571
572                 for (i = 0; i < objs->len; ++i) {
573                         MonoObject *o = (MonoObject*)g_ptr_array_index (objs, i);
574                         /* FIXME: Avoid finalizing threads, etc */
575                         run_finalize (o, 0);
576                 }
577
578                 g_ptr_array_free (objs, TRUE);
579         }
580
581         /* Process finalizers which are already in the queue */
582         GC_invoke_finalizers ();
583
584         /* printf ("DONE.\n"); */
585         SetEvent (req->done_event);
586
587         /* The event is closed in mono_domain_finalize if we get here */
588         g_free (req);
589 }
590
591 static guint32 finalizer_thread (gpointer unused)
592 {
593         gc_thread = mono_thread_current ();
594
595         SetEvent (thread_started_event);
596
597         while(!finished) {
598                 /* Wait to be notified that there's at least one
599                  * finaliser to run
600                  */
601                 WaitForSingleObjectEx (finalizer_event, INFINITE, TRUE);
602
603                 if (domains_to_finalize) {
604                         EnterCriticalSection (&finalizer_mutex);
605                         if (domains_to_finalize) {
606                                 DomainFinalizationReq *req = domains_to_finalize->data;
607                                 domains_to_finalize = g_slist_remove (domains_to_finalize, req);
608                                 LeaveCriticalSection (&finalizer_mutex);
609
610                                 finalize_domain_objects (req);
611                         }
612                         else
613                                 LeaveCriticalSection (&finalizer_mutex);
614                 }                               
615
616 #ifdef DEBUG
617                 g_message (G_GNUC_PRETTY_FUNCTION ": invoking finalizers");
618 #endif
619
620                 /* If finished == TRUE, mono_gc_cleanup has been called (from mono_runtime_cleanup),
621                  * before the domain is unloaded.
622                  *
623                  * There is a bug in GC_invoke_finalizer () in versions <= 6.2alpha4:
624                  * the 'mem_freed' variable is not initialized when there are no
625                  * objects to finalize, which leads to strange behavior later on.
626                  * The check is necessary to work around that bug.
627                  */
628                 if (GC_should_invoke_finalizers ()) {
629                         GC_invoke_finalizers ();
630                 }
631
632                 SetEvent (pending_done_event);
633         }
634
635         SetEvent (shutdown_event);
636         return(0);
637 }
638
639 /* 
640  * Enable or disable the separate finalizer thread.
641  * It's currently disabled because it still requires some
642  * work in the rest of the runtime.
643  */
644 #define ENABLE_FINALIZER_THREAD
645
646 #ifdef WITH_INCLUDED_LIBGC
647 /* from threads.c */
648 extern void mono_gc_stop_world (void);
649 extern void mono_gc_start_world (void);
650 extern void mono_gc_push_all_stacks (void);
651
652 static void mono_gc_lock (void)
653 {
654         EnterCriticalSection (&allocator_section);
655 }
656
657 static void mono_gc_unlock (void)
658 {
659         LeaveCriticalSection (&allocator_section);
660 }
661
662 static GCThreadFunctions mono_gc_thread_vtable = {
663         NULL,
664
665         mono_gc_lock,
666         mono_gc_unlock,
667
668         mono_gc_stop_world,
669         NULL,
670         mono_gc_push_all_stacks,
671         mono_gc_start_world
672 };
673 #endif /* WITH_INCLUDED_LIBGC */
674
675 static void
676 mono_gc_warning (char *msg, GC_word arg)
677 {
678         mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_GC, msg, (unsigned long)arg);
679 }
680
681 static gboolean
682 mono_running_on_valgrind (void)
683 {
684 #ifdef HAVE_VALGRIND_MEMCHECK_H
685                 if (RUNNING_ON_VALGRIND)
686                         return TRUE;
687                 else
688                         return FALSE;
689 #else
690                 return FALSE;
691 #endif
692 }
693
694
695 void mono_gc_init (void)
696 {
697         InitializeCriticalSection (&handle_section);
698         InitializeCriticalSection (&allocator_section);
699
700         InitializeCriticalSection (&finalizer_mutex);
701
702 #ifdef WITH_INCLUDED_LIBGC
703         gc_thread_vtable = &mono_gc_thread_vtable;
704 #endif
705         
706         MONO_GC_REGISTER_ROOT (gc_handles);
707         MONO_GC_REGISTER_ROOT (gc_handle_types);
708         GC_no_dls = TRUE;
709
710         GC_oom_fn = mono_gc_out_of_memory;
711
712         GC_set_warn_proc (mono_gc_warning);
713
714 #ifdef ENABLE_FINALIZER_THREAD
715
716         if (g_getenv ("GC_DONT_GC")) {
717                 gc_disabled = TRUE;
718                 return;
719         }
720         
721         /* valgrind does not play nicely with the GC,
722          * so, turn it off when we are under vg.
723          */
724         if (mono_running_on_valgrind ()) {
725                 /* valgrind doesnt like g_warning for some reason... */
726                 printf ("You are running under valgrind. Currently, valgrind does "
727                            "not support the GC. This program will run with the GC "
728                            "turned off. Your program may take up a fair amount of "
729                            "memory. Also, finalizers will not be run.\n");
730                 
731                 gc_disabled = TRUE;
732                 return;
733         }
734         
735         finalizer_event = CreateEvent (NULL, FALSE, FALSE, NULL);
736         pending_done_event = CreateEvent (NULL, TRUE, FALSE, NULL);
737         shutdown_event = CreateEvent (NULL, TRUE, FALSE, NULL);
738         thread_started_event = CreateEvent (NULL, TRUE, FALSE, NULL);
739         if (finalizer_event == NULL || pending_done_event == NULL || shutdown_event == NULL || thread_started_event == NULL) {
740                 g_assert_not_reached ();
741         }
742
743         GC_finalize_on_demand = 1;
744         GC_finalizer_notifier = finalize_notify;
745
746         mono_thread_create (mono_domain_get (), finalizer_thread, NULL);
747         /*
748          * Wait until the finalizer thread sets gc_thread since its value is needed
749          * by mono_thread_attach ()
750          */
751         WaitForSingleObjectEx (thread_started_event, INFINITE, FALSE);
752 #endif
753 }
754
755 void mono_gc_cleanup (void)
756 {
757 #ifdef DEBUG
758         g_message (G_GNUC_PRETTY_FUNCTION ": cleaning up finalizer");
759 #endif
760
761 #ifdef ENABLE_FINALIZER_THREAD
762         if (!gc_disabled) {
763                 ResetEvent (shutdown_event);
764                 finished = TRUE;
765                 if (mono_thread_current () != gc_thread) {
766                         finalize_notify ();
767                         /* Finishing the finalizer thread, so wait a little bit... */
768                         /* MS seems to wait for about 2 seconds */
769                         if (WaitForSingleObjectEx (shutdown_event, 2000000, FALSE) == WAIT_TIMEOUT) {
770                                 mono_thread_stop (gc_thread);
771                         }
772                 }
773                 gc_thread = NULL;
774                 GC_finalizer_notifier = NULL;
775         }
776
777 #endif
778 }
779
780 void
781 mono_gc_disable (void)
782 {
783 #ifdef HAVE_GC_ENABLE
784         GC_disable ();
785 #else
786         g_assert_not_reached ();
787 #endif
788 }
789
790 void
791 mono_gc_enable (void)
792 {
793 #ifdef HAVE_GC_ENABLE
794         GC_enable ();
795 #else
796         g_assert_not_reached ();
797 #endif
798 }
799
800 #else
801
802 /* no Boehm GC support. */
803 void mono_gc_init (void)
804 {
805         InitializeCriticalSection (&handle_section);
806 }
807
808 void mono_gc_cleanup (void)
809 {
810 }
811
812 void
813 mono_gc_disable (void)
814 {
815 }
816
817 void
818 mono_gc_enable (void)
819 {
820 }
821
822 #endif
823
824 gboolean
825 mono_gc_is_finalizer_thread (MonoThread *thread)
826 {
827         return thread == gc_thread;
828 }
829
830