2 * handle.c: Handle to object in native code
5 * - Ludovic Henry <ludovic@xamarin.com>
6 * - Aleksey Klieger <aleksey.klieger@xamarin.com>
7 * - Rodrigo Kumpera <kumpera@xamarin.com>
9 * Copyright 2016 Dot net foundation.
10 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
16 #include <mono/metadata/handle.h>
17 #include <mono/metadata/object-internals.h>
18 #include <mono/metadata/gc-internals.h>
19 #include <mono/utils/atomic.h>
20 #include <mono/utils/mono-lazy-init.h>
21 #include <mono/utils/mono-threads.h>
22 /* TODO (missing pieces)
27 mix/max/avg size of stack marks
30 Actually do something in mono_handle_verify
32 Shrink the handles stack in mono_handle_stack_scan
33 Properly report it to the profiler.
34 Add a boehm implementation
36 TODO (things to explore):
38 There's no convenient way to wrap the object allocation function.
40 MonoCultureInfoHandle culture = MONO_HANDLE_NEW (MonoCultureInfo, mono_object_new_checked (domain, klass, &error));
42 Maybe what we need is a round of cleanup around all exposed types in the runtime to unify all helpers under the same hoof.
43 Combine: MonoDefaults, GENERATE_GET_CLASS_WITH_CACHE, TYPED_HANDLE_DECL and friends.
44 This would solve the age old issue of making it clear which types are optional and tell that to the linker.
45 We could then generate neat type safe wrappers.
51 * If we are running with cooperative GC, all the handle stack
52 * manipulation will complete before a GC thread scans the handle
53 * stack. If we are using async suspend, however, a thread may be
54 * trying to allocate a new handle, or unwind the handle stack when
55 * the GC stops the world.
57 * In particular, we need to ensure that if the mutator thread is
58 * suspended while manipulating the handle stack, the stack is in a
59 * good enough state to be scanned. In particular, the size of each
60 * chunk should be updated before an object is written into the
61 * handle, and chunks to be scanned (between bottom and top) should
64 * Note that the handle stack is scanned PRECISELY (see
65 * sgen_client_scan_thread_data ()). That means there should not be
66 * stale objects scanned. So when we manipulate the size of a chunk,
67 * wemust ensure that the newly scannable slot is either null or
68 * points to a valid value.
71 const MonoObjectHandle mono_null_value_handle = NULL;
73 #define THIS_IS_AN_OK_NUMBER_OF_HANDLES 100
76 HANDLE_CHUNK_PTR_OBJ = 0x0, /* chunk element points to beginning of a managed object */
77 HANDLE_CHUNK_PTR_INTERIOR = 0x1, /* chunk element points into the middle of a managed object */
78 HANDLE_CHUNK_PTR_MASK = 0x1
81 /* number of bits in each word of the interior pointer bitmap */
82 #define INTERIOR_HANDLE_BITMAP_BITS_PER_WORD (sizeof(guint32) << 3)
85 bitset_bits_test (guint32 *bitmaps, int idx)
87 int w = idx / INTERIOR_HANDLE_BITMAP_BITS_PER_WORD;
88 int b = idx % INTERIOR_HANDLE_BITMAP_BITS_PER_WORD;
89 guint32 bitmap = bitmaps [w];
90 guint32 mask = 1u << b;
91 return ((bitmap & mask) != 0);
95 bitset_bits_set (guint32 *bitmaps, int idx)
97 int w = idx / INTERIOR_HANDLE_BITMAP_BITS_PER_WORD;
98 int b = idx % INTERIOR_HANDLE_BITMAP_BITS_PER_WORD;
99 guint32 *bitmap = &bitmaps [w];
100 guint32 mask = 1u << b;
104 bitset_bits_clear (guint32 *bitmaps, int idx)
106 int w = idx / INTERIOR_HANDLE_BITMAP_BITS_PER_WORD;
107 int b = idx % INTERIOR_HANDLE_BITMAP_BITS_PER_WORD;
108 guint32 *bitmap = &bitmaps [w];
109 guint32 mask = ~(1u << b);
114 chunk_element_objslot_init (HandleChunk *chunk, int idx, gboolean interior)
117 bitset_bits_set (chunk->interior_bitmap, idx);
119 bitset_bits_clear (chunk->interior_bitmap, idx);
120 return &chunk->elems [idx].o;
123 static HandleChunkElem*
124 chunk_element (HandleChunk *chunk, int idx)
126 return &chunk->elems[idx];
130 chunk_element_kind (HandleChunk *chunk, int idx)
132 return bitset_bits_test (chunk->interior_bitmap, idx) ? HANDLE_CHUNK_PTR_INTERIOR : HANDLE_CHUNK_PTR_OBJ;
135 static HandleChunkElem*
136 handle_to_chunk_element (MonoObjectHandle o)
138 return (HandleChunkElem*)o;
141 /* Given a HandleChunkElem* search through the current handle stack to find its chunk and offset. */
143 chunk_element_to_chunk_idx (HandleStack *stack, HandleChunkElem *elem, int *out_idx)
145 HandleChunk *top = stack->top;
146 HandleChunk *cur = stack->bottom;
150 while (cur != NULL) {
151 HandleChunkElem *front = &cur->elems [0];
152 HandleChunkElem *back = &cur->elems [cur->size];
154 if (front <= elem && elem < back) {
155 *out_idx = (int)(elem - front);
160 break; /* didn't find it. */
166 #ifdef MONO_HANDLE_TRACK_OWNER
167 #define SET_OWNER(chunk,idx) do { (chunk)->elems[(idx)].owner = owner; } while (0)
169 #define SET_OWNER(chunk,idx) do { } while (0)
173 #ifndef MONO_HANDLE_TRACK_OWNER
174 mono_handle_new (MonoObject *object)
176 mono_handle_new (MonoObject *object const char *owner)
179 #ifndef MONO_HANDLE_TRACK_OWNER
180 return mono_handle_new_full (object, FALSE);
182 return mono_handle_new_full (object, FALSE, owner);
185 /* Actual handles implementation */
187 #ifndef MONO_HANDLE_TRACK_OWNER
188 mono_handle_new_full (gpointer rawptr, gboolean interior)
190 mono_handle_new_full (gpointer rawptr, gboolean interior, const char *owner)
193 MonoThreadInfo *info = mono_thread_info_current ();
194 HandleStack *handles = (HandleStack *)info->handle_stack;
195 HandleChunk *top = handles->top;
198 if (G_LIKELY (top->size < OBJECTS_PER_HANDLES_CHUNK)) {
200 gpointer* objslot = chunk_element_objslot_init (top, idx, interior);
201 /* can be interrupted anywhere here, so:
202 * 1. make sure the new slot is null
203 * 2. make the new slot scannable (increment size)
204 * 3. put a valid object in there
206 * (have to do 1 then 3 so that if we're interrupted
207 * between 1 and 2, the object is still live)
210 mono_memory_write_barrier ();
212 mono_memory_write_barrier ();
217 if (G_LIKELY (top->next)) {
219 /* make sure size == 0 is visible to a GC thread before it sees the new top */
220 mono_memory_write_barrier ();
225 HandleChunk *new_chunk = g_new (HandleChunk, 1);
227 memset (new_chunk->interior_bitmap, 0, INTERIOR_HANDLE_BITMAP_WORDS);
228 new_chunk->prev = top;
229 new_chunk->next = NULL;
230 /* make sure size == 0 before new chunk is visible */
231 mono_memory_write_barrier ();
232 top->next = new_chunk;
233 handles->top = new_chunk;
240 mono_handle_stack_alloc (void)
242 HandleStack *stack = g_new (HandleStack, 1);
243 HandleChunk *chunk = g_new (HandleChunk, 1);
246 memset (chunk->interior_bitmap, 0, INTERIOR_HANDLE_BITMAP_WORDS);
247 chunk->prev = chunk->next = NULL;
248 mono_memory_write_barrier ();
249 stack->top = stack->bottom = chunk;
254 mono_handle_stack_free (HandleStack *stack)
258 HandleChunk *c = stack->bottom;
259 stack->top = stack->bottom = NULL;
260 mono_memory_write_barrier ();
262 HandleChunk *next = c->next;
271 mono_handle_stack_scan (HandleStack *stack, GcScanFunc func, gpointer gc_data, gboolean precise)
274 We're called twice - on the imprecise pass we call func to pin the
275 objects where the handle points to its interior. On the precise
276 pass, we scan all the objects where the handles point to the start of
279 Note that if we're running, we know the world is stopped.
281 HandleChunk *cur = stack->bottom;
282 HandleChunk *last = stack->top;
288 /* assume that object pointers will be much more common than interior pointers.
289 * scan the object pointers by iterating over the chunk elements.
290 * scan the interior pointers by iterating over the bitmap bits.
293 for (int i = 0; i < cur->size; ++i) {
294 HandleChunkElem* elem = chunk_element (cur, i);
295 int kind = chunk_element_kind (cur, i);
296 gpointer* obj_slot = &elem->o;
297 if (kind == HANDLE_CHUNK_PTR_OBJ && *obj_slot != NULL)
298 func (obj_slot, gc_data);
302 for (int i = 0; i < INTERIOR_HANDLE_BITMAP_WORDS; ++i) {
303 elem_idx = i * INTERIOR_HANDLE_BITMAP_BITS_PER_WORD;
304 if (elem_idx >= cur->size)
306 /* no interior pointers in the range */
307 if (cur->interior_bitmap [i] == 0)
309 for (int j = 0; j < INTERIOR_HANDLE_BITMAP_BITS_PER_WORD && elem_idx < cur->size; ++j,++elem_idx) {
310 HandleChunkElem *elem = chunk_element (cur, elem_idx);
311 int kind = chunk_element_kind (cur, elem_idx);
312 gpointer *ptr_slot = &elem->o;
313 if (kind == HANDLE_CHUNK_PTR_INTERIOR && *ptr_slot != NULL)
314 func (ptr_slot, gc_data);
325 mono_stack_mark_record_size (MonoThreadInfo *info, HandleStackMark *stackmark, const char *func_name)
327 HandleStack *handles = (HandleStack *)info->handle_stack;
328 HandleChunk *cur = stackmark->chunk;
329 int size = -stackmark->size; //discard the starting point of the stack
332 if (cur == handles->top)
337 if (size > THIS_IS_AN_OK_NUMBER_OF_HANDLES)
338 g_warning ("%s USED %d handles\n", func_name, size);
342 * Pop the stack until @stackmark and make @value the top value.
344 * @return the new handle for what @value points to
347 mono_stack_mark_pop_value (MonoThreadInfo *info, HandleStackMark *stackmark, MonoRawHandle value)
349 MonoObject *obj = value ? *((MonoObject**)value) : NULL;
350 mono_stack_mark_pop (info, stackmark);
351 #ifndef MONO_HANDLE_TRACK_OWNER
352 return mono_handle_new (obj);
354 return mono_handle_new (obj, "<mono_stack_mark_pop_value>");
358 /* Temporary place for some of the handle enabled wrapper functions*/
361 mono_string_new_handle (MonoDomain *domain, const char *data, MonoError *error)
363 return MONO_HANDLE_NEW (MonoString, mono_string_new_checked (domain, data, error));
367 mono_array_new_handle (MonoDomain *domain, MonoClass *eclass, uintptr_t n, MonoError *error)
369 return MONO_HANDLE_NEW (MonoArray, mono_array_new_checked (domain, eclass, n, error));
373 mono_array_new_full_handle (MonoDomain *domain, MonoClass *array_class, uintptr_t *lengths, intptr_t *lower_bounds, MonoError *error)
375 return MONO_HANDLE_NEW (MonoArray, mono_array_new_full_checked (domain, array_class, lengths, lower_bounds, error));
378 #ifdef ENABLE_CHECKED_BUILD
379 /* Checked build helpers */
381 mono_handle_verify (MonoRawHandle raw_handle)
388 mono_array_handle_length (MonoArrayHandle arr)
390 MONO_REQ_GC_UNSAFE_MODE;
392 return MONO_HANDLE_RAW (arr)->max_length;
396 mono_gchandle_from_handle (MonoObjectHandle handle, mono_bool pinned)
398 /* FIXME: chunk_element_to_chunk_idx does a linear search through the
399 * chunks and we only need it for the assert */
400 MonoThreadInfo *info = mono_thread_info_current ();
401 HandleStack *stack = (HandleStack*) info->handle_stack;
402 HandleChunkElem* elem = handle_to_chunk_element (handle);
404 HandleChunk *chunk = chunk_element_to_chunk_idx (stack, elem, &elem_idx);
405 /* gchandles cannot deal with interior pointers */
406 g_assert (chunk != NULL);
407 g_assert (chunk_element_kind (chunk, elem_idx) != HANDLE_CHUNK_PTR_INTERIOR);
408 return mono_gchandle_new (MONO_HANDLE_RAW (handle), pinned);
412 mono_gchandle_get_target_handle (uint32_t gchandle)
414 return MONO_HANDLE_NEW (MonoObject, mono_gchandle_get_target (gchandle));
418 mono_array_handle_pin_with_size (MonoArrayHandle handle, int size, uintptr_t idx, uint32_t *gchandle)
420 g_assert (gchandle != NULL);
421 *gchandle = mono_gchandle_from_handle (MONO_HANDLE_CAST(MonoObject,handle), TRUE);
422 MonoArray *raw = MONO_HANDLE_RAW (handle);
423 return mono_array_addr_with_size (raw, size, idx);
427 mono_array_handle_memcpy_refs (MonoArrayHandle dest, uintptr_t dest_idx, MonoArrayHandle src, uintptr_t src_idx, uintptr_t len)
429 mono_array_memcpy_refs (MONO_HANDLE_RAW (dest), dest_idx, MONO_HANDLE_RAW (src), src_idx, len);
433 mono_handle_stack_is_empty (HandleStack *stack)
435 return (stack->top == stack->bottom && stack->top->size == 0);