NaCl runtime fixes
[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/class-internals.h>
19 #include <mono/metadata/profiler-private.h>
20 #ifdef HAVE_VALGRIND_MEMCHECK_H
21 #include <valgrind/memcheck.h>
22 #endif
23
24 #if defined(__native_client_codegen__) && defined(__native_client__)
25 #include <malloc.h>
26 #include <nacl/nacl_dyncode.h>
27 #endif
28
29 static uintptr_t code_memory_used = 0;
30
31 /*
32  * AMD64 processors maintain icache coherency only for pages which are 
33  * marked executable. Also, windows DEP requires us to obtain executable memory from
34  * malloc when using dynamic code managers. The system malloc can't do this so we use a 
35  * slighly modified version of Doug Lea's Malloc package for this purpose:
36  * http://g.oswego.edu/dl/html/malloc.html
37  */
38
39 #define MIN_PAGES 16
40
41 #if defined(__ia64__) || defined(__x86_64__)
42 /*
43  * We require 16 byte alignment on amd64 so the fp literals embedded in the code are 
44  * properly aligned for SSE2.
45  */
46 #define MIN_ALIGN 16
47 #else
48 #define MIN_ALIGN 8
49 #endif
50 #ifdef __native_client_codegen__
51 /* For Google Native Client, all targets of indirect control flow need to    */
52 /* be aligned to a 32-byte boundary. MIN_ALIGN was updated to 32 to force    */
53 /* alignment for calls from tramp-x86.c to mono_global_codeman_reserve()     */
54 /* and mono_domain_code_reserve().                                           */
55 #undef MIN_ALIGN
56 #define MIN_ALIGN 32
57 #endif
58
59 /* if a chunk has less than this amount of free space it's considered full */
60 #define MAX_WASTAGE 32
61 #define MIN_BSIZE 32
62
63 #ifdef __x86_64__
64 #define ARCH_MAP_FLAGS MONO_MMAP_32BIT
65 #else
66 #define ARCH_MAP_FLAGS 0
67 #endif
68
69 #define MONO_PROT_RWX (MONO_MMAP_READ|MONO_MMAP_WRITE|MONO_MMAP_EXEC)
70
71 typedef struct _CodeChunck CodeChunk;
72
73 enum {
74         CODE_FLAG_MMAP,
75         CODE_FLAG_MALLOC
76 };
77
78 struct _CodeChunck {
79         char *data;
80         int pos;
81         int size;
82         CodeChunk *next;
83         unsigned int flags: 8;
84         /* this number of bytes is available to resolve addresses far in memory */
85         unsigned int bsize: 24;
86 };
87
88 struct _MonoCodeManager {
89         int dynamic;
90         int read_only;
91         CodeChunk *current;
92         CodeChunk *full;
93 #if defined(__native_client_codegen__) && defined(__native_client__)
94         GHashTable *hash;
95 #endif
96 };
97
98 #define ALIGN_INT(val,alignment) (((val) + (alignment - 1)) & ~(alignment - 1))
99
100 #if defined(__native_client_codegen__) && defined(__native_client__)
101 /* End of text segment, set by linker. 
102  * Dynamic text starts on the next allocated page.
103  */
104 extern char etext[];
105 char *next_dynamic_code_addr = NULL;
106
107 /*
108  * This routine gets the next available bundle aligned
109  * pointer in the dynamic code section.  It does not check
110  * for the section end, this error will be caught in the
111  * service runtime.
112  */
113 void*
114 allocate_code(intptr_t increment)
115 {
116         char *addr;
117         if (increment < 0) return NULL;
118         increment = increment & kNaClBundleMask ? (increment & ~kNaClBundleMask) + kNaClBundleSize : increment;
119         addr = next_dynamic_code_addr;
120         next_dynamic_code_addr += increment;
121         return addr;
122 }
123
124 int
125 nacl_is_code_address (void *target)
126 {
127         return (char *)target < next_dynamic_code_addr;
128 }
129
130 const int kMaxPatchDepth = 32;
131 __thread unsigned char **patch_source_base = NULL;
132 __thread unsigned char **patch_dest_base = NULL;
133 __thread int *patch_alloc_size = NULL;
134 __thread int patch_current_depth = -1;
135 __thread int allow_target_modification = 1;
136
137 void
138 nacl_allow_target_modification (int val)
139 {
140         allow_target_modification = val;
141 }
142
143 static void
144 nacl_jit_check_init ()
145 {
146         if (patch_source_base == NULL) {
147                 patch_source_base = g_malloc (kMaxPatchDepth * sizeof(unsigned char *));
148                 patch_dest_base = g_malloc (kMaxPatchDepth * sizeof(unsigned char *));
149                 patch_alloc_size = g_malloc (kMaxPatchDepth * sizeof(int));
150         }
151 }
152
153
154 /* Given a patch target, modify the target such that patching will work when
155  * the code is copied to the data section.
156  */
157 void*
158 nacl_modify_patch_target (unsigned char *target)
159 {
160         /* This seems like a bit of an ugly way to do this but the advantage
161          * is we don't have to worry about all the conditions in
162          * mono_resolve_patch_target, and it can be used by all the bare uses
163          * of <arch>_patch.
164          */
165         unsigned char *sb;
166         unsigned char *db;
167
168         if (!allow_target_modification) return target;
169
170         nacl_jit_check_init ();
171         sb = patch_source_base[patch_current_depth];
172         db = patch_dest_base[patch_current_depth];
173
174         if (target >= sb && (target < sb + patch_alloc_size[patch_current_depth])) {
175                 /* Do nothing.  target is in the section being generated.
176                  * no need to modify, the disp will be the same either way.
177                  */
178         } else {
179                 int target_offset = target - db;
180                 target = sb + target_offset;
181         }
182         return target;
183 }
184
185 void*
186 nacl_inverse_modify_patch_target (unsigned char *target)
187 {
188         unsigned char *sb;
189         unsigned char *db;
190         int target_offset;
191
192         if (!allow_target_modification) return target;
193
194         nacl_jit_check_init ();
195         sb = patch_source_base[patch_current_depth];
196         db = patch_dest_base[patch_current_depth];
197
198         target_offset = target - sb;
199         target = db + target_offset;
200         return target;
201 }
202
203
204 #endif /* __native_client_codegen && __native_client__ */
205
206 /**
207  * mono_code_manager_new:
208  *
209  * Creates a new code manager. A code manager can be used to allocate memory
210  * suitable for storing native code that can be later executed.
211  * A code manager allocates memory from the operating system in large chunks
212  * (typically 64KB in size) so that many methods can be allocated inside them
213  * close together, improving cache locality.
214  *
215  * Returns: the new code manager
216  */
217 MonoCodeManager* 
218 mono_code_manager_new (void)
219 {
220         MonoCodeManager *cman = malloc (sizeof (MonoCodeManager));
221         if (!cman)
222                 return NULL;
223         cman->current = NULL;
224         cman->full = NULL;
225         cman->dynamic = 0;
226         cman->read_only = 0;
227 #if defined(__native_client_codegen__) && defined(__native_client__)
228         if (next_dynamic_code_addr == NULL) {
229                 const guint kPageMask = 0xFFFF; /* 64K pages */
230                 next_dynamic_code_addr = (uintptr_t)(etext + kPageMask) & ~kPageMask;
231 #if defined (__GLIBC__)
232                 /* TODO: For now, just jump 64MB ahead to avoid dynamic libraries. */
233                 next_dynamic_code_addr += (uintptr_t)0x4000000;
234 #else
235                 /* Workaround bug in service runtime, unable to allocate */
236                 /* from the first page in the dynamic code section.    */
237                 next_dynamic_code_addr += (uintptr_t)0x10000;
238 #endif
239         }
240         cman->hash =  g_hash_table_new (NULL, NULL);
241         if (patch_source_base == NULL) {
242                 patch_source_base = g_malloc (kMaxPatchDepth * sizeof(unsigned char *));
243                 patch_dest_base = g_malloc (kMaxPatchDepth * sizeof(unsigned char *));
244                 patch_alloc_size = g_malloc (kMaxPatchDepth * sizeof(int));
245         }
246 #endif
247         return cman;
248 }
249
250 /**
251  * mono_code_manager_new_dynamic:
252  *
253  * Creates a new code manager suitable for holding native code that can be
254  * used for single or small methods that need to be deallocated independently
255  * of other native code.
256  *
257  * Returns: the new code manager
258  */
259 MonoCodeManager* 
260 mono_code_manager_new_dynamic (void)
261 {
262         MonoCodeManager *cman = mono_code_manager_new ();
263         cman->dynamic = 1;
264         return cman;
265 }
266
267
268 static void
269 free_chunklist (CodeChunk *chunk)
270 {
271         CodeChunk *dead;
272         
273 #if defined(HAVE_VALGRIND_MEMCHECK_H) && defined (VALGRIND_JIT_UNREGISTER_MAP)
274         int valgrind_unregister = 0;
275         if (RUNNING_ON_VALGRIND)
276                 valgrind_unregister = 1;
277 #define valgrind_unregister(x) do { if (valgrind_unregister) { VALGRIND_JIT_UNREGISTER_MAP(NULL,x); } } while (0) 
278 #else
279 #define valgrind_unregister(x)
280 #endif
281
282         for (; chunk; ) {
283                 dead = chunk;
284                 mono_profiler_code_chunk_destroy ((gpointer) dead->data);
285                 chunk = chunk->next;
286                 if (dead->flags == CODE_FLAG_MMAP) {
287                         mono_vfree (dead->data, dead->size);
288                         /* valgrind_unregister(dead->data); */
289                 } else if (dead->flags == CODE_FLAG_MALLOC) {
290                         dlfree (dead->data);
291                 }
292                 code_memory_used -= dead->size;
293                 free (dead);
294         }
295 }
296
297 /**
298  * mono_code_manager_destroy:
299  * @cman: a code manager
300  *
301  * Free all the memory associated with the code manager @cman.
302  */
303 void
304 mono_code_manager_destroy (MonoCodeManager *cman)
305 {
306         free_chunklist (cman->full);
307         free_chunklist (cman->current);
308         free (cman);
309 }
310
311 /**
312  * mono_code_manager_invalidate:
313  * @cman: a code manager
314  *
315  * Fill all the memory with an invalid native code value
316  * so that any attempt to execute code allocated in the code
317  * manager @cman will fail. This is used for debugging purposes.
318  */
319 void             
320 mono_code_manager_invalidate (MonoCodeManager *cman)
321 {
322         CodeChunk *chunk;
323
324 #if defined(__i386__) || defined(__x86_64__)
325         int fill_value = 0xcc; /* x86 break */
326 #else
327         int fill_value = 0x2a;
328 #endif
329
330         for (chunk = cman->current; chunk; chunk = chunk->next)
331                 memset (chunk->data, fill_value, chunk->size);
332         for (chunk = cman->full; chunk; chunk = chunk->next)
333                 memset (chunk->data, fill_value, chunk->size);
334 }
335
336 /**
337  * mono_code_manager_set_read_only:
338  * @cman: a code manager
339  *
340  * Make the code manager read only, so further allocation requests cause an assert.
341  */
342 void             
343 mono_code_manager_set_read_only (MonoCodeManager *cman)
344 {
345         cman->read_only = TRUE;
346 }
347
348 /**
349  * mono_code_manager_foreach:
350  * @cman: a code manager
351  * @func: a callback function pointer
352  * @user_data: additional data to pass to @func
353  *
354  * Invokes the callback @func for each different chunk of memory allocated
355  * in the code manager @cman.
356  */
357 void
358 mono_code_manager_foreach (MonoCodeManager *cman, MonoCodeManagerFunc func, void *user_data)
359 {
360         CodeChunk *chunk;
361         for (chunk = cman->current; chunk; chunk = chunk->next) {
362                 if (func (chunk->data, chunk->size, chunk->bsize, user_data))
363                         return;
364         }
365         for (chunk = cman->full; chunk; chunk = chunk->next) {
366                 if (func (chunk->data, chunk->size, chunk->bsize, user_data))
367                         return;
368         }
369 }
370
371 /* BIND_ROOM is the divisor for the chunck of code size dedicated
372  * to binding branches (branches not reachable with the immediate displacement)
373  * bind_size = size/BIND_ROOM;
374  * we should reduce it and make MIN_PAGES bigger for such systems
375  */
376 #if defined(__ppc__) || defined(__powerpc__)
377 #define BIND_ROOM 4
378 #endif
379 #if defined(__arm__)
380 #define BIND_ROOM 8
381 #endif
382
383 static CodeChunk*
384 new_codechunk (int dynamic, int size)
385 {
386         int minsize, flags = CODE_FLAG_MMAP;
387         int chunk_size, bsize = 0;
388         int pagesize;
389         CodeChunk *chunk;
390         void *ptr;
391
392 #ifdef FORCE_MALLOC
393         flags = CODE_FLAG_MALLOC;
394 #endif
395
396         pagesize = mono_pagesize ();
397
398         if (dynamic) {
399                 chunk_size = size;
400                 flags = CODE_FLAG_MALLOC;
401         } else {
402                 minsize = pagesize * MIN_PAGES;
403                 if (size < minsize)
404                         chunk_size = minsize;
405                 else {
406                         chunk_size = size;
407                         chunk_size += pagesize - 1;
408                         chunk_size &= ~ (pagesize - 1);
409                 }
410         }
411 #ifdef BIND_ROOM
412         bsize = chunk_size / BIND_ROOM;
413         if (bsize < MIN_BSIZE)
414                 bsize = MIN_BSIZE;
415         bsize += MIN_ALIGN -1;
416         bsize &= ~ (MIN_ALIGN - 1);
417         if (chunk_size - size < bsize) {
418                 chunk_size = size + bsize;
419                 chunk_size += pagesize - 1;
420                 chunk_size &= ~ (pagesize - 1);
421         }
422 #endif
423
424         if (flags == CODE_FLAG_MALLOC) {
425                 ptr = dlmemalign (MIN_ALIGN, chunk_size + MIN_ALIGN - 1);
426                 if (!ptr)
427                         return NULL;
428         } else {
429                 /* Allocate MIN_ALIGN-1 more than we need so we can still */
430                 /* guarantee MIN_ALIGN alignment for individual allocs    */
431                 /* from mono_code_manager_reserve_align.                  */
432                 ptr = mono_valloc (NULL, chunk_size + MIN_ALIGN - 1, MONO_PROT_RWX | ARCH_MAP_FLAGS);
433                 if (!ptr)
434                         return NULL;
435         }
436
437         if (flags == CODE_FLAG_MALLOC) {
438 #ifdef BIND_ROOM
439                 /* Make sure the thunks area is zeroed */
440                 memset (ptr, 0, bsize);
441 #endif
442         }
443
444         chunk = malloc (sizeof (CodeChunk));
445         if (!chunk) {
446                 if (flags == CODE_FLAG_MALLOC)
447                         dlfree (ptr);
448                 else
449                         mono_vfree (ptr, chunk_size);
450                 return NULL;
451         }
452         chunk->next = NULL;
453         chunk->size = chunk_size;
454         chunk->data = ptr;
455         chunk->flags = flags;
456         chunk->pos = bsize;
457         chunk->bsize = bsize;
458         mono_profiler_code_chunk_new((gpointer) chunk->data, chunk->size);
459
460         code_memory_used += chunk_size;
461         mono_runtime_resource_check_limit (MONO_RESOURCE_JIT_CODE, code_memory_used);
462         /*printf ("code chunk at: %p\n", ptr);*/
463         return chunk;
464 }
465
466 /**
467  * mono_code_manager_reserve:
468  * @cman: a code manager
469  * @size: size of memory to allocate
470  * @alignment: power of two alignment value
471  *
472  * Allocates at least @size bytes of memory inside the code manager @cman.
473  *
474  * Returns: the pointer to the allocated memory or #NULL on failure
475  */
476 void*
477 mono_code_manager_reserve_align (MonoCodeManager *cman, int size, int alignment)
478 {
479 #if !defined(__native_client__) || !defined(__native_client_codegen__)
480         CodeChunk *chunk, *prev;
481         void *ptr;
482         guint32 align_mask = alignment - 1;
483
484         g_assert (!cman->read_only);
485
486         /* eventually allow bigger alignments, but we need to fix the dynamic alloc code to
487          * handle this before
488          */
489         g_assert (alignment <= MIN_ALIGN);
490
491         if (cman->dynamic) {
492                 ++mono_stats.dynamic_code_alloc_count;
493                 mono_stats.dynamic_code_bytes_count += size;
494         }
495
496         if (!cman->current) {
497                 cman->current = new_codechunk (cman->dynamic, size);
498                 if (!cman->current)
499                         return NULL;
500         }
501
502         for (chunk = cman->current; chunk; chunk = chunk->next) {
503                 if (ALIGN_INT (chunk->pos, alignment) + size <= chunk->size) {
504                         chunk->pos = ALIGN_INT (chunk->pos, alignment);
505                         /* Align the chunk->data we add to chunk->pos */
506                         /* or we can't guarantee proper alignment     */
507                         ptr = (void*)((((uintptr_t)chunk->data + align_mask) & ~(uintptr_t)align_mask) + chunk->pos);
508                         chunk->pos = ((char*)ptr - chunk->data) + size;
509                         return ptr;
510                 }
511         }
512         /* 
513          * no room found, move one filled chunk to cman->full 
514          * to keep cman->current from growing too much
515          */
516         prev = NULL;
517         for (chunk = cman->current; chunk; prev = chunk, chunk = chunk->next) {
518                 if (chunk->pos + MIN_ALIGN * 4 <= chunk->size)
519                         continue;
520                 if (prev) {
521                         prev->next = chunk->next;
522                 } else {
523                         cman->current = chunk->next;
524                 }
525                 chunk->next = cman->full;
526                 cman->full = chunk;
527                 break;
528         }
529         chunk = new_codechunk (cman->dynamic, size);
530         if (!chunk)
531                 return NULL;
532         chunk->next = cman->current;
533         cman->current = chunk;
534         chunk->pos = ALIGN_INT (chunk->pos, alignment);
535         /* Align the chunk->data we add to chunk->pos */
536         /* or we can't guarantee proper alignment     */
537         ptr = (void*)((((uintptr_t)chunk->data + align_mask) & ~(uintptr_t)align_mask) + chunk->pos);
538         chunk->pos = ((char*)ptr - chunk->data) + size;
539         return ptr;
540 #else
541         unsigned char *temp_ptr, *code_ptr;
542         /* Round up size to next bundle */
543         alignment = kNaClBundleSize;
544         size = (size + kNaClBundleSize) & (~kNaClBundleMask);
545         /* Allocate a temp buffer */
546         temp_ptr = memalign (alignment, size);
547         g_assert (((uintptr_t)temp_ptr & kNaClBundleMask) == 0);
548         /* Allocate code space from the service runtime */
549         code_ptr = allocate_code (size);
550         /* Insert pointer to code space in hash, keyed by buffer ptr */
551         g_hash_table_insert (cman->hash, temp_ptr, code_ptr);
552
553         nacl_jit_check_init ();
554
555         patch_current_depth++;
556         patch_source_base[patch_current_depth] = temp_ptr;
557         patch_dest_base[patch_current_depth] = code_ptr;
558         patch_alloc_size[patch_current_depth] = size;
559         g_assert (patch_current_depth < kMaxPatchDepth);
560         return temp_ptr;
561 #endif
562 }
563
564 /**
565  * mono_code_manager_reserve:
566  * @cman: a code manager
567  * @size: size of memory to allocate
568  *
569  * Allocates at least @size bytes of memory inside the code manager @cman.
570  *
571  * Returns: the pointer to the allocated memory or #NULL on failure
572  */
573 void*
574 mono_code_manager_reserve (MonoCodeManager *cman, int size)
575 {
576         return mono_code_manager_reserve_align (cman, size, MIN_ALIGN);
577 }
578
579 /**
580  * mono_code_manager_commit:
581  * @cman: a code manager
582  * @data: the pointer returned by mono_code_manager_reserve ()
583  * @size: the size requested in the call to mono_code_manager_reserve ()
584  * @newsize: the new size to reserve
585  *
586  * If we reserved too much room for a method and we didn't allocate
587  * already from the code manager, we can get back the excess allocation
588  * for later use in the code manager.
589  */
590 void
591 mono_code_manager_commit (MonoCodeManager *cman, void *data, int size, int newsize)
592 {
593 #if !defined(__native_client__) || !defined(__native_client_codegen__)
594         g_assert (newsize <= size);
595
596         if (cman->current && (size != newsize) && (data == cman->current->data + cman->current->pos - size)) {
597                 cman->current->pos -= size - newsize;
598         }
599 #else
600         unsigned char *code;
601         int status;
602         g_assert (newsize <= size);
603         code = g_hash_table_lookup (cman->hash, data);
604         g_assert (code != NULL);
605         /* Pad space after code with HLTs */
606         /* TODO: this is x86/amd64 specific */
607         while (newsize & kNaClBundleMask) {
608                 *((char *)data + newsize) = 0xf4;
609                 newsize++;
610         }
611         status = nacl_dyncode_create (code, data, newsize);
612         if (status != 0) {
613                 unsigned char *codep;
614                 fprintf(stderr, "Error creating Native Client dynamic code section attempted to be\n"
615                                 "emitted at %p (hex dissasembly of code follows):\n", code);
616                 for (codep = data; codep < data + newsize; codep++)
617                         fprintf(stderr, "%02x ", *codep);
618                 fprintf(stderr, "\n");
619                 g_assert_not_reached ();
620         }
621         g_hash_table_remove (cman->hash, data);
622         g_assert (data == patch_source_base[patch_current_depth]);
623         g_assert (code == patch_dest_base[patch_current_depth]);
624         patch_current_depth--;
625         g_assert (patch_current_depth >= -1);
626         free (data);
627 #endif
628 }
629
630 #if defined(__native_client_codegen__) && defined(__native_client__)
631 void *
632 nacl_code_manager_get_code_dest (MonoCodeManager *cman, void *data)
633 {
634         return g_hash_table_lookup (cman->hash, data);
635 }
636 #endif
637
638 /**
639  * mono_code_manager_size:
640  * @cman: a code manager
641  * @used_size: pointer to an integer for the result
642  *
643  * This function can be used to get statistics about a code manager:
644  * the integer pointed to by @used_size will contain how much
645  * memory is actually used inside the code managed @cman.
646  *
647  * Returns: the amount of memory allocated in @cman
648  */
649 int
650 mono_code_manager_size (MonoCodeManager *cman, int *used_size)
651 {
652         CodeChunk *chunk;
653         guint32 size = 0;
654         guint32 used = 0;
655         for (chunk = cman->current; chunk; chunk = chunk->next) {
656                 size += chunk->size;
657                 used += chunk->pos;
658         }
659         for (chunk = cman->full; chunk; chunk = chunk->next) {
660                 size += chunk->size;
661                 used += chunk->pos;
662         }
663         if (used_size)
664                 *used_size = used;
665         return size;
666 }
667