Use anonymous file instead of regular file to back mmap
[tinycc.git] / tccrun.c
bloba53330f5d7c58a44b4ad3b61de744c7de76befd4
1 /*
2 * TCC - Tiny C Compiler - Support for -run switch
4 * Copyright (c) 2001-2004 Fabrice Bellard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 #include "tcc.h"
23 /* only native compiler supports -run */
24 #ifdef TCC_IS_NATIVE
26 #ifdef CONFIG_TCC_BACKTRACE
27 ST_DATA int rt_num_callers = 6;
28 ST_DATA const char **rt_bound_error_msg;
29 ST_DATA void *rt_prog_main;
30 #endif
32 #ifdef _WIN32
33 #define ucontext_t CONTEXT
34 #endif
36 static void set_pages_executable(void *ptr, unsigned long length);
37 static void set_exception_handler(void);
38 static int rt_get_caller_pc(addr_t *paddr, ucontext_t *uc, int level);
39 static void rt_error(ucontext_t *uc, const char *fmt, ...);
40 static int tcc_relocate_ex(TCCState *s1, void *ptr);
42 #ifdef _WIN64
43 static void win64_add_function_table(TCCState *s1);
44 #endif
46 /* ------------------------------------------------------------- */
47 /* Do all relocations (needed before using tcc_get_symbol())
48 Returns -1 on error. */
50 LIBTCCAPI int tcc_relocate(TCCState *s1, void *ptr)
52 int ret;
54 if (TCC_RELOCATE_AUTO != ptr)
55 return tcc_relocate_ex(s1, ptr);
57 ret = tcc_relocate_ex(s1, NULL);
58 if (ret < 0)
59 return ret;
61 #ifdef HAVE_SELINUX
62 { /* Use mmap instead of malloc for Selinux. */
63 s1->write_mem = mmap (NULL, ret, PROT_READ|PROT_WRITE,
64 MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
65 if (s1->write_mem == MAP_FAILED)
66 tcc_error("mmap not writeable");
68 s1->runtime_mem = mmap (NULL, ret, PROT_READ|PROT_EXEC,
69 MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
70 if (s1->runtime_mem == MAP_FAILED)
71 tcc_error("mmap not executable");
73 ret = tcc_relocate_ex(s1, s1->write_mem);
75 #else
76 s1->runtime_mem = tcc_malloc(ret);
77 ret = tcc_relocate_ex(s1, s1->runtime_mem);
78 #endif
79 return ret;
82 /* launch the compiled program with the given arguments */
83 LIBTCCAPI int tcc_run(TCCState *s1, int argc, char **argv)
85 int (*prog_main)(int, char **);
86 int ret;
88 if (tcc_relocate(s1, TCC_RELOCATE_AUTO) < 0)
89 return -1;
91 prog_main = tcc_get_symbol_err(s1, s1->runtime_main);
93 #ifdef CONFIG_TCC_BACKTRACE
94 if (s1->do_debug) {
95 set_exception_handler();
96 rt_prog_main = prog_main;
98 #endif
100 #ifdef CONFIG_TCC_BCHECK
101 if (s1->do_bounds_check) {
102 void (*bound_init)(void);
103 void (*bound_exit)(void);
104 /* set error function */
105 rt_bound_error_msg = tcc_get_symbol_err(s1, "__bound_error_msg");
106 /* XXX: use .init section so that it also work in binary ? */
107 bound_init = tcc_get_symbol_err(s1, "__bound_init");
108 bound_exit = tcc_get_symbol_err(s1, "__bound_exit");
109 bound_init();
110 ret = (*prog_main)(argc, argv);
111 bound_exit();
112 } else
113 #endif
114 ret = (*prog_main)(argc, argv);
115 return ret;
118 /* relocate code. Return -1 on error, required size if ptr is NULL,
119 otherwise copy code into buffer passed by the caller */
120 static int tcc_relocate_ex(TCCState *s1, void *ptr)
122 Section *s;
123 unsigned long offset, length;
124 addr_t mem;
125 int i;
127 if (NULL == ptr) {
128 s1->nb_errors = 0;
129 #ifdef TCC_TARGET_PE
130 pe_output_file(s1, NULL);
131 #else
132 tcc_add_runtime(s1);
133 relocate_common_syms();
134 tcc_add_linker_symbols(s1);
135 build_got_entries(s1);
136 #endif
137 if (s1->nb_errors)
138 return -1;
141 offset = 0, mem = (addr_t)ptr;
142 for(i = 1; i < s1->nb_sections; i++) {
143 s = s1->sections[i];
144 if (0 == (s->sh_flags & SHF_ALLOC))
145 continue;
146 length = s->data_offset;
147 s->sh_addr = mem ? (mem + offset + 15) & ~15 : 0;
148 offset = (offset + length + 15) & ~15;
150 offset += 16;
152 /* relocate symbols */
153 relocate_syms(s1, 1);
154 if (s1->nb_errors)
155 return -1;
157 #ifdef TCC_HAS_RUNTIME_PLTGOT
158 s1->runtime_plt_and_got_offset = 0;
159 s1->runtime_plt_and_got = (char *)(mem + offset);
160 /* double the size of the buffer for got and plt entries
161 XXX: calculate exact size for them? */
162 offset *= 2;
163 #endif
165 if (0 == mem)
166 return offset;
168 /* relocate each section */
169 for(i = 1; i < s1->nb_sections; i++) {
170 s = s1->sections[i];
171 if (s->reloc)
172 relocate_section(s1, s);
175 for(i = 1; i < s1->nb_sections; i++) {
176 s = s1->sections[i];
177 if (0 == (s->sh_flags & SHF_ALLOC))
178 continue;
179 length = s->data_offset;
180 // printf("%-12s %08x %04x\n", s->name, s->sh_addr, length);
181 ptr = (void*)s->sh_addr;
182 if (NULL == s->data || s->sh_type == SHT_NOBITS)
183 memset(ptr, 0, length);
184 else
185 memcpy(ptr, s->data, length);
186 /* mark executable sections as executable in memory */
187 if (s->sh_flags & SHF_EXECINSTR)
188 set_pages_executable(ptr, length);
191 #ifdef TCC_HAS_RUNTIME_PLTGOT
192 set_pages_executable(s1->runtime_plt_and_got,
193 s1->runtime_plt_and_got_offset);
194 #endif
196 #ifdef _WIN64
197 win64_add_function_table(s1);
198 #endif
199 return 0;
202 /* ------------------------------------------------------------- */
203 /* allow to run code in memory */
205 static void set_pages_executable(void *ptr, unsigned long length)
207 #ifdef _WIN32
208 unsigned long old_protect;
209 VirtualProtect(ptr, length, PAGE_EXECUTE_READWRITE, &old_protect);
210 #else
211 #ifndef PAGESIZE
212 # define PAGESIZE 4096
213 #endif
214 addr_t start, end;
215 start = (addr_t)ptr & ~(PAGESIZE - 1);
216 end = (addr_t)ptr + length;
217 end = (end + PAGESIZE - 1) & ~(PAGESIZE - 1);
218 mprotect((void *)start, end - start, PROT_READ | PROT_WRITE | PROT_EXEC);
219 __clear_cache(ptr, ptr + length);
220 #endif
223 /* ------------------------------------------------------------- */
224 #ifdef CONFIG_TCC_BACKTRACE
226 ST_FUNC void tcc_set_num_callers(int n)
228 rt_num_callers = n;
231 /* print the position in the source file of PC value 'pc' by reading
232 the stabs debug information */
233 static addr_t rt_printline(addr_t wanted_pc, const char *msg)
235 char func_name[128], last_func_name[128];
236 addr_t func_addr, last_pc, pc;
237 const char *incl_files[INCLUDE_STACK_SIZE];
238 int incl_index, len, last_line_num, i;
239 const char *str, *p;
241 Stab_Sym *stab_sym = NULL, *stab_sym_end, *sym;
242 int stab_len = 0;
243 char *stab_str = NULL;
245 if (stab_section) {
246 stab_len = stab_section->data_offset;
247 stab_sym = (Stab_Sym *)stab_section->data;
248 stab_str = stabstr_section->data;
251 func_name[0] = '\0';
252 func_addr = 0;
253 incl_index = 0;
254 last_func_name[0] = '\0';
255 last_pc = (addr_t)-1;
256 last_line_num = 1;
258 if (!stab_sym)
259 goto no_stabs;
261 stab_sym_end = (Stab_Sym*)((char*)stab_sym + stab_len);
262 for (sym = stab_sym + 1; sym < stab_sym_end; ++sym) {
263 switch(sym->n_type) {
264 /* function start or end */
265 case N_FUN:
266 if (sym->n_strx == 0) {
267 /* we test if between last line and end of function */
268 pc = sym->n_value + func_addr;
269 if (wanted_pc >= last_pc && wanted_pc < pc)
270 goto found;
271 func_name[0] = '\0';
272 func_addr = 0;
273 } else {
274 str = stab_str + sym->n_strx;
275 p = strchr(str, ':');
276 if (!p) {
277 pstrcpy(func_name, sizeof(func_name), str);
278 } else {
279 len = p - str;
280 if (len > sizeof(func_name) - 1)
281 len = sizeof(func_name) - 1;
282 memcpy(func_name, str, len);
283 func_name[len] = '\0';
285 func_addr = sym->n_value;
287 break;
288 /* line number info */
289 case N_SLINE:
290 pc = sym->n_value + func_addr;
291 if (wanted_pc >= last_pc && wanted_pc < pc)
292 goto found;
293 last_pc = pc;
294 last_line_num = sym->n_desc;
295 /* XXX: slow! */
296 strcpy(last_func_name, func_name);
297 break;
298 /* include files */
299 case N_BINCL:
300 str = stab_str + sym->n_strx;
301 add_incl:
302 if (incl_index < INCLUDE_STACK_SIZE) {
303 incl_files[incl_index++] = str;
305 break;
306 case N_EINCL:
307 if (incl_index > 1)
308 incl_index--;
309 break;
310 case N_SO:
311 if (sym->n_strx == 0) {
312 incl_index = 0; /* end of translation unit */
313 } else {
314 str = stab_str + sym->n_strx;
315 /* do not add path */
316 len = strlen(str);
317 if (len > 0 && str[len - 1] != '/')
318 goto add_incl;
320 break;
324 no_stabs:
325 /* second pass: we try symtab symbols (no line number info) */
326 incl_index = 0;
327 if (symtab_section)
329 ElfW(Sym) *sym, *sym_end;
330 int type;
332 sym_end = (ElfW(Sym) *)(symtab_section->data + symtab_section->data_offset);
333 for(sym = (ElfW(Sym) *)symtab_section->data + 1;
334 sym < sym_end;
335 sym++) {
336 type = ELFW(ST_TYPE)(sym->st_info);
337 if (type == STT_FUNC || type == STT_GNU_IFUNC) {
338 if (wanted_pc >= sym->st_value &&
339 wanted_pc < sym->st_value + sym->st_size) {
340 pstrcpy(last_func_name, sizeof(last_func_name),
341 strtab_section->data + sym->st_name);
342 func_addr = sym->st_value;
343 goto found;
348 /* did not find any info: */
349 fprintf(stderr, "%s %p ???\n", msg, (void*)wanted_pc);
350 fflush(stderr);
351 return 0;
352 found:
353 i = incl_index;
354 if (i > 0)
355 fprintf(stderr, "%s:%d: ", incl_files[--i], last_line_num);
356 fprintf(stderr, "%s %p", msg, (void*)wanted_pc);
357 if (last_func_name[0] != '\0')
358 fprintf(stderr, " %s()", last_func_name);
359 if (--i >= 0) {
360 fprintf(stderr, " (included from ");
361 for (;;) {
362 fprintf(stderr, "%s", incl_files[i]);
363 if (--i < 0)
364 break;
365 fprintf(stderr, ", ");
367 fprintf(stderr, ")");
369 fprintf(stderr, "\n");
370 fflush(stderr);
371 return func_addr;
374 /* emit a run time error at position 'pc' */
375 static void rt_error(ucontext_t *uc, const char *fmt, ...)
377 va_list ap;
378 addr_t pc;
379 int i;
381 fprintf(stderr, "Runtime error: ");
382 va_start(ap, fmt);
383 vfprintf(stderr, fmt, ap);
384 va_end(ap);
385 fprintf(stderr, "\n");
387 for(i=0;i<rt_num_callers;i++) {
388 if (rt_get_caller_pc(&pc, uc, i) < 0)
389 break;
390 pc = rt_printline(pc, i ? "by" : "at");
391 if (pc == (addr_t)rt_prog_main && pc)
392 break;
396 /* ------------------------------------------------------------- */
397 #ifndef _WIN32
399 /* signal handler for fatal errors */
400 static void sig_error(int signum, siginfo_t *siginf, void *puc)
402 ucontext_t *uc = puc;
404 switch(signum) {
405 case SIGFPE:
406 switch(siginf->si_code) {
407 case FPE_INTDIV:
408 case FPE_FLTDIV:
409 rt_error(uc, "division by zero");
410 break;
411 default:
412 rt_error(uc, "floating point exception");
413 break;
415 break;
416 case SIGBUS:
417 case SIGSEGV:
418 if (rt_bound_error_msg && *rt_bound_error_msg)
419 rt_error(uc, *rt_bound_error_msg);
420 else
421 rt_error(uc, "dereferencing invalid pointer");
422 break;
423 case SIGILL:
424 rt_error(uc, "illegal instruction");
425 break;
426 case SIGABRT:
427 rt_error(uc, "abort() called");
428 break;
429 default:
430 rt_error(uc, "caught signal %d", signum);
431 break;
433 exit(255);
436 #ifndef SA_SIGINFO
437 # define SA_SIGINFO 0x00000004u
438 #endif
440 /* Generate a stack backtrace when a CPU exception occurs. */
441 static void set_exception_handler(void)
443 struct sigaction sigact;
444 /* install TCC signal handlers to print debug info on fatal
445 runtime errors */
446 sigact.sa_flags = SA_SIGINFO | SA_RESETHAND;
447 sigact.sa_sigaction = sig_error;
448 sigemptyset(&sigact.sa_mask);
449 sigaction(SIGFPE, &sigact, NULL);
450 sigaction(SIGILL, &sigact, NULL);
451 sigaction(SIGSEGV, &sigact, NULL);
452 sigaction(SIGBUS, &sigact, NULL);
453 sigaction(SIGABRT, &sigact, NULL);
456 /* ------------------------------------------------------------- */
457 #ifdef __i386__
459 /* fix for glibc 2.1 */
460 #ifndef REG_EIP
461 #define REG_EIP EIP
462 #define REG_EBP EBP
463 #endif
465 /* return the PC at frame level 'level'. Return negative if not found */
466 static int rt_get_caller_pc(addr_t *paddr, ucontext_t *uc, int level)
468 addr_t fp;
469 int i;
471 if (level == 0) {
472 #if defined(__APPLE__)
473 *paddr = uc->uc_mcontext->__ss.__eip;
474 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
475 *paddr = uc->uc_mcontext.mc_eip;
476 #elif defined(__dietlibc__)
477 *paddr = uc->uc_mcontext.eip;
478 #else
479 *paddr = uc->uc_mcontext.gregs[REG_EIP];
480 #endif
481 return 0;
482 } else {
483 #if defined(__APPLE__)
484 fp = uc->uc_mcontext->__ss.__ebp;
485 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
486 fp = uc->uc_mcontext.mc_ebp;
487 #elif defined(__dietlibc__)
488 fp = uc->uc_mcontext.ebp;
489 #else
490 fp = uc->uc_mcontext.gregs[REG_EBP];
491 #endif
492 for(i=1;i<level;i++) {
493 /* XXX: check address validity with program info */
494 if (fp <= 0x1000 || fp >= 0xc0000000)
495 return -1;
496 fp = ((addr_t *)fp)[0];
498 *paddr = ((addr_t *)fp)[1];
499 return 0;
503 /* ------------------------------------------------------------- */
504 #elif defined(__x86_64__)
506 /* return the PC at frame level 'level'. Return negative if not found */
507 static int rt_get_caller_pc(addr_t *paddr, ucontext_t *uc, int level)
509 addr_t fp;
510 int i;
512 if (level == 0) {
513 /* XXX: only support linux */
514 #if defined(__APPLE__)
515 *paddr = uc->uc_mcontext->__ss.__rip;
516 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
517 *paddr = uc->uc_mcontext.mc_rip;
518 #else
519 *paddr = uc->uc_mcontext.gregs[REG_RIP];
520 #endif
521 return 0;
522 } else {
523 #if defined(__APPLE__)
524 fp = uc->uc_mcontext->__ss.__rbp;
525 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
526 fp = uc->uc_mcontext.mc_rbp;
527 #else
528 fp = uc->uc_mcontext.gregs[REG_RBP];
529 #endif
530 for(i=1;i<level;i++) {
531 /* XXX: check address validity with program info */
532 if (fp <= 0x1000)
533 return -1;
534 fp = ((addr_t *)fp)[0];
536 *paddr = ((addr_t *)fp)[1];
537 return 0;
541 /* ------------------------------------------------------------- */
542 #elif defined(__arm__)
544 /* return the PC at frame level 'level'. Return negative if not found */
545 static int rt_get_caller_pc(addr_t *paddr, ucontext_t *uc, int level)
547 addr_t fp, sp;
548 int i;
550 if (level == 0) {
551 /* XXX: only supports linux */
552 #if defined(__linux__)
553 *paddr = uc->uc_mcontext.arm_pc;
554 #else
555 return -1;
556 #endif
557 return 0;
558 } else {
559 #if defined(__linux__)
560 fp = uc->uc_mcontext.arm_fp;
561 sp = uc->uc_mcontext.arm_sp;
562 if (sp < 0x1000)
563 sp = 0x1000;
564 #else
565 return -1;
566 #endif
567 /* XXX: specific to tinycc stack frames */
568 if (fp < sp + 12 || fp & 3)
569 return -1;
570 for(i = 1; i < level; i++) {
571 sp = ((addr_t *)fp)[-2];
572 if (sp < fp || sp - fp > 16 || sp & 3)
573 return -1;
574 fp = ((addr_t *)fp)[-3];
575 if (fp <= sp || fp - sp < 12 || fp & 3)
576 return -1;
578 /* XXX: check address validity with program info */
579 *paddr = ((addr_t *)fp)[-1];
580 return 0;
584 /* ------------------------------------------------------------- */
585 #else
587 #warning add arch specific rt_get_caller_pc()
588 static int rt_get_caller_pc(addr_t *paddr, ucontext_t *uc, int level)
590 return -1;
593 #endif /* !__i386__ */
595 /* ------------------------------------------------------------- */
596 #else /* WIN32 */
598 static long __stdcall cpu_exception_handler(EXCEPTION_POINTERS *ex_info)
600 EXCEPTION_RECORD *er = ex_info->ExceptionRecord;
601 CONTEXT *uc = ex_info->ContextRecord;
602 switch (er->ExceptionCode) {
603 case EXCEPTION_ACCESS_VIOLATION:
604 if (rt_bound_error_msg && *rt_bound_error_msg)
605 rt_error(uc, *rt_bound_error_msg);
606 else
607 rt_error(uc, "access violation");
608 break;
609 case EXCEPTION_STACK_OVERFLOW:
610 rt_error(uc, "stack overflow");
611 break;
612 case EXCEPTION_INT_DIVIDE_BY_ZERO:
613 rt_error(uc, "division by zero");
614 break;
615 default:
616 rt_error(uc, "exception caught");
617 break;
619 return EXCEPTION_EXECUTE_HANDLER;
622 /* Generate a stack backtrace when a CPU exception occurs. */
623 static void set_exception_handler(void)
625 SetUnhandledExceptionFilter(cpu_exception_handler);
628 #ifdef _WIN64
629 static void win64_add_function_table(TCCState *s1)
631 RtlAddFunctionTable(
632 (RUNTIME_FUNCTION*)s1->uw_pdata->sh_addr,
633 s1->uw_pdata->data_offset / sizeof (RUNTIME_FUNCTION),
634 text_section->sh_addr
637 #endif
639 /* return the PC at frame level 'level'. Return non zero if not found */
640 static int rt_get_caller_pc(addr_t *paddr, CONTEXT *uc, int level)
642 addr_t fp, pc;
643 int i;
644 #ifdef _WIN64
645 pc = uc->Rip;
646 fp = uc->Rbp;
647 #else
648 pc = uc->Eip;
649 fp = uc->Ebp;
650 #endif
651 if (level > 0) {
652 for(i=1;i<level;i++) {
653 /* XXX: check address validity with program info */
654 if (fp <= 0x1000 || fp >= 0xc0000000)
655 return -1;
656 fp = ((addr_t*)fp)[0];
658 pc = ((addr_t*)fp)[1];
660 *paddr = pc;
661 return 0;
664 #endif /* _WIN32 */
665 #endif /* CONFIG_TCC_BACKTRACE */
666 /* ------------------------------------------------------------- */
667 #ifdef CONFIG_TCC_STATIC
669 /* dummy function for profiling */
670 ST_FUNC void *dlopen(const char *filename, int flag)
672 return NULL;
675 ST_FUNC void dlclose(void *p)
679 ST_FUNC const char *dlerror(void)
681 return "error";
684 typedef struct TCCSyms {
685 char *str;
686 void *ptr;
687 } TCCSyms;
690 /* add the symbol you want here if no dynamic linking is done */
691 static TCCSyms tcc_syms[] = {
692 #if !defined(CONFIG_TCCBOOT)
693 #define TCCSYM(a) { #a, &a, },
694 TCCSYM(printf)
695 TCCSYM(fprintf)
696 TCCSYM(fopen)
697 TCCSYM(fclose)
698 #undef TCCSYM
699 #endif
700 { NULL, NULL },
703 ST_FUNC void *resolve_sym(TCCState *s1, const char *symbol)
705 TCCSyms *p;
706 p = tcc_syms;
707 while (p->str != NULL) {
708 if (!strcmp(p->str, symbol))
709 return p->ptr;
710 p++;
712 return NULL;
715 #elif !defined(_WIN32)
717 ST_FUNC void *resolve_sym(TCCState *s1, const char *sym)
719 return dlsym(RTLD_DEFAULT, sym);
722 #endif /* CONFIG_TCC_STATIC */
723 #endif /* TCC_IS_NATIVE */
724 /* ------------------------------------------------------------- */