[jit] Always cache the latest image set in case of a cache miss.
[mono.git] / mono / metadata / handle.h
1 /**
2  * \file
3  * Handle to object in native code
4  *
5  * Authors:
6  *  - Ludovic Henry <ludovic@xamarin.com>
7  *  - Aleksey Klieger <aleksey.klieger@xamarin.com>
8  *  - Rodrigo Kumpera <kumpera@xamarin.com>
9  *
10  * Copyright 2016 Dot net foundation.
11  * Licensed under the MIT license. See LICENSE file in the project root for full license information.
12  */
13
14 #ifndef __MONO_HANDLE_H__
15 #define __MONO_HANDLE_H__
16
17 #include <config.h>
18 #include <glib.h>
19
20 #include <mono/metadata/object.h>
21 #include <mono/metadata/class.h>
22 #include <mono/utils/mono-error-internals.h>
23 #include <mono/utils/mono-threads.h>
24 #include <mono/utils/checked-build.h>
25
26 G_BEGIN_DECLS
27
28
29 /*
30 Handle stack.
31
32 The handle stack is designed so it's efficient to pop a large amount of entries at once.
33 The stack is made out of a series of fixed size segments.
34
35 To do bulk operations you use a stack mark.
36         
37 */
38
39 /*
40 3 is the number of fields besides the data in the struct;
41 128 words makes each chunk 512 or 1024 bytes each
42 */
43 #define OBJECTS_PER_HANDLES_CHUNK (128 - 3)
44
45 /*
46 Whether this config needs stack watermark recording to know where to start scanning from.
47 */
48 #ifdef HOST_WATCHOS
49 #define MONO_NEEDS_STACK_WATERMARK 1
50 #endif
51
52 typedef struct _HandleChunk HandleChunk;
53
54 /* define MONO_HANDLE_TRACK_OWNER to store the file and line number of each call to MONO_HANDLE_NEW
55  * in the handle stack.  (This doubles the amount of memory used for handles, so it's only useful for debugging).
56  */
57 /*#define MONO_HANDLE_TRACK_OWNER*/
58
59 /* define MONO_HANDLE_TRACK_SP to record the C stack pointer at the time of each HANDLE_FUNCTION_ENTER and
60  * to ensure that when a new handle is allocated the previous newest handle is not lower in the stack.
61  * This is useful to catch missing HANDLE_FUNCTION_ENTER / HANDLE_FUNCTION_RETURN pairs which could cause
62  * handle leaks.
63  */
64 /*#define MONO_HANDLE_TRACK_SP*/
65
66 typedef struct {
67         gpointer o; /* MonoObject ptr or interior ptr */
68 #ifdef MONO_HANDLE_TRACK_OWNER
69         const char *owner;
70 #endif
71 #ifdef MONO_HANDLE_TRACK_SP
72         gpointer alloc_sp; /* sp from HandleStack:stackmark_sp at time of allocation */
73 #endif
74 } HandleChunkElem;
75
76 /* number of guint32's needed to store the interior pointers bitmap */
77 #define INTERIOR_HANDLE_BITMAP_WORDS ((OBJECTS_PER_HANDLES_CHUNK + 31) / 32)
78
79 struct _HandleChunk {
80         int size; //number of handles
81         /* bits in the range 0..size-1 of interior_bitmap are valid; rest are ignored. */
82         guint32 interior_bitmap [INTERIOR_HANDLE_BITMAP_WORDS];
83         HandleChunk *prev, *next;
84         HandleChunkElem elems [OBJECTS_PER_HANDLES_CHUNK];
85 };
86
87 typedef struct {
88         HandleChunk *top; //alloc from here
89         HandleChunk *bottom; //scan from here
90 #ifdef MONO_HANDLE_TRACK_SP
91         gpointer stackmark_sp; // C stack pointer top when from most recent mono_stack_mark_init
92 #endif
93 } HandleStack;
94
95 typedef struct {
96         int size;
97         HandleChunk *chunk;
98 #ifdef MONO_HANDLE_TRACK_SP
99         gpointer prev_sp; // C stack pointer from prior mono_stack_mark_init
100 #endif
101 } HandleStackMark;
102
103 typedef void *MonoRawHandle;
104
105 typedef void (*GcScanFunc) (gpointer*, gpointer);
106
107
108 #ifndef MONO_HANDLE_TRACK_OWNER
109 MonoRawHandle mono_handle_new (MonoObject *object);
110 MonoRawHandle mono_handle_new_full (gpointer rawptr, gboolean interior);
111 #else
112 MonoRawHandle mono_handle_new (MonoObject *object, const char* owner);
113 MonoRawHandle mono_handle_new_full (gpointer rawptr, gboolean interior, const char *owner);
114 #endif
115
116
117 void mono_handle_stack_scan (HandleStack *stack, GcScanFunc func, gpointer gc_data, gboolean precise);
118 gboolean mono_handle_stack_is_empty (HandleStack *stack);
119 HandleStack* mono_handle_stack_alloc (void);
120 void mono_handle_stack_free (HandleStack *handlestack);
121 MonoRawHandle mono_stack_mark_pop_value (MonoThreadInfo *info, HandleStackMark *stackmark, MonoRawHandle value);
122 void mono_stack_mark_record_size (MonoThreadInfo *info, HandleStackMark *stackmark, const char *func_name);
123
124 #ifdef MONO_HANDLE_TRACK_SP
125 void mono_handle_chunk_leak_check (HandleStack *handles);
126 #endif
127
128 static inline void
129 mono_stack_mark_init (MonoThreadInfo *info, HandleStackMark *stackmark)
130 {
131 #ifdef MONO_HANDLE_TRACK_SP
132         gpointer sptop = (gpointer)(intptr_t)&stackmark;
133 #endif
134         HandleStack *handles = (HandleStack *)info->handle_stack;
135         stackmark->size = handles->top->size;
136         stackmark->chunk = handles->top;
137 #ifdef MONO_HANDLE_TRACK_SP
138         stackmark->prev_sp = handles->stackmark_sp;
139         handles->stackmark_sp = sptop;
140 #endif
141 }
142
143 static inline void
144 mono_stack_mark_pop (MonoThreadInfo *info, HandleStackMark *stackmark)
145 {
146         HandleStack *handles = (HandleStack *)info->handle_stack;
147         HandleChunk *old_top = stackmark->chunk;
148         old_top->size = stackmark->size;
149         mono_memory_write_barrier ();
150         handles->top = old_top;
151 #ifdef MONO_HANDLE_TRACK_SP
152         mono_memory_write_barrier (); /* write to top before prev_sp */
153         handles->stackmark_sp = stackmark->prev_sp;
154 #endif
155 }
156
157 /*
158 Icall macros
159 */
160 #define SETUP_ICALL_COMMON      \
161         do { \
162                 MonoError error;        \
163                 MonoThreadInfo *__info = mono_thread_info_current ();   \
164                 error_init (&error);    \
165
166 #define CLEAR_ICALL_COMMON      \
167         mono_error_set_pending_exception (&error);
168
169 #define SETUP_ICALL_FRAME       \
170         HandleStackMark __mark; \
171         mono_stack_mark_init (__info, &__mark);
172
173 #define CLEAR_ICALL_FRAME       \
174         mono_stack_mark_record_size (__info, &__mark, __FUNCTION__);    \
175         mono_stack_mark_pop (__info, &__mark);
176
177 #define CLEAR_ICALL_FRAME_VALUE(RESULT, HANDLE)                         \
178         mono_stack_mark_record_size (__info, &__mark, __FUNCTION__);    \
179         (RESULT) = mono_stack_mark_pop_value (__info, &__mark, (HANDLE));
180
181
182 #define HANDLE_FUNCTION_ENTER() do {                            \
183         MonoThreadInfo *__info = mono_thread_info_current ();   \
184         SETUP_ICALL_FRAME                                       \
185
186 #define HANDLE_FUNCTION_RETURN()                \
187         CLEAR_ICALL_FRAME;                      \
188         } while (0)
189
190 #define HANDLE_FUNCTION_RETURN_VAL(VAL)         \
191         CLEAR_ICALL_FRAME;                      \
192         return (VAL);                           \
193         } while (0)
194
195 #define HANDLE_FUNCTION_RETURN_OBJ(HANDLE)                      \
196         do {                                                    \
197                 void* __result = (MONO_HANDLE_RAW (HANDLE));    \
198                 CLEAR_ICALL_FRAME;                              \
199                 return __result;                                \
200         } while (0); } while (0);
201
202 #define HANDLE_FUNCTION_RETURN_REF(TYPE, HANDLE)                        \
203         do {                                                            \
204                 MonoRawHandle __result;                                 \
205                 CLEAR_ICALL_FRAME_VALUE (__result, ((MonoRawHandle) (HANDLE))); \
206                 return MONO_HANDLE_CAST (TYPE, __result);               \
207         } while (0); } while (0);
208
209 #ifdef MONO_NEEDS_STACK_WATERMARK
210
211 static void
212 mono_thread_info_pop_stack_mark (MonoThreadInfo *info, void *old_mark)
213 {
214         info->stack_mark = old_mark;
215 }
216
217 static void*
218 mono_thread_info_push_stack_mark (MonoThreadInfo *info, void *mark)
219 {
220         void *old = info->stack_mark;
221         info->stack_mark = mark;
222         return old;
223 }
224
225 #define SETUP_STACK_WATERMARK   \
226         int __dummy;    \
227         __builtin_unwind_init ();       \
228         void *__old_stack_mark = mono_thread_info_push_stack_mark (__info, &__dummy);
229
230 #define CLEAR_STACK_WATERMARK   \
231         mono_thread_info_pop_stack_mark (__info, __old_stack_mark);
232
233 #else
234 #define SETUP_STACK_WATERMARK
235 #define CLEAR_STACK_WATERMARK
236 #endif
237
238 #define ICALL_ENTRY()   \
239         SETUP_ICALL_COMMON      \
240         SETUP_ICALL_FRAME       \
241         SETUP_STACK_WATERMARK
242
243 #define ICALL_RETURN()  \
244         do {    \
245                 CLEAR_STACK_WATERMARK   \
246                 CLEAR_ICALL_COMMON      \
247                 CLEAR_ICALL_FRAME       \
248                 return; \
249         } while (0); } while (0)
250
251 #define ICALL_RETURN_VAL(VAL)   \
252         do {    \
253                 CLEAR_STACK_WATERMARK   \
254                 CLEAR_ICALL_COMMON      \
255                 CLEAR_ICALL_FRAME       \
256                 return VAL;     \
257         } while (0); } while (0)
258
259 #define ICALL_RETURN_OBJ(HANDLE)        \
260         do {    \
261                 CLEAR_STACK_WATERMARK   \
262                 CLEAR_ICALL_COMMON      \
263                 void* __ret = MONO_HANDLE_RAW (HANDLE); \
264                 CLEAR_ICALL_FRAME       \
265                 return __ret;   \
266         } while (0); } while (0)
267
268 /*
269 Handle macros/functions
270 */
271
272 #ifdef ENABLE_CHECKED_BUILD
273 void mono_handle_verify (MonoRawHandle handle);
274 #define HANDLE_INVARIANTS(H) mono_handle_verify((void*)(H))
275 #else
276 #define HANDLE_INVARIANTS(H) (0)
277 #endif
278
279 #define TYPED_HANDLE_PAYLOAD_NAME(TYPE) TYPE ## HandlePayload
280 #define TYPED_HANDLE_NAME(TYPE) TYPE ## Handle
281 #define TYPED_OUT_HANDLE_NAME(TYPE) TYPE ## HandleOut
282
283 #ifdef MONO_HANDLE_TRACK_OWNER
284 #define STRINGIFY_(x) #x
285 #define STRINGIFY(x) STRINGIFY_(x)
286 #define HANDLE_OWNER_STRINGIFY(file,lineno) (const char*) (file ":" STRINGIFY(lineno))
287 #endif
288
289
290 /*
291  * TYPED_HANDLE_DECL(SomeType):
292  *   Expands to a decl for handles to SomeType and to an internal payload struct.
293  *
294  * For example, TYPED_HANDLE_DECL(MonoObject) (see below) expands to:
295  *
296  * typedef struct {
297  *   MonoObject *__raw;
298  * } MonoObjectHandlePayload;
299  *
300  * typedef MonoObjectHandlePayload* MonoObjectHandle;
301  * typedef MonoObjectHandlePayload* MonoObjectHandleOut;
302  */
303 #define TYPED_HANDLE_DECL(TYPE)                                         \
304         typedef struct { TYPE *__raw; } TYPED_HANDLE_PAYLOAD_NAME (TYPE) ; \
305         typedef TYPED_HANDLE_PAYLOAD_NAME (TYPE) * TYPED_HANDLE_NAME (TYPE); \
306         typedef TYPED_HANDLE_PAYLOAD_NAME (TYPE) * TYPED_OUT_HANDLE_NAME (TYPE)
307 /*
308  * TYPED_VALUE_HANDLE_DECL(SomeType):
309  *   Expands to a decl for handles to SomeType (which is a managed valuetype (likely a struct) of some sort) and to an internal payload struct.
310  * For example TYPED_HANDLE_DECL(MonoMethodInfo) expands to:
311  *
312  * typedef struct {
313  *   MonoMethodInfo *__raw;
314  * } MonoMethodInfoHandlePayload;
315  * typedef MonoMethodInfoHandlePayload* MonoMethodInfoHandle;
316  */
317 #define TYPED_VALUE_HANDLE_DECL(TYPE) TYPED_HANDLE_DECL(TYPE)
318
319 /* Have to double expand because MONO_STRUCT_OFFSET is doing token pasting on cross-compilers. */
320 #define MONO_HANDLE_PAYLOAD_OFFSET_(PayloadType) MONO_STRUCT_OFFSET(PayloadType, __raw)
321 #define MONO_HANDLE_PAYLOAD_OFFSET(TYPE) MONO_HANDLE_PAYLOAD_OFFSET_(TYPED_HANDLE_PAYLOAD_NAME (TYPE))
322
323 #define MONO_HANDLE_INIT ((void*) mono_null_value_handle)
324 #define NULL_HANDLE mono_null_value_handle
325
326 //XXX add functions to get/set raw, set field, set field to null, set array, set array to null
327 #define MONO_HANDLE_RAW(HANDLE) (HANDLE_INVARIANTS (HANDLE), ((HANDLE)->__raw))
328 #define MONO_HANDLE_DCL(TYPE, NAME) TYPED_HANDLE_NAME(TYPE) NAME = MONO_HANDLE_NEW (TYPE, (NAME ## _raw))
329
330 #ifndef MONO_HANDLE_TRACK_OWNER
331 #define MONO_HANDLE_NEW(TYPE, VALUE) (TYPED_HANDLE_NAME(TYPE))( mono_handle_new ((MonoObject*)(VALUE)) )
332 #else
333 #define MONO_HANDLE_NEW(TYPE, VALUE) (TYPED_HANDLE_NAME(TYPE))( mono_handle_new ((MonoObject*)(VALUE), HANDLE_OWNER_STRINGIFY(__FILE__, __LINE__)))
334 #endif
335
336 #define MONO_HANDLE_CAST(TYPE, VALUE) (TYPED_HANDLE_NAME(TYPE))( VALUE )
337
338 #define MONO_HANDLE_IS_NULL(HANDLE) (MONO_HANDLE_RAW(HANDLE) == NULL)
339
340
341 /*
342 WARNING WARNING WARNING
343
344 The following functions require a particular evaluation ordering to ensure correctness.
345 We must not have exposed handles while any sort of evaluation is happening as that very evaluation might trigger
346 a safepoint and break us.
347
348 This is why we evaluate index and value before any call to MONO_HANDLE_RAW or other functions that deal with naked objects.
349 */
350 #define MONO_HANDLE_SETRAW(HANDLE, FIELD, VALUE) do {   \
351                 MonoObject *__val = (MonoObject*)(VALUE);       \
352                 MONO_OBJECT_SETREF (MONO_HANDLE_RAW (HANDLE), FIELD, __val);    \
353         } while (0)
354
355 #define MONO_HANDLE_SET(HANDLE, FIELD, VALUE) do {      \
356                 MonoObjectHandle __val = MONO_HANDLE_CAST (MonoObject, VALUE);  \
357                 MONO_OBJECT_SETREF (MONO_HANDLE_RAW (HANDLE), FIELD, MONO_HANDLE_RAW (__val));  \
358         } while (0)
359
360 /* N.B. RESULT is evaluated before HANDLE */
361 #define MONO_HANDLE_GET(RESULT, HANDLE, FIELD) do {                     \
362                 MonoObjectHandle __dest = MONO_HANDLE_CAST(MonoObject, RESULT); \
363                 mono_gc_wbarrier_generic_store (&__dest->__raw,  (MonoObject*)(MONO_HANDLE_RAW(HANDLE)->FIELD)); \
364         } while (0)
365
366 #define MONO_HANDLE_NEW_GET(TYPE,HANDLE,FIELD) (MONO_HANDLE_NEW(TYPE,MONO_HANDLE_RAW(HANDLE)->FIELD))
367
368 #define MONO_HANDLE_GETVAL(HANDLE, FIELD) (MONO_HANDLE_RAW(HANDLE)->FIELD)
369
370 /* VS doesn't support typeof :( :( :( */
371 #define MONO_HANDLE_SETVAL(HANDLE, FIELD, TYPE, VALUE) do {     \
372                 TYPE __val = (VALUE);   \
373                 MONO_HANDLE_RAW (HANDLE)->FIELD = __val;        \
374          } while (0)
375
376 #define MONO_HANDLE_ARRAY_SETREF(HANDLE, IDX, VALUE) do {       \
377                 int __idx = (IDX);      \
378                 MonoObjectHandle __val = MONO_HANDLE_CAST (MonoObject, VALUE);          \
379                 mono_array_setref_fast (MONO_HANDLE_RAW (HANDLE), __idx, MONO_HANDLE_RAW (__val));      \
380         } while (0)
381
382 #define MONO_HANDLE_ARRAY_SETVAL(HANDLE, TYPE, IDX, VALUE) do {         \
383                 int __idx = (IDX);                                      \
384                 TYPE __val = (VALUE);                   \
385                 mono_array_set (MONO_HANDLE_RAW (HANDLE), TYPE, __idx, __val); \
386         } while (0)
387
388 #define MONO_HANDLE_ARRAY_SETRAW(HANDLE, IDX, VALUE) do {       \
389                 int __idx = (IDX);      \
390                 MonoObject *__val = (MonoObject*)(VALUE);       \
391                 mono_array_setref_fast (MONO_HANDLE_RAW (HANDLE), __idx, __val); \
392         } while (0)
393
394 /* N.B. DEST is evaluated AFTER all the other arguments */
395 #define MONO_HANDLE_ARRAY_GETVAL(DEST, HANDLE, TYPE, IDX) do {          \
396                 MonoArrayHandle __arr = (HANDLE);                       \
397                 int __idx = (IDX);                                      \
398                 TYPE __result = mono_array_get (MONO_HANDLE_RAW(__arr), TYPE, __idx); \
399                 (DEST) =  __result;                                     \
400         } while (0)
401
402 #define MONO_HANDLE_ARRAY_GETREF(DEST, HANDLE, IDX) do {                \
403                 mono_handle_array_getref (MONO_HANDLE_CAST(MonoObject, (DEST)), (HANDLE), (IDX)); \
404         } while (0)
405
406 /* Handles into the interior of objects.
407  *
408  * Typically when working with value types, we pass them by reference.  In the case where the value type
409  * is a field in a managed class, the reference will be a pointer into the middle of a managed object.
410  * We need to identify such pointers in order for SGen to scan them correctly.
411  */
412
413 #ifndef MONO_HANDLE_TRACK_OWNER
414 #define MONO_HANDLE_NEW_GET_VALPTR(HANDLE,TYPE,FIELD) (TYPE_VALUE_HANDLE_NAME(TYPE))(mono_handle_new_full (&(HANDLE)->__raw->FIELD), TRUE))
415 #else
416 #define MONO_HANDLE_NEW_GET_VALPTR(HANDLE,TYPE,FIELD) (TYPE_VALUE_HANDLE_NAME(TYPE))(mono_handle_new_full (&(HANDLE)->__raw->FIELD), TRUE, HANDLE_OWNER_STRINGIFY(__FILE__, __LINE__))
417 #endif
418
419
420 #define MONO_HANDLE_ASSIGN(DESTH, SRCH)                         \
421         mono_handle_assign (MONO_HANDLE_CAST (MonoObject, (DESTH)), MONO_HANDLE_CAST(MonoObject, (SRCH)))
422
423 #define MONO_HANDLE_DOMAIN(HANDLE) (mono_object_domain (MONO_HANDLE_RAW (MONO_HANDLE_CAST (MonoObject, HANDLE))))
424
425
426 /* Baked typed handles we all want */
427 TYPED_HANDLE_DECL (MonoString);
428 TYPED_HANDLE_DECL (MonoArray);
429 TYPED_HANDLE_DECL (MonoObject);
430 TYPED_HANDLE_DECL (MonoException);
431 TYPED_HANDLE_DECL (MonoAppContext);
432
433 #define NULL_HANDLE_STRING MONO_HANDLE_CAST(MonoString, NULL_HANDLE)
434
435 /*
436 This is the constant for a handle that points nowhere.
437 Init values to it.
438 */
439 extern const MonoObjectHandle mono_null_value_handle;
440
441 static inline void
442 mono_handle_assign (MonoObjectHandleOut dest, MonoObjectHandle src)
443 {
444         mono_gc_wbarrier_generic_store (&dest->__raw, src ? MONO_HANDLE_RAW(src) : NULL);
445 }
446
447 //FIXME this should go somewhere else
448 MonoStringHandle mono_string_new_handle (MonoDomain *domain, const char *data, MonoError *error);
449 MonoArrayHandle mono_array_new_handle (MonoDomain *domain, MonoClass *eclass, uintptr_t n, MonoError *error);
450 MonoArrayHandle
451 mono_array_new_full_handle (MonoDomain *domain, MonoClass *array_class, uintptr_t *lengths, intptr_t *lower_bounds, MonoError *error);
452
453
454 uintptr_t mono_array_handle_length (MonoArrayHandle arr);
455
456 static inline void
457 mono_handle_array_getref (MonoObjectHandleOut dest, MonoArrayHandle array, uintptr_t index)
458 {
459         mono_gc_wbarrier_generic_store (&dest->__raw, mono_array_get (MONO_HANDLE_RAW (array),gpointer, index));
460 }
461
462 #define mono_handle_class(o) mono_object_class (MONO_HANDLE_RAW (o))
463
464 /* Local handles to global GC handles and back */
465
466 uint32_t
467 mono_gchandle_from_handle (MonoObjectHandle handle, mono_bool pinned);
468
469 MonoObjectHandle
470 mono_gchandle_get_target_handle (uint32_t gchandle);
471
472 void
473 mono_array_handle_memcpy_refs (MonoArrayHandle dest, uintptr_t dest_idx, MonoArrayHandle src, uintptr_t src_idx, uintptr_t len);
474
475 /* Pins the MonoArray using a gchandle and returns a pointer to the
476  * element with the given index (where each element is of the given
477  * size.  Call mono_gchandle_free to unpin.
478  */
479 gpointer
480 mono_array_handle_pin_with_size (MonoArrayHandle handle, int size, uintptr_t index, uint32_t *gchandle);
481
482 #define MONO_ARRAY_HANDLE_PIN(handle,type,index,gchandle_out) mono_array_handle_pin_with_size (MONO_HANDLE_CAST(MonoArray,(handle)), sizeof (type), (index), (gchandle_out))
483
484 void
485 mono_error_set_exception_handle (MonoError *error, MonoExceptionHandle exc);
486
487 MonoAppContextHandle
488 mono_context_get_handle (void);
489
490 void
491 mono_context_set_handle (MonoAppContextHandle new_context);
492
493
494 G_END_DECLS
495
496 #endif /* __MONO_HANDLE_H__ */