Merge pull request #4152 from BrzVlad/misc-gc-altstack
[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 static MonoObject**
76 chunk_element_objslot (HandleChunk *chunk, int idx)
77 {
78         return &chunk->objects[idx].o;
79 }
80
81 #ifdef MONO_HANDLE_TRACK_OWNER
82 #define SET_OWNER(chunk,idx) do { (chunk)->objects[(idx)].owner = owner; } while (0)
83 #else
84 #define SET_OWNER(chunk,idx) do { } while (0)
85 #endif
86
87 /* Actual handles implementation */
88 MonoRawHandle
89 #ifndef MONO_HANDLE_TRACK_OWNER
90 mono_handle_new (MonoObject *object)
91 #else
92 mono_handle_new (MonoObject *object, const char *owner)
93 #endif
94 {
95         MonoThreadInfo *info = mono_thread_info_current ();
96         HandleStack *handles = (HandleStack *)info->handle_stack;
97         HandleChunk *top = handles->top;
98
99 retry:
100         if (G_LIKELY (top->size < OBJECTS_PER_HANDLES_CHUNK)) {
101                 int idx = top->size;
102                 MonoObject** objslot = chunk_element_objslot (top, idx);
103                 /* can be interrupted anywhere here, so:
104                  * 1. make sure the new slot is null
105                  * 2. make the new slot scannable (increment size)
106                  * 3. put a valid object in there
107                  *
108                  * (have to do 1 then 3 so that if we're interrupted
109                  * between 1 and 2, the object is still live)
110                  */
111                 *objslot = NULL;
112                 mono_memory_write_barrier ();
113                 top->size++;
114                 mono_memory_write_barrier ();
115                 *objslot = object;
116                 SET_OWNER (top,idx);
117                 return objslot;
118         }
119         if (G_LIKELY (top->next)) {
120                 top->next->size = 0;
121                 /* make sure size == 0 is visible to a GC thread before it sees the new top */
122                 mono_memory_write_barrier ();
123                 top = top->next;
124                 handles->top = top;
125                 goto retry;
126         }
127         HandleChunk *new_chunk = g_new (HandleChunk, 1);
128         new_chunk->size = 0;
129         new_chunk->prev = top;
130         new_chunk->next = NULL;
131         /* make sure size == 0 before new chunk is visible */
132         mono_memory_write_barrier ();
133         top->next = new_chunk;
134         handles->top = new_chunk;
135         goto retry;
136 }
137
138
139
140 HandleStack*
141 mono_handle_stack_alloc (void)
142 {
143         HandleStack *stack = g_new (HandleStack, 1);
144         HandleChunk *chunk = g_new (HandleChunk, 1);
145
146         chunk->size = 0;
147         chunk->prev = chunk->next = NULL;
148         mono_memory_write_barrier ();
149         stack->top = stack->bottom = chunk;
150         return stack;
151 }
152
153 void
154 mono_handle_stack_free (HandleStack *stack)
155 {
156         if (!stack)
157                 return;
158         HandleChunk *c = stack->bottom;
159         stack->top = stack->bottom = NULL;
160         mono_memory_write_barrier ();
161         while (c) {
162                 HandleChunk *next = c->next;
163                 g_free (c);
164                 c = next;
165         }
166         g_free (c);
167         g_free (stack);
168 }
169
170 void
171 mono_handle_stack_scan (HandleStack *stack, GcScanFunc func, gpointer gc_data)
172 {
173         /* if we're running, we know the world is stopped.
174          */
175         HandleChunk *cur = stack->bottom;
176         HandleChunk *last = stack->top;
177
178         if (!cur)
179                 return;
180
181         while (cur) {
182                 int i;
183                 for (i = 0; i < cur->size; ++i) {
184                         MonoObject **obj_slot = chunk_element_objslot (cur, i);
185                         if (*obj_slot != NULL)
186                                 func ((gpointer*)obj_slot, gc_data);
187                 }
188                 if (cur == last)
189                         break;
190                 cur = cur->next;
191         }
192 }
193
194 void
195 mono_stack_mark_record_size (MonoThreadInfo *info, HandleStackMark *stackmark, const char *func_name)
196 {
197         HandleStack *handles = (HandleStack *)info->handle_stack;
198         HandleChunk *cur = stackmark->chunk;
199         int size = -stackmark->size; //discard the starting point of the stack
200         while (cur) {
201                 size += cur->size;
202                 if (cur == handles->top)
203                         break;
204                 cur = cur->next;
205         }
206
207         if (size > THIS_IS_AN_OK_NUMBER_OF_HANDLES)
208                 g_warning ("%s USED %d handles\n", func_name, size);
209 }
210
211 /*
212  * Pop the stack until @stackmark and make @value the top value.
213  *
214  * @return the new handle for what @value points to 
215  */
216 MonoRawHandle
217 mono_stack_mark_pop_value (MonoThreadInfo *info, HandleStackMark *stackmark, MonoRawHandle value)
218 {
219         MonoObject *obj = value ? *((MonoObject**)value) : NULL;
220         mono_stack_mark_pop (info, stackmark);
221 #ifndef MONO_HANDLE_TRACK_OWNER
222         return mono_handle_new (obj);
223 #else
224         return mono_handle_new (obj, "<mono_stack_mark_pop_value>");
225 #endif
226 }
227
228 /* Temporary place for some of the handle enabled wrapper functions*/
229
230 MonoStringHandle
231 mono_string_new_handle (MonoDomain *domain, const char *data, MonoError *error)
232 {
233         return MONO_HANDLE_NEW (MonoString, mono_string_new_checked (domain, data, error));
234 }
235
236 MonoArrayHandle
237 mono_array_new_handle (MonoDomain *domain, MonoClass *eclass, uintptr_t n, MonoError *error)
238 {
239         return MONO_HANDLE_NEW (MonoArray, mono_array_new_checked (domain, eclass, n, error));
240 }
241
242 #ifdef ENABLE_CHECKED_BUILD
243 /* Checked build helpers */
244 void
245 mono_handle_verify (MonoRawHandle raw_handle)
246 {
247         
248 }
249 #endif
250
251 uintptr_t
252 mono_array_handle_length (MonoArrayHandle arr)
253 {
254         MONO_REQ_GC_UNSAFE_MODE;
255
256         return MONO_HANDLE_RAW (arr)->max_length;
257 }
258
259 uint32_t
260 mono_gchandle_from_handle (MonoObjectHandle handle, mono_bool pinned)
261 {
262         return mono_gchandle_new (MONO_HANDLE_RAW(handle), pinned);
263 }
264
265 MonoObjectHandle
266 mono_gchandle_get_target_handle (uint32_t gchandle)
267 {
268         return MONO_HANDLE_NEW (MonoObject, mono_gchandle_get_target);
269 }
270
271 gpointer
272 mono_array_handle_pin_with_size (MonoArrayHandle handle, int size, uintptr_t idx, uint32_t *gchandle)
273 {
274         g_assert (gchandle != NULL);
275         *gchandle = mono_gchandle_from_handle (MONO_HANDLE_CAST(MonoObject,handle), TRUE);
276         MonoArray *raw = MONO_HANDLE_RAW (handle);
277         return mono_array_addr_with_size (raw, size, idx);
278 }
279
280 void
281 mono_array_handle_memcpy_refs (MonoArrayHandle dest, uintptr_t dest_idx, MonoArrayHandle src, uintptr_t src_idx, uintptr_t len)
282 {
283         mono_array_memcpy_refs (MONO_HANDLE_RAW (dest), dest_idx, MONO_HANDLE_RAW (src), src_idx, len);
284 }
285
286 gboolean
287 mono_handle_stack_is_empty (HandleStack *stack)
288 {
289         return (stack->top == stack->bottom && stack->top->size == 0);
290 }