12 #define USE_DL_PREFIX 1
14 #include "mono-codeman.h"
15 #include "mono-mmap.h"
16 #include "mono-counters.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>
24 #if defined(__native_client_codegen__) && defined(__native_client__)
26 #include <nacl/nacl_dyncode.h>
29 static uintptr_t code_memory_used = 0;
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
41 #if defined(__ia64__) || defined(__x86_64__)
43 * We require 16 byte alignment on amd64 so the fp literals embedded in the code are
44 * properly aligned for SSE2.
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(). */
59 /* if a chunk has less than this amount of free space it's considered full */
60 #define MAX_WASTAGE 32
64 #define ARCH_MAP_FLAGS MONO_MMAP_32BIT
66 #define ARCH_MAP_FLAGS 0
69 #define MONO_PROT_RWX (MONO_MMAP_READ|MONO_MMAP_WRITE|MONO_MMAP_EXEC)
71 typedef struct _CodeChunck CodeChunk;
83 unsigned int flags: 8;
84 /* this number of bytes is available to resolve addresses far in memory */
85 unsigned int bsize: 24;
88 struct _MonoCodeManager {
93 #if defined(__native_client_codegen__) && defined(__native_client__)
98 #define ALIGN_INT(val,alignment) (((val) + (alignment - 1)) & ~(alignment - 1))
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.
105 char *next_dynamic_code_addr = NULL;
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
114 allocate_code(intptr_t increment)
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;
125 nacl_is_code_address (void *target)
127 return (char *)target < next_dynamic_code_addr;
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;
138 nacl_allow_target_modification (int val)
140 allow_target_modification = val;
144 nacl_jit_check_init ()
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));
154 /* Given a patch target, modify the target such that patching will work when
155 * the code is copied to the data section.
158 nacl_modify_patch_target (unsigned char *target)
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
168 if (!allow_target_modification) return target;
170 nacl_jit_check_init ();
171 sb = patch_source_base[patch_current_depth];
172 db = patch_dest_base[patch_current_depth];
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.
179 int target_offset = target - db;
180 target = sb + target_offset;
186 nacl_inverse_modify_patch_target (unsigned char *target)
192 if (!allow_target_modification) return target;
194 nacl_jit_check_init ();
195 sb = patch_source_base[patch_current_depth];
196 db = patch_dest_base[patch_current_depth];
198 target_offset = target - sb;
199 target = db + target_offset;
204 #endif /* __native_client_codegen && __native_client__ */
207 * mono_code_manager_new:
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.
215 * Returns: the new code manager
218 mono_code_manager_new (void)
220 MonoCodeManager *cman = malloc (sizeof (MonoCodeManager));
223 cman->current = NULL;
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;
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;
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));
251 * mono_code_manager_new_dynamic:
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.
257 * Returns: the new code manager
260 mono_code_manager_new_dynamic (void)
262 MonoCodeManager *cman = mono_code_manager_new ();
269 free_chunklist (CodeChunk *chunk)
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)
279 #define valgrind_unregister(x)
284 mono_profiler_code_chunk_destroy ((gpointer) dead->data);
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) {
292 code_memory_used -= dead->size;
298 * mono_code_manager_destroy:
299 * @cman: a code manager
301 * Free all the memory associated with the code manager @cman.
304 mono_code_manager_destroy (MonoCodeManager *cman)
306 free_chunklist (cman->full);
307 free_chunklist (cman->current);
312 * mono_code_manager_invalidate:
313 * @cman: a code manager
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.
320 mono_code_manager_invalidate (MonoCodeManager *cman)
324 #if defined(__i386__) || defined(__x86_64__)
325 int fill_value = 0xcc; /* x86 break */
327 int fill_value = 0x2a;
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);
337 * mono_code_manager_set_read_only:
338 * @cman: a code manager
340 * Make the code manager read only, so further allocation requests cause an assert.
343 mono_code_manager_set_read_only (MonoCodeManager *cman)
345 cman->read_only = TRUE;
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
354 * Invokes the callback @func for each different chunk of memory allocated
355 * in the code manager @cman.
358 mono_code_manager_foreach (MonoCodeManager *cman, MonoCodeManagerFunc func, void *user_data)
361 for (chunk = cman->current; chunk; chunk = chunk->next) {
362 if (func (chunk->data, chunk->size, chunk->bsize, user_data))
365 for (chunk = cman->full; chunk; chunk = chunk->next) {
366 if (func (chunk->data, chunk->size, chunk->bsize, user_data))
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
376 #if defined(__ppc__) || defined(__powerpc__)
384 new_codechunk (int dynamic, int size)
386 int minsize, flags = CODE_FLAG_MMAP;
387 int chunk_size, bsize = 0;
393 flags = CODE_FLAG_MALLOC;
396 pagesize = mono_pagesize ();
400 flags = CODE_FLAG_MALLOC;
402 minsize = pagesize * MIN_PAGES;
404 chunk_size = minsize;
407 chunk_size += pagesize - 1;
408 chunk_size &= ~ (pagesize - 1);
412 bsize = chunk_size / BIND_ROOM;
413 if (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);
424 if (flags == CODE_FLAG_MALLOC) {
425 ptr = dlmemalign (MIN_ALIGN, chunk_size + MIN_ALIGN - 1);
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);
437 if (flags == CODE_FLAG_MALLOC) {
439 /* Make sure the thunks area is zeroed */
440 memset (ptr, 0, bsize);
444 chunk = malloc (sizeof (CodeChunk));
446 if (flags == CODE_FLAG_MALLOC)
449 mono_vfree (ptr, chunk_size);
453 chunk->size = chunk_size;
455 chunk->flags = flags;
457 chunk->bsize = bsize;
458 mono_profiler_code_chunk_new((gpointer) chunk->data, chunk->size);
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);*/
467 * mono_code_manager_reserve:
468 * @cman: a code manager
469 * @size: size of memory to allocate
470 * @alignment: power of two alignment value
472 * Allocates at least @size bytes of memory inside the code manager @cman.
474 * Returns: the pointer to the allocated memory or #NULL on failure
477 mono_code_manager_reserve_align (MonoCodeManager *cman, int size, int alignment)
479 #if !defined(__native_client__) || !defined(__native_client_codegen__)
480 CodeChunk *chunk, *prev;
482 guint32 align_mask = alignment - 1;
484 g_assert (!cman->read_only);
486 /* eventually allow bigger alignments, but we need to fix the dynamic alloc code to
489 g_assert (alignment <= MIN_ALIGN);
492 ++mono_stats.dynamic_code_alloc_count;
493 mono_stats.dynamic_code_bytes_count += size;
496 if (!cman->current) {
497 cman->current = new_codechunk (cman->dynamic, size);
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;
513 * no room found, move one filled chunk to cman->full
514 * to keep cman->current from growing too much
517 for (chunk = cman->current; chunk; prev = chunk, chunk = chunk->next) {
518 if (chunk->pos + MIN_ALIGN * 4 <= chunk->size)
521 prev->next = chunk->next;
523 cman->current = chunk->next;
525 chunk->next = cman->full;
529 chunk = new_codechunk (cman->dynamic, size);
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;
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);
553 nacl_jit_check_init ();
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);
565 * mono_code_manager_reserve:
566 * @cman: a code manager
567 * @size: size of memory to allocate
569 * Allocates at least @size bytes of memory inside the code manager @cman.
571 * Returns: the pointer to the allocated memory or #NULL on failure
574 mono_code_manager_reserve (MonoCodeManager *cman, int size)
576 return mono_code_manager_reserve_align (cman, size, MIN_ALIGN);
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
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.
591 mono_code_manager_commit (MonoCodeManager *cman, void *data, int size, int newsize)
593 #if !defined(__native_client__) || !defined(__native_client_codegen__)
594 g_assert (newsize <= size);
596 if (cman->current && (size != newsize) && (data == cman->current->data + cman->current->pos - size)) {
597 cman->current->pos -= size - newsize;
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;
611 status = nacl_dyncode_create (code, data, newsize);
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 ();
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);
630 #if defined(__native_client_codegen__) && defined(__native_client__)
632 nacl_code_manager_get_code_dest (MonoCodeManager *cman, void *data)
634 return g_hash_table_lookup (cman->hash, data);
639 * mono_code_manager_size:
640 * @cman: a code manager
641 * @used_size: pointer to an integer for the result
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.
647 * Returns: the amount of memory allocated in @cman
650 mono_code_manager_size (MonoCodeManager *cman, int *used_size)
655 for (chunk = cman->current; chunk; chunk = chunk->next) {
659 for (chunk = cman->full; chunk; chunk = chunk->next) {