Merge pull request #1840 from ludovic-henry/iolayer-thread-interrupt
[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)
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)) {
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                 guint8 *card_data, *card_base;
1600                 guint8 *card_data_end;
1601                 char *obj_start = sgen_card_table_align_pointer (obj);
1602                 mword obj_size = sgen_client_par_object_get_size (vt, obj);
1603                 char *obj_end = (char*)obj + obj_size;
1604                 size_t card_count;
1605                 size_t extra_idx = 0;
1606
1607                 MonoArray *arr = (MonoArray*)obj;
1608                 mword desc = (mword)klass->element_class->gc_descr;
1609                 int elem_size = mono_array_element_size (klass);
1610
1611 #ifdef SGEN_HAVE_OVERLAPPING_CARDS
1612                 guint8 *overflow_scan_end = NULL;
1613 #endif
1614
1615 #ifdef SGEN_OBJECT_LAYOUT_STATISTICS
1616                 if (klass->element_class->valuetype)
1617                         sgen_object_layout_scanned_vtype_array ();
1618                 else
1619                         sgen_object_layout_scanned_ref_array ();
1620 #endif
1621
1622                 if (cards)
1623                         card_data = cards;
1624                 else
1625                         card_data = sgen_card_table_get_card_scan_address ((mword)obj);
1626
1627                 card_base = card_data;
1628                 card_count = sgen_card_table_number_of_cards_in_range ((mword)obj, obj_size);
1629                 card_data_end = card_data + card_count;
1630
1631
1632 #ifdef SGEN_HAVE_OVERLAPPING_CARDS
1633                 /*Check for overflow and if so, setup to scan in two steps*/
1634                 if (!cards && card_data_end >= SGEN_SHADOW_CARDTABLE_END) {
1635                         overflow_scan_end = sgen_shadow_cardtable + (card_data_end - SGEN_SHADOW_CARDTABLE_END);
1636                         card_data_end = SGEN_SHADOW_CARDTABLE_END;
1637                 }
1638
1639 LOOP_HEAD:
1640 #endif
1641
1642                 card_data = find_next_card (card_data, card_data_end);
1643                 for (; card_data < card_data_end; card_data = find_next_card (card_data + 1, card_data_end)) {
1644                         size_t index;
1645                         size_t idx = (card_data - card_base) + extra_idx;
1646                         char *start = (char*)(obj_start + idx * CARD_SIZE_IN_BYTES);
1647                         char *card_end = start + CARD_SIZE_IN_BYTES;
1648                         char *first_elem, *elem;
1649
1650                         HEAVY_STAT (++los_marked_cards);
1651
1652                         if (!cards)
1653                                 sgen_card_table_prepare_card_for_scanning (card_data);
1654
1655                         card_end = MIN (card_end, obj_end);
1656
1657                         if (start <= (char*)arr->vector)
1658                                 index = 0;
1659                         else
1660                                 index = ARRAY_OBJ_INDEX (start, obj, elem_size);
1661
1662                         elem = first_elem = (char*)mono_array_addr_with_size_fast ((MonoArray*)obj, elem_size, index);
1663                         if (klass->element_class->valuetype) {
1664                                 ScanVTypeFunc scan_vtype_func = ctx.ops->scan_vtype;
1665
1666                                 for (; elem < card_end; elem += elem_size)
1667                                         scan_vtype_func (obj, elem, desc, ctx.queue BINARY_PROTOCOL_ARG (elem_size));
1668                         } else {
1669                                 CopyOrMarkObjectFunc copy_func = ctx.ops->copy_or_mark_object;
1670
1671                                 HEAVY_STAT (++los_array_cards);
1672                                 for (; elem < card_end; elem += SIZEOF_VOID_P) {
1673                                         gpointer new, old = *(gpointer*)elem;
1674                                         if ((mod_union && old) || G_UNLIKELY (sgen_ptr_in_nursery (old))) {
1675                                                 HEAVY_STAT (++los_array_remsets);
1676                                                 copy_func ((GCObject**)elem, ctx.queue);
1677                                                 new = *(gpointer*)elem;
1678                                                 if (G_UNLIKELY (sgen_ptr_in_nursery (new)))
1679                                                         sgen_add_to_global_remset (elem, new);
1680                                         }
1681                                 }
1682                         }
1683
1684                         binary_protocol_card_scan (first_elem, elem - first_elem);
1685                 }
1686
1687 #ifdef SGEN_HAVE_OVERLAPPING_CARDS
1688                 if (overflow_scan_end) {
1689                         extra_idx = card_data - card_base;
1690                         card_base = card_data = sgen_shadow_cardtable;
1691                         card_data_end = overflow_scan_end;
1692                         overflow_scan_end = NULL;
1693                         goto LOOP_HEAD;
1694                 }
1695 #endif
1696                 return TRUE;
1697         }
1698
1699         return FALSE;
1700 }
1701
1702 /*
1703  * Array and string allocation
1704  */
1705
1706 void*
1707 mono_gc_alloc_vector (MonoVTable *vtable, size_t size, uintptr_t max_length)
1708 {
1709         MonoArray *arr;
1710         TLAB_ACCESS_INIT;
1711
1712         if (!SGEN_CAN_ALIGN_UP (size))
1713                 return NULL;
1714
1715 #ifndef DISABLE_CRITICAL_REGION
1716         ENTER_CRITICAL_REGION;
1717         arr = (MonoArray*)sgen_try_alloc_obj_nolock (vtable, size);
1718         if (arr) {
1719                 /*This doesn't require fencing since EXIT_CRITICAL_REGION already does it for us*/
1720                 arr->max_length = (mono_array_size_t)max_length;
1721                 EXIT_CRITICAL_REGION;
1722                 goto done;
1723         }
1724         EXIT_CRITICAL_REGION;
1725 #endif
1726
1727         LOCK_GC;
1728
1729         arr = (MonoArray*)sgen_alloc_obj_nolock (vtable, size);
1730         if (G_UNLIKELY (!arr)) {
1731                 UNLOCK_GC;
1732                 return mono_gc_out_of_memory (size);
1733         }
1734
1735         arr->max_length = (mono_array_size_t)max_length;
1736
1737         UNLOCK_GC;
1738
1739  done:
1740         if (G_UNLIKELY (alloc_events))
1741                 mono_profiler_allocation (&arr->obj);
1742
1743         SGEN_ASSERT (6, SGEN_ALIGN_UP (size) == SGEN_ALIGN_UP (sgen_client_par_object_get_size (vtable, (GCObject*)arr)), "Vector has incorrect size.");
1744         return arr;
1745 }
1746
1747 void*
1748 mono_gc_alloc_array (MonoVTable *vtable, size_t size, uintptr_t max_length, uintptr_t bounds_size)
1749 {
1750         MonoArray *arr;
1751         MonoArrayBounds *bounds;
1752         TLAB_ACCESS_INIT;
1753
1754         if (!SGEN_CAN_ALIGN_UP (size))
1755                 return NULL;
1756
1757 #ifndef DISABLE_CRITICAL_REGION
1758         ENTER_CRITICAL_REGION;
1759         arr = (MonoArray*)sgen_try_alloc_obj_nolock (vtable, size);
1760         if (arr) {
1761                 /*This doesn't require fencing since EXIT_CRITICAL_REGION already does it for us*/
1762                 arr->max_length = (mono_array_size_t)max_length;
1763
1764                 bounds = (MonoArrayBounds*)((char*)arr + size - bounds_size);
1765                 arr->bounds = bounds;
1766                 EXIT_CRITICAL_REGION;
1767                 goto done;
1768         }
1769         EXIT_CRITICAL_REGION;
1770 #endif
1771
1772         LOCK_GC;
1773
1774         arr = (MonoArray*)sgen_alloc_obj_nolock (vtable, size);
1775         if (G_UNLIKELY (!arr)) {
1776                 UNLOCK_GC;
1777                 return mono_gc_out_of_memory (size);
1778         }
1779
1780         arr->max_length = (mono_array_size_t)max_length;
1781
1782         bounds = (MonoArrayBounds*)((char*)arr + size - bounds_size);
1783         arr->bounds = bounds;
1784
1785         UNLOCK_GC;
1786
1787  done:
1788         if (G_UNLIKELY (alloc_events))
1789                 mono_profiler_allocation (&arr->obj);
1790
1791         SGEN_ASSERT (6, SGEN_ALIGN_UP (size) == SGEN_ALIGN_UP (sgen_client_par_object_get_size (vtable, (GCObject*)arr)), "Array has incorrect size.");
1792         return arr;
1793 }
1794
1795 void*
1796 mono_gc_alloc_string (MonoVTable *vtable, size_t size, gint32 len)
1797 {
1798         MonoString *str;
1799         TLAB_ACCESS_INIT;
1800
1801         if (!SGEN_CAN_ALIGN_UP (size))
1802                 return NULL;
1803
1804 #ifndef DISABLE_CRITICAL_REGION
1805         ENTER_CRITICAL_REGION;
1806         str = (MonoString*)sgen_try_alloc_obj_nolock (vtable, size);
1807         if (str) {
1808                 /*This doesn't require fencing since EXIT_CRITICAL_REGION already does it for us*/
1809                 str->length = len;
1810                 EXIT_CRITICAL_REGION;
1811                 goto done;
1812         }
1813         EXIT_CRITICAL_REGION;
1814 #endif
1815
1816         LOCK_GC;
1817
1818         str = (MonoString*)sgen_alloc_obj_nolock (vtable, size);
1819         if (G_UNLIKELY (!str)) {
1820                 UNLOCK_GC;
1821                 return mono_gc_out_of_memory (size);
1822         }
1823
1824         str->length = len;
1825
1826         UNLOCK_GC;
1827
1828  done:
1829         if (G_UNLIKELY (alloc_events))
1830                 mono_profiler_allocation (&str->object);
1831
1832         return str;
1833 }
1834
1835 /*
1836  * Strings
1837  */
1838
1839 void
1840 mono_gc_set_string_length (MonoString *str, gint32 new_length)
1841 {
1842         mono_unichar2 *new_end = str->chars + new_length;
1843
1844         /* zero the discarded string. This null-delimits the string and allows
1845          * the space to be reclaimed by SGen. */
1846
1847         if (nursery_canaries_enabled () && sgen_ptr_in_nursery (str)) {
1848                 CHECK_CANARY_FOR_OBJECT ((GCObject*)str, TRUE);
1849                 memset (new_end, 0, (str->length - new_length + 1) * sizeof (mono_unichar2) + CANARY_SIZE);
1850                 memcpy (new_end + 1 , CANARY_STRING, CANARY_SIZE);
1851         } else {
1852                 memset (new_end, 0, (str->length - new_length + 1) * sizeof (mono_unichar2));
1853         }
1854
1855         str->length = new_length;
1856 }
1857
1858 /*
1859  * Profiling
1860  */
1861
1862 #define GC_ROOT_NUM 32
1863 typedef struct {
1864         int count;              /* must be the first field */
1865         void *objects [GC_ROOT_NUM];
1866         int root_types [GC_ROOT_NUM];
1867         uintptr_t extra_info [GC_ROOT_NUM];
1868 } GCRootReport;
1869
1870 static void
1871 notify_gc_roots (GCRootReport *report)
1872 {
1873         if (!report->count)
1874                 return;
1875         mono_profiler_gc_roots (report->count, report->objects, report->root_types, report->extra_info);
1876         report->count = 0;
1877 }
1878
1879 static void
1880 add_profile_gc_root (GCRootReport *report, void *object, int rtype, uintptr_t extra_info)
1881 {
1882         if (report->count == GC_ROOT_NUM)
1883                 notify_gc_roots (report);
1884         report->objects [report->count] = object;
1885         report->root_types [report->count] = rtype;
1886         report->extra_info [report->count++] = (uintptr_t)SGEN_LOAD_VTABLE (object)->klass;
1887 }
1888
1889 void
1890 sgen_client_nursery_objects_pinned (void **definitely_pinned, int count)
1891 {
1892         if (mono_profiler_get_events () & MONO_PROFILE_GC_ROOTS) {
1893                 GCRootReport report;
1894                 int idx;
1895                 report.count = 0;
1896                 for (idx = 0; idx < count; ++idx)
1897                         add_profile_gc_root (&report, definitely_pinned [idx], MONO_PROFILE_GC_ROOT_PINNING | MONO_PROFILE_GC_ROOT_MISC, 0);
1898                 notify_gc_roots (&report);
1899         }
1900 }
1901
1902 static void
1903 report_finalizer_roots_from_queue (SgenPointerQueue *queue)
1904 {
1905         GCRootReport report;
1906         size_t i;
1907
1908         report.count = 0;
1909         for (i = 0; i < queue->next_slot; ++i) {
1910                 void *obj = queue->data [i];
1911                 if (!obj)
1912                         continue;
1913                 add_profile_gc_root (&report, obj, MONO_PROFILE_GC_ROOT_FINALIZER, 0);
1914         }
1915         notify_gc_roots (&report);
1916 }
1917
1918 static void
1919 report_finalizer_roots (SgenPointerQueue *fin_ready_queue, SgenPointerQueue *critical_fin_queue)
1920 {
1921         report_finalizer_roots_from_queue (fin_ready_queue);
1922         report_finalizer_roots_from_queue (critical_fin_queue);
1923 }
1924
1925 static GCRootReport *root_report;
1926
1927 static void
1928 single_arg_report_root (MonoObject **obj, void *gc_data)
1929 {
1930         if (*obj)
1931                 add_profile_gc_root (root_report, *obj, MONO_PROFILE_GC_ROOT_OTHER, 0);
1932 }
1933
1934 static void
1935 precisely_report_roots_from (GCRootReport *report, void** start_root, void** end_root, mword desc)
1936 {
1937         switch (desc & ROOT_DESC_TYPE_MASK) {
1938         case ROOT_DESC_BITMAP:
1939                 desc >>= ROOT_DESC_TYPE_SHIFT;
1940                 while (desc) {
1941                         if ((desc & 1) && *start_root) {
1942                                 add_profile_gc_root (report, *start_root, MONO_PROFILE_GC_ROOT_OTHER, 0);
1943                         }
1944                         desc >>= 1;
1945                         start_root++;
1946                 }
1947                 return;
1948         case ROOT_DESC_COMPLEX: {
1949                 gsize *bitmap_data = sgen_get_complex_descriptor_bitmap (desc);
1950                 gsize bwords = (*bitmap_data) - 1;
1951                 void **start_run = start_root;
1952                 bitmap_data++;
1953                 while (bwords-- > 0) {
1954                         gsize bmap = *bitmap_data++;
1955                         void **objptr = start_run;
1956                         while (bmap) {
1957                                 if ((bmap & 1) && *objptr) {
1958                                         add_profile_gc_root (report, *objptr, MONO_PROFILE_GC_ROOT_OTHER, 0);
1959                                 }
1960                                 bmap >>= 1;
1961                                 ++objptr;
1962                         }
1963                         start_run += GC_BITS_PER_WORD;
1964                 }
1965                 break;
1966         }
1967         case ROOT_DESC_USER: {
1968                 MonoGCRootMarkFunc marker = (MonoGCRootMarkFunc)sgen_get_user_descriptor_func (desc);
1969                 root_report = report;
1970                 marker ((MonoObject**)start_root, single_arg_report_root, NULL);
1971                 break;
1972         }
1973         case ROOT_DESC_RUN_LEN:
1974                 g_assert_not_reached ();
1975         default:
1976                 g_assert_not_reached ();
1977         }
1978 }
1979
1980 static void
1981 report_registered_roots_by_type (int root_type)
1982 {
1983         GCRootReport report;
1984         void **start_root;
1985         RootRecord *root;
1986         report.count = 0;
1987         SGEN_HASH_TABLE_FOREACH (&roots_hash [root_type], start_root, root) {
1988                 SGEN_LOG (6, "Precise root scan %p-%p (desc: %p)", start_root, root->end_root, (void*)root->root_desc);
1989                 precisely_report_roots_from (&report, start_root, (void**)root->end_root, root->root_desc);
1990         } SGEN_HASH_TABLE_FOREACH_END;
1991         notify_gc_roots (&report);
1992 }
1993
1994 static void
1995 report_registered_roots (void)
1996 {
1997         report_registered_roots_by_type (ROOT_TYPE_NORMAL);
1998         report_registered_roots_by_type (ROOT_TYPE_WBARRIER);
1999 }
2000
2001 void
2002 sgen_client_collecting_minor (SgenPointerQueue *fin_ready_queue, SgenPointerQueue *critical_fin_queue)
2003 {
2004         if (mono_profiler_get_events () & MONO_PROFILE_GC_ROOTS)
2005                 report_registered_roots ();
2006         if (mono_profiler_get_events () & MONO_PROFILE_GC_ROOTS)
2007                 report_finalizer_roots (fin_ready_queue, critical_fin_queue);
2008 }
2009
2010 static GCRootReport major_root_report;
2011 static gboolean profile_roots;
2012
2013 void
2014 sgen_client_collecting_major_1 (void)
2015 {
2016         profile_roots = mono_profiler_get_events () & MONO_PROFILE_GC_ROOTS;
2017         memset (&major_root_report, 0, sizeof (GCRootReport));
2018 }
2019
2020 void
2021 sgen_client_pinned_los_object (GCObject *obj)
2022 {
2023         if (profile_roots)
2024                 add_profile_gc_root (&major_root_report, (char*)obj, MONO_PROFILE_GC_ROOT_PINNING | MONO_PROFILE_GC_ROOT_MISC, 0);
2025 }
2026
2027 void
2028 sgen_client_collecting_major_2 (void)
2029 {
2030         if (profile_roots)
2031                 notify_gc_roots (&major_root_report);
2032
2033         if (mono_profiler_get_events () & MONO_PROFILE_GC_ROOTS)
2034                 report_registered_roots ();
2035 }
2036
2037 void
2038 sgen_client_collecting_major_3 (SgenPointerQueue *fin_ready_queue, SgenPointerQueue *critical_fin_queue)
2039 {
2040         if (mono_profiler_get_events () & MONO_PROFILE_GC_ROOTS)
2041                 report_finalizer_roots (fin_ready_queue, critical_fin_queue);
2042 }
2043
2044 #define MOVED_OBJECTS_NUM 64
2045 static void *moved_objects [MOVED_OBJECTS_NUM];
2046 static int moved_objects_idx = 0;
2047
2048 void
2049 mono_sgen_register_moved_object (void *obj, void *destination)
2050 {
2051         g_assert (mono_profiler_events & MONO_PROFILE_GC_MOVES);
2052
2053         if (moved_objects_idx == MOVED_OBJECTS_NUM) {
2054                 mono_profiler_gc_moves (moved_objects, moved_objects_idx);
2055                 moved_objects_idx = 0;
2056         }
2057         moved_objects [moved_objects_idx++] = obj;
2058         moved_objects [moved_objects_idx++] = destination;
2059 }
2060
2061 void
2062 mono_sgen_gc_event_moves (void)
2063 {
2064         if (moved_objects_idx) {
2065                 mono_profiler_gc_moves (moved_objects, moved_objects_idx);
2066                 moved_objects_idx = 0;
2067         }
2068 }
2069
2070 /*
2071  * Heap walking
2072  */
2073
2074 #define REFS_SIZE 128
2075 typedef struct {
2076         void *data;
2077         MonoGCReferences callback;
2078         int flags;
2079         int count;
2080         int called;
2081         MonoObject *refs [REFS_SIZE];
2082         uintptr_t offsets [REFS_SIZE];
2083 } HeapWalkInfo;
2084
2085 #undef HANDLE_PTR
2086 #define HANDLE_PTR(ptr,obj)     do {    \
2087                 if (*(ptr)) {   \
2088                         if (hwi->count == REFS_SIZE) {  \
2089                                 hwi->callback ((MonoObject*)start, mono_object_class (start), hwi->called? 0: size, hwi->count, hwi->refs, hwi->offsets, hwi->data);    \
2090                                 hwi->count = 0; \
2091                                 hwi->called = 1;        \
2092                         }       \
2093                         hwi->offsets [hwi->count] = (char*)(ptr)-(char*)start;  \
2094                         hwi->refs [hwi->count++] = *(ptr);      \
2095                 }       \
2096         } while (0)
2097
2098 static void
2099 collect_references (HeapWalkInfo *hwi, GCObject *obj, size_t size)
2100 {
2101         char *start = (char*)obj;
2102         mword desc = sgen_obj_get_descriptor (obj);
2103
2104 #include "sgen/sgen-scan-object.h"
2105 }
2106
2107 static void
2108 walk_references (GCObject *start, size_t size, void *data)
2109 {
2110         HeapWalkInfo *hwi = data;
2111         hwi->called = 0;
2112         hwi->count = 0;
2113         collect_references (hwi, start, size);
2114         if (hwi->count || !hwi->called)
2115                 hwi->callback (start, mono_object_class (start), hwi->called? 0: size, hwi->count, hwi->refs, hwi->offsets, hwi->data);
2116 }
2117
2118 /**
2119  * mono_gc_walk_heap:
2120  * @flags: flags for future use
2121  * @callback: a function pointer called for each object in the heap
2122  * @data: a user data pointer that is passed to callback
2123  *
2124  * This function can be used to iterate over all the live objects in the heap:
2125  * for each object, @callback is invoked, providing info about the object's
2126  * location in memory, its class, its size and the objects it references.
2127  * For each referenced object it's offset from the object address is
2128  * reported in the offsets array.
2129  * The object references may be buffered, so the callback may be invoked
2130  * multiple times for the same object: in all but the first call, the size
2131  * argument will be zero.
2132  * Note that this function can be only called in the #MONO_GC_EVENT_PRE_START_WORLD
2133  * profiler event handler.
2134  *
2135  * Returns: a non-zero value if the GC doesn't support heap walking
2136  */
2137 int
2138 mono_gc_walk_heap (int flags, MonoGCReferences callback, void *data)
2139 {
2140         HeapWalkInfo hwi;
2141
2142         hwi.flags = flags;
2143         hwi.callback = callback;
2144         hwi.data = data;
2145
2146         sgen_clear_nursery_fragments ();
2147         sgen_scan_area_with_callback (nursery_section->data, nursery_section->end_data, walk_references, &hwi, FALSE, TRUE);
2148
2149         major_collector.iterate_objects (ITERATE_OBJECTS_SWEEP_ALL, walk_references, &hwi);
2150         sgen_los_iterate_objects (walk_references, &hwi);
2151
2152         return 0;
2153 }
2154
2155 /*
2156  * Threads
2157  */
2158
2159 void
2160 mono_gc_set_gc_callbacks (MonoGCCallbacks *callbacks)
2161 {
2162         gc_callbacks = *callbacks;
2163 }
2164
2165 MonoGCCallbacks *
2166 mono_gc_get_gc_callbacks ()
2167 {
2168         return &gc_callbacks;
2169 }
2170
2171 void
2172 sgen_client_thread_register (SgenThreadInfo* info, void *stack_bottom_fallback)
2173 {
2174         size_t stsize = 0;
2175         guint8 *staddr = NULL;
2176
2177 #ifndef HAVE_KW_THREAD
2178         g_assert (!mono_native_tls_get_value (thread_info_key));
2179         mono_native_tls_set_value (thread_info_key, info);
2180 #else
2181         sgen_thread_info = info;
2182 #endif
2183
2184         info->client_info.skip = 0;
2185         info->client_info.stopped_ip = NULL;
2186         info->client_info.stopped_domain = NULL;
2187
2188         info->client_info.stack_start = NULL;
2189
2190 #ifdef SGEN_POSIX_STW
2191         info->client_info.stop_count = -1;
2192         info->client_info.signal = 0;
2193 #endif
2194
2195         /* On win32, stack_start_limit should be 0, since the stack can grow dynamically */
2196         mono_thread_info_get_stack_bounds (&staddr, &stsize);
2197         if (staddr) {
2198 #ifndef HOST_WIN32
2199                 info->client_info.stack_start_limit = staddr;
2200 #endif
2201                 info->client_info.stack_end = staddr + stsize;
2202         } else {
2203                 gsize stack_bottom = (gsize)stack_bottom_fallback;
2204                 stack_bottom += 4095;
2205                 stack_bottom &= ~4095;
2206                 info->client_info.stack_end = (char*)stack_bottom;
2207         }
2208
2209 #ifdef USE_MONO_CTX
2210         memset (&info->client_info.ctx, 0, sizeof (MonoContext));
2211 #else
2212         memset (&info->client_info.regs, 0, sizeof (info->client_info.regs));
2213 #endif
2214
2215         if (mono_gc_get_gc_callbacks ()->thread_attach_func)
2216                 info->client_info.runtime_data = mono_gc_get_gc_callbacks ()->thread_attach_func ();
2217
2218         binary_protocol_thread_register ((gpointer)mono_thread_info_get_tid (info));
2219
2220         SGEN_LOG (3, "registered thread %p (%p) stack end %p", info, (gpointer)mono_thread_info_get_tid (info), info->client_info.stack_end);
2221 }
2222
2223 void
2224 sgen_client_thread_unregister (SgenThreadInfo *p)
2225 {
2226         MonoNativeThreadId tid;
2227
2228 #ifndef HAVE_KW_THREAD
2229         mono_native_tls_set_value (thread_info_key, NULL);
2230 #else
2231         sgen_thread_info = NULL;
2232 #endif
2233
2234         tid = mono_thread_info_get_tid (p);
2235
2236         if (p->client_info.info.runtime_thread)
2237                 mono_threads_add_joinable_thread ((gpointer)tid);
2238
2239         if (mono_gc_get_gc_callbacks ()->thread_detach_func) {
2240                 mono_gc_get_gc_callbacks ()->thread_detach_func (p->client_info.runtime_data);
2241                 p->client_info.runtime_data = NULL;
2242         }
2243
2244         binary_protocol_thread_unregister ((gpointer)tid);
2245         SGEN_LOG (3, "unregister thread %p (%p)", p, (gpointer)tid);
2246 }
2247
2248 void
2249 mono_gc_set_skip_thread (gboolean skip)
2250 {
2251         SgenThreadInfo *info = mono_thread_info_current ();
2252
2253         LOCK_GC;
2254         info->client_info.gc_disabled = skip;
2255         UNLOCK_GC;
2256 }
2257
2258 static gboolean
2259 is_critical_method (MonoMethod *method)
2260 {
2261         return mono_runtime_is_critical_method (method) || sgen_is_critical_method (method);
2262 }
2263
2264 static gboolean
2265 thread_in_critical_region (SgenThreadInfo *info)
2266 {
2267         return info->client_info.in_critical_region;
2268 }
2269
2270 static void
2271 sgen_thread_attach (SgenThreadInfo *info)
2272 {
2273         if (mono_gc_get_gc_callbacks ()->thread_attach_func && !info->client_info.runtime_data)
2274                 info->client_info.runtime_data = mono_gc_get_gc_callbacks ()->thread_attach_func ();
2275 }
2276
2277 static void
2278 sgen_thread_detach (SgenThreadInfo *p)
2279 {
2280         /* If a delegate is passed to native code and invoked on a thread we dont
2281          * know about, the jit will register it with mono_jit_thread_attach, but
2282          * we have no way of knowing when that thread goes away.  SGen has a TSD
2283          * so we assume that if the domain is still registered, we can detach
2284          * the thread
2285          */
2286         if (mono_domain_get ())
2287                 mono_thread_detach_internal (mono_thread_internal_current ());
2288 }
2289
2290 gboolean
2291 mono_gc_register_thread (void *baseptr)
2292 {
2293         return mono_thread_info_attach (baseptr) != NULL;
2294 }
2295
2296 gboolean
2297 mono_gc_is_gc_thread (void)
2298 {
2299         gboolean result;
2300         LOCK_GC;
2301         result = mono_thread_info_current () != NULL;
2302         UNLOCK_GC;
2303         return result;
2304 }
2305
2306 void
2307 sgen_client_thread_register_worker (void)
2308 {
2309         mono_thread_info_register_small_id ();
2310 }
2311
2312 /* Variables holding start/end nursery so it won't have to be passed at every call */
2313 static void *scan_area_arg_start, *scan_area_arg_end;
2314
2315 void
2316 mono_gc_conservatively_scan_area (void *start, void *end)
2317 {
2318         sgen_conservatively_pin_objects_from (start, end, scan_area_arg_start, scan_area_arg_end, PIN_TYPE_STACK);
2319 }
2320
2321 void*
2322 mono_gc_scan_object (void *obj, void *gc_data)
2323 {
2324         ScanCopyContext *ctx = gc_data;
2325         ctx->ops->copy_or_mark_object ((GCObject**)&obj, ctx->queue);
2326         return obj;
2327 }
2328
2329 /*
2330  * Mark from thread stacks and registers.
2331  */
2332 void
2333 sgen_client_scan_thread_data (void *start_nursery, void *end_nursery, gboolean precise, ScanCopyContext ctx)
2334 {
2335         SgenThreadInfo *info;
2336
2337         scan_area_arg_start = start_nursery;
2338         scan_area_arg_end = end_nursery;
2339
2340         FOREACH_THREAD (info) {
2341                 int skip_reason = 0;
2342                 if (info->client_info.skip) {
2343                         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);
2344                         skip_reason = 1;
2345                 } else if (info->client_info.gc_disabled) {
2346                         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);
2347                         skip_reason = 2;
2348                 } else if (!mono_thread_info_is_live (info)) {
2349                         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);
2350                         skip_reason = 3;
2351                 }
2352
2353                 binary_protocol_scan_stack ((gpointer)mono_thread_info_get_tid (info), info->client_info.stack_start, info->client_info.stack_end, skip_reason);
2354
2355                 if (skip_reason)
2356                         continue;
2357
2358                 g_assert (info->client_info.suspend_done);
2359                 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 ());
2360                 if (mono_gc_get_gc_callbacks ()->thread_mark_func && !conservative_stack_mark) {
2361                         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);
2362                 } else if (!precise) {
2363                         if (!conservative_stack_mark) {
2364                                 fprintf (stderr, "Precise stack mark not supported - disabling.\n");
2365                                 conservative_stack_mark = TRUE;
2366                         }
2367                         sgen_conservatively_pin_objects_from (info->client_info.stack_start, info->client_info.stack_end, start_nursery, end_nursery, PIN_TYPE_STACK);
2368                 }
2369
2370                 if (!precise) {
2371 #ifdef USE_MONO_CTX
2372                         sgen_conservatively_pin_objects_from ((void**)&info->client_info.ctx, (void**)&info->client_info.ctx + ARCH_NUM_REGS,
2373                                 start_nursery, end_nursery, PIN_TYPE_STACK);
2374 #else
2375                         sgen_conservatively_pin_objects_from ((void**)&info->client_info.regs, (void**)&info->client_info.regs + ARCH_NUM_REGS,
2376                                         start_nursery, end_nursery, PIN_TYPE_STACK);
2377 #endif
2378                 }
2379         } END_FOREACH_THREAD
2380 }
2381
2382 /*
2383  * mono_gc_set_stack_end:
2384  *
2385  *   Set the end of the current threads stack to STACK_END. The stack space between 
2386  * STACK_END and the real end of the threads stack will not be scanned during collections.
2387  */
2388 void
2389 mono_gc_set_stack_end (void *stack_end)
2390 {
2391         SgenThreadInfo *info;
2392
2393         LOCK_GC;
2394         info = mono_thread_info_current ();
2395         if (info) {
2396                 SGEN_ASSERT (0, stack_end < info->client_info.stack_end, "Can only lower stack end");
2397                 info->client_info.stack_end = stack_end;
2398         }
2399         UNLOCK_GC;
2400 }
2401
2402 /*
2403  * Roots
2404  */
2405
2406 int
2407 mono_gc_register_root (char *start, size_t size, MonoGCDescriptor descr)
2408 {
2409         return sgen_register_root (start, size, descr, descr ? ROOT_TYPE_NORMAL : ROOT_TYPE_PINNED);
2410 }
2411
2412 int
2413 mono_gc_register_root_wbarrier (char *start, size_t size, MonoGCDescriptor descr)
2414 {
2415         return sgen_register_root (start, size, descr, ROOT_TYPE_WBARRIER);
2416 }
2417
2418 void
2419 mono_gc_deregister_root (char* addr)
2420 {
2421         sgen_deregister_root (addr);
2422 }
2423
2424 /*
2425  * PThreads
2426  */
2427
2428 #ifndef HOST_WIN32
2429 int
2430 mono_gc_pthread_create (pthread_t *new_thread, const pthread_attr_t *attr, void *(*start_routine)(void *), void *arg)
2431 {
2432         return pthread_create (new_thread, attr, start_routine, arg);
2433 }
2434 #endif
2435
2436 /*
2437  * Miscellaneous
2438  */
2439
2440 void
2441 sgen_client_total_allocated_heap_changed (size_t allocated_heap)
2442 {
2443         mono_runtime_resource_check_limit (MONO_RESOURCE_GC_HEAP, allocated_heap);
2444 }
2445
2446 gboolean
2447 mono_gc_user_markers_supported (void)
2448 {
2449         return TRUE;
2450 }
2451
2452 gboolean
2453 mono_object_is_alive (MonoObject* o)
2454 {
2455         return TRUE;
2456 }
2457
2458 int
2459 mono_gc_get_generation (MonoObject *obj)
2460 {
2461         if (sgen_ptr_in_nursery (obj))
2462                 return 0;
2463         return 1;
2464 }
2465
2466 void
2467 mono_gc_enable_events (void)
2468 {
2469 }
2470
2471 const char *
2472 mono_gc_get_gc_name (void)
2473 {
2474         return "sgen";
2475 }
2476
2477 char*
2478 mono_gc_get_description (void)
2479 {
2480         return g_strdup ("sgen");
2481 }
2482
2483 void
2484 mono_gc_set_desktop_mode (void)
2485 {
2486 }
2487
2488 gboolean
2489 mono_gc_is_moving (void)
2490 {
2491         return TRUE;
2492 }
2493
2494 gboolean
2495 mono_gc_is_disabled (void)
2496 {
2497         return FALSE;
2498 }
2499
2500 #ifdef HOST_WIN32
2501 BOOL APIENTRY mono_gc_dllmain (HMODULE module_handle, DWORD reason, LPVOID reserved)
2502 {
2503         return TRUE;
2504 }
2505 #endif
2506
2507 int
2508 mono_gc_max_generation (void)
2509 {
2510         return 1;
2511 }
2512
2513 gboolean
2514 mono_gc_precise_stack_mark_enabled (void)
2515 {
2516         return !conservative_stack_mark;
2517 }
2518
2519 void
2520 mono_gc_collect (int generation)
2521 {
2522         sgen_gc_collect (generation);
2523 }
2524
2525 int
2526 mono_gc_collection_count (int generation)
2527 {
2528         return sgen_gc_collection_count (generation);
2529 }
2530
2531 int64_t
2532 mono_gc_get_used_size (void)
2533 {
2534         return (int64_t)sgen_gc_get_used_size ();
2535 }
2536
2537 int64_t
2538 mono_gc_get_heap_size (void)
2539 {
2540         return (int64_t)sgen_gc_get_total_heap_allocation ();
2541 }
2542
2543 MonoGCDescriptor
2544 mono_gc_make_root_descr_user (MonoGCRootMarkFunc marker)
2545 {
2546         return sgen_make_user_root_descriptor (marker);
2547 }
2548
2549 MonoGCDescriptor
2550 mono_gc_make_descr_for_string (gsize *bitmap, int numbits)
2551 {
2552         return SGEN_DESC_STRING;
2553 }
2554
2555 void*
2556 mono_gc_get_nursery (int *shift_bits, size_t *size)
2557 {
2558         *size = sgen_nursery_size;
2559         *shift_bits = DEFAULT_NURSERY_BITS;
2560         return sgen_get_nursery_start ();
2561 }
2562
2563 int
2564 mono_gc_get_los_limit (void)
2565 {
2566         return SGEN_MAX_SMALL_OBJ_SIZE;
2567 }
2568
2569 void
2570 mono_gc_weak_link_add (void **link_addr, MonoObject *obj, gboolean track)
2571 {
2572         sgen_register_disappearing_link (obj, link_addr, track, FALSE);
2573 }
2574
2575 void
2576 mono_gc_weak_link_remove (void **link_addr, gboolean track)
2577 {
2578         sgen_register_disappearing_link (NULL, link_addr, track, FALSE);
2579 }
2580
2581 MonoObject*
2582 mono_gc_weak_link_get (void **link_addr)
2583 {
2584         return sgen_weak_link_get (link_addr);
2585 }
2586
2587 gboolean
2588 mono_gc_set_allow_synchronous_major (gboolean flag)
2589 {
2590         return sgen_set_allow_synchronous_major (flag);
2591 }
2592
2593 void*
2594 mono_gc_invoke_with_gc_lock (MonoGCLockedCallbackFunc func, void *data)
2595 {
2596         void *result;
2597         LOCK_INTERRUPTION;
2598         result = func (data);
2599         UNLOCK_INTERRUPTION;
2600         return result;
2601 }
2602
2603 void
2604 mono_gc_register_altstack (gpointer stack, gint32 stack_size, gpointer altstack, gint32 altstack_size)
2605 {
2606         // FIXME:
2607 }
2608
2609 void
2610 sgen_client_out_of_memory (size_t size)
2611 {
2612         mono_gc_out_of_memory (size);
2613 }
2614
2615 guint8*
2616 mono_gc_get_card_table (int *shift_bits, gpointer *mask)
2617 {
2618         return sgen_get_card_table_configuration (shift_bits, mask);
2619 }
2620
2621 gboolean
2622 mono_gc_card_table_nursery_check (void)
2623 {
2624         return !sgen_get_major_collector ()->is_concurrent;
2625 }
2626
2627 /* Negative value to remove */
2628 void
2629 mono_gc_add_memory_pressure (gint64 value)
2630 {
2631         /* FIXME: Implement at some point? */
2632 }
2633
2634 /*
2635  * Logging
2636  */
2637
2638 void
2639 sgen_client_degraded_allocation (size_t size)
2640 {
2641         static int last_major_gc_warned = -1;
2642         static int num_degraded = 0;
2643
2644         if (last_major_gc_warned < gc_stats.major_gc_count) {
2645                 ++num_degraded;
2646                 if (num_degraded == 1 || num_degraded == 3)
2647                         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_GC, "Warning: Degraded allocation.  Consider increasing nursery-size if the warning persists.");
2648                 else if (num_degraded == 10)
2649                         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_GC, "Warning: Repeated degraded allocation.  Consider increasing nursery-size.");
2650                 last_major_gc_warned = gc_stats.major_gc_count;
2651         }
2652 }
2653
2654 void
2655 sgen_client_log_timing (GGTimingInfo *info, mword last_major_num_sections, mword last_los_memory_usage)
2656 {
2657         SgenMajorCollector *major_collector = sgen_get_major_collector ();
2658         mword num_major_sections = major_collector->get_num_major_sections ();
2659         char full_timing_buff [1024];
2660         full_timing_buff [0] = '\0';
2661
2662         if (!info->is_overflow)
2663                 sprintf (full_timing_buff, "total %.2fms, bridge %.2fms", info->stw_time / 10000.0f, (int)info->bridge_time / 10000.0f);
2664         if (info->generation == GENERATION_OLD)
2665                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_GC, "GC_MAJOR%s: (%s) pause %.2fms, %s major %dK/%dK los %dK/%dK",
2666                         info->is_overflow ? "_OVERFLOW" : "",
2667                         info->reason ? info->reason : "",
2668                         (int)info->total_time / 10000.0f,
2669                         full_timing_buff,
2670                         major_collector->section_size * num_major_sections / 1024,
2671                         major_collector->section_size * last_major_num_sections / 1024,
2672                         los_memory_usage / 1024,
2673                         last_los_memory_usage / 1024);
2674         else
2675                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_GC, "GC_MINOR%s: (%s) pause %.2fms, %s promoted %dK major %dK los %dK",
2676                                 info->is_overflow ? "_OVERFLOW" : "",
2677                         info->reason ? info->reason : "",
2678                         (int)info->total_time / 10000.0f,
2679                         full_timing_buff,
2680                         (num_major_sections - last_major_num_sections) * major_collector->section_size / 1024,
2681                         major_collector->section_size * num_major_sections / 1024,
2682                         los_memory_usage / 1024);
2683 }
2684
2685 /*
2686  * Debugging
2687  */
2688
2689 const char*
2690 sgen_client_description_for_internal_mem_type (int type)
2691 {
2692         switch (type) {
2693         case INTERNAL_MEM_EPHEMERON_LINK: return "ephemeron-link";
2694         default:
2695                 return NULL;
2696         }
2697 }
2698
2699 void
2700 sgen_client_pre_collection_checks (void)
2701 {
2702         if (sgen_mono_xdomain_checks) {
2703                 sgen_clear_nursery_fragments ();
2704                 sgen_check_for_xdomain_refs ();
2705         }
2706 }
2707
2708 gboolean
2709 sgen_client_vtable_is_inited (MonoVTable *vt)
2710 {
2711         return vt->klass->inited;
2712 }
2713
2714 const char*
2715 sgen_client_vtable_get_namespace (MonoVTable *vt)
2716 {
2717         return vt->klass->name_space;
2718 }
2719
2720 const char*
2721 sgen_client_vtable_get_name (MonoVTable *vt)
2722 {
2723         return vt->klass->name;
2724 }
2725
2726 /*
2727  * Initialization
2728  */
2729
2730 void
2731 sgen_client_init (void)
2732 {
2733         int dummy;
2734         MonoThreadInfoCallbacks cb;
2735
2736         cb.thread_register = sgen_thread_register;
2737         cb.thread_detach = sgen_thread_detach;
2738         cb.thread_unregister = sgen_thread_unregister;
2739         cb.thread_attach = sgen_thread_attach;
2740         cb.mono_method_is_critical = (gpointer)is_critical_method;
2741         cb.mono_thread_in_critical_region = thread_in_critical_region;
2742
2743         mono_threads_init (&cb, sizeof (SgenThreadInfo));
2744
2745         ///* Keep this the default for now */
2746         /* Precise marking is broken on all supported targets. Disable until fixed. */
2747         conservative_stack_mark = TRUE;
2748
2749         sgen_register_fixed_internal_mem_type (INTERNAL_MEM_EPHEMERON_LINK, sizeof (EphemeronLinkNode));
2750
2751         mono_sgen_init_stw ();
2752
2753 #ifndef HAVE_KW_THREAD
2754         mono_native_tls_alloc (&thread_info_key, NULL);
2755 #if defined(TARGET_OSX) || defined(TARGET_WIN32) || defined(TARGET_ANDROID) || defined(TARGET_IOS)
2756         /* 
2757          * CEE_MONO_TLS requires the tls offset, not the key, so the code below only works on darwin,
2758          * where the two are the same.
2759          */
2760         mono_tls_key_set_offset (TLS_KEY_SGEN_THREAD_INFO, thread_info_key);
2761 #endif
2762 #else
2763         {
2764                 int tls_offset = -1;
2765                 MONO_THREAD_VAR_OFFSET (sgen_thread_info, tls_offset);
2766                 mono_tls_key_set_offset (TLS_KEY_SGEN_THREAD_INFO, tls_offset);
2767         }
2768 #endif
2769
2770         /*
2771          * This needs to happen before any internal allocations because
2772          * it inits the small id which is required for hazard pointer
2773          * operations.
2774          */
2775         sgen_os_init ();
2776
2777         mono_gc_register_thread (&dummy);
2778 }
2779
2780 gboolean
2781 sgen_client_handle_gc_param (const char *opt)
2782 {
2783         if (g_str_has_prefix (opt, "stack-mark=")) {
2784                 opt = strchr (opt, '=') + 1;
2785                 if (!strcmp (opt, "precise")) {
2786                         conservative_stack_mark = FALSE;
2787                 } else if (!strcmp (opt, "conservative")) {
2788                         conservative_stack_mark = TRUE;
2789                 } else {
2790                         sgen_env_var_error (MONO_GC_PARAMS_NAME, conservative_stack_mark ? "Using `conservative`." : "Using `precise`.",
2791                                         "Invalid value `%s` for `stack-mark` option, possible values are: `precise`, `conservative`.", opt);
2792                 }
2793         } else if (g_str_has_prefix (opt, "bridge-implementation=")) {
2794                 opt = strchr (opt, '=') + 1;
2795                 sgen_set_bridge_implementation (opt);
2796         } else if (g_str_has_prefix (opt, "toggleref-test")) {
2797                 /* FIXME: This should probably in MONO_GC_DEBUG */
2798                 sgen_register_test_toggleref_callback ();
2799         } else {
2800                 return FALSE;
2801         }
2802         return TRUE;
2803 }
2804
2805 void
2806 sgen_client_print_gc_params_usage (void)
2807 {
2808         fprintf (stderr, "  stack-mark=MARK-METHOD (where MARK-METHOD is 'precise' or 'conservative')\n");
2809 }
2810
2811 gboolean
2812 sgen_client_handle_gc_debug (const char *opt)
2813 {
2814         if (!strcmp (opt, "xdomain-checks")) {
2815                 sgen_mono_xdomain_checks = TRUE;
2816         } else if (!strcmp (opt, "do-not-finalize")) {
2817                 do_not_finalize = TRUE;
2818         } else if (!strcmp (opt, "log-finalizers")) {
2819                 log_finalizers = TRUE;
2820         } else if (!strcmp (opt, "no-managed-allocator")) {
2821                 sgen_set_use_managed_allocator (FALSE);
2822         } else if (!sgen_bridge_handle_gc_debug (opt)) {
2823                 return FALSE;
2824         }
2825         return TRUE;
2826 }
2827
2828 void
2829 sgen_client_print_gc_debug_usage (void)
2830 {
2831         fprintf (stderr, "  xdomain-checks\n");
2832         fprintf (stderr, "  do-not-finalize\n");
2833         fprintf (stderr, "  log-finalizers\n");
2834         fprintf (stderr, "  no-managed-allocator\n");
2835         sgen_bridge_print_gc_debug_usage ();
2836 }
2837
2838
2839 gpointer
2840 sgen_client_get_provenance (void)
2841 {
2842 #ifdef SGEN_OBJECT_PROVENANCE
2843         MonoGCCallbacks *cb = mono_gc_get_gc_callbacks ();
2844         gpointer (*get_provenance_func) (void);
2845         if (!cb)
2846                 return NULL;
2847         get_provenance_func = cb->get_provenance_func;
2848         if (get_provenance_func)
2849                 return get_provenance_func ();
2850         return NULL;
2851 #else
2852         return NULL;
2853 #endif
2854 }
2855
2856 void
2857 sgen_client_describe_invalid_pointer (GCObject *ptr)
2858 {
2859         sgen_bridge_describe_pointer (ptr);
2860 }
2861
2862 void
2863 mono_gc_base_init (void)
2864 {
2865         mono_counters_init ();
2866
2867 #ifdef HEAVY_STATISTICS
2868         mono_counters_register ("los marked cards", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &los_marked_cards);
2869         mono_counters_register ("los array cards scanned ", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &los_array_cards);
2870         mono_counters_register ("los array remsets", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &los_array_remsets);
2871
2872         mono_counters_register ("WBarrier set arrayref", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_wbarrier_set_arrayref);
2873         mono_counters_register ("WBarrier value copy", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_wbarrier_value_copy);
2874         mono_counters_register ("WBarrier object copy", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_wbarrier_object_copy);
2875 #endif
2876
2877         sgen_gc_init ();
2878
2879         if (nursery_canaries_enabled ())
2880                 sgen_set_use_managed_allocator (FALSE);
2881 }
2882
2883 void
2884 mono_gc_base_cleanup (void)
2885 {
2886 }
2887
2888 gboolean
2889 mono_gc_is_null (void)
2890 {
2891         return FALSE;
2892 }
2893
2894 #endif