2003-06-15 Zoltan Varga <vargaz@freemail.hu>
[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 #ifdef PLATFORM_WINCE /* FIXME: add accessors to gc.dll API */
26 extern void (*__imp_GC_finalizer_notifier)(void);
27 #define GC_finalizer_notifier __imp_GC_finalizer_notifier
28 extern int __imp_GC_finalize_on_demand;
29 #define GC_finalize_on_demand __imp_GC_finalize_on_demand
30 #endif
31
32 static int finalize_slot = -1;
33
34 static gboolean gc_disabled = FALSE;
35
36 static void object_register_finalizer (MonoObject *obj, void (*callback)(void *, void*));
37
38 #if HAVE_BOEHM_GC
39 static void finalize_notify (void);
40 static HANDLE pending_done_event;
41 #endif
42
43 /* 
44  * actually, we might want to queue the finalize requests in a separate thread,
45  * but we need to be careful about the execution domain of the thread...
46  */
47 static void
48 run_finalize (void *obj, void *data)
49 {
50         MonoObject *exc = NULL;
51         MonoObject *o;
52         o = (MonoObject*)((char*)obj + GPOINTER_TO_UINT (data));
53
54         if (finalize_slot < 0) {
55                 int i;
56                 for (i = 0; i < mono_defaults.object_class->vtable_size; ++i) {
57                         MonoMethod *cm = mono_defaults.object_class->vtable [i];
58                
59                         if (!strcmp (cm->name, "Finalize")) {
60                                 finalize_slot = i;
61                                 break;
62                         }
63                 }
64         }
65
66         /* make sure the finalizer is not called again if the object is resurrected */
67         object_register_finalizer (obj, NULL);
68         /* speedup later... and use a timeout */
69         /*g_print ("Finalize run on %p %s.%s\n", o, mono_object_class (o)->name_space, mono_object_class (o)->name);*/
70         mono_domain_set (mono_object_domain (o));
71
72         mono_runtime_invoke (o->vtable->klass->vtable [finalize_slot], o, NULL, &exc);
73
74         if (exc) {
75                 /* fixme: do something useful */
76         }
77 }
78
79 /*
80  * Some of our objects may point to a different address than the address returned by GC_malloc()
81  * (because of the GetHashCode hack), but we need to pass the real address to register_finalizer.
82  * This also means that in the callback we need to adjust the pointer to get back the real
83  * MonoObject*.
84  * We also need to be consistent in the use of the GC_debug* variants of malloc and register_finalizer, 
85  * since that, too, can cause the underlying pointer to be offset.
86  */
87 static void
88 object_register_finalizer (MonoObject *obj, void (*callback)(void *, void*))
89 {
90 #if HAVE_BOEHM_GC
91         guint offset = 0;
92
93 #ifndef GC_DEBUG
94         /* This assertion is not valid when GC_DEBUG is defined */
95         g_assert (GC_base (obj) == (char*)obj - offset);
96 #endif
97         GC_REGISTER_FINALIZER_NO_ORDER ((char*)obj - offset, callback, GUINT_TO_POINTER (offset), NULL, NULL);
98 #endif
99 }
100
101 void
102 mono_object_register_finalizer (MonoObject *obj)
103 {
104         /*g_print ("Registered finalizer on %p %s.%s\n", obj, mono_object_class (obj)->name_space, mono_object_class (obj)->name);*/
105         object_register_finalizer (obj, run_finalize);
106 }
107
108 /* 
109  * to speedup, at class init time, check if a class or struct
110  * have fields that need to be finalized and set a flag.
111  */
112 static void
113 finalize_fields (MonoClass *class, char *data, gboolean instance, GHashTable *todo) {
114         int i;
115         MonoClassField *field;
116         MonoObject *obj;
117
118         /*if (!instance)
119                 g_print ("Finalize statics on on %s\n", class->name);*/
120         if (instance && class->valuetype)
121                 data -= sizeof (MonoObject);
122         do {
123                 for (i = 0; i < class->field.count; ++i) {
124                         field = &class->fields [i];
125                         if (instance) {
126                                 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
127                                         continue;
128                         } else {
129                                 if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC))
130                                         continue;
131                         }
132                         switch (field->type->type) {
133                         case MONO_TYPE_OBJECT:
134                         case MONO_TYPE_CLASS:
135                                 obj = *((MonoObject**)(data + field->offset));
136                                 if (obj) {
137                                         if (mono_object_class (obj)->has_finalize) {
138                                                 /* disable the registered finalizer */
139                                                 object_register_finalizer (obj, NULL);
140                                                 run_finalize (obj, NULL);
141                                         } else {
142                                                 /* 
143                                                  * if the type doesn't have a finalizer, we finalize 
144                                                  * the fields ourselves just like we do for structs.
145                                                  * Disabled for now: how do we handle loops?
146                                                  */
147                                                 /*finalize_fields (mono_object_class (obj), obj, TRUE, todo);*/
148                                         }
149                                 }
150                                 break;
151                         case MONO_TYPE_VALUETYPE: {
152                                 MonoClass *fclass = mono_class_from_mono_type (field->type);
153                                 if (fclass->enumtype)
154                                         continue;
155                                 /*finalize_fields (fclass, data + field->offset, TRUE, todo);*/
156                                 break;
157                         }
158                         case MONO_TYPE_ARRAY:
159                         case MONO_TYPE_SZARRAY:
160                                 /* FIXME: foreach item... */
161                                 break;
162                         }
163                 }
164                 if (!instance)
165                         return;
166                 class = class->parent;
167         } while (class);
168 }
169
170 static void
171 finalize_static_data (MonoClass *class, MonoVTable *vtable, GHashTable *todo) {
172
173         if (class->enumtype || !vtable->data)
174                 return;
175         finalize_fields (class, vtable->data, FALSE, todo);
176 }
177
178 void
179 mono_domain_finalize (MonoDomain *domain) 
180 {
181         GHashTable *todo = g_hash_table_new (NULL, NULL);
182
183         /* 
184          * No need to create another thread 'cause the finalizer thread
185          * is still working and will take care of running the finalizers
186          */ 
187         
188 #if HAVE_BOEHM_GC
189         GC_gcollect ();
190 #endif
191         mono_g_hash_table_foreach (domain->class_vtable_hash, (GHFunc)finalize_static_data, todo);
192         /* FIXME: finalize objects in todo... */
193         g_hash_table_destroy (todo);
194
195         return;
196 }
197
198 void
199 ves_icall_System_GC_InternalCollect (int generation)
200 {
201         MONO_ARCH_SAVE_REGS;
202
203 #if HAVE_BOEHM_GC
204         GC_gcollect ();
205 #endif
206 }
207
208 gint64
209 ves_icall_System_GC_GetTotalMemory (MonoBoolean forceCollection)
210 {
211         MONO_ARCH_SAVE_REGS;
212
213 #if HAVE_BOEHM_GC
214         if (forceCollection)
215                 GC_gcollect ();
216         return GC_get_heap_size ();
217 #else
218         return 0;
219 #endif
220 }
221
222 void
223 ves_icall_System_GC_KeepAlive (MonoObject *obj)
224 {
225         MONO_ARCH_SAVE_REGS;
226
227         /*
228          * Does nothing.
229          */
230 }
231
232 void
233 ves_icall_System_GC_ReRegisterForFinalize (MonoObject *obj)
234 {
235         MONO_ARCH_SAVE_REGS;
236
237         object_register_finalizer (obj, run_finalize);
238 }
239
240 void
241 ves_icall_System_GC_SuppressFinalize (MonoObject *obj)
242 {
243         MONO_ARCH_SAVE_REGS;
244
245         object_register_finalizer (obj, NULL);
246 }
247
248 void
249 ves_icall_System_GC_WaitForPendingFinalizers (void)
250 {
251         MONO_ARCH_SAVE_REGS;
252         
253 #if HAVE_BOEHM_GC
254         if (!GC_should_invoke_finalizers ())
255                 return;
256
257         ResetEvent (pending_done_event);
258         finalize_notify ();
259         /* g_print ("Waiting for pending finalizers....\n"); */
260         WaitForSingleObject (pending_done_event, INFINITE);
261         /* g_print ("Done pending....\n"); */
262 #else
263 #endif
264 }
265
266 static CRITICAL_SECTION allocator_section;
267 static CRITICAL_SECTION handle_section;
268 static guint32 next_handle = 0;
269 static gpointer *gc_handles = NULL;
270 static guint8 *gc_handle_types = NULL;
271 static guint32 array_size = 0;
272
273 /*
274  * The handle type is encoded in the lower two bits of the handle value:
275  * 0 -> normal
276  * 1 -> pinned
277  * 2 -> weak
278  */
279
280 typedef enum {
281         HANDLE_WEAK,
282         HANDLE_WEAK_TRACK,
283         HANDLE_NORMAL,
284         HANDLE_PINNED
285 } HandleType;
286
287 /*
288  * FIXME: make thread safe and reuse the array entries.
289  */
290 MonoObject *
291 ves_icall_System_GCHandle_GetTarget (guint32 handle)
292 {
293         MonoObject *obj;
294         gint32 type;
295
296         MONO_ARCH_SAVE_REGS;
297
298         if (gc_handles) {
299                 type = handle & 0x3;
300                 EnterCriticalSection (&handle_section);
301                 g_assert (type == gc_handle_types [handle >> 2]);
302                 obj = gc_handles [handle >> 2];
303                 LeaveCriticalSection (&handle_section);
304                 if (!obj)
305                         return NULL;
306
307                 if ((type == HANDLE_WEAK) || (type == HANDLE_WEAK_TRACK))
308                         return REVEAL_POINTER (obj);
309                 else
310                         return obj;
311         }
312         return NULL;
313 }
314
315 guint32
316 ves_icall_System_GCHandle_GetTargetHandle (MonoObject *obj, guint32 handle, gint32 type)
317 {
318         gpointer val = obj;
319         guint32 h, idx;
320
321         MONO_ARCH_SAVE_REGS;
322
323         EnterCriticalSection (&handle_section);
324         /* Indexes start from 1 since 0 means the handle is not allocated */
325         idx = ++next_handle;
326         if (idx >= array_size) {
327 #if HAVE_BOEHM_GC
328                 gpointer *new_array;
329                 guint8 *new_type_array;
330                 if (!array_size)
331                         array_size = 16;
332                 new_array = GC_MALLOC (sizeof (gpointer) * (array_size * 2));
333                 new_type_array = GC_MALLOC (sizeof (guint8) * (array_size * 2));
334                 if (gc_handles) {
335                         int i;
336                         memcpy (new_array, gc_handles, sizeof (gpointer) * array_size);
337                         memcpy (new_type_array, gc_handle_types, sizeof (guint8) * array_size);
338                         /* need to re-register links for weak refs. test if GC_realloc needs the same */
339                         for (i = 0; i < array_size; ++i) {
340 #if 0 /* This breaks the threaded finalizer, by causing segfaults deep
341        * inside libgc.  I assume it will also break without the
342        * threaded finalizer, just that the stress test (bug 31333)
343        * deadlocks too early without it.  Reverting to the previous
344        * version here stops the segfault.
345        */
346                                 if ((gc_handle_types[i] == HANDLE_WEAK) || (gc_handle_types[i] == HANDLE_WEAK_TRACK)) { /* all and only disguised pointers have it set */
347 #else
348                                 if (((gulong)new_array [i]) & 0x1) {
349 #endif
350                                         if (gc_handles [i] != (gpointer)-1)
351                                                 GC_unregister_disappearing_link (&(gc_handles [i]));
352                                         if (new_array [i] != (gpointer)-1)
353                                                 GC_GENERAL_REGISTER_DISAPPEARING_LINK (&(new_array [i]), REVEAL_POINTER (new_array [i]));
354                                 }
355                         }
356                 }
357                 array_size *= 2;
358                 gc_handles = new_array;
359                 gc_handle_types = new_type_array;
360 #else
361                 mono_raise_exception (mono_get_exception_execution_engine ("No GCHandle support built-in"));
362 #endif
363         }
364
365         /* resuse the type from the old target */
366         if (type == -1)
367                 type =  handle & 0x3;
368         h = (idx << 2) | type;
369         switch (type) {
370         case HANDLE_WEAK:
371         case HANDLE_WEAK_TRACK:
372                 val = (gpointer)HIDE_POINTER (val);
373                 gc_handles [idx] = val;
374                 gc_handle_types [idx] = type;
375 #if HAVE_BOEHM_GC
376                 if (gc_handles [idx] != (gpointer)-1)
377                         GC_GENERAL_REGISTER_DISAPPEARING_LINK (&(gc_handles [idx]), obj);
378 #else
379                 mono_raise_exception (mono_get_exception_execution_engine ("No weakref support"));
380 #endif
381                 break;
382         default:
383                 gc_handles [idx] = val;
384                 gc_handle_types [idx] = type;
385                 break;
386         }
387         LeaveCriticalSection (&handle_section);
388         return h;
389 }
390
391 void
392 ves_icall_System_GCHandle_FreeHandle (guint32 handle)
393 {
394         int idx = handle >> 2;
395         int type = handle & 0x3;
396
397         MONO_ARCH_SAVE_REGS;
398
399         EnterCriticalSection (&handle_section);
400
401 #ifdef HAVE_BOEHM_GC
402         g_assert (type == gc_handle_types [idx]);
403         if ((type == HANDLE_WEAK) || (type == HANDLE_WEAK_TRACK)) {
404                 if (gc_handles [idx] != (gpointer)-1)
405                         GC_unregister_disappearing_link (&(gc_handles [idx]));
406         }
407 #else
408         mono_raise_exception (mono_get_exception_execution_engine ("No GCHandle support"));
409 #endif
410
411         gc_handles [idx] = (gpointer)-1;
412         gc_handle_types [idx] = (guint8)-1;
413         LeaveCriticalSection (&handle_section);
414 }
415
416 gpointer
417 ves_icall_System_GCHandle_GetAddrOfPinnedObject (guint32 handle)
418 {
419         MonoObject *obj;
420         int type = handle & 0x3;
421
422         MONO_ARCH_SAVE_REGS;
423
424         if (gc_handles) {
425                 EnterCriticalSection (&handle_section);
426                 obj = gc_handles [handle >> 2];
427                 g_assert (gc_handle_types [handle >> 2] == type);
428                 LeaveCriticalSection (&handle_section);
429                 if ((type == HANDLE_WEAK) || (type == HANDLE_WEAK_TRACK)) {
430                         obj = REVEAL_POINTER (obj);
431                         if (obj == (MonoObject *) -1)
432                                 return NULL;
433                 }
434                 return obj;
435         }
436         return NULL;
437 }
438
439 #if HAVE_BOEHM_GC
440
441 static HANDLE finalizer_event;
442 static volatile gboolean finished=FALSE;
443
444 static void finalize_notify (void)
445 {
446         gboolean pending = GC_should_invoke_finalizers ();
447 #ifdef DEBUG
448         g_message (G_GNUC_PRETTY_FUNCTION ": prodding finalizer");
449 #endif
450
451         SetEvent (finalizer_event);
452         if (finished && pending) {
453                 /* Finishing the finalizer thread, so wait a little bit... */
454                 /* MS seems to wait for about 2 seconds */
455                 ResetEvent (pending_done_event);
456                 WaitForSingleObject (pending_done_event, 2000);
457         }
458 }
459
460 static guint32 finalizer_thread (gpointer unused)
461 {
462         guint32 stack_start;
463         
464         mono_thread_new_init (GetCurrentThreadId (), &stack_start, NULL);
465         
466         while(!finished) {
467                 /* Wait to be notified that there's at least one
468                  * finaliser to run
469                  */
470                 WaitForSingleObject (finalizer_event, INFINITE);
471
472 #ifdef DEBUG
473                 g_message (G_GNUC_PRETTY_FUNCTION ": invoking finalizers");
474 #endif
475
476                 /* Can't run finalizers if we're finishing up, because the
477                  * domain has already been destroyed
478                  *
479                  * There is a bug in GC_invoke_finalizer () in versions <= 6.2alpha4:
480                  * the 'mem_freed' variable is not initialized when there are no
481                  * objects to finalize, which leads to strange behavior later on.
482                  * The check is necessary to work around that bug.
483                  */
484                 if(!finished && GC_should_invoke_finalizers ()) {
485                         GC_invoke_finalizers ();
486                 }
487                 SetEvent (pending_done_event);
488         }
489         
490         return(0);
491 }
492
493 /* 
494  * Enable or disable the separate finalizer thread.
495  * It's currently disabled because it still requires some
496  * work in the rest of the runtime.
497  */
498 #define ENABLE_FINALIZER_THREAD
499
500 #ifdef WITH_INCLUDED_LIBGC
501 /* from threads.c */
502 extern void mono_gc_stop_world (void);
503 extern void mono_gc_start_world (void);
504 extern void mono_gc_push_all_stacks (void);
505
506 static void mono_gc_lock (void)
507 {
508         EnterCriticalSection (&allocator_section);
509 }
510
511 static void mono_gc_unlock (void)
512 {
513         LeaveCriticalSection (&allocator_section);
514 }
515
516 static GCThreadFunctions mono_gc_thread_vtable = {
517         NULL,
518
519         mono_gc_lock,
520         mono_gc_unlock,
521
522         mono_gc_stop_world,
523         NULL,
524         mono_gc_push_all_stacks,
525         mono_gc_start_world
526 };
527 #endif /* WITH_INCLUDED_LIBGC */
528
529 void mono_gc_init (void)
530 {
531         HANDLE gc_thread;
532
533         InitializeCriticalSection (&handle_section);
534         InitializeCriticalSection (&allocator_section);
535
536 #ifdef WITH_INCLUDED_LIBGC
537         gc_thread_vtable = &mono_gc_thread_vtable;
538 #endif
539
540 #ifdef ENABLE_FINALIZER_THREAD
541
542         if (getenv ("GC_DONT_GC")) {
543                 gc_disabled = TRUE;
544                 return;
545         }
546         
547         finalizer_event = CreateEvent (NULL, FALSE, FALSE, NULL);
548         pending_done_event = CreateEvent (NULL, TRUE, FALSE, NULL);
549         if (finalizer_event == NULL || pending_done_event == NULL) {
550                 g_assert_not_reached ();
551         }
552
553         GC_finalize_on_demand = 1;
554         GC_finalizer_notifier = finalize_notify;
555         
556         /* Don't use mono_thread_create here, because we don't want
557          * the runtime to wait for this thread to exit when it's
558          * cleaning up.
559          */
560         gc_thread = CreateThread (NULL, 0, finalizer_thread, NULL, 0, NULL);
561         if (gc_thread == NULL) {
562                 g_assert_not_reached ();
563         }
564 #endif
565 }
566
567 void mono_gc_cleanup (void)
568 {
569 #ifdef DEBUG
570         g_message (G_GNUC_PRETTY_FUNCTION ": cleaning up finalizer");
571 #endif
572
573 #ifdef ENABLE_FINALIZER_THREAD
574         finished = TRUE;
575         if (!gc_disabled)
576                 finalize_notify ();
577 #endif
578 }
579
580 #else
581
582 /* no Boehm GC support. */
583 void mono_gc_init (void)
584 {
585         InitializeCriticalSection (&handle_section);
586 }
587
588 void mono_gc_cleanup (void)
589 {
590 }
591
592 #endif
593