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