tccpp: signal missing #endif error
[tinycc/kirr.git] / tccrun.c
blob25f24777b24d7dc0318f0b446dfe160f86076e67
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 /* ------------------------------------------------------------- */
34 /* Do all relocations (needed before using tcc_get_symbol())
35 Returns -1 on error. */
37 int tcc_relocate(TCCState *s1)
39 int ret;
41 ret = tcc_relocate_ex(s1, NULL);
42 if (-1 != ret) {
43 s1->runtime_mem = tcc_malloc(ret);
44 ret = tcc_relocate_ex(s1, s1->runtime_mem);
46 return ret;
49 /* launch the compiled program with the given arguments */
50 int tcc_run(TCCState *s1, int argc, char **argv)
52 int (*prog_main)(int, char **);
54 if (tcc_relocate(s1) < 0)
55 return -1;
57 prog_main = tcc_get_symbol_err(s1, "main");
59 #ifdef CONFIG_TCC_BACKTRACE
60 if (s1->do_debug)
61 set_exception_handler();
62 #endif
64 #ifdef CONFIG_TCC_BCHECK
65 if (s1->do_bounds_check) {
66 void (*bound_init)(void);
67 void (*bound_exit)(void);
68 int ret;
69 /* set error function */
70 rt_bound_error_msg = tcc_get_symbol_err(s1, "__bound_error_msg");
71 rt_prog_main = prog_main;
72 /* XXX: use .init section so that it also work in binary ? */
73 bound_init = tcc_get_symbol_err(s1, "__bound_init");
74 bound_exit = tcc_get_symbol_err(s1, "__bound_exit");
75 bound_init();
76 ret = (*prog_main)(argc, argv);
77 bound_exit();
78 return ret;
80 #endif
82 #ifdef TCC_TARGET_PE
84 unsigned char *p = tcc_get_symbol(s1, "tinyc_no_getbp");
85 if (p) *p = 0;
87 #endif
88 return (*prog_main)(argc, argv);
92 /* relocate code. Return -1 on error, required size if ptr is NULL,
93 otherwise copy code into buffer passed by the caller */
94 static int tcc_relocate_ex(TCCState *s1, void *ptr)
96 Section *s;
97 unsigned long offset, length;
98 uplong mem;
99 int i;
101 if (0 == s1->runtime_added) {
102 s1->runtime_added = 1;
103 s1->nb_errors = 0;
104 #ifdef TCC_TARGET_PE
105 pe_output_file(s1, NULL);
106 #else
107 tcc_add_runtime(s1);
108 relocate_common_syms();
109 tcc_add_linker_symbols(s1);
110 build_got_entries(s1);
111 #endif
112 if (s1->nb_errors)
113 return -1;
116 offset = 0, mem = (uplong)ptr;
117 for(i = 1; i < s1->nb_sections; i++) {
118 s = s1->sections[i];
119 if (0 == (s->sh_flags & SHF_ALLOC))
120 continue;
121 length = s->data_offset;
122 s->sh_addr = mem ? (mem + offset + 15) & ~15 : 0;
123 offset = (offset + length + 15) & ~15;
125 offset += 16;
127 /* relocate symbols */
128 relocate_syms(s1, 1);
129 if (s1->nb_errors)
130 return -1;
132 #if defined TCC_TARGET_X86_64 && !defined TCC_TARGET_PE
133 s1->runtime_plt_and_got_offset = 0;
134 s1->runtime_plt_and_got = (char *)(mem + offset);
135 /* double the size of the buffer for got and plt entries
136 XXX: calculate exact size for them? */
137 offset *= 2;
138 #endif
140 if (0 == mem)
141 return offset;
143 /* relocate each section */
144 for(i = 1; i < s1->nb_sections; i++) {
145 s = s1->sections[i];
146 if (s->reloc)
147 relocate_section(s1, s);
150 for(i = 1; i < s1->nb_sections; i++) {
151 s = s1->sections[i];
152 if (0 == (s->sh_flags & SHF_ALLOC))
153 continue;
154 length = s->data_offset;
155 // printf("%-12s %08x %04x\n", s->name, s->sh_addr, length);
156 ptr = (void*)(uplong)s->sh_addr;
157 if (NULL == s->data || s->sh_type == SHT_NOBITS)
158 memset(ptr, 0, length);
159 else
160 memcpy(ptr, s->data, length);
161 /* mark executable sections as executable in memory */
162 if (s->sh_flags & SHF_EXECINSTR)
163 set_pages_executable(ptr, length);
166 #if defined TCC_TARGET_X86_64 && !defined TCC_TARGET_PE
167 set_pages_executable(s1->runtime_plt_and_got,
168 s1->runtime_plt_and_got_offset);
169 #endif
170 return 0;
173 /* ------------------------------------------------------------- */
174 /* allow to run code in memory */
176 static void set_pages_executable(void *ptr, unsigned long length)
178 #ifdef _WIN32
179 unsigned long old_protect;
180 VirtualProtect(ptr, length, PAGE_EXECUTE_READWRITE, &old_protect);
181 #else
182 unsigned long start, end;
183 start = (uplong)ptr & ~(PAGESIZE - 1);
184 end = (uplong)ptr + length;
185 end = (end + PAGESIZE - 1) & ~(PAGESIZE - 1);
186 mprotect((void *)start, end - start, PROT_READ | PROT_WRITE | PROT_EXEC);
187 #endif
190 /* ------------------------------------------------------------- */
191 #ifdef CONFIG_TCC_BACKTRACE
193 /* print the position in the source file of PC value 'pc' by reading
194 the stabs debug information */
195 static uplong rt_printline(uplong wanted_pc)
197 Stab_Sym *sym, *sym_end;
198 char func_name[128], last_func_name[128];
199 unsigned long func_addr, last_pc, pc;
200 const char *incl_files[INCLUDE_STACK_SIZE];
201 int incl_index, len, last_line_num, i;
202 const char *str, *p;
204 fprintf(stderr, "0x%08lx:", (unsigned long)wanted_pc);
206 func_name[0] = '\0';
207 func_addr = 0;
208 incl_index = 0;
209 last_func_name[0] = '\0';
210 last_pc = 0xffffffff;
211 last_line_num = 1;
212 sym = (Stab_Sym *)stab_section->data + 1;
213 sym_end = (Stab_Sym *)(stab_section->data + stab_section->data_offset);
214 while (sym < sym_end) {
215 switch(sym->n_type) {
216 /* function start or end */
217 case N_FUN:
218 if (sym->n_strx == 0) {
219 /* we test if between last line and end of function */
220 pc = sym->n_value + func_addr;
221 if (wanted_pc >= last_pc && wanted_pc < pc)
222 goto found;
223 func_name[0] = '\0';
224 func_addr = 0;
225 } else {
226 str = stabstr_section->data + sym->n_strx;
227 p = strchr(str, ':');
228 if (!p) {
229 pstrcpy(func_name, sizeof(func_name), str);
230 } else {
231 len = p - str;
232 if (len > sizeof(func_name) - 1)
233 len = sizeof(func_name) - 1;
234 memcpy(func_name, str, len);
235 func_name[len] = '\0';
237 func_addr = sym->n_value;
239 break;
240 /* line number info */
241 case N_SLINE:
242 pc = sym->n_value + func_addr;
243 if (wanted_pc >= last_pc && wanted_pc < pc)
244 goto found;
245 last_pc = pc;
246 last_line_num = sym->n_desc;
247 /* XXX: slow! */
248 strcpy(last_func_name, func_name);
249 break;
250 /* include files */
251 case N_BINCL:
252 str = stabstr_section->data + sym->n_strx;
253 add_incl:
254 if (incl_index < INCLUDE_STACK_SIZE) {
255 incl_files[incl_index++] = str;
257 break;
258 case N_EINCL:
259 if (incl_index > 1)
260 incl_index--;
261 break;
262 case N_SO:
263 if (sym->n_strx == 0) {
264 incl_index = 0; /* end of translation unit */
265 } else {
266 str = stabstr_section->data + sym->n_strx;
267 /* do not add path */
268 len = strlen(str);
269 if (len > 0 && str[len - 1] != '/')
270 goto add_incl;
272 break;
274 sym++;
277 /* second pass: we try symtab symbols (no line number info) */
278 incl_index = 0;
280 ElfW(Sym) *sym, *sym_end;
281 int type;
283 sym_end = (ElfW(Sym) *)(symtab_section->data + symtab_section->data_offset);
284 for(sym = (ElfW(Sym) *)symtab_section->data + 1;
285 sym < sym_end;
286 sym++) {
287 type = ELFW(ST_TYPE)(sym->st_info);
288 if (type == STT_FUNC) {
289 if (wanted_pc >= sym->st_value &&
290 wanted_pc < sym->st_value + sym->st_size) {
291 pstrcpy(last_func_name, sizeof(last_func_name),
292 strtab_section->data + sym->st_name);
293 func_addr = sym->st_value;
294 goto found;
299 /* did not find any info: */
300 fprintf(stderr, " ???\n");
301 return 0;
302 found:
303 if (last_func_name[0] != '\0') {
304 fprintf(stderr, " %s()", last_func_name);
306 if (incl_index > 0) {
307 fprintf(stderr, " (%s:%d",
308 incl_files[incl_index - 1], last_line_num);
309 for(i = incl_index - 2; i >= 0; i--)
310 fprintf(stderr, ", included from %s", incl_files[i]);
311 fprintf(stderr, ")");
313 fprintf(stderr, "\n");
314 return func_addr;
317 /* emit a run time error at position 'pc' */
318 static void rt_error(ucontext_t *uc, const char *fmt, ...)
320 va_list ap;
321 uplong pc;
322 int i;
324 va_start(ap, fmt);
325 fprintf(stderr, "Runtime error: ");
326 vfprintf(stderr, fmt, ap);
327 fprintf(stderr, "\n");
329 for(i=0;i<num_callers;i++) {
330 if (rt_get_caller_pc(&pc, uc, i) < 0)
331 break;
332 if (i == 0)
333 fprintf(stderr, "at ");
334 else
335 fprintf(stderr, "by ");
336 pc = rt_printline(pc);
337 if (pc == (uplong)rt_prog_main && pc)
338 break;
340 exit(255);
341 va_end(ap);
344 /* ------------------------------------------------------------- */
345 #ifndef _WIN32
347 /* signal handler for fatal errors */
348 static void sig_error(int signum, siginfo_t *siginf, void *puc)
350 ucontext_t *uc = puc;
352 switch(signum) {
353 case SIGFPE:
354 switch(siginf->si_code) {
355 case FPE_INTDIV:
356 case FPE_FLTDIV:
357 rt_error(uc, "division by zero");
358 break;
359 default:
360 rt_error(uc, "floating point exception");
361 break;
363 break;
364 case SIGBUS:
365 case SIGSEGV:
366 if (rt_bound_error_msg && *rt_bound_error_msg)
367 rt_error(uc, *rt_bound_error_msg);
368 else
369 rt_error(uc, "dereferencing invalid pointer");
370 break;
371 case SIGILL:
372 rt_error(uc, "illegal instruction");
373 break;
374 case SIGABRT:
375 rt_error(uc, "abort() called");
376 break;
377 default:
378 rt_error(uc, "caught signal %d", signum);
379 break;
381 exit(255);
384 /* Generate a stack backtrace when a CPU exception occurs. */
385 static void set_exception_handler(void)
387 struct sigaction sigact;
388 /* install TCC signal handlers to print debug info on fatal
389 runtime errors */
390 sigact.sa_flags = SA_SIGINFO | SA_RESETHAND;
391 sigact.sa_sigaction = sig_error;
392 sigemptyset(&sigact.sa_mask);
393 sigaction(SIGFPE, &sigact, NULL);
394 sigaction(SIGILL, &sigact, NULL);
395 sigaction(SIGSEGV, &sigact, NULL);
396 sigaction(SIGBUS, &sigact, NULL);
397 sigaction(SIGABRT, &sigact, NULL);
400 /* ------------------------------------------------------------- */
401 #ifdef __i386__
403 /* fix for glibc 2.1 */
404 #ifndef REG_EIP
405 #define REG_EIP EIP
406 #define REG_EBP EBP
407 #endif
409 /* return the PC at frame level 'level'. Return non zero if not found */
410 static int rt_get_caller_pc(unsigned long *paddr, ucontext_t *uc, int level)
412 unsigned long fp;
413 int i;
415 if (level == 0) {
416 #if defined(__FreeBSD__)
417 *paddr = uc->uc_mcontext.mc_eip;
418 #elif defined(__dietlibc__)
419 *paddr = uc->uc_mcontext.eip;
420 #else
421 *paddr = uc->uc_mcontext.gregs[REG_EIP];
422 #endif
423 return 0;
424 } else {
425 #if defined(__FreeBSD__)
426 fp = uc->uc_mcontext.mc_ebp;
427 #elif defined(__dietlibc__)
428 fp = uc->uc_mcontext.ebp;
429 #else
430 fp = uc->uc_mcontext.gregs[REG_EBP];
431 #endif
432 for(i=1;i<level;i++) {
433 /* XXX: check address validity with program info */
434 if (fp <= 0x1000 || fp >= 0xc0000000)
435 return -1;
436 fp = ((unsigned long *)fp)[0];
438 *paddr = ((unsigned long *)fp)[1];
439 return 0;
443 /* ------------------------------------------------------------- */
444 #elif defined(__x86_64__)
446 /* return the PC at frame level 'level'. Return non zero if not found */
447 static int rt_get_caller_pc(unsigned long *paddr,
448 ucontext_t *uc, int level)
450 unsigned long fp;
451 int i;
453 if (level == 0) {
454 /* XXX: only support linux */
455 #if defined(__FreeBSD__)
456 *paddr = uc->uc_mcontext.mc_rip;
457 #else
458 *paddr = uc->uc_mcontext.gregs[REG_RIP];
459 #endif
460 return 0;
461 } else {
462 #if defined(__FreeBSD__)
463 fp = uc->uc_mcontext.mc_rbp;
464 #else
465 fp = uc->uc_mcontext.gregs[REG_RBP];
466 #endif
467 for(i=1;i<level;i++) {
468 /* XXX: check address validity with program info */
469 if (fp <= 0x1000)
470 return -1;
471 fp = ((unsigned long *)fp)[0];
473 *paddr = ((unsigned long *)fp)[1];
474 return 0;
478 /* ------------------------------------------------------------- */
479 #else
481 #warning add arch specific rt_get_caller_pc()
482 static int rt_get_caller_pc(unsigned long *paddr,
483 ucontext_t *uc, int level)
485 return -1;
488 #endif /* !__i386__ */
490 /* ------------------------------------------------------------- */
491 #else /* WIN32 */
493 static long __stdcall cpu_exception_handler(EXCEPTION_POINTERS *ex_info)
495 CONTEXT *uc = ex_info->ContextRecord;
497 EXCEPTION_RECORD *er = ex_info->ExceptionRecord;
498 printf("CPU exception: code=%08lx addr=%p\n",
499 er->ExceptionCode, er->ExceptionAddress);
501 if (rt_bound_error_msg && *rt_bound_error_msg)
502 rt_error(uc, *rt_bound_error_msg);
503 else
504 rt_error(uc, "dereferencing invalid pointer");
505 exit(255);
506 //return EXCEPTION_CONTINUE_SEARCH;
509 /* Generate a stack backtrace when a CPU exception occurs. */
510 static void set_exception_handler(void)
512 SetUnhandledExceptionFilter(cpu_exception_handler);
515 #ifdef _WIN64
516 #define Eip Rip
517 #define Ebp Rbp
518 #endif
520 /* return the PC at frame level 'level'. Return non zero if not found */
521 static int rt_get_caller_pc(uplong *paddr, CONTEXT *uc, int level)
523 uplong fp;
524 int i;
526 if (level == 0) {
527 *paddr = uc->Eip;
528 return 0;
529 } else {
530 fp = uc->Ebp;
531 for(i=1;i<level;i++) {
532 /* XXX: check address validity with program info */
533 if (fp <= 0x1000 || fp >= 0xc0000000)
534 return -1;
535 fp = ((uplong*)fp)[0];
537 *paddr = ((uplong*)fp)[1];
538 return 0;
542 #undef Eip
543 #undef Ebp
545 #endif /* _WIN32 */
546 #endif /* CONFIG_TCC_BACKTRACE */
547 /* ------------------------------------------------------------- */
549 #ifdef CONFIG_TCC_STATIC
551 #define RTLD_LAZY 0x001
552 #define RTLD_NOW 0x002
553 #define RTLD_GLOBAL 0x100
554 #define RTLD_DEFAULT NULL
556 /* dummy function for profiling */
557 void *dlopen(const char *filename, int flag)
559 return NULL;
562 void dlclose(void *p)
566 const char *dlerror(void)
568 return "error";
571 typedef struct TCCSyms {
572 char *str;
573 void *ptr;
574 } TCCSyms;
576 #define TCCSYM(a) { #a, &a, },
578 /* add the symbol you want here if no dynamic linking is done */
579 static TCCSyms tcc_syms[] = {
580 #if !defined(CONFIG_TCCBOOT)
581 TCCSYM(printf)
582 TCCSYM(fprintf)
583 TCCSYM(fopen)
584 TCCSYM(fclose)
585 #endif
586 { NULL, NULL },
589 void *resolve_sym(TCCState *s1, const char *symbol)
591 TCCSyms *p;
592 p = tcc_syms;
593 while (p->str != NULL) {
594 if (!strcmp(p->str, symbol))
595 return p->ptr;
596 p++;
598 return NULL;
601 #elif !defined(_WIN32)
603 void *resolve_sym(TCCState *s1, const char *sym)
605 return dlsym(RTLD_DEFAULT, sym);
608 #endif /* CONFIG_TCC_STATIC */
610 /* ------------------------------------------------------------- */