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