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