Add macro to browse reloc and sym entries
[tinycc.git] / tccrun.c
blob55fb3d8147a1c3b2530d432286dc8cc3b430047a
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. Ref:
63 http://www.gnu.org/s/libc/manual/html_node/File-Size.html */
65 char tmpfname[] = "/tmp/.tccrunXXXXXX";
66 int fd = mkstemp (tmpfname);
68 s1->mem_size = ret;
69 unlink (tmpfname);
70 ftruncate (fd, s1->mem_size);
72 s1->write_mem = mmap (NULL, ret, PROT_READ|PROT_WRITE,
73 MAP_SHARED, fd, 0);
74 if (s1->write_mem == MAP_FAILED)
75 tcc_error("/tmp not writeable");
77 s1->runtime_mem = mmap (NULL, ret, PROT_READ|PROT_EXEC,
78 MAP_SHARED, fd, 0);
79 if (s1->runtime_mem == MAP_FAILED)
80 tcc_error("/tmp not executable");
82 ret = tcc_relocate_ex(s1, s1->write_mem);
84 #else
85 s1->runtime_mem = tcc_malloc(ret);
86 ret = tcc_relocate_ex(s1, s1->runtime_mem);
87 #endif
88 return ret;
91 /* launch the compiled program with the given arguments */
92 LIBTCCAPI int tcc_run(TCCState *s1, int argc, char **argv)
94 int (*prog_main)(int, char **);
95 int ret;
97 if (tcc_relocate(s1, TCC_RELOCATE_AUTO) < 0)
98 return -1;
100 prog_main = tcc_get_symbol_err(s1, s1->runtime_main);
102 #ifdef CONFIG_TCC_BACKTRACE
103 if (s1->do_debug) {
104 set_exception_handler();
105 rt_prog_main = prog_main;
107 #endif
109 #ifdef CONFIG_TCC_BCHECK
110 if (s1->do_bounds_check) {
111 void (*bound_init)(void);
112 void (*bound_exit)(void);
113 void (*bound_new_region)(void *p, unsigned long size);
114 int (*bound_delete_region)(void *p);
115 int i;
117 /* set error function */
118 rt_bound_error_msg = tcc_get_symbol_err(s1, "__bound_error_msg");
119 /* XXX: use .init section so that it also work in binary ? */
120 bound_init = tcc_get_symbol_err(s1, "__bound_init");
121 bound_exit = tcc_get_symbol_err(s1, "__bound_exit");
122 bound_new_region = tcc_get_symbol_err(s1, "__bound_new_region");
123 bound_delete_region = tcc_get_symbol_err(s1, "__bound_delete_region");
124 bound_init();
125 /* mark argv area as valid */
126 bound_new_region(argv, argc*sizeof(argv[0]));
127 for (i=0; i<argc; ++i)
128 bound_new_region(argv[i], strlen(argv[i]));
130 ret = (*prog_main)(argc, argv);
132 /* unmark argv area */
133 for (i=0; i<argc; ++i)
134 bound_delete_region(argv[i]);
135 bound_delete_region(argv);
137 bound_exit();
138 } else
139 #endif
140 ret = (*prog_main)(argc, argv);
141 return ret;
144 /* relocate code. Return -1 on error, required size if ptr is NULL,
145 otherwise copy code into buffer passed by the caller */
146 static int tcc_relocate_ex(TCCState *s1, void *ptr)
148 Section *s;
149 unsigned long offset, length;
150 addr_t mem;
151 int i;
153 if (NULL == ptr) {
154 s1->nb_errors = 0;
155 #ifdef TCC_TARGET_PE
156 pe_output_file(s1, NULL);
157 #else
158 tcc_add_runtime(s1);
159 relocate_common_syms();
160 tcc_add_linker_symbols(s1);
161 build_got_entries(s1);
162 #endif
163 if (s1->nb_errors)
164 return -1;
167 offset = 0, mem = (addr_t)ptr;
168 for(i = 1; i < s1->nb_sections; i++) {
169 s = s1->sections[i];
170 if (0 == (s->sh_flags & SHF_ALLOC))
171 continue;
172 length = s->data_offset;
173 s->sh_addr = mem ? (mem + offset + 15) & ~15 : 0;
174 offset = (offset + length + 15) & ~15;
176 offset += 16;
178 /* relocate symbols */
179 relocate_syms(s1, 1);
180 if (s1->nb_errors)
181 return -1;
183 #ifdef TCC_HAS_RUNTIME_PLTGOT
184 s1->runtime_plt_and_got_offset = 0;
185 s1->runtime_plt_and_got = (char *)(mem + offset);
186 /* double the size of the buffer for got and plt entries
187 XXX: calculate exact size for them? */
188 offset *= 2;
189 #endif
191 if (0 == mem)
192 return offset;
194 /* relocate each section */
195 for(i = 1; i < s1->nb_sections; i++) {
196 s = s1->sections[i];
197 if (s->reloc)
198 relocate_section(s1, s);
201 for(i = 1; i < s1->nb_sections; i++) {
202 s = s1->sections[i];
203 if (0 == (s->sh_flags & SHF_ALLOC))
204 continue;
205 length = s->data_offset;
206 // printf("%-12s %08x %04x\n", s->name, s->sh_addr, length);
207 ptr = (void*)s->sh_addr;
208 if (NULL == s->data || s->sh_type == SHT_NOBITS)
209 memset(ptr, 0, length);
210 else
211 memcpy(ptr, s->data, length);
212 /* mark executable sections as executable in memory */
213 if (s->sh_flags & SHF_EXECINSTR)
214 set_pages_executable(ptr, length);
217 #ifdef TCC_HAS_RUNTIME_PLTGOT
218 set_pages_executable(s1->runtime_plt_and_got,
219 s1->runtime_plt_and_got_offset);
220 #endif
222 #ifdef _WIN64
223 win64_add_function_table(s1);
224 #endif
225 return 0;
228 /* ------------------------------------------------------------- */
229 /* allow to run code in memory */
231 static void set_pages_executable(void *ptr, unsigned long length)
233 #ifdef _WIN32
234 unsigned long old_protect;
235 VirtualProtect(ptr, length, PAGE_EXECUTE_READWRITE, &old_protect);
236 #else
237 #ifndef PAGESIZE
238 # define PAGESIZE 4096
239 #endif
240 addr_t start, end;
241 start = (addr_t)ptr & ~(PAGESIZE - 1);
242 end = (addr_t)ptr + length;
243 end = (end + PAGESIZE - 1) & ~(PAGESIZE - 1);
244 mprotect((void *)start, end - start, PROT_READ | PROT_WRITE | PROT_EXEC);
245 __clear_cache(ptr, ptr + length);
246 #endif
249 /* ------------------------------------------------------------- */
250 #ifdef CONFIG_TCC_BACKTRACE
252 ST_FUNC void tcc_set_num_callers(int n)
254 rt_num_callers = n;
257 /* print the position in the source file of PC value 'pc' by reading
258 the stabs debug information */
259 static addr_t rt_printline(addr_t wanted_pc, const char *msg)
261 char func_name[128], last_func_name[128];
262 addr_t func_addr, last_pc, pc;
263 const char *incl_files[INCLUDE_STACK_SIZE];
264 int incl_index, len, last_line_num, i;
265 const char *str, *p;
267 Stab_Sym *stab_sym = NULL, *stab_sym_end, *sym;
268 int stab_len = 0;
269 char *stab_str = NULL;
271 if (stab_section) {
272 stab_len = stab_section->data_offset;
273 stab_sym = (Stab_Sym *)stab_section->data;
274 stab_str = stabstr_section->data;
277 func_name[0] = '\0';
278 func_addr = 0;
279 incl_index = 0;
280 last_func_name[0] = '\0';
281 last_pc = (addr_t)-1;
282 last_line_num = 1;
284 if (!stab_sym)
285 goto no_stabs;
287 stab_sym_end = (Stab_Sym*)((char*)stab_sym + stab_len);
288 for (sym = stab_sym + 1; sym < stab_sym_end; ++sym) {
289 switch(sym->n_type) {
290 /* function start or end */
291 case N_FUN:
292 if (sym->n_strx == 0) {
293 /* we test if between last line and end of function */
294 pc = sym->n_value + func_addr;
295 if (wanted_pc >= last_pc && wanted_pc < pc)
296 goto found;
297 func_name[0] = '\0';
298 func_addr = 0;
299 } else {
300 str = stab_str + sym->n_strx;
301 p = strchr(str, ':');
302 if (!p) {
303 pstrcpy(func_name, sizeof(func_name), str);
304 } else {
305 len = p - str;
306 if (len > sizeof(func_name) - 1)
307 len = sizeof(func_name) - 1;
308 memcpy(func_name, str, len);
309 func_name[len] = '\0';
311 func_addr = sym->n_value;
313 break;
314 /* line number info */
315 case N_SLINE:
316 pc = sym->n_value + func_addr;
317 if (wanted_pc >= last_pc && wanted_pc < pc)
318 goto found;
319 last_pc = pc;
320 last_line_num = sym->n_desc;
321 /* XXX: slow! */
322 strcpy(last_func_name, func_name);
323 break;
324 /* include files */
325 case N_BINCL:
326 str = stab_str + sym->n_strx;
327 add_incl:
328 if (incl_index < INCLUDE_STACK_SIZE) {
329 incl_files[incl_index++] = str;
331 break;
332 case N_EINCL:
333 if (incl_index > 1)
334 incl_index--;
335 break;
336 case N_SO:
337 if (sym->n_strx == 0) {
338 incl_index = 0; /* end of translation unit */
339 } else {
340 str = stab_str + sym->n_strx;
341 /* do not add path */
342 len = strlen(str);
343 if (len > 0 && str[len - 1] != '/')
344 goto add_incl;
346 break;
350 no_stabs:
351 /* second pass: we try symtab symbols (no line number info) */
352 incl_index = 0;
353 if (symtab_section)
355 ElfW(Sym) *sym, *sym_end;
356 int type;
358 sym_end = (ElfW(Sym) *)(symtab_section->data + symtab_section->data_offset);
359 for(sym = (ElfW(Sym) *)symtab_section->data + 1;
360 sym < sym_end;
361 sym++) {
362 type = ELFW(ST_TYPE)(sym->st_info);
363 if (type == STT_FUNC || type == STT_GNU_IFUNC) {
364 if (wanted_pc >= sym->st_value &&
365 wanted_pc < sym->st_value + sym->st_size) {
366 pstrcpy(last_func_name, sizeof(last_func_name),
367 strtab_section->data + sym->st_name);
368 func_addr = sym->st_value;
369 goto found;
374 /* did not find any info: */
375 fprintf(stderr, "%s %p ???\n", msg, (void*)wanted_pc);
376 fflush(stderr);
377 return 0;
378 found:
379 i = incl_index;
380 if (i > 0)
381 fprintf(stderr, "%s:%d: ", incl_files[--i], last_line_num);
382 fprintf(stderr, "%s %p", msg, (void*)wanted_pc);
383 if (last_func_name[0] != '\0')
384 fprintf(stderr, " %s()", last_func_name);
385 if (--i >= 0) {
386 fprintf(stderr, " (included from ");
387 for (;;) {
388 fprintf(stderr, "%s", incl_files[i]);
389 if (--i < 0)
390 break;
391 fprintf(stderr, ", ");
393 fprintf(stderr, ")");
395 fprintf(stderr, "\n");
396 fflush(stderr);
397 return func_addr;
400 /* emit a run time error at position 'pc' */
401 static void rt_error(ucontext_t *uc, const char *fmt, ...)
403 va_list ap;
404 addr_t pc;
405 int i;
407 fprintf(stderr, "Runtime error: ");
408 va_start(ap, fmt);
409 vfprintf(stderr, fmt, ap);
410 va_end(ap);
411 fprintf(stderr, "\n");
413 for(i=0;i<rt_num_callers;i++) {
414 if (rt_get_caller_pc(&pc, uc, i) < 0)
415 break;
416 pc = rt_printline(pc, i ? "by" : "at");
417 if (pc == (addr_t)rt_prog_main && pc)
418 break;
422 /* ------------------------------------------------------------- */
423 #ifndef _WIN32
425 /* signal handler for fatal errors */
426 static void sig_error(int signum, siginfo_t *siginf, void *puc)
428 ucontext_t *uc = puc;
430 switch(signum) {
431 case SIGFPE:
432 switch(siginf->si_code) {
433 case FPE_INTDIV:
434 case FPE_FLTDIV:
435 rt_error(uc, "division by zero");
436 break;
437 default:
438 rt_error(uc, "floating point exception");
439 break;
441 break;
442 case SIGBUS:
443 case SIGSEGV:
444 if (rt_bound_error_msg && *rt_bound_error_msg)
445 rt_error(uc, *rt_bound_error_msg);
446 else
447 rt_error(uc, "dereferencing invalid pointer");
448 break;
449 case SIGILL:
450 rt_error(uc, "illegal instruction");
451 break;
452 case SIGABRT:
453 rt_error(uc, "abort() called");
454 break;
455 default:
456 rt_error(uc, "caught signal %d", signum);
457 break;
459 exit(255);
462 #ifndef SA_SIGINFO
463 # define SA_SIGINFO 0x00000004u
464 #endif
466 /* Generate a stack backtrace when a CPU exception occurs. */
467 static void set_exception_handler(void)
469 struct sigaction sigact;
470 /* install TCC signal handlers to print debug info on fatal
471 runtime errors */
472 sigact.sa_flags = SA_SIGINFO | SA_RESETHAND;
473 sigact.sa_sigaction = sig_error;
474 sigemptyset(&sigact.sa_mask);
475 sigaction(SIGFPE, &sigact, NULL);
476 sigaction(SIGILL, &sigact, NULL);
477 sigaction(SIGSEGV, &sigact, NULL);
478 sigaction(SIGBUS, &sigact, NULL);
479 sigaction(SIGABRT, &sigact, NULL);
482 /* ------------------------------------------------------------- */
483 #ifdef __i386__
485 /* fix for glibc 2.1 */
486 #ifndef REG_EIP
487 #define REG_EIP EIP
488 #define REG_EBP EBP
489 #endif
491 /* return the PC at frame level 'level'. Return negative if not found */
492 static int rt_get_caller_pc(addr_t *paddr, ucontext_t *uc, int level)
494 addr_t fp;
495 int i;
497 if (level == 0) {
498 #if defined(__APPLE__)
499 *paddr = uc->uc_mcontext->__ss.__eip;
500 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
501 *paddr = uc->uc_mcontext.mc_eip;
502 #elif defined(__dietlibc__)
503 *paddr = uc->uc_mcontext.eip;
504 #else
505 *paddr = uc->uc_mcontext.gregs[REG_EIP];
506 #endif
507 return 0;
508 } else {
509 #if defined(__APPLE__)
510 fp = uc->uc_mcontext->__ss.__ebp;
511 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
512 fp = uc->uc_mcontext.mc_ebp;
513 #elif defined(__dietlibc__)
514 fp = uc->uc_mcontext.ebp;
515 #else
516 fp = uc->uc_mcontext.gregs[REG_EBP];
517 #endif
518 for(i=1;i<level;i++) {
519 /* XXX: check address validity with program info */
520 if (fp <= 0x1000 || fp >= 0xc0000000)
521 return -1;
522 fp = ((addr_t *)fp)[0];
524 *paddr = ((addr_t *)fp)[1];
525 return 0;
529 /* ------------------------------------------------------------- */
530 #elif defined(__x86_64__)
532 /* return the PC at frame level 'level'. Return negative if not found */
533 static int rt_get_caller_pc(addr_t *paddr, ucontext_t *uc, int level)
535 addr_t fp;
536 int i;
538 if (level == 0) {
539 /* XXX: only support linux */
540 #if defined(__APPLE__)
541 *paddr = uc->uc_mcontext->__ss.__rip;
542 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
543 *paddr = uc->uc_mcontext.mc_rip;
544 #else
545 *paddr = uc->uc_mcontext.gregs[REG_RIP];
546 #endif
547 return 0;
548 } else {
549 #if defined(__APPLE__)
550 fp = uc->uc_mcontext->__ss.__rbp;
551 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
552 fp = uc->uc_mcontext.mc_rbp;
553 #else
554 fp = uc->uc_mcontext.gregs[REG_RBP];
555 #endif
556 for(i=1;i<level;i++) {
557 /* XXX: check address validity with program info */
558 if (fp <= 0x1000)
559 return -1;
560 fp = ((addr_t *)fp)[0];
562 *paddr = ((addr_t *)fp)[1];
563 return 0;
567 /* ------------------------------------------------------------- */
568 #elif defined(__arm__)
570 /* return the PC at frame level 'level'. Return negative if not found */
571 static int rt_get_caller_pc(addr_t *paddr, ucontext_t *uc, int level)
573 addr_t fp, sp;
574 int i;
576 if (level == 0) {
577 /* XXX: only supports linux */
578 #if defined(__linux__)
579 *paddr = uc->uc_mcontext.arm_pc;
580 #else
581 return -1;
582 #endif
583 return 0;
584 } else {
585 #if defined(__linux__)
586 fp = uc->uc_mcontext.arm_fp;
587 sp = uc->uc_mcontext.arm_sp;
588 if (sp < 0x1000)
589 sp = 0x1000;
590 #else
591 return -1;
592 #endif
593 /* XXX: specific to tinycc stack frames */
594 if (fp < sp + 12 || fp & 3)
595 return -1;
596 for(i = 1; i < level; i++) {
597 sp = ((addr_t *)fp)[-2];
598 if (sp < fp || sp - fp > 16 || sp & 3)
599 return -1;
600 fp = ((addr_t *)fp)[-3];
601 if (fp <= sp || fp - sp < 12 || fp & 3)
602 return -1;
604 /* XXX: check address validity with program info */
605 *paddr = ((addr_t *)fp)[-1];
606 return 0;
610 /* ------------------------------------------------------------- */
611 #else
613 #warning add arch specific rt_get_caller_pc()
614 static int rt_get_caller_pc(addr_t *paddr, ucontext_t *uc, int level)
616 return -1;
619 #endif /* !__i386__ */
621 /* ------------------------------------------------------------- */
622 #else /* WIN32 */
624 static long __stdcall cpu_exception_handler(EXCEPTION_POINTERS *ex_info)
626 EXCEPTION_RECORD *er = ex_info->ExceptionRecord;
627 CONTEXT *uc = ex_info->ContextRecord;
628 switch (er->ExceptionCode) {
629 case EXCEPTION_ACCESS_VIOLATION:
630 if (rt_bound_error_msg && *rt_bound_error_msg)
631 rt_error(uc, *rt_bound_error_msg);
632 else
633 rt_error(uc, "access violation");
634 break;
635 case EXCEPTION_STACK_OVERFLOW:
636 rt_error(uc, "stack overflow");
637 break;
638 case EXCEPTION_INT_DIVIDE_BY_ZERO:
639 rt_error(uc, "division by zero");
640 break;
641 default:
642 rt_error(uc, "exception caught");
643 break;
645 return EXCEPTION_EXECUTE_HANDLER;
648 /* Generate a stack backtrace when a CPU exception occurs. */
649 static void set_exception_handler(void)
651 SetUnhandledExceptionFilter(cpu_exception_handler);
654 #ifdef _WIN64
655 static void win64_add_function_table(TCCState *s1)
657 RtlAddFunctionTable(
658 (RUNTIME_FUNCTION*)s1->uw_pdata->sh_addr,
659 s1->uw_pdata->data_offset / sizeof (RUNTIME_FUNCTION),
660 text_section->sh_addr
663 #endif
665 /* return the PC at frame level 'level'. Return non zero if not found */
666 static int rt_get_caller_pc(addr_t *paddr, CONTEXT *uc, int level)
668 addr_t fp, pc;
669 int i;
670 #ifdef _WIN64
671 pc = uc->Rip;
672 fp = uc->Rbp;
673 #else
674 pc = uc->Eip;
675 fp = uc->Ebp;
676 #endif
677 if (level > 0) {
678 for(i=1;i<level;i++) {
679 /* XXX: check address validity with program info */
680 if (fp <= 0x1000 || fp >= 0xc0000000)
681 return -1;
682 fp = ((addr_t*)fp)[0];
684 pc = ((addr_t*)fp)[1];
686 *paddr = pc;
687 return 0;
690 #endif /* _WIN32 */
691 #endif /* CONFIG_TCC_BACKTRACE */
692 /* ------------------------------------------------------------- */
693 #ifdef CONFIG_TCC_STATIC
695 /* dummy function for profiling */
696 ST_FUNC void *dlopen(const char *filename, int flag)
698 return NULL;
701 ST_FUNC void dlclose(void *p)
705 ST_FUNC const char *dlerror(void)
707 return "error";
710 typedef struct TCCSyms {
711 char *str;
712 void *ptr;
713 } TCCSyms;
716 /* add the symbol you want here if no dynamic linking is done */
717 static TCCSyms tcc_syms[] = {
718 #if !defined(CONFIG_TCCBOOT)
719 #define TCCSYM(a) { #a, &a, },
720 TCCSYM(printf)
721 TCCSYM(fprintf)
722 TCCSYM(fopen)
723 TCCSYM(fclose)
724 #undef TCCSYM
725 #endif
726 { NULL, NULL },
729 ST_FUNC void *resolve_sym(TCCState *s1, const char *symbol)
731 TCCSyms *p;
732 p = tcc_syms;
733 while (p->str != NULL) {
734 if (!strcmp(p->str, symbol))
735 return p->ptr;
736 p++;
738 return NULL;
741 #elif !defined(_WIN32)
743 ST_FUNC void *resolve_sym(TCCState *s1, const char *sym)
745 return dlsym(RTLD_DEFAULT, sym);
748 #endif /* CONFIG_TCC_STATIC */
749 #endif /* TCC_IS_NATIVE */
750 /* ------------------------------------------------------------- */