Merge pull request #472 from MelanieT/spmanager_fix
[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 #ifndef DISABLE_PERFCOUNTERS
210         mono_perfcounters->gc_induced++;
211 #endif
212         GC_gcollect ();
213 }
214
215 /**
216  * mono_gc_max_generation:
217  *
218  * Get the maximum generation number used by the current garbage
219  * collector. The value will be 0 for the Boehm collector, 1 or more
220  * for the generational collectors.
221  *
222  * Returns: the maximum generation number.
223  */
224 int
225 mono_gc_max_generation (void)
226 {
227         return 0;
228 }
229
230 /**
231  * mono_gc_get_generation:
232  * @object: a managed object
233  *
234  * Get the garbage collector's generation that @object belongs to.
235  * Use this has a hint only.
236  *
237  * Returns: a garbage collector generation number
238  */
239 int
240 mono_gc_get_generation  (MonoObject *object)
241 {
242         return 0;
243 }
244
245 /**
246  * mono_gc_collection_count:
247  * @generation: a GC generation number
248  *
249  * Get how many times a garbage collection has been performed
250  * for the given @generation number.
251  *
252  * Returns: the number of garbage collections
253  */
254 int
255 mono_gc_collection_count (int generation)
256 {
257         return GC_gc_no;
258 }
259
260 /**
261  * mono_gc_add_memory_pressure:
262  * @value: amount of bytes
263  *
264  * Adjust the garbage collector's view of how many bytes of memory
265  * are indirectly referenced by managed objects (for example unmanaged
266  * memory holding image or other binary data).
267  * This is a hint only to the garbage collector algorithm.
268  * Note that negative amounts of @value will decrease the memory
269  * pressure.
270  */
271 void
272 mono_gc_add_memory_pressure (gint64 value)
273 {
274 }
275
276 /**
277  * mono_gc_get_used_size:
278  *
279  * Get the approximate amount of memory used by managed objects.
280  *
281  * Returns: the amount of memory used in bytes
282  */
283 int64_t
284 mono_gc_get_used_size (void)
285 {
286         return GC_get_heap_size () - GC_get_free_bytes ();
287 }
288
289 /**
290  * mono_gc_get_heap_size:
291  *
292  * Get the amount of memory used by the garbage collector.
293  *
294  * Returns: the size of the heap in bytes
295  */
296 int64_t
297 mono_gc_get_heap_size (void)
298 {
299         return GC_get_heap_size ();
300 }
301
302 void
303 mono_gc_disable (void)
304 {
305 #ifdef HAVE_GC_ENABLE
306         GC_disable ();
307 #else
308         g_assert_not_reached ();
309 #endif
310 }
311
312 void
313 mono_gc_enable (void)
314 {
315 #ifdef HAVE_GC_ENABLE
316         GC_enable ();
317 #else
318         g_assert_not_reached ();
319 #endif
320 }
321
322 gboolean
323 mono_gc_is_gc_thread (void)
324 {
325 #if GC_VERSION_MAJOR >= 7
326         return TRUE;
327 #elif defined(USE_INCLUDED_LIBGC)
328         return GC_thread_is_registered ();
329 #else
330         return TRUE;
331 #endif
332 }
333
334 extern int GC_thread_register_foreign (void *base_addr);
335
336 gboolean
337 mono_gc_register_thread (void *baseptr)
338 {
339         return mono_thread_info_attach (baseptr) != NULL;
340 }
341
342 static void*
343 boehm_thread_register (MonoThreadInfo* info, void *baseptr)
344 {
345 #if GC_VERSION_MAJOR >= 7
346         struct GC_stack_base sb;
347         int res;
348
349         res = GC_get_stack_base (&sb);
350         if (res != GC_SUCCESS) {
351                 sb.mem_base = baseptr;
352 #ifdef __ia64__
353                 /* Can't determine the register stack bounds */
354                 g_error ("mono_gc_register_thread failed ().\n");
355 #endif
356         }
357         res = GC_register_my_thread (&sb);
358         if ((res != GC_SUCCESS) && (res != GC_DUPLICATE)) {
359                 g_warning ("GC_register_my_thread () failed.\n");
360                 return NULL;
361         }
362         return info;
363 #else
364         if (mono_gc_is_gc_thread())
365                 return info;
366 #if defined(USE_INCLUDED_LIBGC) && !defined(HOST_WIN32)
367         return GC_thread_register_foreign (baseptr) ? info : NULL;
368 #else
369         return NULL;
370 #endif
371 #endif
372 }
373
374 gboolean
375 mono_object_is_alive (MonoObject* o)
376 {
377 #ifdef USE_INCLUDED_LIBGC
378         return GC_is_marked ((gpointer)o);
379 #else
380         return TRUE;
381 #endif
382 }
383
384 int
385 mono_gc_walk_heap (int flags, MonoGCReferences callback, void *data)
386 {
387         return 1;
388 }
389
390 #ifdef USE_INCLUDED_LIBGC
391
392 static gint64 gc_start_time;
393
394 static void
395 on_gc_notification (GCEventType event)
396 {
397         MonoGCEvent e = (MonoGCEvent)event;
398
399         switch (e) {
400         case MONO_GC_EVENT_PRE_STOP_WORLD:
401                 MONO_GC_WORLD_STOP_BEGIN ();
402                 mono_thread_info_suspend_lock ();
403                 break;
404
405         case MONO_GC_EVENT_POST_STOP_WORLD:
406                 MONO_GC_WORLD_STOP_END ();
407                 break;
408
409         case MONO_GC_EVENT_PRE_START_WORLD:
410                 MONO_GC_WORLD_RESTART_BEGIN (1);
411                 break;
412
413         case MONO_GC_EVENT_POST_START_WORLD:
414                 MONO_GC_WORLD_RESTART_END (1);
415                 mono_thread_info_suspend_unlock ();
416                 break;
417
418         case MONO_GC_EVENT_START:
419                 MONO_GC_BEGIN (1);
420 #ifndef DISABLE_PERFCOUNTERS
421                 if (mono_perfcounters)
422                         mono_perfcounters->gc_collections0++;
423 #endif
424                 gc_stats.major_gc_count ++;
425                 gc_start_time = mono_100ns_ticks ();
426                 break;
427
428         case MONO_GC_EVENT_END:
429                 MONO_GC_END (1);
430 #if defined(ENABLE_DTRACE) && defined(__sun__)
431                 /* This works around a dtrace -G problem on Solaris.
432                    Limit its actual use to when the probe is enabled. */
433                 if (MONO_GC_END_ENABLED ())
434                         sleep(0);
435 #endif
436
437 #ifndef DISABLE_PERFCOUNTERS
438                 if (mono_perfcounters) {
439                         guint64 heap_size = GC_get_heap_size ();
440                         guint64 used_size = heap_size - GC_get_free_bytes ();
441                         mono_perfcounters->gc_total_bytes = used_size;
442                         mono_perfcounters->gc_committed_bytes = heap_size;
443                         mono_perfcounters->gc_reserved_bytes = heap_size;
444                         mono_perfcounters->gc_gen0size = heap_size;
445                 }
446 #endif
447                 gc_stats.major_gc_time_usecs += (mono_100ns_ticks () - gc_start_time) / 10;
448                 mono_trace_message (MONO_TRACE_GC, "gc took %d usecs", (mono_100ns_ticks () - gc_start_time) / 10);
449                 break;
450         }
451
452         mono_profiler_gc_event (e, 0);
453 }
454  
455 static void
456 on_gc_heap_resize (size_t new_size)
457 {
458         guint64 heap_size = GC_get_heap_size ();
459 #ifndef DISABLE_PERFCOUNTERS
460         if (mono_perfcounters) {
461                 mono_perfcounters->gc_committed_bytes = heap_size;
462                 mono_perfcounters->gc_reserved_bytes = heap_size;
463                 mono_perfcounters->gc_gen0size = heap_size;
464         }
465 #endif
466         mono_profiler_gc_heap_resize (new_size);
467 }
468
469 void
470 mono_gc_enable_events (void)
471 {
472         GC_notify_event = on_gc_notification;
473         GC_on_heap_resize = on_gc_heap_resize;
474 }
475
476 #else
477
478 void
479 mono_gc_enable_events (void)
480 {
481 }
482
483 #endif
484
485 int
486 mono_gc_register_root (char *start, size_t size, void *descr)
487 {
488         /* for some strange reason, they want one extra byte on the end */
489         GC_add_roots (start, start + size + 1);
490
491         return TRUE;
492 }
493
494 void
495 mono_gc_deregister_root (char* addr)
496 {
497 #ifndef HOST_WIN32
498         /* FIXME: libgc doesn't define this work win32 for some reason */
499         /* FIXME: No size info */
500         GC_remove_roots (addr, addr + sizeof (gpointer) + 1);
501 #endif
502 }
503
504 void
505 mono_gc_weak_link_add (void **link_addr, MonoObject *obj, gboolean track)
506 {
507         /* libgc requires that we use HIDE_POINTER... */
508         *link_addr = (void*)HIDE_POINTER (obj);
509         if (track)
510                 GC_REGISTER_LONG_LINK (link_addr, obj);
511         else
512                 GC_GENERAL_REGISTER_DISAPPEARING_LINK (link_addr, obj);
513 }
514
515 void
516 mono_gc_weak_link_remove (void **link_addr, gboolean track)
517 {
518         if (track)
519                 GC_unregister_long_link (link_addr);
520         else
521                 GC_unregister_disappearing_link (link_addr);
522         *link_addr = NULL;
523 }
524
525 static gpointer
526 reveal_link (gpointer link_addr)
527 {
528         void **link_a = link_addr;
529         return REVEAL_POINTER (*link_a);
530 }
531
532 MonoObject*
533 mono_gc_weak_link_get (void **link_addr)
534 {
535         MonoObject *obj = GC_call_with_alloc_lock (reveal_link, link_addr);
536         if (obj == (MonoObject *) -1)
537                 return NULL;
538         return obj;
539 }
540
541 void*
542 mono_gc_make_descr_for_string (gsize *bitmap, int numbits)
543 {
544         return mono_gc_make_descr_from_bitmap (bitmap, numbits);
545 }
546
547 void*
548 mono_gc_make_descr_for_object (gsize *bitmap, int numbits, size_t obj_size)
549 {
550         return mono_gc_make_descr_from_bitmap (bitmap, numbits);
551 }
552
553 void*
554 mono_gc_make_descr_for_array (int vector, gsize *elem_bitmap, int numbits, size_t elem_size)
555 {
556         /* libgc has no usable support for arrays... */
557         return GC_NO_DESCRIPTOR;
558 }
559
560 void*
561 mono_gc_make_descr_from_bitmap (gsize *bitmap, int numbits)
562 {
563 #ifdef HAVE_GC_GCJ_MALLOC
564         /* It seems there are issues when the bitmap doesn't fit: play it safe */
565         if (numbits >= 30)
566                 return GC_NO_DESCRIPTOR;
567         else
568                 return (gpointer)GC_make_descriptor ((GC_bitmap)bitmap, numbits);
569 #else
570         return NULL;
571 #endif
572 }
573
574 void*
575 mono_gc_make_root_descr_all_refs (int numbits)
576 {
577         return NULL;
578 }
579
580 void*
581 mono_gc_alloc_fixed (size_t size, void *descr)
582 {
583         /* To help track down typed allocation bugs */
584         /*
585         static int count;
586         count ++;
587         if (count == atoi (getenv ("COUNT2")))
588                 printf ("HIT!\n");
589         if (count > atoi (getenv ("COUNT2")))
590                 return GC_MALLOC (size);
591         */
592
593         if (descr)
594                 return GC_MALLOC_EXPLICITLY_TYPED (size, (GC_descr)descr);
595         else
596                 return GC_MALLOC (size);
597 }
598
599 void
600 mono_gc_free_fixed (void* addr)
601 {
602 }
603
604 int
605 mono_gc_invoke_finalizers (void)
606 {
607         /* There is a bug in GC_invoke_finalizer () in versions <= 6.2alpha4:
608          * the 'mem_freed' variable is not initialized when there are no
609          * objects to finalize, which leads to strange behavior later on.
610          * The check is necessary to work around that bug.
611          */
612         if (GC_should_invoke_finalizers ())
613                 return GC_invoke_finalizers ();
614         return 0;
615 }
616
617 gboolean
618 mono_gc_pending_finalizers (void)
619 {
620         return GC_should_invoke_finalizers ();
621 }
622
623 void
624 mono_gc_wbarrier_set_field (MonoObject *obj, gpointer field_ptr, MonoObject* value)
625 {
626         *(void**)field_ptr = value;
627 }
628
629 void
630 mono_gc_wbarrier_set_arrayref (MonoArray *arr, gpointer slot_ptr, MonoObject* value)
631 {
632         *(void**)slot_ptr = value;
633 }
634
635 void
636 mono_gc_wbarrier_arrayref_copy (gpointer dest_ptr, gpointer src_ptr, int count)
637 {
638         mono_gc_memmove (dest_ptr, src_ptr, count * sizeof (gpointer));
639 }
640
641 void
642 mono_gc_wbarrier_generic_store (gpointer ptr, MonoObject* value)
643 {
644         *(void**)ptr = value;
645 }
646
647 void
648 mono_gc_wbarrier_generic_nostore (gpointer ptr)
649 {
650 }
651
652 void
653 mono_gc_wbarrier_value_copy (gpointer dest, gpointer src, int count, MonoClass *klass)
654 {
655         mono_gc_memmove (dest, src, count * mono_class_value_size (klass, NULL));
656 }
657
658 void
659 mono_gc_wbarrier_object_copy (MonoObject* obj, MonoObject *src)
660 {
661         /* do not copy the sync state */
662         mono_gc_memmove ((char*)obj + sizeof (MonoObject), (char*)src + sizeof (MonoObject),
663                         mono_object_class (obj)->instance_size - sizeof (MonoObject));
664 }
665
666 void
667 mono_gc_clear_domain (MonoDomain *domain)
668 {
669 }
670
671 int
672 mono_gc_get_suspend_signal (void)
673 {
674 #ifdef USE_INCLUDED_GC
675         return GC_get_suspend_signal ();
676 #else
677         return -1;
678 #endif
679 }
680
681 #if defined(USE_INCLUDED_LIBGC) && defined(USE_COMPILER_TLS) && defined(__linux__) && (defined(__i386__) || defined(__x86_64__))
682 extern __thread MONO_TLS_FAST void* GC_thread_tls;
683 #include "metadata-internals.h"
684
685 static int
686 shift_amount (int v)
687 {
688         int i = 0;
689         while (!(v & (1 << i)))
690                 i++;
691         return i;
692 }
693
694 enum {
695         ATYPE_FREEPTR,
696         ATYPE_FREEPTR_FOR_BOX,
697         ATYPE_NORMAL,
698         ATYPE_GCJ,
699         ATYPE_STRING,
700         ATYPE_NUM
701 };
702
703 static MonoMethod*
704 create_allocator (int atype, int offset)
705 {
706         int index_var, bytes_var, my_fl_var, my_entry_var;
707         guint32 no_freelist_branch, not_small_enough_branch = 0;
708         guint32 size_overflow_branch = 0;
709         MonoMethodBuilder *mb;
710         MonoMethod *res;
711         MonoMethodSignature *csig;
712         AllocatorWrapperInfo *info;
713
714         if (atype == ATYPE_STRING) {
715                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
716                 csig->ret = &mono_defaults.string_class->byval_arg;
717                 csig->params [0] = &mono_defaults.int_class->byval_arg;
718                 csig->params [1] = &mono_defaults.int32_class->byval_arg;
719         } else {
720                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
721                 csig->ret = &mono_defaults.object_class->byval_arg;
722                 csig->params [0] = &mono_defaults.int_class->byval_arg;
723         }
724
725         mb = mono_mb_new (mono_defaults.object_class, "Alloc", MONO_WRAPPER_ALLOC);
726         bytes_var = mono_mb_add_local (mb, &mono_defaults.int32_class->byval_arg);
727         if (atype == ATYPE_STRING) {
728                 /* a string alloator method takes the args: (vtable, len) */
729                 /* bytes = (sizeof (MonoString) + ((len + 1) * 2)); */
730                 mono_mb_emit_ldarg (mb, 1);
731                 mono_mb_emit_icon (mb, 1);
732                 mono_mb_emit_byte (mb, MONO_CEE_ADD);
733                 mono_mb_emit_icon (mb, 1);
734                 mono_mb_emit_byte (mb, MONO_CEE_SHL);
735                 // sizeof (MonoString) might include padding
736                 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoString, chars));
737                 mono_mb_emit_byte (mb, MONO_CEE_ADD);
738                 mono_mb_emit_stloc (mb, bytes_var);
739         } else {
740                 /* bytes = vtable->klass->instance_size */
741                 mono_mb_emit_ldarg (mb, 0);
742                 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoVTable, klass));
743                 mono_mb_emit_byte (mb, MONO_CEE_ADD);
744                 mono_mb_emit_byte (mb, MONO_CEE_LDIND_I);
745                 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoClass, instance_size));
746                 mono_mb_emit_byte (mb, MONO_CEE_ADD);
747                 /* FIXME: assert instance_size stays a 4 byte integer */
748                 mono_mb_emit_byte (mb, MONO_CEE_LDIND_U4);
749                 mono_mb_emit_stloc (mb, bytes_var);
750         }
751
752         /* this is needed for strings/arrays only as the other big types are never allocated with this method */
753         if (atype == ATYPE_STRING) {
754                 /* check for size */
755                 /* if (!SMALL_ENOUGH (bytes)) jump slow_path;*/
756                 mono_mb_emit_ldloc (mb, bytes_var);
757                 mono_mb_emit_icon (mb, (NFREELISTS-1) * GRANULARITY);
758                 not_small_enough_branch = mono_mb_emit_short_branch (mb, MONO_CEE_BGT_UN_S);
759                 /* check for overflow */
760                 mono_mb_emit_ldloc (mb, bytes_var);
761                 mono_mb_emit_icon (mb, sizeof (MonoString));
762                 size_overflow_branch = mono_mb_emit_short_branch (mb, MONO_CEE_BLE_UN_S);
763         }
764
765         /* int index = INDEX_FROM_BYTES(bytes); */
766         index_var = mono_mb_add_local (mb, &mono_defaults.int32_class->byval_arg);
767         
768         mono_mb_emit_ldloc (mb, bytes_var);
769         mono_mb_emit_icon (mb, GRANULARITY - 1);
770         mono_mb_emit_byte (mb, MONO_CEE_ADD);
771         mono_mb_emit_icon (mb, shift_amount (GRANULARITY));
772         mono_mb_emit_byte (mb, MONO_CEE_SHR_UN);
773         mono_mb_emit_icon (mb, shift_amount (sizeof (gpointer)));
774         mono_mb_emit_byte (mb, MONO_CEE_SHL);
775         /* index var is already adjusted into bytes */
776         mono_mb_emit_stloc (mb, index_var);
777
778         my_fl_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
779         my_entry_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
780         /* my_fl = ((GC_thread)tsd) -> ptrfree_freelists + index; */
781         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
782         mono_mb_emit_byte (mb, 0x0D); /* CEE_MONO_TLS */
783         mono_mb_emit_i4 (mb, offset);
784         if (atype == ATYPE_FREEPTR || atype == ATYPE_FREEPTR_FOR_BOX || atype == ATYPE_STRING)
785                 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (struct GC_Thread_Rep, ptrfree_freelists));
786         else if (atype == ATYPE_NORMAL)
787                 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (struct GC_Thread_Rep, normal_freelists));
788         else if (atype == ATYPE_GCJ)
789                 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (struct GC_Thread_Rep, gcj_freelists));
790         else
791                 g_assert_not_reached ();
792         mono_mb_emit_byte (mb, MONO_CEE_ADD);
793         mono_mb_emit_ldloc (mb, index_var);
794         mono_mb_emit_byte (mb, MONO_CEE_ADD);
795         mono_mb_emit_stloc (mb, my_fl_var);
796
797         /* my_entry = *my_fl; */
798         mono_mb_emit_ldloc (mb, my_fl_var);
799         mono_mb_emit_byte (mb, MONO_CEE_LDIND_I);
800         mono_mb_emit_stloc (mb, my_entry_var);
801
802         /* if (EXPECT((word)my_entry >= HBLKSIZE, 1)) { */
803         mono_mb_emit_ldloc (mb, my_entry_var);
804         mono_mb_emit_icon (mb, HBLKSIZE);
805         no_freelist_branch = mono_mb_emit_short_branch (mb, MONO_CEE_BLT_UN_S);
806
807         /* ptr_t next = obj_link(my_entry); *my_fl = next; */
808         mono_mb_emit_ldloc (mb, my_fl_var);
809         mono_mb_emit_ldloc (mb, my_entry_var);
810         mono_mb_emit_byte (mb, MONO_CEE_LDIND_I);
811         mono_mb_emit_byte (mb, MONO_CEE_STIND_I);
812
813         /* set the vtable and clear the words in the object */
814         mono_mb_emit_ldloc (mb, my_entry_var);
815         mono_mb_emit_ldarg (mb, 0);
816         mono_mb_emit_byte (mb, MONO_CEE_STIND_I);
817
818         if (atype == ATYPE_FREEPTR) {
819                 int start_var, end_var, start_loop;
820                 /* end = my_entry + bytes; start = my_entry + sizeof (gpointer);
821                  */
822                 start_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
823                 end_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
824                 mono_mb_emit_ldloc (mb, my_entry_var);
825                 mono_mb_emit_ldloc (mb, bytes_var);
826                 mono_mb_emit_byte (mb, MONO_CEE_ADD);
827                 mono_mb_emit_stloc (mb, end_var);
828                 mono_mb_emit_ldloc (mb, my_entry_var);
829                 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoObject, synchronisation));
830                 mono_mb_emit_byte (mb, MONO_CEE_ADD);
831                 mono_mb_emit_stloc (mb, start_var);
832                 /*
833                  * do {
834                  *      *start++ = NULL;
835                  * } while (start < end);
836                  */
837                 start_loop = mono_mb_get_label (mb);
838                 mono_mb_emit_ldloc (mb, start_var);
839                 mono_mb_emit_icon (mb, 0);
840                 mono_mb_emit_byte (mb, MONO_CEE_STIND_I);
841                 mono_mb_emit_ldloc (mb, start_var);
842                 mono_mb_emit_icon (mb, sizeof (gpointer));
843                 mono_mb_emit_byte (mb, MONO_CEE_ADD);
844                 mono_mb_emit_stloc (mb, start_var);
845
846                 mono_mb_emit_ldloc (mb, start_var);
847                 mono_mb_emit_ldloc (mb, end_var);
848                 mono_mb_emit_byte (mb, MONO_CEE_BLT_UN_S);
849                 mono_mb_emit_byte (mb, start_loop - (mono_mb_get_label (mb) + 1));
850         } else if (atype == ATYPE_FREEPTR_FOR_BOX || atype == ATYPE_STRING) {
851                 /* need to clear just the sync pointer */
852                 mono_mb_emit_ldloc (mb, my_entry_var);
853                 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoObject, synchronisation));
854                 mono_mb_emit_byte (mb, MONO_CEE_ADD);
855                 mono_mb_emit_icon (mb, 0);
856                 mono_mb_emit_byte (mb, MONO_CEE_STIND_I);
857         }
858
859         if (atype == ATYPE_STRING) {
860                 /* need to set length and clear the last char */
861                 /* s->length = len; */
862                 mono_mb_emit_ldloc (mb, my_entry_var);
863                 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoString, length));
864                 mono_mb_emit_byte (mb, MONO_CEE_ADD);
865                 mono_mb_emit_ldarg (mb, 1);
866                 mono_mb_emit_byte (mb, MONO_CEE_STIND_I4);
867                 /* s->chars [len] = 0; */
868                 mono_mb_emit_ldloc (mb, my_entry_var);
869                 mono_mb_emit_ldloc (mb, bytes_var);
870                 mono_mb_emit_icon (mb, 2);
871                 mono_mb_emit_byte (mb, MONO_CEE_SUB);
872                 mono_mb_emit_byte (mb, MONO_CEE_ADD);
873                 mono_mb_emit_icon (mb, 0);
874                 mono_mb_emit_byte (mb, MONO_CEE_STIND_I2);
875         }
876
877         /* return my_entry; */
878         mono_mb_emit_ldloc (mb, my_entry_var);
879         mono_mb_emit_byte (mb, MONO_CEE_RET);
880         
881         mono_mb_patch_short_branch (mb, no_freelist_branch);
882         if (not_small_enough_branch > 0)
883                 mono_mb_patch_short_branch (mb, not_small_enough_branch);
884         if (size_overflow_branch > 0)
885                 mono_mb_patch_short_branch (mb, size_overflow_branch);
886         /* the slow path: we just call back into the runtime */
887         if (atype == ATYPE_STRING) {
888                 mono_mb_emit_ldarg (mb, 1);
889                 mono_mb_emit_icall (mb, mono_string_alloc);
890         } else {
891                 mono_mb_emit_ldarg (mb, 0);
892                 mono_mb_emit_icall (mb, mono_object_new_specific);
893         }
894
895         mono_mb_emit_byte (mb, MONO_CEE_RET);
896
897         res = mono_mb_create_method (mb, csig, 8);
898         mono_mb_free (mb);
899         mono_method_get_header (res)->init_locals = FALSE;
900
901         info = mono_image_alloc0 (mono_defaults.corlib, sizeof (AllocatorWrapperInfo));
902         info->gc_name = "boehm";
903         info->alloc_type = atype;
904         mono_marshal_set_wrapper_info (res, info);
905
906         return res;
907 }
908
909 static MonoMethod* alloc_method_cache [ATYPE_NUM];
910
911 static G_GNUC_UNUSED gboolean
912 mono_gc_is_critical_method (MonoMethod *method)
913 {
914         int i;
915
916         for (i = 0; i < ATYPE_NUM; ++i)
917                 if (method == alloc_method_cache [i])
918                         return TRUE;
919
920         return FALSE;
921 }
922
923 /*
924  * If possible, generate a managed method that can quickly allocate objects in class
925  * @klass. The method will typically have an thread-local inline allocation sequence.
926  * The signature of the called method is:
927  *      object allocate (MonoVTable *vtable)
928  * Some of the logic here is similar to mono_class_get_allocation_ftn () i object.c,
929  * keep in sync.
930  * The thread local alloc logic is taken from libgc/pthread_support.c.
931  */
932
933 MonoMethod*
934 mono_gc_get_managed_allocator (MonoVTable *vtable, gboolean for_box)
935 {
936         int offset = -1;
937         int atype;
938         MonoClass *klass = vtable->klass;
939         MONO_THREAD_VAR_OFFSET (GC_thread_tls, offset);
940
941         /*g_print ("thread tls: %d\n", offset);*/
942         if (offset == -1)
943                 return NULL;
944         if (!SMALL_ENOUGH (klass->instance_size))
945                 return NULL;
946         if (mono_class_has_finalizer (klass) || klass->marshalbyref || (mono_profiler_get_events () & MONO_PROFILE_ALLOCATIONS))
947                 return NULL;
948         if (klass->rank)
949                 return NULL;
950         if (klass->byval_arg.type == MONO_TYPE_STRING) {
951                 atype = ATYPE_STRING;
952         } else if (!klass->has_references) {
953                 if (for_box)
954                         atype = ATYPE_FREEPTR_FOR_BOX;
955                 else
956                         atype = ATYPE_FREEPTR;
957         } else {
958                 return NULL;
959                 /*
960                  * disabled because we currently do a runtime choice anyway, to
961                  * deal with multiple appdomains.
962                 if (vtable->gc_descr != GC_NO_DESCRIPTOR)
963                         atype = ATYPE_GCJ;
964                 else
965                         atype = ATYPE_NORMAL;
966                 */
967         }
968         return mono_gc_get_managed_allocator_by_type (atype);
969 }
970
971 MonoMethod*
972 mono_gc_get_managed_array_allocator (MonoVTable *vtable, int rank)
973 {
974         return NULL;
975 }
976
977 /**
978  * mono_gc_get_managed_allocator_by_type:
979  *
980  *   Return a managed allocator method corresponding to allocator type ATYPE.
981  */
982 MonoMethod*
983 mono_gc_get_managed_allocator_by_type (int atype)
984 {
985         int offset = -1;
986         MonoMethod *res;
987         MONO_THREAD_VAR_OFFSET (GC_thread_tls, offset);
988
989         mono_loader_lock ();
990         res = alloc_method_cache [atype];
991         if (!res)
992                 res = alloc_method_cache [atype] = create_allocator (atype, offset);
993         mono_loader_unlock ();
994         return res;
995 }
996
997 guint32
998 mono_gc_get_managed_allocator_types (void)
999 {
1000         return ATYPE_NUM;
1001 }
1002
1003 MonoMethod*
1004 mono_gc_get_write_barrier (void)
1005 {
1006         g_assert_not_reached ();
1007         return NULL;
1008 }
1009
1010 #else
1011
1012 static G_GNUC_UNUSED gboolean
1013 mono_gc_is_critical_method (MonoMethod *method)
1014 {
1015         return FALSE;
1016 }
1017
1018 MonoMethod*
1019 mono_gc_get_managed_allocator (MonoVTable *vtable, gboolean for_box)
1020 {
1021         return NULL;
1022 }
1023
1024 MonoMethod*
1025 mono_gc_get_managed_array_allocator (MonoVTable *vtable, int rank)
1026 {
1027         return NULL;
1028 }
1029
1030 MonoMethod*
1031 mono_gc_get_managed_allocator_by_type (int atype)
1032 {
1033         return NULL;
1034 }
1035
1036 guint32
1037 mono_gc_get_managed_allocator_types (void)
1038 {
1039         return 0;
1040 }
1041
1042 MonoMethod*
1043 mono_gc_get_write_barrier (void)
1044 {
1045         g_assert_not_reached ();
1046         return NULL;
1047 }
1048
1049 #endif
1050
1051 const char *
1052 mono_gc_get_gc_name (void)
1053 {
1054         return "boehm";
1055 }
1056
1057 void*
1058 mono_gc_invoke_with_gc_lock (MonoGCLockedCallbackFunc func, void *data)
1059 {
1060         return GC_call_with_alloc_lock (func, data);
1061 }
1062
1063 char*
1064 mono_gc_get_description (void)
1065 {
1066         return g_strdup (DEFAULT_GC_NAME);
1067 }
1068
1069 void
1070 mono_gc_set_desktop_mode (void)
1071 {
1072         GC_dont_expand = 1;
1073 }
1074
1075 gboolean
1076 mono_gc_is_moving (void)
1077 {
1078         return FALSE;
1079 }
1080
1081 gboolean
1082 mono_gc_is_disabled (void)
1083 {
1084         if (GC_dont_gc || g_getenv ("GC_DONT_GC"))
1085                 return TRUE;
1086         else
1087                 return FALSE;
1088 }
1089
1090 void
1091 mono_gc_wbarrier_value_copy_bitmap (gpointer _dest, gpointer _src, int size, unsigned bitmap)
1092 {
1093         g_assert_not_reached ();
1094 }
1095
1096
1097 guint8*
1098 mono_gc_get_card_table (int *shift_bits, gpointer *card_mask)
1099 {
1100         g_assert_not_reached ();
1101         return NULL;
1102 }
1103
1104 gboolean
1105 mono_gc_card_table_nursery_check (void)
1106 {
1107         g_assert_not_reached ();
1108         return TRUE;
1109 }
1110
1111 void*
1112 mono_gc_get_nursery (int *shift_bits, size_t *size)
1113 {
1114         return NULL;
1115 }
1116
1117 void
1118 mono_gc_set_current_thread_appdomain (MonoDomain *domain)
1119 {
1120 }
1121
1122 gboolean
1123 mono_gc_precise_stack_mark_enabled (void)
1124 {
1125         return FALSE;
1126 }
1127
1128 FILE *
1129 mono_gc_get_logfile (void)
1130 {
1131         return NULL;
1132 }
1133
1134 void
1135 mono_gc_conservatively_scan_area (void *start, void *end)
1136 {
1137         g_assert_not_reached ();
1138 }
1139
1140 void *
1141 mono_gc_scan_object (void *obj)
1142 {
1143         g_assert_not_reached ();
1144         return NULL;
1145 }
1146
1147 gsize*
1148 mono_gc_get_bitmap_for_descr (void *descr, int *numbits)
1149 {
1150         g_assert_not_reached ();
1151         return NULL;
1152 }
1153
1154 void
1155 mono_gc_set_gc_callbacks (MonoGCCallbacks *callbacks)
1156 {
1157 }
1158
1159 void
1160 mono_gc_set_stack_end (void *stack_end)
1161 {
1162 }
1163
1164 void mono_gc_set_skip_thread (gboolean value)
1165 {
1166 }
1167
1168 /*
1169  * These will call the redefined versions in libgc.
1170  */
1171
1172 #ifndef HOST_WIN32
1173
1174 int
1175 mono_gc_pthread_create (pthread_t *new_thread, const pthread_attr_t *attr, void *(*start_routine)(void *), void *arg)
1176 {
1177         return pthread_create (new_thread, attr, start_routine, arg);
1178 }
1179
1180 int
1181 mono_gc_pthread_join (pthread_t thread, void **retval)
1182 {
1183         return pthread_join (thread, retval);
1184 }
1185
1186 int
1187 mono_gc_pthread_detach (pthread_t thread)
1188 {
1189         return pthread_detach (thread);
1190 }
1191
1192 void
1193 mono_gc_pthread_exit (void *retval)
1194 {
1195         pthread_exit (retval);
1196 }
1197
1198 #endif
1199
1200 #ifdef HOST_WIN32
1201 BOOL APIENTRY mono_gc_dllmain (HMODULE module_handle, DWORD reason, LPVOID reserved)
1202 {
1203 #ifdef USE_INCLUDED_LIBGC
1204         return GC_DllMain (module_handle, reason, reserved);
1205 #else
1206         return TRUE;
1207 #endif
1208 }
1209 #endif
1210
1211 guint
1212 mono_gc_get_vtable_bits (MonoClass *class)
1213 {
1214         return 0;
1215 }
1216
1217 /*
1218  * mono_gc_register_altstack:
1219  *
1220  *   Register the dimensions of the normal stack and altstack with the collector.
1221  * Currently, STACK/STACK_SIZE is only used when the thread is suspended while it is on an altstack.
1222  */
1223 void
1224 mono_gc_register_altstack (gpointer stack, gint32 stack_size, gpointer altstack, gint32 altstack_size)
1225 {
1226 #ifdef USE_INCLUDED_LIBGC
1227         GC_register_altstack (stack, stack_size, altstack, altstack_size);
1228 #endif
1229 }
1230
1231 int
1232 mono_gc_get_los_limit (void)
1233 {
1234         return G_MAXINT;
1235 }
1236
1237 gboolean
1238 mono_gc_user_markers_supported (void)
1239 {
1240         return FALSE;
1241 }
1242
1243 void *
1244 mono_gc_make_root_descr_user (MonoGCRootMarkFunc marker)
1245 {
1246         g_assert_not_reached ();
1247         return NULL;
1248 }
1249
1250 #endif /* no Boehm GC */