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