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