4efcea0ae25500addaca763aaa9bb3721d495734
[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         MonoGHashTable *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                 /* Workaround bug in service runtime, unable to allocate */
232                 /* from the first page in the dynamic code section.    */
233                 /* TODO: remove */
234                 next_dynamic_code_addr += (uintptr_t)0x10000;
235         }
236         cman->hash =  mono_g_hash_table_new (NULL, NULL);
237         /* Keep the hash table from being collected */
238         mono_gc_register_root (&cman->hash, sizeof (void*), NULL);
239         if (patch_source_base == NULL) {
240                 patch_source_base = g_malloc (kMaxPatchDepth * sizeof(unsigned char *));
241                 patch_dest_base = g_malloc (kMaxPatchDepth * sizeof(unsigned char *));
242                 patch_alloc_size = g_malloc (kMaxPatchDepth * sizeof(int));
243         }
244 #endif
245         return cman;
246 }
247
248 /**
249  * mono_code_manager_new_dynamic:
250  *
251  * Creates a new code manager suitable for holding native code that can be
252  * used for single or small methods that need to be deallocated independently
253  * of other native code.
254  *
255  * Returns: the new code manager
256  */
257 MonoCodeManager* 
258 mono_code_manager_new_dynamic (void)
259 {
260         MonoCodeManager *cman = mono_code_manager_new ();
261         cman->dynamic = 1;
262         return cman;
263 }
264
265
266 static void
267 free_chunklist (CodeChunk *chunk)
268 {
269         CodeChunk *dead;
270         
271 #if defined(HAVE_VALGRIND_MEMCHECK_H) && defined (VALGRIND_JIT_UNREGISTER_MAP)
272         int valgrind_unregister = 0;
273         if (RUNNING_ON_VALGRIND)
274                 valgrind_unregister = 1;
275 #define valgrind_unregister(x) do { if (valgrind_unregister) { VALGRIND_JIT_UNREGISTER_MAP(NULL,x); } } while (0) 
276 #else
277 #define valgrind_unregister(x)
278 #endif
279
280         for (; chunk; ) {
281                 dead = chunk;
282                 mono_profiler_code_chunk_destroy ((gpointer) dead->data);
283                 chunk = chunk->next;
284                 if (dead->flags == CODE_FLAG_MMAP) {
285                         mono_vfree (dead->data, dead->size);
286                         /* valgrind_unregister(dead->data); */
287                 } else if (dead->flags == CODE_FLAG_MALLOC) {
288                         dlfree (dead->data);
289                 }
290                 code_memory_used -= dead->size;
291                 free (dead);
292         }
293 }
294
295 /**
296  * mono_code_manager_destroy:
297  * @cman: a code manager
298  *
299  * Free all the memory associated with the code manager @cman.
300  */
301 void
302 mono_code_manager_destroy (MonoCodeManager *cman)
303 {
304         free_chunklist (cman->full);
305         free_chunklist (cman->current);
306         free (cman);
307 }
308
309 /**
310  * mono_code_manager_invalidate:
311  * @cman: a code manager
312  *
313  * Fill all the memory with an invalid native code value
314  * so that any attempt to execute code allocated in the code
315  * manager @cman will fail. This is used for debugging purposes.
316  */
317 void             
318 mono_code_manager_invalidate (MonoCodeManager *cman)
319 {
320         CodeChunk *chunk;
321
322 #if defined(__i386__) || defined(__x86_64__)
323         int fill_value = 0xcc; /* x86 break */
324 #else
325         int fill_value = 0x2a;
326 #endif
327
328         for (chunk = cman->current; chunk; chunk = chunk->next)
329                 memset (chunk->data, fill_value, chunk->size);
330         for (chunk = cman->full; chunk; chunk = chunk->next)
331                 memset (chunk->data, fill_value, chunk->size);
332 }
333
334 /**
335  * mono_code_manager_set_read_only:
336  * @cman: a code manager
337  *
338  * Make the code manager read only, so further allocation requests cause an assert.
339  */
340 void             
341 mono_code_manager_set_read_only (MonoCodeManager *cman)
342 {
343         cman->read_only = TRUE;
344 }
345
346 /**
347  * mono_code_manager_foreach:
348  * @cman: a code manager
349  * @func: a callback function pointer
350  * @user_data: additional data to pass to @func
351  *
352  * Invokes the callback @func for each different chunk of memory allocated
353  * in the code manager @cman.
354  */
355 void
356 mono_code_manager_foreach (MonoCodeManager *cman, MonoCodeManagerFunc func, void *user_data)
357 {
358         CodeChunk *chunk;
359         for (chunk = cman->current; chunk; chunk = chunk->next) {
360                 if (func (chunk->data, chunk->size, chunk->bsize, user_data))
361                         return;
362         }
363         for (chunk = cman->full; chunk; chunk = chunk->next) {
364                 if (func (chunk->data, chunk->size, chunk->bsize, user_data))
365                         return;
366         }
367 }
368
369 /* BIND_ROOM is the divisor for the chunck of code size dedicated
370  * to binding branches (branches not reachable with the immediate displacement)
371  * bind_size = size/BIND_ROOM;
372  * we should reduce it and make MIN_PAGES bigger for such systems
373  */
374 #if defined(__ppc__) || defined(__powerpc__)
375 #define BIND_ROOM 4
376 #endif
377 #if defined(__arm__)
378 #define BIND_ROOM 8
379 #endif
380
381 static CodeChunk*
382 new_codechunk (int dynamic, int size)
383 {
384         int minsize, flags = CODE_FLAG_MMAP;
385         int chunk_size, bsize = 0;
386         int pagesize;
387         CodeChunk *chunk;
388         void *ptr;
389
390 #ifdef FORCE_MALLOC
391         flags = CODE_FLAG_MALLOC;
392 #endif
393
394         pagesize = mono_pagesize ();
395
396         if (dynamic) {
397                 chunk_size = size;
398                 flags = CODE_FLAG_MALLOC;
399         } else {
400                 minsize = pagesize * MIN_PAGES;
401                 if (size < minsize)
402                         chunk_size = minsize;
403                 else {
404                         chunk_size = size;
405                         chunk_size += pagesize - 1;
406                         chunk_size &= ~ (pagesize - 1);
407                 }
408         }
409 #ifdef BIND_ROOM
410         bsize = chunk_size / BIND_ROOM;
411         if (bsize < MIN_BSIZE)
412                 bsize = MIN_BSIZE;
413         bsize += MIN_ALIGN -1;
414         bsize &= ~ (MIN_ALIGN - 1);
415         if (chunk_size - size < bsize) {
416                 chunk_size = size + bsize;
417                 chunk_size += pagesize - 1;
418                 chunk_size &= ~ (pagesize - 1);
419         }
420 #endif
421
422         if (flags == CODE_FLAG_MALLOC) {
423                 ptr = dlmemalign (MIN_ALIGN, chunk_size + MIN_ALIGN - 1);
424                 if (!ptr)
425                         return NULL;
426         } else {
427                 /* Allocate MIN_ALIGN-1 more than we need so we can still */
428                 /* guarantee MIN_ALIGN alignment for individual allocs    */
429                 /* from mono_code_manager_reserve_align.                  */
430                 ptr = mono_valloc (NULL, chunk_size + MIN_ALIGN - 1, MONO_PROT_RWX | ARCH_MAP_FLAGS);
431                 if (!ptr)
432                         return NULL;
433         }
434
435         if (flags == CODE_FLAG_MALLOC) {
436 #ifdef BIND_ROOM
437                 /* Make sure the thunks area is zeroed */
438                 memset (ptr, 0, bsize);
439 #endif
440         }
441
442         chunk = malloc (sizeof (CodeChunk));
443         if (!chunk) {
444                 if (flags == CODE_FLAG_MALLOC)
445                         dlfree (ptr);
446                 else
447                         mono_vfree (ptr, chunk_size);
448                 return NULL;
449         }
450         chunk->next = NULL;
451         chunk->size = chunk_size;
452         chunk->data = ptr;
453         chunk->flags = flags;
454         chunk->pos = bsize;
455         chunk->bsize = bsize;
456         mono_profiler_code_chunk_new((gpointer) chunk->data, chunk->size);
457
458         code_memory_used += chunk_size;
459         mono_runtime_resource_check_limit (MONO_RESOURCE_JIT_CODE, code_memory_used);
460         /*printf ("code chunk at: %p\n", ptr);*/
461         return chunk;
462 }
463
464 /**
465  * mono_code_manager_reserve:
466  * @cman: a code manager
467  * @size: size of memory to allocate
468  * @alignment: power of two alignment value
469  *
470  * Allocates at least @size bytes of memory inside the code manager @cman.
471  *
472  * Returns: the pointer to the allocated memory or #NULL on failure
473  */
474 void*
475 mono_code_manager_reserve_align (MonoCodeManager *cman, int size, int alignment)
476 {
477 #if !defined(__native_client__) || !defined(__native_client_codegen__)
478         CodeChunk *chunk, *prev;
479         void *ptr;
480         guint32 align_mask = alignment - 1;
481
482         g_assert (!cman->read_only);
483
484         /* eventually allow bigger alignments, but we need to fix the dynamic alloc code to
485          * handle this before
486          */
487         g_assert (alignment <= MIN_ALIGN);
488
489         if (cman->dynamic) {
490                 ++mono_stats.dynamic_code_alloc_count;
491                 mono_stats.dynamic_code_bytes_count += size;
492         }
493
494         if (!cman->current) {
495                 cman->current = new_codechunk (cman->dynamic, size);
496                 if (!cman->current)
497                         return NULL;
498         }
499
500         for (chunk = cman->current; chunk; chunk = chunk->next) {
501                 if (ALIGN_INT (chunk->pos, alignment) + size <= chunk->size) {
502                         chunk->pos = ALIGN_INT (chunk->pos, alignment);
503                         /* Align the chunk->data we add to chunk->pos */
504                         /* or we can't guarantee proper alignment     */
505                         ptr = (void*)((((uintptr_t)chunk->data + align_mask) & ~(uintptr_t)align_mask) + chunk->pos);
506                         chunk->pos = ((char*)ptr - chunk->data) + size;
507                         return ptr;
508                 }
509         }
510         /* 
511          * no room found, move one filled chunk to cman->full 
512          * to keep cman->current from growing too much
513          */
514         prev = NULL;
515         for (chunk = cman->current; chunk; prev = chunk, chunk = chunk->next) {
516                 if (chunk->pos + MIN_ALIGN * 4 <= chunk->size)
517                         continue;
518                 if (prev) {
519                         prev->next = chunk->next;
520                 } else {
521                         cman->current = chunk->next;
522                 }
523                 chunk->next = cman->full;
524                 cman->full = chunk;
525                 break;
526         }
527         chunk = new_codechunk (cman->dynamic, size);
528         if (!chunk)
529                 return NULL;
530         chunk->next = cman->current;
531         cman->current = chunk;
532         chunk->pos = ALIGN_INT (chunk->pos, alignment);
533         /* Align the chunk->data we add to chunk->pos */
534         /* or we can't guarantee proper alignment     */
535         ptr = (void*)((((uintptr_t)chunk->data + align_mask) & ~(uintptr_t)align_mask) + chunk->pos);
536         chunk->pos = ((char*)ptr - chunk->data) + size;
537         return ptr;
538 #else
539         unsigned char *temp_ptr, *code_ptr;
540         /* Round up size to next bundle */
541         alignment = kNaClBundleSize;
542         size = (size + kNaClBundleSize) & (~kNaClBundleMask);
543         /* Allocate a temp buffer */
544         temp_ptr = memalign (alignment, size);
545         g_assert (((uintptr_t)temp_ptr & kNaClBundleMask) == 0);
546         /* Allocate code space from the service runtime */
547         code_ptr = allocate_code (size);
548         /* Insert pointer to code space in hash, keyed by buffer ptr */
549         mono_g_hash_table_insert (cman->hash, temp_ptr, code_ptr);
550
551         nacl_jit_check_init ();
552
553         patch_current_depth++;
554         patch_source_base[patch_current_depth] = temp_ptr;
555         patch_dest_base[patch_current_depth] = code_ptr;
556         patch_alloc_size[patch_current_depth] = size;
557         g_assert (patch_current_depth < kMaxPatchDepth);
558         return temp_ptr;
559 #endif
560 }
561
562 /**
563  * mono_code_manager_reserve:
564  * @cman: a code manager
565  * @size: size of memory to allocate
566  *
567  * Allocates at least @size bytes of memory inside the code manager @cman.
568  *
569  * Returns: the pointer to the allocated memory or #NULL on failure
570  */
571 void*
572 mono_code_manager_reserve (MonoCodeManager *cman, int size)
573 {
574         return mono_code_manager_reserve_align (cman, size, MIN_ALIGN);
575 }
576
577 /**
578  * mono_code_manager_commit:
579  * @cman: a code manager
580  * @data: the pointer returned by mono_code_manager_reserve ()
581  * @size: the size requested in the call to mono_code_manager_reserve ()
582  * @newsize: the new size to reserve
583  *
584  * If we reserved too much room for a method and we didn't allocate
585  * already from the code manager, we can get back the excess allocation
586  * for later use in the code manager.
587  */
588 void
589 mono_code_manager_commit (MonoCodeManager *cman, void *data, int size, int newsize)
590 {
591 #if !defined(__native_client__) || !defined(__native_client_codegen__)
592         g_assert (newsize <= size);
593
594         if (cman->current && (size != newsize) && (data == cman->current->data + cman->current->pos - size)) {
595                 cman->current->pos -= size - newsize;
596         }
597 #else
598         unsigned char *code;
599         int status;
600         g_assert (newsize <= size);
601         code = mono_g_hash_table_lookup (cman->hash, data);
602         g_assert (code != NULL);
603         /* Pad space after code with HLTs */
604         /* TODO: this is x86/amd64 specific */
605         while (newsize & kNaClBundleMask) {
606                 *((char *)data + newsize) = 0xf4;
607                 newsize++;
608         }
609         status = nacl_dyncode_create (code, data, newsize);
610         if (status != 0) {
611                 g_assert_not_reached ();
612         }
613         mono_g_hash_table_remove (cman->hash, data);
614         g_assert (data == patch_source_base[patch_current_depth]);
615         g_assert (code == patch_dest_base[patch_current_depth]);
616         patch_current_depth--;
617         g_assert (patch_current_depth >= -1);
618         free (data);
619 #endif
620 }
621
622 #if defined(__native_client_codegen__) && defined(__native_client__)
623 void *
624 nacl_code_manager_get_code_dest (MonoCodeManager *cman, void *data)
625 {
626         return mono_g_hash_table_lookup (cman->hash, data);
627 }
628 #endif
629
630 /**
631  * mono_code_manager_size:
632  * @cman: a code manager
633  * @used_size: pointer to an integer for the result
634  *
635  * This function can be used to get statistics about a code manager:
636  * the integer pointed to by @used_size will contain how much
637  * memory is actually used inside the code managed @cman.
638  *
639  * Returns: the amount of memory allocated in @cman
640  */
641 int
642 mono_code_manager_size (MonoCodeManager *cman, int *used_size)
643 {
644         CodeChunk *chunk;
645         guint32 size = 0;
646         guint32 used = 0;
647         for (chunk = cman->current; chunk; chunk = chunk->next) {
648                 size += chunk->size;
649                 used += chunk->pos;
650         }
651         for (chunk = cman->full; chunk; chunk = chunk->next) {
652                 size += chunk->size;
653                 used += chunk->pos;
654         }
655         if (used_size)
656                 *used_size = used;
657         return size;
658 }
659