Merge pull request #499 from bh-whd/master
[mono.git] / mono / metadata / boehm-gc.c
1 /*
2  * boehm-gc.c: GC implementation using either the installed or included Boehm GC.
3  *
4  * Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
5  * Copyright 2004-2011 Novell, Inc (http://www.novell.com)
6  * Copyright 2011-2012 Xamarin, Inc (http://www.xamarin.com)
7  */
8
9 #include "config.h"
10
11 #include <string.h>
12
13 #define GC_I_HIDE_POINTERS
14 #include <mono/metadata/gc-internal.h>
15 #include <mono/metadata/mono-gc.h>
16 #include <mono/metadata/gc-internal.h>
17 #include <mono/metadata/profiler-private.h>
18 #include <mono/metadata/class-internals.h>
19 #include <mono/metadata/method-builder.h>
20 #include <mono/metadata/opcodes.h>
21 #include <mono/metadata/domain-internals.h>
22 #include <mono/metadata/metadata-internals.h>
23 #include <mono/metadata/marshal.h>
24 #include <mono/metadata/runtime.h>
25 #include <mono/utils/mono-logger-internal.h>
26 #include <mono/utils/mono-time.h>
27 #include <mono/utils/mono-threads.h>
28 #include <mono/utils/dtrace.h>
29 #include <mono/utils/gc_wrapper.h>
30
31 #if HAVE_BOEHM_GC
32
33 #ifdef USE_INCLUDED_LIBGC
34 #undef TRUE
35 #undef FALSE
36 #define THREAD_LOCAL_ALLOC 1
37 #include "private/pthread_support.h"
38 #endif
39
40 #if defined(PLATFORM_MACOSX) && defined(HAVE_PTHREAD_GET_STACKADDR_NP)
41 void *pthread_get_stackaddr_np(pthread_t);
42 #endif
43
44 #define GC_NO_DESCRIPTOR ((gpointer)(0 | GC_DS_LENGTH))
45 /*Boehm max heap cannot be smaller than 16MB*/
46 #define MIN_BOEHM_MAX_HEAP_SIZE_IN_MB 16
47 #define MIN_BOEHM_MAX_HEAP_SIZE (MIN_BOEHM_MAX_HEAP_SIZE_IN_MB << 20)
48
49 static gboolean gc_initialized = FALSE;
50
51 static void*
52 boehm_thread_register (MonoThreadInfo* info, void *baseptr);
53
54 static void
55 mono_gc_warning (char *msg, GC_word arg)
56 {
57         mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_GC, msg, (unsigned long)arg);
58 }
59
60 void
61 mono_gc_base_init (void)
62 {
63         MonoThreadInfoCallbacks cb;
64         char *env;
65
66         if (gc_initialized)
67                 return;
68
69         /*
70          * Handle the case when we are called from a thread different from the main thread,
71          * confusing libgc.
72          * FIXME: Move this to libgc where it belongs.
73          *
74          * we used to do this only when running on valgrind,
75          * but it happens also in other setups.
76          */
77 #if defined(HAVE_PTHREAD_GETATTR_NP) && defined(HAVE_PTHREAD_ATTR_GETSTACK)
78         {
79                 size_t size;
80                 void *sstart;
81                 pthread_attr_t attr;
82                 pthread_getattr_np (pthread_self (), &attr);
83                 pthread_attr_getstack (&attr, &sstart, &size);
84                 pthread_attr_destroy (&attr); 
85                 /*g_print ("stackbottom pth is: %p\n", (char*)sstart + size);*/
86 #ifdef __ia64__
87                 /*
88                  * The calculation above doesn't seem to work on ia64, also we need to set
89                  * GC_register_stackbottom as well, but don't know how.
90                  */
91 #else
92                 /* apparently with some linuxthreads implementations sstart can be NULL,
93                  * fallback to the more imprecise method (bug# 78096).
94                  */
95                 if (sstart) {
96                         GC_stackbottom = (char*)sstart + size;
97                 } else {
98                         int dummy;
99                         gsize stack_bottom = (gsize)&dummy;
100                         stack_bottom += 4095;
101                         stack_bottom &= ~4095;
102                         GC_stackbottom = (char*)stack_bottom;
103                 }
104 #endif
105         }
106 #elif defined(HAVE_PTHREAD_GET_STACKSIZE_NP) && defined(HAVE_PTHREAD_GET_STACKADDR_NP)
107                 GC_stackbottom = (char*)pthread_get_stackaddr_np (pthread_self ());
108 #elif defined(__OpenBSD__)
109 #  include <pthread_np.h>
110         {
111                 stack_t ss;
112                 int rslt;
113
114                 rslt = pthread_stackseg_np(pthread_self(), &ss);
115                 g_assert (rslt == 0);
116
117                 GC_stackbottom = (char*)ss.ss_sp;
118         }
119 #elif defined(__native_client__)
120         /* Do nothing, GC_stackbottom is set correctly in libgc */
121 #else
122         {
123                 int dummy;
124                 gsize stack_bottom = (gsize)&dummy;
125                 stack_bottom += 4095;
126                 stack_bottom &= ~4095;
127                 /*g_print ("stackbottom is: %p\n", (char*)stack_bottom);*/
128                 GC_stackbottom = (char*)stack_bottom;
129         }
130 #endif
131
132 #if !defined(PLATFORM_ANDROID)
133         /* If GC_no_dls is set to true, GC_find_limit is not called. This causes a seg fault on Android. */
134         GC_no_dls = TRUE;
135 #endif
136         GC_init ();
137         GC_oom_fn = mono_gc_out_of_memory;
138         GC_set_warn_proc (mono_gc_warning);
139         GC_finalize_on_demand = 1;
140         GC_finalizer_notifier = mono_gc_finalize_notify;
141
142 #ifdef HAVE_GC_GCJ_MALLOC
143         GC_init_gcj_malloc (5, NULL);
144 #endif
145
146 #ifdef HAVE_GC_ALLOW_REGISTER_THREADS
147         GC_allow_register_threads();
148 #endif
149
150         if ((env = getenv ("MONO_GC_PARAMS"))) {
151                 char **ptr, **opts = g_strsplit (env, ",", -1);
152                 for (ptr = opts; *ptr; ++ptr) {
153                         char *opt = *ptr;
154                         if (g_str_has_prefix (opt, "max-heap-size=")) {
155                                 glong max_heap;
156
157                                 opt = strchr (opt, '=') + 1;
158                                 if (*opt && mono_gc_parse_environment_string_extract_number (opt, &max_heap)) {
159                                         if (max_heap < MIN_BOEHM_MAX_HEAP_SIZE) {
160                                                 fprintf (stderr, "max-heap-size must be at least %dMb.\n", MIN_BOEHM_MAX_HEAP_SIZE_IN_MB);
161                                                 exit (1);
162                                         }
163                                         GC_set_max_heap_size (max_heap);
164                                 } else {
165                                         fprintf (stderr, "max-heap-size must be an integer.\n");
166                                         exit (1);
167                                 }
168                                 continue;
169                         } else {
170                                 /* Could be a parameter for sgen */
171                                 /*
172                                 fprintf (stderr, "MONO_GC_PARAMS must be a comma-delimited list of one or more of the following:\n");
173                                 fprintf (stderr, "  max-heap-size=N (where N is an integer, possibly with a k, m or a g suffix)\n");
174                                 exit (1);
175                                 */
176                         }
177                 }
178                 g_strfreev (opts);
179         }
180
181         memset (&cb, 0, sizeof (cb));
182         cb.thread_register = boehm_thread_register;
183         cb.mono_method_is_critical = (gpointer)mono_runtime_is_critical_method;
184 #ifndef HOST_WIN32
185         cb.mono_gc_pthread_create = (gpointer)mono_gc_pthread_create;
186 #endif
187         
188         mono_threads_init (&cb, sizeof (MonoThreadInfo));
189
190         mono_gc_enable_events ();
191         gc_initialized = TRUE;
192 }
193
194 /**
195  * mono_gc_collect:
196  * @generation: GC generation identifier
197  *
198  * Perform a garbage collection for the given generation, higher numbers
199  * mean usually older objects. Collecting a high-numbered generation
200  * implies collecting also the lower-numbered generations.
201  * The maximum value for @generation can be retrieved with a call to
202  * mono_gc_max_generation(), so this function is usually called as:
203  *
204  *      mono_gc_collect (mono_gc_max_generation ());
205  */
206 void
207 mono_gc_collect (int generation)
208 {
209         MONO_GC_BEGIN (generation);
210
211 #ifndef DISABLE_PERFCOUNTERS
212         mono_perfcounters->gc_induced++;
213 #endif
214         GC_gcollect ();
215         
216         MONO_GC_END (generation);
217 #if defined(ENABLE_DTRACE) && defined(__sun__)
218         /* This works around a dtrace -G problem on Solaris.
219            Limit its actual use to when the probe is enabled. */
220         if (MONO_GC_END_ENABLED ())
221                 sleep(0);
222 #endif
223 }
224
225 /**
226  * mono_gc_max_generation:
227  *
228  * Get the maximum generation number used by the current garbage
229  * collector. The value will be 0 for the Boehm collector, 1 or more
230  * for the generational collectors.
231  *
232  * Returns: the maximum generation number.
233  */
234 int
235 mono_gc_max_generation (void)
236 {
237         return 0;
238 }
239
240 /**
241  * mono_gc_get_generation:
242  * @object: a managed object
243  *
244  * Get the garbage collector's generation that @object belongs to.
245  * Use this has a hint only.
246  *
247  * Returns: a garbage collector generation number
248  */
249 int
250 mono_gc_get_generation  (MonoObject *object)
251 {
252         return 0;
253 }
254
255 /**
256  * mono_gc_collection_count:
257  * @generation: a GC generation number
258  *
259  * Get how many times a garbage collection has been performed
260  * for the given @generation number.
261  *
262  * Returns: the number of garbage collections
263  */
264 int
265 mono_gc_collection_count (int generation)
266 {
267         return GC_gc_no;
268 }
269
270 /**
271  * mono_gc_add_memory_pressure:
272  * @value: amount of bytes
273  *
274  * Adjust the garbage collector's view of how many bytes of memory
275  * are indirectly referenced by managed objects (for example unmanaged
276  * memory holding image or other binary data).
277  * This is a hint only to the garbage collector algorithm.
278  * Note that negative amounts of @value will decrease the memory
279  * pressure.
280  */
281 void
282 mono_gc_add_memory_pressure (gint64 value)
283 {
284 }
285
286 /**
287  * mono_gc_get_used_size:
288  *
289  * Get the approximate amount of memory used by managed objects.
290  *
291  * Returns: the amount of memory used in bytes
292  */
293 int64_t
294 mono_gc_get_used_size (void)
295 {
296         return GC_get_heap_size () - GC_get_free_bytes ();
297 }
298
299 /**
300  * mono_gc_get_heap_size:
301  *
302  * Get the amount of memory used by the garbage collector.
303  *
304  * Returns: the size of the heap in bytes
305  */
306 int64_t
307 mono_gc_get_heap_size (void)
308 {
309         return GC_get_heap_size ();
310 }
311
312 void
313 mono_gc_disable (void)
314 {
315 #ifdef HAVE_GC_ENABLE
316         GC_disable ();
317 #else
318         g_assert_not_reached ();
319 #endif
320 }
321
322 void
323 mono_gc_enable (void)
324 {
325 #ifdef HAVE_GC_ENABLE
326         GC_enable ();
327 #else
328         g_assert_not_reached ();
329 #endif
330 }
331
332 gboolean
333 mono_gc_is_gc_thread (void)
334 {
335 #if GC_VERSION_MAJOR >= 7
336         return TRUE;
337 #elif defined(USE_INCLUDED_LIBGC)
338         return GC_thread_is_registered ();
339 #else
340         return TRUE;
341 #endif
342 }
343
344 extern int GC_thread_register_foreign (void *base_addr);
345
346 gboolean
347 mono_gc_register_thread (void *baseptr)
348 {
349         return mono_thread_info_attach (baseptr) != NULL;
350 }
351
352 static void*
353 boehm_thread_register (MonoThreadInfo* info, void *baseptr)
354 {
355 #if GC_VERSION_MAJOR >= 7
356         struct GC_stack_base sb;
357         int res;
358
359         res = GC_get_stack_base (&sb);
360         if (res != GC_SUCCESS) {
361                 sb.mem_base = baseptr;
362 #ifdef __ia64__
363                 /* Can't determine the register stack bounds */
364                 g_error ("mono_gc_register_thread failed ().\n");
365 #endif
366         }
367         res = GC_register_my_thread (&sb);
368         if ((res != GC_SUCCESS) && (res != GC_DUPLICATE)) {
369                 g_warning ("GC_register_my_thread () failed.\n");
370                 return NULL;
371         }
372         return info;
373 #else
374         if (mono_gc_is_gc_thread())
375                 return info;
376 #if defined(USE_INCLUDED_LIBGC) && !defined(HOST_WIN32)
377         return GC_thread_register_foreign (baseptr) ? info : NULL;
378 #else
379         return NULL;
380 #endif
381 #endif
382 }
383
384 gboolean
385 mono_object_is_alive (MonoObject* o)
386 {
387 #ifdef USE_INCLUDED_LIBGC
388         return GC_is_marked ((gpointer)o);
389 #else
390         return TRUE;
391 #endif
392 }
393
394 int
395 mono_gc_walk_heap (int flags, MonoGCReferences callback, void *data)
396 {
397         return 1;
398 }
399
400 #ifdef USE_INCLUDED_LIBGC
401
402 static gint64 gc_start_time;
403
404 static void
405 on_gc_notification (GCEventType event)
406 {
407         MonoGCEvent e = (MonoGCEvent)event;
408
409         if (e == MONO_GC_EVENT_PRE_STOP_WORLD) 
410                 mono_thread_info_suspend_lock ();
411         else if (e == MONO_GC_EVENT_POST_START_WORLD)
412                 mono_thread_info_suspend_unlock ();
413         
414         if (e == MONO_GC_EVENT_START) {
415 #ifndef DISABLE_PERFCOUNTERS
416                 if (mono_perfcounters)
417                         mono_perfcounters->gc_collections0++;
418 #endif
419                 gc_stats.major_gc_count ++;
420                 gc_start_time = mono_100ns_ticks ();
421         } else if (e == MONO_GC_EVENT_END) {
422 #ifndef DISABLE_PERFCOUNTERS
423                 if (mono_perfcounters) {
424                         guint64 heap_size = GC_get_heap_size ();
425                         guint64 used_size = heap_size - GC_get_free_bytes ();
426                         mono_perfcounters->gc_total_bytes = used_size;
427                         mono_perfcounters->gc_committed_bytes = heap_size;
428                         mono_perfcounters->gc_reserved_bytes = heap_size;
429                         mono_perfcounters->gc_gen0size = heap_size;
430                 }
431 #endif
432                 gc_stats.major_gc_time_usecs += (mono_100ns_ticks () - gc_start_time) / 10;
433                 mono_trace_message (MONO_TRACE_GC, "gc took %d usecs", (mono_100ns_ticks () - gc_start_time) / 10);
434         }
435         mono_profiler_gc_event (e, 0);
436 }
437  
438 static void
439 on_gc_heap_resize (size_t new_size)
440 {
441         guint64 heap_size = GC_get_heap_size ();
442 #ifndef DISABLE_PERFCOUNTERS
443         if (mono_perfcounters) {
444                 mono_perfcounters->gc_committed_bytes = heap_size;
445                 mono_perfcounters->gc_reserved_bytes = heap_size;
446                 mono_perfcounters->gc_gen0size = heap_size;
447         }
448 #endif
449         mono_profiler_gc_heap_resize (new_size);
450 }
451
452 void
453 mono_gc_enable_events (void)
454 {
455         GC_notify_event = on_gc_notification;
456         GC_on_heap_resize = on_gc_heap_resize;
457 }
458
459 #else
460
461 void
462 mono_gc_enable_events (void)
463 {
464 }
465
466 #endif
467
468 int
469 mono_gc_register_root (char *start, size_t size, void *descr)
470 {
471         /* for some strange reason, they want one extra byte on the end */
472         GC_add_roots (start, start + size + 1);
473
474         return TRUE;
475 }
476
477 void
478 mono_gc_deregister_root (char* addr)
479 {
480 #ifndef HOST_WIN32
481         /* FIXME: libgc doesn't define this work win32 for some reason */
482         /* FIXME: No size info */
483         GC_remove_roots (addr, addr + sizeof (gpointer) + 1);
484 #endif
485 }
486
487 void
488 mono_gc_weak_link_add (void **link_addr, MonoObject *obj, gboolean track)
489 {
490         /* libgc requires that we use HIDE_POINTER... */
491         *link_addr = (void*)HIDE_POINTER (obj);
492         GC_GENERAL_REGISTER_DISAPPEARING_LINK (link_addr, obj);
493 }
494
495 void
496 mono_gc_weak_link_remove (void **link_addr)
497 {
498         GC_unregister_disappearing_link (link_addr);
499         *link_addr = NULL;
500 }
501
502 static gpointer
503 reveal_link (gpointer link_addr)
504 {
505         void **link_a = link_addr;
506         return REVEAL_POINTER (*link_a);
507 }
508
509 MonoObject*
510 mono_gc_weak_link_get (void **link_addr)
511 {
512         MonoObject *obj = GC_call_with_alloc_lock (reveal_link, link_addr);
513         if (obj == (MonoObject *) -1)
514                 return NULL;
515         return obj;
516 }
517
518 void*
519 mono_gc_make_descr_for_string (gsize *bitmap, int numbits)
520 {
521         return mono_gc_make_descr_from_bitmap (bitmap, numbits);
522 }
523
524 void*
525 mono_gc_make_descr_for_object (gsize *bitmap, int numbits, size_t obj_size)
526 {
527         return mono_gc_make_descr_from_bitmap (bitmap, numbits);
528 }
529
530 void*
531 mono_gc_make_descr_for_array (int vector, gsize *elem_bitmap, int numbits, size_t elem_size)
532 {
533         /* libgc has no usable support for arrays... */
534         return GC_NO_DESCRIPTOR;
535 }
536
537 void*
538 mono_gc_make_descr_from_bitmap (gsize *bitmap, int numbits)
539 {
540 #ifdef HAVE_GC_GCJ_MALLOC
541         /* It seems there are issues when the bitmap doesn't fit: play it safe */
542         if (numbits >= 30)
543                 return GC_NO_DESCRIPTOR;
544         else
545                 return (gpointer)GC_make_descriptor ((GC_bitmap)bitmap, numbits);
546 #else
547         return NULL;
548 #endif
549 }
550
551 void*
552 mono_gc_make_root_descr_all_refs (int numbits)
553 {
554         return NULL;
555 }
556
557 void*
558 mono_gc_alloc_fixed (size_t size, void *descr)
559 {
560         /* To help track down typed allocation bugs */
561         /*
562         static int count;
563         count ++;
564         if (count == atoi (getenv ("COUNT2")))
565                 printf ("HIT!\n");
566         if (count > atoi (getenv ("COUNT2")))
567                 return GC_MALLOC (size);
568         */
569
570         if (descr)
571                 return GC_MALLOC_EXPLICITLY_TYPED (size, (GC_descr)descr);
572         else
573                 return GC_MALLOC (size);
574 }
575
576 void
577 mono_gc_free_fixed (void* addr)
578 {
579 }
580
581 int
582 mono_gc_invoke_finalizers (void)
583 {
584         /* There is a bug in GC_invoke_finalizer () in versions <= 6.2alpha4:
585          * the 'mem_freed' variable is not initialized when there are no
586          * objects to finalize, which leads to strange behavior later on.
587          * The check is necessary to work around that bug.
588          */
589         if (GC_should_invoke_finalizers ())
590                 return GC_invoke_finalizers ();
591         return 0;
592 }
593
594 gboolean
595 mono_gc_pending_finalizers (void)
596 {
597         return GC_should_invoke_finalizers ();
598 }
599
600 /*
601  * LOCKING: Assumes the domain_finalizers lock is held.
602  */
603 static void
604 add_weak_track_handle_internal (MonoDomain *domain, MonoObject *obj, guint32 gchandle)
605 {
606         GSList *refs;
607
608         if (!domain->track_resurrection_objects_hash)
609                 domain->track_resurrection_objects_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
610
611         refs = g_hash_table_lookup (domain->track_resurrection_objects_hash, obj);
612         refs = g_slist_prepend (refs, GUINT_TO_POINTER (gchandle));
613         g_hash_table_insert (domain->track_resurrection_objects_hash, obj, refs);
614 }
615
616 void
617 mono_gc_add_weak_track_handle (MonoObject *obj, guint32 handle)
618 {
619         MonoDomain *domain;
620
621         if (!obj)
622                 return;
623
624         domain = mono_object_get_domain (obj);
625
626         mono_domain_finalizers_lock (domain);
627
628         add_weak_track_handle_internal (domain, obj, handle);
629
630         g_hash_table_insert (domain->track_resurrection_handles_hash, GUINT_TO_POINTER (handle), obj);
631
632         mono_domain_finalizers_unlock (domain);
633 }
634
635 /*
636  * LOCKING: Assumes the domain_finalizers lock is held.
637  */
638 static void
639 remove_weak_track_handle_internal (MonoDomain *domain, MonoObject *obj, guint32 gchandle)
640 {
641         GSList *refs;
642
643         if (!domain->track_resurrection_objects_hash)
644                 return;
645
646         refs = g_hash_table_lookup (domain->track_resurrection_objects_hash, obj);
647         refs = g_slist_remove (refs, GUINT_TO_POINTER (gchandle));
648         g_hash_table_insert (domain->track_resurrection_objects_hash, obj, refs);
649 }
650
651 void
652 mono_gc_change_weak_track_handle (MonoObject *old_obj, MonoObject *obj, guint32 gchandle)
653 {
654         MonoDomain *domain = mono_domain_get ();
655
656         mono_domain_finalizers_lock (domain);
657
658         if (old_obj)
659                 remove_weak_track_handle_internal (domain, old_obj, gchandle);
660         if (obj)
661                 add_weak_track_handle_internal (domain, obj, gchandle);
662
663         mono_domain_finalizers_unlock (domain);
664 }
665
666 void
667 mono_gc_remove_weak_track_handle (guint32 gchandle)
668 {
669         MonoDomain *domain = mono_domain_get ();
670         MonoObject *obj;
671
672         /* Clean our entries in the two hashes in MonoDomain */
673
674         mono_domain_finalizers_lock (domain);
675
676         /* Get the original object this handle pointed to */
677         obj = g_hash_table_lookup (domain->track_resurrection_handles_hash, GUINT_TO_POINTER (gchandle));
678         if (obj) {
679                 g_hash_table_remove (domain->track_resurrection_handles_hash, GUINT_TO_POINTER (gchandle));
680
681                 remove_weak_track_handle_internal (domain, obj, gchandle);
682         }
683
684         mono_domain_finalizers_unlock (domain);
685 }
686
687 GSList*
688 mono_gc_remove_weak_track_object (MonoDomain *domain, MonoObject *obj)
689 {
690         GSList *refs = NULL;
691
692         if (domain->track_resurrection_objects_hash) {
693                 refs = g_hash_table_lookup (domain->track_resurrection_objects_hash, obj);
694
695                 if (refs)
696                         /*
697                          * Since we don't run finalizers again for resurrected objects,
698                          * no need to keep these around.
699                          */
700                         g_hash_table_remove (domain->track_resurrection_objects_hash, obj);
701         }
702
703         return refs;
704 }
705
706 void
707 mono_gc_wbarrier_set_field (MonoObject *obj, gpointer field_ptr, MonoObject* value)
708 {
709         *(void**)field_ptr = value;
710 }
711
712 void
713 mono_gc_wbarrier_set_arrayref (MonoArray *arr, gpointer slot_ptr, MonoObject* value)
714 {
715         *(void**)slot_ptr = value;
716 }
717
718 void
719 mono_gc_wbarrier_arrayref_copy (gpointer dest_ptr, gpointer src_ptr, int count)
720 {
721         mono_gc_memmove (dest_ptr, src_ptr, count * sizeof (gpointer));
722 }
723
724 void
725 mono_gc_wbarrier_generic_store (gpointer ptr, MonoObject* value)
726 {
727         *(void**)ptr = value;
728 }
729
730 void
731 mono_gc_wbarrier_generic_nostore (gpointer ptr)
732 {
733 }
734
735 void
736 mono_gc_wbarrier_value_copy (gpointer dest, gpointer src, int count, MonoClass *klass)
737 {
738         mono_gc_memmove (dest, src, count * mono_class_value_size (klass, NULL));
739 }
740
741 void
742 mono_gc_wbarrier_object_copy (MonoObject* obj, MonoObject *src)
743 {
744         /* do not copy the sync state */
745         mono_gc_memmove ((char*)obj + sizeof (MonoObject), (char*)src + sizeof (MonoObject),
746                         mono_object_class (obj)->instance_size - sizeof (MonoObject));
747 }
748
749 void
750 mono_gc_clear_domain (MonoDomain *domain)
751 {
752 }
753
754 int
755 mono_gc_get_suspend_signal (void)
756 {
757 #ifdef USE_INCLUDED_GC
758         return GC_get_suspend_signal ();
759 #else
760         return -1;
761 #endif
762 }
763
764 #if defined(USE_INCLUDED_LIBGC) && defined(USE_COMPILER_TLS) && defined(__linux__) && (defined(__i386__) || defined(__x86_64__))
765 extern __thread MONO_TLS_FAST void* GC_thread_tls;
766 #include "metadata-internals.h"
767
768 static int
769 shift_amount (int v)
770 {
771         int i = 0;
772         while (!(v & (1 << i)))
773                 i++;
774         return i;
775 }
776
777 enum {
778         ATYPE_FREEPTR,
779         ATYPE_FREEPTR_FOR_BOX,
780         ATYPE_NORMAL,
781         ATYPE_GCJ,
782         ATYPE_STRING,
783         ATYPE_NUM
784 };
785
786 static MonoMethod*
787 create_allocator (int atype, int offset)
788 {
789         int index_var, bytes_var, my_fl_var, my_entry_var;
790         guint32 no_freelist_branch, not_small_enough_branch = 0;
791         guint32 size_overflow_branch = 0;
792         MonoMethodBuilder *mb;
793         MonoMethod *res;
794         MonoMethodSignature *csig;
795         AllocatorWrapperInfo *info;
796
797         if (atype == ATYPE_STRING) {
798                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
799                 csig->ret = &mono_defaults.string_class->byval_arg;
800                 csig->params [0] = &mono_defaults.int_class->byval_arg;
801                 csig->params [1] = &mono_defaults.int32_class->byval_arg;
802         } else {
803                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
804                 csig->ret = &mono_defaults.object_class->byval_arg;
805                 csig->params [0] = &mono_defaults.int_class->byval_arg;
806         }
807
808         mb = mono_mb_new (mono_defaults.object_class, "Alloc", MONO_WRAPPER_ALLOC);
809         bytes_var = mono_mb_add_local (mb, &mono_defaults.int32_class->byval_arg);
810         if (atype == ATYPE_STRING) {
811                 /* a string alloator method takes the args: (vtable, len) */
812                 /* bytes = (sizeof (MonoString) + ((len + 1) * 2)); */
813                 mono_mb_emit_ldarg (mb, 1);
814                 mono_mb_emit_icon (mb, 1);
815                 mono_mb_emit_byte (mb, MONO_CEE_ADD);
816                 mono_mb_emit_icon (mb, 1);
817                 mono_mb_emit_byte (mb, MONO_CEE_SHL);
818                 // sizeof (MonoString) might include padding
819                 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoString, chars));
820                 mono_mb_emit_byte (mb, MONO_CEE_ADD);
821                 mono_mb_emit_stloc (mb, bytes_var);
822         } else {
823                 /* bytes = vtable->klass->instance_size */
824                 mono_mb_emit_ldarg (mb, 0);
825                 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoVTable, klass));
826                 mono_mb_emit_byte (mb, MONO_CEE_ADD);
827                 mono_mb_emit_byte (mb, MONO_CEE_LDIND_I);
828                 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoClass, instance_size));
829                 mono_mb_emit_byte (mb, MONO_CEE_ADD);
830                 /* FIXME: assert instance_size stays a 4 byte integer */
831                 mono_mb_emit_byte (mb, MONO_CEE_LDIND_U4);
832                 mono_mb_emit_stloc (mb, bytes_var);
833         }
834
835         /* this is needed for strings/arrays only as the other big types are never allocated with this method */
836         if (atype == ATYPE_STRING) {
837                 /* check for size */
838                 /* if (!SMALL_ENOUGH (bytes)) jump slow_path;*/
839                 mono_mb_emit_ldloc (mb, bytes_var);
840                 mono_mb_emit_icon (mb, (NFREELISTS-1) * GRANULARITY);
841                 not_small_enough_branch = mono_mb_emit_short_branch (mb, MONO_CEE_BGT_UN_S);
842                 /* check for overflow */
843                 mono_mb_emit_ldloc (mb, bytes_var);
844                 mono_mb_emit_icon (mb, sizeof (MonoString));
845                 size_overflow_branch = mono_mb_emit_short_branch (mb, MONO_CEE_BLE_UN_S);
846         }
847
848         /* int index = INDEX_FROM_BYTES(bytes); */
849         index_var = mono_mb_add_local (mb, &mono_defaults.int32_class->byval_arg);
850         
851         mono_mb_emit_ldloc (mb, bytes_var);
852         mono_mb_emit_icon (mb, GRANULARITY - 1);
853         mono_mb_emit_byte (mb, MONO_CEE_ADD);
854         mono_mb_emit_icon (mb, shift_amount (GRANULARITY));
855         mono_mb_emit_byte (mb, MONO_CEE_SHR_UN);
856         mono_mb_emit_icon (mb, shift_amount (sizeof (gpointer)));
857         mono_mb_emit_byte (mb, MONO_CEE_SHL);
858         /* index var is already adjusted into bytes */
859         mono_mb_emit_stloc (mb, index_var);
860
861         my_fl_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
862         my_entry_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
863         /* my_fl = ((GC_thread)tsd) -> ptrfree_freelists + index; */
864         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
865         mono_mb_emit_byte (mb, 0x0D); /* CEE_MONO_TLS */
866         mono_mb_emit_i4 (mb, offset);
867         if (atype == ATYPE_FREEPTR || atype == ATYPE_FREEPTR_FOR_BOX || atype == ATYPE_STRING)
868                 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (struct GC_Thread_Rep, ptrfree_freelists));
869         else if (atype == ATYPE_NORMAL)
870                 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (struct GC_Thread_Rep, normal_freelists));
871         else if (atype == ATYPE_GCJ)
872                 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (struct GC_Thread_Rep, gcj_freelists));
873         else
874                 g_assert_not_reached ();
875         mono_mb_emit_byte (mb, MONO_CEE_ADD);
876         mono_mb_emit_ldloc (mb, index_var);
877         mono_mb_emit_byte (mb, MONO_CEE_ADD);
878         mono_mb_emit_stloc (mb, my_fl_var);
879
880         /* my_entry = *my_fl; */
881         mono_mb_emit_ldloc (mb, my_fl_var);
882         mono_mb_emit_byte (mb, MONO_CEE_LDIND_I);
883         mono_mb_emit_stloc (mb, my_entry_var);
884
885         /* if (EXPECT((word)my_entry >= HBLKSIZE, 1)) { */
886         mono_mb_emit_ldloc (mb, my_entry_var);
887         mono_mb_emit_icon (mb, HBLKSIZE);
888         no_freelist_branch = mono_mb_emit_short_branch (mb, MONO_CEE_BLT_UN_S);
889
890         /* ptr_t next = obj_link(my_entry); *my_fl = next; */
891         mono_mb_emit_ldloc (mb, my_fl_var);
892         mono_mb_emit_ldloc (mb, my_entry_var);
893         mono_mb_emit_byte (mb, MONO_CEE_LDIND_I);
894         mono_mb_emit_byte (mb, MONO_CEE_STIND_I);
895
896         /* set the vtable and clear the words in the object */
897         mono_mb_emit_ldloc (mb, my_entry_var);
898         mono_mb_emit_ldarg (mb, 0);
899         mono_mb_emit_byte (mb, MONO_CEE_STIND_I);
900
901         if (atype == ATYPE_FREEPTR) {
902                 int start_var, end_var, start_loop;
903                 /* end = my_entry + bytes; start = my_entry + sizeof (gpointer);
904                  */
905                 start_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
906                 end_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
907                 mono_mb_emit_ldloc (mb, my_entry_var);
908                 mono_mb_emit_ldloc (mb, bytes_var);
909                 mono_mb_emit_byte (mb, MONO_CEE_ADD);
910                 mono_mb_emit_stloc (mb, end_var);
911                 mono_mb_emit_ldloc (mb, my_entry_var);
912                 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoObject, synchronisation));
913                 mono_mb_emit_byte (mb, MONO_CEE_ADD);
914                 mono_mb_emit_stloc (mb, start_var);
915                 /*
916                  * do {
917                  *      *start++ = NULL;
918                  * } while (start < end);
919                  */
920                 start_loop = mono_mb_get_label (mb);
921                 mono_mb_emit_ldloc (mb, start_var);
922                 mono_mb_emit_icon (mb, 0);
923                 mono_mb_emit_byte (mb, MONO_CEE_STIND_I);
924                 mono_mb_emit_ldloc (mb, start_var);
925                 mono_mb_emit_icon (mb, sizeof (gpointer));
926                 mono_mb_emit_byte (mb, MONO_CEE_ADD);
927                 mono_mb_emit_stloc (mb, start_var);
928
929                 mono_mb_emit_ldloc (mb, start_var);
930                 mono_mb_emit_ldloc (mb, end_var);
931                 mono_mb_emit_byte (mb, MONO_CEE_BLT_UN_S);
932                 mono_mb_emit_byte (mb, start_loop - (mono_mb_get_label (mb) + 1));
933         } else if (atype == ATYPE_FREEPTR_FOR_BOX || atype == ATYPE_STRING) {
934                 /* need to clear just the sync pointer */
935                 mono_mb_emit_ldloc (mb, my_entry_var);
936                 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoObject, synchronisation));
937                 mono_mb_emit_byte (mb, MONO_CEE_ADD);
938                 mono_mb_emit_icon (mb, 0);
939                 mono_mb_emit_byte (mb, MONO_CEE_STIND_I);
940         }
941
942         if (atype == ATYPE_STRING) {
943                 /* need to set length and clear the last char */
944                 /* s->length = len; */
945                 mono_mb_emit_ldloc (mb, my_entry_var);
946                 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoString, length));
947                 mono_mb_emit_byte (mb, MONO_CEE_ADD);
948                 mono_mb_emit_ldarg (mb, 1);
949                 mono_mb_emit_byte (mb, MONO_CEE_STIND_I4);
950                 /* s->chars [len] = 0; */
951                 mono_mb_emit_ldloc (mb, my_entry_var);
952                 mono_mb_emit_ldloc (mb, bytes_var);
953                 mono_mb_emit_icon (mb, 2);
954                 mono_mb_emit_byte (mb, MONO_CEE_SUB);
955                 mono_mb_emit_byte (mb, MONO_CEE_ADD);
956                 mono_mb_emit_icon (mb, 0);
957                 mono_mb_emit_byte (mb, MONO_CEE_STIND_I2);
958         }
959
960         /* return my_entry; */
961         mono_mb_emit_ldloc (mb, my_entry_var);
962         mono_mb_emit_byte (mb, MONO_CEE_RET);
963         
964         mono_mb_patch_short_branch (mb, no_freelist_branch);
965         if (not_small_enough_branch > 0)
966                 mono_mb_patch_short_branch (mb, not_small_enough_branch);
967         if (size_overflow_branch > 0)
968                 mono_mb_patch_short_branch (mb, size_overflow_branch);
969         /* the slow path: we just call back into the runtime */
970         if (atype == ATYPE_STRING) {
971                 mono_mb_emit_ldarg (mb, 1);
972                 mono_mb_emit_icall (mb, mono_string_alloc);
973         } else {
974                 mono_mb_emit_ldarg (mb, 0);
975                 mono_mb_emit_icall (mb, mono_object_new_specific);
976         }
977
978         mono_mb_emit_byte (mb, MONO_CEE_RET);
979
980         res = mono_mb_create_method (mb, csig, 8);
981         mono_mb_free (mb);
982         mono_method_get_header (res)->init_locals = FALSE;
983
984         info = mono_image_alloc0 (mono_defaults.corlib, sizeof (AllocatorWrapperInfo));
985         info->gc_name = "boehm";
986         info->alloc_type = atype;
987         mono_marshal_set_wrapper_info (res, info);
988
989         return res;
990 }
991
992 static MonoMethod* alloc_method_cache [ATYPE_NUM];
993
994 static G_GNUC_UNUSED gboolean
995 mono_gc_is_critical_method (MonoMethod *method)
996 {
997         int i;
998
999         for (i = 0; i < ATYPE_NUM; ++i)
1000                 if (method == alloc_method_cache [i])
1001                         return TRUE;
1002
1003         return FALSE;
1004 }
1005
1006 /*
1007  * If possible, generate a managed method that can quickly allocate objects in class
1008  * @klass. The method will typically have an thread-local inline allocation sequence.
1009  * The signature of the called method is:
1010  *      object allocate (MonoVTable *vtable)
1011  * Some of the logic here is similar to mono_class_get_allocation_ftn () i object.c,
1012  * keep in sync.
1013  * The thread local alloc logic is taken from libgc/pthread_support.c.
1014  */
1015
1016 MonoMethod*
1017 mono_gc_get_managed_allocator (MonoVTable *vtable, gboolean for_box)
1018 {
1019         int offset = -1;
1020         int atype;
1021         MonoClass *klass = vtable->klass;
1022         MONO_THREAD_VAR_OFFSET (GC_thread_tls, offset);
1023
1024         /*g_print ("thread tls: %d\n", offset);*/
1025         if (offset == -1)
1026                 return NULL;
1027         if (!SMALL_ENOUGH (klass->instance_size))
1028                 return NULL;
1029         if (mono_class_has_finalizer (klass) || klass->marshalbyref || (mono_profiler_get_events () & MONO_PROFILE_ALLOCATIONS))
1030                 return NULL;
1031         if (klass->rank)
1032                 return NULL;
1033         if (klass->byval_arg.type == MONO_TYPE_STRING) {
1034                 atype = ATYPE_STRING;
1035         } else if (!klass->has_references) {
1036                 if (for_box)
1037                         atype = ATYPE_FREEPTR_FOR_BOX;
1038                 else
1039                         atype = ATYPE_FREEPTR;
1040         } else {
1041                 return NULL;
1042                 /*
1043                  * disabled because we currently do a runtime choice anyway, to
1044                  * deal with multiple appdomains.
1045                 if (vtable->gc_descr != GC_NO_DESCRIPTOR)
1046                         atype = ATYPE_GCJ;
1047                 else
1048                         atype = ATYPE_NORMAL;
1049                 */
1050         }
1051         return mono_gc_get_managed_allocator_by_type (atype);
1052 }
1053
1054 MonoMethod*
1055 mono_gc_get_managed_array_allocator (MonoVTable *vtable, int rank)
1056 {
1057         return NULL;
1058 }
1059
1060 /**
1061  * mono_gc_get_managed_allocator_by_type:
1062  *
1063  *   Return a managed allocator method corresponding to allocator type ATYPE.
1064  */
1065 MonoMethod*
1066 mono_gc_get_managed_allocator_by_type (int atype)
1067 {
1068         int offset = -1;
1069         MonoMethod *res;
1070         MONO_THREAD_VAR_OFFSET (GC_thread_tls, offset);
1071
1072         mono_loader_lock ();
1073         res = alloc_method_cache [atype];
1074         if (!res)
1075                 res = alloc_method_cache [atype] = create_allocator (atype, offset);
1076         mono_loader_unlock ();
1077         return res;
1078 }
1079
1080 guint32
1081 mono_gc_get_managed_allocator_types (void)
1082 {
1083         return ATYPE_NUM;
1084 }
1085
1086 MonoMethod*
1087 mono_gc_get_write_barrier (void)
1088 {
1089         g_assert_not_reached ();
1090         return NULL;
1091 }
1092
1093 #else
1094
1095 static G_GNUC_UNUSED gboolean
1096 mono_gc_is_critical_method (MonoMethod *method)
1097 {
1098         return FALSE;
1099 }
1100
1101 MonoMethod*
1102 mono_gc_get_managed_allocator (MonoVTable *vtable, gboolean for_box)
1103 {
1104         return NULL;
1105 }
1106
1107 MonoMethod*
1108 mono_gc_get_managed_array_allocator (MonoVTable *vtable, int rank)
1109 {
1110         return NULL;
1111 }
1112
1113 MonoMethod*
1114 mono_gc_get_managed_allocator_by_type (int atype)
1115 {
1116         return NULL;
1117 }
1118
1119 guint32
1120 mono_gc_get_managed_allocator_types (void)
1121 {
1122         return 0;
1123 }
1124
1125 MonoMethod*
1126 mono_gc_get_write_barrier (void)
1127 {
1128         g_assert_not_reached ();
1129         return NULL;
1130 }
1131
1132 #endif
1133
1134 const char *
1135 mono_gc_get_gc_name (void)
1136 {
1137         return "boehm";
1138 }
1139
1140 void*
1141 mono_gc_invoke_with_gc_lock (MonoGCLockedCallbackFunc func, void *data)
1142 {
1143         return GC_call_with_alloc_lock (func, data);
1144 }
1145
1146 char*
1147 mono_gc_get_description (void)
1148 {
1149         return g_strdup (DEFAULT_GC_NAME);
1150 }
1151
1152 void
1153 mono_gc_set_desktop_mode (void)
1154 {
1155         GC_dont_expand = 1;
1156 }
1157
1158 gboolean
1159 mono_gc_is_moving (void)
1160 {
1161         return FALSE;
1162 }
1163
1164 gboolean
1165 mono_gc_is_disabled (void)
1166 {
1167         if (GC_dont_gc || g_getenv ("GC_DONT_GC"))
1168                 return TRUE;
1169         else
1170                 return FALSE;
1171 }
1172
1173 void
1174 mono_gc_wbarrier_value_copy_bitmap (gpointer _dest, gpointer _src, int size, unsigned bitmap)
1175 {
1176         g_assert_not_reached ();
1177 }
1178
1179
1180 guint8*
1181 mono_gc_get_card_table (int *shift_bits, gpointer *card_mask)
1182 {
1183         g_assert_not_reached ();
1184         return NULL;
1185 }
1186
1187 void*
1188 mono_gc_get_nursery (int *shift_bits, size_t *size)
1189 {
1190         return NULL;
1191 }
1192
1193 void
1194 mono_gc_set_current_thread_appdomain (MonoDomain *domain)
1195 {
1196 }
1197
1198 gboolean
1199 mono_gc_precise_stack_mark_enabled (void)
1200 {
1201         return FALSE;
1202 }
1203
1204 FILE *
1205 mono_gc_get_logfile (void)
1206 {
1207         return NULL;
1208 }
1209
1210 void
1211 mono_gc_conservatively_scan_area (void *start, void *end)
1212 {
1213         g_assert_not_reached ();
1214 }
1215
1216 void *
1217 mono_gc_scan_object (void *obj)
1218 {
1219         g_assert_not_reached ();
1220         return NULL;
1221 }
1222
1223 gsize*
1224 mono_gc_get_bitmap_for_descr (void *descr, int *numbits)
1225 {
1226         g_assert_not_reached ();
1227         return NULL;
1228 }
1229
1230 void
1231 mono_gc_set_gc_callbacks (MonoGCCallbacks *callbacks)
1232 {
1233 }
1234
1235 void
1236 mono_gc_set_stack_end (void *stack_end)
1237 {
1238 }
1239
1240 void mono_gc_set_skip_thread (gboolean value)
1241 {
1242 }
1243
1244 /*
1245  * These will call the redefined versions in libgc.
1246  */
1247
1248 #ifndef HOST_WIN32
1249
1250 int
1251 mono_gc_pthread_create (pthread_t *new_thread, const pthread_attr_t *attr, void *(*start_routine)(void *), void *arg)
1252 {
1253         return pthread_create (new_thread, attr, start_routine, arg);
1254 }
1255
1256 int
1257 mono_gc_pthread_join (pthread_t thread, void **retval)
1258 {
1259         return pthread_join (thread, retval);
1260 }
1261
1262 int
1263 mono_gc_pthread_detach (pthread_t thread)
1264 {
1265         return pthread_detach (thread);
1266 }
1267
1268 void
1269 mono_gc_pthread_exit (void *retval)
1270 {
1271         pthread_exit (retval);
1272 }
1273
1274 #endif
1275
1276 #ifdef HOST_WIN32
1277 BOOL APIENTRY mono_gc_dllmain (HMODULE module_handle, DWORD reason, LPVOID reserved)
1278 {
1279 #ifdef USE_INCLUDED_LIBGC
1280         return GC_DllMain (module_handle, reason, reserved);
1281 #else
1282         return TRUE;
1283 #endif
1284 }
1285 #endif
1286
1287 guint
1288 mono_gc_get_vtable_bits (MonoClass *class)
1289 {
1290         return 0;
1291 }
1292
1293 /*
1294  * mono_gc_register_altstack:
1295  *
1296  *   Register the dimensions of the normal stack and altstack with the collector.
1297  * Currently, STACK/STACK_SIZE is only used when the thread is suspended while it is on an altstack.
1298  */
1299 void
1300 mono_gc_register_altstack (gpointer stack, gint32 stack_size, gpointer altstack, gint32 altstack_size)
1301 {
1302 #ifdef USE_INCLUDED_LIBGC
1303         GC_register_altstack (stack, stack_size, altstack, altstack_size);
1304 #endif
1305 }
1306
1307 int
1308 mono_gc_get_los_limit (void)
1309 {
1310         return G_MAXINT;
1311 }
1312
1313 gboolean
1314 mono_gc_user_markers_supported (void)
1315 {
1316         return FALSE;
1317 }
1318
1319 void *
1320 mono_gc_make_root_descr_user (MonoGCRootMarkFunc marker)
1321 {
1322         g_assert_not_reached ();
1323         return NULL;
1324 }
1325
1326 #endif /* no Boehm GC */