Add support for __builtin_frame_address(level)
[tinycc.git] / tccrun.c
blob531f46a82274b2c1e077f3de71ef4d337e61c5fe
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(uplong *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 #ifdef HAVE_SELINUX
58 /* Use mmap instead of malloc for Selinux
59 Ref http://www.gnu.org/s/libc/manual/html_node/File-Size.html */
60 char tmpfname[] = "/tmp/.tccrunXXXXXX";
61 int fd = mkstemp (tmpfname);
62 if ((ret= tcc_relocate_ex(s1,NULL)) < 0)return -1;
63 s1->mem_size=ret;
64 unlink (tmpfname); ftruncate (fd, s1->mem_size);
65 s1->write_mem = mmap (NULL, ret, PROT_READ|PROT_WRITE,
66 MAP_SHARED, fd, 0);
67 if(s1->write_mem == MAP_FAILED){
68 tcc_error("/tmp not writeable");
69 return -1;
71 s1->runtime_mem = mmap (NULL, ret, PROT_READ|PROT_EXEC,
72 MAP_SHARED, fd, 0);
73 if(s1->runtime_mem == MAP_FAILED){
74 tcc_error("/tmp not executable");
75 return -1;
77 ret = tcc_relocate_ex(s1, s1->write_mem);
78 #else
79 ret = tcc_relocate_ex(s1, NULL);
80 if (-1 != ret) {
81 s1->runtime_mem = tcc_malloc(ret);
82 ret = tcc_relocate_ex(s1, s1->runtime_mem);
84 #endif
85 return ret;
88 /* launch the compiled program with the given arguments */
89 LIBTCCAPI int tcc_run(TCCState *s1, int argc, char **argv)
91 int (*prog_main)(int, char **);
92 int ret;
94 if (tcc_relocate(s1, TCC_RELOCATE_AUTO) < 0)
95 return -1;
97 prog_main = tcc_get_symbol_err(s1, "main");
99 #ifdef CONFIG_TCC_BACKTRACE
100 if (s1->do_debug) {
101 set_exception_handler();
102 rt_prog_main = prog_main;
104 #endif
106 #ifdef CONFIG_TCC_BCHECK
107 if (s1->do_bounds_check) {
108 void (*bound_init)(void);
109 void (*bound_exit)(void);
110 /* set error function */
111 rt_bound_error_msg = tcc_get_symbol_err(s1, "__bound_error_msg");
112 /* XXX: use .init section so that it also work in binary ? */
113 bound_init = tcc_get_symbol_err(s1, "__bound_init");
114 bound_exit = tcc_get_symbol_err(s1, "__bound_exit");
115 bound_init();
116 ret = (*prog_main)(argc, argv);
117 bound_exit();
118 } else
119 #endif
120 ret = (*prog_main)(argc, argv);
121 return ret;
124 /* relocate code. Return -1 on error, required size if ptr is NULL,
125 otherwise copy code into buffer passed by the caller */
126 static int tcc_relocate_ex(TCCState *s1, void *ptr)
128 Section *s;
129 unsigned long offset, length;
130 uplong mem;
131 int i;
133 if (0 == s1->runtime_added) {
134 s1->runtime_added = 1;
135 s1->nb_errors = 0;
136 #ifdef TCC_TARGET_PE
137 pe_output_file(s1, NULL);
138 #else
139 tcc_add_runtime(s1);
140 relocate_common_syms();
141 tcc_add_linker_symbols(s1);
142 build_got_entries(s1);
143 #endif
144 if (s1->nb_errors)
145 return -1;
148 offset = 0, mem = (uplong)ptr;
149 for(i = 1; i < s1->nb_sections; i++) {
150 s = s1->sections[i];
151 if (0 == (s->sh_flags & SHF_ALLOC))
152 continue;
153 length = s->data_offset;
154 s->sh_addr = mem ? (mem + offset + 15) & ~15 : 0;
155 offset = (offset + length + 15) & ~15;
157 offset += 16;
159 /* relocate symbols */
160 relocate_syms(s1, 1);
161 if (s1->nb_errors)
162 return -1;
164 #if (defined TCC_TARGET_X86_64 || defined TCC_TARGET_ARM) && !defined TCC_TARGET_PE
165 s1->runtime_plt_and_got_offset = 0;
166 s1->runtime_plt_and_got = (char *)(mem + offset);
167 /* double the size of the buffer for got and plt entries
168 XXX: calculate exact size for them? */
169 offset *= 2;
170 #endif
172 if (0 == mem)
173 return offset;
175 /* relocate each section */
176 for(i = 1; i < s1->nb_sections; i++) {
177 s = s1->sections[i];
178 if (s->reloc)
179 relocate_section(s1, s);
182 for(i = 1; i < s1->nb_sections; i++) {
183 s = s1->sections[i];
184 if (0 == (s->sh_flags & SHF_ALLOC))
185 continue;
186 length = s->data_offset;
187 // printf("%-12s %08x %04x\n", s->name, s->sh_addr, length);
188 ptr = (void*)(uplong)s->sh_addr;
189 if (NULL == s->data || s->sh_type == SHT_NOBITS)
190 memset(ptr, 0, length);
191 else
192 memcpy(ptr, s->data, length);
193 /* mark executable sections as executable in memory */
194 if (s->sh_flags & SHF_EXECINSTR)
195 set_pages_executable(ptr, length);
198 #if (defined TCC_TARGET_X86_64 || defined TCC_TARGET_ARM) && !defined TCC_TARGET_PE
199 set_pages_executable(s1->runtime_plt_and_got,
200 s1->runtime_plt_and_got_offset);
201 #endif
203 #ifdef _WIN64
204 win64_add_function_table(s1);
205 #endif
206 return 0;
209 /* ------------------------------------------------------------- */
210 /* allow to run code in memory */
212 static void set_pages_executable(void *ptr, unsigned long length)
214 #ifdef _WIN32
215 unsigned long old_protect;
216 VirtualProtect(ptr, length, PAGE_EXECUTE_READWRITE, &old_protect);
217 #else
218 unsigned long start, end;
219 start = (uplong)ptr & ~(PAGESIZE - 1);
220 end = (uplong)ptr + length;
221 end = (end + PAGESIZE - 1) & ~(PAGESIZE - 1);
222 mprotect((void *)start, end - start, PROT_READ | PROT_WRITE | PROT_EXEC);
223 #endif
226 /* ------------------------------------------------------------- */
227 #endif /* TCC_IS_NATIVE */
229 #ifdef CONFIG_TCC_BACKTRACE
231 PUB_FUNC void tcc_set_num_callers(int n)
233 rt_num_callers = n;
236 /* print the position in the source file of PC value 'pc' by reading
237 the stabs debug information */
238 static uplong rt_printline(uplong wanted_pc, const char *msg)
240 char func_name[128], last_func_name[128];
241 uplong func_addr, last_pc, pc;
242 const char *incl_files[INCLUDE_STACK_SIZE];
243 int incl_index, len, last_line_num, i;
244 const char *str, *p;
246 Stab_Sym *stab_sym = NULL, *stab_sym_end, *sym;
247 int stab_len = 0;
248 char *stab_str = NULL;
250 if (stab_section) {
251 stab_len = stab_section->data_offset;
252 stab_sym = (Stab_Sym *)stab_section->data;
253 stab_str = stabstr_section->data;
256 func_name[0] = '\0';
257 func_addr = 0;
258 incl_index = 0;
259 last_func_name[0] = '\0';
260 last_pc = (uplong)-1;
261 last_line_num = 1;
263 if (!stab_sym)
264 goto no_stabs;
266 stab_sym_end = (Stab_Sym*)((char*)stab_sym + stab_len);
267 for (sym = stab_sym + 1; sym < stab_sym_end; ++sym) {
268 switch(sym->n_type) {
269 /* function start or end */
270 case N_FUN:
271 if (sym->n_strx == 0) {
272 /* we test if between last line and end of function */
273 pc = sym->n_value + func_addr;
274 if (wanted_pc >= last_pc && wanted_pc < pc)
275 goto found;
276 func_name[0] = '\0';
277 func_addr = 0;
278 } else {
279 str = stab_str + sym->n_strx;
280 p = strchr(str, ':');
281 if (!p) {
282 pstrcpy(func_name, sizeof(func_name), str);
283 } else {
284 len = p - str;
285 if (len > sizeof(func_name) - 1)
286 len = sizeof(func_name) - 1;
287 memcpy(func_name, str, len);
288 func_name[len] = '\0';
290 func_addr = sym->n_value;
292 break;
293 /* line number info */
294 case N_SLINE:
295 pc = sym->n_value + func_addr;
296 if (wanted_pc >= last_pc && wanted_pc < pc)
297 goto found;
298 last_pc = pc;
299 last_line_num = sym->n_desc;
300 /* XXX: slow! */
301 strcpy(last_func_name, func_name);
302 break;
303 /* include files */
304 case N_BINCL:
305 str = stab_str + sym->n_strx;
306 add_incl:
307 if (incl_index < INCLUDE_STACK_SIZE) {
308 incl_files[incl_index++] = str;
310 break;
311 case N_EINCL:
312 if (incl_index > 1)
313 incl_index--;
314 break;
315 case N_SO:
316 if (sym->n_strx == 0) {
317 incl_index = 0; /* end of translation unit */
318 } else {
319 str = stab_str + sym->n_strx;
320 /* do not add path */
321 len = strlen(str);
322 if (len > 0 && str[len - 1] != '/')
323 goto add_incl;
325 break;
329 no_stabs:
330 /* second pass: we try symtab symbols (no line number info) */
331 incl_index = 0;
332 if (symtab_section)
334 ElfW(Sym) *sym, *sym_end;
335 int type;
337 sym_end = (ElfW(Sym) *)(symtab_section->data + symtab_section->data_offset);
338 for(sym = (ElfW(Sym) *)symtab_section->data + 1;
339 sym < sym_end;
340 sym++) {
341 type = ELFW(ST_TYPE)(sym->st_info);
342 if (type == STT_FUNC || type == STT_GNU_IFUNC) {
343 if (wanted_pc >= sym->st_value &&
344 wanted_pc < sym->st_value + sym->st_size) {
345 pstrcpy(last_func_name, sizeof(last_func_name),
346 strtab_section->data + sym->st_name);
347 func_addr = sym->st_value;
348 goto found;
353 /* did not find any info: */
354 fprintf(stderr, "%s %p ???\n", msg, (void*)wanted_pc);
355 fflush(stderr);
356 return 0;
357 found:
358 i = incl_index;
359 if (i > 0)
360 fprintf(stderr, "%s:%d: ", incl_files[--i], last_line_num);
361 fprintf(stderr, "%s %p", msg, (void*)wanted_pc);
362 if (last_func_name[0] != '\0')
363 fprintf(stderr, " %s()", last_func_name);
364 if (--i >= 0) {
365 fprintf(stderr, " (included from ");
366 for (;;) {
367 fprintf(stderr, "%s", incl_files[i]);
368 if (--i < 0)
369 break;
370 fprintf(stderr, ", ");
372 fprintf(stderr, ")");
374 fprintf(stderr, "\n");
375 fflush(stderr);
376 return func_addr;
379 /* emit a run time error at position 'pc' */
380 static void rt_error(ucontext_t *uc, const char *fmt, ...)
382 va_list ap;
383 uplong pc;
384 int i;
386 fprintf(stderr, "Runtime error: ");
387 va_start(ap, fmt);
388 vfprintf(stderr, fmt, ap);
389 va_end(ap);
390 fprintf(stderr, "\n");
392 for(i=0;i<rt_num_callers;i++) {
393 if (rt_get_caller_pc(&pc, uc, i) < 0)
394 break;
395 pc = rt_printline(pc, i ? "by" : "at");
396 if (pc == (uplong)rt_prog_main && pc)
397 break;
401 /* ------------------------------------------------------------- */
402 #ifndef _WIN32
404 /* signal handler for fatal errors */
405 static void sig_error(int signum, siginfo_t *siginf, void *puc)
407 ucontext_t *uc = puc;
409 switch(signum) {
410 case SIGFPE:
411 switch(siginf->si_code) {
412 case FPE_INTDIV:
413 case FPE_FLTDIV:
414 rt_error(uc, "division by zero");
415 break;
416 default:
417 rt_error(uc, "floating point exception");
418 break;
420 break;
421 case SIGBUS:
422 case SIGSEGV:
423 if (rt_bound_error_msg && *rt_bound_error_msg)
424 rt_error(uc, *rt_bound_error_msg);
425 else
426 rt_error(uc, "dereferencing invalid pointer");
427 break;
428 case SIGILL:
429 rt_error(uc, "illegal instruction");
430 break;
431 case SIGABRT:
432 rt_error(uc, "abort() called");
433 break;
434 default:
435 rt_error(uc, "caught signal %d", signum);
436 break;
438 exit(255);
441 /* Generate a stack backtrace when a CPU exception occurs. */
442 static void set_exception_handler(void)
444 struct sigaction sigact;
445 /* install TCC signal handlers to print debug info on fatal
446 runtime errors */
447 sigact.sa_flags = SA_SIGINFO | SA_RESETHAND;
448 sigact.sa_sigaction = sig_error;
449 sigemptyset(&sigact.sa_mask);
450 sigaction(SIGFPE, &sigact, NULL);
451 sigaction(SIGILL, &sigact, NULL);
452 sigaction(SIGSEGV, &sigact, NULL);
453 sigaction(SIGBUS, &sigact, NULL);
454 sigaction(SIGABRT, &sigact, NULL);
457 /* ------------------------------------------------------------- */
458 #ifdef __i386__
460 /* fix for glibc 2.1 */
461 #ifndef REG_EIP
462 #define REG_EIP EIP
463 #define REG_EBP EBP
464 #endif
466 /* return the PC at frame level 'level'. Return non zero if not found */
467 static int rt_get_caller_pc(unsigned long *paddr, ucontext_t *uc, int level)
469 unsigned long fp;
470 int i;
472 if (level == 0) {
473 #if defined(__APPLE__)
474 *paddr = uc->uc_mcontext->__ss.__eip;
475 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
476 *paddr = uc->uc_mcontext.mc_eip;
477 #elif defined(__dietlibc__)
478 *paddr = uc->uc_mcontext.eip;
479 #else
480 *paddr = uc->uc_mcontext.gregs[REG_EIP];
481 #endif
482 return 0;
483 } else {
484 #if defined(__APPLE__)
485 fp = uc->uc_mcontext->__ss.__ebp;
486 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
487 fp = uc->uc_mcontext.mc_ebp;
488 #elif defined(__dietlibc__)
489 fp = uc->uc_mcontext.ebp;
490 #else
491 fp = uc->uc_mcontext.gregs[REG_EBP];
492 #endif
493 for(i=1;i<level;i++) {
494 /* XXX: check address validity with program info */
495 if (fp <= 0x1000 || fp >= 0xc0000000)
496 return -1;
497 fp = ((unsigned long *)fp)[0];
499 *paddr = ((unsigned long *)fp)[1];
500 return 0;
504 /* ------------------------------------------------------------- */
505 #elif defined(__x86_64__)
507 /* return the PC at frame level 'level'. Return non zero if not found */
508 static int rt_get_caller_pc(unsigned long *paddr,
509 ucontext_t *uc, int level)
511 unsigned long fp;
512 int i;
514 if (level == 0) {
515 /* XXX: only support linux */
516 #if defined(__APPLE__)
517 *paddr = uc->uc_mcontext->__ss.__rip;
518 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
519 *paddr = uc->uc_mcontext.mc_rip;
520 #else
521 *paddr = uc->uc_mcontext.gregs[REG_RIP];
522 #endif
523 return 0;
524 } else {
525 #if defined(__APPLE__)
526 fp = uc->uc_mcontext->__ss.__rbp;
527 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
528 fp = uc->uc_mcontext.mc_rbp;
529 #else
530 fp = uc->uc_mcontext.gregs[REG_RBP];
531 #endif
532 for(i=1;i<level;i++) {
533 /* XXX: check address validity with program info */
534 if (fp <= 0x1000)
535 return -1;
536 fp = ((unsigned long *)fp)[0];
538 *paddr = ((unsigned long *)fp)[1];
539 return 0;
543 /* ------------------------------------------------------------- */
544 #elif defined(__arm__)
546 /* return the PC at frame level 'level'. Return negative if not found */
547 static int rt_get_caller_pc(unsigned long *paddr,
548 ucontext_t *uc, int level)
550 uint32_t fp, sp;
551 int i;
553 if (level == 0) {
554 /* XXX: only supports linux */
555 #if defined(__linux__)
556 *paddr = uc->uc_mcontext.arm_pc;
557 #else
558 return -1;
559 #endif
560 return 0;
561 } else {
562 #if defined(__linux__)
563 fp = uc->uc_mcontext.arm_fp;
564 sp = uc->uc_mcontext.arm_sp;
565 if (sp < 0x1000)
566 sp = 0x1000;
567 #else
568 return -1;
569 #endif
570 /* XXX: specific to tinycc stack frames */
571 if (fp < sp + 12 || fp & 3)
572 return -1;
573 for(i = 1; i < level; i++) {
574 sp = ((uint32_t *)fp)[-2];
575 if (sp < fp || sp - fp > 16 || sp & 3)
576 return -1;
577 fp = ((uint32_t *)fp)[-3];
578 if (fp <= sp || fp - sp < 12 || fp & 3)
579 return -1;
581 /* XXX: check address validity with program info */
582 *paddr = ((uint32_t *)fp)[-1];
583 return 0;
587 /* ------------------------------------------------------------- */
588 #else
590 #warning add arch specific rt_get_caller_pc()
591 static int rt_get_caller_pc(unsigned long *paddr,
592 ucontext_t *uc, int level)
594 return -1;
597 #endif /* !__i386__ */
599 /* ------------------------------------------------------------- */
600 #else /* WIN32 */
602 static long __stdcall cpu_exception_handler(EXCEPTION_POINTERS *ex_info)
604 EXCEPTION_RECORD *er = ex_info->ExceptionRecord;
605 CONTEXT *uc = ex_info->ContextRecord;
606 switch (er->ExceptionCode) {
607 case EXCEPTION_ACCESS_VIOLATION:
608 if (rt_bound_error_msg && *rt_bound_error_msg)
609 rt_error(uc, *rt_bound_error_msg);
610 else
611 rt_error(uc, "access violation");
612 break;
613 case EXCEPTION_STACK_OVERFLOW:
614 rt_error(uc, "stack overflow");
615 break;
616 case EXCEPTION_INT_DIVIDE_BY_ZERO:
617 rt_error(uc, "division by zero");
618 break;
619 default:
620 rt_error(uc, "exception caught");
621 break;
623 exit(-1);
624 return EXCEPTION_CONTINUE_SEARCH;
627 /* Generate a stack backtrace when a CPU exception occurs. */
628 static void set_exception_handler(void)
630 SetUnhandledExceptionFilter(cpu_exception_handler);
633 #ifdef _WIN64
634 static void win64_add_function_table(TCCState *s1)
636 RtlAddFunctionTable(
637 (RUNTIME_FUNCTION*)(uplong)s1->uw_pdata->sh_addr,
638 s1->uw_pdata->data_offset / sizeof (RUNTIME_FUNCTION),
639 (uplong)text_section->sh_addr
642 #endif
644 /* return the PC at frame level 'level'. Return non zero if not found */
645 static int rt_get_caller_pc(uplong *paddr, CONTEXT *uc, int level)
647 uplong fp, pc;
648 int i;
649 #ifdef _WIN64
650 pc = uc->Rip;
651 fp = uc->Rbp;
652 #else
653 pc = uc->Eip;
654 fp = uc->Ebp;
655 #endif
656 if (level > 0) {
657 for(i=1;i<level;i++) {
658 /* XXX: check address validity with program info */
659 if (fp <= 0x1000 || fp >= 0xc0000000)
660 return -1;
661 fp = ((uplong*)fp)[0];
663 pc = ((uplong*)fp)[1];
665 *paddr = pc;
666 return 0;
669 #endif /* _WIN32 */
670 #endif /* CONFIG_TCC_BACKTRACE */
671 /* ------------------------------------------------------------- */
673 #ifdef CONFIG_TCC_STATIC
675 #define RTLD_LAZY 0x001
676 #define RTLD_NOW 0x002
677 #define RTLD_GLOBAL 0x100
678 #define RTLD_DEFAULT NULL
680 /* dummy function for profiling */
681 ST_FUNC void *dlopen(const char *filename, int flag)
683 return NULL;
686 ST_FUNC void dlclose(void *p)
690 const char *dlerror(void)
692 return "error";
695 typedef struct TCCSyms {
696 char *str;
697 void *ptr;
698 } TCCSyms;
700 #define TCCSYM(a) { #a, &a, },
702 /* add the symbol you want here if no dynamic linking is done */
703 static TCCSyms tcc_syms[] = {
704 #if !defined(CONFIG_TCCBOOT)
705 TCCSYM(printf)
706 TCCSYM(fprintf)
707 TCCSYM(fopen)
708 TCCSYM(fclose)
709 #endif
710 { NULL, NULL },
713 ST_FUNC void *resolve_sym(TCCState *s1, const char *symbol)
715 TCCSyms *p;
716 p = tcc_syms;
717 while (p->str != NULL) {
718 if (!strcmp(p->str, symbol))
719 return p->ptr;
720 p++;
722 return NULL;
725 #elif !defined(_WIN32)
727 ST_FUNC void *resolve_sym(TCCState *s1, const char *sym)
729 return dlsym(RTLD_DEFAULT, sym);
732 #endif /* CONFIG_TCC_STATIC */
734 /* ------------------------------------------------------------- */