2 * boehm-gc.c: GC implementation using either the installed or included Boehm GC.
4 * Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
5 * Copyright 2004-2011 Novell, Inc (http://www.novell.com)
6 * Copyright 2011-2012 Xamarin, Inc (http://www.xamarin.com)
13 #define GC_I_HIDE_POINTERS
14 #include <mono/metadata/gc-internals.h>
15 #include <mono/metadata/mono-gc.h>
16 #include <mono/metadata/profiler-private.h>
17 #include <mono/metadata/class-internals.h>
18 #include <mono/metadata/method-builder.h>
19 #include <mono/metadata/opcodes.h>
20 #include <mono/metadata/domain-internals.h>
21 #include <mono/metadata/metadata-internals.h>
22 #include <mono/metadata/marshal.h>
23 #include <mono/metadata/runtime.h>
24 #include <mono/metadata/sgen-toggleref.h>
25 #include <mono/utils/atomic.h>
26 #include <mono/utils/mono-logger-internals.h>
27 #include <mono/utils/mono-memory-model.h>
28 #include <mono/utils/mono-time.h>
29 #include <mono/utils/mono-threads.h>
30 #include <mono/utils/dtrace.h>
31 #include <mono/utils/gc_wrapper.h>
32 #include <mono/utils/mono-mutex.h>
33 #include <mono/utils/mono-counters.h>
39 #define THREAD_LOCAL_ALLOC 1
40 #include "private/pthread_support.h"
42 #if defined(PLATFORM_MACOSX) && defined(HAVE_PTHREAD_GET_STACKADDR_NP)
43 void *pthread_get_stackaddr_np(pthread_t);
46 #define GC_NO_DESCRIPTOR ((gpointer)(0 | GC_DS_LENGTH))
47 /*Boehm max heap cannot be smaller than 16MB*/
48 #define MIN_BOEHM_MAX_HEAP_SIZE_IN_MB 16
49 #define MIN_BOEHM_MAX_HEAP_SIZE (MIN_BOEHM_MAX_HEAP_SIZE_IN_MB << 20)
51 static gboolean gc_initialized = FALSE;
52 static mono_mutex_t mono_gc_lock;
55 boehm_thread_register (MonoThreadInfo* info, void *baseptr);
57 boehm_thread_unregister (MonoThreadInfo *p);
59 register_test_toggleref_callback (void);
61 #define BOEHM_GC_BIT_FINALIZER_AWARE 1
62 static MonoGCFinalizerCallbacks fin_callbacks;
66 static mono_mutex_t handle_section;
67 #define lock_handles(handles) mono_mutex_lock (&handle_section)
68 #define unlock_handles(handles) mono_mutex_unlock (&handle_section)
75 guint slot_hint : 24; /* starting slot for search in bitmap */
76 /* 2^16 appdomains should be enough for everyone (though I know I'll regret this in 20 years) */
77 /* we alloc this only for weak refs, since we can get the domain directly in the other cases */
81 #define EMPTY_HANDLE_DATA(type) {NULL, NULL, 0, (type), 0, NULL}
83 /* weak and weak-track arrays will be allocated in malloc memory
85 static HandleData gc_handles [] = {
86 EMPTY_HANDLE_DATA (HANDLE_WEAK),
87 EMPTY_HANDLE_DATA (HANDLE_WEAK_TRACK),
88 EMPTY_HANDLE_DATA (HANDLE_NORMAL),
89 EMPTY_HANDLE_DATA (HANDLE_PINNED)
93 mono_gc_warning (char *msg, GC_word arg)
95 mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_GC, msg, (unsigned long)arg);
99 mono_gc_base_init (void)
101 MonoThreadInfoCallbacks cb;
108 mono_counters_init ();
111 * Handle the case when we are called from a thread different from the main thread,
113 * FIXME: Move this to libgc where it belongs.
115 * we used to do this only when running on valgrind,
116 * but it happens also in other setups.
118 #if defined(HAVE_PTHREAD_GETATTR_NP) && defined(HAVE_PTHREAD_ATTR_GETSTACK) && !defined(__native_client__)
123 pthread_getattr_np (pthread_self (), &attr);
124 pthread_attr_getstack (&attr, &sstart, &size);
125 pthread_attr_destroy (&attr);
126 /*g_print ("stackbottom pth is: %p\n", (char*)sstart + size);*/
129 * The calculation above doesn't seem to work on ia64, also we need to set
130 * GC_register_stackbottom as well, but don't know how.
133 /* apparently with some linuxthreads implementations sstart can be NULL,
134 * fallback to the more imprecise method (bug# 78096).
137 GC_stackbottom = (char*)sstart + size;
140 gsize stack_bottom = (gsize)&dummy;
141 stack_bottom += 4095;
142 stack_bottom &= ~4095;
143 GC_stackbottom = (char*)stack_bottom;
147 #elif defined(HAVE_PTHREAD_GET_STACKSIZE_NP) && defined(HAVE_PTHREAD_GET_STACKADDR_NP)
148 GC_stackbottom = (char*)pthread_get_stackaddr_np (pthread_self ());
149 #elif defined(__OpenBSD__)
150 # include <pthread_np.h>
155 rslt = pthread_stackseg_np(pthread_self(), &ss);
156 g_assert (rslt == 0);
158 GC_stackbottom = (char*)ss.ss_sp;
160 #elif defined(__native_client__)
161 /* Do nothing, GC_stackbottom is set correctly in libgc */
165 gsize stack_bottom = (gsize)&dummy;
166 stack_bottom += 4095;
167 stack_bottom &= ~4095;
168 /*g_print ("stackbottom is: %p\n", (char*)stack_bottom);*/
169 GC_stackbottom = (char*)stack_bottom;
173 #if !defined(PLATFORM_ANDROID)
174 /* If GC_no_dls is set to true, GC_find_limit is not called. This causes a seg fault on Android. */
178 if ((env = g_getenv ("MONO_GC_DEBUG"))) {
179 char **opts = g_strsplit (env, ",", -1);
180 for (char **ptr = opts; ptr && *ptr; ptr ++) {
182 if (!strcmp (opt, "do-not-finalize")) {
183 mono_do_not_finalize = 1;
184 } else if (!strcmp (opt, "log-finalizers")) {
193 GC_oom_fn = mono_gc_out_of_memory;
194 GC_set_warn_proc (mono_gc_warning);
195 GC_finalize_on_demand = 1;
196 GC_finalizer_notifier = mono_gc_finalize_notify;
198 GC_init_gcj_malloc (5, NULL);
200 if ((env = g_getenv ("MONO_GC_PARAMS"))) {
201 char **ptr, **opts = g_strsplit (env, ",", -1);
202 for (ptr = opts; *ptr; ++ptr) {
204 if (g_str_has_prefix (opt, "max-heap-size=")) {
207 opt = strchr (opt, '=') + 1;
208 if (*opt && mono_gc_parse_environment_string_extract_number (opt, &max_heap)) {
209 if (max_heap < MIN_BOEHM_MAX_HEAP_SIZE) {
210 fprintf (stderr, "max-heap-size must be at least %dMb.\n", MIN_BOEHM_MAX_HEAP_SIZE_IN_MB);
213 GC_set_max_heap_size (max_heap);
215 fprintf (stderr, "max-heap-size must be an integer.\n");
219 } else if (g_str_has_prefix (opt, "toggleref-test")) {
220 register_test_toggleref_callback ();
223 /* Could be a parameter for sgen */
225 fprintf (stderr, "MONO_GC_PARAMS must be a comma-delimited list of one or more of the following:\n");
226 fprintf (stderr, " max-heap-size=N (where N is an integer, possibly with a k, m or a g suffix)\n");
234 memset (&cb, 0, sizeof (cb));
235 cb.thread_register = boehm_thread_register;
236 cb.thread_unregister = boehm_thread_unregister;
237 cb.mono_method_is_critical = (gpointer)mono_runtime_is_critical_method;
239 mono_threads_init (&cb, sizeof (MonoThreadInfo));
240 mono_mutex_init (&mono_gc_lock);
241 mono_mutex_init_recursive (&handle_section);
243 mono_thread_info_attach (&dummy);
245 mono_gc_enable_events ();
247 MONO_GC_REGISTER_ROOT_FIXED (gc_handles [HANDLE_NORMAL].entries, MONO_ROOT_SOURCE_GC_HANDLE, "gc handles table");
248 MONO_GC_REGISTER_ROOT_FIXED (gc_handles [HANDLE_PINNED].entries, MONO_ROOT_SOURCE_GC_HANDLE, "gc handles table");
250 gc_initialized = TRUE;
254 mono_gc_base_cleanup (void)
256 GC_finalizer_notifier = NULL;
261 * @generation: GC generation identifier
263 * Perform a garbage collection for the given generation, higher numbers
264 * mean usually older objects. Collecting a high-numbered generation
265 * implies collecting also the lower-numbered generations.
266 * The maximum value for @generation can be retrieved with a call to
267 * mono_gc_max_generation(), so this function is usually called as:
269 * mono_gc_collect (mono_gc_max_generation ());
272 mono_gc_collect (int generation)
274 #ifndef DISABLE_PERFCOUNTERS
275 mono_perfcounters->gc_induced++;
281 * mono_gc_max_generation:
283 * Get the maximum generation number used by the current garbage
284 * collector. The value will be 0 for the Boehm collector, 1 or more
285 * for the generational collectors.
287 * Returns: the maximum generation number.
290 mono_gc_max_generation (void)
296 * mono_gc_get_generation:
297 * @object: a managed object
299 * Get the garbage collector's generation that @object belongs to.
300 * Use this has a hint only.
302 * Returns: a garbage collector generation number
305 mono_gc_get_generation (MonoObject *object)
311 * mono_gc_collection_count:
312 * @generation: a GC generation number
314 * Get how many times a garbage collection has been performed
315 * for the given @generation number.
317 * Returns: the number of garbage collections
320 mono_gc_collection_count (int generation)
326 * mono_gc_add_memory_pressure:
327 * @value: amount of bytes
329 * Adjust the garbage collector's view of how many bytes of memory
330 * are indirectly referenced by managed objects (for example unmanaged
331 * memory holding image or other binary data).
332 * This is a hint only to the garbage collector algorithm.
333 * Note that negative amounts of @value will decrease the memory
337 mono_gc_add_memory_pressure (gint64 value)
342 * mono_gc_get_used_size:
344 * Get the approximate amount of memory used by managed objects.
346 * Returns: the amount of memory used in bytes
349 mono_gc_get_used_size (void)
351 return GC_get_heap_size () - GC_get_free_bytes ();
355 * mono_gc_get_heap_size:
357 * Get the amount of memory used by the garbage collector.
359 * Returns: the size of the heap in bytes
362 mono_gc_get_heap_size (void)
364 return GC_get_heap_size ();
368 mono_gc_is_gc_thread (void)
370 return GC_thread_is_registered ();
373 extern int GC_thread_register_foreign (void *base_addr);
376 mono_gc_register_thread (void *baseptr)
378 return mono_thread_info_attach (baseptr) != NULL;
382 boehm_thread_register (MonoThreadInfo* info, void *baseptr)
384 if (mono_gc_is_gc_thread())
386 #if !defined(HOST_WIN32)
387 return GC_thread_register_foreign (baseptr) ? info : NULL;
394 boehm_thread_unregister (MonoThreadInfo *p)
396 MonoNativeThreadId tid;
398 tid = mono_thread_info_get_tid (p);
400 if (p->runtime_thread)
401 mono_threads_add_joinable_thread ((gpointer)tid);
405 mono_object_is_alive (MonoObject* o)
407 return GC_is_marked ((gpointer)o);
411 mono_gc_walk_heap (int flags, MonoGCReferences callback, void *data)
416 static gint64 gc_start_time;
419 on_gc_notification (GCEventType event)
421 MonoGCEvent e = (MonoGCEvent)event;
424 case MONO_GC_EVENT_PRE_STOP_WORLD:
425 MONO_GC_WORLD_STOP_BEGIN ();
426 mono_thread_info_suspend_lock ();
429 case MONO_GC_EVENT_POST_STOP_WORLD:
430 MONO_GC_WORLD_STOP_END ();
433 case MONO_GC_EVENT_PRE_START_WORLD:
434 MONO_GC_WORLD_RESTART_BEGIN (1);
437 case MONO_GC_EVENT_POST_START_WORLD:
438 MONO_GC_WORLD_RESTART_END (1);
439 mono_thread_info_suspend_unlock ();
442 case MONO_GC_EVENT_START:
444 #ifndef DISABLE_PERFCOUNTERS
445 if (mono_perfcounters)
446 mono_perfcounters->gc_collections0++;
448 gc_stats.major_gc_count ++;
449 gc_start_time = mono_100ns_ticks ();
452 case MONO_GC_EVENT_END:
454 #if defined(ENABLE_DTRACE) && defined(__sun__)
455 /* This works around a dtrace -G problem on Solaris.
456 Limit its actual use to when the probe is enabled. */
457 if (MONO_GC_END_ENABLED ())
461 #ifndef DISABLE_PERFCOUNTERS
462 if (mono_perfcounters) {
463 guint64 heap_size = GC_get_heap_size ();
464 guint64 used_size = heap_size - GC_get_free_bytes ();
465 mono_perfcounters->gc_total_bytes = used_size;
466 mono_perfcounters->gc_committed_bytes = heap_size;
467 mono_perfcounters->gc_reserved_bytes = heap_size;
468 mono_perfcounters->gc_gen0size = heap_size;
471 gc_stats.major_gc_time += mono_100ns_ticks () - gc_start_time;
472 mono_trace_message (MONO_TRACE_GC, "gc took %d usecs", (mono_100ns_ticks () - gc_start_time) / 10);
478 mono_profiler_gc_event (e, 0);
482 on_gc_heap_resize (size_t new_size)
484 guint64 heap_size = GC_get_heap_size ();
485 #ifndef DISABLE_PERFCOUNTERS
486 if (mono_perfcounters) {
487 mono_perfcounters->gc_committed_bytes = heap_size;
488 mono_perfcounters->gc_reserved_bytes = heap_size;
489 mono_perfcounters->gc_gen0size = heap_size;
492 mono_profiler_gc_heap_resize (new_size);
496 mono_gc_enable_events (void)
498 GC_notify_event = on_gc_notification;
499 GC_on_heap_resize = on_gc_heap_resize;
502 static gboolean alloc_events = FALSE;
505 mono_gc_enable_alloc_events (void)
511 mono_gc_register_root (char *start, size_t size, void *descr, MonoGCRootSource source, const char *msg)
513 /* for some strange reason, they want one extra byte on the end */
514 GC_add_roots (start, start + size + 1);
520 mono_gc_deregister_root (char* addr)
523 /* FIXME: libgc doesn't define this work win32 for some reason */
524 /* FIXME: No size info */
525 GC_remove_roots (addr, addr + sizeof (gpointer) + 1);
530 mono_gc_weak_link_add (void **link_addr, MonoObject *obj, gboolean track)
532 /* libgc requires that we use HIDE_POINTER... */
533 *link_addr = (void*)HIDE_POINTER (obj);
535 GC_REGISTER_LONG_LINK (link_addr, obj);
537 GC_GENERAL_REGISTER_DISAPPEARING_LINK (link_addr, obj);
541 mono_gc_weak_link_remove (void **link_addr, gboolean track)
544 GC_unregister_long_link (link_addr);
546 GC_unregister_disappearing_link (link_addr);
551 reveal_link (gpointer link_addr)
553 void **link_a = link_addr;
554 return REVEAL_POINTER (*link_a);
558 mono_gc_weak_link_get (void **link_addr)
560 MonoObject *obj = GC_call_with_alloc_lock (reveal_link, link_addr);
561 if (obj == (MonoObject *) -1)
567 mono_gc_make_descr_for_string (gsize *bitmap, int numbits)
569 return mono_gc_make_descr_from_bitmap (bitmap, numbits);
573 mono_gc_make_descr_for_object (gsize *bitmap, int numbits, size_t obj_size)
575 return mono_gc_make_descr_from_bitmap (bitmap, numbits);
579 mono_gc_make_descr_for_array (int vector, gsize *elem_bitmap, int numbits, size_t elem_size)
581 /* libgc has no usable support for arrays... */
582 return GC_NO_DESCRIPTOR;
586 mono_gc_make_descr_from_bitmap (gsize *bitmap, int numbits)
588 /* It seems there are issues when the bitmap doesn't fit: play it safe */
590 return GC_NO_DESCRIPTOR;
592 return (gpointer)GC_make_descriptor ((GC_bitmap)bitmap, numbits);
596 mono_gc_make_root_descr_all_refs (int numbits)
602 mono_gc_alloc_fixed (size_t size, void *descr, MonoGCRootSource source, const char *msg)
604 /* To help track down typed allocation bugs */
608 if (count == atoi (g_getenv ("COUNT2")))
610 if (count > atoi (g_getenv ("COUNT2")))
611 return GC_MALLOC (size);
615 return GC_MALLOC_EXPLICITLY_TYPED (size, (GC_descr)descr);
617 return GC_MALLOC (size);
621 mono_gc_free_fixed (void* addr)
626 mono_gc_alloc_obj (MonoVTable *vtable, size_t size)
630 if (!vtable->klass->has_references) {
631 obj = GC_MALLOC_ATOMIC (size);
633 obj->vtable = vtable;
634 obj->synchronisation = NULL;
636 memset ((char *) obj + sizeof (MonoObject), 0, size - sizeof (MonoObject));
637 } else if (vtable->gc_descr != GC_NO_DESCRIPTOR) {
638 obj = GC_GCJ_MALLOC (size, vtable);
640 obj = GC_MALLOC (size);
642 obj->vtable = vtable;
645 if (G_UNLIKELY (alloc_events))
646 mono_profiler_allocation (obj);
652 mono_gc_alloc_vector (MonoVTable *vtable, size_t size, uintptr_t max_length)
656 if (!vtable->klass->has_references) {
657 obj = GC_MALLOC_ATOMIC (size);
659 obj->obj.vtable = vtable;
660 obj->obj.synchronisation = NULL;
662 memset ((char *) obj + sizeof (MonoObject), 0, size - sizeof (MonoObject));
663 } else if (vtable->gc_descr != GC_NO_DESCRIPTOR) {
664 obj = GC_GCJ_MALLOC (size, vtable);
666 obj = GC_MALLOC (size);
668 obj->obj.vtable = vtable;
671 obj->max_length = max_length;
673 if (G_UNLIKELY (alloc_events))
674 mono_profiler_allocation (&obj->obj);
680 mono_gc_alloc_array (MonoVTable *vtable, size_t size, uintptr_t max_length, uintptr_t bounds_size)
684 if (!vtable->klass->has_references) {
685 obj = GC_MALLOC_ATOMIC (size);
687 obj->obj.vtable = vtable;
688 obj->obj.synchronisation = NULL;
690 memset ((char *) obj + sizeof (MonoObject), 0, size - sizeof (MonoObject));
691 } else if (vtable->gc_descr != GC_NO_DESCRIPTOR) {
692 obj = GC_GCJ_MALLOC (size, vtable);
694 obj = GC_MALLOC (size);
696 obj->obj.vtable = vtable;
699 obj->max_length = max_length;
702 obj->bounds = (MonoArrayBounds *) ((char *) obj + size - bounds_size);
704 if (G_UNLIKELY (alloc_events))
705 mono_profiler_allocation (&obj->obj);
711 mono_gc_alloc_string (MonoVTable *vtable, size_t size, gint32 len)
713 MonoString *obj = GC_MALLOC_ATOMIC (size);
715 obj->object.vtable = vtable;
716 obj->object.synchronisation = NULL;
718 obj->chars [len] = 0;
720 if (G_UNLIKELY (alloc_events))
721 mono_profiler_allocation (&obj->object);
727 mono_gc_invoke_finalizers (void)
729 /* There is a bug in GC_invoke_finalizer () in versions <= 6.2alpha4:
730 * the 'mem_freed' variable is not initialized when there are no
731 * objects to finalize, which leads to strange behavior later on.
732 * The check is necessary to work around that bug.
734 if (GC_should_invoke_finalizers ())
735 return GC_invoke_finalizers ();
740 mono_gc_pending_finalizers (void)
742 return GC_should_invoke_finalizers ();
746 mono_gc_wbarrier_set_field (MonoObject *obj, gpointer field_ptr, MonoObject* value)
748 *(void**)field_ptr = value;
752 mono_gc_wbarrier_set_arrayref (MonoArray *arr, gpointer slot_ptr, MonoObject* value)
754 *(void**)slot_ptr = value;
758 mono_gc_wbarrier_arrayref_copy (gpointer dest_ptr, gpointer src_ptr, int count)
760 mono_gc_memmove_aligned (dest_ptr, src_ptr, count * sizeof (gpointer));
764 mono_gc_wbarrier_generic_store (gpointer ptr, MonoObject* value)
766 *(void**)ptr = value;
770 mono_gc_wbarrier_generic_store_atomic (gpointer ptr, MonoObject *value)
772 InterlockedWritePointer (ptr, value);
776 mono_gc_wbarrier_generic_nostore (gpointer ptr)
781 mono_gc_wbarrier_value_copy (gpointer dest, gpointer src, int count, MonoClass *klass)
783 mono_gc_memmove_atomic (dest, src, count * mono_class_value_size (klass, NULL));
787 mono_gc_wbarrier_object_copy (MonoObject* obj, MonoObject *src)
789 /* do not copy the sync state */
790 mono_gc_memmove_aligned ((char*)obj + sizeof (MonoObject), (char*)src + sizeof (MonoObject),
791 mono_object_class (obj)->instance_size - sizeof (MonoObject));
795 mono_gc_clear_domain (MonoDomain *domain)
800 mono_gc_get_suspend_signal (void)
802 return GC_get_suspend_signal ();
806 mono_gc_get_restart_signal (void)
808 return GC_get_restart_signal ();
811 #if defined(USE_COMPILER_TLS) && defined(__linux__) && (defined(__i386__) || defined(__x86_64__))
812 extern __thread MONO_TLS_FAST void* GC_thread_tls;
813 #include "metadata-internals.h"
819 while (!(v & (1 << i)))
826 ATYPE_FREEPTR_FOR_BOX,
834 create_allocator (int atype, int tls_key, gboolean slowpath)
836 int index_var, bytes_var, my_fl_var, my_entry_var;
837 guint32 no_freelist_branch, not_small_enough_branch = 0;
838 guint32 size_overflow_branch = 0;
839 MonoMethodBuilder *mb;
841 MonoMethodSignature *csig;
842 const char *name = NULL;
845 if (atype == ATYPE_FREEPTR) {
846 name = slowpath ? "SlowAllocPtrfree" : "AllocPtrfree";
847 } else if (atype == ATYPE_FREEPTR_FOR_BOX) {
848 name = slowpath ? "SlowAllocPtrfreeBox" : "AllocPtrfreeBox";
849 } else if (atype == ATYPE_NORMAL) {
850 name = slowpath ? "SlowAlloc" : "Alloc";
851 } else if (atype == ATYPE_GCJ) {
852 name = slowpath ? "SlowAllocGcj" : "AllocGcj";
853 } else if (atype == ATYPE_STRING) {
854 name = slowpath ? "SlowAllocString" : "AllocString";
856 g_assert_not_reached ();
859 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
861 if (atype == ATYPE_STRING) {
862 csig->ret = &mono_defaults.string_class->byval_arg;
863 csig->params [0] = &mono_defaults.int_class->byval_arg;
864 csig->params [1] = &mono_defaults.int32_class->byval_arg;
866 csig->ret = &mono_defaults.object_class->byval_arg;
867 csig->params [0] = &mono_defaults.int_class->byval_arg;
868 csig->params [1] = &mono_defaults.int32_class->byval_arg;
871 mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_ALLOC);
874 goto always_slowpath;
876 bytes_var = mono_mb_add_local (mb, &mono_defaults.int32_class->byval_arg);
877 if (atype == ATYPE_STRING) {
878 /* a string alloator method takes the args: (vtable, len) */
879 /* bytes = (offsetof (MonoString, chars) + ((len + 1) * 2)); */
880 mono_mb_emit_ldarg (mb, 1);
881 mono_mb_emit_icon (mb, 1);
882 mono_mb_emit_byte (mb, MONO_CEE_ADD);
883 mono_mb_emit_icon (mb, 1);
884 mono_mb_emit_byte (mb, MONO_CEE_SHL);
885 // sizeof (MonoString) might include padding
886 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoString, chars));
887 mono_mb_emit_byte (mb, MONO_CEE_ADD);
888 mono_mb_emit_stloc (mb, bytes_var);
890 mono_mb_emit_ldarg (mb, 1);
891 mono_mb_emit_stloc (mb, bytes_var);
894 /* this is needed for strings/arrays only as the other big types are never allocated with this method */
895 if (atype == ATYPE_STRING) {
897 /* if (!SMALL_ENOUGH (bytes)) jump slow_path;*/
898 mono_mb_emit_ldloc (mb, bytes_var);
899 mono_mb_emit_icon (mb, (NFREELISTS-1) * GRANULARITY);
900 not_small_enough_branch = mono_mb_emit_short_branch (mb, MONO_CEE_BGT_UN_S);
901 /* check for overflow */
902 mono_mb_emit_ldloc (mb, bytes_var);
903 mono_mb_emit_icon (mb, sizeof (MonoString));
904 size_overflow_branch = mono_mb_emit_short_branch (mb, MONO_CEE_BLE_UN_S);
907 /* int index = INDEX_FROM_BYTES(bytes); */
908 index_var = mono_mb_add_local (mb, &mono_defaults.int32_class->byval_arg);
910 mono_mb_emit_ldloc (mb, bytes_var);
911 mono_mb_emit_icon (mb, GRANULARITY - 1);
912 mono_mb_emit_byte (mb, MONO_CEE_ADD);
913 mono_mb_emit_icon (mb, shift_amount (GRANULARITY));
914 mono_mb_emit_byte (mb, MONO_CEE_SHR_UN);
915 mono_mb_emit_icon (mb, shift_amount (sizeof (gpointer)));
916 mono_mb_emit_byte (mb, MONO_CEE_SHL);
917 /* index var is already adjusted into bytes */
918 mono_mb_emit_stloc (mb, index_var);
920 my_fl_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
921 my_entry_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
922 /* my_fl = ((GC_thread)tsd) -> ptrfree_freelists + index; */
923 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
924 mono_mb_emit_byte (mb, 0x0D); /* CEE_MONO_TLS */
925 mono_mb_emit_i4 (mb, tls_key);
926 if (atype == ATYPE_FREEPTR || atype == ATYPE_FREEPTR_FOR_BOX || atype == ATYPE_STRING)
927 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (struct GC_Thread_Rep, ptrfree_freelists));
928 else if (atype == ATYPE_NORMAL)
929 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (struct GC_Thread_Rep, normal_freelists));
930 else if (atype == ATYPE_GCJ)
931 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (struct GC_Thread_Rep, gcj_freelists));
933 g_assert_not_reached ();
934 mono_mb_emit_byte (mb, MONO_CEE_ADD);
935 mono_mb_emit_ldloc (mb, index_var);
936 mono_mb_emit_byte (mb, MONO_CEE_ADD);
937 mono_mb_emit_stloc (mb, my_fl_var);
939 /* my_entry = *my_fl; */
940 mono_mb_emit_ldloc (mb, my_fl_var);
941 mono_mb_emit_byte (mb, MONO_CEE_LDIND_I);
942 mono_mb_emit_stloc (mb, my_entry_var);
944 /* if (EXPECT((word)my_entry >= HBLKSIZE, 1)) { */
945 mono_mb_emit_ldloc (mb, my_entry_var);
946 mono_mb_emit_icon (mb, HBLKSIZE);
947 no_freelist_branch = mono_mb_emit_short_branch (mb, MONO_CEE_BLT_UN_S);
949 /* ptr_t next = obj_link(my_entry); *my_fl = next; */
950 mono_mb_emit_ldloc (mb, my_fl_var);
951 mono_mb_emit_ldloc (mb, my_entry_var);
952 mono_mb_emit_byte (mb, MONO_CEE_LDIND_I);
953 mono_mb_emit_byte (mb, MONO_CEE_STIND_I);
955 /* set the vtable and clear the words in the object */
956 mono_mb_emit_ldloc (mb, my_entry_var);
957 mono_mb_emit_ldarg (mb, 0);
958 mono_mb_emit_byte (mb, MONO_CEE_STIND_I);
960 if (atype == ATYPE_FREEPTR) {
961 int start_var, end_var, start_loop;
962 /* end = my_entry + bytes; start = my_entry + sizeof (gpointer);
964 start_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
965 end_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
966 mono_mb_emit_ldloc (mb, my_entry_var);
967 mono_mb_emit_ldloc (mb, bytes_var);
968 mono_mb_emit_byte (mb, MONO_CEE_ADD);
969 mono_mb_emit_stloc (mb, end_var);
970 mono_mb_emit_ldloc (mb, my_entry_var);
971 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoObject, synchronisation));
972 mono_mb_emit_byte (mb, MONO_CEE_ADD);
973 mono_mb_emit_stloc (mb, start_var);
977 * } while (start < end);
979 start_loop = mono_mb_get_label (mb);
980 mono_mb_emit_ldloc (mb, start_var);
981 mono_mb_emit_icon (mb, 0);
982 mono_mb_emit_byte (mb, MONO_CEE_STIND_I);
983 mono_mb_emit_ldloc (mb, start_var);
984 mono_mb_emit_icon (mb, sizeof (gpointer));
985 mono_mb_emit_byte (mb, MONO_CEE_ADD);
986 mono_mb_emit_stloc (mb, start_var);
988 mono_mb_emit_ldloc (mb, start_var);
989 mono_mb_emit_ldloc (mb, end_var);
990 mono_mb_emit_byte (mb, MONO_CEE_BLT_UN_S);
991 mono_mb_emit_byte (mb, start_loop - (mono_mb_get_label (mb) + 1));
992 } else if (atype == ATYPE_FREEPTR_FOR_BOX || atype == ATYPE_STRING) {
993 /* need to clear just the sync pointer */
994 mono_mb_emit_ldloc (mb, my_entry_var);
995 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoObject, synchronisation));
996 mono_mb_emit_byte (mb, MONO_CEE_ADD);
997 mono_mb_emit_icon (mb, 0);
998 mono_mb_emit_byte (mb, MONO_CEE_STIND_I);
1001 if (atype == ATYPE_STRING) {
1002 /* need to set length and clear the last char */
1003 /* s->length = len; */
1004 mono_mb_emit_ldloc (mb, my_entry_var);
1005 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoString, length));
1006 mono_mb_emit_byte (mb, MONO_CEE_ADD);
1007 mono_mb_emit_ldarg (mb, 1);
1008 mono_mb_emit_byte (mb, MONO_CEE_STIND_I4);
1009 /* s->chars [len] = 0; */
1010 mono_mb_emit_ldloc (mb, my_entry_var);
1011 mono_mb_emit_ldloc (mb, bytes_var);
1012 mono_mb_emit_icon (mb, 2);
1013 mono_mb_emit_byte (mb, MONO_CEE_SUB);
1014 mono_mb_emit_byte (mb, MONO_CEE_ADD);
1015 mono_mb_emit_icon (mb, 0);
1016 mono_mb_emit_byte (mb, MONO_CEE_STIND_I2);
1019 /* return my_entry; */
1020 mono_mb_emit_ldloc (mb, my_entry_var);
1021 mono_mb_emit_byte (mb, MONO_CEE_RET);
1023 mono_mb_patch_short_branch (mb, no_freelist_branch);
1024 if (not_small_enough_branch > 0)
1025 mono_mb_patch_short_branch (mb, not_small_enough_branch);
1026 if (size_overflow_branch > 0)
1027 mono_mb_patch_short_branch (mb, size_overflow_branch);
1029 /* the slow path: we just call back into the runtime */
1031 if (atype == ATYPE_STRING) {
1032 mono_mb_emit_ldarg (mb, 1);
1033 mono_mb_emit_icall (mb, mono_string_alloc);
1035 mono_mb_emit_ldarg (mb, 0);
1036 mono_mb_emit_icall (mb, mono_object_new_specific);
1039 mono_mb_emit_byte (mb, MONO_CEE_RET);
1041 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
1042 info->d.alloc.gc_name = "boehm";
1043 info->d.alloc.alloc_type = atype;
1045 res = mono_mb_create (mb, csig, 8, info);
1047 mono_method_get_header (res)->init_locals = FALSE;
1052 static MonoMethod* alloc_method_cache [ATYPE_NUM];
1053 static MonoMethod* slowpath_alloc_method_cache [ATYPE_NUM];
1055 static G_GNUC_UNUSED gboolean
1056 mono_gc_is_critical_method (MonoMethod *method)
1060 for (i = 0; i < ATYPE_NUM; ++i)
1061 if (method == alloc_method_cache [i] || method == slowpath_alloc_method_cache [i])
1068 * If possible, generate a managed method that can quickly allocate objects in class
1069 * @klass. The method will typically have an thread-local inline allocation sequence.
1070 * The signature of the called method is:
1071 * object allocate (MonoVTable *vtable)
1072 * Some of the logic here is similar to mono_class_get_allocation_ftn () i object.c,
1074 * The thread local alloc logic is taken from libgc/pthread_support.c.
1078 mono_gc_get_managed_allocator (MonoClass *klass, gboolean for_box, gboolean known_instance_size)
1082 MONO_THREAD_VAR_OFFSET (GC_thread_tls, offset);
1084 /*g_print ("thread tls: %d\n", offset);*/
1087 if (!SMALL_ENOUGH (klass->instance_size))
1089 if (mono_class_has_finalizer (klass) || mono_class_is_marshalbyref (klass) || (mono_profiler_get_events () & MONO_PROFILE_ALLOCATIONS))
1093 if (mono_class_is_open_constructed_type (&klass->byval_arg))
1095 if (klass->byval_arg.type == MONO_TYPE_STRING) {
1096 atype = ATYPE_STRING;
1097 } else if (!known_instance_size) {
1099 } else if (!klass->has_references) {
1101 atype = ATYPE_FREEPTR_FOR_BOX;
1103 atype = ATYPE_FREEPTR;
1107 * disabled because we currently do a runtime choice anyway, to
1108 * deal with multiple appdomains.
1109 if (vtable->gc_descr != GC_NO_DESCRIPTOR)
1112 atype = ATYPE_NORMAL;
1115 return mono_gc_get_managed_allocator_by_type (atype, FALSE);
1119 mono_gc_get_managed_array_allocator (MonoClass *klass)
1125 * mono_gc_get_managed_allocator_by_type:
1127 * Return a managed allocator method corresponding to allocator type ATYPE.
1130 mono_gc_get_managed_allocator_by_type (int atype, gboolean slowpath)
1134 MonoMethod **cache = slowpath ? slowpath_alloc_method_cache : alloc_method_cache;
1135 MONO_THREAD_VAR_OFFSET (GC_thread_tls, offset);
1137 mono_tls_key_set_offset (TLS_KEY_BOEHM_GC_THREAD, offset);
1139 res = cache [atype];
1143 res = create_allocator (atype, TLS_KEY_BOEHM_GC_THREAD, slowpath);
1144 mono_mutex_lock (&mono_gc_lock);
1145 if (cache [atype]) {
1146 mono_free_method (res);
1147 res = cache [atype];
1149 mono_memory_barrier ();
1150 cache [atype] = res;
1152 mono_mutex_unlock (&mono_gc_lock);
1157 mono_gc_get_managed_allocator_types (void)
1163 mono_gc_get_write_barrier (void)
1165 g_assert_not_reached ();
1171 static G_GNUC_UNUSED gboolean
1172 mono_gc_is_critical_method (MonoMethod *method)
1178 mono_gc_get_managed_allocator (MonoClass *klass, gboolean for_box, gboolean known_instance_size)
1184 mono_gc_get_managed_array_allocator (MonoClass *klass)
1190 mono_gc_get_managed_allocator_by_type (int atype, gboolean slowpath)
1196 mono_gc_get_managed_allocator_types (void)
1202 mono_gc_get_write_barrier (void)
1204 g_assert_not_reached ();
1211 mono_gc_get_specific_write_barrier (gboolean is_concurrent)
1213 g_assert_not_reached ();
1218 mono_gc_get_aligned_size_for_allocator (int size)
1224 mono_gc_get_gc_name (void)
1230 mono_gc_invoke_with_gc_lock (MonoGCLockedCallbackFunc func, void *data)
1232 return GC_call_with_alloc_lock (func, data);
1236 mono_gc_get_description (void)
1238 return g_strdup (DEFAULT_GC_NAME);
1242 mono_gc_set_desktop_mode (void)
1248 mono_gc_is_moving (void)
1254 mono_gc_is_disabled (void)
1256 if (GC_dont_gc || g_getenv ("GC_DONT_GC"))
1263 mono_gc_wbarrier_value_copy_bitmap (gpointer _dest, gpointer _src, int size, unsigned bitmap)
1265 g_assert_not_reached ();
1270 mono_gc_get_card_table (int *shift_bits, gpointer *card_mask)
1272 g_assert_not_reached ();
1277 mono_gc_card_table_nursery_check (void)
1279 g_assert_not_reached ();
1284 mono_gc_get_nursery (int *shift_bits, size_t *size)
1290 mono_gc_set_current_thread_appdomain (MonoDomain *domain)
1295 mono_gc_precise_stack_mark_enabled (void)
1301 mono_gc_get_logfile (void)
1307 mono_gc_conservatively_scan_area (void *start, void *end)
1309 g_assert_not_reached ();
1313 mono_gc_scan_object (void *obj, void *gc_data)
1315 g_assert_not_reached ();
1320 mono_gc_get_bitmap_for_descr (void *descr, int *numbits)
1322 g_assert_not_reached ();
1327 mono_gc_set_gc_callbacks (MonoGCCallbacks *callbacks)
1332 mono_gc_set_stack_end (void *stack_end)
1336 void mono_gc_set_skip_thread (gboolean value)
1341 mono_gc_register_for_finalization (MonoObject *obj, void *user_data)
1346 /* This assertion is not valid when GC_DEBUG is defined */
1347 g_assert (GC_base (obj) == (char*)obj - offset);
1350 GC_REGISTER_FINALIZER_NO_ORDER ((char*)obj - offset, user_data, GUINT_TO_POINTER (offset), NULL, NULL);
1355 mono_gc_pthread_create (pthread_t *new_thread, const pthread_attr_t *attr, void *(*start_routine)(void *), void *arg)
1357 /* it is being replaced by GC_pthread_create on some
1358 * platforms, see libgc/include/gc_pthread_redirects.h */
1359 return pthread_create (new_thread, attr, start_routine, arg);
1364 BOOL APIENTRY mono_gc_dllmain (HMODULE module_handle, DWORD reason, LPVOID reserved)
1366 return GC_DllMain (module_handle, reason, reserved);
1371 mono_gc_get_vtable_bits (MonoClass *klass)
1373 if (fin_callbacks.is_class_finalization_aware) {
1374 if (fin_callbacks.is_class_finalization_aware (klass))
1375 return BOEHM_GC_BIT_FINALIZER_AWARE;
1381 * mono_gc_register_altstack:
1383 * Register the dimensions of the normal stack and altstack with the collector.
1384 * Currently, STACK/STACK_SIZE is only used when the thread is suspended while it is on an altstack.
1387 mono_gc_register_altstack (gpointer stack, gint32 stack_size, gpointer altstack, gint32 altstack_size)
1389 GC_register_altstack (stack, stack_size, altstack, altstack_size);
1393 mono_gc_get_los_limit (void)
1399 mono_gc_set_string_length (MonoString *str, gint32 new_length)
1401 mono_unichar2 *new_end = str->chars + new_length;
1403 /* zero the discarded string. This null-delimits the string and allows
1404 * the space to be reclaimed by SGen. */
1406 memset (new_end, 0, (str->length - new_length + 1) * sizeof (mono_unichar2));
1407 str->length = new_length;
1411 mono_gc_user_markers_supported (void)
1417 mono_gc_make_root_descr_user (MonoGCRootMarkFunc marker)
1419 g_assert_not_reached ();
1423 /* Toggleref support */
1426 mono_gc_toggleref_add (MonoObject *object, mono_bool strong_ref)
1428 GC_toggleref_add ((GC_PTR)object, (int)strong_ref);
1432 mono_gc_toggleref_register_callback (MonoToggleRefStatus (*proccess_toggleref) (MonoObject *obj))
1434 GC_toggleref_register_callback ((int (*) (GC_PTR obj)) proccess_toggleref);
1437 /* Test support code */
1439 static MonoToggleRefStatus
1440 test_toggleref_callback (MonoObject *obj)
1442 static MonoClassField *mono_toggleref_test_field;
1443 int status = MONO_TOGGLE_REF_DROP;
1445 if (!mono_toggleref_test_field) {
1446 mono_toggleref_test_field = mono_class_get_field_from_name (mono_object_get_class (obj), "__test");
1447 g_assert (mono_toggleref_test_field);
1450 mono_field_get_value (obj, mono_toggleref_test_field, &status);
1451 printf ("toggleref-cb obj %d\n", status);
1456 register_test_toggleref_callback (void)
1458 mono_gc_toggleref_register_callback (test_toggleref_callback);
1462 is_finalization_aware (MonoObject *obj)
1464 MonoVTable *vt = obj->vtable;
1465 return (vt->gc_bits & BOEHM_GC_BIT_FINALIZER_AWARE) == BOEHM_GC_BIT_FINALIZER_AWARE;
1469 fin_notifier (MonoObject *obj)
1471 if (is_finalization_aware (obj))
1472 fin_callbacks.object_queued_for_finalization (obj);
1476 mono_gc_register_finalizer_callbacks (MonoGCFinalizerCallbacks *callbacks)
1478 if (callbacks->version != MONO_GC_FINALIZER_EXTENSION_VERSION)
1479 g_error ("Invalid finalizer callback version. Expected %d but got %d\n", MONO_GC_FINALIZER_EXTENSION_VERSION, callbacks->version);
1481 fin_callbacks = *callbacks;
1483 GC_set_finalizer_notify_proc ((void (*) (GC_PTR))fin_notifier);
1486 #define BITMAP_SIZE (sizeof (*((HandleData *)NULL)->bitmap) * CHAR_BIT)
1488 static inline gboolean
1489 slot_occupied (HandleData *handles, guint slot) {
1490 return handles->bitmap [slot / BITMAP_SIZE] & (1 << (slot % BITMAP_SIZE));
1494 vacate_slot (HandleData *handles, guint slot) {
1495 handles->bitmap [slot / BITMAP_SIZE] &= ~(1 << (slot % BITMAP_SIZE));
1499 occupy_slot (HandleData *handles, guint slot) {
1500 handles->bitmap [slot / BITMAP_SIZE] |= 1 << (slot % BITMAP_SIZE);
1504 find_first_unset (guint32 bitmap)
1507 for (i = 0; i < 32; ++i) {
1508 if (!(bitmap & (1 << i)))
1515 handle_data_alloc_entries (HandleData *handles)
1518 if (MONO_GC_HANDLE_TYPE_IS_WEAK (handles->type)) {
1519 handles->entries = g_malloc0 (sizeof (*handles->entries) * handles->size);
1520 handles->domain_ids = g_malloc0 (sizeof (*handles->domain_ids) * handles->size);
1522 handles->entries = mono_gc_alloc_fixed (sizeof (*handles->entries) * handles->size, NULL, MONO_ROOT_SOURCE_GC_HANDLE, "gc handles table");
1524 handles->bitmap = g_malloc0 (handles->size / CHAR_BIT);
1528 handle_data_next_unset (HandleData *handles)
1531 for (slot = handles->slot_hint; slot < handles->size / BITMAP_SIZE; ++slot) {
1532 if (handles->bitmap [slot] == 0xffffffff)
1534 handles->slot_hint = slot;
1535 return find_first_unset (handles->bitmap [slot]);
1541 handle_data_first_unset (HandleData *handles)
1544 for (slot = 0; slot < handles->slot_hint; ++slot) {
1545 if (handles->bitmap [slot] == 0xffffffff)
1547 handles->slot_hint = slot;
1548 return find_first_unset (handles->bitmap [slot]);
1553 /* Returns the index of the current slot in the bitmap. */
1555 handle_data_grow (HandleData *handles, gboolean track)
1557 guint32 *new_bitmap;
1558 guint32 new_size = handles->size * 2; /* always double: we memset to 0 based on this below */
1560 /* resize and copy the bitmap */
1561 new_bitmap = g_malloc0 (new_size / CHAR_BIT);
1562 memcpy (new_bitmap, handles->bitmap, handles->size / CHAR_BIT);
1563 g_free (handles->bitmap);
1564 handles->bitmap = new_bitmap;
1566 /* resize and copy the entries */
1567 if (MONO_GC_HANDLE_TYPE_IS_WEAK (handles->type)) {
1569 guint16 *domain_ids;
1571 domain_ids = g_malloc0 (sizeof (*handles->domain_ids) * new_size);
1572 entries = g_malloc0 (sizeof (*handles->entries) * new_size);
1573 memcpy (domain_ids, handles->domain_ids, sizeof (*handles->domain_ids) * handles->size);
1574 for (i = 0; i < handles->size; ++i) {
1575 MonoObject *obj = mono_gc_weak_link_get (&(handles->entries [i]));
1577 mono_gc_weak_link_add (&(entries [i]), obj, track);
1578 mono_gc_weak_link_remove (&(handles->entries [i]), track);
1580 g_assert (!handles->entries [i]);
1583 g_free (handles->entries);
1584 g_free (handles->domain_ids);
1585 handles->entries = entries;
1586 handles->domain_ids = domain_ids;
1589 entries = mono_gc_alloc_fixed (sizeof (*handles->entries) * new_size, NULL, MONO_ROOT_SOURCE_GC_HANDLE, "gc handles table");
1590 mono_gc_memmove_aligned (entries, handles->entries, sizeof (*handles->entries) * handles->size);
1591 mono_gc_free_fixed (handles->entries);
1592 handles->entries = entries;
1594 handles->slot_hint = handles->size / BITMAP_SIZE;
1595 handles->size = new_size;
1599 alloc_handle (HandleData *handles, MonoObject *obj, gboolean track)
1603 lock_handles (handles);
1605 handle_data_alloc_entries (handles);
1606 i = handle_data_next_unset (handles);
1607 if (i == -1 && handles->slot_hint != 0)
1608 i = handle_data_first_unset (handles);
1610 handle_data_grow (handles, track);
1613 slot = handles->slot_hint * BITMAP_SIZE + i;
1614 occupy_slot (handles, slot);
1615 handles->entries [slot] = NULL;
1616 if (MONO_GC_HANDLE_TYPE_IS_WEAK (handles->type)) {
1617 /*FIXME, what to use when obj == null?*/
1618 handles->domain_ids [slot] = (obj ? mono_object_get_domain (obj) : mono_domain_get ())->domain_id;
1620 mono_gc_weak_link_add (&(handles->entries [slot]), obj, track);
1622 handles->entries [slot] = obj;
1625 #ifndef DISABLE_PERFCOUNTERS
1626 mono_perfcounters->gc_num_handles++;
1628 unlock_handles (handles);
1629 res = MONO_GC_HANDLE (slot, handles->type);
1630 mono_profiler_gc_handle (MONO_PROFILER_GC_HANDLE_CREATED, handles->type, res, obj);
1635 * mono_gchandle_new:
1636 * @obj: managed object to get a handle for
1637 * @pinned: whether the object should be pinned
1639 * This returns a handle that wraps the object, this is used to keep a
1640 * reference to a managed object from the unmanaged world and preventing the
1641 * object from being disposed.
1643 * If @pinned is false the address of the object can not be obtained, if it is
1644 * true the address of the object can be obtained. This will also pin the
1645 * object so it will not be possible by a moving garbage collector to move the
1648 * Returns: a handle that can be used to access the object from
1652 mono_gchandle_new (MonoObject *obj, gboolean pinned)
1654 return alloc_handle (&gc_handles [pinned? HANDLE_PINNED: HANDLE_NORMAL], obj, FALSE);
1658 * mono_gchandle_new_weakref:
1659 * @obj: managed object to get a handle for
1660 * @pinned: whether the object should be pinned
1662 * This returns a weak handle that wraps the object, this is used to
1663 * keep a reference to a managed object from the unmanaged world.
1664 * Unlike the mono_gchandle_new the object can be reclaimed by the
1665 * garbage collector. In this case the value of the GCHandle will be
1668 * If @pinned is false the address of the object can not be obtained, if it is
1669 * true the address of the object can be obtained. This will also pin the
1670 * object so it will not be possible by a moving garbage collector to move the
1673 * Returns: a handle that can be used to access the object from
1677 mono_gchandle_new_weakref (MonoObject *obj, gboolean track_resurrection)
1679 return alloc_handle (&gc_handles [track_resurrection? HANDLE_WEAK_TRACK: HANDLE_WEAK], obj, track_resurrection);
1683 * mono_gchandle_get_target:
1684 * @gchandle: a GCHandle's handle.
1686 * The handle was previously created by calling mono_gchandle_new or
1687 * mono_gchandle_new_weakref.
1689 * Returns a pointer to the MonoObject represented by the handle or
1690 * NULL for a collected object if using a weakref handle.
1693 mono_gchandle_get_target (guint32 gchandle)
1695 guint slot = MONO_GC_HANDLE_SLOT (gchandle);
1696 guint type = MONO_GC_HANDLE_TYPE (gchandle);
1697 HandleData *handles = &gc_handles [type];
1698 MonoObject *obj = NULL;
1699 if (type >= HANDLE_TYPE_MAX)
1702 lock_handles (handles);
1703 if (slot < handles->size && slot_occupied (handles, slot)) {
1704 if (MONO_GC_HANDLE_TYPE_IS_WEAK (handles->type)) {
1705 obj = mono_gc_weak_link_get (&handles->entries [slot]);
1707 obj = handles->entries [slot];
1710 /* print a warning? */
1712 unlock_handles (handles);
1713 /*g_print ("get target of entry %d of type %d: %p\n", slot, handles->type, obj);*/
1718 mono_gchandle_set_target (guint32 gchandle, MonoObject *obj)
1720 guint slot = MONO_GC_HANDLE_SLOT (gchandle);
1721 guint type = MONO_GC_HANDLE_TYPE (gchandle);
1722 HandleData *handles = &gc_handles [type];
1723 MonoObject *old_obj = NULL;
1725 g_assert (type < HANDLE_TYPE_MAX);
1726 lock_handles (handles);
1727 if (slot < handles->size && slot_occupied (handles, slot)) {
1728 if (MONO_GC_HANDLE_TYPE_IS_WEAK (handles->type)) {
1729 old_obj = handles->entries [slot];
1730 if (handles->entries [slot])
1731 mono_gc_weak_link_remove (&handles->entries [slot], handles->type == HANDLE_WEAK_TRACK);
1733 mono_gc_weak_link_add (&handles->entries [slot], obj, handles->type == HANDLE_WEAK_TRACK);
1734 /*FIXME, what to use when obj == null?*/
1735 handles->domain_ids [slot] = (obj ? mono_object_get_domain (obj) : mono_domain_get ())->domain_id;
1737 handles->entries [slot] = obj;
1740 /* print a warning? */
1742 /*g_print ("changed entry %d of type %d to object %p (in slot: %p)\n", slot, handles->type, obj, handles->entries [slot]);*/
1743 unlock_handles (handles);
1747 * mono_gchandle_is_in_domain:
1748 * @gchandle: a GCHandle's handle.
1749 * @domain: An application domain.
1751 * Returns: true if the object wrapped by the @gchandle belongs to the specific @domain.
1754 mono_gc_is_null (void)
1760 mono_gchandle_is_in_domain (guint32 gchandle, MonoDomain *domain)
1762 guint slot = MONO_GC_HANDLE_SLOT (gchandle);
1763 guint type = MONO_GC_HANDLE_TYPE (gchandle);
1764 HandleData *handles = &gc_handles [type];
1765 gboolean result = FALSE;
1767 if (type >= HANDLE_TYPE_MAX)
1770 lock_handles (handles);
1771 if (slot < handles->size && slot_occupied (handles, slot)) {
1772 if (MONO_GC_HANDLE_TYPE_IS_WEAK (handles->type)) {
1773 result = domain->domain_id == handles->domain_ids [slot];
1776 obj = handles->entries [slot];
1780 result = domain == mono_object_domain (obj);
1783 /* print a warning? */
1785 unlock_handles (handles);
1790 * mono_gchandle_free:
1791 * @gchandle: a GCHandle's handle.
1793 * Frees the @gchandle handle. If there are no outstanding
1794 * references, the garbage collector can reclaim the memory of the
1798 mono_gchandle_free (guint32 gchandle)
1800 guint slot = MONO_GC_HANDLE_SLOT (gchandle);
1801 guint type = MONO_GC_HANDLE_TYPE (gchandle);
1802 HandleData *handles = &gc_handles [type];
1803 if (type >= HANDLE_TYPE_MAX)
1806 lock_handles (handles);
1807 if (slot < handles->size && slot_occupied (handles, slot)) {
1808 if (MONO_GC_HANDLE_TYPE_IS_WEAK (handles->type)) {
1809 if (handles->entries [slot])
1810 mono_gc_weak_link_remove (&handles->entries [slot], handles->type == HANDLE_WEAK_TRACK);
1812 handles->entries [slot] = NULL;
1814 vacate_slot (handles, slot);
1816 /* print a warning? */
1818 #ifndef DISABLE_PERFCOUNTERS
1819 mono_perfcounters->gc_num_handles--;
1821 /*g_print ("freed entry %d of type %d\n", slot, handles->type);*/
1822 unlock_handles (handles);
1823 mono_profiler_gc_handle (MONO_PROFILER_GC_HANDLE_DESTROYED, handles->type, gchandle, NULL);
1827 * mono_gchandle_free_domain:
1828 * @domain: domain that is unloading
1830 * Function used internally to cleanup any GC handle for objects belonging
1831 * to the specified domain during appdomain unload.
1834 mono_gchandle_free_domain (MonoDomain *domain)
1838 for (type = HANDLE_TYPE_MIN; type < HANDLE_PINNED; ++type) {
1840 HandleData *handles = &gc_handles [type];
1841 lock_handles (handles);
1842 for (slot = 0; slot < handles->size; ++slot) {
1843 if (!slot_occupied (handles, slot))
1845 if (MONO_GC_HANDLE_TYPE_IS_WEAK (type)) {
1846 if (domain->domain_id == handles->domain_ids [slot]) {
1847 vacate_slot (handles, slot);
1848 if (handles->entries [slot])
1849 mono_gc_weak_link_remove (&handles->entries [slot], handles->type == HANDLE_WEAK_TRACK);
1852 if (handles->entries [slot] && mono_object_domain (handles->entries [slot]) == domain) {
1853 vacate_slot (handles, slot);
1854 handles->entries [slot] = NULL;
1858 unlock_handles (handles);
1863 #endif /* no Boehm GC */