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