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