[io-layer] Extract error (#4279)
[mono.git] / mono / utils / mono-codeman.c
1 #include "config.h"
2
3 #ifdef HAVE_UNISTD_H
4 #include <unistd.h>
5 #endif
6 #include <stdlib.h>
7 #include <string.h>
8 #include <assert.h>
9 #include <glib.h>
10
11 /* For dlmalloc.h */
12 #define USE_DL_PREFIX 1
13
14 #include "mono-codeman.h"
15 #include "mono-mmap.h"
16 #include "mono-counters.h"
17 #include "dlmalloc.h"
18 #include <mono/metadata/profiler-private.h>
19 #ifdef HAVE_VALGRIND_MEMCHECK_H
20 #include <valgrind/memcheck.h>
21 #endif
22
23 #include <mono/utils/mono-os-mutex.h>
24
25
26 static uintptr_t code_memory_used = 0;
27 static size_t dynamic_code_alloc_count;
28 static size_t dynamic_code_bytes_count;
29 static size_t dynamic_code_frees_count;
30 static MonoCodeManagerCallbacks code_manager_callbacks;
31
32 /*
33  * AMD64 processors maintain icache coherency only for pages which are 
34  * marked executable. Also, windows DEP requires us to obtain executable memory from
35  * malloc when using dynamic code managers. The system malloc can't do this so we use a 
36  * slighly modified version of Doug Lea's Malloc package for this purpose:
37  * http://g.oswego.edu/dl/html/malloc.html
38  */
39
40 #define MIN_PAGES 16
41
42 #if defined(__ia64__) || defined(__x86_64__) || defined (_WIN64)
43 /*
44  * We require 16 byte alignment on amd64 so the fp literals embedded in the code are 
45  * properly aligned for SSE2.
46  */
47 #define MIN_ALIGN 16
48 #else
49 #define MIN_ALIGN 8
50 #endif
51
52 /* if a chunk has less than this amount of free space it's considered full */
53 #define MAX_WASTAGE 32
54 #define MIN_BSIZE 32
55
56 #ifdef __x86_64__
57 #define ARCH_MAP_FLAGS MONO_MMAP_32BIT
58 #else
59 #define ARCH_MAP_FLAGS 0
60 #endif
61
62 #define MONO_PROT_RWX (MONO_MMAP_READ|MONO_MMAP_WRITE|MONO_MMAP_EXEC)
63
64 typedef struct _CodeChunck CodeChunk;
65
66 enum {
67         CODE_FLAG_MMAP,
68         CODE_FLAG_MALLOC
69 };
70
71 struct _CodeChunck {
72         char *data;
73         int pos;
74         int size;
75         CodeChunk *next;
76         unsigned int flags: 8;
77         /* this number of bytes is available to resolve addresses far in memory */
78         unsigned int bsize: 24;
79 };
80
81 struct _MonoCodeManager {
82         int dynamic;
83         int read_only;
84         CodeChunk *current;
85         CodeChunk *full;
86         CodeChunk *last;
87 };
88
89 #define ALIGN_INT(val,alignment) (((val) + (alignment - 1)) & ~(alignment - 1))
90
91 #define VALLOC_FREELIST_SIZE 16
92
93 static mono_mutex_t valloc_mutex;
94 static GHashTable *valloc_freelists;
95
96 static void*
97 codechunk_valloc (void *preferred, guint32 size)
98 {
99         void *ptr;
100         GSList *freelist;
101
102         if (!valloc_freelists) {
103                 mono_os_mutex_init_recursive (&valloc_mutex);
104                 valloc_freelists = g_hash_table_new (NULL, NULL);
105         }
106
107         /*
108          * Keep a small freelist of memory blocks to decrease pressure on the kernel memory subsystem to avoid #3321.
109          */
110         mono_os_mutex_lock (&valloc_mutex);
111         freelist = (GSList *) g_hash_table_lookup (valloc_freelists, GUINT_TO_POINTER (size));
112         if (freelist) {
113                 ptr = freelist->data;
114                 memset (ptr, 0, size);
115                 freelist = g_slist_delete_link (freelist, freelist);
116                 g_hash_table_insert (valloc_freelists, GUINT_TO_POINTER (size), freelist);
117         } else {
118                 ptr = mono_valloc (preferred, size, MONO_PROT_RWX | ARCH_MAP_FLAGS, MONO_MEM_ACCOUNT_CODE);
119                 if (!ptr && preferred)
120                         ptr = mono_valloc (NULL, size, MONO_PROT_RWX | ARCH_MAP_FLAGS, MONO_MEM_ACCOUNT_CODE);
121         }
122         mono_os_mutex_unlock (&valloc_mutex);
123         return ptr;
124 }
125
126 static void
127 codechunk_vfree (void *ptr, guint32 size)
128 {
129         GSList *freelist;
130
131         mono_os_mutex_lock (&valloc_mutex);
132         freelist = (GSList *) g_hash_table_lookup (valloc_freelists, GUINT_TO_POINTER (size));
133         if (!freelist || g_slist_length (freelist) < VALLOC_FREELIST_SIZE) {
134                 freelist = g_slist_prepend (freelist, ptr);
135                 g_hash_table_insert (valloc_freelists, GUINT_TO_POINTER (size), freelist);
136         } else {
137                 mono_vfree (ptr, size, MONO_MEM_ACCOUNT_CODE);
138         }
139         mono_os_mutex_unlock (&valloc_mutex);
140 }               
141
142 static void
143 codechunk_cleanup (void)
144 {
145         GHashTableIter iter;
146         gpointer key, value;
147
148         if (!valloc_freelists)
149                 return;
150         g_hash_table_iter_init (&iter, valloc_freelists);
151         while (g_hash_table_iter_next (&iter, &key, &value)) {
152                 GSList *freelist = (GSList *) value;
153                 GSList *l;
154
155                 for (l = freelist; l; l = l->next) {
156                         mono_vfree (l->data, GPOINTER_TO_UINT (key), MONO_MEM_ACCOUNT_CODE);
157                 }
158                 g_slist_free (freelist);
159         }
160         g_hash_table_destroy (valloc_freelists);
161 }
162
163 void
164 mono_code_manager_init (void)
165 {
166         mono_counters_register ("Dynamic code allocs", MONO_COUNTER_JIT | MONO_COUNTER_ULONG, &dynamic_code_alloc_count);
167         mono_counters_register ("Dynamic code bytes", MONO_COUNTER_JIT | MONO_COUNTER_ULONG, &dynamic_code_bytes_count);
168         mono_counters_register ("Dynamic code frees", MONO_COUNTER_JIT | MONO_COUNTER_ULONG, &dynamic_code_frees_count);
169 }
170
171 void
172 mono_code_manager_cleanup (void)
173 {
174         codechunk_cleanup ();
175 }
176
177 void
178 mono_code_manager_install_callbacks (MonoCodeManagerCallbacks* callbacks)
179 {
180         code_manager_callbacks = *callbacks;
181 }
182
183 /**
184  * mono_code_manager_new:
185  *
186  * Creates a new code manager. A code manager can be used to allocate memory
187  * suitable for storing native code that can be later executed.
188  * A code manager allocates memory from the operating system in large chunks
189  * (typically 64KB in size) so that many methods can be allocated inside them
190  * close together, improving cache locality.
191  *
192  * Returns: the new code manager
193  */
194 MonoCodeManager* 
195 mono_code_manager_new (void)
196 {
197         return (MonoCodeManager *) g_malloc0 (sizeof (MonoCodeManager));
198 }
199
200 /**
201  * mono_code_manager_new_dynamic:
202  *
203  * Creates a new code manager suitable for holding native code that can be
204  * used for single or small methods that need to be deallocated independently
205  * of other native code.
206  *
207  * Returns: the new code manager
208  */
209 MonoCodeManager* 
210 mono_code_manager_new_dynamic (void)
211 {
212         MonoCodeManager *cman = mono_code_manager_new ();
213         cman->dynamic = 1;
214         return cman;
215 }
216
217
218 static void
219 free_chunklist (CodeChunk *chunk)
220 {
221         CodeChunk *dead;
222         
223 #if defined(HAVE_VALGRIND_MEMCHECK_H) && defined (VALGRIND_JIT_UNREGISTER_MAP)
224         int valgrind_unregister = 0;
225         if (RUNNING_ON_VALGRIND)
226                 valgrind_unregister = 1;
227 #define valgrind_unregister(x) do { if (valgrind_unregister) { VALGRIND_JIT_UNREGISTER_MAP(NULL,x); } } while (0) 
228 #else
229 #define valgrind_unregister(x)
230 #endif
231
232         for (; chunk; ) {
233                 dead = chunk;
234                 mono_profiler_code_chunk_destroy ((gpointer) dead->data);
235                 if (code_manager_callbacks.chunk_destroy)
236                         code_manager_callbacks.chunk_destroy ((gpointer)dead->data);
237                 chunk = chunk->next;
238                 if (dead->flags == CODE_FLAG_MMAP) {
239                         codechunk_vfree (dead->data, dead->size);
240                         /* valgrind_unregister(dead->data); */
241                 } else if (dead->flags == CODE_FLAG_MALLOC) {
242                         dlfree (dead->data);
243                 }
244                 code_memory_used -= dead->size;
245                 g_free (dead);
246         }
247 }
248
249 /**
250  * mono_code_manager_destroy:
251  * @cman: a code manager
252  *
253  * Free all the memory associated with the code manager @cman.
254  */
255 void
256 mono_code_manager_destroy (MonoCodeManager *cman)
257 {
258         free_chunklist (cman->full);
259         free_chunklist (cman->current);
260         g_free (cman);
261 }
262
263 /**
264  * mono_code_manager_invalidate:
265  * @cman: a code manager
266  *
267  * Fill all the memory with an invalid native code value
268  * so that any attempt to execute code allocated in the code
269  * manager @cman will fail. This is used for debugging purposes.
270  */
271 void             
272 mono_code_manager_invalidate (MonoCodeManager *cman)
273 {
274         CodeChunk *chunk;
275
276 #if defined(__i386__) || defined(__x86_64__)
277         int fill_value = 0xcc; /* x86 break */
278 #else
279         int fill_value = 0x2a;
280 #endif
281
282         for (chunk = cman->current; chunk; chunk = chunk->next)
283                 memset (chunk->data, fill_value, chunk->size);
284         for (chunk = cman->full; chunk; chunk = chunk->next)
285                 memset (chunk->data, fill_value, chunk->size);
286 }
287
288 /**
289  * mono_code_manager_set_read_only:
290  * @cman: a code manager
291  *
292  * Make the code manager read only, so further allocation requests cause an assert.
293  */
294 void             
295 mono_code_manager_set_read_only (MonoCodeManager *cman)
296 {
297         cman->read_only = TRUE;
298 }
299
300 /**
301  * mono_code_manager_foreach:
302  * @cman: a code manager
303  * @func: a callback function pointer
304  * @user_data: additional data to pass to @func
305  *
306  * Invokes the callback @func for each different chunk of memory allocated
307  * in the code manager @cman.
308  */
309 void
310 mono_code_manager_foreach (MonoCodeManager *cman, MonoCodeManagerFunc func, void *user_data)
311 {
312         CodeChunk *chunk;
313         for (chunk = cman->current; chunk; chunk = chunk->next) {
314                 if (func (chunk->data, chunk->size, chunk->bsize, user_data))
315                         return;
316         }
317         for (chunk = cman->full; chunk; chunk = chunk->next) {
318                 if (func (chunk->data, chunk->size, chunk->bsize, user_data))
319                         return;
320         }
321 }
322
323 /* BIND_ROOM is the divisor for the chunck of code size dedicated
324  * to binding branches (branches not reachable with the immediate displacement)
325  * bind_size = size/BIND_ROOM;
326  * we should reduce it and make MIN_PAGES bigger for such systems
327  */
328 #if defined(__ppc__) || defined(__powerpc__)
329 #define BIND_ROOM 4
330 #endif
331 #if defined(TARGET_ARM64)
332 #define BIND_ROOM 4
333 #endif
334
335 static CodeChunk*
336 new_codechunk (CodeChunk *last, int dynamic, int size)
337 {
338         int minsize, flags = CODE_FLAG_MMAP;
339         int chunk_size, bsize = 0;
340         int pagesize, valloc_granule;
341         CodeChunk *chunk;
342         void *ptr;
343
344 #ifdef FORCE_MALLOC
345         flags = CODE_FLAG_MALLOC;
346 #endif
347
348         pagesize = mono_pagesize ();
349         valloc_granule = mono_valloc_granule ();
350
351         if (dynamic) {
352                 chunk_size = size;
353                 flags = CODE_FLAG_MALLOC;
354         } else {
355                 minsize = MAX (pagesize * MIN_PAGES, valloc_granule);
356                 if (size < minsize)
357                         chunk_size = minsize;
358                 else {
359                         /* Allocate MIN_ALIGN-1 more than we need so we can still */
360                         /* guarantee MIN_ALIGN alignment for individual allocs    */
361                         /* from mono_code_manager_reserve_align.                  */
362                         size += MIN_ALIGN - 1;
363                         size &= ~(MIN_ALIGN - 1);
364                         chunk_size = size;
365                         chunk_size += valloc_granule - 1;
366                         chunk_size &= ~ (valloc_granule - 1);
367                 }
368         }
369 #ifdef BIND_ROOM
370         if (dynamic)
371                 /* Reserve more space since there are no other chunks we might use if this one gets full */
372                 bsize = (chunk_size * 2) / BIND_ROOM;
373         else
374                 bsize = chunk_size / BIND_ROOM;
375         if (bsize < MIN_BSIZE)
376                 bsize = MIN_BSIZE;
377         bsize += MIN_ALIGN -1;
378         bsize &= ~ (MIN_ALIGN - 1);
379         if (chunk_size - size < bsize) {
380                 chunk_size = size + bsize;
381                 if (!dynamic) {
382                         chunk_size += valloc_granule - 1;
383                         chunk_size &= ~ (valloc_granule - 1);
384                 }
385         }
386 #endif
387
388         if (flags == CODE_FLAG_MALLOC) {
389                 ptr = dlmemalign (MIN_ALIGN, chunk_size + MIN_ALIGN - 1);
390                 if (!ptr)
391                         return NULL;
392         } else {
393                 /* Try to allocate code chunks next to each other to help the VM */
394                 ptr = NULL;
395                 if (last)
396                         ptr = codechunk_valloc ((guint8*)last->data + last->size, chunk_size);
397                 if (!ptr)
398                         ptr = codechunk_valloc (NULL, chunk_size);
399                 if (!ptr)
400                         return NULL;
401         }
402
403         if (flags == CODE_FLAG_MALLOC) {
404 #ifdef BIND_ROOM
405                 /* Make sure the thunks area is zeroed */
406                 memset (ptr, 0, bsize);
407 #endif
408         }
409
410         chunk = (CodeChunk *) g_malloc (sizeof (CodeChunk));
411         if (!chunk) {
412                 if (flags == CODE_FLAG_MALLOC)
413                         dlfree (ptr);
414                 else
415                         mono_vfree (ptr, chunk_size, MONO_MEM_ACCOUNT_CODE);
416                 return NULL;
417         }
418         chunk->next = NULL;
419         chunk->size = chunk_size;
420         chunk->data = (char *) ptr;
421         chunk->flags = flags;
422         chunk->pos = bsize;
423         chunk->bsize = bsize;
424         if (code_manager_callbacks.chunk_new)
425                 code_manager_callbacks.chunk_new ((gpointer)chunk->data, chunk->size);
426         mono_profiler_code_chunk_new((gpointer) chunk->data, chunk->size);
427
428         code_memory_used += chunk_size;
429         mono_runtime_resource_check_limit (MONO_RESOURCE_JIT_CODE, code_memory_used);
430         /*printf ("code chunk at: %p\n", ptr);*/
431         return chunk;
432 }
433
434 /**
435  * mono_code_manager_reserve:
436  * @cman: a code manager
437  * @size: size of memory to allocate
438  * @alignment: power of two alignment value
439  *
440  * Allocates at least @size bytes of memory inside the code manager @cman.
441  *
442  * Returns: the pointer to the allocated memory or #NULL on failure
443  */
444 void*
445 mono_code_manager_reserve_align (MonoCodeManager *cman, int size, int alignment)
446 {
447         CodeChunk *chunk, *prev;
448         void *ptr;
449         guint32 align_mask = alignment - 1;
450
451         g_assert (!cman->read_only);
452
453         /* eventually allow bigger alignments, but we need to fix the dynamic alloc code to
454          * handle this before
455          */
456         g_assert (alignment <= MIN_ALIGN);
457
458         if (cman->dynamic) {
459                 ++dynamic_code_alloc_count;
460                 dynamic_code_bytes_count += size;
461         }
462
463         if (!cman->current) {
464                 cman->current = new_codechunk (cman->last, cman->dynamic, size);
465                 if (!cman->current)
466                         return NULL;
467                 cman->last = cman->current;
468         }
469
470         for (chunk = cman->current; chunk; chunk = chunk->next) {
471                 if (ALIGN_INT (chunk->pos, alignment) + size <= chunk->size) {
472                         chunk->pos = ALIGN_INT (chunk->pos, alignment);
473                         /* Align the chunk->data we add to chunk->pos */
474                         /* or we can't guarantee proper alignment     */
475                         ptr = (void*)((((uintptr_t)chunk->data + align_mask) & ~(uintptr_t)align_mask) + chunk->pos);
476                         chunk->pos = ((char*)ptr - chunk->data) + size;
477                         return ptr;
478                 }
479         }
480         /* 
481          * no room found, move one filled chunk to cman->full 
482          * to keep cman->current from growing too much
483          */
484         prev = NULL;
485         for (chunk = cman->current; chunk; prev = chunk, chunk = chunk->next) {
486                 if (chunk->pos + MIN_ALIGN * 4 <= chunk->size)
487                         continue;
488                 if (prev) {
489                         prev->next = chunk->next;
490                 } else {
491                         cman->current = chunk->next;
492                 }
493                 chunk->next = cman->full;
494                 cman->full = chunk;
495                 break;
496         }
497         chunk = new_codechunk (cman->last, cman->dynamic, size);
498         if (!chunk)
499                 return NULL;
500         chunk->next = cman->current;
501         cman->current = chunk;
502         cman->last = cman->current;
503         chunk->pos = ALIGN_INT (chunk->pos, alignment);
504         /* Align the chunk->data we add to chunk->pos */
505         /* or we can't guarantee proper alignment     */
506         ptr = (void*)((((uintptr_t)chunk->data + align_mask) & ~(uintptr_t)align_mask) + chunk->pos);
507         chunk->pos = ((char*)ptr - chunk->data) + size;
508         return ptr;
509 }
510
511 /**
512  * mono_code_manager_reserve:
513  * @cman: a code manager
514  * @size: size of memory to allocate
515  *
516  * Allocates at least @size bytes of memory inside the code manager @cman.
517  *
518  * Returns: the pointer to the allocated memory or #NULL on failure
519  */
520 void*
521 mono_code_manager_reserve (MonoCodeManager *cman, int size)
522 {
523         return mono_code_manager_reserve_align (cman, size, MIN_ALIGN);
524 }
525
526 /**
527  * mono_code_manager_commit:
528  * @cman: a code manager
529  * @data: the pointer returned by mono_code_manager_reserve ()
530  * @size: the size requested in the call to mono_code_manager_reserve ()
531  * @newsize: the new size to reserve
532  *
533  * If we reserved too much room for a method and we didn't allocate
534  * already from the code manager, we can get back the excess allocation
535  * for later use in the code manager.
536  */
537 void
538 mono_code_manager_commit (MonoCodeManager *cman, void *data, int size, int newsize)
539 {
540         g_assert (newsize <= size);
541
542         if (cman->current && (size != newsize) && (data == cman->current->data + cman->current->pos - size)) {
543                 cman->current->pos -= size - newsize;
544         }
545 }
546
547 /**
548  * mono_code_manager_size:
549  * @cman: a code manager
550  * @used_size: pointer to an integer for the result
551  *
552  * This function can be used to get statistics about a code manager:
553  * the integer pointed to by @used_size will contain how much
554  * memory is actually used inside the code managed @cman.
555  *
556  * Returns: the amount of memory allocated in @cman
557  */
558 int
559 mono_code_manager_size (MonoCodeManager *cman, int *used_size)
560 {
561         CodeChunk *chunk;
562         guint32 size = 0;
563         guint32 used = 0;
564         for (chunk = cman->current; chunk; chunk = chunk->next) {
565                 size += chunk->size;
566                 used += chunk->pos;
567         }
568         for (chunk = cman->full; chunk; chunk = chunk->next) {
569                 size += chunk->size;
570                 used += chunk->pos;
571         }
572         if (used_size)
573                 *used_size = used;
574         return size;
575 }