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