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