tccrun: rt_printline: fix no-stabs case
[tinycc.git] / tccrun.c
blob224d0637f470b3888b0d77fd21aa8cc74993fc8b
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 char func_name[128], last_func_name[128];
228 uplong func_addr, last_pc, pc;
229 const char *incl_files[INCLUDE_STACK_SIZE];
230 int incl_index, len, last_line_num, i;
231 const char *str, *p;
233 Stab_Sym *stab_sym = NULL, *stab_sym_end, *sym;
234 int stab_len = 0;
235 char *stab_str = NULL;
237 if (stab_section) {
238 stab_len = stab_section->data_offset;
239 stab_sym = (Stab_Sym *)stab_section->data;
240 stab_str = stabstr_section->data;
243 func_name[0] = '\0';
244 func_addr = 0;
245 incl_index = 0;
246 last_func_name[0] = '\0';
247 last_pc = (uplong)-1;
248 last_line_num = 1;
250 if (!stab_sym)
251 goto no_stabs;
253 stab_sym_end = (Stab_Sym*)((char*)stab_sym + stab_len);
254 for (sym = stab_sym + 1; sym < stab_sym_end; ++sym) {
255 switch(sym->n_type) {
256 /* function start or end */
257 case N_FUN:
258 if (sym->n_strx == 0) {
259 /* we test if between last line and end of function */
260 pc = sym->n_value + func_addr;
261 if (wanted_pc >= last_pc && wanted_pc < pc)
262 goto found;
263 func_name[0] = '\0';
264 func_addr = 0;
265 } else {
266 str = stab_str + sym->n_strx;
267 p = strchr(str, ':');
268 if (!p) {
269 pstrcpy(func_name, sizeof(func_name), str);
270 } else {
271 len = p - str;
272 if (len > sizeof(func_name) - 1)
273 len = sizeof(func_name) - 1;
274 memcpy(func_name, str, len);
275 func_name[len] = '\0';
277 func_addr = sym->n_value;
279 break;
280 /* line number info */
281 case N_SLINE:
282 pc = sym->n_value + func_addr;
283 if (wanted_pc >= last_pc && wanted_pc < pc)
284 goto found;
285 last_pc = pc;
286 last_line_num = sym->n_desc;
287 /* XXX: slow! */
288 strcpy(last_func_name, func_name);
289 break;
290 /* include files */
291 case N_BINCL:
292 str = stab_str + sym->n_strx;
293 add_incl:
294 if (incl_index < INCLUDE_STACK_SIZE) {
295 incl_files[incl_index++] = str;
297 break;
298 case N_EINCL:
299 if (incl_index > 1)
300 incl_index--;
301 break;
302 case N_SO:
303 if (sym->n_strx == 0) {
304 incl_index = 0; /* end of translation unit */
305 } else {
306 str = stab_str + sym->n_strx;
307 /* do not add path */
308 len = strlen(str);
309 if (len > 0 && str[len - 1] != '/')
310 goto add_incl;
312 break;
316 no_stabs:
317 /* second pass: we try symtab symbols (no line number info) */
318 incl_index = 0;
319 if (symtab_section)
321 ElfW(Sym) *sym, *sym_end;
322 int type;
324 sym_end = (ElfW(Sym) *)(symtab_section->data + symtab_section->data_offset);
325 for(sym = (ElfW(Sym) *)symtab_section->data + 1;
326 sym < sym_end;
327 sym++) {
328 type = ELFW(ST_TYPE)(sym->st_info);
329 if (type == STT_FUNC || type == STT_GNU_IFUNC) {
330 if (wanted_pc >= sym->st_value &&
331 wanted_pc < sym->st_value + sym->st_size) {
332 pstrcpy(last_func_name, sizeof(last_func_name),
333 strtab_section->data + sym->st_name);
334 func_addr = sym->st_value;
335 goto found;
340 /* did not find any info: */
341 fprintf(stderr, "%s %p ???\n", msg, (void*)wanted_pc);
342 fflush(stderr);
343 return 0;
344 found:
345 i = incl_index;
346 if (i > 0)
347 fprintf(stderr, "%s:%d: ", incl_files[--i], last_line_num);
348 fprintf(stderr, "%s %p", msg, (void*)wanted_pc);
349 if (last_func_name[0] != '\0')
350 fprintf(stderr, " %s()", last_func_name);
351 if (--i >= 0) {
352 fprintf(stderr, " (included from ");
353 for (;;) {
354 fprintf(stderr, "%s", incl_files[i]);
355 if (--i < 0)
356 break;
357 fprintf(stderr, ", ");
359 fprintf(stderr, ")");
361 fprintf(stderr, "\n");
362 fflush(stderr);
363 return func_addr;
366 /* emit a run time error at position 'pc' */
367 static void rt_error(ucontext_t *uc, const char *fmt, ...)
369 va_list ap;
370 uplong pc;
371 int i;
373 va_start(ap, fmt);
374 fprintf(stderr, "Runtime error: ");
375 vfprintf(stderr, fmt, ap);
376 fprintf(stderr, "\n");
378 for(i=0;i<num_callers;i++) {
379 if (rt_get_caller_pc(&pc, uc, i) < 0)
380 break;
381 pc = rt_printline(pc, i ? "by" : "at");
382 if (pc == (uplong)rt_prog_main && pc)
383 break;
385 exit(255);
386 va_end(ap);
389 /* ------------------------------------------------------------- */
390 #ifndef _WIN32
392 /* signal handler for fatal errors */
393 static void sig_error(int signum, siginfo_t *siginf, void *puc)
395 ucontext_t *uc = puc;
397 switch(signum) {
398 case SIGFPE:
399 switch(siginf->si_code) {
400 case FPE_INTDIV:
401 case FPE_FLTDIV:
402 rt_error(uc, "division by zero");
403 break;
404 default:
405 rt_error(uc, "floating point exception");
406 break;
408 break;
409 case SIGBUS:
410 case SIGSEGV:
411 if (rt_bound_error_msg && *rt_bound_error_msg)
412 rt_error(uc, *rt_bound_error_msg);
413 else
414 rt_error(uc, "dereferencing invalid pointer");
415 break;
416 case SIGILL:
417 rt_error(uc, "illegal instruction");
418 break;
419 case SIGABRT:
420 rt_error(uc, "abort() called");
421 break;
422 default:
423 rt_error(uc, "caught signal %d", signum);
424 break;
426 exit(255);
429 /* Generate a stack backtrace when a CPU exception occurs. */
430 static void set_exception_handler(void)
432 struct sigaction sigact;
433 /* install TCC signal handlers to print debug info on fatal
434 runtime errors */
435 sigact.sa_flags = SA_SIGINFO | SA_RESETHAND;
436 sigact.sa_sigaction = sig_error;
437 sigemptyset(&sigact.sa_mask);
438 sigaction(SIGFPE, &sigact, NULL);
439 sigaction(SIGILL, &sigact, NULL);
440 sigaction(SIGSEGV, &sigact, NULL);
441 sigaction(SIGBUS, &sigact, NULL);
442 sigaction(SIGABRT, &sigact, NULL);
445 /* ------------------------------------------------------------- */
446 #ifdef __i386__
448 /* fix for glibc 2.1 */
449 #ifndef REG_EIP
450 #define REG_EIP EIP
451 #define REG_EBP EBP
452 #endif
454 /* return the PC at frame level 'level'. Return non zero if not found */
455 static int rt_get_caller_pc(unsigned long *paddr, ucontext_t *uc, int level)
457 unsigned long fp;
458 int i;
460 if (level == 0) {
461 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
462 *paddr = uc->uc_mcontext.mc_eip;
463 #elif defined(__dietlibc__)
464 *paddr = uc->uc_mcontext.eip;
465 #else
466 *paddr = uc->uc_mcontext.gregs[REG_EIP];
467 #endif
468 return 0;
469 } else {
470 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
471 fp = uc->uc_mcontext.mc_ebp;
472 #elif defined(__dietlibc__)
473 fp = uc->uc_mcontext.ebp;
474 #else
475 fp = uc->uc_mcontext.gregs[REG_EBP];
476 #endif
477 for(i=1;i<level;i++) {
478 /* XXX: check address validity with program info */
479 if (fp <= 0x1000 || fp >= 0xc0000000)
480 return -1;
481 fp = ((unsigned long *)fp)[0];
483 *paddr = ((unsigned long *)fp)[1];
484 return 0;
488 /* ------------------------------------------------------------- */
489 #elif defined(__x86_64__)
491 /* return the PC at frame level 'level'. Return non zero if not found */
492 static int rt_get_caller_pc(unsigned long *paddr,
493 ucontext_t *uc, int level)
495 unsigned long fp;
496 int i;
498 if (level == 0) {
499 /* XXX: only support linux */
500 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
501 *paddr = uc->uc_mcontext.mc_rip;
502 #else
503 *paddr = uc->uc_mcontext.gregs[REG_RIP];
504 #endif
505 return 0;
506 } else {
507 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
508 fp = uc->uc_mcontext.mc_rbp;
509 #else
510 fp = uc->uc_mcontext.gregs[REG_RBP];
511 #endif
512 for(i=1;i<level;i++) {
513 /* XXX: check address validity with program info */
514 if (fp <= 0x1000)
515 return -1;
516 fp = ((unsigned long *)fp)[0];
518 *paddr = ((unsigned long *)fp)[1];
519 return 0;
523 /* ------------------------------------------------------------- */
524 #elif defined(__arm__)
526 /* return the PC at frame level 'level'. Return negative if not found */
527 static int rt_get_caller_pc(unsigned long *paddr,
528 ucontext_t *uc, int level)
530 uint32_t fp, sp;
531 int i;
533 if (level == 0) {
534 /* XXX: only supports linux */
535 #if defined(__linux__)
536 *paddr = uc->uc_mcontext.arm_pc;
537 #else
538 return -1;
539 #endif
540 return 0;
541 } else {
542 #if defined(__linux__)
543 fp = uc->uc_mcontext.arm_fp;
544 sp = uc->uc_mcontext.arm_sp;
545 if (sp < 0x1000)
546 sp = 0x1000;
547 #else
548 return -1;
549 #endif
550 /* XXX: specific to tinycc stack frames */
551 if (fp < sp + 12 || fp & 3)
552 return -1;
553 for(i = 1; i < level; i++) {
554 sp = ((uint32_t *)fp)[-2];
555 if (sp < fp || sp - fp > 16 || sp & 3)
556 return -1;
557 fp = ((uint32_t *)fp)[-3];
558 if (fp <= sp || fp - sp < 12 || fp & 3)
559 return -1;
561 /* XXX: check address validity with program info */
562 *paddr = ((uint32_t *)fp)[-1];
563 return 0;
567 /* ------------------------------------------------------------- */
568 #else
570 #warning add arch specific rt_get_caller_pc()
571 static int rt_get_caller_pc(unsigned long *paddr,
572 ucontext_t *uc, int level)
574 return -1;
577 #endif /* !__i386__ */
579 /* ------------------------------------------------------------- */
580 #else /* WIN32 */
582 static long __stdcall cpu_exception_handler(EXCEPTION_POINTERS *ex_info)
584 CONTEXT *uc = ex_info->ContextRecord;
586 EXCEPTION_RECORD *er = ex_info->ExceptionRecord;
587 printf("CPU exception: code=%08lx addr=%p\n",
588 er->ExceptionCode, er->ExceptionAddress);
590 if (rt_bound_error_msg && *rt_bound_error_msg)
591 rt_error(uc, *rt_bound_error_msg);
592 else
593 rt_error(uc, "dereferencing invalid pointer");
594 exit(255);
595 //return EXCEPTION_CONTINUE_SEARCH;
598 /* Generate a stack backtrace when a CPU exception occurs. */
599 static void set_exception_handler(void)
601 SetUnhandledExceptionFilter(cpu_exception_handler);
604 #ifdef _WIN64
605 static void win64_add_function_table(TCCState *s1)
607 RtlAddFunctionTable(
608 (RUNTIME_FUNCTION*)(uplong)s1->uw_pdata->sh_addr,
609 s1->uw_pdata->data_offset / sizeof (RUNTIME_FUNCTION),
610 (uplong)text_section->sh_addr
613 #endif
615 #ifdef _WIN64
616 #define Eip Rip
617 #define Ebp Rbp
618 #endif
620 /* return the PC at frame level 'level'. Return non zero if not found */
621 static int rt_get_caller_pc(uplong *paddr, CONTEXT *uc, int level)
623 uplong fp;
624 int i;
626 if (level == 0) {
627 *paddr = uc->Eip;
628 return 0;
629 } else {
630 fp = uc->Ebp;
631 for(i=1;i<level;i++) {
632 /* XXX: check address validity with program info */
633 if (fp <= 0x1000 || fp >= 0xc0000000)
634 return -1;
635 fp = ((uplong*)fp)[0];
637 *paddr = ((uplong*)fp)[1];
638 return 0;
642 #undef Eip
643 #undef Ebp
645 #endif /* _WIN32 */
646 #endif /* CONFIG_TCC_BACKTRACE */
647 /* ------------------------------------------------------------- */
649 #ifdef CONFIG_TCC_STATIC
651 #define RTLD_LAZY 0x001
652 #define RTLD_NOW 0x002
653 #define RTLD_GLOBAL 0x100
654 #define RTLD_DEFAULT NULL
656 /* dummy function for profiling */
657 void *dlopen(const char *filename, int flag)
659 return NULL;
662 void dlclose(void *p)
666 const char *dlerror(void)
668 return "error";
671 typedef struct TCCSyms {
672 char *str;
673 void *ptr;
674 } TCCSyms;
676 #define TCCSYM(a) { #a, &a, },
678 /* add the symbol you want here if no dynamic linking is done */
679 static TCCSyms tcc_syms[] = {
680 #if !defined(CONFIG_TCCBOOT)
681 TCCSYM(printf)
682 TCCSYM(fprintf)
683 TCCSYM(fopen)
684 TCCSYM(fclose)
685 #endif
686 { NULL, NULL },
689 void *resolve_sym(TCCState *s1, const char *symbol)
691 TCCSyms *p;
692 p = tcc_syms;
693 while (p->str != NULL) {
694 if (!strcmp(p->str, symbol))
695 return p->ptr;
696 p++;
698 return NULL;
701 #elif !defined(_WIN32)
703 void *resolve_sym(TCCState *s1, const char *sym)
705 return dlsym(RTLD_DEFAULT, sym);
708 #endif /* CONFIG_TCC_STATIC */
710 /* ------------------------------------------------------------- */