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