Support -v --help the same way as gcc does
[tinycc.git] / tccrun.c
blob02f207c9a9050a4d83025f54c0b469f5c0511490
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 typedef struct rt_context
29 /* --> tccelf.c:tcc_add_btstub wants those below in that order: */
30 Stab_Sym *stab_sym, *stab_sym_end;
31 char *stab_str;
32 ElfW(Sym) *esym_start, *esym_end;
33 char *elf_str;
34 addr_t prog_base;
35 void *bounds_start;
36 struct rt_context *next;
37 /* <-- */
38 int num_callers;
39 addr_t ip, fp, sp;
40 void *top_func;
41 jmp_buf jmp_buf;
42 char do_jmp;
43 } rt_context;
45 static rt_context g_rtctxt;
46 static void set_exception_handler(void);
47 static int _rt_error(void *fp, void *ip, const char *fmt, va_list ap);
48 static void rt_exit(int code);
49 #endif /* CONFIG_TCC_BACKTRACE */
51 /* defined when included from lib/bt-exe.c */
52 #ifndef CONFIG_TCC_BACKTRACE_ONLY
54 #ifndef _WIN32
55 # include <sys/mman.h>
56 #endif
58 static void set_pages_executable(TCCState *s1, void *ptr, unsigned long length);
59 static int tcc_relocate_ex(TCCState *s1, void *ptr, addr_t ptr_diff);
61 #ifdef _WIN64
62 static void *win64_add_function_table(TCCState *s1);
63 static void win64_del_function_table(void *);
64 #endif
66 /* ------------------------------------------------------------- */
67 /* Do all relocations (needed before using tcc_get_symbol())
68 Returns -1 on error. */
70 LIBTCCAPI int tcc_relocate(TCCState *s1, void *ptr)
72 int size;
73 addr_t ptr_diff = 0;
75 if (TCC_RELOCATE_AUTO != ptr)
76 return tcc_relocate_ex(s1, ptr, 0);
78 size = tcc_relocate_ex(s1, NULL, 0);
79 if (size < 0)
80 return -1;
82 #ifdef HAVE_SELINUX
84 /* Using mmap instead of malloc */
85 void *prx;
86 char tmpfname[] = "/tmp/.tccrunXXXXXX";
87 int fd = mkstemp(tmpfname);
88 unlink(tmpfname);
89 ftruncate(fd, size);
91 ptr = mmap (NULL, size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
92 prx = mmap (NULL, size, PROT_READ|PROT_EXEC, MAP_SHARED, fd, 0);
93 if (ptr == MAP_FAILED || prx == MAP_FAILED)
94 tcc_error("tccrun: could not map memory");
95 dynarray_add(&s1->runtime_mem, &s1->nb_runtime_mem, (void*)(addr_t)size);
96 dynarray_add(&s1->runtime_mem, &s1->nb_runtime_mem, prx);
97 ptr_diff = (char*)prx - (char*)ptr;
98 close(fd);
100 #else
101 ptr = tcc_malloc(size);
102 #endif
103 tcc_relocate_ex(s1, ptr, ptr_diff); /* no more errors expected */
104 dynarray_add(&s1->runtime_mem, &s1->nb_runtime_mem, ptr);
105 return 0;
108 ST_FUNC void tcc_run_free(TCCState *s1)
110 int i;
112 for (i = 0; i < s1->nb_runtime_mem; ++i) {
113 #ifdef HAVE_SELINUX
114 unsigned size = (unsigned)(addr_t)s1->runtime_mem[i++];
115 munmap(s1->runtime_mem[i++], size);
116 munmap(s1->runtime_mem[i], size);
117 #else
118 #ifdef _WIN64
119 win64_del_function_table(*(void**)s1->runtime_mem[i]);
120 #endif
121 tcc_free(s1->runtime_mem[i]);
122 #endif
124 tcc_free(s1->runtime_mem);
127 static void run_cdtors(TCCState *s1, const char *start, const char *end)
129 void **a = tcc_get_symbol(s1, start);
130 void **b = tcc_get_symbol(s1, end);
131 while (a != b)
132 ((void(*)(void))*a++)();
135 /* launch the compiled program with the given arguments */
136 LIBTCCAPI int tcc_run(TCCState *s1, int argc, char **argv)
138 int (*prog_main)(int, char **), ret;
139 #ifdef CONFIG_TCC_BACKTRACE
140 rt_context *rc = &g_rtctxt;
141 #endif
143 s1->runtime_main = s1->nostdlib ? "_start" : "main";
144 if ((s1->dflag & 16) && !find_elf_sym(s1->symtab, s1->runtime_main))
145 return 0;
146 #ifdef CONFIG_TCC_BACKTRACE
147 if (s1->do_debug)
148 tcc_add_symbol(s1, "exit", rt_exit);
149 #endif
150 if (tcc_relocate(s1, TCC_RELOCATE_AUTO) < 0)
151 return -1;
152 prog_main = tcc_get_symbol_err(s1, s1->runtime_main);
154 #ifdef CONFIG_TCC_BACKTRACE
155 memset(rc, 0, sizeof *rc);
156 if (s1->do_debug) {
157 void *p;
158 rc->stab_sym = (Stab_Sym *)stab_section->data;
159 rc->stab_sym_end = (Stab_Sym *)(stab_section->data + stab_section->data_offset);
160 rc->stab_str = (char *)stab_section->link->data;
161 rc->esym_start = (ElfW(Sym) *)(symtab_section->data);
162 rc->esym_end = (ElfW(Sym) *)(symtab_section->data + symtab_section->data_offset);
163 rc->elf_str = (char *)symtab_section->link->data;
164 #if PTR_SIZE == 8
165 rc->prog_base = text_section->sh_addr & 0xffffffff00000000ULL;
166 #endif
167 rc->top_func = tcc_get_symbol(s1, "main");
168 rc->num_callers = s1->rt_num_callers;
169 rc->do_jmp = 1;
170 if ((p = tcc_get_symbol(s1, "__rt_error")))
171 *(void**)p = _rt_error;
172 #ifdef CONFIG_TCC_BCHECK
173 if (s1->do_bounds_check) {
174 if ((p = tcc_get_symbol(s1, "__bound_init")))
175 ((void(*)(void*))p)(bounds_section->data);
177 #endif
178 set_exception_handler();
180 #endif
182 errno = 0; /* clean errno value */
183 fflush(stdout);
184 fflush(stderr);
185 run_cdtors(s1, "__init_array_start", "__init_array_end");
186 #ifdef CONFIG_TCC_BACKTRACE
187 if (!rc->do_jmp || !(ret = setjmp(rc->jmp_buf)))
188 #endif
190 ret = prog_main(argc, argv);
192 run_cdtors(s1, "__fini_array_start", "__fini_array_end");
193 if ((s1->dflag & 16) && ret)
194 fprintf(s1->ppfp, "[returns %d]\n", ret), fflush(s1->ppfp);
195 return ret;
198 #if defined TCC_TARGET_I386 || defined TCC_TARGET_X86_64
199 /* To avoid that x86 processors would reload cached instructions
200 each time when data is written in the near, we need to make
201 sure that code and data do not share the same 64 byte unit */
202 #define RUN_SECTION_ALIGNMENT 63
203 #else
204 #define RUN_SECTION_ALIGNMENT 0
205 #endif
207 /* relocate code. Return -1 on error, required size if ptr is NULL,
208 otherwise copy code into buffer passed by the caller */
209 static int tcc_relocate_ex(TCCState *s1, void *ptr, addr_t ptr_diff)
211 Section *s;
212 unsigned offset, length, align, max_align, i, k, f;
213 addr_t mem, addr;
215 if (NULL == ptr) {
216 s1->nb_errors = 0;
217 #ifdef TCC_TARGET_PE
218 pe_output_file(s1, NULL);
219 #else
220 tcc_add_runtime(s1);
221 resolve_common_syms(s1);
222 build_got_entries(s1);
223 #endif
224 if (s1->nb_errors)
225 return -1;
228 offset = max_align = 0, mem = (addr_t)ptr;
229 #ifdef _WIN64
230 offset += sizeof (void*); /* space for function_table pointer */
231 #endif
232 for (k = 0; k < 2; ++k) {
233 f = 0, addr = k ? mem : mem + ptr_diff;
234 for(i = 1; i < s1->nb_sections; i++) {
235 s = s1->sections[i];
236 if (0 == (s->sh_flags & SHF_ALLOC))
237 continue;
238 if (k != !(s->sh_flags & SHF_EXECINSTR))
239 continue;
240 align = s->sh_addralign - 1;
241 if (++f == 1 && align < RUN_SECTION_ALIGNMENT)
242 align = RUN_SECTION_ALIGNMENT;
243 if (max_align < align)
244 max_align = align;
245 offset += -(addr + offset) & align;
246 s->sh_addr = mem ? addr + offset : 0;
247 offset += s->data_offset;
248 #if 0
249 if (mem)
250 printf("%-16s %p len %04x align %2d\n",
251 s->name, (void*)s->sh_addr, (unsigned)s->data_offset, align + 1);
252 #endif
256 /* relocate symbols */
257 relocate_syms(s1, s1->symtab, !(s1->nostdlib));
258 if (s1->nb_errors)
259 return -1;
261 if (0 == mem)
262 return offset + max_align;
264 #ifdef TCC_TARGET_PE
265 s1->pe_imagebase = mem;
266 #endif
268 /* relocate each section */
269 for(i = 1; i < s1->nb_sections; i++) {
270 s = s1->sections[i];
271 if (s->reloc)
272 relocate_section(s1, s);
274 #ifndef TCC_TARGET_PE
275 relocate_plt(s1);
276 #endif
278 for(i = 1; i < s1->nb_sections; i++) {
279 s = s1->sections[i];
280 if (0 == (s->sh_flags & SHF_ALLOC))
281 continue;
282 length = s->data_offset;
283 ptr = (void*)s->sh_addr;
284 if (s->sh_flags & SHF_EXECINSTR)
285 ptr = (char*)((addr_t)ptr - ptr_diff);
286 if (NULL == s->data || s->sh_type == SHT_NOBITS)
287 memset(ptr, 0, length);
288 else
289 memcpy(ptr, s->data, length);
290 /* mark executable sections as executable in memory */
291 if (s->sh_flags & SHF_EXECINSTR)
292 set_pages_executable(s1, (char*)((addr_t)ptr + ptr_diff), length);
295 #ifdef _WIN64
296 *(void**)mem = win64_add_function_table(s1);
297 #endif
299 return 0;
302 /* ------------------------------------------------------------- */
303 /* allow to run code in memory */
305 static void set_pages_executable(TCCState *s1, void *ptr, unsigned long length)
307 #ifdef _WIN32
308 unsigned long old_protect;
309 VirtualProtect(ptr, length, PAGE_EXECUTE_READWRITE, &old_protect);
310 #else
311 void __clear_cache(void *beginning, void *end);
312 # ifndef HAVE_SELINUX
313 addr_t start, end;
314 # ifndef PAGESIZE
315 # define PAGESIZE 4096
316 # endif
317 start = (addr_t)ptr & ~(PAGESIZE - 1);
318 end = (addr_t)ptr + length;
319 end = (end + PAGESIZE - 1) & ~(PAGESIZE - 1);
320 if (mprotect((void *)start, end - start, PROT_READ | PROT_WRITE | PROT_EXEC))
321 tcc_error("mprotect failed: did you mean to configure --with-selinux?");
322 # endif
323 # if defined TCC_TARGET_ARM || defined TCC_TARGET_ARM64
324 __clear_cache(ptr, (char *)ptr + length);
325 # endif
326 #endif
329 #ifdef _WIN64
330 static void *win64_add_function_table(TCCState *s1)
332 void *p = NULL;
333 if (s1->uw_pdata) {
334 p = (void*)s1->uw_pdata->sh_addr;
335 RtlAddFunctionTable(
336 (RUNTIME_FUNCTION*)p,
337 s1->uw_pdata->data_offset / sizeof (RUNTIME_FUNCTION),
338 s1->pe_imagebase
340 s1->uw_pdata = NULL;
342 return p;
345 static void win64_del_function_table(void *p)
347 if (p) {
348 RtlDeleteFunctionTable((RUNTIME_FUNCTION*)p);
351 #endif
352 #endif //ndef CONFIG_TCC_BACKTRACE_ONLY
353 /* ------------------------------------------------------------- */
354 #ifdef CONFIG_TCC_BACKTRACE
356 static int rt_vprintf(const char *fmt, va_list ap)
358 int ret = vfprintf(stderr, fmt, ap);
359 fflush(stderr);
360 return ret;
363 static int rt_printf(const char *fmt, ...)
365 va_list ap;
366 int r;
367 va_start(ap, fmt);
368 r = rt_vprintf(fmt, ap);
369 va_end(ap);
370 return r;
373 #define INCLUDE_STACK_SIZE 32
375 /* print the position in the source file of PC value 'pc' by reading
376 the stabs debug information */
377 static addr_t rt_printline (rt_context *rc, addr_t wanted_pc,
378 const char *msg, const char *skip)
380 char func_name[128];
381 addr_t func_addr, last_pc, pc;
382 const char *incl_files[INCLUDE_STACK_SIZE];
383 int incl_index, last_incl_index, len, last_line_num, i;
384 const char *str, *p;
385 ElfW(Sym) *esym;
386 Stab_Sym *sym;
388 next:
389 func_name[0] = '\0';
390 func_addr = 0;
391 incl_index = 0;
392 last_pc = (addr_t)-1;
393 last_line_num = 1;
394 last_incl_index = 0;
396 for (sym = rc->stab_sym + 1; sym < rc->stab_sym_end; ++sym) {
397 str = rc->stab_str + sym->n_strx;
398 pc = sym->n_value;
400 switch(sym->n_type) {
401 case N_SLINE:
402 if (func_addr)
403 goto rel_pc;
404 case N_SO:
405 case N_SOL:
406 goto abs_pc;
407 case N_FUN:
408 if (sym->n_strx == 0) /* end of function */
409 goto rel_pc;
410 abs_pc:
411 #if PTR_SIZE == 8
412 /* Stab_Sym.n_value is only 32bits */
413 pc += rc->prog_base;
414 #endif
415 goto check_pc;
416 rel_pc:
417 pc += func_addr;
418 check_pc:
419 if (pc >= wanted_pc && wanted_pc >= last_pc)
420 goto found;
421 break;
424 switch(sym->n_type) {
425 /* function start or end */
426 case N_FUN:
427 if (sym->n_strx == 0)
428 goto reset_func;
429 p = strchr(str, ':');
430 if (0 == p || (len = p - str + 1, len > sizeof func_name))
431 len = sizeof func_name;
432 pstrcpy(func_name, len, str);
433 func_addr = pc;
434 break;
435 /* line number info */
436 case N_SLINE:
437 last_pc = pc;
438 last_line_num = sym->n_desc;
439 last_incl_index = incl_index;
440 break;
441 /* include files */
442 case N_BINCL:
443 if (incl_index < INCLUDE_STACK_SIZE)
444 incl_files[incl_index++] = str;
445 break;
446 case N_EINCL:
447 if (incl_index > 1)
448 incl_index--;
449 break;
450 /* start/end of translation unit */
451 case N_SO:
452 incl_index = 0;
453 if (sym->n_strx) {
454 /* do not add path */
455 len = strlen(str);
456 if (len > 0 && str[len - 1] != '/')
457 incl_files[incl_index++] = str;
459 reset_func:
460 func_name[0] = '\0';
461 func_addr = 0;
462 last_pc = (addr_t)-1;
463 break;
464 /* alternative file name (from #line or #include directives) */
465 case N_SOL:
466 if (incl_index)
467 incl_files[incl_index-1] = str;
468 break;
472 func_name[0] = '\0';
473 func_addr = 0;
474 last_incl_index = 0;
476 /* we try symtab symbols (no line number info) */
477 for (esym = rc->esym_start + 1; esym < rc->esym_end; ++esym) {
478 int type = ELFW(ST_TYPE)(esym->st_info);
479 if (type == STT_FUNC || type == STT_GNU_IFUNC) {
480 if (wanted_pc >= esym->st_value &&
481 wanted_pc < esym->st_value + esym->st_size) {
482 pstrcpy(func_name, sizeof(func_name),
483 rc->elf_str + esym->st_name);
484 func_addr = esym->st_value;
485 goto found;
490 if ((rc = rc->next))
491 goto next;
493 found:
494 i = last_incl_index;
495 if (i > 0) {
496 str = incl_files[--i];
497 if (skip[0] && strstr(str, skip))
498 return (addr_t)-1;
499 rt_printf("%s:%d: ", str, last_line_num);
500 } else
501 rt_printf("%08llx : ", (long long)wanted_pc);
502 rt_printf("%s %s", msg, func_name[0] ? func_name : "???");
503 #if 0
504 if (--i >= 0) {
505 rt_printf(" (included from ");
506 for (;;) {
507 rt_printf("%s", incl_files[i]);
508 if (--i < 0)
509 break;
510 rt_printf(", ");
512 rt_printf(")");
514 #endif
515 return func_addr;
518 static int rt_get_caller_pc(addr_t *paddr, rt_context *rc, int level);
520 static int _rt_error(void *fp, void *ip, const char *fmt, va_list ap)
522 rt_context *rc = &g_rtctxt;
523 addr_t pc = 0;
524 char skip[100];
525 int i, level, ret, n;
526 const char *a, *b, *msg;
528 if (fp) {
529 /* we're called from tcc_backtrace. */
530 rc->fp = (addr_t)fp;
531 rc->ip = (addr_t)ip;
532 msg = "";
533 } else {
534 /* we're called from signal/exception handler */
535 msg = "RUNTIME ERROR: ";
538 skip[0] = 0;
539 /* If fmt is like "^file.c^..." then skip calls from 'file.c' */
540 if (fmt[0] == '^' && (b = strchr(a = fmt + 1, fmt[0]))) {
541 memcpy(skip, a, b - a), skip[b - a] = 0;
542 fmt = b + 1;
545 n = rc->num_callers ? rc->num_callers : 6;
546 for (i = level = 0; level < n; i++) {
547 ret = rt_get_caller_pc(&pc, rc, i);
548 a = "%s";
549 if (ret != -1) {
550 pc = rt_printline(rc, pc, level ? "by" : "at", skip);
551 if (pc == (addr_t)-1)
552 continue;
553 a = ": %s";
555 if (level == 0) {
556 rt_printf(a, msg);
557 rt_vprintf(fmt, ap);
558 } else if (ret == -1)
559 break;
560 rt_printf("\n");
561 if (ret == -1 || (pc == (addr_t)rc->top_func && pc))
562 break;
563 ++level;
566 rc->ip = rc->fp = 0;
567 return 0;
570 /* emit a run time error at position 'pc' */
571 static int rt_error(const char *fmt, ...)
573 va_list ap;
574 int ret;
575 va_start(ap, fmt);
576 ret = _rt_error(0, 0, fmt, ap);
577 va_end(ap);
578 return ret;
581 static void rt_exit(int code)
583 rt_context *rc = &g_rtctxt;
584 if (rc->do_jmp)
585 longjmp(rc->jmp_buf, code ? code : 256);
586 exit(code);
589 /* ------------------------------------------------------------- */
591 #ifndef _WIN32
592 # include <signal.h>
593 # ifndef __OpenBSD__
594 # include <sys/ucontext.h>
595 # endif
596 #else
597 # define ucontext_t CONTEXT
598 #endif
600 /* translate from ucontext_t* to internal rt_context * */
601 static void rt_getcontext(ucontext_t *uc, rt_context *rc)
603 #if defined _WIN64
604 rc->ip = uc->Rip;
605 rc->fp = uc->Rbp;
606 rc->sp = uc->Rsp;
607 #elif defined _WIN32
608 rc->ip = uc->Eip;
609 rc->fp = uc->Ebp;
610 rc->sp = uc->Esp;
611 #elif defined __i386__
612 # if defined(__APPLE__)
613 rc->ip = uc->uc_mcontext->__ss.__eip;
614 rc->fp = uc->uc_mcontext->__ss.__ebp;
615 # elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
616 rc->ip = uc->uc_mcontext.mc_eip;
617 rc->fp = uc->uc_mcontext.mc_ebp;
618 # elif defined(__dietlibc__)
619 rc->ip = uc->uc_mcontext.eip;
620 rc->fp = uc->uc_mcontext.ebp;
621 # elif defined(__NetBSD__)
622 rc->ip = uc->uc_mcontext.__gregs[_REG_EIP];
623 rc->fp = uc->uc_mcontext.__gregs[_REG_EBP];
624 # elif defined(__OpenBSD__)
625 rc->ip = uc->sc_eip;
626 rc->fp = uc->sc_ebp;
627 # elif !defined REG_EIP && defined EIP /* fix for glibc 2.1 */
628 rc->ip = uc->uc_mcontext.gregs[EIP];
629 rc->fp = uc->uc_mcontext.gregs[EBP];
630 # else
631 rc->ip = uc->uc_mcontext.gregs[REG_EIP];
632 rc->fp = uc->uc_mcontext.gregs[REG_EBP];
633 # endif
634 #elif defined(__x86_64__)
635 # if defined(__APPLE__)
636 rc->ip = uc->uc_mcontext->__ss.__rip;
637 rc->fp = uc->uc_mcontext->__ss.__rbp;
638 # elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
639 rc->ip = uc->uc_mcontext.mc_rip;
640 rc->fp = uc->uc_mcontext.mc_rbp;
641 # elif defined(__NetBSD__)
642 rc->ip = uc->uc_mcontext.__gregs[_REG_RIP];
643 rc->fp = uc->uc_mcontext.__gregs[_REG_RBP];
644 # else
645 rc->ip = uc->uc_mcontext.gregs[REG_RIP];
646 rc->fp = uc->uc_mcontext.gregs[REG_RBP];
647 # endif
648 #elif defined(__arm__)
649 rc->ip = uc->uc_mcontext.arm_pc;
650 rc->fp = uc->uc_mcontext.arm_fp;
651 rc->sp = uc->uc_mcontext.arm_sp;
652 #elif defined(__aarch64__)
653 rc->ip = uc->uc_mcontext.pc;
654 rc->fp = uc->uc_mcontext.regs[29];
655 #endif
658 /* ------------------------------------------------------------- */
659 #ifndef _WIN32
660 /* signal handler for fatal errors */
661 static void sig_error(int signum, siginfo_t *siginf, void *puc)
663 rt_context *rc = &g_rtctxt;
664 rt_getcontext(puc, rc);
666 switch(signum) {
667 case SIGFPE:
668 switch(siginf->si_code) {
669 case FPE_INTDIV:
670 case FPE_FLTDIV:
671 rt_error("division by zero");
672 break;
673 default:
674 rt_error("floating point exception");
675 break;
677 break;
678 case SIGBUS:
679 case SIGSEGV:
680 rt_error("invalid memory access");
681 break;
682 case SIGILL:
683 rt_error("illegal instruction");
684 break;
685 case SIGABRT:
686 rt_error("abort() called");
687 break;
688 default:
689 rt_error("caught signal %d", signum);
690 break;
692 rt_exit(255);
695 #ifndef SA_SIGINFO
696 # define SA_SIGINFO 0x00000004u
697 #endif
699 /* Generate a stack backtrace when a CPU exception occurs. */
700 static void set_exception_handler(void)
702 struct sigaction sigact;
703 /* install TCC signal handlers to print debug info on fatal
704 runtime errors */
705 sigact.sa_flags = SA_SIGINFO | SA_RESETHAND;
706 #if 0//def SIGSTKSZ // this causes signals not to work at all on some (older) linuxes
707 sigact.sa_flags |= SA_ONSTACK;
708 #endif
709 sigact.sa_sigaction = sig_error;
710 sigemptyset(&sigact.sa_mask);
711 sigaction(SIGFPE, &sigact, NULL);
712 sigaction(SIGILL, &sigact, NULL);
713 sigaction(SIGSEGV, &sigact, NULL);
714 sigaction(SIGBUS, &sigact, NULL);
715 sigaction(SIGABRT, &sigact, NULL);
716 #if 0//def SIGSTKSZ
717 /* This allows stack overflow to be reported instead of a SEGV */
719 stack_t ss;
720 static unsigned char stack[SIGSTKSZ] __attribute__((aligned(16)));
722 ss.ss_sp = stack;
723 ss.ss_size = SIGSTKSZ;
724 ss.ss_flags = 0;
725 sigaltstack(&ss, NULL);
727 #endif
730 #else /* WIN32 */
732 /* signal handler for fatal errors */
733 static long __stdcall cpu_exception_handler(EXCEPTION_POINTERS *ex_info)
735 rt_context *rc = &g_rtctxt;
736 unsigned code;
737 rt_getcontext(ex_info->ContextRecord, rc);
739 switch (code = ex_info->ExceptionRecord->ExceptionCode) {
740 case EXCEPTION_ACCESS_VIOLATION:
741 rt_error("invalid memory access");
742 break;
743 case EXCEPTION_STACK_OVERFLOW:
744 rt_error("stack overflow");
745 break;
746 case EXCEPTION_INT_DIVIDE_BY_ZERO:
747 rt_error("division by zero");
748 break;
749 case EXCEPTION_BREAKPOINT:
750 case EXCEPTION_SINGLE_STEP:
751 rc->ip = *(addr_t*)rc->sp;
752 rt_error("breakpoint/single-step exception:");
753 return EXCEPTION_CONTINUE_SEARCH;
754 default:
755 rt_error("caught exception %08x", code);
756 break;
758 if (rc->do_jmp)
759 rt_exit(255);
760 return EXCEPTION_EXECUTE_HANDLER;
763 /* Generate a stack backtrace when a CPU exception occurs. */
764 static void set_exception_handler(void)
766 SetUnhandledExceptionFilter(cpu_exception_handler);
769 #endif
771 /* ------------------------------------------------------------- */
772 /* return the PC at frame level 'level'. Return negative if not found */
773 #if defined(__i386__) || defined(__x86_64__)
774 static int rt_get_caller_pc(addr_t *paddr, rt_context *rc, int level)
776 addr_t ip, fp;
777 if (level == 0) {
778 ip = rc->ip;
779 } else {
780 ip = 0;
781 fp = rc->fp;
782 while (--level) {
783 /* XXX: check address validity with program info */
784 if (fp <= 0x1000)
785 break;
786 fp = ((addr_t *)fp)[0];
788 if (fp > 0x1000)
789 ip = ((addr_t *)fp)[1];
791 if (ip <= 0x1000)
792 return -1;
793 *paddr = ip;
794 return 0;
797 #elif defined(__arm__)
798 static int rt_get_caller_pc(addr_t *paddr, rt_context *rc, int level)
800 /* XXX: only supports linux */
801 #if !defined(__linux__)
802 return -1;
803 #else
804 if (level == 0) {
805 *paddr = rc->ip;
806 } else {
807 addr_t fp = rc->fp;
808 addr_t sp = rc->sp;
809 if (sp < 0x1000)
810 sp = 0x1000;
811 /* XXX: specific to tinycc stack frames */
812 if (fp < sp + 12 || fp & 3)
813 return -1;
814 while (--level) {
815 sp = ((addr_t *)fp)[-2];
816 if (sp < fp || sp - fp > 16 || sp & 3)
817 return -1;
818 fp = ((addr_t *)fp)[-3];
819 if (fp <= sp || fp - sp < 12 || fp & 3)
820 return -1;
822 /* XXX: check address validity with program info */
823 *paddr = ((addr_t *)fp)[-1];
825 return 0;
826 #endif
829 #elif defined(__aarch64__)
830 static int rt_get_caller_pc(addr_t *paddr, rt_context *rc, int level)
832 if (level == 0) {
833 *paddr = rc->ip;
834 } else {
835 addr_t *fp = (addr_t*)rc->fp;
836 while (--level)
837 fp = (addr_t *)fp[0];
838 *paddr = fp[1];
840 return 0;
843 #else
844 #warning add arch specific rt_get_caller_pc()
845 static int rt_get_caller_pc(addr_t *paddr, rt_context *rc, int level)
847 return -1;
850 #endif
851 #endif /* CONFIG_TCC_BACKTRACE */
852 /* ------------------------------------------------------------- */
853 #ifdef CONFIG_TCC_STATIC
855 /* dummy function for profiling */
856 ST_FUNC void *dlopen(const char *filename, int flag)
858 return NULL;
861 ST_FUNC void dlclose(void *p)
865 ST_FUNC const char *dlerror(void)
867 return "error";
870 typedef struct TCCSyms {
871 char *str;
872 void *ptr;
873 } TCCSyms;
876 /* add the symbol you want here if no dynamic linking is done */
877 static TCCSyms tcc_syms[] = {
878 #if !defined(CONFIG_TCCBOOT)
879 #define TCCSYM(a) { #a, &a, },
880 TCCSYM(printf)
881 TCCSYM(fprintf)
882 TCCSYM(fopen)
883 TCCSYM(fclose)
884 #undef TCCSYM
885 #endif
886 { NULL, NULL },
889 ST_FUNC void *dlsym(void *handle, const char *symbol)
891 TCCSyms *p;
892 p = tcc_syms;
893 while (p->str != NULL) {
894 if (!strcmp(p->str, symbol))
895 return p->ptr;
896 p++;
898 return NULL;
901 #endif /* CONFIG_TCC_STATIC */
902 #endif /* TCC_IS_NATIVE */
903 /* ------------------------------------------------------------- */