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