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