[coop handles] Assert if interior ptr handle passed to mono_gchandle_from_handle
[mono.git] / mono / metadata / handle.c
1 /*
2  * handle.c: Handle to object in native code
3  *
4  * Authors:
5  *  - Ludovic Henry <ludovic@xamarin.com>
6  *  - Aleksey Klieger <aleksey.klieger@xamarin.com>
7  *  - Rodrigo Kumpera <kumpera@xamarin.com>
8  *
9  * Copyright 2016 Dot net foundation.
10  * Licensed under the MIT license. See LICENSE file in the project root for full license information.
11  */
12
13 #include <config.h>
14 #include <glib.h>
15
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)
23
24 Add counters for:
25         number of stack marks
26         stack marks per icall
27         mix/max/avg size of stack marks
28         handle stack wastage
29
30 Actually do something in mono_handle_verify
31
32 Shrink the handles stack in mono_handle_stack_scan
33 Properly report it to the profiler.
34 Add a boehm implementation
35
36 TODO (things to explore):
37
38 There's no convenient way to wrap the object allocation function.
39 Right now we do this:
40         MonoCultureInfoHandle culture = MONO_HANDLE_NEW (MonoCultureInfo, mono_object_new_checked (domain, klass, &error));
41
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.
46 */
47
48 /*
49  * NOTE: Async suspend
50  * 
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.
56  *
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
62  * always be valid.
63  *
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.
69  */
70
71 const MonoObjectHandle mono_null_value_handle = NULL;
72
73 #define THIS_IS_AN_OK_NUMBER_OF_HANDLES 100
74
75 enum {
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
79 };
80
81 /* number of bits in each word of the interior pointer bitmap */
82 #define INTERIOR_HANDLE_BITMAP_BITS_PER_WORD (sizeof(guint32) << 3)
83
84 static gboolean
85 bitset_bits_test (guint32 *bitmaps, int idx)
86 {
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);
92 }
93
94 static void
95 bitset_bits_set (guint32 *bitmaps, int idx)
96 {
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;
101         *bitmap |= mask;
102 }
103 static void
104 bitset_bits_clear (guint32 *bitmaps, int idx)
105 {
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);
110         *bitmap &= mask;
111 }
112
113 static gpointer*
114 chunk_element_objslot_init (HandleChunk *chunk, int idx, gboolean interior)
115 {
116         if (interior)
117                 bitset_bits_set (chunk->interior_bitmap, idx);
118         else
119                 bitset_bits_clear (chunk->interior_bitmap, idx);
120         return &chunk->elems [idx].o;
121 }
122
123 static HandleChunkElem*
124 chunk_element (HandleChunk *chunk, int idx)
125 {
126         return &chunk->elems[idx];
127 }
128
129 static guint
130 chunk_element_kind (HandleChunk *chunk, int idx)
131 {
132         return bitset_bits_test (chunk->interior_bitmap, idx) ? HANDLE_CHUNK_PTR_INTERIOR : HANDLE_CHUNK_PTR_OBJ;
133 }
134
135 static HandleChunkElem*
136 handle_to_chunk_element (MonoObjectHandle o)
137 {
138         return (HandleChunkElem*)o;
139 }
140
141 /* Given a HandleChunkElem* search through the current handle stack to find its chunk and offset. */
142 static HandleChunk*
143 chunk_element_to_chunk_idx (HandleStack *stack, HandleChunkElem *elem, int *out_idx)
144 {
145         HandleChunk *top = stack->top;
146         HandleChunk *cur = stack->bottom;
147
148         *out_idx = 0;
149
150         while (cur != NULL) {
151                 HandleChunkElem *front = &cur->elems [0];
152                 HandleChunkElem *back = &cur->elems [cur->size];
153
154                 if (front <= elem && elem < back) {
155                         *out_idx = (int)(elem - front);
156                         return cur;
157                 }
158
159                 if (cur == top)
160                         break; /* didn't find it. */
161                 cur = cur->next;
162         }
163         return NULL;
164 }
165
166 #ifdef MONO_HANDLE_TRACK_OWNER
167 #define SET_OWNER(chunk,idx) do { (chunk)->elems[(idx)].owner = owner; } while (0)
168 #else
169 #define SET_OWNER(chunk,idx) do { } while (0)
170 #endif
171
172 MonoRawHandle
173 #ifndef MONO_HANDLE_TRACK_OWNER
174 mono_handle_new (MonoObject *object)
175 #else
176 mono_handle_new (MonoObject *object const char *owner)
177 #endif
178 {
179 #ifndef MONO_HANDLE_TRACK_OWNER
180         return mono_handle_new_full (object, FALSE);
181 #else
182         return mono_handle_new_full (object, FALSE, owner);
183 #endif
184 }
185 /* Actual handles implementation */
186 MonoRawHandle
187 #ifndef MONO_HANDLE_TRACK_OWNER
188 mono_handle_new_full (gpointer rawptr, gboolean interior)
189 #else
190 mono_handle_new_full (gpointer rawptr, gboolean interior, const char *owner)
191 #endif
192 {
193         MonoThreadInfo *info = mono_thread_info_current ();
194         HandleStack *handles = (HandleStack *)info->handle_stack;
195         HandleChunk *top = handles->top;
196
197 retry:
198         if (G_LIKELY (top->size < OBJECTS_PER_HANDLES_CHUNK)) {
199                 int idx = top->size;
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
205                  *
206                  * (have to do 1 then 3 so that if we're interrupted
207                  * between 1 and 2, the object is still live)
208                  */
209                 *objslot = NULL;
210                 mono_memory_write_barrier ();
211                 top->size++;
212                 mono_memory_write_barrier ();
213                 *objslot = rawptr;
214                 SET_OWNER (top,idx);
215                 return objslot;
216         }
217         if (G_LIKELY (top->next)) {
218                 top->next->size = 0;
219                 /* make sure size == 0 is visible to a GC thread before it sees the new top */
220                 mono_memory_write_barrier ();
221                 top = top->next;
222                 handles->top = top;
223                 goto retry;
224         }
225         HandleChunk *new_chunk = g_new (HandleChunk, 1);
226         new_chunk->size = 0;
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;
234         goto retry;
235 }
236
237
238
239 HandleStack*
240 mono_handle_stack_alloc (void)
241 {
242         HandleStack *stack = g_new (HandleStack, 1);
243         HandleChunk *chunk = g_new (HandleChunk, 1);
244
245         chunk->size = 0;
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;
250         return stack;
251 }
252
253 void
254 mono_handle_stack_free (HandleStack *stack)
255 {
256         if (!stack)
257                 return;
258         HandleChunk *c = stack->bottom;
259         stack->top = stack->bottom = NULL;
260         mono_memory_write_barrier ();
261         while (c) {
262                 HandleChunk *next = c->next;
263                 g_free (c);
264                 c = next;
265         }
266         g_free (c);
267         g_free (stack);
268 }
269
270 void
271 mono_handle_stack_scan (HandleStack *stack, GcScanFunc func, gpointer gc_data, gboolean precise)
272 {
273         /*
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
277           the object.
278
279           Note that if we're running, we know the world is stopped.
280         */
281         HandleChunk *cur = stack->bottom;
282         HandleChunk *last = stack->top;
283
284         if (!cur)
285                 return;
286
287         while (cur) {
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.
291                  */
292                 if (precise) {
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);
299                         }
300                 } else {
301                         int elem_idx = 0;
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)
305                                         break;
306                                 /* no interior pointers in the range */ 
307                                 if (cur->interior_bitmap [i] == 0)
308                                         continue;
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);
315                                 }
316                         }            
317                 }
318                 if (cur == last)
319                         break;
320                 cur = cur->next;
321         }
322 }
323
324 void
325 mono_stack_mark_record_size (MonoThreadInfo *info, HandleStackMark *stackmark, const char *func_name)
326 {
327         HandleStack *handles = (HandleStack *)info->handle_stack;
328         HandleChunk *cur = stackmark->chunk;
329         int size = -stackmark->size; //discard the starting point of the stack
330         while (cur) {
331                 size += cur->size;
332                 if (cur == handles->top)
333                         break;
334                 cur = cur->next;
335         }
336
337         if (size > THIS_IS_AN_OK_NUMBER_OF_HANDLES)
338                 g_warning ("%s USED %d handles\n", func_name, size);
339 }
340
341 /*
342  * Pop the stack until @stackmark and make @value the top value.
343  *
344  * @return the new handle for what @value points to 
345  */
346 MonoRawHandle
347 mono_stack_mark_pop_value (MonoThreadInfo *info, HandleStackMark *stackmark, MonoRawHandle value)
348 {
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);
353 #else
354         return mono_handle_new (obj, "<mono_stack_mark_pop_value>");
355 #endif
356 }
357
358 /* Temporary place for some of the handle enabled wrapper functions*/
359
360 MonoStringHandle
361 mono_string_new_handle (MonoDomain *domain, const char *data, MonoError *error)
362 {
363         return MONO_HANDLE_NEW (MonoString, mono_string_new_checked (domain, data, error));
364 }
365
366 MonoArrayHandle
367 mono_array_new_handle (MonoDomain *domain, MonoClass *eclass, uintptr_t n, MonoError *error)
368 {
369         return MONO_HANDLE_NEW (MonoArray, mono_array_new_checked (domain, eclass, n, error));
370 }
371
372 MonoArrayHandle
373 mono_array_new_full_handle (MonoDomain *domain, MonoClass *array_class, uintptr_t *lengths, intptr_t *lower_bounds, MonoError *error)
374 {
375         return MONO_HANDLE_NEW (MonoArray, mono_array_new_full_checked (domain, array_class, lengths, lower_bounds, error));
376 }
377
378 #ifdef ENABLE_CHECKED_BUILD
379 /* Checked build helpers */
380 void
381 mono_handle_verify (MonoRawHandle raw_handle)
382 {
383         
384 }
385 #endif
386
387 uintptr_t
388 mono_array_handle_length (MonoArrayHandle arr)
389 {
390         MONO_REQ_GC_UNSAFE_MODE;
391
392         return MONO_HANDLE_RAW (arr)->max_length;
393 }
394
395 uint32_t
396 mono_gchandle_from_handle (MonoObjectHandle handle, mono_bool pinned)
397 {
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);
403         int elem_idx = 0;
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);
409 }
410
411 MonoObjectHandle
412 mono_gchandle_get_target_handle (uint32_t gchandle)
413 {
414         return MONO_HANDLE_NEW (MonoObject, mono_gchandle_get_target (gchandle));
415 }
416
417 gpointer
418 mono_array_handle_pin_with_size (MonoArrayHandle handle, int size, uintptr_t idx, uint32_t *gchandle)
419 {
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);
424 }
425
426 void
427 mono_array_handle_memcpy_refs (MonoArrayHandle dest, uintptr_t dest_idx, MonoArrayHandle src, uintptr_t src_idx, uintptr_t len)
428 {
429         mono_array_memcpy_refs (MONO_HANDLE_RAW (dest), dest_idx, MONO_HANDLE_RAW (src), src_idx, len);
430 }
431
432 gboolean
433 mono_handle_stack_is_empty (HandleStack *stack)
434 {
435         return (stack->top == stack->bottom && stack->top->size == 0);
436 }