2009-07-20 Geoff Norton <gnorton@novell.com>
[mono.git] / mono / metadata / gc.c
1 /*
2  * metadata/gc.c: GC icalls.
3  *
4  * Author: Paolo Molaro <lupus@ximian.com>
5  *
6  * Copyright 2002-2003 Ximian, Inc (http://www.ximian.com)
7  * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
8  */
9
10 #include <config.h>
11 #include <glib.h>
12 #include <string.h>
13
14 #include <mono/metadata/gc-internal.h>
15 #include <mono/metadata/mono-gc.h>
16 #include <mono/metadata/threads.h>
17 #include <mono/metadata/tabledefs.h>
18 #include <mono/metadata/exception.h>
19 #include <mono/metadata/profiler-private.h>
20 #include <mono/metadata/domain-internals.h>
21 #include <mono/metadata/class-internals.h>
22 #include <mono/metadata/metadata-internals.h>
23 #include <mono/metadata/mono-mlist.h>
24 #include <mono/metadata/threadpool.h>
25 #include <mono/metadata/threads-types.h>
26 #include <mono/utils/mono-logger.h>
27 #include <mono/metadata/gc-internal.h>
28 #include <mono/metadata/marshal.h> /* for mono_delegate_free_ftnptr () */
29 #include <mono/metadata/attach.h>
30 #include <mono/utils/mono-semaphore.h>
31
32 #ifndef PLATFORM_WIN32
33 #include <pthread.h>
34 #endif
35
36 typedef struct DomainFinalizationReq {
37         MonoDomain *domain;
38         HANDLE done_event;
39 } DomainFinalizationReq;
40
41 #ifdef PLATFORM_WINCE /* FIXME: add accessors to gc.dll API */
42 extern void (*__imp_GC_finalizer_notifier)(void);
43 #define GC_finalizer_notifier __imp_GC_finalizer_notifier
44 extern int __imp_GC_finalize_on_demand;
45 #define GC_finalize_on_demand __imp_GC_finalize_on_demand
46 #endif
47
48 static gboolean gc_disabled = FALSE;
49
50 static gboolean finalizing_root_domain = FALSE;
51
52 #define mono_finalizer_lock() EnterCriticalSection (&finalizer_mutex)
53 #define mono_finalizer_unlock() LeaveCriticalSection (&finalizer_mutex)
54 static CRITICAL_SECTION finalizer_mutex;
55
56 static GSList *domains_to_finalize= NULL;
57 static MonoMList *threads_to_finalize = NULL;
58
59 static MonoThread *gc_thread;
60
61 static void object_register_finalizer (MonoObject *obj, void (*callback)(void *, void*));
62
63 static void mono_gchandle_set_target (guint32 gchandle, MonoObject *obj);
64
65 #ifndef HAVE_NULL_GC
66 static HANDLE pending_done_event;
67 static HANDLE shutdown_event;
68 #endif
69
70 static void
71 add_thread_to_finalize (MonoThread *thread)
72 {
73         mono_finalizer_lock ();
74         if (!threads_to_finalize)
75                 MONO_GC_REGISTER_ROOT (threads_to_finalize);
76         threads_to_finalize = mono_mlist_append (threads_to_finalize, (MonoObject*)thread);
77         mono_finalizer_unlock ();
78 }
79
80 static gboolean suspend_finalizers = FALSE;
81 /* 
82  * actually, we might want to queue the finalize requests in a separate thread,
83  * but we need to be careful about the execution domain of the thread...
84  */
85 void
86 mono_gc_run_finalize (void *obj, void *data)
87 {
88         MonoObject *exc = NULL;
89         MonoObject *o;
90 #ifndef HAVE_SGEN_GC
91         MonoObject *o2;
92 #endif
93         MonoMethod* finalizer = NULL;
94         MonoDomain *caller_domain = mono_domain_get ();
95         MonoDomain *domain;
96         RuntimeInvokeFunction runtime_invoke;
97         GSList *l, *refs = NULL;
98
99         o = (MonoObject*)((char*)obj + GPOINTER_TO_UINT (data));
100
101         if (suspend_finalizers)
102                 return;
103
104         domain = o->vtable->domain;
105
106 #ifndef HAVE_SGEN_GC
107         mono_domain_finalizers_lock (domain);
108
109         o2 = g_hash_table_lookup (domain->finalizable_objects_hash, o);
110
111         refs = mono_gc_remove_weak_track_object (domain, o);
112
113         mono_domain_finalizers_unlock (domain);
114
115         if (!o2)
116                 /* Already finalized somehow */
117                 return;
118 #endif
119
120         if (refs) {
121                 /*
122                  * Support for GCHandles of type WeakTrackResurrection:
123                  *
124                  *   Its not exactly clear how these are supposed to work, or how their
125                  * semantics can be implemented. We only implement one crucial thing:
126                  * these handles are only cleared after the finalizer has ran.
127                  */
128                 for (l = refs; l; l = l->next) {
129                         guint32 gchandle = GPOINTER_TO_UINT (l->data);
130
131                         mono_gchandle_set_target (gchandle, o);
132                 }
133
134                 g_slist_free (refs);
135         }
136                 
137         /* make sure the finalizer is not called again if the object is resurrected */
138         object_register_finalizer (obj, NULL);
139
140         if (o->vtable->klass == mono_get_thread_class ()) {
141                 MonoThread *t = (MonoThread*)o;
142
143                 if (mono_gc_is_finalizer_thread (t))
144                         /* Avoid finalizing ourselves */
145                         return;
146
147                 if (t->threadpool_thread && finalizing_root_domain) {
148                         /* Don't finalize threadpool threads when
149                            shutting down - they're finalized when the
150                            threadpool shuts down. */
151                         add_thread_to_finalize (t);
152                         return;
153                 }
154         }
155
156         if (o->vtable->klass->image == mono_defaults.corlib && !strcmp (o->vtable->klass->name, "DynamicMethod") && finalizing_root_domain) {
157                 /*
158                  * These can't be finalized during unloading/shutdown, since that would
159                  * free the native code which can still be referenced by other
160                  * finalizers.
161                  * FIXME: This is not perfect, objects dying at the same time as 
162                  * dynamic methods can still reference them even when !shutdown.
163                  */
164                 return;
165         }
166
167         if (mono_runtime_get_no_exec ())
168                 return;
169
170         /* speedup later... and use a timeout */
171         /* g_print ("Finalize run on %p %s.%s\n", o, mono_object_class (o)->name_space, mono_object_class (o)->name); */
172
173         /* Use _internal here, since this thread can enter a doomed appdomain */
174         mono_domain_set_internal (mono_object_domain (o));
175
176         /* delegates that have a native function pointer allocated are
177          * registered for finalization, but they don't have a Finalize
178          * method, because in most cases it's not needed and it's just a waste.
179          */
180         if (o->vtable->klass->delegate) {
181                 MonoDelegate* del = (MonoDelegate*)o;
182                 if (del->delegate_trampoline)
183                         mono_delegate_free_ftnptr ((MonoDelegate*)o);
184                 return;
185         }
186
187         finalizer = mono_class_get_finalizer (o->vtable->klass);
188
189 #ifndef DISABLE_COM
190         /* If object has a CCW but has no finalizer, it was only
191          * registered for finalization in order to free the CCW.
192          * Else it needs the regular finalizer run.
193          * FIXME: what to do about ressurection and suppression
194          * of finalizer on object with CCW.
195          */
196         if (mono_marshal_free_ccw (o) && !finalizer) {
197                 mono_domain_set_internal (caller_domain);
198                 return;
199         }
200 #endif
201
202         /* 
203          * To avoid the locking plus the other overhead of mono_runtime_invoke (),
204          * create and precompile a wrapper which calls the finalize method using
205          * a CALLVIRT.
206          */
207         if (!domain->finalize_runtime_invoke) {
208                 MonoMethod *invoke = mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE);
209
210                 domain->finalize_runtime_invoke = mono_compile_method (invoke);
211         }
212
213         runtime_invoke = domain->finalize_runtime_invoke;
214
215         mono_runtime_class_init (o->vtable);
216
217         runtime_invoke (o, NULL, &exc, NULL);
218
219         if (exc) {
220                 /* fixme: do something useful */
221         }
222
223         mono_domain_set_internal (caller_domain);
224 }
225
226 void
227 mono_gc_finalize_threadpool_threads (void)
228 {
229         while (threads_to_finalize) {
230                 MonoThread *thread = (MonoThread*) mono_mlist_get_data (threads_to_finalize);
231
232                 /* Force finalization of the thread. */
233                 thread->threadpool_thread = FALSE;
234                 mono_object_register_finalizer ((MonoObject*)thread);
235
236                 mono_gc_run_finalize (thread, NULL);
237
238                 threads_to_finalize = mono_mlist_next (threads_to_finalize);
239         }
240 }
241
242 gpointer
243 mono_gc_out_of_memory (size_t size)
244 {
245         /* 
246          * we could allocate at program startup some memory that we could release 
247          * back to the system at this point if we're really low on memory (ie, size is
248          * lower than the memory we set apart)
249          */
250         mono_raise_exception (mono_domain_get ()->out_of_memory_ex);
251
252         return NULL;
253 }
254
255 /*
256  * Some of our objects may point to a different address than the address returned by GC_malloc()
257  * (because of the GetHashCode hack), but we need to pass the real address to register_finalizer.
258  * This also means that in the callback we need to adjust the pointer to get back the real
259  * MonoObject*.
260  * We also need to be consistent in the use of the GC_debug* variants of malloc and register_finalizer, 
261  * since that, too, can cause the underlying pointer to be offset.
262  */
263 static void
264 object_register_finalizer (MonoObject *obj, void (*callback)(void *, void*))
265 {
266 #if HAVE_BOEHM_GC
267         guint offset = 0;
268         MonoDomain *domain = obj->vtable->domain;
269
270 #ifndef GC_DEBUG
271         /* This assertion is not valid when GC_DEBUG is defined */
272         g_assert (GC_base (obj) == (char*)obj - offset);
273 #endif
274
275         if (mono_domain_is_unloading (domain) && (callback != NULL))
276                 /*
277                  * Can't register finalizers in a dying appdomain, since they
278                  * could be invoked after the appdomain has been unloaded.
279                  */
280                 return;
281
282         mono_domain_finalizers_lock (domain);
283
284         if (callback)
285                 g_hash_table_insert (domain->finalizable_objects_hash, obj, obj);
286         else
287                 g_hash_table_remove (domain->finalizable_objects_hash, obj);
288
289         mono_domain_finalizers_unlock (domain);
290
291         GC_REGISTER_FINALIZER_NO_ORDER ((char*)obj - offset, callback, GUINT_TO_POINTER (offset), NULL, NULL);
292 #elif defined(HAVE_SGEN_GC)
293         mono_gc_register_for_finalization (obj, callback);
294 #endif
295 }
296
297 /**
298  * mono_object_register_finalizer:
299  * @obj: object to register
300  *
301  * Records that object @obj has a finalizer, this will call the
302  * Finalize method when the garbage collector disposes the object.
303  * 
304  */
305 void
306 mono_object_register_finalizer (MonoObject *obj)
307 {
308         /* g_print ("Registered finalizer on %p %s.%s\n", obj, mono_object_class (obj)->name_space, mono_object_class (obj)->name); */
309         object_register_finalizer (obj, mono_gc_run_finalize);
310 }
311
312 /**
313  * mono_domain_finalize:
314  * @domain: the domain to finalize
315  * @timeout: msects to wait for the finalization to complete, -1 to wait indefinitely
316  *
317  *  Request finalization of all finalizable objects inside @domain. Wait
318  * @timeout msecs for the finalization to complete.
319  *
320  * Returns: TRUE if succeeded, FALSE if there was a timeout
321  */
322
323 gboolean
324 mono_domain_finalize (MonoDomain *domain, guint32 timeout) 
325 {
326         DomainFinalizationReq *req;
327         guint32 res;
328         HANDLE done_event;
329
330         if (mono_thread_current () == gc_thread)
331                 /* We are called from inside a finalizer, not much we can do here */
332                 return FALSE;
333
334         /* 
335          * No need to create another thread 'cause the finalizer thread
336          * is still working and will take care of running the finalizers
337          */ 
338         
339 #ifndef HAVE_NULL_GC
340         if (gc_disabled)
341                 return TRUE;
342
343         mono_gc_collect (mono_gc_max_generation ());
344
345         done_event = CreateEvent (NULL, TRUE, FALSE, NULL);
346         if (done_event == NULL) {
347                 return FALSE;
348         }
349
350         req = g_new0 (DomainFinalizationReq, 1);
351         req->domain = domain;
352         req->done_event = done_event;
353
354         if (domain == mono_get_root_domain ())
355                 finalizing_root_domain = TRUE;
356         
357         mono_finalizer_lock ();
358
359         domains_to_finalize = g_slist_append (domains_to_finalize, req);
360
361         mono_finalizer_unlock ();
362
363         /* Tell the finalizer thread to finalize this appdomain */
364         mono_gc_finalize_notify ();
365
366         if (timeout == -1)
367                 timeout = INFINITE;
368
369         res = WaitForSingleObjectEx (done_event, timeout, TRUE);
370
371         /* printf ("WAIT RES: %d.\n", res); */
372         if (res == WAIT_TIMEOUT) {
373                 /* We leak the handle here */
374                 return FALSE;
375         }
376
377         CloseHandle (done_event);
378
379         if (domain == mono_get_root_domain ()) {
380                 mono_thread_pool_cleanup ();
381                 mono_gc_finalize_threadpool_threads ();
382         }
383
384         return TRUE;
385 #else
386         /* We don't support domain finalization without a GC */
387         return FALSE;
388 #endif
389 }
390
391 void
392 ves_icall_System_GC_InternalCollect (int generation)
393 {
394         mono_gc_collect (generation);
395 }
396
397 gint64
398 ves_icall_System_GC_GetTotalMemory (MonoBoolean forceCollection)
399 {
400         MONO_ARCH_SAVE_REGS;
401
402         if (forceCollection)
403                 mono_gc_collect (mono_gc_max_generation ());
404         return mono_gc_get_used_size ();
405 }
406
407 void
408 ves_icall_System_GC_KeepAlive (MonoObject *obj)
409 {
410         MONO_ARCH_SAVE_REGS;
411
412         /*
413          * Does nothing.
414          */
415 }
416
417 void
418 ves_icall_System_GC_ReRegisterForFinalize (MonoObject *obj)
419 {
420         if (!obj)
421                 mono_raise_exception (mono_get_exception_argument_null ("obj"));
422
423         object_register_finalizer (obj, mono_gc_run_finalize);
424 }
425
426 void
427 ves_icall_System_GC_SuppressFinalize (MonoObject *obj)
428 {
429         if (!obj)
430                 mono_raise_exception (mono_get_exception_argument_null ("obj"));
431
432         /* delegates have no finalizers, but we register them to deal with the
433          * unmanaged->managed trampoline. We don't let the user suppress it
434          * otherwise we'd leak it.
435          */
436         if (obj->vtable->klass->delegate)
437                 return;
438
439         /* FIXME: Need to handle case where obj has COM Callable Wrapper
440          * generated for it that needs cleaned up, but user wants to suppress
441          * their derived object finalizer. */
442
443         object_register_finalizer (obj, NULL);
444 }
445
446 void
447 ves_icall_System_GC_WaitForPendingFinalizers (void)
448 {
449 #ifndef HAVE_NULL_GC
450         if (!mono_gc_pending_finalizers ())
451                 return;
452
453         if (mono_thread_current () == gc_thread)
454                 /* Avoid deadlocks */
455                 return;
456
457         ResetEvent (pending_done_event);
458         mono_gc_finalize_notify ();
459         /* g_print ("Waiting for pending finalizers....\n"); */
460         WaitForSingleObjectEx (pending_done_event, INFINITE, TRUE);
461         /* g_print ("Done pending....\n"); */
462 #endif
463 }
464
465 #define mono_allocator_lock() EnterCriticalSection (&allocator_section)
466 #define mono_allocator_unlock() LeaveCriticalSection (&allocator_section)
467 static CRITICAL_SECTION allocator_section;
468 static CRITICAL_SECTION handle_section;
469
470 typedef enum {
471         HANDLE_WEAK,
472         HANDLE_WEAK_TRACK,
473         HANDLE_NORMAL,
474         HANDLE_PINNED
475 } HandleType;
476
477 static HandleType mono_gchandle_get_type (guint32 gchandle);
478
479 MonoObject *
480 ves_icall_System_GCHandle_GetTarget (guint32 handle)
481 {
482         return mono_gchandle_get_target (handle);
483 }
484
485 /*
486  * if type == -1, change the target of the handle, otherwise allocate a new handle.
487  */
488 guint32
489 ves_icall_System_GCHandle_GetTargetHandle (MonoObject *obj, guint32 handle, gint32 type)
490 {
491         if (type == -1) {
492                 mono_gchandle_set_target (handle, obj);
493                 /* the handle doesn't change */
494                 return handle;
495         }
496         switch (type) {
497         case HANDLE_WEAK:
498                 return mono_gchandle_new_weakref (obj, FALSE);
499         case HANDLE_WEAK_TRACK:
500                 return mono_gchandle_new_weakref (obj, TRUE);
501         case HANDLE_NORMAL:
502                 return mono_gchandle_new (obj, FALSE);
503         case HANDLE_PINNED:
504                 return mono_gchandle_new (obj, TRUE);
505         default:
506                 g_assert_not_reached ();
507         }
508         return 0;
509 }
510
511 void
512 ves_icall_System_GCHandle_FreeHandle (guint32 handle)
513 {
514         mono_gchandle_free (handle);
515 }
516
517 gpointer
518 ves_icall_System_GCHandle_GetAddrOfPinnedObject (guint32 handle)
519 {
520         MonoObject *obj;
521
522         if (mono_gchandle_get_type (handle) != HANDLE_PINNED)
523                 return (gpointer)-2;
524         obj = mono_gchandle_get_target (handle);
525         if (obj) {
526                 MonoClass *klass = mono_object_class (obj);
527                 if (klass == mono_defaults.string_class) {
528                         return mono_string_chars ((MonoString*)obj);
529                 } else if (klass->rank) {
530                         return mono_array_addr ((MonoArray*)obj, char, 0);
531                 } else {
532                         /* the C# code will check and throw the exception */
533                         /* FIXME: missing !klass->blittable test, see bug #61134 */
534                         if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
535                                 return (gpointer)-1;
536                         return (char*)obj + sizeof (MonoObject);
537                 }
538         }
539         return NULL;
540 }
541
542 typedef struct {
543         guint32  *bitmap;
544         gpointer *entries;
545         guint32   size;
546         guint8    type;
547         guint     slot_hint : 24; /* starting slot for search */
548         /* 2^16 appdomains should be enough for everyone (though I know I'll regret this in 20 years) */
549         /* we alloc this only for weak refs, since we can get the domain directly in the other cases */
550         guint16  *domain_ids;
551 } HandleData;
552
553 /* weak and weak-track arrays will be allocated in malloc memory 
554  */
555 static HandleData gc_handles [] = {
556         {NULL, NULL, 0, HANDLE_WEAK, 0},
557         {NULL, NULL, 0, HANDLE_WEAK_TRACK, 0},
558         {NULL, NULL, 0, HANDLE_NORMAL, 0},
559         {NULL, NULL, 0, HANDLE_PINNED, 0}
560 };
561
562 #define lock_handles(handles) EnterCriticalSection (&handle_section)
563 #define unlock_handles(handles) LeaveCriticalSection (&handle_section)
564
565 static int
566 find_first_unset (guint32 bitmap)
567 {
568         int i;
569         for (i = 0; i < 32; ++i) {
570                 if (!(bitmap & (1 << i)))
571                         return i;
572         }
573         return -1;
574 }
575
576 static guint32
577 alloc_handle (HandleData *handles, MonoObject *obj, gboolean track)
578 {
579         gint slot, i;
580         lock_handles (handles);
581         if (!handles->size) {
582                 handles->size = 32;
583                 if (handles->type > HANDLE_WEAK_TRACK) {
584                         handles->entries = mono_gc_alloc_fixed (sizeof (gpointer) * handles->size, NULL);
585                 } else {
586                         handles->entries = g_malloc0 (sizeof (gpointer) * handles->size);
587                         handles->domain_ids = g_malloc0 (sizeof (guint16) * handles->size);
588                 }
589                 handles->bitmap = g_malloc0 (handles->size / 8);
590         }
591         i = -1;
592         for (slot = handles->slot_hint; slot < handles->size / 32; ++slot) {
593                 if (handles->bitmap [slot] != 0xffffffff) {
594                         i = find_first_unset (handles->bitmap [slot]);
595                         handles->slot_hint = slot;
596                         break;
597                 }
598         }
599         if (i == -1 && handles->slot_hint != 0) {
600                 for (slot = 0; slot < handles->slot_hint; ++slot) {
601                         if (handles->bitmap [slot] != 0xffffffff) {
602                                 i = find_first_unset (handles->bitmap [slot]);
603                                 handles->slot_hint = slot;
604                                 break;
605                         }
606                 }
607         }
608         if (i == -1) {
609                 guint32 *new_bitmap;
610                 guint32 new_size = handles->size * 2; /* always double: we memset to 0 based on this below */
611
612                 /* resize and copy the bitmap */
613                 new_bitmap = g_malloc0 (new_size / 8);
614                 memcpy (new_bitmap, handles->bitmap, handles->size / 8);
615                 g_free (handles->bitmap);
616                 handles->bitmap = new_bitmap;
617
618                 /* resize and copy the entries */
619                 if (handles->type > HANDLE_WEAK_TRACK) {
620                         gpointer *entries;
621                         entries = mono_gc_alloc_fixed (sizeof (gpointer) * new_size, NULL);
622                         memcpy (entries, handles->entries, sizeof (gpointer) * handles->size);
623                         handles->entries = entries;
624                 } else {
625                         gpointer *entries;
626                         guint16 *domain_ids;
627                         domain_ids = g_malloc0 (sizeof (guint16) * new_size);
628                         entries = g_malloc (sizeof (gpointer) * new_size);
629                         /* we disable GC because we could lose some disappearing link updates */
630                         mono_gc_disable ();
631                         memcpy (entries, handles->entries, sizeof (gpointer) * handles->size);
632                         memset (entries + handles->size, 0, sizeof (gpointer) * handles->size);
633                         memcpy (domain_ids, handles->domain_ids, sizeof (guint16) * handles->size);
634                         for (i = 0; i < handles->size; ++i) {
635                                 MonoObject *obj = mono_gc_weak_link_get (&(handles->entries [i]));
636                                 if (handles->entries [i])
637                                         mono_gc_weak_link_remove (&(handles->entries [i]));
638                                 /*g_print ("reg/unreg entry %d of type %d at %p to object %p (%p), was: %p\n", i, handles->type, &(entries [i]), obj, entries [i], handles->entries [i]);*/
639                                 if (obj) {
640                                         mono_gc_weak_link_add (&(entries [i]), obj, track);
641                                 }
642                         }
643                         g_free (handles->entries);
644                         g_free (handles->domain_ids);
645                         handles->entries = entries;
646                         handles->domain_ids = domain_ids;
647                         mono_gc_enable ();
648                 }
649
650                 /* set i and slot to the next free position */
651                 i = 0;
652                 slot = (handles->size + 1) / 32;
653                 handles->slot_hint = handles->size + 1;
654                 handles->size = new_size;
655         }
656         handles->bitmap [slot] |= 1 << i;
657         slot = slot * 32 + i;
658         handles->entries [slot] = obj;
659         if (handles->type <= HANDLE_WEAK_TRACK) {
660                 if (obj)
661                         mono_gc_weak_link_add (&(handles->entries [slot]), obj, track);
662         }
663
664         mono_perfcounters->gc_num_handles++;
665         unlock_handles (handles);
666         /*g_print ("allocated entry %d of type %d to object %p (in slot: %p)\n", slot, handles->type, obj, handles->entries [slot]);*/
667         return (slot << 3) | (handles->type + 1);
668 }
669
670 /**
671  * mono_gchandle_new:
672  * @obj: managed object to get a handle for
673  * @pinned: whether the object should be pinned
674  *
675  * This returns a handle that wraps the object, this is used to keep a
676  * reference to a managed object from the unmanaged world and preventing the
677  * object from being disposed.
678  * 
679  * If @pinned is false the address of the object can not be obtained, if it is
680  * true the address of the object can be obtained.  This will also pin the
681  * object so it will not be possible by a moving garbage collector to move the
682  * object. 
683  * 
684  * Returns: a handle that can be used to access the object from
685  * unmanaged code.
686  */
687 guint32
688 mono_gchandle_new (MonoObject *obj, gboolean pinned)
689 {
690         return alloc_handle (&gc_handles [pinned? HANDLE_PINNED: HANDLE_NORMAL], obj, FALSE);
691 }
692
693 /**
694  * mono_gchandle_new_weakref:
695  * @obj: managed object to get a handle for
696  * @pinned: whether the object should be pinned
697  *
698  * This returns a weak handle that wraps the object, this is used to
699  * keep a reference to a managed object from the unmanaged world.
700  * Unlike the mono_gchandle_new the object can be reclaimed by the
701  * garbage collector.  In this case the value of the GCHandle will be
702  * set to zero.
703  * 
704  * If @pinned is false the address of the object can not be obtained, if it is
705  * true the address of the object can be obtained.  This will also pin the
706  * object so it will not be possible by a moving garbage collector to move the
707  * object. 
708  * 
709  * Returns: a handle that can be used to access the object from
710  * unmanaged code.
711  */
712 guint32
713 mono_gchandle_new_weakref (MonoObject *obj, gboolean track_resurrection)
714 {
715         guint32 handle = alloc_handle (&gc_handles [track_resurrection? HANDLE_WEAK_TRACK: HANDLE_WEAK], obj, track_resurrection);
716
717 #ifndef HAVE_SGEN_GC
718         if (track_resurrection)
719                 mono_gc_add_weak_track_handle (obj, handle);
720 #endif
721
722         return handle;
723 }
724
725 static HandleType
726 mono_gchandle_get_type (guint32 gchandle)
727 {
728         guint type = (gchandle & 7) - 1;
729
730         return type;
731 }
732
733 /**
734  * mono_gchandle_get_target:
735  * @gchandle: a GCHandle's handle.
736  *
737  * The handle was previously created by calling mono_gchandle_new or
738  * mono_gchandle_new_weakref. 
739  *
740  * Returns a pointer to the MonoObject represented by the handle or
741  * NULL for a collected object if using a weakref handle.
742  */
743 MonoObject*
744 mono_gchandle_get_target (guint32 gchandle)
745 {
746         guint slot = gchandle >> 3;
747         guint type = (gchandle & 7) - 1;
748         HandleData *handles = &gc_handles [type];
749         MonoObject *obj = NULL;
750         if (type > 3)
751                 return NULL;
752         lock_handles (handles);
753         if (slot < handles->size && (handles->bitmap [slot / 32] & (1 << (slot % 32)))) {
754                 if (handles->type <= HANDLE_WEAK_TRACK) {
755                         obj = mono_gc_weak_link_get (&handles->entries [slot]);
756                 } else {
757                         obj = handles->entries [slot];
758                 }
759         } else {
760                 /* print a warning? */
761         }
762         unlock_handles (handles);
763         /*g_print ("get target of entry %d of type %d: %p\n", slot, handles->type, obj);*/
764         return obj;
765 }
766
767 static void
768 mono_gchandle_set_target (guint32 gchandle, MonoObject *obj)
769 {
770         guint slot = gchandle >> 3;
771         guint type = (gchandle & 7) - 1;
772         HandleData *handles = &gc_handles [type];
773         MonoObject *old_obj = NULL;
774
775         if (type > 3)
776                 return;
777         lock_handles (handles);
778         if (slot < handles->size && (handles->bitmap [slot / 32] & (1 << (slot % 32)))) {
779                 if (handles->type <= HANDLE_WEAK_TRACK) {
780                         old_obj = handles->entries [slot];
781                         if (handles->entries [slot])
782                                 mono_gc_weak_link_remove (&handles->entries [slot]);
783                         if (obj)
784                                 mono_gc_weak_link_add (&handles->entries [slot], obj, handles->type == HANDLE_WEAK_TRACK);
785                 } else {
786                         handles->entries [slot] = obj;
787                 }
788         } else {
789                 /* print a warning? */
790         }
791         /*g_print ("changed entry %d of type %d to object %p (in slot: %p)\n", slot, handles->type, obj, handles->entries [slot]);*/
792         unlock_handles (handles);
793
794 #ifndef HAVE_SGEN_GC
795         if (type == HANDLE_WEAK_TRACK)
796                 mono_gc_change_weak_track_handle (old_obj, obj, gchandle);
797 #endif
798 }
799
800 /**
801  * mono_gchandle_is_in_domain:
802  * @gchandle: a GCHandle's handle.
803  * @domain: An application domain.
804  *
805  * Returns: true if the object wrapped by the @gchandle belongs to the specific @domain.
806  */
807 gboolean
808 mono_gchandle_is_in_domain (guint32 gchandle, MonoDomain *domain)
809 {
810         guint slot = gchandle >> 3;
811         guint type = (gchandle & 7) - 1;
812         HandleData *handles = &gc_handles [type];
813         gboolean result = FALSE;
814         if (type > 3)
815                 return FALSE;
816         lock_handles (handles);
817         if (slot < handles->size && (handles->bitmap [slot / 32] & (1 << (slot % 32)))) {
818                 if (handles->type <= HANDLE_WEAK_TRACK) {
819                         result = domain->domain_id == handles->domain_ids [slot];
820                 } else {
821                         MonoObject *obj;
822                         obj = handles->entries [slot];
823                         if (obj == NULL)
824                                 result = TRUE;
825                         else
826                                 result = domain == mono_object_domain (obj);
827                 }
828         } else {
829                 /* print a warning? */
830         }
831         unlock_handles (handles);
832         return result;
833 }
834
835 /**
836  * mono_gchandle_free:
837  * @gchandle: a GCHandle's handle.
838  *
839  * Frees the @gchandle handle.  If there are no outstanding
840  * references, the garbage collector can reclaim the memory of the
841  * object wrapped. 
842  */
843 void
844 mono_gchandle_free (guint32 gchandle)
845 {
846         guint slot = gchandle >> 3;
847         guint type = (gchandle & 7) - 1;
848         HandleData *handles = &gc_handles [type];
849         if (type > 3)
850                 return;
851 #ifndef HAVE_SGEN_GC
852         if (type == HANDLE_WEAK_TRACK)
853                 mono_gc_remove_weak_track_handle (gchandle);
854 #endif
855
856         lock_handles (handles);
857         if (slot < handles->size && (handles->bitmap [slot / 32] & (1 << (slot % 32)))) {
858                 if (handles->type <= HANDLE_WEAK_TRACK) {
859                         if (handles->entries [slot])
860                                 mono_gc_weak_link_remove (&handles->entries [slot]);
861                 } else {
862                         handles->entries [slot] = NULL;
863                 }
864                 handles->bitmap [slot / 32] &= ~(1 << (slot % 32));
865         } else {
866                 /* print a warning? */
867         }
868         mono_perfcounters->gc_num_handles--;
869         /*g_print ("freed entry %d of type %d\n", slot, handles->type);*/
870         unlock_handles (handles);
871 }
872
873 /**
874  * mono_gchandle_free_domain:
875  * @domain: domain that is unloading
876  *
877  * Function used internally to cleanup any GC handle for objects belonging
878  * to the specified domain during appdomain unload.
879  */
880 void
881 mono_gchandle_free_domain (MonoDomain *domain)
882 {
883         guint type;
884
885         for (type = 0; type < 3; ++type) {
886                 guint slot;
887                 HandleData *handles = &gc_handles [type];
888                 lock_handles (handles);
889                 for (slot = 0; slot < handles->size; ++slot) {
890                         if (!(handles->bitmap [slot / 32] & (1 << (slot % 32))))
891                                 continue;
892                         if (type <= HANDLE_WEAK_TRACK) {
893                                 if (domain->domain_id == handles->domain_ids [slot]) {
894                                         handles->bitmap [slot / 32] &= ~(1 << (slot % 32));
895                                         if (handles->entries [slot])
896                                                 mono_gc_weak_link_remove (&handles->entries [slot]);
897                                 }
898                         } else {
899                                 if (handles->entries [slot] && mono_object_domain (handles->entries [slot]) == domain) {
900                                         handles->bitmap [slot / 32] &= ~(1 << (slot % 32));
901                                         handles->entries [slot] = NULL;
902                                 }
903                         }
904                 }
905                 unlock_handles (handles);
906         }
907
908 }
909
910 #ifndef HAVE_NULL_GC
911
912 #ifdef MONO_HAS_SEMAPHORES
913 static MonoSemType finalizer_sem;
914 #endif
915 static HANDLE finalizer_event;
916 static volatile gboolean finished=FALSE;
917
918 void
919 mono_gc_finalize_notify (void)
920 {
921 #ifdef DEBUG
922         g_message (G_GNUC_PRETTY_FUNCTION ": prodding finalizer");
923 #endif
924
925 #ifdef MONO_HAS_SEMAPHORES
926         MONO_SEM_POST (&finalizer_sem);
927 #else
928         SetEvent (finalizer_event);
929 #endif
930 }
931
932 #ifdef HAVE_BOEHM_GC
933
934 static void
935 collect_objects (gpointer key, gpointer value, gpointer user_data)
936 {
937         GPtrArray *arr = (GPtrArray*)user_data;
938         g_ptr_array_add (arr, key);
939 }
940
941 #endif
942
943 /*
944  * finalize_domain_objects:
945  *
946  *  Run the finalizers of all finalizable objects in req->domain.
947  */
948 static void
949 finalize_domain_objects (DomainFinalizationReq *req)
950 {
951         MonoDomain *domain = req->domain;
952
953 #ifdef HAVE_BOEHM_GC
954         while (g_hash_table_size (domain->finalizable_objects_hash) > 0) {
955                 int i;
956                 GPtrArray *objs;
957                 /* 
958                  * Since the domain is unloading, nobody is allowed to put
959                  * new entries into the hash table. But finalize_object might
960                  * remove entries from the hash table, so we make a copy.
961                  */
962                 objs = g_ptr_array_new ();
963                 g_hash_table_foreach (domain->finalizable_objects_hash, collect_objects, objs);
964                 /* printf ("FINALIZING %d OBJECTS.\n", objs->len); */
965
966                 for (i = 0; i < objs->len; ++i) {
967                         MonoObject *o = (MonoObject*)g_ptr_array_index (objs, i);
968                         /* FIXME: Avoid finalizing threads, etc */
969                         mono_gc_run_finalize (o, 0);
970                 }
971
972                 g_ptr_array_free (objs, TRUE);
973         }
974 #elif defined(HAVE_SGEN_GC)
975 #define NUM_FOBJECTS 64
976         MonoObject *to_finalize [NUM_FOBJECTS];
977         int count;
978         while ((count = mono_gc_finalizers_for_domain (domain, to_finalize, NUM_FOBJECTS))) {
979                 int i;
980                 for (i = 0; i < count; ++i) {
981                         mono_gc_run_finalize (to_finalize [i], 0);
982                 }
983         }
984 #endif
985
986         /* Process finalizers which are already in the queue */
987         mono_gc_invoke_finalizers ();
988
989         /* printf ("DONE.\n"); */
990         SetEvent (req->done_event);
991
992         /* The event is closed in mono_domain_finalize if we get here */
993         g_free (req);
994 }
995
996 static guint32
997 finalizer_thread (gpointer unused)
998 {
999         while (!finished) {
1000                 /* Wait to be notified that there's at least one
1001                  * finaliser to run
1002                  */
1003 #ifdef MONO_HAS_SEMAPHORES
1004                 MONO_SEM_WAIT (&finalizer_sem);
1005 #else
1006                 /* Use alertable=FALSE since we will be asked to exit using the event too */
1007                 WaitForSingleObjectEx (finalizer_event, INFINITE, FALSE);
1008 #endif
1009
1010 #ifndef DISABLE_ATTACH
1011                 mono_attach_maybe_start ();
1012 #endif
1013
1014                 if (domains_to_finalize) {
1015                         mono_finalizer_lock ();
1016                         if (domains_to_finalize) {
1017                                 DomainFinalizationReq *req = domains_to_finalize->data;
1018                                 domains_to_finalize = g_slist_remove (domains_to_finalize, req);
1019                                 mono_finalizer_unlock ();
1020
1021                                 finalize_domain_objects (req);
1022                         } else {
1023                                 mono_finalizer_unlock ();
1024                         }
1025                 }                               
1026
1027                 /* If finished == TRUE, mono_gc_cleanup has been called (from mono_runtime_cleanup),
1028                  * before the domain is unloaded.
1029                  */
1030                 mono_gc_invoke_finalizers ();
1031
1032                 SetEvent (pending_done_event);
1033         }
1034
1035         SetEvent (shutdown_event);
1036         return 0;
1037 }
1038
1039 void
1040 mono_gc_init (void)
1041 {
1042         InitializeCriticalSection (&handle_section);
1043         InitializeCriticalSection (&allocator_section);
1044
1045         InitializeCriticalSection (&finalizer_mutex);
1046
1047         MONO_GC_REGISTER_ROOT (gc_handles [HANDLE_NORMAL].entries);
1048         MONO_GC_REGISTER_ROOT (gc_handles [HANDLE_PINNED].entries);
1049
1050         mono_gc_base_init ();
1051
1052         if (g_getenv ("GC_DONT_GC")) {
1053                 gc_disabled = TRUE;
1054                 return;
1055         }
1056         
1057         finalizer_event = CreateEvent (NULL, FALSE, FALSE, NULL);
1058         pending_done_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1059         shutdown_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1060         if (finalizer_event == NULL || pending_done_event == NULL || shutdown_event == NULL) {
1061                 g_assert_not_reached ();
1062         }
1063 #ifdef MONO_HAS_SEMAPHORES
1064         MONO_SEM_INIT (&finalizer_sem, 0);
1065 #endif
1066
1067         gc_thread = mono_thread_create_internal (mono_domain_get (), finalizer_thread, NULL, FALSE);
1068 }
1069
1070 void
1071 mono_gc_cleanup (void)
1072 {
1073 #ifdef DEBUG
1074         g_message (G_GNUC_PRETTY_FUNCTION ": cleaning up finalizer");
1075 #endif
1076
1077         if (!gc_disabled) {
1078                 ResetEvent (shutdown_event);
1079                 finished = TRUE;
1080                 if (mono_thread_current () != gc_thread) {
1081                         mono_gc_finalize_notify ();
1082                         /* Finishing the finalizer thread, so wait a little bit... */
1083                         /* MS seems to wait for about 2 seconds */
1084                         if (WaitForSingleObjectEx (shutdown_event, 2000, FALSE) == WAIT_TIMEOUT) {
1085                                 int ret;
1086
1087                                 /* Set a flag which the finalizer thread can check */
1088                                 suspend_finalizers = TRUE;
1089
1090                                 /* Try to abort the thread, in the hope that it is running managed code */
1091                                 mono_thread_stop (gc_thread);
1092
1093                                 /* Wait for it to stop */
1094                                 ret = WaitForSingleObjectEx (gc_thread->handle, 100, TRUE);
1095
1096                                 if (ret == WAIT_TIMEOUT) {
1097                                         /* 
1098                                          * The finalizer thread refused to die. There is not much we 
1099                                          * can do here, since the runtime is shutting down so the 
1100                                          * state the finalizer thread depends on will vanish.
1101                                          */
1102                                         g_warning ("Shutting down finalizer thread timed out.");
1103                                 } else {
1104                                         /*
1105                                          * FIXME: On unix, when the above wait returns, the thread 
1106                                          * might still be running io-layer code, or pthreads code.
1107                                          */
1108                                         Sleep (100);
1109                                 }
1110
1111                         }
1112                 }
1113                 gc_thread = NULL;
1114 #ifdef HAVE_BOEHM_GC
1115                 GC_finalizer_notifier = NULL;
1116 #endif
1117         }
1118
1119         DeleteCriticalSection (&handle_section);
1120         DeleteCriticalSection (&allocator_section);
1121         DeleteCriticalSection (&finalizer_mutex);
1122 }
1123
1124 #else
1125
1126 /* Null GC dummy functions */
1127 void
1128 mono_gc_finalize_notify (void)
1129 {
1130 }
1131
1132 void mono_gc_init (void)
1133 {
1134         InitializeCriticalSection (&handle_section);
1135 }
1136
1137 void mono_gc_cleanup (void)
1138 {
1139 }
1140
1141 #endif
1142
1143 /**
1144  * mono_gc_is_finalizer_thread:
1145  * @thread: the thread to test.
1146  *
1147  * In Mono objects are finalized asynchronously on a separate thread.
1148  * This routine tests whether the @thread argument represents the
1149  * finalization thread.
1150  * 
1151  * Returns true if @thread is the finalization thread.
1152  */
1153 gboolean
1154 mono_gc_is_finalizer_thread (MonoThread *thread)
1155 {
1156         return thread == gc_thread;
1157 }
1158
1159 static MonoGetIPFromSigCtxFunc get_ip_from_sigctx = NULL;
1160
1161 void
1162 mono_install_get_ip_from_sigctx (MonoGetIPFromSigCtxFunc func)
1163 {
1164         get_ip_from_sigctx = func;
1165 }
1166
1167 gpointer
1168 mono_gc_get_ip_from_sigctx (gpointer ctx)
1169 {
1170         g_assert (get_ip_from_sigctx);
1171         return get_ip_from_sigctx (ctx);
1172 }