3 * GC implementation using either the installed or included Boehm GC.
5 * Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
6 * Copyright 2004-2011 Novell, Inc (http://www.novell.com)
7 * Copyright 2011-2012 Xamarin, Inc (http://www.xamarin.com)
8 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
15 #define GC_I_HIDE_POINTERS
16 #include <mono/metadata/gc-internals.h>
17 #include <mono/metadata/mono-gc.h>
18 #include <mono/metadata/profiler-private.h>
19 #include <mono/metadata/class-internals.h>
20 #include <mono/metadata/method-builder.h>
21 #include <mono/metadata/opcodes.h>
22 #include <mono/metadata/domain-internals.h>
23 #include <mono/metadata/metadata-internals.h>
24 #include <mono/metadata/marshal.h>
25 #include <mono/metadata/runtime.h>
26 #include <mono/metadata/handle.h>
27 #include <mono/metadata/sgen-toggleref.h>
28 #include <mono/metadata/w32handle.h>
29 #include <mono/utils/atomic.h>
30 #include <mono/utils/mono-logger-internals.h>
31 #include <mono/utils/mono-memory-model.h>
32 #include <mono/utils/mono-time.h>
33 #include <mono/utils/mono-threads.h>
34 #include <mono/utils/dtrace.h>
35 #include <mono/utils/gc_wrapper.h>
36 #include <mono/utils/mono-os-mutex.h>
37 #include <mono/utils/mono-counters.h>
38 #include <mono/utils/mono-compiler.h>
44 #define THREAD_LOCAL_ALLOC 1
45 #include "private/pthread_support.h"
47 #if defined(PLATFORM_MACOSX) && defined(HAVE_PTHREAD_GET_STACKADDR_NP)
48 void *pthread_get_stackaddr_np(pthread_t);
51 #define GC_NO_DESCRIPTOR ((gpointer)(0 | GC_DS_LENGTH))
52 /*Boehm max heap cannot be smaller than 16MB*/
53 #define MIN_BOEHM_MAX_HEAP_SIZE_IN_MB 16
54 #define MIN_BOEHM_MAX_HEAP_SIZE (MIN_BOEHM_MAX_HEAP_SIZE_IN_MB << 20)
56 static gboolean gc_initialized = FALSE;
57 static mono_mutex_t mono_gc_lock;
60 boehm_thread_register (MonoThreadInfo* info, void *baseptr);
62 boehm_thread_unregister (MonoThreadInfo *p);
64 boehm_thread_detach (MonoThreadInfo *p);
66 register_test_toggleref_callback (void);
68 #define BOEHM_GC_BIT_FINALIZER_AWARE 1
69 static MonoGCFinalizerCallbacks fin_callbacks;
73 static mono_mutex_t handle_section;
74 #define lock_handles(handles) mono_os_mutex_lock (&handle_section)
75 #define unlock_handles(handles) mono_os_mutex_unlock (&handle_section)
82 guint slot_hint : 24; /* starting slot for search in bitmap */
83 /* 2^16 appdomains should be enough for everyone (though I know I'll regret this in 20 years) */
84 /* we alloc this only for weak refs, since we can get the domain directly in the other cases */
88 #define EMPTY_HANDLE_DATA(type) {NULL, NULL, 0, (type), 0, NULL}
90 /* weak and weak-track arrays will be allocated in malloc memory
92 static HandleData gc_handles [] = {
93 EMPTY_HANDLE_DATA (HANDLE_WEAK),
94 EMPTY_HANDLE_DATA (HANDLE_WEAK_TRACK),
95 EMPTY_HANDLE_DATA (HANDLE_NORMAL),
96 EMPTY_HANDLE_DATA (HANDLE_PINNED)
100 mono_gc_warning (char *msg, GC_word arg)
102 mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_GC, msg, (unsigned long)arg);
105 static void on_gc_notification (GC_EventType event);
106 static void on_gc_heap_resize (size_t new_size);
109 mono_gc_base_init (void)
111 MonoThreadInfoCallbacks cb;
118 mono_counters_init ();
121 mono_w32handle_init ();
125 * Handle the case when we are called from a thread different from the main thread,
127 * FIXME: Move this to libgc where it belongs.
129 * we used to do this only when running on valgrind,
130 * but it happens also in other setups.
132 #if defined(HAVE_PTHREAD_GETATTR_NP) && defined(HAVE_PTHREAD_ATTR_GETSTACK) && !defined(__native_client__)
137 pthread_getattr_np (pthread_self (), &attr);
138 pthread_attr_getstack (&attr, &sstart, &size);
139 pthread_attr_destroy (&attr);
140 /*g_print ("stackbottom pth is: %p\n", (char*)sstart + size);*/
141 /* apparently with some linuxthreads implementations sstart can be NULL,
142 * fallback to the more imprecise method (bug# 78096).
145 GC_stackbottom = (char*)sstart + size;
148 gsize stack_bottom = (gsize)&dummy;
149 stack_bottom += 4095;
150 stack_bottom &= ~4095;
151 GC_stackbottom = (char*)stack_bottom;
154 #elif defined(HAVE_PTHREAD_GET_STACKSIZE_NP) && defined(HAVE_PTHREAD_GET_STACKADDR_NP)
155 GC_stackbottom = (char*)pthread_get_stackaddr_np (pthread_self ());
156 #elif defined(__OpenBSD__)
157 # include <pthread_np.h>
162 rslt = pthread_stackseg_np(pthread_self(), &ss);
163 g_assert (rslt == 0);
165 GC_stackbottom = (char*)ss.ss_sp;
167 #elif defined(__native_client__)
168 /* Do nothing, GC_stackbottom is set correctly in libgc */
172 gsize stack_bottom = (gsize)&dummy;
173 stack_bottom += 4095;
174 stack_bottom &= ~4095;
175 /*g_print ("stackbottom is: %p\n", (char*)stack_bottom);*/
176 GC_stackbottom = (char*)stack_bottom;
180 #if !defined(PLATFORM_ANDROID)
181 /* If GC_no_dls is set to true, GC_find_limit is not called. This causes a seg fault on Android. */
185 if ((env = g_getenv ("MONO_GC_DEBUG"))) {
186 char **opts = g_strsplit (env, ",", -1);
187 for (char **ptr = opts; ptr && *ptr; ptr ++) {
189 if (!strcmp (opt, "do-not-finalize")) {
190 mono_do_not_finalize = 1;
191 } else if (!strcmp (opt, "log-finalizers")) {
201 GC_set_warn_proc (mono_gc_warning);
202 GC_finalize_on_demand = 1;
203 GC_finalizer_notifier = mono_gc_finalize_notify;
205 GC_init_gcj_malloc (5, NULL);
206 GC_allow_register_threads ();
208 if ((env = g_getenv ("MONO_GC_PARAMS"))) {
209 char **ptr, **opts = g_strsplit (env, ",", -1);
210 for (ptr = opts; *ptr; ++ptr) {
212 if (g_str_has_prefix (opt, "max-heap-size=")) {
215 opt = strchr (opt, '=') + 1;
216 if (*opt && mono_gc_parse_environment_string_extract_number (opt, &max_heap)) {
217 if (max_heap < MIN_BOEHM_MAX_HEAP_SIZE) {
218 fprintf (stderr, "max-heap-size must be at least %dMb.\n", MIN_BOEHM_MAX_HEAP_SIZE_IN_MB);
221 GC_set_max_heap_size (max_heap);
223 fprintf (stderr, "max-heap-size must be an integer.\n");
227 } else if (g_str_has_prefix (opt, "toggleref-test")) {
228 register_test_toggleref_callback ();
231 /* Could be a parameter for sgen */
233 fprintf (stderr, "MONO_GC_PARAMS must be a comma-delimited list of one or more of the following:\n");
234 fprintf (stderr, " max-heap-size=N (where N is an integer, possibly with a k, m or a g suffix)\n");
243 memset (&cb, 0, sizeof (cb));
244 cb.thread_register = boehm_thread_register;
245 cb.thread_unregister = boehm_thread_unregister;
246 cb.thread_detach = boehm_thread_detach;
247 cb.mono_method_is_critical = (gboolean (*)(void *))mono_runtime_is_critical_method;
249 mono_threads_init (&cb, sizeof (MonoThreadInfo));
250 mono_os_mutex_init (&mono_gc_lock);
251 mono_os_mutex_init_recursive (&handle_section);
253 mono_thread_info_attach (&dummy);
255 GC_set_on_collection_event (on_gc_notification);
256 GC_on_heap_resize = on_gc_heap_resize;
258 gc_initialized = TRUE;
262 mono_gc_base_cleanup (void)
264 GC_finalizer_notifier = NULL;
269 * \param generation GC generation identifier
271 * Perform a garbage collection for the given generation, higher numbers
272 * mean usually older objects. Collecting a high-numbered generation
273 * implies collecting also the lower-numbered generations.
274 * The maximum value for \p generation can be retrieved with a call to
275 * \c mono_gc_max_generation, so this function is usually called as:
277 * <code>mono_gc_collect (mono_gc_max_generation ());</code>
280 mono_gc_collect (int generation)
282 #ifndef DISABLE_PERFCOUNTERS
283 mono_perfcounters->gc_induced++;
289 * mono_gc_max_generation:
291 * Get the maximum generation number used by the current garbage
292 * collector. The value will be 0 for the Boehm collector, 1 or more
293 * for the generational collectors.
295 * Returns: the maximum generation number.
298 mono_gc_max_generation (void)
304 * mono_gc_get_generation:
305 * \param object a managed object
307 * Get the garbage collector's generation that \p object belongs to.
308 * Use this has a hint only.
310 * \returns a garbage collector generation number
313 mono_gc_get_generation (MonoObject *object)
319 * mono_gc_collection_count:
320 * \param generation a GC generation number
322 * Get how many times a garbage collection has been performed
323 * for the given \p generation number.
325 * \returns the number of garbage collections
328 mono_gc_collection_count (int generation)
334 * mono_gc_add_memory_pressure:
335 * \param value amount of bytes
337 * Adjust the garbage collector's view of how many bytes of memory
338 * are indirectly referenced by managed objects (for example unmanaged
339 * memory holding image or other binary data).
340 * This is a hint only to the garbage collector algorithm.
341 * Note that negative amounts of p value will decrease the memory
345 mono_gc_add_memory_pressure (gint64 value)
350 * mono_gc_get_used_size:
352 * Get the approximate amount of memory used by managed objects.
354 * Returns: the amount of memory used in bytes
357 mono_gc_get_used_size (void)
359 return GC_get_heap_size () - GC_get_free_bytes ();
363 * mono_gc_get_heap_size:
365 * Get the amount of memory used by the garbage collector.
367 * Returns: the size of the heap in bytes
370 mono_gc_get_heap_size (void)
372 return GC_get_heap_size ();
376 mono_gc_is_gc_thread (void)
378 return GC_thread_is_registered ();
382 mono_gc_register_thread (void *baseptr)
384 return mono_thread_info_attach (baseptr) != NULL;
388 boehm_thread_register (MonoThreadInfo* info, void *baseptr)
390 struct GC_stack_base sb;
393 /* TODO: use GC_get_stack_base instead of baseptr. */
394 sb.mem_base = baseptr;
395 res = GC_register_my_thread (&sb);
396 if (res == GC_UNIMPLEMENTED)
397 return NULL; /* Cannot happen with GC v7+. */
399 info->handle_stack = mono_handle_stack_alloc ();
405 boehm_thread_unregister (MonoThreadInfo *p)
407 MonoNativeThreadId tid;
409 tid = mono_thread_info_get_tid (p);
411 if (p->runtime_thread)
412 mono_threads_add_joinable_thread ((gpointer)tid);
416 boehm_thread_detach (MonoThreadInfo *p)
418 if (mono_thread_internal_current_is_attached ())
419 mono_thread_detach_internal (mono_thread_internal_current ());
423 mono_object_is_alive (MonoObject* o)
425 return GC_is_marked ((ptr_t)o);
429 mono_gc_walk_heap (int flags, MonoGCReferences callback, void *data)
434 static gint64 gc_start_time;
437 on_gc_notification (GC_EventType event)
439 MonoGCEvent e = (MonoGCEvent)event;
442 case MONO_GC_EVENT_PRE_STOP_WORLD:
443 MONO_GC_WORLD_STOP_BEGIN ();
446 case MONO_GC_EVENT_POST_STOP_WORLD:
447 MONO_GC_WORLD_STOP_END ();
450 case MONO_GC_EVENT_PRE_START_WORLD:
451 MONO_GC_WORLD_RESTART_BEGIN (1);
454 case MONO_GC_EVENT_POST_START_WORLD:
455 MONO_GC_WORLD_RESTART_END (1);
458 case MONO_GC_EVENT_START:
460 #ifndef DISABLE_PERFCOUNTERS
461 if (mono_perfcounters)
462 mono_perfcounters->gc_collections0++;
464 gc_stats.major_gc_count ++;
465 gc_start_time = mono_100ns_ticks ();
468 case MONO_GC_EVENT_END:
470 #if defined(ENABLE_DTRACE) && defined(__sun__)
471 /* This works around a dtrace -G problem on Solaris.
472 Limit its actual use to when the probe is enabled. */
473 if (MONO_GC_END_ENABLED ())
477 #ifndef DISABLE_PERFCOUNTERS
478 if (mono_perfcounters) {
479 guint64 heap_size = GC_get_heap_size ();
480 guint64 used_size = heap_size - GC_get_free_bytes ();
481 mono_perfcounters->gc_total_bytes = used_size;
482 mono_perfcounters->gc_committed_bytes = heap_size;
483 mono_perfcounters->gc_reserved_bytes = heap_size;
484 mono_perfcounters->gc_gen0size = heap_size;
487 gc_stats.major_gc_time += mono_100ns_ticks () - gc_start_time;
488 mono_trace_message (MONO_TRACE_GC, "gc took %d usecs", (mono_100ns_ticks () - gc_start_time) / 10);
494 mono_profiler_gc_event (e, 0);
497 case MONO_GC_EVENT_PRE_STOP_WORLD:
498 mono_thread_info_suspend_lock ();
499 mono_profiler_gc_event (MONO_GC_EVENT_PRE_STOP_WORLD_LOCKED, 0);
501 case MONO_GC_EVENT_POST_START_WORLD:
502 mono_thread_info_suspend_unlock ();
503 mono_profiler_gc_event (MONO_GC_EVENT_POST_START_WORLD_UNLOCKED, 0);
512 on_gc_heap_resize (size_t new_size)
514 guint64 heap_size = GC_get_heap_size ();
515 #ifndef DISABLE_PERFCOUNTERS
516 if (mono_perfcounters) {
517 mono_perfcounters->gc_committed_bytes = heap_size;
518 mono_perfcounters->gc_reserved_bytes = heap_size;
519 mono_perfcounters->gc_gen0size = heap_size;
522 mono_profiler_gc_heap_resize (new_size);
526 mono_gc_register_root (char *start, size_t size, void *descr, MonoGCRootSource source, const char *msg)
528 /* for some strange reason, they want one extra byte on the end */
529 GC_add_roots (start, start + size + 1);
535 mono_gc_register_root_wbarrier (char *start, size_t size, MonoGCDescriptor descr, MonoGCRootSource source, const char *msg)
537 return mono_gc_register_root (start, size, descr, source, msg);
541 mono_gc_deregister_root (char* addr)
544 /* FIXME: libgc doesn't define this work win32 for some reason */
545 /* FIXME: No size info */
546 GC_remove_roots (addr, addr + sizeof (gpointer) + 1);
551 mono_gc_weak_link_add (void **link_addr, MonoObject *obj, gboolean track)
553 /* libgc requires that we use HIDE_POINTER... */
554 *link_addr = (void*)HIDE_POINTER (obj);
556 GC_REGISTER_LONG_LINK (link_addr, obj);
558 GC_GENERAL_REGISTER_DISAPPEARING_LINK (link_addr, obj);
562 mono_gc_weak_link_remove (void **link_addr, gboolean track)
565 GC_unregister_long_link (link_addr);
567 GC_unregister_disappearing_link (link_addr);
572 reveal_link (gpointer link_addr)
574 void **link_a = (void **)link_addr;
575 return REVEAL_POINTER (*link_a);
579 mono_gc_weak_link_get (void **link_addr)
581 MonoObject *obj = (MonoObject *)GC_call_with_alloc_lock (reveal_link, link_addr);
582 if (obj == (MonoObject *) -1)
588 mono_gc_make_descr_for_string (gsize *bitmap, int numbits)
590 return mono_gc_make_descr_from_bitmap (bitmap, numbits);
594 mono_gc_make_descr_for_object (gsize *bitmap, int numbits, size_t obj_size)
596 return mono_gc_make_descr_from_bitmap (bitmap, numbits);
600 mono_gc_make_descr_for_array (int vector, gsize *elem_bitmap, int numbits, size_t elem_size)
602 /* libgc has no usable support for arrays... */
603 return GC_NO_DESCRIPTOR;
607 mono_gc_make_descr_from_bitmap (gsize *bitmap, int numbits)
609 /* It seems there are issues when the bitmap doesn't fit: play it safe */
611 return GC_NO_DESCRIPTOR;
613 return (gpointer)GC_make_descriptor ((GC_bitmap)bitmap, numbits);
617 mono_gc_make_vector_descr (void)
623 mono_gc_make_root_descr_all_refs (int numbits)
629 mono_gc_alloc_fixed (size_t size, void *descr, MonoGCRootSource source, const char *msg)
631 return GC_MALLOC_UNCOLLECTABLE (size);
635 mono_gc_free_fixed (void* addr)
641 mono_gc_alloc_obj (MonoVTable *vtable, size_t size)
645 if (!vtable->klass->has_references) {
646 obj = (MonoObject *)GC_MALLOC_ATOMIC (size);
647 if (G_UNLIKELY (!obj))
650 obj->vtable = vtable;
651 obj->synchronisation = NULL;
653 memset ((char *) obj + sizeof (MonoObject), 0, size - sizeof (MonoObject));
654 } else if (vtable->gc_descr != GC_NO_DESCRIPTOR) {
655 obj = (MonoObject *)GC_GCJ_MALLOC (size, vtable);
656 if (G_UNLIKELY (!obj))
659 obj = (MonoObject *)GC_MALLOC (size);
660 if (G_UNLIKELY (!obj))
663 obj->vtable = vtable;
666 if (G_UNLIKELY (mono_profiler_events & MONO_PROFILE_ALLOCATIONS))
667 mono_profiler_allocation (obj);
673 mono_gc_alloc_vector (MonoVTable *vtable, size_t size, uintptr_t max_length)
677 if (!vtable->klass->has_references) {
678 obj = (MonoArray *)GC_MALLOC_ATOMIC (size);
679 if (G_UNLIKELY (!obj))
682 obj->obj.vtable = vtable;
683 obj->obj.synchronisation = NULL;
685 memset ((char *) obj + sizeof (MonoObject), 0, size - sizeof (MonoObject));
686 } else if (vtable->gc_descr != GC_NO_DESCRIPTOR) {
687 obj = (MonoArray *)GC_GCJ_MALLOC (size, vtable);
688 if (G_UNLIKELY (!obj))
691 obj = (MonoArray *)GC_MALLOC (size);
692 if (G_UNLIKELY (!obj))
695 obj->obj.vtable = vtable;
698 obj->max_length = max_length;
700 if (G_UNLIKELY (mono_profiler_events & MONO_PROFILE_ALLOCATIONS))
701 mono_profiler_allocation (&obj->obj);
707 mono_gc_alloc_array (MonoVTable *vtable, size_t size, uintptr_t max_length, uintptr_t bounds_size)
711 if (!vtable->klass->has_references) {
712 obj = (MonoArray *)GC_MALLOC_ATOMIC (size);
713 if (G_UNLIKELY (!obj))
716 obj->obj.vtable = vtable;
717 obj->obj.synchronisation = NULL;
719 memset ((char *) obj + sizeof (MonoObject), 0, size - sizeof (MonoObject));
720 } else if (vtable->gc_descr != GC_NO_DESCRIPTOR) {
721 obj = (MonoArray *)GC_GCJ_MALLOC (size, vtable);
722 if (G_UNLIKELY (!obj))
725 obj = (MonoArray *)GC_MALLOC (size);
726 if (G_UNLIKELY (!obj))
729 obj->obj.vtable = vtable;
732 obj->max_length = max_length;
735 obj->bounds = (MonoArrayBounds *) ((char *) obj + size - bounds_size);
737 if (G_UNLIKELY (mono_profiler_events & MONO_PROFILE_ALLOCATIONS))
738 mono_profiler_allocation (&obj->obj);
744 mono_gc_alloc_string (MonoVTable *vtable, size_t size, gint32 len)
746 MonoString *obj = (MonoString *)GC_MALLOC_ATOMIC (size);
747 if (G_UNLIKELY (!obj))
750 obj->object.vtable = vtable;
751 obj->object.synchronisation = NULL;
753 obj->chars [len] = 0;
755 if (G_UNLIKELY (mono_profiler_events & MONO_PROFILE_ALLOCATIONS))
756 mono_profiler_allocation (&obj->object);
762 mono_gc_alloc_mature (MonoVTable *vtable, size_t size)
764 return mono_gc_alloc_obj (vtable, size);
768 mono_gc_alloc_pinned_obj (MonoVTable *vtable, size_t size)
770 return mono_gc_alloc_obj (vtable, size);
774 mono_gc_invoke_finalizers (void)
776 /* There is a bug in GC_invoke_finalizer () in versions <= 6.2alpha4:
777 * the 'mem_freed' variable is not initialized when there are no
778 * objects to finalize, which leads to strange behavior later on.
779 * The check is necessary to work around that bug.
781 if (GC_should_invoke_finalizers ())
782 return GC_invoke_finalizers ();
787 mono_gc_pending_finalizers (void)
789 return GC_should_invoke_finalizers ();
793 mono_gc_wbarrier_set_field (MonoObject *obj, gpointer field_ptr, MonoObject* value)
795 *(void**)field_ptr = value;
799 mono_gc_wbarrier_set_arrayref (MonoArray *arr, gpointer slot_ptr, MonoObject* value)
801 *(void**)slot_ptr = value;
805 mono_gc_wbarrier_arrayref_copy (gpointer dest_ptr, gpointer src_ptr, int count)
807 mono_gc_memmove_aligned (dest_ptr, src_ptr, count * sizeof (gpointer));
811 mono_gc_wbarrier_generic_store (gpointer ptr, MonoObject* value)
813 *(void**)ptr = value;
817 mono_gc_wbarrier_generic_store_atomic (gpointer ptr, MonoObject *value)
819 InterlockedWritePointer ((volatile gpointer *)ptr, value);
823 mono_gc_wbarrier_generic_nostore (gpointer ptr)
828 mono_gc_wbarrier_value_copy (gpointer dest, gpointer src, int count, MonoClass *klass)
830 mono_gc_memmove_atomic (dest, src, count * mono_class_value_size (klass, NULL));
834 mono_gc_wbarrier_object_copy (MonoObject* obj, MonoObject *src)
836 /* do not copy the sync state */
837 mono_gc_memmove_aligned ((char*)obj + sizeof (MonoObject), (char*)src + sizeof (MonoObject),
838 mono_object_class (obj)->instance_size - sizeof (MonoObject));
842 mono_gc_clear_domain (MonoDomain *domain)
847 mono_gc_suspend_finalizers (void)
852 mono_gc_get_suspend_signal (void)
854 return GC_get_suspend_signal ();
858 mono_gc_get_restart_signal (void)
860 return GC_get_thr_restart_signal ();
863 #if defined(USE_COMPILER_TLS) && defined(__linux__) && (defined(__i386__) || defined(__x86_64__))
864 extern __thread void* GC_thread_tls;
865 #include "metadata-internals.h"
871 while (!(v & (1 << i)))
878 ATYPE_FREEPTR_FOR_BOX,
886 create_allocator (int atype, int tls_key, gboolean slowpath)
888 int index_var, bytes_var, my_fl_var, my_entry_var;
889 guint32 no_freelist_branch, not_small_enough_branch = 0;
890 guint32 size_overflow_branch = 0;
891 MonoMethodBuilder *mb;
893 MonoMethodSignature *csig;
894 const char *name = NULL;
897 g_assert_not_reached ();
899 if (atype == ATYPE_FREEPTR) {
900 name = slowpath ? "SlowAllocPtrfree" : "AllocPtrfree";
901 } else if (atype == ATYPE_FREEPTR_FOR_BOX) {
902 name = slowpath ? "SlowAllocPtrfreeBox" : "AllocPtrfreeBox";
903 } else if (atype == ATYPE_NORMAL) {
904 name = slowpath ? "SlowAlloc" : "Alloc";
905 } else if (atype == ATYPE_GCJ) {
906 name = slowpath ? "SlowAllocGcj" : "AllocGcj";
907 } else if (atype == ATYPE_STRING) {
908 name = slowpath ? "SlowAllocString" : "AllocString";
910 g_assert_not_reached ();
913 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
915 if (atype == ATYPE_STRING) {
916 csig->ret = &mono_defaults.string_class->byval_arg;
917 csig->params [0] = &mono_defaults.int_class->byval_arg;
918 csig->params [1] = &mono_defaults.int32_class->byval_arg;
920 csig->ret = &mono_defaults.object_class->byval_arg;
921 csig->params [0] = &mono_defaults.int_class->byval_arg;
922 csig->params [1] = &mono_defaults.int32_class->byval_arg;
925 mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_ALLOC);
928 goto always_slowpath;
930 bytes_var = mono_mb_add_local (mb, &mono_defaults.int32_class->byval_arg);
931 if (atype == ATYPE_STRING) {
932 /* a string alloator method takes the args: (vtable, len) */
933 /* bytes = (offsetof (MonoString, chars) + ((len + 1) * 2)); */
934 mono_mb_emit_ldarg (mb, 1);
935 mono_mb_emit_icon (mb, 1);
936 mono_mb_emit_byte (mb, MONO_CEE_ADD);
937 mono_mb_emit_icon (mb, 1);
938 mono_mb_emit_byte (mb, MONO_CEE_SHL);
939 // sizeof (MonoString) might include padding
940 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoString, chars));
941 mono_mb_emit_byte (mb, MONO_CEE_ADD);
942 mono_mb_emit_stloc (mb, bytes_var);
944 mono_mb_emit_ldarg (mb, 1);
945 mono_mb_emit_stloc (mb, bytes_var);
948 /* this is needed for strings/arrays only as the other big types are never allocated with this method */
949 if (atype == ATYPE_STRING) {
951 /* if (!SMALL_ENOUGH (bytes)) jump slow_path;*/
952 mono_mb_emit_ldloc (mb, bytes_var);
953 mono_mb_emit_icon (mb, (NFREELISTS-1) * GRANULARITY);
954 not_small_enough_branch = mono_mb_emit_short_branch (mb, MONO_CEE_BGT_UN_S);
955 /* check for overflow */
956 mono_mb_emit_ldloc (mb, bytes_var);
957 mono_mb_emit_icon (mb, sizeof (MonoString));
958 size_overflow_branch = mono_mb_emit_short_branch (mb, MONO_CEE_BLE_UN_S);
961 /* int index = INDEX_FROM_BYTES(bytes); */
962 index_var = mono_mb_add_local (mb, &mono_defaults.int32_class->byval_arg);
964 mono_mb_emit_ldloc (mb, bytes_var);
965 mono_mb_emit_icon (mb, GRANULARITY - 1);
966 mono_mb_emit_byte (mb, MONO_CEE_ADD);
967 mono_mb_emit_icon (mb, shift_amount (GRANULARITY));
968 mono_mb_emit_byte (mb, MONO_CEE_SHR_UN);
969 mono_mb_emit_icon (mb, shift_amount (sizeof (gpointer)));
970 mono_mb_emit_byte (mb, MONO_CEE_SHL);
971 /* index var is already adjusted into bytes */
972 mono_mb_emit_stloc (mb, index_var);
974 my_fl_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
975 my_entry_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
976 /* my_fl = ((GC_thread)tsd) -> ptrfree_freelists + index; */
977 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
978 mono_mb_emit_byte (mb, 0x0D); /* CEE_MONO_TLS */
979 mono_mb_emit_i4 (mb, tls_key);
980 if (atype == ATYPE_FREEPTR || atype == ATYPE_FREEPTR_FOR_BOX || atype == ATYPE_STRING)
981 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (struct GC_Thread_Rep, tlfs)
982 + G_STRUCT_OFFSET (struct thread_local_freelists,
984 else if (atype == ATYPE_NORMAL)
985 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (struct GC_Thread_Rep, tlfs)
986 + G_STRUCT_OFFSET (struct thread_local_freelists,
988 else if (atype == ATYPE_GCJ)
989 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (struct GC_Thread_Rep, tlfs)
990 + G_STRUCT_OFFSET (struct thread_local_freelists,
993 g_assert_not_reached ();
994 mono_mb_emit_byte (mb, MONO_CEE_ADD);
995 mono_mb_emit_ldloc (mb, index_var);
996 mono_mb_emit_byte (mb, MONO_CEE_ADD);
997 mono_mb_emit_stloc (mb, my_fl_var);
999 /* my_entry = *my_fl; */
1000 mono_mb_emit_ldloc (mb, my_fl_var);
1001 mono_mb_emit_byte (mb, MONO_CEE_LDIND_I);
1002 mono_mb_emit_stloc (mb, my_entry_var);
1004 /* if (EXPECT((word)my_entry >= HBLKSIZE, 1)) { */
1005 mono_mb_emit_ldloc (mb, my_entry_var);
1006 mono_mb_emit_icon (mb, HBLKSIZE);
1007 no_freelist_branch = mono_mb_emit_short_branch (mb, MONO_CEE_BLT_UN_S);
1009 /* ptr_t next = obj_link(my_entry); *my_fl = next; */
1010 mono_mb_emit_ldloc (mb, my_fl_var);
1011 mono_mb_emit_ldloc (mb, my_entry_var);
1012 mono_mb_emit_byte (mb, MONO_CEE_LDIND_I);
1013 mono_mb_emit_byte (mb, MONO_CEE_STIND_I);
1015 /* set the vtable and clear the words in the object */
1016 mono_mb_emit_ldloc (mb, my_entry_var);
1017 mono_mb_emit_ldarg (mb, 0);
1018 mono_mb_emit_byte (mb, MONO_CEE_STIND_I);
1020 if (atype == ATYPE_FREEPTR) {
1021 int start_var, end_var, start_loop;
1022 /* end = my_entry + bytes; start = my_entry + sizeof (gpointer);
1024 start_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
1025 end_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
1026 mono_mb_emit_ldloc (mb, my_entry_var);
1027 mono_mb_emit_ldloc (mb, bytes_var);
1028 mono_mb_emit_byte (mb, MONO_CEE_ADD);
1029 mono_mb_emit_stloc (mb, end_var);
1030 mono_mb_emit_ldloc (mb, my_entry_var);
1031 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoObject, synchronisation));
1032 mono_mb_emit_byte (mb, MONO_CEE_ADD);
1033 mono_mb_emit_stloc (mb, start_var);
1037 * } while (start < end);
1039 start_loop = mono_mb_get_label (mb);
1040 mono_mb_emit_ldloc (mb, start_var);
1041 mono_mb_emit_icon (mb, 0);
1042 mono_mb_emit_byte (mb, MONO_CEE_STIND_I);
1043 mono_mb_emit_ldloc (mb, start_var);
1044 mono_mb_emit_icon (mb, sizeof (gpointer));
1045 mono_mb_emit_byte (mb, MONO_CEE_ADD);
1046 mono_mb_emit_stloc (mb, start_var);
1048 mono_mb_emit_ldloc (mb, start_var);
1049 mono_mb_emit_ldloc (mb, end_var);
1050 mono_mb_emit_byte (mb, MONO_CEE_BLT_UN_S);
1051 mono_mb_emit_byte (mb, start_loop - (mono_mb_get_label (mb) + 1));
1052 } else if (atype == ATYPE_FREEPTR_FOR_BOX || atype == ATYPE_STRING) {
1053 /* need to clear just the sync pointer */
1054 mono_mb_emit_ldloc (mb, my_entry_var);
1055 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoObject, synchronisation));
1056 mono_mb_emit_byte (mb, MONO_CEE_ADD);
1057 mono_mb_emit_icon (mb, 0);
1058 mono_mb_emit_byte (mb, MONO_CEE_STIND_I);
1061 if (atype == ATYPE_STRING) {
1062 /* need to set length and clear the last char */
1063 /* s->length = len; */
1064 mono_mb_emit_ldloc (mb, my_entry_var);
1065 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoString, length));
1066 mono_mb_emit_byte (mb, MONO_CEE_ADD);
1067 mono_mb_emit_ldarg (mb, 1);
1068 mono_mb_emit_byte (mb, MONO_CEE_STIND_I4);
1069 /* s->chars [len] = 0; */
1070 mono_mb_emit_ldloc (mb, my_entry_var);
1071 mono_mb_emit_ldloc (mb, bytes_var);
1072 mono_mb_emit_icon (mb, 2);
1073 mono_mb_emit_byte (mb, MONO_CEE_SUB);
1074 mono_mb_emit_byte (mb, MONO_CEE_ADD);
1075 mono_mb_emit_icon (mb, 0);
1076 mono_mb_emit_byte (mb, MONO_CEE_STIND_I2);
1079 /* return my_entry; */
1080 mono_mb_emit_ldloc (mb, my_entry_var);
1081 mono_mb_emit_byte (mb, MONO_CEE_RET);
1083 mono_mb_patch_short_branch (mb, no_freelist_branch);
1084 if (not_small_enough_branch > 0)
1085 mono_mb_patch_short_branch (mb, not_small_enough_branch);
1086 if (size_overflow_branch > 0)
1087 mono_mb_patch_short_branch (mb, size_overflow_branch);
1089 /* the slow path: we just call back into the runtime */
1091 if (atype == ATYPE_STRING) {
1092 mono_mb_emit_ldarg (mb, 1);
1093 mono_mb_emit_icall (mb, ves_icall_string_alloc);
1095 mono_mb_emit_ldarg (mb, 0);
1096 mono_mb_emit_icall (mb, ves_icall_object_new_specific);
1099 mono_mb_emit_byte (mb, MONO_CEE_RET);
1101 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
1102 info->d.alloc.gc_name = "boehm";
1103 info->d.alloc.alloc_type = atype;
1104 mb->init_locals = FALSE;
1106 res = mono_mb_create (mb, csig, 8, info);
1112 static MonoMethod* alloc_method_cache [ATYPE_NUM];
1113 static MonoMethod* slowpath_alloc_method_cache [ATYPE_NUM];
1116 mono_gc_is_critical_method (MonoMethod *method)
1120 for (i = 0; i < ATYPE_NUM; ++i)
1121 if (method == alloc_method_cache [i] || method == slowpath_alloc_method_cache [i])
1128 * If possible, generate a managed method that can quickly allocate objects in class
1129 * @klass. The method will typically have an thread-local inline allocation sequence.
1130 * The signature of the called method is:
1131 * object allocate (MonoVTable *vtable)
1132 * Some of the logic here is similar to mono_class_get_allocation_ftn () i object.c,
1134 * The thread local alloc logic is taken from libgc/pthread_support.c.
1138 mono_gc_get_managed_allocator (MonoClass *klass, gboolean for_box, gboolean known_instance_size)
1143 * Tls implementation changed, we jump to tls native getters/setters.
1144 * Is boehm managed allocator ok with this ? Do we even care ?
1148 if (!SMALL_ENOUGH (klass->instance_size))
1150 if (mono_class_has_finalizer (klass) || mono_class_is_marshalbyref (klass))
1152 if (mono_profiler_get_events () & (MONO_PROFILE_ALLOCATIONS | MONO_PROFILE_STATISTICAL))
1156 if (mono_class_is_open_constructed_type (&klass->byval_arg))
1158 if (klass->byval_arg.type == MONO_TYPE_STRING) {
1159 atype = ATYPE_STRING;
1160 } else if (!known_instance_size) {
1162 } else if (!klass->has_references) {
1164 atype = ATYPE_FREEPTR_FOR_BOX;
1166 atype = ATYPE_FREEPTR;
1170 * disabled because we currently do a runtime choice anyway, to
1171 * deal with multiple appdomains.
1172 if (vtable->gc_descr != GC_NO_DESCRIPTOR)
1175 atype = ATYPE_NORMAL;
1178 return mono_gc_get_managed_allocator_by_type (atype, MANAGED_ALLOCATOR_REGULAR);
1182 mono_gc_get_managed_array_allocator (MonoClass *klass)
1188 * mono_gc_get_managed_allocator_by_type:
1190 * Return a managed allocator method corresponding to allocator type ATYPE.
1193 mono_gc_get_managed_allocator_by_type (int atype, ManagedAllocatorVariant variant)
1196 gboolean slowpath = variant != MANAGED_ALLOCATOR_REGULAR;
1197 MonoMethod **cache = slowpath ? slowpath_alloc_method_cache : alloc_method_cache;
1201 res = cache [atype];
1205 res = create_allocator (atype, -1, slowpath);
1206 mono_os_mutex_lock (&mono_gc_lock);
1207 if (cache [atype]) {
1208 mono_free_method (res);
1209 res = cache [atype];
1211 mono_memory_barrier ();
1212 cache [atype] = res;
1214 mono_os_mutex_unlock (&mono_gc_lock);
1219 mono_gc_get_managed_allocator_types (void)
1225 mono_gc_get_write_barrier (void)
1227 g_assert_not_reached ();
1234 mono_gc_is_critical_method (MonoMethod *method)
1240 mono_gc_get_managed_allocator (MonoClass *klass, gboolean for_box, gboolean known_instance_size)
1246 mono_gc_get_managed_array_allocator (MonoClass *klass)
1252 mono_gc_get_managed_allocator_by_type (int atype, ManagedAllocatorVariant variant)
1258 mono_gc_get_managed_allocator_types (void)
1264 mono_gc_get_write_barrier (void)
1266 g_assert_not_reached ();
1273 mono_gc_get_specific_write_barrier (gboolean is_concurrent)
1275 g_assert_not_reached ();
1280 mono_gc_get_aligned_size_for_allocator (int size)
1286 mono_gc_get_gc_name (void)
1292 mono_gc_invoke_with_gc_lock (MonoGCLockedCallbackFunc func, void *data)
1294 return GC_call_with_alloc_lock (func, data);
1298 mono_gc_get_description (void)
1300 return g_strdup (DEFAULT_GC_NAME);
1304 mono_gc_set_desktop_mode (void)
1310 mono_gc_is_moving (void)
1316 mono_gc_is_disabled (void)
1318 if (GC_dont_gc || g_hasenv ("GC_DONT_GC"))
1325 mono_gc_wbarrier_range_copy (gpointer _dest, gpointer _src, int size)
1327 g_assert_not_reached ();
1331 mono_gc_get_range_copy_func (void)
1333 return &mono_gc_wbarrier_range_copy;
1337 mono_gc_get_card_table (int *shift_bits, gpointer *card_mask)
1339 g_assert_not_reached ();
1344 mono_gc_card_table_nursery_check (void)
1346 g_assert_not_reached ();
1351 mono_gc_get_nursery (int *shift_bits, size_t *size)
1357 mono_gc_precise_stack_mark_enabled (void)
1363 mono_gc_get_logfile (void)
1369 mono_gc_params_set (const char* options)
1374 mono_gc_debug_set (const char* options)
1379 mono_gc_conservatively_scan_area (void *start, void *end)
1381 g_assert_not_reached ();
1385 mono_gc_scan_object (void *obj, void *gc_data)
1387 g_assert_not_reached ();
1392 mono_gc_get_bitmap_for_descr (void *descr, int *numbits)
1394 g_assert_not_reached ();
1399 mono_gc_set_gc_callbacks (MonoGCCallbacks *callbacks)
1404 mono_gc_set_stack_end (void *stack_end)
1408 void mono_gc_set_skip_thread (gboolean value)
1413 mono_gc_register_for_finalization (MonoObject *obj, void *user_data)
1418 /* This assertion is not valid when GC_DEBUG is defined */
1419 g_assert (GC_base (obj) == (char*)obj - offset);
1422 GC_REGISTER_FINALIZER_NO_ORDER ((char*)obj - offset, (GC_finalization_proc)user_data, GUINT_TO_POINTER (offset), NULL, NULL);
1427 mono_gc_pthread_create (pthread_t *new_thread, const pthread_attr_t *attr, void *(*start_routine)(void *), void *arg)
1429 /* it is being replaced by GC_pthread_create on some
1430 * platforms, see libgc/include/gc_pthread_redirects.h */
1431 return pthread_create (new_thread, attr, start_routine, arg);
1436 BOOL APIENTRY mono_gc_dllmain (HMODULE module_handle, DWORD reason, LPVOID reserved)
1438 return GC_DllMain (module_handle, reason, reserved);
1443 mono_gc_get_vtable_bits (MonoClass *klass)
1445 if (fin_callbacks.is_class_finalization_aware) {
1446 if (fin_callbacks.is_class_finalization_aware (klass))
1447 return BOEHM_GC_BIT_FINALIZER_AWARE;
1453 * mono_gc_register_altstack:
1455 * Register the dimensions of the normal stack and altstack with the collector.
1456 * Currently, STACK/STACK_SIZE is only used when the thread is suspended while it is on an altstack.
1459 mono_gc_register_altstack (gpointer stack, gint32 stack_size, gpointer altstack, gint32 altstack_size)
1461 GC_register_altstack (stack, stack_size, altstack, altstack_size);
1465 mono_gc_get_los_limit (void)
1471 mono_gc_set_string_length (MonoString *str, gint32 new_length)
1473 mono_unichar2 *new_end = str->chars + new_length;
1475 /* zero the discarded string. This null-delimits the string and allows
1476 * the space to be reclaimed by SGen. */
1478 memset (new_end, 0, (str->length - new_length + 1) * sizeof (mono_unichar2));
1479 str->length = new_length;
1483 mono_gc_user_markers_supported (void)
1489 mono_gc_make_root_descr_user (MonoGCRootMarkFunc marker)
1491 g_assert_not_reached ();
1495 /* Toggleref support */
1498 mono_gc_toggleref_add (MonoObject *object, mono_bool strong_ref)
1500 if (GC_toggleref_add ((GC_PTR)object, (int)strong_ref) != GC_SUCCESS)
1501 g_error ("GC_toggleref_add failed\n");
1505 mono_gc_toggleref_register_callback (MonoToggleRefStatus (*proccess_toggleref) (MonoObject *obj))
1507 GC_set_toggleref_func ((GC_ToggleRefStatus (*) (GC_PTR obj)) proccess_toggleref);
1510 /* Test support code */
1512 static MonoToggleRefStatus
1513 test_toggleref_callback (MonoObject *obj)
1515 static MonoClassField *mono_toggleref_test_field;
1516 MonoToggleRefStatus status = MONO_TOGGLE_REF_DROP;
1518 if (!mono_toggleref_test_field) {
1519 mono_toggleref_test_field = mono_class_get_field_from_name (mono_object_get_class (obj), "__test");
1520 g_assert (mono_toggleref_test_field);
1523 mono_field_get_value (obj, mono_toggleref_test_field, &status);
1524 printf ("toggleref-cb obj %d\n", status);
1529 register_test_toggleref_callback (void)
1531 mono_gc_toggleref_register_callback (test_toggleref_callback);
1535 is_finalization_aware (MonoObject *obj)
1537 MonoVTable *vt = obj->vtable;
1538 return (vt->gc_bits & BOEHM_GC_BIT_FINALIZER_AWARE) == BOEHM_GC_BIT_FINALIZER_AWARE;
1542 fin_notifier (MonoObject *obj)
1544 if (is_finalization_aware (obj))
1545 fin_callbacks.object_queued_for_finalization (obj);
1549 mono_gc_register_finalizer_callbacks (MonoGCFinalizerCallbacks *callbacks)
1551 if (callbacks->version != MONO_GC_FINALIZER_EXTENSION_VERSION)
1552 g_error ("Invalid finalizer callback version. Expected %d but got %d\n", MONO_GC_FINALIZER_EXTENSION_VERSION, callbacks->version);
1554 fin_callbacks = *callbacks;
1556 GC_set_await_finalize_proc ((void (*) (GC_PTR))fin_notifier);
1559 #define BITMAP_SIZE (sizeof (*((HandleData *)NULL)->bitmap) * CHAR_BIT)
1561 static inline gboolean
1562 slot_occupied (HandleData *handles, guint slot) {
1563 return handles->bitmap [slot / BITMAP_SIZE] & (1 << (slot % BITMAP_SIZE));
1567 vacate_slot (HandleData *handles, guint slot) {
1568 handles->bitmap [slot / BITMAP_SIZE] &= ~(1 << (slot % BITMAP_SIZE));
1572 occupy_slot (HandleData *handles, guint slot) {
1573 handles->bitmap [slot / BITMAP_SIZE] |= 1 << (slot % BITMAP_SIZE);
1577 find_first_unset (guint32 bitmap)
1580 for (i = 0; i < 32; ++i) {
1581 if (!(bitmap & (1 << i)))
1588 handle_data_alloc_entries (HandleData *handles)
1591 if (MONO_GC_HANDLE_TYPE_IS_WEAK (handles->type)) {
1592 handles->entries = (void **)g_malloc0 (sizeof (*handles->entries) * handles->size);
1593 handles->domain_ids = (guint16 *)g_malloc0 (sizeof (*handles->domain_ids) * handles->size);
1595 handles->entries = (void **)mono_gc_alloc_fixed (sizeof (*handles->entries) * handles->size, NULL, MONO_ROOT_SOURCE_GC_HANDLE, "gc handles table");
1597 handles->bitmap = (guint32 *)g_malloc0 (handles->size / CHAR_BIT);
1601 handle_data_next_unset (HandleData *handles)
1604 for (slot = handles->slot_hint; slot < handles->size / BITMAP_SIZE; ++slot) {
1605 if (handles->bitmap [slot] == 0xffffffff)
1607 handles->slot_hint = slot;
1608 return find_first_unset (handles->bitmap [slot]);
1614 handle_data_first_unset (HandleData *handles)
1617 for (slot = 0; slot < handles->slot_hint; ++slot) {
1618 if (handles->bitmap [slot] == 0xffffffff)
1620 handles->slot_hint = slot;
1621 return find_first_unset (handles->bitmap [slot]);
1626 /* Returns the index of the current slot in the bitmap. */
1628 handle_data_grow (HandleData *handles, gboolean track)
1630 guint32 *new_bitmap;
1631 guint32 new_size = handles->size * 2; /* always double: we memset to 0 based on this below */
1633 /* resize and copy the bitmap */
1634 new_bitmap = (guint32 *)g_malloc0 (new_size / CHAR_BIT);
1635 memcpy (new_bitmap, handles->bitmap, handles->size / CHAR_BIT);
1636 g_free (handles->bitmap);
1637 handles->bitmap = new_bitmap;
1639 /* resize and copy the entries */
1640 if (MONO_GC_HANDLE_TYPE_IS_WEAK (handles->type)) {
1642 guint16 *domain_ids;
1644 domain_ids = (guint16 *)g_malloc0 (sizeof (*handles->domain_ids) * new_size);
1645 entries = (void **)g_malloc0 (sizeof (*handles->entries) * new_size);
1646 memcpy (domain_ids, handles->domain_ids, sizeof (*handles->domain_ids) * handles->size);
1647 for (i = 0; i < handles->size; ++i) {
1648 MonoObject *obj = mono_gc_weak_link_get (&(handles->entries [i]));
1650 mono_gc_weak_link_add (&(entries [i]), obj, track);
1651 mono_gc_weak_link_remove (&(handles->entries [i]), track);
1653 g_assert (!handles->entries [i]);
1656 g_free (handles->entries);
1657 g_free (handles->domain_ids);
1658 handles->entries = entries;
1659 handles->domain_ids = domain_ids;
1662 entries = (void **)mono_gc_alloc_fixed (sizeof (*handles->entries) * new_size, NULL, MONO_ROOT_SOURCE_GC_HANDLE, "gc handles table");
1663 mono_gc_memmove_aligned (entries, handles->entries, sizeof (*handles->entries) * handles->size);
1664 mono_gc_free_fixed (handles->entries);
1665 handles->entries = entries;
1667 handles->slot_hint = handles->size / BITMAP_SIZE;
1668 handles->size = new_size;
1672 alloc_handle (HandleData *handles, MonoObject *obj, gboolean track)
1676 lock_handles (handles);
1678 handle_data_alloc_entries (handles);
1679 i = handle_data_next_unset (handles);
1680 if (i == -1 && handles->slot_hint != 0)
1681 i = handle_data_first_unset (handles);
1683 handle_data_grow (handles, track);
1686 slot = handles->slot_hint * BITMAP_SIZE + i;
1687 occupy_slot (handles, slot);
1688 handles->entries [slot] = NULL;
1689 if (MONO_GC_HANDLE_TYPE_IS_WEAK (handles->type)) {
1690 /*FIXME, what to use when obj == null?*/
1691 handles->domain_ids [slot] = (obj ? mono_object_get_domain (obj) : mono_domain_get ())->domain_id;
1693 mono_gc_weak_link_add (&(handles->entries [slot]), obj, track);
1695 handles->entries [slot] = obj;
1698 #ifndef DISABLE_PERFCOUNTERS
1699 mono_perfcounters->gc_num_handles++;
1701 unlock_handles (handles);
1702 res = MONO_GC_HANDLE (slot, handles->type);
1703 mono_profiler_gc_handle (MONO_PROFILER_GC_HANDLE_CREATED, handles->type, res, obj);
1708 * mono_gchandle_new:
1709 * \param obj managed object to get a handle for
1710 * \param pinned whether the object should be pinned
1712 * This returns a handle that wraps the object, this is used to keep a
1713 * reference to a managed object from the unmanaged world and preventing the
1714 * object from being disposed.
1716 * If \p pinned is false the address of the object can not be obtained, if it is
1717 * true the address of the object can be obtained. This will also pin the
1718 * object so it will not be possible by a moving garbage collector to move the
1721 * \returns a handle that can be used to access the object from
1725 mono_gchandle_new (MonoObject *obj, gboolean pinned)
1727 return alloc_handle (&gc_handles [pinned? HANDLE_PINNED: HANDLE_NORMAL], obj, FALSE);
1731 * mono_gchandle_new_weakref:
1732 * \param obj managed object to get a handle for
1733 * \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.
1735 * This returns a weak handle that wraps the object, this is used to
1736 * keep a reference to a managed object from the unmanaged world.
1737 * Unlike the \c mono_gchandle_new the object can be reclaimed by the
1738 * garbage collector. In this case the value of the GCHandle will be
1741 * If \p track_resurrection is TRUE the object will be tracked through
1742 * finalization and if the object is resurrected during the execution
1743 * of the finalizer, then the returned weakref will continue to hold
1744 * a reference to the object. If \p track_resurrection is FALSE, then
1745 * the weak reference's target will become NULL as soon as the object
1746 * is passed on to the finalizer.
1748 * \returns a handle that can be used to access the object from
1752 mono_gchandle_new_weakref (MonoObject *obj, gboolean track_resurrection)
1754 return alloc_handle (&gc_handles [track_resurrection? HANDLE_WEAK_TRACK: HANDLE_WEAK], obj, track_resurrection);
1758 * mono_gchandle_get_target:
1759 * \param gchandle a GCHandle's handle.
1761 * The handle was previously created by calling \c mono_gchandle_new or
1762 * \c mono_gchandle_new_weakref.
1764 * \returns A pointer to the \c MonoObject* represented by the handle or
1765 * NULL for a collected object if using a weakref handle.
1768 mono_gchandle_get_target (guint32 gchandle)
1770 guint slot = MONO_GC_HANDLE_SLOT (gchandle);
1771 guint type = MONO_GC_HANDLE_TYPE (gchandle);
1772 HandleData *handles = &gc_handles [type];
1773 MonoObject *obj = NULL;
1774 if (type >= HANDLE_TYPE_MAX)
1777 lock_handles (handles);
1778 if (slot < handles->size && slot_occupied (handles, slot)) {
1779 if (MONO_GC_HANDLE_TYPE_IS_WEAK (handles->type)) {
1780 obj = mono_gc_weak_link_get (&handles->entries [slot]);
1782 obj = (MonoObject *)handles->entries [slot];
1785 /* print a warning? */
1787 unlock_handles (handles);
1788 /*g_print ("get target of entry %d of type %d: %p\n", slot, handles->type, obj);*/
1793 mono_gchandle_set_target (guint32 gchandle, MonoObject *obj)
1795 guint slot = MONO_GC_HANDLE_SLOT (gchandle);
1796 guint type = MONO_GC_HANDLE_TYPE (gchandle);
1797 HandleData *handles = &gc_handles [type];
1798 MonoObject *old_obj = NULL;
1800 g_assert (type < HANDLE_TYPE_MAX);
1801 lock_handles (handles);
1802 if (slot < handles->size && slot_occupied (handles, slot)) {
1803 if (MONO_GC_HANDLE_TYPE_IS_WEAK (handles->type)) {
1804 old_obj = (MonoObject *)handles->entries [slot];
1805 if (handles->entries [slot])
1806 mono_gc_weak_link_remove (&handles->entries [slot], handles->type == HANDLE_WEAK_TRACK);
1808 mono_gc_weak_link_add (&handles->entries [slot], obj, handles->type == HANDLE_WEAK_TRACK);
1809 /*FIXME, what to use when obj == null?*/
1810 handles->domain_ids [slot] = (obj ? mono_object_get_domain (obj) : mono_domain_get ())->domain_id;
1812 handles->entries [slot] = obj;
1815 /* print a warning? */
1817 /*g_print ("changed entry %d of type %d to object %p (in slot: %p)\n", slot, handles->type, obj, handles->entries [slot]);*/
1818 unlock_handles (handles);
1822 mono_gc_is_null (void)
1828 * mono_gchandle_is_in_domain:
1829 * \param gchandle a GCHandle's handle.
1830 * \param domain An application domain.
1832 * Use this function to determine if the \p gchandle points to an
1833 * object allocated in the specified \p domain.
1835 * \returns TRUE if the object wrapped by the \p gchandle belongs to the specific \p domain.
1838 mono_gchandle_is_in_domain (guint32 gchandle, MonoDomain *domain)
1840 guint slot = MONO_GC_HANDLE_SLOT (gchandle);
1841 guint type = MONO_GC_HANDLE_TYPE (gchandle);
1842 HandleData *handles = &gc_handles [type];
1843 gboolean result = FALSE;
1845 if (type >= HANDLE_TYPE_MAX)
1848 lock_handles (handles);
1849 if (slot < handles->size && slot_occupied (handles, slot)) {
1850 if (MONO_GC_HANDLE_TYPE_IS_WEAK (handles->type)) {
1851 result = domain->domain_id == handles->domain_ids [slot];
1854 obj = (MonoObject *)handles->entries [slot];
1858 result = domain == mono_object_domain (obj);
1861 /* print a warning? */
1863 unlock_handles (handles);
1868 * mono_gchandle_free:
1869 * \param gchandle a GCHandle's handle.
1871 * Frees the \p gchandle handle. If there are no outstanding
1872 * references, the garbage collector can reclaim the memory of the
1876 mono_gchandle_free (guint32 gchandle)
1878 guint slot = MONO_GC_HANDLE_SLOT (gchandle);
1879 guint type = MONO_GC_HANDLE_TYPE (gchandle);
1880 HandleData *handles = &gc_handles [type];
1881 if (type >= HANDLE_TYPE_MAX)
1884 lock_handles (handles);
1885 if (slot < handles->size && slot_occupied (handles, slot)) {
1886 if (MONO_GC_HANDLE_TYPE_IS_WEAK (handles->type)) {
1887 if (handles->entries [slot])
1888 mono_gc_weak_link_remove (&handles->entries [slot], handles->type == HANDLE_WEAK_TRACK);
1890 handles->entries [slot] = NULL;
1892 vacate_slot (handles, slot);
1894 /* print a warning? */
1896 #ifndef DISABLE_PERFCOUNTERS
1897 mono_perfcounters->gc_num_handles--;
1899 /*g_print ("freed entry %d of type %d\n", slot, handles->type);*/
1900 unlock_handles (handles);
1901 mono_profiler_gc_handle (MONO_PROFILER_GC_HANDLE_DESTROYED, handles->type, gchandle, NULL);
1905 * mono_gchandle_free_domain:
1906 * \param domain domain that is unloading
1908 * Function used internally to cleanup any GC handle for objects belonging
1909 * to the specified domain during appdomain unload.
1912 mono_gchandle_free_domain (MonoDomain *domain)
1916 for (type = HANDLE_TYPE_MIN; type < HANDLE_PINNED; ++type) {
1918 HandleData *handles = &gc_handles [type];
1919 lock_handles (handles);
1920 for (slot = 0; slot < handles->size; ++slot) {
1921 if (!slot_occupied (handles, slot))
1923 if (MONO_GC_HANDLE_TYPE_IS_WEAK (type)) {
1924 if (domain->domain_id == handles->domain_ids [slot]) {
1925 vacate_slot (handles, slot);
1926 if (handles->entries [slot])
1927 mono_gc_weak_link_remove (&handles->entries [slot], handles->type == HANDLE_WEAK_TRACK);
1930 if (handles->entries [slot] && mono_object_domain (handles->entries [slot]) == domain) {
1931 vacate_slot (handles, slot);
1932 handles->entries [slot] = NULL;
1936 unlock_handles (handles);
1942 MONO_EMPTY_SOURCE_FILE (boehm_gc);
1943 #endif /* no Boehm GC */