Merge pull request #2018 from alexrp/profiler-jit-info-removal
[mono.git] / mono / metadata / sgen-mono.c
1 /*
2  * sgen-mono.c: SGen features specific to Mono.
3  *
4  * Copyright (C) 2014 Xamarin Inc
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Library General Public
8  * License 2.0 as published by the Free Software Foundation;
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Library General Public License for more details.
14  *
15  * You should have received a copy of the GNU Library General Public
16  * License 2.0 along with this library; if not, write to the Free
17  * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18  */
19
20 #include "config.h"
21 #ifdef HAVE_SGEN_GC
22
23 #include "sgen/sgen-gc.h"
24 #include "sgen/sgen-protocol.h"
25 #include "metadata/monitor.h"
26 #include "sgen/sgen-layout-stats.h"
27 #include "sgen/sgen-client.h"
28 #include "sgen/sgen-cardtable.h"
29 #include "sgen/sgen-pinning.h"
30 #include "metadata/marshal.h"
31 #include "metadata/method-builder.h"
32 #include "metadata/abi-details.h"
33 #include "metadata/mono-gc.h"
34 #include "metadata/runtime.h"
35 #include "metadata/sgen-bridge-internal.h"
36 #include "metadata/gc-internal.h"
37 #include "utils/mono-memory-model.h"
38 #include "utils/mono-logger-internal.h"
39
40 #ifdef HEAVY_STATISTICS
41 static guint64 stat_wbarrier_set_arrayref = 0;
42 static guint64 stat_wbarrier_value_copy = 0;
43 static guint64 stat_wbarrier_object_copy = 0;
44
45 static guint64 los_marked_cards;
46 static guint64 los_array_cards;
47 static guint64 los_array_remsets;
48 #endif
49
50 /* If set, mark stacks conservatively, even if precise marking is possible */
51 static gboolean conservative_stack_mark = FALSE;
52 /* If set, check that there are no references to the domain left at domain unload */
53 gboolean sgen_mono_xdomain_checks = FALSE;
54
55 /* Functions supplied by the runtime to be called by the GC */
56 static MonoGCCallbacks gc_callbacks;
57
58 #ifdef HAVE_KW_THREAD
59 __thread SgenThreadInfo *sgen_thread_info;
60 #else
61 MonoNativeTlsKey thread_info_key;
62 #endif
63
64 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
65
66 #define OPDEF(a,b,c,d,e,f,g,h,i,j) \
67         a = i,
68
69 enum {
70 #include "mono/cil/opcode.def"
71         CEE_LAST
72 };
73
74 #undef OPDEF
75
76 /*
77  * Write barriers
78  */
79
80 static gboolean
81 ptr_on_stack (void *ptr)
82 {
83         gpointer stack_start = &stack_start;
84         SgenThreadInfo *info = mono_thread_info_current ();
85
86         if (ptr >= stack_start && ptr < (gpointer)info->client_info.stack_end)
87                 return TRUE;
88         return FALSE;
89 }
90
91 #ifdef SGEN_HEAVY_BINARY_PROTOCOL
92 #undef HANDLE_PTR
93 #define HANDLE_PTR(ptr,obj) do {                                        \
94                 gpointer o = *(gpointer*)(ptr);                         \
95                 if ((o)) {                                              \
96                         gpointer d = ((char*)dest) + ((char*)(ptr) - (char*)(obj)); \
97                         binary_protocol_wbarrier (d, o, (gpointer) SGEN_LOAD_VTABLE (o)); \
98                 }                                                       \
99         } while (0)
100
101 static void
102 scan_object_for_binary_protocol_copy_wbarrier (gpointer dest, char *start, mword desc)
103 {
104 #define SCAN_OBJECT_NOVTABLE
105 #include "sgen/sgen-scan-object.h"
106 }
107 #endif
108
109 void
110 mono_gc_wbarrier_value_copy (gpointer dest, gpointer src, int count, MonoClass *klass)
111 {
112         HEAVY_STAT (++stat_wbarrier_value_copy);
113         g_assert (klass->valuetype);
114
115         SGEN_LOG (8, "Adding value remset at %p, count %d, descr %p for class %s (%p)", dest, count, (gpointer)klass->gc_descr, klass->name, klass);
116
117         if (sgen_ptr_in_nursery (dest) || ptr_on_stack (dest) || !sgen_gc_descr_has_references ((mword)klass->gc_descr)) {
118                 size_t element_size = mono_class_value_size (klass, NULL);
119                 size_t size = count * element_size;
120                 mono_gc_memmove_atomic (dest, src, size);               
121                 return;
122         }
123
124 #ifdef SGEN_HEAVY_BINARY_PROTOCOL
125         if (binary_protocol_is_heavy_enabled ()) {
126                 size_t element_size = mono_class_value_size (klass, NULL);
127                 int i;
128                 for (i = 0; i < count; ++i) {
129                         scan_object_for_binary_protocol_copy_wbarrier ((char*)dest + i * element_size,
130                                         (char*)src + i * element_size - sizeof (MonoObject),
131                                         (mword) klass->gc_descr);
132                 }
133         }
134 #endif
135
136         sgen_get_remset ()->wbarrier_value_copy (dest, src, count, mono_class_value_size (klass, NULL));
137 }
138
139 /**
140  * mono_gc_wbarrier_object_copy:
141  *
142  * Write barrier to call when obj is the result of a clone or copy of an object.
143  */
144 void
145 mono_gc_wbarrier_object_copy (MonoObject* obj, MonoObject *src)
146 {
147         int size;
148
149         HEAVY_STAT (++stat_wbarrier_object_copy);
150
151         if (sgen_ptr_in_nursery (obj) || ptr_on_stack (obj) || !SGEN_OBJECT_HAS_REFERENCES (src)) {
152                 size = mono_object_class (obj)->instance_size;
153                 mono_gc_memmove_aligned ((char*)obj + sizeof (MonoObject), (char*)src + sizeof (MonoObject),
154                                 size - sizeof (MonoObject));
155                 return; 
156         }
157
158 #ifdef SGEN_HEAVY_BINARY_PROTOCOL
159         if (binary_protocol_is_heavy_enabled ())
160                 scan_object_for_binary_protocol_copy_wbarrier (obj, (char*)src, (mword) src->vtable->gc_descr);
161 #endif
162
163         sgen_get_remset ()->wbarrier_object_copy (obj, src);
164 }
165
166 void
167 mono_gc_wbarrier_set_arrayref (MonoArray *arr, gpointer slot_ptr, MonoObject* value)
168 {
169         HEAVY_STAT (++stat_wbarrier_set_arrayref);
170         if (sgen_ptr_in_nursery (slot_ptr)) {
171                 *(void**)slot_ptr = value;
172                 return;
173         }
174         SGEN_LOG (8, "Adding remset at %p", slot_ptr);
175         if (value)
176                 binary_protocol_wbarrier (slot_ptr, value, value->vtable);
177
178         sgen_get_remset ()->wbarrier_set_field ((GCObject*)arr, slot_ptr, value);
179 }
180
181 void
182 mono_gc_wbarrier_set_field (MonoObject *obj, gpointer field_ptr, MonoObject* value)
183 {
184         mono_gc_wbarrier_set_arrayref ((MonoArray*)obj, field_ptr, value);
185 }
186
187 void
188 mono_gc_wbarrier_value_copy_bitmap (gpointer _dest, gpointer _src, int size, unsigned bitmap)
189 {
190         sgen_wbarrier_value_copy_bitmap (_dest, _src, size, bitmap);
191 }
192
193 static MonoMethod *write_barrier_conc_method;
194 static MonoMethod *write_barrier_noconc_method;
195
196 gboolean
197 sgen_is_critical_method (MonoMethod *method)
198 {
199         return (method == write_barrier_conc_method || method == write_barrier_noconc_method || sgen_is_managed_allocator (method));
200 }
201
202 gboolean
203 sgen_has_critical_method (void)
204 {
205         return write_barrier_conc_method || write_barrier_noconc_method || sgen_has_managed_allocator ();
206 }
207
208 #ifndef DISABLE_JIT
209
210 static void
211 emit_nursery_check (MonoMethodBuilder *mb, int *nursery_check_return_labels, gboolean is_concurrent)
212 {
213         int shifted_nursery_start = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
214
215         memset (nursery_check_return_labels, 0, sizeof (int) * 2);
216         // if (ptr_in_nursery (ptr)) return;
217         /*
218          * Masking out the bits might be faster, but we would have to use 64 bit
219          * immediates, which might be slower.
220          */
221         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
222         mono_mb_emit_byte (mb, CEE_MONO_LDPTR_NURSERY_START);
223         mono_mb_emit_icon (mb, DEFAULT_NURSERY_BITS);
224         mono_mb_emit_byte (mb, CEE_SHR_UN);
225         mono_mb_emit_stloc (mb, shifted_nursery_start);
226
227         mono_mb_emit_ldarg (mb, 0);
228         mono_mb_emit_icon (mb, DEFAULT_NURSERY_BITS);
229         mono_mb_emit_byte (mb, CEE_SHR_UN);
230         mono_mb_emit_ldloc (mb, shifted_nursery_start);
231         nursery_check_return_labels [0] = mono_mb_emit_branch (mb, CEE_BEQ);
232
233         if (!is_concurrent) {
234                 // if (!ptr_in_nursery (*ptr)) return;
235                 mono_mb_emit_ldarg (mb, 0);
236                 mono_mb_emit_byte (mb, CEE_LDIND_I);
237                 mono_mb_emit_icon (mb, DEFAULT_NURSERY_BITS);
238                 mono_mb_emit_byte (mb, CEE_SHR_UN);
239                 mono_mb_emit_ldloc (mb, shifted_nursery_start);
240                 nursery_check_return_labels [1] = mono_mb_emit_branch (mb, CEE_BNE_UN);
241         }
242 }
243 #endif
244
245 MonoMethod*
246 mono_gc_get_specific_write_barrier (gboolean is_concurrent)
247 {
248         MonoMethod *res;
249         MonoMethodBuilder *mb;
250         MonoMethodSignature *sig;
251         MonoMethod **write_barrier_method_addr;
252 #ifdef MANAGED_WBARRIER
253         int i, nursery_check_labels [2];
254 #endif
255
256         // FIXME: Maybe create a separate version for ctors (the branch would be
257         // correctly predicted more times)
258         if (is_concurrent)
259                 write_barrier_method_addr = &write_barrier_conc_method;
260         else
261                 write_barrier_method_addr = &write_barrier_noconc_method;
262
263         if (*write_barrier_method_addr)
264                 return *write_barrier_method_addr;
265
266         /* Create the IL version of mono_gc_barrier_generic_store () */
267         sig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
268         sig->ret = &mono_defaults.void_class->byval_arg;
269         sig->params [0] = &mono_defaults.int_class->byval_arg;
270
271         if (is_concurrent)
272                 mb = mono_mb_new (mono_defaults.object_class, "wbarrier_conc", MONO_WRAPPER_WRITE_BARRIER);
273         else
274                 mb = mono_mb_new (mono_defaults.object_class, "wbarrier_noconc", MONO_WRAPPER_WRITE_BARRIER);
275
276 #ifndef DISABLE_JIT
277 #ifdef MANAGED_WBARRIER
278         emit_nursery_check (mb, nursery_check_labels, is_concurrent);
279         /*
280         addr = sgen_cardtable + ((address >> CARD_BITS) & CARD_MASK)
281         *addr = 1;
282
283         sgen_cardtable:
284                 LDC_PTR sgen_cardtable
285
286         address >> CARD_BITS
287                 LDARG_0
288                 LDC_I4 CARD_BITS
289                 SHR_UN
290         if (SGEN_HAVE_OVERLAPPING_CARDS) {
291                 LDC_PTR card_table_mask
292                 AND
293         }
294         AND
295         ldc_i4_1
296         stind_i1
297         */
298         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
299         mono_mb_emit_byte (mb, CEE_MONO_LDPTR_CARD_TABLE);
300         mono_mb_emit_ldarg (mb, 0);
301         mono_mb_emit_icon (mb, CARD_BITS);
302         mono_mb_emit_byte (mb, CEE_SHR_UN);
303         mono_mb_emit_byte (mb, CEE_CONV_I);
304 #ifdef SGEN_HAVE_OVERLAPPING_CARDS
305 #if SIZEOF_VOID_P == 8
306         mono_mb_emit_icon8 (mb, CARD_MASK);
307 #else
308         mono_mb_emit_icon (mb, CARD_MASK);
309 #endif
310         mono_mb_emit_byte (mb, CEE_CONV_I);
311         mono_mb_emit_byte (mb, CEE_AND);
312 #endif
313         mono_mb_emit_byte (mb, CEE_ADD);
314         mono_mb_emit_icon (mb, 1);
315         mono_mb_emit_byte (mb, CEE_STIND_I1);
316
317         // return;
318         for (i = 0; i < 2; ++i) {
319                 if (nursery_check_labels [i])
320                         mono_mb_patch_branch (mb, nursery_check_labels [i]);
321         }
322         mono_mb_emit_byte (mb, CEE_RET);
323 #else
324         mono_mb_emit_ldarg (mb, 0);
325         mono_mb_emit_icall (mb, mono_gc_wbarrier_generic_nostore);
326         mono_mb_emit_byte (mb, CEE_RET);
327 #endif
328 #endif
329         res = mono_mb_create_method (mb, sig, 16);
330         mono_mb_free (mb);
331
332         LOCK_GC;
333         if (*write_barrier_method_addr) {
334                 /* Already created */
335                 mono_free_method (res);
336         } else {
337                 /* double-checked locking */
338                 mono_memory_barrier ();
339                 *write_barrier_method_addr = res;
340         }
341         UNLOCK_GC;
342
343         return *write_barrier_method_addr;
344 }
345
346 MonoMethod*
347 mono_gc_get_write_barrier (void)
348 {
349         return mono_gc_get_specific_write_barrier (major_collector.is_concurrent);
350 }
351
352 /*
353  * Dummy filler objects
354  */
355
356 /* Vtable of the objects used to fill out nursery fragments before a collection */
357 static GCVTable array_fill_vtable;
358
359 static GCVTable
360 get_array_fill_vtable (void)
361 {
362         if (!array_fill_vtable) {
363                 static MonoClass klass;
364                 static char _vtable[sizeof(MonoVTable)+8];
365                 MonoVTable* vtable = (MonoVTable*) ALIGN_TO(_vtable, 8);
366                 gsize bmap;
367
368                 MonoDomain *domain = mono_get_root_domain ();
369                 g_assert (domain);
370
371                 klass.element_class = mono_defaults.byte_class;
372                 klass.rank = 1;
373                 klass.instance_size = sizeof (MonoArray);
374                 klass.sizes.element_size = 1;
375                 klass.name = "array_filler_type";
376
377                 vtable->klass = &klass;
378                 bmap = 0;
379                 vtable->gc_descr = mono_gc_make_descr_for_array (TRUE, &bmap, 0, 1);
380                 vtable->rank = 1;
381
382                 array_fill_vtable = vtable;
383         }
384         return array_fill_vtable;
385 }
386
387 gboolean
388 sgen_client_array_fill_range (char *start, size_t size)
389 {
390         MonoArray *o;
391
392         if (size < sizeof (MonoArray)) {
393                 memset (start, 0, size);
394                 return FALSE;
395         }
396
397         o = (MonoArray*)start;
398         o->obj.vtable = (MonoVTable*)get_array_fill_vtable ();
399         /* Mark this as not a real object */
400         o->obj.synchronisation = GINT_TO_POINTER (-1);
401         o->bounds = NULL;
402         o->max_length = (mono_array_size_t)(size - sizeof (MonoArray));
403
404         return TRUE;
405 }
406
407 void
408 sgen_client_zero_array_fill_header (void *p, size_t size)
409 {
410         if (size >= sizeof (MonoArray)) {
411                 memset (p, 0, sizeof (MonoArray));
412         } else {
413                 static guint8 zeros [sizeof (MonoArray)];
414
415                 SGEN_ASSERT (0, !memcmp (p, zeros, size), "TLAB segment must be zeroed out.");
416         }
417 }
418
419 /*
420  * Finalization
421  */
422
423 static MonoGCFinalizerCallbacks fin_callbacks;
424
425 guint
426 mono_gc_get_vtable_bits (MonoClass *class)
427 {
428         guint res = 0;
429         /* FIXME move this to the bridge code */
430         if (sgen_need_bridge_processing ()) {
431                 switch (sgen_bridge_class_kind (class)) {
432                 case GC_BRIDGE_TRANSPARENT_BRIDGE_CLASS:
433                 case GC_BRIDGE_OPAQUE_BRIDGE_CLASS:
434                         res = SGEN_GC_BIT_BRIDGE_OBJECT;
435                         break;
436                 case GC_BRIDGE_OPAQUE_CLASS:
437                         res = SGEN_GC_BIT_BRIDGE_OPAQUE_OBJECT;
438                         break;
439                 case GC_BRIDGE_TRANSPARENT_CLASS:
440                         break;
441                 }
442         }
443         if (fin_callbacks.is_class_finalization_aware) {
444                 if (fin_callbacks.is_class_finalization_aware (class))
445                         res |= SGEN_GC_BIT_FINALIZER_AWARE;
446         }
447         return res;
448 }
449
450 static gboolean
451 is_finalization_aware (MonoObject *obj)
452 {
453         MonoVTable *vt = SGEN_LOAD_VTABLE (obj);
454         return (vt->gc_bits & SGEN_GC_BIT_FINALIZER_AWARE) == SGEN_GC_BIT_FINALIZER_AWARE;
455 }
456
457 void
458 sgen_client_object_queued_for_finalization (GCObject *obj)
459 {
460         if (fin_callbacks.object_queued_for_finalization && is_finalization_aware (obj))
461                 fin_callbacks.object_queued_for_finalization (obj);
462
463 #ifdef ENABLE_DTRACE
464         if (G_UNLIKELY (MONO_GC_FINALIZE_ENQUEUE_ENABLED ())) {
465                 int gen = sgen_ptr_in_nursery (obj) ? GENERATION_NURSERY : GENERATION_OLD;
466                 GCVTable vt = SGEN_LOAD_VTABLE (obj);
467                 MONO_GC_FINALIZE_ENQUEUE ((mword)obj, sgen_safe_object_get_size (obj),
468                                 sgen_client_vtable_get_namespace (vt), sgen_client_vtable_get_name (vt), gen,
469                                 sgen_client_object_has_critical_finalizer (obj));
470         }
471 #endif
472 }
473
474 void
475 mono_gc_register_finalizer_callbacks (MonoGCFinalizerCallbacks *callbacks)
476 {
477         if (callbacks->version != MONO_GC_FINALIZER_EXTENSION_VERSION)
478                 g_error ("Invalid finalizer callback version. Expected %d but got %d\n", MONO_GC_FINALIZER_EXTENSION_VERSION, callbacks->version);
479
480         fin_callbacks = *callbacks;
481 }
482
483 void
484 sgen_client_run_finalize (MonoObject *obj)
485 {
486         mono_gc_run_finalize (obj, NULL);
487 }
488
489 int
490 mono_gc_invoke_finalizers (void)
491 {
492         return sgen_gc_invoke_finalizers ();
493 }
494
495 gboolean
496 mono_gc_pending_finalizers (void)
497 {
498         return sgen_have_pending_finalizers ();
499 }
500
501 void
502 sgen_client_finalize_notify (void)
503 {
504         mono_gc_finalize_notify ();
505 }
506
507 void
508 mono_gc_register_for_finalization (MonoObject *obj, void *user_data)
509 {
510         sgen_object_register_for_finalization (obj, user_data);
511 }
512
513 static gboolean
514 object_in_domain_predicate (MonoObject *obj, void *user_data)
515 {
516         MonoDomain *domain = user_data;
517         if (mono_object_domain (obj) == domain) {
518                 SGEN_LOG (5, "Unregistering finalizer for object: %p (%s)", obj, sgen_client_vtable_get_name (SGEN_LOAD_VTABLE (obj)));
519                 return TRUE;
520         }
521         return FALSE;
522 }
523
524 /**
525  * mono_gc_finalizers_for_domain:
526  * @domain: the unloading appdomain
527  * @out_array: output array
528  * @out_size: size of output array
529  *
530  * Store inside @out_array up to @out_size objects that belong to the unloading
531  * appdomain @domain. Returns the number of stored items. Can be called repeteadly
532  * until it returns 0.
533  * The items are removed from the finalizer data structure, so the caller is supposed
534  * to finalize them.
535  * @out_array should be on the stack to allow the GC to know the objects are still alive.
536  */
537 int
538 mono_gc_finalizers_for_domain (MonoDomain *domain, MonoObject **out_array, int out_size)
539 {
540         return sgen_gather_finalizers_if (object_in_domain_predicate, domain, out_array, out_size);
541 }
542
543 /*
544  * Ephemerons
545  */
546
547 typedef struct _EphemeronLinkNode EphemeronLinkNode;
548
549 struct _EphemeronLinkNode {
550         EphemeronLinkNode *next;
551         MonoArray *array;
552 };
553
554 typedef struct {
555        GCObject *key;
556        GCObject *value;
557 } Ephemeron;
558
559 static EphemeronLinkNode *ephemeron_list;
560
561 /* LOCKING: requires that the GC lock is held */
562 static void
563 null_ephemerons_for_domain (MonoDomain *domain)
564 {
565         EphemeronLinkNode *current = ephemeron_list, *prev = NULL;
566
567         while (current) {
568                 MonoObject *object = (MonoObject*)current->array;
569
570                 if (object)
571                         SGEN_ASSERT (0, object->vtable, "Can't have objects without vtables.");
572
573                 if (object && object->vtable->domain == domain) {
574                         EphemeronLinkNode *tmp = current;
575
576                         if (prev)
577                                 prev->next = current->next;
578                         else
579                                 ephemeron_list = current->next;
580
581                         current = current->next;
582                         sgen_free_internal (tmp, INTERNAL_MEM_EPHEMERON_LINK);
583                 } else {
584                         prev = current;
585                         current = current->next;
586                 }
587         }
588 }
589
590 /* LOCKING: requires that the GC lock is held */
591 void
592 sgen_client_clear_unreachable_ephemerons (ScanCopyContext ctx)
593 {
594         CopyOrMarkObjectFunc copy_func = ctx.ops->copy_or_mark_object;
595         SgenGrayQueue *queue = ctx.queue;
596         EphemeronLinkNode *current = ephemeron_list, *prev = NULL;
597         Ephemeron *cur, *array_end;
598         GCObject *tombstone;
599
600         while (current) {
601                 MonoArray *array = current->array;
602
603                 if (!sgen_is_object_alive_for_current_gen ((GCObject*)array)) {
604                         EphemeronLinkNode *tmp = current;
605
606                         SGEN_LOG (5, "Dead Ephemeron array at %p", array);
607
608                         if (prev)
609                                 prev->next = current->next;
610                         else
611                                 ephemeron_list = current->next;
612
613                         current = current->next;
614                         sgen_free_internal (tmp, INTERNAL_MEM_EPHEMERON_LINK);
615
616                         continue;
617                 }
618
619                 copy_func ((GCObject**)&array, queue);
620                 current->array = array;
621
622                 SGEN_LOG (5, "Clearing unreachable entries for ephemeron array at %p", array);
623
624                 cur = mono_array_addr (array, Ephemeron, 0);
625                 array_end = cur + mono_array_length_fast (array);
626                 tombstone = SGEN_LOAD_VTABLE ((GCObject*)array)->domain->ephemeron_tombstone;
627
628                 for (; cur < array_end; ++cur) {
629                         GCObject *key = cur->key;
630
631                         if (!key || key == tombstone)
632                                 continue;
633
634                         SGEN_LOG (5, "[%zd] key %p (%s) value %p (%s)", cur - mono_array_addr (array, Ephemeron, 0),
635                                 key, sgen_is_object_alive_for_current_gen (key) ? "reachable" : "unreachable",
636                                 cur->value, cur->value && sgen_is_object_alive_for_current_gen (cur->value) ? "reachable" : "unreachable");
637
638                         if (!sgen_is_object_alive_for_current_gen (key)) {
639                                 cur->key = tombstone;
640                                 cur->value = NULL;
641                                 continue;
642                         }
643                 }
644                 prev = current;
645                 current = current->next;
646         }
647 }
648
649 /*
650 LOCKING: requires that the GC lock is held
651
652 Limitations: We scan all ephemerons on every collection since the current design doesn't allow for a simple nursery/mature split.
653 */
654 gboolean
655 sgen_client_mark_ephemerons (ScanCopyContext ctx)
656 {
657         CopyOrMarkObjectFunc copy_func = ctx.ops->copy_or_mark_object;
658         SgenGrayQueue *queue = ctx.queue;
659         gboolean nothing_marked = TRUE;
660         EphemeronLinkNode *current = ephemeron_list;
661         Ephemeron *cur, *array_end;
662         GCObject *tombstone;
663
664         for (current = ephemeron_list; current; current = current->next) {
665                 MonoArray *array = current->array;
666                 SGEN_LOG (5, "Ephemeron array at %p", array);
667
668                 /*It has to be alive*/
669                 if (!sgen_is_object_alive_for_current_gen ((GCObject*)array)) {
670                         SGEN_LOG (5, "\tnot reachable");
671                         continue;
672                 }
673
674                 copy_func ((GCObject**)&array, queue);
675
676                 cur = mono_array_addr (array, Ephemeron, 0);
677                 array_end = cur + mono_array_length_fast (array);
678                 tombstone = SGEN_LOAD_VTABLE ((GCObject*)array)->domain->ephemeron_tombstone;
679
680                 for (; cur < array_end; ++cur) {
681                         GCObject *key = cur->key;
682
683                         if (!key || key == tombstone)
684                                 continue;
685
686                         SGEN_LOG (5, "[%zd] key %p (%s) value %p (%s)", cur - mono_array_addr (array, Ephemeron, 0),
687                                 key, sgen_is_object_alive_for_current_gen (key) ? "reachable" : "unreachable",
688                                 cur->value, cur->value && sgen_is_object_alive_for_current_gen (cur->value) ? "reachable" : "unreachable");
689
690                         if (sgen_is_object_alive_for_current_gen (key)) {
691                                 GCObject *value = cur->value;
692
693                                 copy_func (&cur->key, queue);
694                                 if (value) {
695                                         if (!sgen_is_object_alive_for_current_gen (value))
696                                                 nothing_marked = FALSE;
697                                         copy_func (&cur->value, queue);
698                                 }
699                         }
700                 }
701         }
702
703         SGEN_LOG (5, "Ephemeron run finished. Is it done %d", nothing_marked);
704         return nothing_marked;
705 }
706
707 gboolean
708 mono_gc_ephemeron_array_add (MonoObject *obj)
709 {
710         EphemeronLinkNode *node;
711
712         LOCK_GC;
713
714         node = sgen_alloc_internal (INTERNAL_MEM_EPHEMERON_LINK);
715         if (!node) {
716                 UNLOCK_GC;
717                 return FALSE;
718         }
719         node->array = (MonoArray*)obj;
720         node->next = ephemeron_list;
721         ephemeron_list = node;
722
723         SGEN_LOG (5, "Registered ephemeron array %p", obj);
724
725         UNLOCK_GC;
726         return TRUE;
727 }
728
729 /*
730  * Appdomain handling
731  */
732
733 void
734 mono_gc_set_current_thread_appdomain (MonoDomain *domain)
735 {
736         SgenThreadInfo *info = mono_thread_info_current ();
737
738         /* Could be called from sgen_thread_unregister () with a NULL info */
739         if (domain) {
740                 g_assert (info);
741                 info->client_info.stopped_domain = domain;
742         }
743 }
744
745 static gboolean
746 need_remove_object_for_domain (GCObject *start, MonoDomain *domain)
747 {
748         if (mono_object_domain (start) == domain) {
749                 SGEN_LOG (4, "Need to cleanup object %p", start);
750                 binary_protocol_cleanup (start, (gpointer)SGEN_LOAD_VTABLE (start), sgen_safe_object_get_size ((GCObject*)start));
751                 return TRUE;
752         }
753         return FALSE;
754 }
755
756 static void
757 process_object_for_domain_clearing (GCObject *start, MonoDomain *domain)
758 {
759         MonoVTable *vt = SGEN_LOAD_VTABLE (start);
760         if (vt->klass == mono_defaults.internal_thread_class)
761                 g_assert (mono_object_domain (start) == mono_get_root_domain ());
762         /* The object could be a proxy for an object in the domain
763            we're deleting. */
764 #ifndef DISABLE_REMOTING
765         if (mono_defaults.real_proxy_class->supertypes && mono_class_has_parent_fast (vt->klass, mono_defaults.real_proxy_class)) {
766                 MonoObject *server = ((MonoRealProxy*)start)->unwrapped_server;
767
768                 /* The server could already have been zeroed out, so
769                    we need to check for that, too. */
770                 if (server && (!SGEN_LOAD_VTABLE (server) || mono_object_domain (server) == domain)) {
771                         SGEN_LOG (4, "Cleaning up remote pointer in %p to object %p", start, server);
772                         ((MonoRealProxy*)start)->unwrapped_server = NULL;
773                 }
774         }
775 #endif
776 }
777
778 static gboolean
779 clear_domain_process_object (GCObject *obj, MonoDomain *domain)
780 {
781         gboolean remove;
782
783         process_object_for_domain_clearing (obj, domain);
784         remove = need_remove_object_for_domain (obj, domain);
785
786         if (remove && obj->synchronisation) {
787                 void **dislink = mono_monitor_get_object_monitor_weak_link (obj);
788                 if (dislink)
789                         sgen_register_disappearing_link (NULL, dislink, FALSE, TRUE);
790         }
791
792         return remove;
793 }
794
795 static void
796 clear_domain_process_minor_object_callback (GCObject *obj, size_t size, MonoDomain *domain)
797 {
798         if (clear_domain_process_object (obj, domain)) {
799                 CANARIFY_SIZE (size);
800                 memset (obj, 0, size);
801         }
802 }
803
804 static void
805 clear_domain_process_major_object_callback (GCObject *obj, size_t size, MonoDomain *domain)
806 {
807         clear_domain_process_object (obj, domain);
808 }
809
810 static void
811 clear_domain_free_major_non_pinned_object_callback (GCObject *obj, size_t size, MonoDomain *domain)
812 {
813         if (need_remove_object_for_domain (obj, domain))
814                 major_collector.free_non_pinned_object (obj, size);
815 }
816
817 static void
818 clear_domain_free_major_pinned_object_callback (GCObject *obj, size_t size, MonoDomain *domain)
819 {
820         if (need_remove_object_for_domain (obj, domain))
821                 major_collector.free_pinned_object (obj, size);
822 }
823
824 /*
825  * When appdomains are unloaded we can easily remove objects that have finalizers,
826  * but all the others could still be present in random places on the heap.
827  * We need a sweep to get rid of them even though it's going to be costly
828  * with big heaps.
829  * The reason we need to remove them is because we access the vtable and class
830  * structures to know the object size and the reference bitmap: once the domain is
831  * unloaded the point to random memory.
832  */
833 void
834 mono_gc_clear_domain (MonoDomain * domain)
835 {
836         LOSObject *bigobj, *prev;
837         int i;
838
839         LOCK_GC;
840
841         binary_protocol_domain_unload_begin (domain);
842
843         sgen_stop_world (0);
844
845         if (sgen_concurrent_collection_in_progress ())
846                 sgen_perform_collection (0, GENERATION_OLD, "clear domain", TRUE);
847         SGEN_ASSERT (0, !sgen_concurrent_collection_in_progress (), "We just ordered a synchronous collection.  Why are we collecting concurrently?");
848
849         major_collector.finish_sweeping ();
850
851         sgen_process_fin_stage_entries ();
852         sgen_process_dislink_stage_entries ();
853
854         sgen_clear_nursery_fragments ();
855
856         if (sgen_mono_xdomain_checks && domain != mono_get_root_domain ()) {
857                 sgen_scan_for_registered_roots_in_domain (domain, ROOT_TYPE_NORMAL);
858                 sgen_scan_for_registered_roots_in_domain (domain, ROOT_TYPE_WBARRIER);
859                 sgen_check_for_xdomain_refs ();
860         }
861
862         /*Ephemerons and dislinks must be processed before LOS since they might end up pointing
863         to memory returned to the OS.*/
864         null_ephemerons_for_domain (domain);
865
866         for (i = GENERATION_NURSERY; i < GENERATION_MAX; ++i)
867                 sgen_null_links_if (object_in_domain_predicate, domain, i);
868
869         for (i = GENERATION_NURSERY; i < GENERATION_MAX; ++i)
870                 sgen_remove_finalizers_if (object_in_domain_predicate, domain, i);
871
872         sgen_scan_area_with_callback (nursery_section->data, nursery_section->end_data,
873                         (IterateObjectCallbackFunc)clear_domain_process_minor_object_callback, domain, FALSE, TRUE);
874
875         /* We need two passes over major and large objects because
876            freeing such objects might give their memory back to the OS
877            (in the case of large objects) or obliterate its vtable
878            (pinned objects with major-copying or pinned and non-pinned
879            objects with major-mark&sweep), but we might need to
880            dereference a pointer from an object to another object if
881            the first object is a proxy. */
882         major_collector.iterate_objects (ITERATE_OBJECTS_SWEEP_ALL, (IterateObjectCallbackFunc)clear_domain_process_major_object_callback, domain);
883         for (bigobj = los_object_list; bigobj; bigobj = bigobj->next)
884                 clear_domain_process_object ((GCObject*)bigobj->data, domain);
885
886         prev = NULL;
887         for (bigobj = los_object_list; bigobj;) {
888                 if (need_remove_object_for_domain ((GCObject*)bigobj->data, domain)) {
889                         LOSObject *to_free = bigobj;
890                         if (prev)
891                                 prev->next = bigobj->next;
892                         else
893                                 los_object_list = bigobj->next;
894                         bigobj = bigobj->next;
895                         SGEN_LOG (4, "Freeing large object %p", bigobj->data);
896                         sgen_los_free_object (to_free);
897                         continue;
898                 }
899                 prev = bigobj;
900                 bigobj = bigobj->next;
901         }
902         major_collector.iterate_objects (ITERATE_OBJECTS_SWEEP_NON_PINNED, (IterateObjectCallbackFunc)clear_domain_free_major_non_pinned_object_callback, domain);
903         major_collector.iterate_objects (ITERATE_OBJECTS_SWEEP_PINNED, (IterateObjectCallbackFunc)clear_domain_free_major_pinned_object_callback, domain);
904
905         if (domain == mono_get_root_domain ()) {
906                 sgen_pin_stats_print_class_stats ();
907                 sgen_object_layout_dump (stdout);
908         }
909
910         sgen_restart_world (0, NULL);
911
912         binary_protocol_domain_unload_end (domain);
913         binary_protocol_flush_buffers (FALSE);
914
915         UNLOCK_GC;
916 }
917
918 /*
919  * Allocation
920  */
921
922 static gboolean alloc_events = FALSE;
923
924 void
925 mono_gc_enable_alloc_events (void)
926 {
927         alloc_events = TRUE;
928 }
929
930 void*
931 mono_gc_alloc_obj (MonoVTable *vtable, size_t size)
932 {
933         MonoObject *obj = sgen_alloc_obj (vtable, size);
934
935         if (G_UNLIKELY (alloc_events))
936                 mono_profiler_allocation (obj);
937
938         return obj;
939 }
940
941 void*
942 mono_gc_alloc_pinned_obj (MonoVTable *vtable, size_t size)
943 {
944         MonoObject *obj = sgen_alloc_obj_pinned (vtable, size);
945
946         if (G_UNLIKELY (alloc_events))
947                 mono_profiler_allocation (obj);
948
949         return obj;
950 }
951
952 void*
953 mono_gc_alloc_mature (MonoVTable *vtable)
954 {
955         MonoObject *obj = sgen_alloc_obj_mature (vtable, vtable->klass->instance_size);
956
957         if (obj && G_UNLIKELY (obj->vtable->klass->has_finalize))
958                 mono_object_register_finalizer (obj);
959
960         if (G_UNLIKELY (alloc_events))
961                 mono_profiler_allocation (obj);
962
963         return obj;
964 }
965
966 void*
967 mono_gc_alloc_fixed (size_t size, MonoGCDescriptor descr, MonoGCRootSource source, const char *msg)
968 {
969         /* FIXME: do a single allocation */
970         void *res = calloc (1, size);
971         if (!res)
972                 return NULL;
973         if (!mono_gc_register_root (res, size, descr, source, msg)) {
974                 free (res);
975                 res = NULL;
976         }
977         return res;
978 }
979
980 void
981 mono_gc_free_fixed (void* addr)
982 {
983         mono_gc_deregister_root (addr);
984         free (addr);
985 }
986
987 /*
988  * Managed allocator
989  */
990
991 static MonoMethod* alloc_method_cache [ATYPE_NUM];
992 static MonoMethod* slowpath_alloc_method_cache [ATYPE_NUM];
993 static gboolean use_managed_allocator = TRUE;
994
995 #ifdef MANAGED_ALLOCATION
996
997 #ifdef HAVE_KW_THREAD
998
999 #define EMIT_TLS_ACCESS_NEXT_ADDR(mb)   do {    \
1000         mono_mb_emit_byte ((mb), MONO_CUSTOM_PREFIX);   \
1001         mono_mb_emit_byte ((mb), CEE_MONO_TLS);         \
1002         mono_mb_emit_i4 ((mb), TLS_KEY_SGEN_TLAB_NEXT_ADDR);            \
1003         } while (0)
1004
1005 #define EMIT_TLS_ACCESS_TEMP_END(mb)    do {    \
1006         mono_mb_emit_byte ((mb), MONO_CUSTOM_PREFIX);   \
1007         mono_mb_emit_byte ((mb), CEE_MONO_TLS);         \
1008         mono_mb_emit_i4 ((mb), TLS_KEY_SGEN_TLAB_TEMP_END);             \
1009         } while (0)
1010
1011 #else
1012
1013 #if defined(TARGET_OSX) || defined(TARGET_WIN32) || defined(TARGET_ANDROID) || defined(TARGET_IOS)
1014 #define EMIT_TLS_ACCESS_NEXT_ADDR(mb)   do {    \
1015         mono_mb_emit_byte ((mb), MONO_CUSTOM_PREFIX);   \
1016         mono_mb_emit_byte ((mb), CEE_MONO_TLS);         \
1017         mono_mb_emit_i4 ((mb), TLS_KEY_SGEN_THREAD_INFO);       \
1018         mono_mb_emit_icon ((mb), MONO_STRUCT_OFFSET (SgenThreadInfo, tlab_next_addr));  \
1019         mono_mb_emit_byte ((mb), CEE_ADD);              \
1020         mono_mb_emit_byte ((mb), CEE_LDIND_I);          \
1021         } while (0)
1022
1023 #define EMIT_TLS_ACCESS_TEMP_END(mb)    do {    \
1024         mono_mb_emit_byte ((mb), MONO_CUSTOM_PREFIX);   \
1025         mono_mb_emit_byte ((mb), CEE_MONO_TLS);         \
1026         mono_mb_emit_i4 ((mb), TLS_KEY_SGEN_THREAD_INFO);       \
1027         mono_mb_emit_icon ((mb), MONO_STRUCT_OFFSET (SgenThreadInfo, tlab_temp_end));   \
1028         mono_mb_emit_byte ((mb), CEE_ADD);              \
1029         mono_mb_emit_byte ((mb), CEE_LDIND_I);          \
1030         } while (0)
1031
1032 #else
1033 #define EMIT_TLS_ACCESS_NEXT_ADDR(mb)   do { g_error ("sgen is not supported when using --with-tls=pthread.\n"); } while (0)
1034 #define EMIT_TLS_ACCESS_TEMP_END(mb)    do { g_error ("sgen is not supported when using --with-tls=pthread.\n"); } while (0)
1035 #endif
1036
1037 #endif
1038
1039 /* FIXME: Do this in the JIT, where specialized allocation sequences can be created
1040  * for each class. This is currently not easy to do, as it is hard to generate basic 
1041  * blocks + branches, but it is easy with the linear IL codebase.
1042  *
1043  * For this to work we'd need to solve the TLAB race, first.  Now we
1044  * require the allocator to be in a few known methods to make sure
1045  * that they are executed atomically via the restart mechanism.
1046  */
1047 static MonoMethod*
1048 create_allocator (int atype, gboolean slowpath)
1049 {
1050         int p_var, size_var;
1051         guint32 slowpath_branch, max_size_branch;
1052         MonoMethodBuilder *mb;
1053         MonoMethod *res;
1054         MonoMethodSignature *csig;
1055         static gboolean registered = FALSE;
1056         int tlab_next_addr_var, new_next_var;
1057         const char *name = NULL;
1058         AllocatorWrapperInfo *info;
1059         int num_params, i;
1060
1061         if (!registered) {
1062                 mono_register_jit_icall (mono_gc_alloc_obj, "mono_gc_alloc_obj", mono_create_icall_signature ("object ptr int"), FALSE);
1063                 mono_register_jit_icall (mono_gc_alloc_vector, "mono_gc_alloc_vector", mono_create_icall_signature ("object ptr int int"), FALSE);
1064                 mono_register_jit_icall (mono_gc_alloc_string, "mono_gc_alloc_string", mono_create_icall_signature ("object ptr int int32"), FALSE);
1065                 registered = TRUE;
1066         }
1067
1068         if (atype == ATYPE_SMALL) {
1069                 name = slowpath ? "SlowAllocSmall" : "AllocSmall";
1070         } else if (atype == ATYPE_NORMAL) {
1071                 name = slowpath ? "SlowAlloc" : "Alloc";
1072         } else if (atype == ATYPE_VECTOR) {
1073                 name = slowpath ? "SlowAllocVector" : "AllocVector";
1074         } else if (atype == ATYPE_STRING) {
1075                 name = slowpath ? "SlowAllocString" : "AllocString";
1076         } else {
1077                 g_assert_not_reached ();
1078         }
1079
1080         if (atype == ATYPE_NORMAL)
1081                 num_params = 1;
1082         else
1083                 num_params = 2;
1084
1085         csig = mono_metadata_signature_alloc (mono_defaults.corlib, num_params);
1086         if (atype == ATYPE_STRING) {
1087                 csig->ret = &mono_defaults.string_class->byval_arg;
1088                 csig->params [0] = &mono_defaults.int_class->byval_arg;
1089                 csig->params [1] = &mono_defaults.int32_class->byval_arg;
1090         } else {
1091                 csig->ret = &mono_defaults.object_class->byval_arg;
1092                 for (i = 0; i < num_params; i++)
1093                         csig->params [i] = &mono_defaults.int_class->byval_arg;
1094         }
1095
1096         mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_ALLOC);
1097
1098 #ifndef DISABLE_JIT
1099         if (slowpath) {
1100                 switch (atype) {
1101                 case ATYPE_NORMAL:
1102                 case ATYPE_SMALL:
1103                         mono_mb_emit_ldarg (mb, 0);
1104                         mono_mb_emit_icall (mb, mono_object_new_specific);
1105                         break;
1106                 case ATYPE_VECTOR:
1107                         mono_mb_emit_ldarg (mb, 0);
1108                         mono_mb_emit_ldarg (mb, 1);
1109                         mono_mb_emit_icall (mb, mono_array_new_specific);
1110                         break;
1111                 case ATYPE_STRING:
1112                         mono_mb_emit_ldarg (mb, 1);
1113                         mono_mb_emit_icall (mb, mono_string_alloc);
1114                         break;
1115                 default:
1116                         g_assert_not_reached ();
1117                 }
1118
1119                 goto done;
1120         }
1121
1122         size_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
1123         if (atype == ATYPE_SMALL) {
1124                 /* size_var = size_arg */
1125                 mono_mb_emit_ldarg (mb, 1);
1126                 mono_mb_emit_stloc (mb, size_var);
1127         } else if (atype == ATYPE_NORMAL) {
1128                 /* size = vtable->klass->instance_size; */
1129                 mono_mb_emit_ldarg (mb, 0);
1130                 mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoVTable, klass));
1131                 mono_mb_emit_byte (mb, CEE_ADD);
1132                 mono_mb_emit_byte (mb, CEE_LDIND_I);
1133                 mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoClass, instance_size));
1134                 mono_mb_emit_byte (mb, CEE_ADD);
1135                 /* FIXME: assert instance_size stays a 4 byte integer */
1136                 mono_mb_emit_byte (mb, CEE_LDIND_U4);
1137                 mono_mb_emit_byte (mb, CEE_CONV_I);
1138                 mono_mb_emit_stloc (mb, size_var);
1139         } else if (atype == ATYPE_VECTOR) {
1140                 MonoExceptionClause *clause;
1141                 int pos, pos_leave, pos_error;
1142                 MonoClass *oom_exc_class;
1143                 MonoMethod *ctor;
1144
1145                 /*
1146                  * n > MONO_ARRAY_MAX_INDEX => OutOfMemoryException
1147                  * n < 0                    => OverflowException
1148                  *
1149                  * We can do an unsigned comparison to catch both cases, then in the error
1150                  * case compare signed to distinguish between them.
1151                  */
1152                 mono_mb_emit_ldarg (mb, 1);
1153                 mono_mb_emit_icon (mb, MONO_ARRAY_MAX_INDEX);
1154                 mono_mb_emit_byte (mb, CEE_CONV_U);
1155                 pos = mono_mb_emit_short_branch (mb, CEE_BLE_UN_S);
1156
1157                 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
1158                 mono_mb_emit_byte (mb, CEE_MONO_NOT_TAKEN);
1159                 mono_mb_emit_ldarg (mb, 1);
1160                 mono_mb_emit_icon (mb, 0);
1161                 pos_error = mono_mb_emit_short_branch (mb, CEE_BLT_S);
1162                 mono_mb_emit_exception (mb, "OutOfMemoryException", NULL);
1163                 mono_mb_patch_short_branch (mb, pos_error);
1164                 mono_mb_emit_exception (mb, "OverflowException", NULL);
1165
1166                 mono_mb_patch_short_branch (mb, pos);
1167
1168                 clause = mono_image_alloc0 (mono_defaults.corlib, sizeof (MonoExceptionClause));
1169                 clause->try_offset = mono_mb_get_label (mb);
1170
1171                 /* vtable->klass->sizes.element_size */
1172                 mono_mb_emit_ldarg (mb, 0);
1173                 mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoVTable, klass));
1174                 mono_mb_emit_byte (mb, CEE_ADD);
1175                 mono_mb_emit_byte (mb, CEE_LDIND_I);
1176                 mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoClass, sizes));
1177                 mono_mb_emit_byte (mb, CEE_ADD);
1178                 mono_mb_emit_byte (mb, CEE_LDIND_U4);
1179                 mono_mb_emit_byte (mb, CEE_CONV_I);
1180
1181                 /* * n */
1182                 mono_mb_emit_ldarg (mb, 1);
1183                 mono_mb_emit_byte (mb, CEE_MUL_OVF_UN);
1184                 /* + sizeof (MonoArray) */
1185                 mono_mb_emit_icon (mb, sizeof (MonoArray));
1186                 mono_mb_emit_byte (mb, CEE_ADD_OVF_UN);
1187                 mono_mb_emit_stloc (mb, size_var);
1188
1189                 pos_leave = mono_mb_emit_branch (mb, CEE_LEAVE);
1190
1191                 /* catch */
1192                 clause->flags = MONO_EXCEPTION_CLAUSE_NONE;
1193                 clause->try_len = mono_mb_get_pos (mb) - clause->try_offset;
1194                 clause->data.catch_class = mono_class_from_name (mono_defaults.corlib,
1195                                 "System", "OverflowException");
1196                 g_assert (clause->data.catch_class);
1197                 clause->handler_offset = mono_mb_get_label (mb);
1198
1199                 oom_exc_class = mono_class_from_name (mono_defaults.corlib,
1200                                 "System", "OutOfMemoryException");
1201                 g_assert (oom_exc_class);
1202                 ctor = mono_class_get_method_from_name (oom_exc_class, ".ctor", 0);
1203                 g_assert (ctor);
1204
1205                 mono_mb_emit_byte (mb, CEE_POP);
1206                 mono_mb_emit_op (mb, CEE_NEWOBJ, ctor);
1207                 mono_mb_emit_byte (mb, CEE_THROW);
1208
1209                 clause->handler_len = mono_mb_get_pos (mb) - clause->handler_offset;
1210                 mono_mb_set_clauses (mb, 1, clause);
1211                 mono_mb_patch_branch (mb, pos_leave);
1212                 /* end catch */
1213         } else if (atype == ATYPE_STRING) {
1214                 int pos;
1215
1216                 /*
1217                  * a string allocator method takes the args: (vtable, len)
1218                  *
1219                  * bytes = offsetof (MonoString, chars) + ((len + 1) * 2)
1220                  *
1221                  * condition:
1222                  *
1223                  * bytes <= INT32_MAX - (SGEN_ALLOC_ALIGN - 1)
1224                  *
1225                  * therefore:
1226                  *
1227                  * offsetof (MonoString, chars) + ((len + 1) * 2) <= INT32_MAX - (SGEN_ALLOC_ALIGN - 1)
1228                  * len <= (INT32_MAX - (SGEN_ALLOC_ALIGN - 1) - offsetof (MonoString, chars)) / 2 - 1
1229                  */
1230                 mono_mb_emit_ldarg (mb, 1);
1231                 mono_mb_emit_icon (mb, (INT32_MAX - (SGEN_ALLOC_ALIGN - 1) - MONO_STRUCT_OFFSET (MonoString, chars)) / 2 - 1);
1232                 pos = mono_mb_emit_short_branch (mb, MONO_CEE_BLE_UN_S);
1233
1234                 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
1235                 mono_mb_emit_byte (mb, CEE_MONO_NOT_TAKEN);
1236                 mono_mb_emit_exception (mb, "OutOfMemoryException", NULL);
1237                 mono_mb_patch_short_branch (mb, pos);
1238
1239                 mono_mb_emit_ldarg (mb, 1);
1240                 mono_mb_emit_icon (mb, 1);
1241                 mono_mb_emit_byte (mb, MONO_CEE_SHL);
1242                 //WE manually fold the above + 2 here
1243                 mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoString, chars) + 2);
1244                 mono_mb_emit_byte (mb, CEE_ADD);
1245                 mono_mb_emit_stloc (mb, size_var);
1246         } else {
1247                 g_assert_not_reached ();
1248         }
1249
1250         if (atype != ATYPE_SMALL) {
1251                 /* size += ALLOC_ALIGN - 1; */
1252                 mono_mb_emit_ldloc (mb, size_var);
1253                 mono_mb_emit_icon (mb, SGEN_ALLOC_ALIGN - 1);
1254                 mono_mb_emit_byte (mb, CEE_ADD);
1255                 /* size &= ~(ALLOC_ALIGN - 1); */
1256                 mono_mb_emit_icon (mb, ~(SGEN_ALLOC_ALIGN - 1));
1257                 mono_mb_emit_byte (mb, CEE_AND);
1258                 mono_mb_emit_stloc (mb, size_var);
1259         }
1260
1261         /* if (size > MAX_SMALL_OBJ_SIZE) goto slowpath */
1262         if (atype != ATYPE_SMALL) {
1263                 mono_mb_emit_ldloc (mb, size_var);
1264                 mono_mb_emit_icon (mb, SGEN_MAX_SMALL_OBJ_SIZE);
1265                 max_size_branch = mono_mb_emit_short_branch (mb, MONO_CEE_BGT_UN_S);
1266         }
1267
1268         /*
1269          * We need to modify tlab_next, but the JIT only supports reading, so we read
1270          * another tls var holding its address instead.
1271          */
1272
1273         /* tlab_next_addr (local) = tlab_next_addr (TLS var) */
1274         tlab_next_addr_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
1275         EMIT_TLS_ACCESS_NEXT_ADDR (mb);
1276         mono_mb_emit_stloc (mb, tlab_next_addr_var);
1277
1278         /* p = (void**)tlab_next; */
1279         p_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
1280         mono_mb_emit_ldloc (mb, tlab_next_addr_var);
1281         mono_mb_emit_byte (mb, CEE_LDIND_I);
1282         mono_mb_emit_stloc (mb, p_var);
1283         
1284         /* new_next = (char*)p + size; */
1285         new_next_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
1286         mono_mb_emit_ldloc (mb, p_var);
1287         mono_mb_emit_ldloc (mb, size_var);
1288         mono_mb_emit_byte (mb, CEE_CONV_I);
1289         mono_mb_emit_byte (mb, CEE_ADD);
1290         mono_mb_emit_stloc (mb, new_next_var);
1291
1292         /* if (G_LIKELY (new_next < tlab_temp_end)) */
1293         mono_mb_emit_ldloc (mb, new_next_var);
1294         EMIT_TLS_ACCESS_TEMP_END (mb);
1295         slowpath_branch = mono_mb_emit_short_branch (mb, MONO_CEE_BLT_UN_S);
1296
1297         /* Slowpath */
1298         if (atype != ATYPE_SMALL)
1299                 mono_mb_patch_short_branch (mb, max_size_branch);
1300
1301         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
1302         mono_mb_emit_byte (mb, CEE_MONO_NOT_TAKEN);
1303
1304         /* FIXME: mono_gc_alloc_obj takes a 'size_t' as an argument, not an int32 */
1305         mono_mb_emit_ldarg (mb, 0);
1306         mono_mb_emit_ldloc (mb, size_var);
1307         if (atype == ATYPE_NORMAL || atype == ATYPE_SMALL) {
1308                 mono_mb_emit_icall (mb, mono_gc_alloc_obj);
1309         } else if (atype == ATYPE_VECTOR) {
1310                 mono_mb_emit_ldarg (mb, 1);
1311                 mono_mb_emit_icall (mb, mono_gc_alloc_vector);
1312         } else if (atype == ATYPE_STRING) {
1313                 mono_mb_emit_ldarg (mb, 1);
1314                 mono_mb_emit_icall (mb, mono_gc_alloc_string);
1315         } else {
1316                 g_assert_not_reached ();
1317         }
1318         mono_mb_emit_byte (mb, CEE_RET);
1319
1320         /* Fastpath */
1321         mono_mb_patch_short_branch (mb, slowpath_branch);
1322
1323         /* FIXME: Memory barrier */
1324
1325         /* tlab_next = new_next */
1326         mono_mb_emit_ldloc (mb, tlab_next_addr_var);
1327         mono_mb_emit_ldloc (mb, new_next_var);
1328         mono_mb_emit_byte (mb, CEE_STIND_I);
1329
1330         /*The tlab store must be visible before the the vtable store. This could be replaced with a DDS but doing it with IL would be tricky. */
1331         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
1332         mono_mb_emit_byte (mb, CEE_MONO_MEMORY_BARRIER);
1333         mono_mb_emit_i4 (mb, MONO_MEMORY_BARRIER_REL);
1334
1335         /* *p = vtable; */
1336         mono_mb_emit_ldloc (mb, p_var);
1337         mono_mb_emit_ldarg (mb, 0);
1338         mono_mb_emit_byte (mb, CEE_STIND_I);
1339
1340         if (atype == ATYPE_VECTOR) {
1341                 /* arr->max_length = max_length; */
1342                 mono_mb_emit_ldloc (mb, p_var);
1343                 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoArray, max_length));
1344                 mono_mb_emit_ldarg (mb, 1);
1345 #ifdef MONO_BIG_ARRAYS
1346                 mono_mb_emit_byte (mb, CEE_STIND_I);
1347 #else
1348                 mono_mb_emit_byte (mb, CEE_STIND_I4);
1349 #endif
1350         } else  if (atype == ATYPE_STRING) {
1351                 /* need to set length and clear the last char */
1352                 /* s->length = len; */
1353                 mono_mb_emit_ldloc (mb, p_var);
1354                 mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoString, length));
1355                 mono_mb_emit_byte (mb, MONO_CEE_ADD);
1356                 mono_mb_emit_ldarg (mb, 1);
1357                 mono_mb_emit_byte (mb, MONO_CEE_STIND_I4);
1358                 /* s->chars [len] = 0; */
1359                 mono_mb_emit_ldloc (mb, p_var);
1360                 mono_mb_emit_ldloc (mb, size_var);
1361                 mono_mb_emit_icon (mb, 2);
1362                 mono_mb_emit_byte (mb, MONO_CEE_SUB);
1363                 mono_mb_emit_byte (mb, MONO_CEE_ADD);
1364                 mono_mb_emit_icon (mb, 0);
1365                 mono_mb_emit_byte (mb, MONO_CEE_STIND_I2);
1366         }
1367
1368         /*
1369         We must make sure both vtable and max_length are globaly visible before returning to managed land.
1370         */
1371         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
1372         mono_mb_emit_byte (mb, CEE_MONO_MEMORY_BARRIER);
1373         mono_mb_emit_i4 (mb, MONO_MEMORY_BARRIER_REL);
1374
1375         /* return p */
1376         mono_mb_emit_ldloc (mb, p_var);
1377
1378  done:
1379         mono_mb_emit_byte (mb, CEE_RET);
1380 #endif
1381
1382         res = mono_mb_create_method (mb, csig, 8);
1383         mono_mb_free (mb);
1384 #ifndef DISABLE_JIT
1385         mono_method_get_header (res)->init_locals = FALSE;
1386 #endif
1387
1388         info = mono_image_alloc0 (mono_defaults.corlib, sizeof (AllocatorWrapperInfo));
1389         info->gc_name = "sgen";
1390         info->alloc_type = atype;
1391         mono_marshal_set_wrapper_info (res, info);
1392
1393         return res;
1394 }
1395 #endif
1396
1397 int
1398 mono_gc_get_aligned_size_for_allocator (int size)
1399 {
1400         int aligned_size = size;
1401         aligned_size += SGEN_ALLOC_ALIGN - 1;
1402         aligned_size &= ~(SGEN_ALLOC_ALIGN - 1);
1403         return aligned_size;
1404 }
1405
1406 /*
1407  * Generate an allocator method implementing the fast path of mono_gc_alloc_obj ().
1408  * The signature of the called method is:
1409  *      object allocate (MonoVTable *vtable)
1410  */
1411 MonoMethod*
1412 mono_gc_get_managed_allocator (MonoClass *klass, gboolean for_box, gboolean known_instance_size)
1413 {
1414 #ifdef MANAGED_ALLOCATION
1415         if (collect_before_allocs)
1416                 return NULL;
1417         if (!mono_runtime_has_tls_get ())
1418                 return NULL;
1419         if (klass->instance_size > tlab_size)
1420                 return NULL;
1421         if (known_instance_size && ALIGN_TO (klass->instance_size, SGEN_ALLOC_ALIGN) >= SGEN_MAX_SMALL_OBJ_SIZE)
1422                 return NULL;
1423         if (mono_class_has_finalizer (klass) || mono_class_is_marshalbyref (klass) || (mono_profiler_get_events () & MONO_PROFILE_ALLOCATIONS))
1424                 return NULL;
1425         if (klass->rank)
1426                 return NULL;
1427         if (klass->byval_arg.type == MONO_TYPE_STRING)
1428                 return mono_gc_get_managed_allocator_by_type (ATYPE_STRING, FALSE);
1429         /* Generic classes have dynamic field and can go above MAX_SMALL_OBJ_SIZE. */
1430         if (known_instance_size)
1431                 return mono_gc_get_managed_allocator_by_type (ATYPE_SMALL, FALSE);
1432         else
1433                 return mono_gc_get_managed_allocator_by_type (ATYPE_NORMAL, FALSE);
1434 #else
1435         return NULL;
1436 #endif
1437 }
1438
1439 MonoMethod*
1440 mono_gc_get_managed_array_allocator (MonoClass *klass)
1441 {
1442 #ifdef MANAGED_ALLOCATION
1443         if (klass->rank != 1)
1444                 return NULL;
1445         if (!mono_runtime_has_tls_get ())
1446                 return NULL;
1447         if (mono_profiler_get_events () & MONO_PROFILE_ALLOCATIONS)
1448                 return NULL;
1449         if (has_per_allocation_action)
1450                 return NULL;
1451         g_assert (!mono_class_has_finalizer (klass) && !mono_class_is_marshalbyref (klass));
1452
1453         return mono_gc_get_managed_allocator_by_type (ATYPE_VECTOR, FALSE);
1454 #else
1455         return NULL;
1456 #endif
1457 }
1458
1459 void
1460 sgen_set_use_managed_allocator (gboolean flag)
1461 {
1462         use_managed_allocator = flag;
1463 }
1464
1465 MonoMethod*
1466 mono_gc_get_managed_allocator_by_type (int atype, gboolean slowpath)
1467 {
1468 #ifdef MANAGED_ALLOCATION
1469         MonoMethod *res;
1470         MonoMethod **cache = slowpath ? slowpath_alloc_method_cache : alloc_method_cache;
1471
1472         if (!use_managed_allocator)
1473                 return NULL;
1474
1475         if (!mono_runtime_has_tls_get ())
1476                 return NULL;
1477
1478         res = cache [atype];
1479         if (res)
1480                 return res;
1481
1482         res = create_allocator (atype, slowpath);
1483         LOCK_GC;
1484         if (cache [atype]) {
1485                 mono_free_method (res);
1486                 res = cache [atype];
1487         } else {
1488                 mono_memory_barrier ();
1489                 cache [atype] = res;
1490         }
1491         UNLOCK_GC;
1492
1493         return res;
1494 #else
1495         return NULL;
1496 #endif
1497 }
1498
1499 guint32
1500 mono_gc_get_managed_allocator_types (void)
1501 {
1502         return ATYPE_NUM;
1503 }
1504
1505 gboolean
1506 sgen_is_managed_allocator (MonoMethod *method)
1507 {
1508         int i;
1509
1510         for (i = 0; i < ATYPE_NUM; ++i)
1511                 if (method == alloc_method_cache [i] || method == slowpath_alloc_method_cache [i])
1512                         return TRUE;
1513         return FALSE;
1514 }
1515
1516 gboolean
1517 sgen_has_managed_allocator (void)
1518 {
1519         int i;
1520
1521         for (i = 0; i < ATYPE_NUM; ++i)
1522                 if (alloc_method_cache [i] || slowpath_alloc_method_cache [i])
1523                         return TRUE;
1524         return FALSE;
1525 }
1526
1527 /*
1528  * Cardtable scanning
1529  */
1530
1531 #define MWORD_MASK (sizeof (mword) - 1)
1532
1533 static inline int
1534 find_card_offset (mword card)
1535 {
1536 /*XXX Use assembly as this generates some pretty bad code */
1537 #if defined(__i386__) && defined(__GNUC__)
1538         return  (__builtin_ffs (card) - 1) / 8;
1539 #elif defined(__x86_64__) && defined(__GNUC__)
1540         return (__builtin_ffsll (card) - 1) / 8;
1541 #elif defined(__s390x__)
1542         return (__builtin_ffsll (GUINT64_TO_LE(card)) - 1) / 8;
1543 #else
1544         int i;
1545         guint8 *ptr = (guint8 *) &card;
1546         for (i = 0; i < sizeof (mword); ++i) {
1547                 if (ptr[i])
1548                         return i;
1549         }
1550         return 0;
1551 #endif
1552 }
1553
1554 static guint8*
1555 find_next_card (guint8 *card_data, guint8 *end)
1556 {
1557         mword *cards, *cards_end;
1558         mword card;
1559
1560         while ((((mword)card_data) & MWORD_MASK) && card_data < end) {
1561                 if (*card_data)
1562                         return card_data;
1563                 ++card_data;
1564         }
1565
1566         if (card_data == end)
1567                 return end;
1568
1569         cards = (mword*)card_data;
1570         cards_end = (mword*)((mword)end & ~MWORD_MASK);
1571         while (cards < cards_end) {
1572                 card = *cards;
1573                 if (card)
1574                         return (guint8*)cards + find_card_offset (card);
1575                 ++cards;
1576         }
1577
1578         card_data = (guint8*)cards_end;
1579         while (card_data < end) {
1580                 if (*card_data)
1581                         return card_data;
1582                 ++card_data;
1583         }
1584
1585         return end;
1586 }
1587
1588 #define ARRAY_OBJ_INDEX(ptr,array,elem_size) (((char*)(ptr) - ((char*)(array) + G_STRUCT_OFFSET (MonoArray, vector))) / (elem_size))
1589
1590 gboolean
1591 sgen_client_cardtable_scan_object (GCObject *obj, mword block_obj_size, guint8 *cards, gboolean mod_union, ScanCopyContext ctx)
1592 {
1593         MonoVTable *vt = SGEN_LOAD_VTABLE (obj);
1594         MonoClass *klass = vt->klass;
1595
1596         SGEN_ASSERT (0, SGEN_VTABLE_HAS_REFERENCES (vt), "Why would we ever call this on reference-free objects?");
1597
1598         if (vt->rank) {
1599                 MonoArray *arr = (MonoArray*)obj;
1600                 guint8 *card_data, *card_base;
1601                 guint8 *card_data_end;
1602                 char *obj_start = sgen_card_table_align_pointer (obj);
1603                 mword bounds_size;
1604                 mword obj_size = sgen_mono_array_size (vt, arr, &bounds_size, sgen_vtable_get_descriptor (vt));
1605                 /* We don't want to scan the bounds entries at the end of multidimensional arrays */
1606                 char *obj_end = (char*)obj + obj_size - bounds_size;
1607                 size_t card_count;
1608                 size_t extra_idx = 0;
1609
1610                 mword desc = (mword)klass->element_class->gc_descr;
1611                 int elem_size = mono_array_element_size (klass);
1612
1613 #ifdef SGEN_HAVE_OVERLAPPING_CARDS
1614                 guint8 *overflow_scan_end = NULL;
1615 #endif
1616
1617 #ifdef SGEN_OBJECT_LAYOUT_STATISTICS
1618                 if (klass->element_class->valuetype)
1619                         sgen_object_layout_scanned_vtype_array ();
1620                 else
1621                         sgen_object_layout_scanned_ref_array ();
1622 #endif
1623
1624                 if (cards)
1625                         card_data = cards;
1626                 else
1627                         card_data = sgen_card_table_get_card_scan_address ((mword)obj);
1628
1629                 card_base = card_data;
1630                 card_count = sgen_card_table_number_of_cards_in_range ((mword)obj, obj_size);
1631                 card_data_end = card_data + card_count;
1632
1633
1634 #ifdef SGEN_HAVE_OVERLAPPING_CARDS
1635                 /*Check for overflow and if so, setup to scan in two steps*/
1636                 if (!cards && card_data_end >= SGEN_SHADOW_CARDTABLE_END) {
1637                         overflow_scan_end = sgen_shadow_cardtable + (card_data_end - SGEN_SHADOW_CARDTABLE_END);
1638                         card_data_end = SGEN_SHADOW_CARDTABLE_END;
1639                 }
1640
1641 LOOP_HEAD:
1642 #endif
1643
1644                 card_data = find_next_card (card_data, card_data_end);
1645                 for (; card_data < card_data_end; card_data = find_next_card (card_data + 1, card_data_end)) {
1646                         size_t index;
1647                         size_t idx = (card_data - card_base) + extra_idx;
1648                         char *start = (char*)(obj_start + idx * CARD_SIZE_IN_BYTES);
1649                         char *card_end = start + CARD_SIZE_IN_BYTES;
1650                         char *first_elem, *elem;
1651
1652                         HEAVY_STAT (++los_marked_cards);
1653
1654                         if (!cards)
1655                                 sgen_card_table_prepare_card_for_scanning (card_data);
1656
1657                         card_end = MIN (card_end, obj_end);
1658
1659                         if (start <= (char*)arr->vector)
1660                                 index = 0;
1661                         else
1662                                 index = ARRAY_OBJ_INDEX (start, obj, elem_size);
1663
1664                         elem = first_elem = (char*)mono_array_addr_with_size_fast ((MonoArray*)obj, elem_size, index);
1665                         if (klass->element_class->valuetype) {
1666                                 ScanVTypeFunc scan_vtype_func = ctx.ops->scan_vtype;
1667
1668                                 for (; elem < card_end; elem += elem_size)
1669                                         scan_vtype_func (obj, elem, desc, ctx.queue BINARY_PROTOCOL_ARG (elem_size));
1670                         } else {
1671                                 CopyOrMarkObjectFunc copy_func = ctx.ops->copy_or_mark_object;
1672
1673                                 HEAVY_STAT (++los_array_cards);
1674                                 for (; elem < card_end; elem += SIZEOF_VOID_P) {
1675                                         gpointer new, old = *(gpointer*)elem;
1676                                         if ((mod_union && old) || G_UNLIKELY (sgen_ptr_in_nursery (old))) {
1677                                                 HEAVY_STAT (++los_array_remsets);
1678                                                 copy_func ((GCObject**)elem, ctx.queue);
1679                                                 new = *(gpointer*)elem;
1680                                                 if (G_UNLIKELY (sgen_ptr_in_nursery (new)))
1681                                                         sgen_add_to_global_remset (elem, new);
1682                                         }
1683                                 }
1684                         }
1685
1686                         binary_protocol_card_scan (first_elem, elem - first_elem);
1687                 }
1688
1689 #ifdef SGEN_HAVE_OVERLAPPING_CARDS
1690                 if (overflow_scan_end) {
1691                         extra_idx = card_data - card_base;
1692                         card_base = card_data = sgen_shadow_cardtable;
1693                         card_data_end = overflow_scan_end;
1694                         overflow_scan_end = NULL;
1695                         goto LOOP_HEAD;
1696                 }
1697 #endif
1698                 return TRUE;
1699         }
1700
1701         return FALSE;
1702 }
1703
1704 /*
1705  * Array and string allocation
1706  */
1707
1708 void*
1709 mono_gc_alloc_vector (MonoVTable *vtable, size_t size, uintptr_t max_length)
1710 {
1711         MonoArray *arr;
1712         TLAB_ACCESS_INIT;
1713
1714         if (!SGEN_CAN_ALIGN_UP (size))
1715                 return NULL;
1716
1717 #ifndef DISABLE_CRITICAL_REGION
1718         ENTER_CRITICAL_REGION;
1719         arr = (MonoArray*)sgen_try_alloc_obj_nolock (vtable, size);
1720         if (arr) {
1721                 /*This doesn't require fencing since EXIT_CRITICAL_REGION already does it for us*/
1722                 arr->max_length = (mono_array_size_t)max_length;
1723                 EXIT_CRITICAL_REGION;
1724                 goto done;
1725         }
1726         EXIT_CRITICAL_REGION;
1727 #endif
1728
1729         LOCK_GC;
1730
1731         arr = (MonoArray*)sgen_alloc_obj_nolock (vtable, size);
1732         if (G_UNLIKELY (!arr)) {
1733                 UNLOCK_GC;
1734                 return mono_gc_out_of_memory (size);
1735         }
1736
1737         arr->max_length = (mono_array_size_t)max_length;
1738
1739         UNLOCK_GC;
1740
1741  done:
1742         if (G_UNLIKELY (alloc_events))
1743                 mono_profiler_allocation (&arr->obj);
1744
1745         SGEN_ASSERT (6, SGEN_ALIGN_UP (size) == SGEN_ALIGN_UP (sgen_client_par_object_get_size (vtable, (GCObject*)arr)), "Vector has incorrect size.");
1746         return arr;
1747 }
1748
1749 void*
1750 mono_gc_alloc_array (MonoVTable *vtable, size_t size, uintptr_t max_length, uintptr_t bounds_size)
1751 {
1752         MonoArray *arr;
1753         MonoArrayBounds *bounds;
1754         TLAB_ACCESS_INIT;
1755
1756         if (!SGEN_CAN_ALIGN_UP (size))
1757                 return NULL;
1758
1759 #ifndef DISABLE_CRITICAL_REGION
1760         ENTER_CRITICAL_REGION;
1761         arr = (MonoArray*)sgen_try_alloc_obj_nolock (vtable, size);
1762         if (arr) {
1763                 /*This doesn't require fencing since EXIT_CRITICAL_REGION already does it for us*/
1764                 arr->max_length = (mono_array_size_t)max_length;
1765
1766                 bounds = (MonoArrayBounds*)((char*)arr + size - bounds_size);
1767                 arr->bounds = bounds;
1768                 EXIT_CRITICAL_REGION;
1769                 goto done;
1770         }
1771         EXIT_CRITICAL_REGION;
1772 #endif
1773
1774         LOCK_GC;
1775
1776         arr = (MonoArray*)sgen_alloc_obj_nolock (vtable, size);
1777         if (G_UNLIKELY (!arr)) {
1778                 UNLOCK_GC;
1779                 return mono_gc_out_of_memory (size);
1780         }
1781
1782         arr->max_length = (mono_array_size_t)max_length;
1783
1784         bounds = (MonoArrayBounds*)((char*)arr + size - bounds_size);
1785         arr->bounds = bounds;
1786
1787         UNLOCK_GC;
1788
1789  done:
1790         if (G_UNLIKELY (alloc_events))
1791                 mono_profiler_allocation (&arr->obj);
1792
1793         SGEN_ASSERT (6, SGEN_ALIGN_UP (size) == SGEN_ALIGN_UP (sgen_client_par_object_get_size (vtable, (GCObject*)arr)), "Array has incorrect size.");
1794         return arr;
1795 }
1796
1797 void*
1798 mono_gc_alloc_string (MonoVTable *vtable, size_t size, gint32 len)
1799 {
1800         MonoString *str;
1801         TLAB_ACCESS_INIT;
1802
1803         if (!SGEN_CAN_ALIGN_UP (size))
1804                 return NULL;
1805
1806 #ifndef DISABLE_CRITICAL_REGION
1807         ENTER_CRITICAL_REGION;
1808         str = (MonoString*)sgen_try_alloc_obj_nolock (vtable, size);
1809         if (str) {
1810                 /*This doesn't require fencing since EXIT_CRITICAL_REGION already does it for us*/
1811                 str->length = len;
1812                 EXIT_CRITICAL_REGION;
1813                 goto done;
1814         }
1815         EXIT_CRITICAL_REGION;
1816 #endif
1817
1818         LOCK_GC;
1819
1820         str = (MonoString*)sgen_alloc_obj_nolock (vtable, size);
1821         if (G_UNLIKELY (!str)) {
1822                 UNLOCK_GC;
1823                 return mono_gc_out_of_memory (size);
1824         }
1825
1826         str->length = len;
1827
1828         UNLOCK_GC;
1829
1830  done:
1831         if (G_UNLIKELY (alloc_events))
1832                 mono_profiler_allocation (&str->object);
1833
1834         return str;
1835 }
1836
1837 /*
1838  * Strings
1839  */
1840
1841 void
1842 mono_gc_set_string_length (MonoString *str, gint32 new_length)
1843 {
1844         mono_unichar2 *new_end = str->chars + new_length;
1845
1846         /* zero the discarded string. This null-delimits the string and allows
1847          * the space to be reclaimed by SGen. */
1848
1849         if (nursery_canaries_enabled () && sgen_ptr_in_nursery (str)) {
1850                 CHECK_CANARY_FOR_OBJECT ((GCObject*)str, TRUE);
1851                 memset (new_end, 0, (str->length - new_length + 1) * sizeof (mono_unichar2) + CANARY_SIZE);
1852                 memcpy (new_end + 1 , CANARY_STRING, CANARY_SIZE);
1853         } else {
1854                 memset (new_end, 0, (str->length - new_length + 1) * sizeof (mono_unichar2));
1855         }
1856
1857         str->length = new_length;
1858 }
1859
1860 /*
1861  * Profiling
1862  */
1863
1864 #define GC_ROOT_NUM 32
1865 typedef struct {
1866         int count;              /* must be the first field */
1867         void *objects [GC_ROOT_NUM];
1868         int root_types [GC_ROOT_NUM];
1869         uintptr_t extra_info [GC_ROOT_NUM];
1870 } GCRootReport;
1871
1872 static void
1873 notify_gc_roots (GCRootReport *report)
1874 {
1875         if (!report->count)
1876                 return;
1877         mono_profiler_gc_roots (report->count, report->objects, report->root_types, report->extra_info);
1878         report->count = 0;
1879 }
1880
1881 static void
1882 add_profile_gc_root (GCRootReport *report, void *object, int rtype, uintptr_t extra_info)
1883 {
1884         if (report->count == GC_ROOT_NUM)
1885                 notify_gc_roots (report);
1886         report->objects [report->count] = object;
1887         report->root_types [report->count] = rtype;
1888         report->extra_info [report->count++] = (uintptr_t)SGEN_LOAD_VTABLE (object)->klass;
1889 }
1890
1891 void
1892 sgen_client_nursery_objects_pinned (void **definitely_pinned, int count)
1893 {
1894         if (mono_profiler_get_events () & MONO_PROFILE_GC_ROOTS) {
1895                 GCRootReport report;
1896                 int idx;
1897                 report.count = 0;
1898                 for (idx = 0; idx < count; ++idx)
1899                         add_profile_gc_root (&report, definitely_pinned [idx], MONO_PROFILE_GC_ROOT_PINNING | MONO_PROFILE_GC_ROOT_MISC, 0);
1900                 notify_gc_roots (&report);
1901         }
1902 }
1903
1904 static void
1905 report_finalizer_roots_from_queue (SgenPointerQueue *queue)
1906 {
1907         GCRootReport report;
1908         size_t i;
1909
1910         report.count = 0;
1911         for (i = 0; i < queue->next_slot; ++i) {
1912                 void *obj = queue->data [i];
1913                 if (!obj)
1914                         continue;
1915                 add_profile_gc_root (&report, obj, MONO_PROFILE_GC_ROOT_FINALIZER, 0);
1916         }
1917         notify_gc_roots (&report);
1918 }
1919
1920 static void
1921 report_finalizer_roots (SgenPointerQueue *fin_ready_queue, SgenPointerQueue *critical_fin_queue)
1922 {
1923         report_finalizer_roots_from_queue (fin_ready_queue);
1924         report_finalizer_roots_from_queue (critical_fin_queue);
1925 }
1926
1927 static GCRootReport *root_report;
1928
1929 static void
1930 single_arg_report_root (MonoObject **obj, void *gc_data)
1931 {
1932         if (*obj)
1933                 add_profile_gc_root (root_report, *obj, MONO_PROFILE_GC_ROOT_OTHER, 0);
1934 }
1935
1936 static void
1937 precisely_report_roots_from (GCRootReport *report, void** start_root, void** end_root, mword desc)
1938 {
1939         switch (desc & ROOT_DESC_TYPE_MASK) {
1940         case ROOT_DESC_BITMAP:
1941                 desc >>= ROOT_DESC_TYPE_SHIFT;
1942                 while (desc) {
1943                         if ((desc & 1) && *start_root) {
1944                                 add_profile_gc_root (report, *start_root, MONO_PROFILE_GC_ROOT_OTHER, 0);
1945                         }
1946                         desc >>= 1;
1947                         start_root++;
1948                 }
1949                 return;
1950         case ROOT_DESC_COMPLEX: {
1951                 gsize *bitmap_data = sgen_get_complex_descriptor_bitmap (desc);
1952                 gsize bwords = (*bitmap_data) - 1;
1953                 void **start_run = start_root;
1954                 bitmap_data++;
1955                 while (bwords-- > 0) {
1956                         gsize bmap = *bitmap_data++;
1957                         void **objptr = start_run;
1958                         while (bmap) {
1959                                 if ((bmap & 1) && *objptr) {
1960                                         add_profile_gc_root (report, *objptr, MONO_PROFILE_GC_ROOT_OTHER, 0);
1961                                 }
1962                                 bmap >>= 1;
1963                                 ++objptr;
1964                         }
1965                         start_run += GC_BITS_PER_WORD;
1966                 }
1967                 break;
1968         }
1969         case ROOT_DESC_USER: {
1970                 MonoGCRootMarkFunc marker = (MonoGCRootMarkFunc)sgen_get_user_descriptor_func (desc);
1971                 root_report = report;
1972                 marker ((MonoObject**)start_root, single_arg_report_root, NULL);
1973                 break;
1974         }
1975         case ROOT_DESC_RUN_LEN:
1976                 g_assert_not_reached ();
1977         default:
1978                 g_assert_not_reached ();
1979         }
1980 }
1981
1982 static void
1983 report_registered_roots_by_type (int root_type)
1984 {
1985         GCRootReport report;
1986         void **start_root;
1987         RootRecord *root;
1988         report.count = 0;
1989         SGEN_HASH_TABLE_FOREACH (&roots_hash [root_type], start_root, root) {
1990                 SGEN_LOG (6, "Precise root scan %p-%p (desc: %p)", start_root, root->end_root, (void*)root->root_desc);
1991                 precisely_report_roots_from (&report, start_root, (void**)root->end_root, root->root_desc);
1992         } SGEN_HASH_TABLE_FOREACH_END;
1993         notify_gc_roots (&report);
1994 }
1995
1996 static void
1997 report_registered_roots (void)
1998 {
1999         report_registered_roots_by_type (ROOT_TYPE_NORMAL);
2000         report_registered_roots_by_type (ROOT_TYPE_WBARRIER);
2001 }
2002
2003 void
2004 sgen_client_collecting_minor (SgenPointerQueue *fin_ready_queue, SgenPointerQueue *critical_fin_queue)
2005 {
2006         if (mono_profiler_get_events () & MONO_PROFILE_GC_ROOTS)
2007                 report_registered_roots ();
2008         if (mono_profiler_get_events () & MONO_PROFILE_GC_ROOTS)
2009                 report_finalizer_roots (fin_ready_queue, critical_fin_queue);
2010 }
2011
2012 static GCRootReport major_root_report;
2013 static gboolean profile_roots;
2014
2015 void
2016 sgen_client_collecting_major_1 (void)
2017 {
2018         profile_roots = mono_profiler_get_events () & MONO_PROFILE_GC_ROOTS;
2019         memset (&major_root_report, 0, sizeof (GCRootReport));
2020 }
2021
2022 void
2023 sgen_client_pinned_los_object (GCObject *obj)
2024 {
2025         if (profile_roots)
2026                 add_profile_gc_root (&major_root_report, (char*)obj, MONO_PROFILE_GC_ROOT_PINNING | MONO_PROFILE_GC_ROOT_MISC, 0);
2027 }
2028
2029 void
2030 sgen_client_collecting_major_2 (void)
2031 {
2032         if (profile_roots)
2033                 notify_gc_roots (&major_root_report);
2034
2035         if (mono_profiler_get_events () & MONO_PROFILE_GC_ROOTS)
2036                 report_registered_roots ();
2037 }
2038
2039 void
2040 sgen_client_collecting_major_3 (SgenPointerQueue *fin_ready_queue, SgenPointerQueue *critical_fin_queue)
2041 {
2042         if (mono_profiler_get_events () & MONO_PROFILE_GC_ROOTS)
2043                 report_finalizer_roots (fin_ready_queue, critical_fin_queue);
2044 }
2045
2046 #define MOVED_OBJECTS_NUM 64
2047 static void *moved_objects [MOVED_OBJECTS_NUM];
2048 static int moved_objects_idx = 0;
2049
2050 void
2051 mono_sgen_register_moved_object (void *obj, void *destination)
2052 {
2053         g_assert (mono_profiler_events & MONO_PROFILE_GC_MOVES);
2054
2055         if (moved_objects_idx == MOVED_OBJECTS_NUM) {
2056                 mono_profiler_gc_moves (moved_objects, moved_objects_idx);
2057                 moved_objects_idx = 0;
2058         }
2059         moved_objects [moved_objects_idx++] = obj;
2060         moved_objects [moved_objects_idx++] = destination;
2061 }
2062
2063 void
2064 mono_sgen_gc_event_moves (void)
2065 {
2066         if (moved_objects_idx) {
2067                 mono_profiler_gc_moves (moved_objects, moved_objects_idx);
2068                 moved_objects_idx = 0;
2069         }
2070 }
2071
2072 /*
2073  * Heap walking
2074  */
2075
2076 #define REFS_SIZE 128
2077 typedef struct {
2078         void *data;
2079         MonoGCReferences callback;
2080         int flags;
2081         int count;
2082         int called;
2083         MonoObject *refs [REFS_SIZE];
2084         uintptr_t offsets [REFS_SIZE];
2085 } HeapWalkInfo;
2086
2087 #undef HANDLE_PTR
2088 #define HANDLE_PTR(ptr,obj)     do {    \
2089                 if (*(ptr)) {   \
2090                         if (hwi->count == REFS_SIZE) {  \
2091                                 hwi->callback ((MonoObject*)start, mono_object_class (start), hwi->called? 0: size, hwi->count, hwi->refs, hwi->offsets, hwi->data);    \
2092                                 hwi->count = 0; \
2093                                 hwi->called = 1;        \
2094                         }       \
2095                         hwi->offsets [hwi->count] = (char*)(ptr)-(char*)start;  \
2096                         hwi->refs [hwi->count++] = *(ptr);      \
2097                 }       \
2098         } while (0)
2099
2100 static void
2101 collect_references (HeapWalkInfo *hwi, GCObject *obj, size_t size)
2102 {
2103         char *start = (char*)obj;
2104         mword desc = sgen_obj_get_descriptor (obj);
2105
2106 #include "sgen/sgen-scan-object.h"
2107 }
2108
2109 static void
2110 walk_references (GCObject *start, size_t size, void *data)
2111 {
2112         HeapWalkInfo *hwi = data;
2113         hwi->called = 0;
2114         hwi->count = 0;
2115         collect_references (hwi, start, size);
2116         if (hwi->count || !hwi->called)
2117                 hwi->callback (start, mono_object_class (start), hwi->called? 0: size, hwi->count, hwi->refs, hwi->offsets, hwi->data);
2118 }
2119
2120 /**
2121  * mono_gc_walk_heap:
2122  * @flags: flags for future use
2123  * @callback: a function pointer called for each object in the heap
2124  * @data: a user data pointer that is passed to callback
2125  *
2126  * This function can be used to iterate over all the live objects in the heap:
2127  * for each object, @callback is invoked, providing info about the object's
2128  * location in memory, its class, its size and the objects it references.
2129  * For each referenced object it's offset from the object address is
2130  * reported in the offsets array.
2131  * The object references may be buffered, so the callback may be invoked
2132  * multiple times for the same object: in all but the first call, the size
2133  * argument will be zero.
2134  * Note that this function can be only called in the #MONO_GC_EVENT_PRE_START_WORLD
2135  * profiler event handler.
2136  *
2137  * Returns: a non-zero value if the GC doesn't support heap walking
2138  */
2139 int
2140 mono_gc_walk_heap (int flags, MonoGCReferences callback, void *data)
2141 {
2142         HeapWalkInfo hwi;
2143
2144         hwi.flags = flags;
2145         hwi.callback = callback;
2146         hwi.data = data;
2147
2148         sgen_clear_nursery_fragments ();
2149         sgen_scan_area_with_callback (nursery_section->data, nursery_section->end_data, walk_references, &hwi, FALSE, TRUE);
2150
2151         major_collector.iterate_objects (ITERATE_OBJECTS_SWEEP_ALL, walk_references, &hwi);
2152         sgen_los_iterate_objects (walk_references, &hwi);
2153
2154         return 0;
2155 }
2156
2157 /*
2158  * Threads
2159  */
2160
2161 void
2162 mono_gc_set_gc_callbacks (MonoGCCallbacks *callbacks)
2163 {
2164         gc_callbacks = *callbacks;
2165 }
2166
2167 MonoGCCallbacks *
2168 mono_gc_get_gc_callbacks ()
2169 {
2170         return &gc_callbacks;
2171 }
2172
2173 void
2174 sgen_client_thread_register (SgenThreadInfo* info, void *stack_bottom_fallback)
2175 {
2176         size_t stsize = 0;
2177         guint8 *staddr = NULL;
2178
2179 #ifndef HAVE_KW_THREAD
2180         g_assert (!mono_native_tls_get_value (thread_info_key));
2181         mono_native_tls_set_value (thread_info_key, info);
2182 #else
2183         sgen_thread_info = info;
2184 #endif
2185
2186         info->client_info.skip = 0;
2187         info->client_info.stopped_ip = NULL;
2188         info->client_info.stopped_domain = NULL;
2189
2190         info->client_info.stack_start = NULL;
2191
2192 #ifdef SGEN_POSIX_STW
2193         info->client_info.stop_count = -1;
2194         info->client_info.signal = 0;
2195 #endif
2196
2197         /* On win32, stack_start_limit should be 0, since the stack can grow dynamically */
2198         mono_thread_info_get_stack_bounds (&staddr, &stsize);
2199         if (staddr) {
2200 #ifndef HOST_WIN32
2201                 info->client_info.stack_start_limit = staddr;
2202 #endif
2203                 info->client_info.stack_end = staddr + stsize;
2204         } else {
2205                 gsize stack_bottom = (gsize)stack_bottom_fallback;
2206                 stack_bottom += 4095;
2207                 stack_bottom &= ~4095;
2208                 info->client_info.stack_end = (char*)stack_bottom;
2209         }
2210
2211 #ifdef USE_MONO_CTX
2212         memset (&info->client_info.ctx, 0, sizeof (MonoContext));
2213 #else
2214         memset (&info->client_info.regs, 0, sizeof (info->client_info.regs));
2215 #endif
2216
2217         if (mono_gc_get_gc_callbacks ()->thread_attach_func)
2218                 info->client_info.runtime_data = mono_gc_get_gc_callbacks ()->thread_attach_func ();
2219
2220         binary_protocol_thread_register ((gpointer)mono_thread_info_get_tid (info));
2221
2222         SGEN_LOG (3, "registered thread %p (%p) stack end %p", info, (gpointer)mono_thread_info_get_tid (info), info->client_info.stack_end);
2223 }
2224
2225 void
2226 sgen_client_thread_unregister (SgenThreadInfo *p)
2227 {
2228         MonoNativeThreadId tid;
2229
2230 #ifndef HAVE_KW_THREAD
2231         mono_native_tls_set_value (thread_info_key, NULL);
2232 #else
2233         sgen_thread_info = NULL;
2234 #endif
2235
2236         tid = mono_thread_info_get_tid (p);
2237
2238         if (p->client_info.info.runtime_thread)
2239                 mono_threads_add_joinable_thread ((gpointer)tid);
2240
2241         if (mono_gc_get_gc_callbacks ()->thread_detach_func) {
2242                 mono_gc_get_gc_callbacks ()->thread_detach_func (p->client_info.runtime_data);
2243                 p->client_info.runtime_data = NULL;
2244         }
2245
2246         binary_protocol_thread_unregister ((gpointer)tid);
2247         SGEN_LOG (3, "unregister thread %p (%p)", p, (gpointer)tid);
2248 }
2249
2250 void
2251 mono_gc_set_skip_thread (gboolean skip)
2252 {
2253         SgenThreadInfo *info = mono_thread_info_current ();
2254
2255         LOCK_GC;
2256         info->client_info.gc_disabled = skip;
2257         UNLOCK_GC;
2258 }
2259
2260 static gboolean
2261 is_critical_method (MonoMethod *method)
2262 {
2263         return mono_runtime_is_critical_method (method) || sgen_is_critical_method (method);
2264 }
2265
2266 static gboolean
2267 thread_in_critical_region (SgenThreadInfo *info)
2268 {
2269         return info->client_info.in_critical_region;
2270 }
2271
2272 static void
2273 sgen_thread_attach (SgenThreadInfo *info)
2274 {
2275         if (mono_gc_get_gc_callbacks ()->thread_attach_func && !info->client_info.runtime_data)
2276                 info->client_info.runtime_data = mono_gc_get_gc_callbacks ()->thread_attach_func ();
2277 }
2278
2279 static void
2280 sgen_thread_detach (SgenThreadInfo *p)
2281 {
2282         /* If a delegate is passed to native code and invoked on a thread we dont
2283          * know about, the jit will register it with mono_jit_thread_attach, but
2284          * we have no way of knowing when that thread goes away.  SGen has a TSD
2285          * so we assume that if the domain is still registered, we can detach
2286          * the thread
2287          */
2288         if (mono_domain_get ())
2289                 mono_thread_detach_internal (mono_thread_internal_current ());
2290 }
2291
2292 gboolean
2293 mono_gc_register_thread (void *baseptr)
2294 {
2295         return mono_thread_info_attach (baseptr) != NULL;
2296 }
2297
2298 gboolean
2299 mono_gc_is_gc_thread (void)
2300 {
2301         gboolean result;
2302         LOCK_GC;
2303         result = mono_thread_info_current () != NULL;
2304         UNLOCK_GC;
2305         return result;
2306 }
2307
2308 void
2309 sgen_client_thread_register_worker (void)
2310 {
2311         mono_thread_info_register_small_id ();
2312 }
2313
2314 /* Variables holding start/end nursery so it won't have to be passed at every call */
2315 static void *scan_area_arg_start, *scan_area_arg_end;
2316
2317 void
2318 mono_gc_conservatively_scan_area (void *start, void *end)
2319 {
2320         sgen_conservatively_pin_objects_from (start, end, scan_area_arg_start, scan_area_arg_end, PIN_TYPE_STACK);
2321 }
2322
2323 void*
2324 mono_gc_scan_object (void *obj, void *gc_data)
2325 {
2326         ScanCopyContext *ctx = gc_data;
2327         ctx->ops->copy_or_mark_object ((GCObject**)&obj, ctx->queue);
2328         return obj;
2329 }
2330
2331 /*
2332  * Mark from thread stacks and registers.
2333  */
2334 void
2335 sgen_client_scan_thread_data (void *start_nursery, void *end_nursery, gboolean precise, ScanCopyContext ctx)
2336 {
2337         SgenThreadInfo *info;
2338
2339         scan_area_arg_start = start_nursery;
2340         scan_area_arg_end = end_nursery;
2341
2342         FOREACH_THREAD (info) {
2343                 int skip_reason = 0;
2344                 if (info->client_info.skip) {
2345                         SGEN_LOG (3, "Skipping dead thread %p, range: %p-%p, size: %zd", info, info->client_info.stack_start, info->client_info.stack_end, (char*)info->client_info.stack_end - (char*)info->client_info.stack_start);
2346                         skip_reason = 1;
2347                 } else if (info->client_info.gc_disabled) {
2348                         SGEN_LOG (3, "GC disabled for thread %p, range: %p-%p, size: %zd", info, info->client_info.stack_start, info->client_info.stack_end, (char*)info->client_info.stack_end - (char*)info->client_info.stack_start);
2349                         skip_reason = 2;
2350                 } else if (!mono_thread_info_is_live (info)) {
2351                         SGEN_LOG (3, "Skipping non-running thread %p, range: %p-%p, size: %zd (state %x)", info, info->client_info.stack_start, info->client_info.stack_end, (char*)info->client_info.stack_end - (char*)info->client_info.stack_start, info->client_info.info.thread_state);
2352                         skip_reason = 3;
2353                 }
2354
2355                 binary_protocol_scan_stack ((gpointer)mono_thread_info_get_tid (info), info->client_info.stack_start, info->client_info.stack_end, skip_reason);
2356
2357                 if (skip_reason)
2358                         continue;
2359
2360                 g_assert (info->client_info.suspend_done);
2361                 SGEN_LOG (3, "Scanning thread %p, range: %p-%p, size: %zd, pinned=%zd", info, info->client_info.stack_start, info->client_info.stack_end, (char*)info->client_info.stack_end - (char*)info->client_info.stack_start, sgen_get_pinned_count ());
2362                 if (mono_gc_get_gc_callbacks ()->thread_mark_func && !conservative_stack_mark) {
2363                         mono_gc_get_gc_callbacks ()->thread_mark_func (info->client_info.runtime_data, info->client_info.stack_start, info->client_info.stack_end, precise, &ctx);
2364                 } else if (!precise) {
2365                         if (!conservative_stack_mark) {
2366                                 fprintf (stderr, "Precise stack mark not supported - disabling.\n");
2367                                 conservative_stack_mark = TRUE;
2368                         }
2369                         sgen_conservatively_pin_objects_from (info->client_info.stack_start, info->client_info.stack_end, start_nursery, end_nursery, PIN_TYPE_STACK);
2370                 }
2371
2372                 if (!precise) {
2373 #ifdef USE_MONO_CTX
2374                         sgen_conservatively_pin_objects_from ((void**)&info->client_info.ctx, (void**)&info->client_info.ctx + ARCH_NUM_REGS,
2375                                 start_nursery, end_nursery, PIN_TYPE_STACK);
2376 #else
2377                         sgen_conservatively_pin_objects_from ((void**)&info->client_info.regs, (void**)&info->client_info.regs + ARCH_NUM_REGS,
2378                                         start_nursery, end_nursery, PIN_TYPE_STACK);
2379 #endif
2380                 }
2381         } END_FOREACH_THREAD
2382 }
2383
2384 /*
2385  * mono_gc_set_stack_end:
2386  *
2387  *   Set the end of the current threads stack to STACK_END. The stack space between 
2388  * STACK_END and the real end of the threads stack will not be scanned during collections.
2389  */
2390 void
2391 mono_gc_set_stack_end (void *stack_end)
2392 {
2393         SgenThreadInfo *info;
2394
2395         LOCK_GC;
2396         info = mono_thread_info_current ();
2397         if (info) {
2398                 SGEN_ASSERT (0, stack_end < info->client_info.stack_end, "Can only lower stack end");
2399                 info->client_info.stack_end = stack_end;
2400         }
2401         UNLOCK_GC;
2402 }
2403
2404 /*
2405  * Roots
2406  */
2407
2408 int
2409 mono_gc_register_root (char *start, size_t size, MonoGCDescriptor descr, MonoGCRootSource source, const char *msg)
2410 {
2411         return sgen_register_root (start, size, descr, descr ? ROOT_TYPE_NORMAL : ROOT_TYPE_PINNED, source, msg);
2412 }
2413
2414 int
2415 mono_gc_register_root_wbarrier (char *start, size_t size, MonoGCDescriptor descr, MonoGCRootSource source, const char *msg)
2416 {
2417         return sgen_register_root (start, size, descr, ROOT_TYPE_WBARRIER, source, msg);
2418 }
2419
2420 void
2421 mono_gc_deregister_root (char* addr)
2422 {
2423         sgen_deregister_root (addr);
2424 }
2425
2426 /*
2427  * PThreads
2428  */
2429
2430 #ifndef HOST_WIN32
2431 int
2432 mono_gc_pthread_create (pthread_t *new_thread, const pthread_attr_t *attr, void *(*start_routine)(void *), void *arg)
2433 {
2434         return pthread_create (new_thread, attr, start_routine, arg);
2435 }
2436 #endif
2437
2438 /*
2439  * Miscellaneous
2440  */
2441
2442 void
2443 sgen_client_total_allocated_heap_changed (size_t allocated_heap)
2444 {
2445         mono_runtime_resource_check_limit (MONO_RESOURCE_GC_HEAP, allocated_heap);
2446 }
2447
2448 gboolean
2449 mono_gc_user_markers_supported (void)
2450 {
2451         return TRUE;
2452 }
2453
2454 gboolean
2455 mono_object_is_alive (MonoObject* o)
2456 {
2457         return TRUE;
2458 }
2459
2460 int
2461 mono_gc_get_generation (MonoObject *obj)
2462 {
2463         if (sgen_ptr_in_nursery (obj))
2464                 return 0;
2465         return 1;
2466 }
2467
2468 void
2469 mono_gc_enable_events (void)
2470 {
2471 }
2472
2473 const char *
2474 mono_gc_get_gc_name (void)
2475 {
2476         return "sgen";
2477 }
2478
2479 char*
2480 mono_gc_get_description (void)
2481 {
2482         return g_strdup ("sgen");
2483 }
2484
2485 void
2486 mono_gc_set_desktop_mode (void)
2487 {
2488 }
2489
2490 gboolean
2491 mono_gc_is_moving (void)
2492 {
2493         return TRUE;
2494 }
2495
2496 gboolean
2497 mono_gc_is_disabled (void)
2498 {
2499         return FALSE;
2500 }
2501
2502 #ifdef HOST_WIN32
2503 BOOL APIENTRY mono_gc_dllmain (HMODULE module_handle, DWORD reason, LPVOID reserved)
2504 {
2505         return TRUE;
2506 }
2507 #endif
2508
2509 int
2510 mono_gc_max_generation (void)
2511 {
2512         return 1;
2513 }
2514
2515 gboolean
2516 mono_gc_precise_stack_mark_enabled (void)
2517 {
2518         return !conservative_stack_mark;
2519 }
2520
2521 void
2522 mono_gc_collect (int generation)
2523 {
2524         sgen_gc_collect (generation);
2525 }
2526
2527 int
2528 mono_gc_collection_count (int generation)
2529 {
2530         return sgen_gc_collection_count (generation);
2531 }
2532
2533 int64_t
2534 mono_gc_get_used_size (void)
2535 {
2536         return (int64_t)sgen_gc_get_used_size ();
2537 }
2538
2539 int64_t
2540 mono_gc_get_heap_size (void)
2541 {
2542         return (int64_t)sgen_gc_get_total_heap_allocation ();
2543 }
2544
2545 MonoGCDescriptor
2546 mono_gc_make_root_descr_user (MonoGCRootMarkFunc marker)
2547 {
2548         return sgen_make_user_root_descriptor (marker);
2549 }
2550
2551 MonoGCDescriptor
2552 mono_gc_make_descr_for_string (gsize *bitmap, int numbits)
2553 {
2554         return SGEN_DESC_STRING;
2555 }
2556
2557 void*
2558 mono_gc_get_nursery (int *shift_bits, size_t *size)
2559 {
2560         *size = sgen_nursery_size;
2561         *shift_bits = DEFAULT_NURSERY_BITS;
2562         return sgen_get_nursery_start ();
2563 }
2564
2565 int
2566 mono_gc_get_los_limit (void)
2567 {
2568         return SGEN_MAX_SMALL_OBJ_SIZE;
2569 }
2570
2571 void
2572 mono_gc_weak_link_add (void **link_addr, MonoObject *obj, gboolean track)
2573 {
2574         sgen_register_disappearing_link (obj, link_addr, track, FALSE);
2575 }
2576
2577 void
2578 mono_gc_weak_link_remove (void **link_addr, gboolean track)
2579 {
2580         sgen_register_disappearing_link (NULL, link_addr, track, FALSE);
2581 }
2582
2583 MonoObject*
2584 mono_gc_weak_link_get (void **link_addr)
2585 {
2586         return sgen_weak_link_get (link_addr);
2587 }
2588
2589 gboolean
2590 mono_gc_set_allow_synchronous_major (gboolean flag)
2591 {
2592         return sgen_set_allow_synchronous_major (flag);
2593 }
2594
2595 void*
2596 mono_gc_invoke_with_gc_lock (MonoGCLockedCallbackFunc func, void *data)
2597 {
2598         void *result;
2599         LOCK_INTERRUPTION;
2600         result = func (data);
2601         UNLOCK_INTERRUPTION;
2602         return result;
2603 }
2604
2605 void
2606 mono_gc_register_altstack (gpointer stack, gint32 stack_size, gpointer altstack, gint32 altstack_size)
2607 {
2608         // FIXME:
2609 }
2610
2611 void
2612 sgen_client_out_of_memory (size_t size)
2613 {
2614         mono_gc_out_of_memory (size);
2615 }
2616
2617 guint8*
2618 mono_gc_get_card_table (int *shift_bits, gpointer *mask)
2619 {
2620         return sgen_get_card_table_configuration (shift_bits, mask);
2621 }
2622
2623 gboolean
2624 mono_gc_card_table_nursery_check (void)
2625 {
2626         return !sgen_get_major_collector ()->is_concurrent;
2627 }
2628
2629 /* Negative value to remove */
2630 void
2631 mono_gc_add_memory_pressure (gint64 value)
2632 {
2633         /* FIXME: Implement at some point? */
2634 }
2635
2636 /*
2637  * Logging
2638  */
2639
2640 void
2641 sgen_client_degraded_allocation (size_t size)
2642 {
2643         static int last_major_gc_warned = -1;
2644         static int num_degraded = 0;
2645
2646         if (last_major_gc_warned < gc_stats.major_gc_count) {
2647                 ++num_degraded;
2648                 if (num_degraded == 1 || num_degraded == 3)
2649                         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_GC, "Warning: Degraded allocation.  Consider increasing nursery-size if the warning persists.");
2650                 else if (num_degraded == 10)
2651                         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_GC, "Warning: Repeated degraded allocation.  Consider increasing nursery-size.");
2652                 last_major_gc_warned = gc_stats.major_gc_count;
2653         }
2654 }
2655
2656 void
2657 sgen_client_log_timing (GGTimingInfo *info, mword last_major_num_sections, mword last_los_memory_usage)
2658 {
2659         SgenMajorCollector *major_collector = sgen_get_major_collector ();
2660         mword num_major_sections = major_collector->get_num_major_sections ();
2661         char full_timing_buff [1024];
2662         full_timing_buff [0] = '\0';
2663
2664         if (!info->is_overflow)
2665                 sprintf (full_timing_buff, "total %.2fms, bridge %.2fms", info->stw_time / 10000.0f, (int)info->bridge_time / 10000.0f);
2666         if (info->generation == GENERATION_OLD)
2667                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_GC, "GC_MAJOR%s: (%s) pause %.2fms, %s major %dK/%dK los %dK/%dK",
2668                         info->is_overflow ? "_OVERFLOW" : "",
2669                         info->reason ? info->reason : "",
2670                         (int)info->total_time / 10000.0f,
2671                         full_timing_buff,
2672                         major_collector->section_size * num_major_sections / 1024,
2673                         major_collector->section_size * last_major_num_sections / 1024,
2674                         los_memory_usage / 1024,
2675                         last_los_memory_usage / 1024);
2676         else
2677                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_GC, "GC_MINOR%s: (%s) pause %.2fms, %s promoted %dK major %dK los %dK",
2678                                 info->is_overflow ? "_OVERFLOW" : "",
2679                         info->reason ? info->reason : "",
2680                         (int)info->total_time / 10000.0f,
2681                         full_timing_buff,
2682                         (num_major_sections - last_major_num_sections) * major_collector->section_size / 1024,
2683                         major_collector->section_size * num_major_sections / 1024,
2684                         los_memory_usage / 1024);
2685 }
2686
2687 /*
2688  * Debugging
2689  */
2690
2691 const char*
2692 sgen_client_description_for_internal_mem_type (int type)
2693 {
2694         switch (type) {
2695         case INTERNAL_MEM_EPHEMERON_LINK: return "ephemeron-link";
2696         default:
2697                 return NULL;
2698         }
2699 }
2700
2701 void
2702 sgen_client_pre_collection_checks (void)
2703 {
2704         if (sgen_mono_xdomain_checks) {
2705                 sgen_clear_nursery_fragments ();
2706                 sgen_check_for_xdomain_refs ();
2707         }
2708 }
2709
2710 gboolean
2711 sgen_client_vtable_is_inited (MonoVTable *vt)
2712 {
2713         return vt->klass->inited;
2714 }
2715
2716 const char*
2717 sgen_client_vtable_get_namespace (MonoVTable *vt)
2718 {
2719         return vt->klass->name_space;
2720 }
2721
2722 const char*
2723 sgen_client_vtable_get_name (MonoVTable *vt)
2724 {
2725         return vt->klass->name;
2726 }
2727
2728 /*
2729  * Initialization
2730  */
2731
2732 void
2733 sgen_client_init (void)
2734 {
2735         int dummy;
2736         MonoThreadInfoCallbacks cb;
2737
2738         cb.thread_register = sgen_thread_register;
2739         cb.thread_detach = sgen_thread_detach;
2740         cb.thread_unregister = sgen_thread_unregister;
2741         cb.thread_attach = sgen_thread_attach;
2742         cb.mono_method_is_critical = (gpointer)is_critical_method;
2743         cb.mono_thread_in_critical_region = thread_in_critical_region;
2744
2745         mono_threads_init (&cb, sizeof (SgenThreadInfo));
2746
2747         ///* Keep this the default for now */
2748         /* Precise marking is broken on all supported targets. Disable until fixed. */
2749         conservative_stack_mark = TRUE;
2750
2751         sgen_register_fixed_internal_mem_type (INTERNAL_MEM_EPHEMERON_LINK, sizeof (EphemeronLinkNode));
2752
2753         mono_sgen_init_stw ();
2754
2755 #ifndef HAVE_KW_THREAD
2756         mono_native_tls_alloc (&thread_info_key, NULL);
2757 #if defined(TARGET_OSX) || defined(TARGET_WIN32) || defined(TARGET_ANDROID) || defined(TARGET_IOS)
2758         /* 
2759          * CEE_MONO_TLS requires the tls offset, not the key, so the code below only works on darwin,
2760          * where the two are the same.
2761          */
2762         mono_tls_key_set_offset (TLS_KEY_SGEN_THREAD_INFO, thread_info_key);
2763 #endif
2764 #else
2765         {
2766                 int tls_offset = -1;
2767                 MONO_THREAD_VAR_OFFSET (sgen_thread_info, tls_offset);
2768                 mono_tls_key_set_offset (TLS_KEY_SGEN_THREAD_INFO, tls_offset);
2769         }
2770 #endif
2771
2772         /*
2773          * This needs to happen before any internal allocations because
2774          * it inits the small id which is required for hazard pointer
2775          * operations.
2776          */
2777         sgen_os_init ();
2778
2779         mono_gc_register_thread (&dummy);
2780 }
2781
2782 gboolean
2783 sgen_client_handle_gc_param (const char *opt)
2784 {
2785         if (g_str_has_prefix (opt, "stack-mark=")) {
2786                 opt = strchr (opt, '=') + 1;
2787                 if (!strcmp (opt, "precise")) {
2788                         conservative_stack_mark = FALSE;
2789                 } else if (!strcmp (opt, "conservative")) {
2790                         conservative_stack_mark = TRUE;
2791                 } else {
2792                         sgen_env_var_error (MONO_GC_PARAMS_NAME, conservative_stack_mark ? "Using `conservative`." : "Using `precise`.",
2793                                         "Invalid value `%s` for `stack-mark` option, possible values are: `precise`, `conservative`.", opt);
2794                 }
2795         } else if (g_str_has_prefix (opt, "bridge-implementation=")) {
2796                 opt = strchr (opt, '=') + 1;
2797                 sgen_set_bridge_implementation (opt);
2798         } else if (g_str_has_prefix (opt, "toggleref-test")) {
2799                 /* FIXME: This should probably in MONO_GC_DEBUG */
2800                 sgen_register_test_toggleref_callback ();
2801         } else {
2802                 return FALSE;
2803         }
2804         return TRUE;
2805 }
2806
2807 void
2808 sgen_client_print_gc_params_usage (void)
2809 {
2810         fprintf (stderr, "  stack-mark=MARK-METHOD (where MARK-METHOD is 'precise' or 'conservative')\n");
2811 }
2812
2813 gboolean
2814 sgen_client_handle_gc_debug (const char *opt)
2815 {
2816         if (!strcmp (opt, "xdomain-checks")) {
2817                 sgen_mono_xdomain_checks = TRUE;
2818         } else if (!strcmp (opt, "do-not-finalize")) {
2819                 do_not_finalize = TRUE;
2820         } else if (!strcmp (opt, "log-finalizers")) {
2821                 log_finalizers = TRUE;
2822         } else if (!strcmp (opt, "no-managed-allocator")) {
2823                 sgen_set_use_managed_allocator (FALSE);
2824         } else if (!sgen_bridge_handle_gc_debug (opt)) {
2825                 return FALSE;
2826         }
2827         return TRUE;
2828 }
2829
2830 void
2831 sgen_client_print_gc_debug_usage (void)
2832 {
2833         fprintf (stderr, "  xdomain-checks\n");
2834         fprintf (stderr, "  do-not-finalize\n");
2835         fprintf (stderr, "  log-finalizers\n");
2836         fprintf (stderr, "  no-managed-allocator\n");
2837         sgen_bridge_print_gc_debug_usage ();
2838 }
2839
2840
2841 gpointer
2842 sgen_client_get_provenance (void)
2843 {
2844 #ifdef SGEN_OBJECT_PROVENANCE
2845         MonoGCCallbacks *cb = mono_gc_get_gc_callbacks ();
2846         gpointer (*get_provenance_func) (void);
2847         if (!cb)
2848                 return NULL;
2849         get_provenance_func = cb->get_provenance_func;
2850         if (get_provenance_func)
2851                 return get_provenance_func ();
2852         return NULL;
2853 #else
2854         return NULL;
2855 #endif
2856 }
2857
2858 void
2859 sgen_client_describe_invalid_pointer (GCObject *ptr)
2860 {
2861         sgen_bridge_describe_pointer (ptr);
2862 }
2863
2864 void
2865 mono_gc_base_init (void)
2866 {
2867         mono_counters_init ();
2868
2869 #ifdef HEAVY_STATISTICS
2870         mono_counters_register ("los marked cards", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &los_marked_cards);
2871         mono_counters_register ("los array cards scanned ", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &los_array_cards);
2872         mono_counters_register ("los array remsets", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &los_array_remsets);
2873
2874         mono_counters_register ("WBarrier set arrayref", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_wbarrier_set_arrayref);
2875         mono_counters_register ("WBarrier value copy", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_wbarrier_value_copy);
2876         mono_counters_register ("WBarrier object copy", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_wbarrier_object_copy);
2877 #endif
2878
2879         sgen_gc_init ();
2880
2881         if (nursery_canaries_enabled ())
2882                 sgen_set_use_managed_allocator (FALSE);
2883 }
2884
2885 void
2886 mono_gc_base_cleanup (void)
2887 {
2888 }
2889
2890 gboolean
2891 mono_gc_is_null (void)
2892 {
2893         return FALSE;
2894 }
2895
2896 #endif