Multiple fixes for 64 bit sections
[tinycc.git] / tccrun.c
blob2ea3c4916df6ed4ba1a467d0a800957ced830ec6
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 CONFIG_TCC_BACKTRACE
24 ST_DATA int rt_num_callers = 6;
25 ST_DATA const char **rt_bound_error_msg;
26 ST_DATA void *rt_prog_main;
27 #endif
29 #ifdef _WIN32
30 #define ucontext_t CONTEXT
31 #endif
33 static void set_pages_executable(void *ptr, unsigned long length);
34 static void set_exception_handler(void);
35 static int rt_get_caller_pc(uplong *paddr, ucontext_t *uc, int level);
36 static void rt_error(ucontext_t *uc, const char *fmt, ...);
37 static int tcc_relocate_ex(TCCState *s1, void *ptr);
39 #if defined TCC_TARGET_X86_64 && defined TCC_TARGET_PE
40 static void win64_add_function_table(TCCState *s1);
41 #endif
44 /* ------------------------------------------------------------- */
45 /* Do all relocations (needed before using tcc_get_symbol())
46 Returns -1 on error. */
48 LIBTCCAPI int tcc_relocate(TCCState *s1)
50 int ret;
51 #ifdef HAVE_SELINUX
52 /* Use mmap instead of malloc for Selinux
53 Ref http://www.gnu.org/s/libc/manual/html_node/File-Size.html */
54 char tmpfname[] = "/tmp/.tccrunXXXXXX";
55 int fd = mkstemp (tmpfname);
56 if ((ret= tcc_relocate_ex(s1,NULL)) < 0)return -1;
57 s1->mem_size=ret;
58 unlink (tmpfname); ftruncate (fd, s1->mem_size);
59 s1->write_mem = mmap (NULL, ret, PROT_READ|PROT_WRITE,
60 MAP_SHARED, fd, 0);
61 if(s1->write_mem == MAP_FAILED){
62 tcc_error("/tmp not writeable");
63 return -1;
65 s1->runtime_mem = mmap (NULL, ret, PROT_READ|PROT_EXEC,
66 MAP_SHARED, fd, 0);
67 if(s1->runtime_mem == MAP_FAILED){
68 tcc_error("/tmp not executable");
69 return -1;
71 ret = tcc_relocate_ex(s1, s1->write_mem);
72 #else
73 ret = tcc_relocate_ex(s1, NULL);
74 if (-1 != ret) {
75 s1->runtime_mem = tcc_malloc(ret);
76 ret = tcc_relocate_ex(s1, s1->runtime_mem);
78 #endif
79 return ret;
82 /* launch the compiled program with the given arguments */
83 LIBTCCAPI int tcc_run(TCCState *s1, int argc, char **argv)
85 int (*prog_main)(int, char **);
86 int ret;
88 if (tcc_relocate(s1) < 0)
89 return -1;
91 prog_main = tcc_get_symbol_err(s1, "main");
93 #ifdef CONFIG_TCC_BACKTRACE
94 if (s1->do_debug) {
95 set_exception_handler();
96 rt_prog_main = prog_main;
98 #endif
100 #ifdef CONFIG_TCC_BCHECK
101 if (s1->do_bounds_check) {
102 void (*bound_init)(void);
103 void (*bound_exit)(void);
104 /* set error function */
105 rt_bound_error_msg = tcc_get_symbol_err(s1, "__bound_error_msg");
106 /* XXX: use .init section so that it also work in binary ? */
107 bound_init = tcc_get_symbol_err(s1, "__bound_init");
108 bound_exit = tcc_get_symbol_err(s1, "__bound_exit");
109 bound_init();
110 ret = (*prog_main)(argc, argv);
111 bound_exit();
112 } else
113 #endif
114 ret = (*prog_main)(argc, argv);
115 return ret;
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 #if defined TCC_TARGET_X86_64 && defined TCC_TARGET_PE
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 PUB_FUNC void tcc_set_num_callers(int n)
225 rt_num_callers = n;
228 /* print the position in the source file of PC value 'pc' by reading
229 the stabs debug information */
230 static uplong rt_printline(uplong wanted_pc, const char *msg)
232 char func_name[128], last_func_name[128];
233 uplong func_addr, last_pc, pc;
234 const char *incl_files[INCLUDE_STACK_SIZE];
235 int incl_index, len, last_line_num, i;
236 const char *str, *p;
238 Stab_Sym *stab_sym = NULL, *stab_sym_end, *sym;
239 int stab_len = 0;
240 char *stab_str = NULL;
242 if (stab_section) {
243 stab_len = stab_section->data_offset;
244 stab_sym = (Stab_Sym *)stab_section->data;
245 stab_str = stabstr_section->data;
248 func_name[0] = '\0';
249 func_addr = 0;
250 incl_index = 0;
251 last_func_name[0] = '\0';
252 last_pc = (uplong)-1;
253 last_line_num = 1;
255 if (!stab_sym)
256 goto no_stabs;
258 stab_sym_end = (Stab_Sym*)((char*)stab_sym + stab_len);
259 for (sym = stab_sym + 1; sym < stab_sym_end; ++sym) {
260 switch(sym->n_type) {
261 /* function start or end */
262 case N_FUN:
263 if (sym->n_strx == 0) {
264 /* we test if between last line and end of function */
265 pc = sym->n_value + func_addr;
266 if (wanted_pc >= last_pc && wanted_pc < pc)
267 goto found;
268 func_name[0] = '\0';
269 func_addr = 0;
270 } else {
271 str = stab_str + sym->n_strx;
272 p = strchr(str, ':');
273 if (!p) {
274 pstrcpy(func_name, sizeof(func_name), str);
275 } else {
276 len = p - str;
277 if (len > sizeof(func_name) - 1)
278 len = sizeof(func_name) - 1;
279 memcpy(func_name, str, len);
280 func_name[len] = '\0';
282 func_addr = sym->n_value;
284 break;
285 /* line number info */
286 case N_SLINE:
287 pc = sym->n_value + func_addr;
288 if (wanted_pc >= last_pc && wanted_pc < pc)
289 goto found;
290 last_pc = pc;
291 last_line_num = sym->n_desc;
292 /* XXX: slow! */
293 strcpy(last_func_name, func_name);
294 break;
295 /* include files */
296 case N_BINCL:
297 str = stab_str + sym->n_strx;
298 add_incl:
299 if (incl_index < INCLUDE_STACK_SIZE) {
300 incl_files[incl_index++] = str;
302 break;
303 case N_EINCL:
304 if (incl_index > 1)
305 incl_index--;
306 break;
307 case N_SO:
308 if (sym->n_strx == 0) {
309 incl_index = 0; /* end of translation unit */
310 } else {
311 str = stab_str + sym->n_strx;
312 /* do not add path */
313 len = strlen(str);
314 if (len > 0 && str[len - 1] != '/')
315 goto add_incl;
317 break;
321 no_stabs:
322 /* second pass: we try symtab symbols (no line number info) */
323 incl_index = 0;
324 if (symtab_section)
326 ElfW(Sym) *sym, *sym_end;
327 int type;
329 sym_end = (ElfW(Sym) *)(symtab_section->data + symtab_section->data_offset);
330 for(sym = (ElfW(Sym) *)symtab_section->data + 1;
331 sym < sym_end;
332 sym++) {
333 type = ELFW(ST_TYPE)(sym->st_info);
334 if (type == STT_FUNC || type == STT_GNU_IFUNC) {
335 if (wanted_pc >= sym->st_value &&
336 wanted_pc < sym->st_value + sym->st_size) {
337 pstrcpy(last_func_name, sizeof(last_func_name),
338 strtab_section->data + sym->st_name);
339 func_addr = sym->st_value;
340 goto found;
345 /* did not find any info: */
346 fprintf(stderr, "%s %p ???\n", msg, (void*)wanted_pc);
347 fflush(stderr);
348 return 0;
349 found:
350 i = incl_index;
351 if (i > 0)
352 fprintf(stderr, "%s:%d: ", incl_files[--i], last_line_num);
353 fprintf(stderr, "%s %p", msg, (void*)wanted_pc);
354 if (last_func_name[0] != '\0')
355 fprintf(stderr, " %s()", last_func_name);
356 if (--i >= 0) {
357 fprintf(stderr, " (included from ");
358 for (;;) {
359 fprintf(stderr, "%s", incl_files[i]);
360 if (--i < 0)
361 break;
362 fprintf(stderr, ", ");
364 fprintf(stderr, ")");
366 fprintf(stderr, "\n");
367 fflush(stderr);
368 return func_addr;
371 /* emit a run time error at position 'pc' */
372 static void rt_error(ucontext_t *uc, const char *fmt, ...)
374 va_list ap;
375 uplong pc;
376 int i;
378 fprintf(stderr, "Runtime error: ");
379 va_start(ap, fmt);
380 vfprintf(stderr, fmt, ap);
381 va_end(ap);
382 fprintf(stderr, "\n");
384 for(i=0;i<rt_num_callers;i++) {
385 if (rt_get_caller_pc(&pc, uc, i) < 0)
386 break;
387 pc = rt_printline(pc, i ? "by" : "at");
388 if (pc == (uplong)rt_prog_main && pc)
389 break;
393 /* ------------------------------------------------------------- */
394 #ifndef _WIN32
396 /* signal handler for fatal errors */
397 static void sig_error(int signum, siginfo_t *siginf, void *puc)
399 ucontext_t *uc = puc;
401 switch(signum) {
402 case SIGFPE:
403 switch(siginf->si_code) {
404 case FPE_INTDIV:
405 case FPE_FLTDIV:
406 rt_error(uc, "division by zero");
407 break;
408 default:
409 rt_error(uc, "floating point exception");
410 break;
412 break;
413 case SIGBUS:
414 case SIGSEGV:
415 if (rt_bound_error_msg && *rt_bound_error_msg)
416 rt_error(uc, *rt_bound_error_msg);
417 else
418 rt_error(uc, "dereferencing invalid pointer");
419 break;
420 case SIGILL:
421 rt_error(uc, "illegal instruction");
422 break;
423 case SIGABRT:
424 rt_error(uc, "abort() called");
425 break;
426 default:
427 rt_error(uc, "caught signal %d", signum);
428 break;
430 exit(255);
433 /* Generate a stack backtrace when a CPU exception occurs. */
434 static void set_exception_handler(void)
436 struct sigaction sigact;
437 /* install TCC signal handlers to print debug info on fatal
438 runtime errors */
439 sigact.sa_flags = SA_SIGINFO | SA_RESETHAND;
440 sigact.sa_sigaction = sig_error;
441 sigemptyset(&sigact.sa_mask);
442 sigaction(SIGFPE, &sigact, NULL);
443 sigaction(SIGILL, &sigact, NULL);
444 sigaction(SIGSEGV, &sigact, NULL);
445 sigaction(SIGBUS, &sigact, NULL);
446 sigaction(SIGABRT, &sigact, NULL);
449 /* ------------------------------------------------------------- */
450 #ifdef __i386__
452 /* fix for glibc 2.1 */
453 #ifndef REG_EIP
454 #define REG_EIP EIP
455 #define REG_EBP EBP
456 #endif
458 /* return the PC at frame level 'level'. Return non zero if not found */
459 static int rt_get_caller_pc(unsigned long *paddr, ucontext_t *uc, int level)
461 unsigned long fp;
462 int i;
464 if (level == 0) {
465 #if defined(__APPLE__)
466 *paddr = uc->uc_mcontext->__ss.__eip;
467 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
468 *paddr = uc->uc_mcontext.mc_eip;
469 #elif defined(__dietlibc__)
470 *paddr = uc->uc_mcontext.eip;
471 #else
472 *paddr = uc->uc_mcontext.gregs[REG_EIP];
473 #endif
474 return 0;
475 } else {
476 #if defined(__APPLE__)
477 fp = uc->uc_mcontext->__ss.__ebp;
478 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
479 fp = uc->uc_mcontext.mc_ebp;
480 #elif defined(__dietlibc__)
481 fp = uc->uc_mcontext.ebp;
482 #else
483 fp = uc->uc_mcontext.gregs[REG_EBP];
484 #endif
485 for(i=1;i<level;i++) {
486 /* XXX: check address validity with program info */
487 if (fp <= 0x1000 || fp >= 0xc0000000)
488 return -1;
489 fp = ((unsigned long *)fp)[0];
491 *paddr = ((unsigned long *)fp)[1];
492 return 0;
496 /* ------------------------------------------------------------- */
497 #elif defined(__x86_64__)
499 /* return the PC at frame level 'level'. Return non zero if not found */
500 static int rt_get_caller_pc(unsigned long *paddr,
501 ucontext_t *uc, int level)
503 unsigned long fp;
504 int i;
506 if (level == 0) {
507 /* XXX: only support linux */
508 #if defined(__APPLE__)
509 *paddr = uc->uc_mcontext->__ss.__rip;
510 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
511 *paddr = uc->uc_mcontext.mc_rip;
512 #else
513 *paddr = uc->uc_mcontext.gregs[REG_RIP];
514 #endif
515 return 0;
516 } else {
517 #if defined(__APPLE__)
518 fp = uc->uc_mcontext->__ss.__rbp;
519 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
520 fp = uc->uc_mcontext.mc_rbp;
521 #else
522 fp = uc->uc_mcontext.gregs[REG_RBP];
523 #endif
524 for(i=1;i<level;i++) {
525 /* XXX: check address validity with program info */
526 if (fp <= 0x1000)
527 return -1;
528 fp = ((unsigned long *)fp)[0];
530 *paddr = ((unsigned long *)fp)[1];
531 return 0;
535 /* ------------------------------------------------------------- */
536 #elif defined(__arm__)
538 /* return the PC at frame level 'level'. Return negative if not found */
539 static int rt_get_caller_pc(unsigned long *paddr,
540 ucontext_t *uc, int level)
542 uint32_t fp, sp;
543 int i;
545 if (level == 0) {
546 /* XXX: only supports linux */
547 #if defined(__linux__)
548 *paddr = uc->uc_mcontext.arm_pc;
549 #else
550 return -1;
551 #endif
552 return 0;
553 } else {
554 #if defined(__linux__)
555 fp = uc->uc_mcontext.arm_fp;
556 sp = uc->uc_mcontext.arm_sp;
557 if (sp < 0x1000)
558 sp = 0x1000;
559 #else
560 return -1;
561 #endif
562 /* XXX: specific to tinycc stack frames */
563 if (fp < sp + 12 || fp & 3)
564 return -1;
565 for(i = 1; i < level; i++) {
566 sp = ((uint32_t *)fp)[-2];
567 if (sp < fp || sp - fp > 16 || sp & 3)
568 return -1;
569 fp = ((uint32_t *)fp)[-3];
570 if (fp <= sp || fp - sp < 12 || fp & 3)
571 return -1;
573 /* XXX: check address validity with program info */
574 *paddr = ((uint32_t *)fp)[-1];
575 return 0;
579 /* ------------------------------------------------------------- */
580 #else
582 #warning add arch specific rt_get_caller_pc()
583 static int rt_get_caller_pc(unsigned long *paddr,
584 ucontext_t *uc, int level)
586 return -1;
589 #endif /* !__i386__ */
591 /* ------------------------------------------------------------- */
592 #else /* WIN32 */
594 static long __stdcall cpu_exception_handler(EXCEPTION_POINTERS *ex_info)
596 EXCEPTION_RECORD *er = ex_info->ExceptionRecord;
597 CONTEXT *uc = ex_info->ContextRecord;
598 switch (er->ExceptionCode) {
599 case EXCEPTION_ACCESS_VIOLATION:
600 if (rt_bound_error_msg && *rt_bound_error_msg)
601 rt_error(uc, *rt_bound_error_msg);
602 else
603 rt_error(uc, "access violation");
604 break;
605 case EXCEPTION_STACK_OVERFLOW:
606 rt_error(uc, "stack overflow");
607 break;
608 case EXCEPTION_INT_DIVIDE_BY_ZERO:
609 rt_error(uc, "division by zero");
610 break;
611 default:
612 rt_error(uc, "exception caught");
613 break;
615 exit(-1);
616 return EXCEPTION_CONTINUE_SEARCH;
619 /* Generate a stack backtrace when a CPU exception occurs. */
620 static void set_exception_handler(void)
622 SetUnhandledExceptionFilter(cpu_exception_handler);
625 #ifdef TCC_TARGET_PE
626 #ifdef TCC_TARGET_X86_64
627 static void win64_add_function_table(TCCState *s1)
629 RtlAddFunctionTable(
630 (RUNTIME_FUNCTION*)(uplong)s1->uw_pdata->sh_addr,
631 s1->uw_pdata->data_offset / sizeof (RUNTIME_FUNCTION),
632 (uplong)text_section->sh_addr
635 #endif
636 #endif
638 /* return the PC at frame level 'level'. Return non zero if not found */
639 static int rt_get_caller_pc(uplong *paddr, CONTEXT *uc, int level)
641 uplong fp, pc;
642 int i;
643 #ifdef _WIN64
644 pc = uc->Rip;
645 fp = uc->Rbp;
646 #else
647 pc = uc->Eip;
648 fp = uc->Ebp;
649 #endif
650 if (level > 0) {
651 for(i=1;i<level;i++) {
652 /* XXX: check address validity with program info */
653 if (fp <= 0x1000 || fp >= 0xc0000000)
654 return -1;
655 fp = ((uplong*)fp)[0];
657 pc = ((uplong*)fp)[1];
659 *paddr = pc;
660 return 0;
663 #endif /* _WIN32 */
664 #endif /* CONFIG_TCC_BACKTRACE */
665 /* ------------------------------------------------------------- */
667 #ifdef CONFIG_TCC_STATIC
669 #define RTLD_LAZY 0x001
670 #define RTLD_NOW 0x002
671 #define RTLD_GLOBAL 0x100
672 #define RTLD_DEFAULT NULL
674 /* dummy function for profiling */
675 ST_FUNC void *dlopen(const char *filename, int flag)
677 return NULL;
680 ST_FUNC void dlclose(void *p)
684 const char *dlerror(void)
686 return "error";
689 typedef struct TCCSyms {
690 char *str;
691 void *ptr;
692 } TCCSyms;
694 #define TCCSYM(a) { #a, &a, },
696 /* add the symbol you want here if no dynamic linking is done */
697 static TCCSyms tcc_syms[] = {
698 #if !defined(CONFIG_TCCBOOT)
699 TCCSYM(printf)
700 TCCSYM(fprintf)
701 TCCSYM(fopen)
702 TCCSYM(fclose)
703 #endif
704 { NULL, NULL },
707 ST_FUNC void *resolve_sym(TCCState *s1, const char *symbol)
709 TCCSyms *p;
710 p = tcc_syms;
711 while (p->str != NULL) {
712 if (!strcmp(p->str, symbol))
713 return p->ptr;
714 p++;
716 return NULL;
719 #elif !defined(_WIN32)
721 ST_FUNC void *resolve_sym(TCCState *s1, const char *sym)
723 return dlsym(RTLD_DEFAULT, sym);
726 #endif /* CONFIG_TCC_STATIC */
728 /* ------------------------------------------------------------- */