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