tccrun: improve rt_printline output format
[tinycc.git] / tccrun.c
blob95b823e875a8f93fe53e618f75877ccec2ca1aa4
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 #ifdef _WIN32
24 #define ucontext_t CONTEXT
25 #endif
27 static void set_pages_executable(void *ptr, unsigned long length);
28 static void set_exception_handler(void);
29 static int rt_get_caller_pc(uplong *paddr, ucontext_t *uc, int level);
30 static void rt_error(ucontext_t *uc, const char *fmt, ...);
31 static int tcc_relocate_ex(TCCState *s1, void *ptr);
33 #ifdef _WIN64
34 static void win64_add_function_table(TCCState *s1);
35 #endif
37 /* ------------------------------------------------------------- */
38 /* Do all relocations (needed before using tcc_get_symbol())
39 Returns -1 on error. */
41 int tcc_relocate(TCCState *s1)
43 int ret;
44 #ifdef HAVE_SELINUX
45 /* Use mmap instead of malloc for Selinux
46 Ref http://www.gnu.org/s/libc/manual/html_node/File-Size.html */
47 char tmpfname[] = "/tmp/.tccrunXXXXXX";
48 int fd = mkstemp (tmpfname);
49 if ((ret= tcc_relocate_ex(s1,NULL)) < 0)return -1;
50 s1->mem_size=ret;
51 unlink (tmpfname); ftruncate (fd, s1->mem_size);
52 s1->write_mem = mmap (NULL, ret, PROT_READ|PROT_WRITE,
53 MAP_SHARED, fd, 0);
54 if(s1->write_mem == MAP_FAILED){
55 error("/tmp not writeable");
56 return -1;
58 s1->runtime_mem = mmap (NULL, ret, PROT_READ|PROT_EXEC,
59 MAP_SHARED, fd, 0);
60 if(s1->runtime_mem == MAP_FAILED){
61 error("/tmp not executable");
62 return -1;
64 ret = tcc_relocate_ex(s1, s1->write_mem);
65 #else
66 ret = tcc_relocate_ex(s1, NULL);
67 if (-1 != ret) {
68 s1->runtime_mem = tcc_malloc(ret);
69 ret = tcc_relocate_ex(s1, s1->runtime_mem);
71 #endif
72 return ret;
75 /* launch the compiled program with the given arguments */
76 int tcc_run(TCCState *s1, int argc, char **argv)
78 int (*prog_main)(int, char **);
80 if (tcc_relocate(s1) < 0)
81 return -1;
83 prog_main = tcc_get_symbol_err(s1, "main");
85 #ifdef CONFIG_TCC_BACKTRACE
86 if (s1->do_debug)
87 set_exception_handler();
88 #endif
90 #ifdef CONFIG_TCC_BCHECK
91 if (s1->do_bounds_check) {
92 void (*bound_init)(void);
93 void (*bound_exit)(void);
94 int ret;
95 /* set error function */
96 rt_bound_error_msg = tcc_get_symbol_err(s1, "__bound_error_msg");
97 rt_prog_main = prog_main;
98 /* XXX: use .init section so that it also work in binary ? */
99 bound_init = tcc_get_symbol_err(s1, "__bound_init");
100 bound_exit = tcc_get_symbol_err(s1, "__bound_exit");
101 bound_init();
102 ret = (*prog_main)(argc, argv);
103 bound_exit();
104 return ret;
106 #endif
108 #ifdef TCC_TARGET_PE
110 unsigned char *p = tcc_get_symbol(s1, "tinyc_no_getbp");
111 if (p) *p = 0;
113 #endif
114 return (*prog_main)(argc, argv);
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 uplong mem;
125 int i;
127 if (0 == s1->runtime_added) {
128 s1->runtime_added = 1;
129 s1->nb_errors = 0;
130 #ifdef TCC_TARGET_PE
131 pe_output_file(s1, NULL);
132 #else
133 tcc_add_runtime(s1);
134 relocate_common_syms();
135 tcc_add_linker_symbols(s1);
136 build_got_entries(s1);
137 #endif
138 if (s1->nb_errors)
139 return -1;
142 offset = 0, mem = (uplong)ptr;
143 for(i = 1; i < s1->nb_sections; i++) {
144 s = s1->sections[i];
145 if (0 == (s->sh_flags & SHF_ALLOC))
146 continue;
147 length = s->data_offset;
148 s->sh_addr = mem ? (mem + offset + 15) & ~15 : 0;
149 offset = (offset + length + 15) & ~15;
151 offset += 16;
153 /* relocate symbols */
154 relocate_syms(s1, 1);
155 if (s1->nb_errors)
156 return -1;
158 #if (defined TCC_TARGET_X86_64 || defined TCC_TARGET_ARM) && !defined TCC_TARGET_PE
159 s1->runtime_plt_and_got_offset = 0;
160 s1->runtime_plt_and_got = (char *)(mem + offset);
161 /* double the size of the buffer for got and plt entries
162 XXX: calculate exact size for them? */
163 offset *= 2;
164 #endif
166 if (0 == mem)
167 return offset;
169 /* relocate each section */
170 for(i = 1; i < s1->nb_sections; i++) {
171 s = s1->sections[i];
172 if (s->reloc)
173 relocate_section(s1, s);
176 for(i = 1; i < s1->nb_sections; i++) {
177 s = s1->sections[i];
178 if (0 == (s->sh_flags & SHF_ALLOC))
179 continue;
180 length = s->data_offset;
181 // printf("%-12s %08x %04x\n", s->name, s->sh_addr, length);
182 ptr = (void*)(uplong)s->sh_addr;
183 if (NULL == s->data || s->sh_type == SHT_NOBITS)
184 memset(ptr, 0, length);
185 else
186 memcpy(ptr, s->data, length);
187 /* mark executable sections as executable in memory */
188 if (s->sh_flags & SHF_EXECINSTR)
189 set_pages_executable(ptr, length);
192 #if (defined TCC_TARGET_X86_64 || defined TCC_TARGET_ARM) && !defined TCC_TARGET_PE
193 set_pages_executable(s1->runtime_plt_and_got,
194 s1->runtime_plt_and_got_offset);
195 #endif
197 #ifdef _WIN64
198 win64_add_function_table(s1);
199 #endif
200 return 0;
203 /* ------------------------------------------------------------- */
204 /* allow to run code in memory */
206 static void set_pages_executable(void *ptr, unsigned long length)
208 #ifdef _WIN32
209 unsigned long old_protect;
210 VirtualProtect(ptr, length, PAGE_EXECUTE_READWRITE, &old_protect);
211 #else
212 unsigned long start, end;
213 start = (uplong)ptr & ~(PAGESIZE - 1);
214 end = (uplong)ptr + length;
215 end = (end + PAGESIZE - 1) & ~(PAGESIZE - 1);
216 mprotect((void *)start, end - start, PROT_READ | PROT_WRITE | PROT_EXEC);
217 #endif
220 /* ------------------------------------------------------------- */
221 #ifdef CONFIG_TCC_BACKTRACE
223 /* print the position in the source file of PC value 'pc' by reading
224 the stabs debug information */
225 static uplong rt_printline(uplong wanted_pc, const char *msg)
227 Stab_Sym *sym, *sym_end;
228 char func_name[128], last_func_name[128];
229 unsigned long func_addr, last_pc, pc;
230 const char *incl_files[INCLUDE_STACK_SIZE];
231 int incl_index, len, last_line_num, i;
232 const char *str, *p;
234 func_name[0] = '\0';
235 func_addr = 0;
236 incl_index = 0;
237 last_func_name[0] = '\0';
238 last_pc = 0xffffffff;
239 last_line_num = 1;
240 sym = (Stab_Sym *)stab_section->data + 1;
241 sym_end = (Stab_Sym *)(stab_section->data + stab_section->data_offset);
242 while (sym < sym_end) {
243 switch(sym->n_type) {
244 /* function start or end */
245 case N_FUN:
246 if (sym->n_strx == 0) {
247 /* we test if between last line and end of function */
248 pc = sym->n_value + func_addr;
249 if (wanted_pc >= last_pc && wanted_pc < pc)
250 goto found;
251 func_name[0] = '\0';
252 func_addr = 0;
253 } else {
254 str = stabstr_section->data + sym->n_strx;
255 p = strchr(str, ':');
256 if (!p) {
257 pstrcpy(func_name, sizeof(func_name), str);
258 } else {
259 len = p - str;
260 if (len > sizeof(func_name) - 1)
261 len = sizeof(func_name) - 1;
262 memcpy(func_name, str, len);
263 func_name[len] = '\0';
265 func_addr = sym->n_value;
267 break;
268 /* line number info */
269 case N_SLINE:
270 pc = sym->n_value + func_addr;
271 if (wanted_pc >= last_pc && wanted_pc < pc)
272 goto found;
273 last_pc = pc;
274 last_line_num = sym->n_desc;
275 /* XXX: slow! */
276 strcpy(last_func_name, func_name);
277 break;
278 /* include files */
279 case N_BINCL:
280 str = stabstr_section->data + sym->n_strx;
281 add_incl:
282 if (incl_index < INCLUDE_STACK_SIZE) {
283 incl_files[incl_index++] = str;
285 break;
286 case N_EINCL:
287 if (incl_index > 1)
288 incl_index--;
289 break;
290 case N_SO:
291 if (sym->n_strx == 0) {
292 incl_index = 0; /* end of translation unit */
293 } else {
294 str = stabstr_section->data + sym->n_strx;
295 /* do not add path */
296 len = strlen(str);
297 if (len > 0 && str[len - 1] != '/')
298 goto add_incl;
300 break;
302 sym++;
305 /* second pass: we try symtab symbols (no line number info) */
306 incl_index = 0;
308 ElfW(Sym) *sym, *sym_end;
309 int type;
311 sym_end = (ElfW(Sym) *)(symtab_section->data + symtab_section->data_offset);
312 for(sym = (ElfW(Sym) *)symtab_section->data + 1;
313 sym < sym_end;
314 sym++) {
315 type = ELFW(ST_TYPE)(sym->st_info);
316 if (type == STT_FUNC || type == STT_GNU_IFUNC) {
317 if (wanted_pc >= sym->st_value &&
318 wanted_pc < sym->st_value + sym->st_size) {
319 pstrcpy(last_func_name, sizeof(last_func_name),
320 strtab_section->data + sym->st_name);
321 func_addr = sym->st_value;
322 goto found;
327 /* did not find any info: */
328 fprintf(stderr, "%s %p ???\n", msg, (void*)wanted_pc);
329 fflush(stderr);
330 return 0;
331 found:
332 i = incl_index;
333 if (i > 0)
334 fprintf(stderr, "%s:%d: ", incl_files[--i], last_line_num);
335 fprintf(stderr, "%s %p", msg, (void*)wanted_pc);
336 if (last_func_name[0] != '\0')
337 fprintf(stderr, " %s()", last_func_name);
338 if (--i >= 0) {
339 fprintf(stderr, " (included from ");
340 for (;;) {
341 fprintf(stderr, "%s", incl_files[i]);
342 if (--i < 0)
343 break;
344 fprintf(stderr, ", ");
346 fprintf(stderr, ")");
348 fprintf(stderr, "\n");
349 fflush(stderr);
350 return func_addr;
353 /* emit a run time error at position 'pc' */
354 static void rt_error(ucontext_t *uc, const char *fmt, ...)
356 va_list ap;
357 uplong pc;
358 int i;
360 va_start(ap, fmt);
361 fprintf(stderr, "Runtime error: ");
362 vfprintf(stderr, fmt, ap);
363 fprintf(stderr, "\n");
365 for(i=0;i<num_callers;i++) {
366 if (rt_get_caller_pc(&pc, uc, i) < 0)
367 break;
368 pc = rt_printline(pc, i ? "by" : "at");
369 if (pc == (uplong)rt_prog_main && pc)
370 break;
372 exit(255);
373 va_end(ap);
376 /* ------------------------------------------------------------- */
377 #ifndef _WIN32
379 /* signal handler for fatal errors */
380 static void sig_error(int signum, siginfo_t *siginf, void *puc)
382 ucontext_t *uc = puc;
384 switch(signum) {
385 case SIGFPE:
386 switch(siginf->si_code) {
387 case FPE_INTDIV:
388 case FPE_FLTDIV:
389 rt_error(uc, "division by zero");
390 break;
391 default:
392 rt_error(uc, "floating point exception");
393 break;
395 break;
396 case SIGBUS:
397 case SIGSEGV:
398 if (rt_bound_error_msg && *rt_bound_error_msg)
399 rt_error(uc, *rt_bound_error_msg);
400 else
401 rt_error(uc, "dereferencing invalid pointer");
402 break;
403 case SIGILL:
404 rt_error(uc, "illegal instruction");
405 break;
406 case SIGABRT:
407 rt_error(uc, "abort() called");
408 break;
409 default:
410 rt_error(uc, "caught signal %d", signum);
411 break;
413 exit(255);
416 /* Generate a stack backtrace when a CPU exception occurs. */
417 static void set_exception_handler(void)
419 struct sigaction sigact;
420 /* install TCC signal handlers to print debug info on fatal
421 runtime errors */
422 sigact.sa_flags = SA_SIGINFO | SA_RESETHAND;
423 sigact.sa_sigaction = sig_error;
424 sigemptyset(&sigact.sa_mask);
425 sigaction(SIGFPE, &sigact, NULL);
426 sigaction(SIGILL, &sigact, NULL);
427 sigaction(SIGSEGV, &sigact, NULL);
428 sigaction(SIGBUS, &sigact, NULL);
429 sigaction(SIGABRT, &sigact, NULL);
432 /* ------------------------------------------------------------- */
433 #ifdef __i386__
435 /* fix for glibc 2.1 */
436 #ifndef REG_EIP
437 #define REG_EIP EIP
438 #define REG_EBP EBP
439 #endif
441 /* return the PC at frame level 'level'. Return non zero if not found */
442 static int rt_get_caller_pc(unsigned long *paddr, ucontext_t *uc, int level)
444 unsigned long fp;
445 int i;
447 if (level == 0) {
448 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
449 *paddr = uc->uc_mcontext.mc_eip;
450 #elif defined(__dietlibc__)
451 *paddr = uc->uc_mcontext.eip;
452 #else
453 *paddr = uc->uc_mcontext.gregs[REG_EIP];
454 #endif
455 return 0;
456 } else {
457 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
458 fp = uc->uc_mcontext.mc_ebp;
459 #elif defined(__dietlibc__)
460 fp = uc->uc_mcontext.ebp;
461 #else
462 fp = uc->uc_mcontext.gregs[REG_EBP];
463 #endif
464 for(i=1;i<level;i++) {
465 /* XXX: check address validity with program info */
466 if (fp <= 0x1000 || fp >= 0xc0000000)
467 return -1;
468 fp = ((unsigned long *)fp)[0];
470 *paddr = ((unsigned long *)fp)[1];
471 return 0;
475 /* ------------------------------------------------------------- */
476 #elif defined(__x86_64__)
478 /* return the PC at frame level 'level'. Return non zero if not found */
479 static int rt_get_caller_pc(unsigned long *paddr,
480 ucontext_t *uc, int level)
482 unsigned long fp;
483 int i;
485 if (level == 0) {
486 /* XXX: only support linux */
487 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
488 *paddr = uc->uc_mcontext.mc_rip;
489 #else
490 *paddr = uc->uc_mcontext.gregs[REG_RIP];
491 #endif
492 return 0;
493 } else {
494 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
495 fp = uc->uc_mcontext.mc_rbp;
496 #else
497 fp = uc->uc_mcontext.gregs[REG_RBP];
498 #endif
499 for(i=1;i<level;i++) {
500 /* XXX: check address validity with program info */
501 if (fp <= 0x1000)
502 return -1;
503 fp = ((unsigned long *)fp)[0];
505 *paddr = ((unsigned long *)fp)[1];
506 return 0;
510 /* ------------------------------------------------------------- */
511 #elif defined(__arm__)
513 /* return the PC at frame level 'level'. Return negative if not found */
514 static int rt_get_caller_pc(unsigned long *paddr,
515 ucontext_t *uc, int level)
517 uint32_t fp, sp;
518 int i;
520 if (level == 0) {
521 /* XXX: only supports linux */
522 #if defined(__linux__)
523 *paddr = uc->uc_mcontext.arm_pc;
524 #else
525 return -1;
526 #endif
527 return 0;
528 } else {
529 #if defined(__linux__)
530 fp = uc->uc_mcontext.arm_fp;
531 sp = uc->uc_mcontext.arm_sp;
532 if (sp < 0x1000)
533 sp = 0x1000;
534 #else
535 return -1;
536 #endif
537 /* XXX: specific to tinycc stack frames */
538 if (fp < sp + 12 || fp & 3)
539 return -1;
540 for(i = 1; i < level; i++) {
541 sp = ((uint32_t *)fp)[-2];
542 if (sp < fp || sp - fp > 16 || sp & 3)
543 return -1;
544 fp = ((uint32_t *)fp)[-3];
545 if (fp <= sp || fp - sp < 12 || fp & 3)
546 return -1;
548 /* XXX: check address validity with program info */
549 *paddr = ((uint32_t *)fp)[-1];
550 return 0;
554 /* ------------------------------------------------------------- */
555 #else
557 #warning add arch specific rt_get_caller_pc()
558 static int rt_get_caller_pc(unsigned long *paddr,
559 ucontext_t *uc, int level)
561 return -1;
564 #endif /* !__i386__ */
566 /* ------------------------------------------------------------- */
567 #else /* WIN32 */
569 static long __stdcall cpu_exception_handler(EXCEPTION_POINTERS *ex_info)
571 CONTEXT *uc = ex_info->ContextRecord;
573 EXCEPTION_RECORD *er = ex_info->ExceptionRecord;
574 printf("CPU exception: code=%08lx addr=%p\n",
575 er->ExceptionCode, er->ExceptionAddress);
577 if (rt_bound_error_msg && *rt_bound_error_msg)
578 rt_error(uc, *rt_bound_error_msg);
579 else
580 rt_error(uc, "dereferencing invalid pointer");
581 exit(255);
582 //return EXCEPTION_CONTINUE_SEARCH;
585 /* Generate a stack backtrace when a CPU exception occurs. */
586 static void set_exception_handler(void)
588 SetUnhandledExceptionFilter(cpu_exception_handler);
591 #ifdef _WIN64
592 static void win64_add_function_table(TCCState *s1)
594 RtlAddFunctionTable(
595 (RUNTIME_FUNCTION*)(uplong)s1->uw_pdata->sh_addr,
596 s1->uw_pdata->data_offset / sizeof (RUNTIME_FUNCTION),
597 (uplong)text_section->sh_addr
600 #endif
602 #ifdef _WIN64
603 #define Eip Rip
604 #define Ebp Rbp
605 #endif
607 /* return the PC at frame level 'level'. Return non zero if not found */
608 static int rt_get_caller_pc(uplong *paddr, CONTEXT *uc, int level)
610 uplong fp;
611 int i;
613 if (level == 0) {
614 *paddr = uc->Eip;
615 return 0;
616 } else {
617 fp = uc->Ebp;
618 for(i=1;i<level;i++) {
619 /* XXX: check address validity with program info */
620 if (fp <= 0x1000 || fp >= 0xc0000000)
621 return -1;
622 fp = ((uplong*)fp)[0];
624 *paddr = ((uplong*)fp)[1];
625 return 0;
629 #undef Eip
630 #undef Ebp
632 #endif /* _WIN32 */
633 #endif /* CONFIG_TCC_BACKTRACE */
634 /* ------------------------------------------------------------- */
636 #ifdef CONFIG_TCC_STATIC
638 #define RTLD_LAZY 0x001
639 #define RTLD_NOW 0x002
640 #define RTLD_GLOBAL 0x100
641 #define RTLD_DEFAULT NULL
643 /* dummy function for profiling */
644 void *dlopen(const char *filename, int flag)
646 return NULL;
649 void dlclose(void *p)
653 const char *dlerror(void)
655 return "error";
658 typedef struct TCCSyms {
659 char *str;
660 void *ptr;
661 } TCCSyms;
663 #define TCCSYM(a) { #a, &a, },
665 /* add the symbol you want here if no dynamic linking is done */
666 static TCCSyms tcc_syms[] = {
667 #if !defined(CONFIG_TCCBOOT)
668 TCCSYM(printf)
669 TCCSYM(fprintf)
670 TCCSYM(fopen)
671 TCCSYM(fclose)
672 #endif
673 { NULL, NULL },
676 void *resolve_sym(TCCState *s1, const char *symbol)
678 TCCSyms *p;
679 p = tcc_syms;
680 while (p->str != NULL) {
681 if (!strcmp(p->str, symbol))
682 return p->ptr;
683 p++;
685 return NULL;
688 #elif !defined(_WIN32)
690 void *resolve_sym(TCCState *s1, const char *sym)
692 return dlsym(RTLD_DEFAULT, sym);
695 #endif /* CONFIG_TCC_STATIC */
697 /* ------------------------------------------------------------- */