Fix R_ARM_REL32 relocation
[tinycc.git] / tccrun.c
blob41081ccd4ac8e1c859d805b56a67d116b64f72d3
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 ST_DATA int rt_num_callers = 6;
28 ST_DATA const char **rt_bound_error_msg;
29 ST_DATA void *rt_prog_main;
30 #endif
32 #ifdef _WIN32
33 #define ucontext_t CONTEXT
34 #endif
36 static void set_pages_executable(void *ptr, unsigned long length);
37 static void set_exception_handler(void);
38 static int rt_get_caller_pc(uplong *paddr, ucontext_t *uc, int level);
39 static void rt_error(ucontext_t *uc, const char *fmt, ...);
40 static int tcc_relocate_ex(TCCState *s1, void *ptr);
42 #ifdef _WIN64
43 static void win64_add_function_table(TCCState *s1);
44 #endif
46 /* ------------------------------------------------------------- */
47 /* Do all relocations (needed before using tcc_get_symbol())
48 Returns -1 on error. */
50 LIBTCCAPI int tcc_relocate(TCCState *s1)
52 int ret;
53 #ifdef HAVE_SELINUX
54 /* Use mmap instead of malloc for Selinux
55 Ref http://www.gnu.org/s/libc/manual/html_node/File-Size.html */
56 char tmpfname[] = "/tmp/.tccrunXXXXXX";
57 int fd = mkstemp (tmpfname);
58 if ((ret= tcc_relocate_ex(s1,NULL)) < 0)return -1;
59 s1->mem_size=ret;
60 unlink (tmpfname); ftruncate (fd, s1->mem_size);
61 s1->write_mem = mmap (NULL, ret, PROT_READ|PROT_WRITE,
62 MAP_SHARED, fd, 0);
63 if(s1->write_mem == MAP_FAILED){
64 tcc_error("/tmp not writeable");
65 return -1;
67 s1->runtime_mem = mmap (NULL, ret, PROT_READ|PROT_EXEC,
68 MAP_SHARED, fd, 0);
69 if(s1->runtime_mem == MAP_FAILED){
70 tcc_error("/tmp not executable");
71 return -1;
73 ret = tcc_relocate_ex(s1, s1->write_mem);
74 #else
75 ret = tcc_relocate_ex(s1, NULL);
76 if (-1 != ret) {
77 s1->runtime_mem = tcc_malloc(ret);
78 ret = tcc_relocate_ex(s1, s1->runtime_mem);
80 #endif
81 return ret;
84 /* launch the compiled program with the given arguments */
85 LIBTCCAPI int tcc_run(TCCState *s1, int argc, char **argv)
87 int (*prog_main)(int, char **);
88 int ret;
90 if (tcc_relocate(s1) < 0)
91 return -1;
93 prog_main = tcc_get_symbol_err(s1, "main");
95 #ifdef CONFIG_TCC_BACKTRACE
96 if (s1->do_debug) {
97 set_exception_handler();
98 rt_prog_main = prog_main;
100 #endif
102 #ifdef CONFIG_TCC_BCHECK
103 if (s1->do_bounds_check) {
104 void (*bound_init)(void);
105 void (*bound_exit)(void);
106 /* set error function */
107 rt_bound_error_msg = tcc_get_symbol_err(s1, "__bound_error_msg");
108 /* XXX: use .init section so that it also work in binary ? */
109 bound_init = tcc_get_symbol_err(s1, "__bound_init");
110 bound_exit = tcc_get_symbol_err(s1, "__bound_exit");
111 bound_init();
112 ret = (*prog_main)(argc, argv);
113 bound_exit();
114 } else
115 #endif
116 ret = (*prog_main)(argc, argv);
117 return ret;
120 /* relocate code. Return -1 on error, required size if ptr is NULL,
121 otherwise copy code into buffer passed by the caller */
122 static int tcc_relocate_ex(TCCState *s1, void *ptr)
124 Section *s;
125 unsigned long offset, length;
126 uplong mem;
127 int i;
129 if (0 == s1->runtime_added) {
130 s1->runtime_added = 1;
131 s1->nb_errors = 0;
132 #ifdef TCC_TARGET_PE
133 pe_output_file(s1, NULL);
134 #else
135 tcc_add_runtime(s1);
136 relocate_common_syms();
137 tcc_add_linker_symbols(s1);
138 build_got_entries(s1);
139 #endif
140 if (s1->nb_errors)
141 return -1;
144 offset = 0, mem = (uplong)ptr;
145 for(i = 1; i < s1->nb_sections; i++) {
146 s = s1->sections[i];
147 if (0 == (s->sh_flags & SHF_ALLOC))
148 continue;
149 length = s->data_offset;
150 s->sh_addr = mem ? (mem + offset + 15) & ~15 : 0;
151 offset = (offset + length + 15) & ~15;
153 offset += 16;
155 /* relocate symbols */
156 relocate_syms(s1, 1);
157 if (s1->nb_errors)
158 return -1;
160 #if (defined TCC_TARGET_X86_64 || defined TCC_TARGET_ARM) && !defined TCC_TARGET_PE
161 s1->runtime_plt_and_got_offset = 0;
162 s1->runtime_plt_and_got = (char *)(mem + offset);
163 /* double the size of the buffer for got and plt entries
164 XXX: calculate exact size for them? */
165 offset *= 2;
166 #endif
168 if (0 == mem)
169 return offset;
171 /* relocate each section */
172 for(i = 1; i < s1->nb_sections; i++) {
173 s = s1->sections[i];
174 if (s->reloc)
175 relocate_section(s1, s);
178 for(i = 1; i < s1->nb_sections; i++) {
179 s = s1->sections[i];
180 if (0 == (s->sh_flags & SHF_ALLOC))
181 continue;
182 length = s->data_offset;
183 // printf("%-12s %08x %04x\n", s->name, s->sh_addr, length);
184 ptr = (void*)(uplong)s->sh_addr;
185 if (NULL == s->data || s->sh_type == SHT_NOBITS)
186 memset(ptr, 0, length);
187 else
188 memcpy(ptr, s->data, length);
189 /* mark executable sections as executable in memory */
190 if (s->sh_flags & SHF_EXECINSTR)
191 set_pages_executable(ptr, length);
194 #if (defined TCC_TARGET_X86_64 || defined TCC_TARGET_ARM) && !defined TCC_TARGET_PE
195 set_pages_executable(s1->runtime_plt_and_got,
196 s1->runtime_plt_and_got_offset);
197 #endif
199 #ifdef _WIN64
200 win64_add_function_table(s1);
201 #endif
202 return 0;
205 /* ------------------------------------------------------------- */
206 /* allow to run code in memory */
208 static void set_pages_executable(void *ptr, unsigned long length)
210 #ifdef _WIN32
211 unsigned long old_protect;
212 VirtualProtect(ptr, length, PAGE_EXECUTE_READWRITE, &old_protect);
213 #else
214 unsigned long start, end;
215 start = (uplong)ptr & ~(PAGESIZE - 1);
216 end = (uplong)ptr + length;
217 end = (end + PAGESIZE - 1) & ~(PAGESIZE - 1);
218 mprotect((void *)start, end - start, PROT_READ | PROT_WRITE | PROT_EXEC);
219 #endif
222 /* ------------------------------------------------------------- */
223 #endif /* TCC_IS_NATIVE */
225 #ifdef CONFIG_TCC_BACKTRACE
227 PUB_FUNC void tcc_set_num_callers(int n)
229 rt_num_callers = n;
232 /* print the position in the source file of PC value 'pc' by reading
233 the stabs debug information */
234 static uplong rt_printline(uplong wanted_pc, const char *msg)
236 char func_name[128], last_func_name[128];
237 uplong func_addr, last_pc, pc;
238 const char *incl_files[INCLUDE_STACK_SIZE];
239 int incl_index, len, last_line_num, i;
240 const char *str, *p;
242 Stab_Sym *stab_sym = NULL, *stab_sym_end, *sym;
243 int stab_len = 0;
244 char *stab_str = NULL;
246 if (stab_section) {
247 stab_len = stab_section->data_offset;
248 stab_sym = (Stab_Sym *)stab_section->data;
249 stab_str = stabstr_section->data;
252 func_name[0] = '\0';
253 func_addr = 0;
254 incl_index = 0;
255 last_func_name[0] = '\0';
256 last_pc = (uplong)-1;
257 last_line_num = 1;
259 if (!stab_sym)
260 goto no_stabs;
262 stab_sym_end = (Stab_Sym*)((char*)stab_sym + stab_len);
263 for (sym = stab_sym + 1; sym < stab_sym_end; ++sym) {
264 switch(sym->n_type) {
265 /* function start or end */
266 case N_FUN:
267 if (sym->n_strx == 0) {
268 /* we test if between last line and end of function */
269 pc = sym->n_value + func_addr;
270 if (wanted_pc >= last_pc && wanted_pc < pc)
271 goto found;
272 func_name[0] = '\0';
273 func_addr = 0;
274 } else {
275 str = stab_str + sym->n_strx;
276 p = strchr(str, ':');
277 if (!p) {
278 pstrcpy(func_name, sizeof(func_name), str);
279 } else {
280 len = p - str;
281 if (len > sizeof(func_name) - 1)
282 len = sizeof(func_name) - 1;
283 memcpy(func_name, str, len);
284 func_name[len] = '\0';
286 func_addr = sym->n_value;
288 break;
289 /* line number info */
290 case N_SLINE:
291 pc = sym->n_value + func_addr;
292 if (wanted_pc >= last_pc && wanted_pc < pc)
293 goto found;
294 last_pc = pc;
295 last_line_num = sym->n_desc;
296 /* XXX: slow! */
297 strcpy(last_func_name, func_name);
298 break;
299 /* include files */
300 case N_BINCL:
301 str = stab_str + sym->n_strx;
302 add_incl:
303 if (incl_index < INCLUDE_STACK_SIZE) {
304 incl_files[incl_index++] = str;
306 break;
307 case N_EINCL:
308 if (incl_index > 1)
309 incl_index--;
310 break;
311 case N_SO:
312 if (sym->n_strx == 0) {
313 incl_index = 0; /* end of translation unit */
314 } else {
315 str = stab_str + sym->n_strx;
316 /* do not add path */
317 len = strlen(str);
318 if (len > 0 && str[len - 1] != '/')
319 goto add_incl;
321 break;
325 no_stabs:
326 /* second pass: we try symtab symbols (no line number info) */
327 incl_index = 0;
328 if (symtab_section)
330 ElfW(Sym) *sym, *sym_end;
331 int type;
333 sym_end = (ElfW(Sym) *)(symtab_section->data + symtab_section->data_offset);
334 for(sym = (ElfW(Sym) *)symtab_section->data + 1;
335 sym < sym_end;
336 sym++) {
337 type = ELFW(ST_TYPE)(sym->st_info);
338 if (type == STT_FUNC || type == STT_GNU_IFUNC) {
339 if (wanted_pc >= sym->st_value &&
340 wanted_pc < sym->st_value + sym->st_size) {
341 pstrcpy(last_func_name, sizeof(last_func_name),
342 strtab_section->data + sym->st_name);
343 func_addr = sym->st_value;
344 goto found;
349 /* did not find any info: */
350 fprintf(stderr, "%s %p ???\n", msg, (void*)wanted_pc);
351 fflush(stderr);
352 return 0;
353 found:
354 i = incl_index;
355 if (i > 0)
356 fprintf(stderr, "%s:%d: ", incl_files[--i], last_line_num);
357 fprintf(stderr, "%s %p", msg, (void*)wanted_pc);
358 if (last_func_name[0] != '\0')
359 fprintf(stderr, " %s()", last_func_name);
360 if (--i >= 0) {
361 fprintf(stderr, " (included from ");
362 for (;;) {
363 fprintf(stderr, "%s", incl_files[i]);
364 if (--i < 0)
365 break;
366 fprintf(stderr, ", ");
368 fprintf(stderr, ")");
370 fprintf(stderr, "\n");
371 fflush(stderr);
372 return func_addr;
375 /* emit a run time error at position 'pc' */
376 static void rt_error(ucontext_t *uc, const char *fmt, ...)
378 va_list ap;
379 uplong pc;
380 int i;
382 fprintf(stderr, "Runtime error: ");
383 va_start(ap, fmt);
384 vfprintf(stderr, fmt, ap);
385 va_end(ap);
386 fprintf(stderr, "\n");
388 for(i=0;i<rt_num_callers;i++) {
389 if (rt_get_caller_pc(&pc, uc, i) < 0)
390 break;
391 pc = rt_printline(pc, i ? "by" : "at");
392 if (pc == (uplong)rt_prog_main && pc)
393 break;
397 /* ------------------------------------------------------------- */
398 #ifndef _WIN32
400 /* signal handler for fatal errors */
401 static void sig_error(int signum, siginfo_t *siginf, void *puc)
403 ucontext_t *uc = puc;
405 switch(signum) {
406 case SIGFPE:
407 switch(siginf->si_code) {
408 case FPE_INTDIV:
409 case FPE_FLTDIV:
410 rt_error(uc, "division by zero");
411 break;
412 default:
413 rt_error(uc, "floating point exception");
414 break;
416 break;
417 case SIGBUS:
418 case SIGSEGV:
419 if (rt_bound_error_msg && *rt_bound_error_msg)
420 rt_error(uc, *rt_bound_error_msg);
421 else
422 rt_error(uc, "dereferencing invalid pointer");
423 break;
424 case SIGILL:
425 rt_error(uc, "illegal instruction");
426 break;
427 case SIGABRT:
428 rt_error(uc, "abort() called");
429 break;
430 default:
431 rt_error(uc, "caught signal %d", signum);
432 break;
434 exit(255);
437 /* Generate a stack backtrace when a CPU exception occurs. */
438 static void set_exception_handler(void)
440 struct sigaction sigact;
441 /* install TCC signal handlers to print debug info on fatal
442 runtime errors */
443 sigact.sa_flags = SA_SIGINFO | SA_RESETHAND;
444 sigact.sa_sigaction = sig_error;
445 sigemptyset(&sigact.sa_mask);
446 sigaction(SIGFPE, &sigact, NULL);
447 sigaction(SIGILL, &sigact, NULL);
448 sigaction(SIGSEGV, &sigact, NULL);
449 sigaction(SIGBUS, &sigact, NULL);
450 sigaction(SIGABRT, &sigact, NULL);
453 /* ------------------------------------------------------------- */
454 #ifdef __i386__
456 /* fix for glibc 2.1 */
457 #ifndef REG_EIP
458 #define REG_EIP EIP
459 #define REG_EBP EBP
460 #endif
462 /* return the PC at frame level 'level'. Return non zero if not found */
463 static int rt_get_caller_pc(unsigned long *paddr, ucontext_t *uc, int level)
465 unsigned long fp;
466 int i;
468 if (level == 0) {
469 #if defined(__APPLE__)
470 *paddr = uc->uc_mcontext->__ss.__eip;
471 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
472 *paddr = uc->uc_mcontext.mc_eip;
473 #elif defined(__dietlibc__)
474 *paddr = uc->uc_mcontext.eip;
475 #else
476 *paddr = uc->uc_mcontext.gregs[REG_EIP];
477 #endif
478 return 0;
479 } else {
480 #if defined(__APPLE__)
481 fp = uc->uc_mcontext->__ss.__ebp;
482 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
483 fp = uc->uc_mcontext.mc_ebp;
484 #elif defined(__dietlibc__)
485 fp = uc->uc_mcontext.ebp;
486 #else
487 fp = uc->uc_mcontext.gregs[REG_EBP];
488 #endif
489 for(i=1;i<level;i++) {
490 /* XXX: check address validity with program info */
491 if (fp <= 0x1000 || fp >= 0xc0000000)
492 return -1;
493 fp = ((unsigned long *)fp)[0];
495 *paddr = ((unsigned long *)fp)[1];
496 return 0;
500 /* ------------------------------------------------------------- */
501 #elif defined(__x86_64__)
503 /* return the PC at frame level 'level'. Return non zero if not found */
504 static int rt_get_caller_pc(unsigned long *paddr,
505 ucontext_t *uc, int level)
507 unsigned long fp;
508 int i;
510 if (level == 0) {
511 /* XXX: only support linux */
512 #if defined(__APPLE__)
513 *paddr = uc->uc_mcontext->__ss.__rip;
514 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
515 *paddr = uc->uc_mcontext.mc_rip;
516 #else
517 *paddr = uc->uc_mcontext.gregs[REG_RIP];
518 #endif
519 return 0;
520 } else {
521 #if defined(__APPLE__)
522 fp = uc->uc_mcontext->__ss.__rbp;
523 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
524 fp = uc->uc_mcontext.mc_rbp;
525 #else
526 fp = uc->uc_mcontext.gregs[REG_RBP];
527 #endif
528 for(i=1;i<level;i++) {
529 /* XXX: check address validity with program info */
530 if (fp <= 0x1000)
531 return -1;
532 fp = ((unsigned long *)fp)[0];
534 *paddr = ((unsigned long *)fp)[1];
535 return 0;
539 /* ------------------------------------------------------------- */
540 #elif defined(__arm__)
542 /* return the PC at frame level 'level'. Return negative if not found */
543 static int rt_get_caller_pc(unsigned long *paddr,
544 ucontext_t *uc, int level)
546 uint32_t fp, sp;
547 int i;
549 if (level == 0) {
550 /* XXX: only supports linux */
551 #if defined(__linux__)
552 *paddr = uc->uc_mcontext.arm_pc;
553 #else
554 return -1;
555 #endif
556 return 0;
557 } else {
558 #if defined(__linux__)
559 fp = uc->uc_mcontext.arm_fp;
560 sp = uc->uc_mcontext.arm_sp;
561 if (sp < 0x1000)
562 sp = 0x1000;
563 #else
564 return -1;
565 #endif
566 /* XXX: specific to tinycc stack frames */
567 if (fp < sp + 12 || fp & 3)
568 return -1;
569 for(i = 1; i < level; i++) {
570 sp = ((uint32_t *)fp)[-2];
571 if (sp < fp || sp - fp > 16 || sp & 3)
572 return -1;
573 fp = ((uint32_t *)fp)[-3];
574 if (fp <= sp || fp - sp < 12 || fp & 3)
575 return -1;
577 /* XXX: check address validity with program info */
578 *paddr = ((uint32_t *)fp)[-1];
579 return 0;
583 /* ------------------------------------------------------------- */
584 #else
586 #warning add arch specific rt_get_caller_pc()
587 static int rt_get_caller_pc(unsigned long *paddr,
588 ucontext_t *uc, int level)
590 return -1;
593 #endif /* !__i386__ */
595 /* ------------------------------------------------------------- */
596 #else /* WIN32 */
598 static long __stdcall cpu_exception_handler(EXCEPTION_POINTERS *ex_info)
600 EXCEPTION_RECORD *er = ex_info->ExceptionRecord;
601 CONTEXT *uc = ex_info->ContextRecord;
602 switch (er->ExceptionCode) {
603 case EXCEPTION_ACCESS_VIOLATION:
604 if (rt_bound_error_msg && *rt_bound_error_msg)
605 rt_error(uc, *rt_bound_error_msg);
606 else
607 rt_error(uc, "access violation");
608 break;
609 case EXCEPTION_STACK_OVERFLOW:
610 rt_error(uc, "stack overflow");
611 break;
612 case EXCEPTION_INT_DIVIDE_BY_ZERO:
613 rt_error(uc, "division by zero");
614 break;
615 default:
616 rt_error(uc, "exception caught");
617 break;
619 exit(-1);
620 return EXCEPTION_CONTINUE_SEARCH;
623 /* Generate a stack backtrace when a CPU exception occurs. */
624 static void set_exception_handler(void)
626 SetUnhandledExceptionFilter(cpu_exception_handler);
629 #ifdef _WIN64
630 static void win64_add_function_table(TCCState *s1)
632 RtlAddFunctionTable(
633 (RUNTIME_FUNCTION*)(uplong)s1->uw_pdata->sh_addr,
634 s1->uw_pdata->data_offset / sizeof (RUNTIME_FUNCTION),
635 (uplong)text_section->sh_addr
638 #endif
640 /* return the PC at frame level 'level'. Return non zero if not found */
641 static int rt_get_caller_pc(uplong *paddr, CONTEXT *uc, int level)
643 uplong fp, pc;
644 int i;
645 #ifdef _WIN64
646 pc = uc->Rip;
647 fp = uc->Rbp;
648 #else
649 pc = uc->Eip;
650 fp = uc->Ebp;
651 #endif
652 if (level > 0) {
653 for(i=1;i<level;i++) {
654 /* XXX: check address validity with program info */
655 if (fp <= 0x1000 || fp >= 0xc0000000)
656 return -1;
657 fp = ((uplong*)fp)[0];
659 pc = ((uplong*)fp)[1];
661 *paddr = pc;
662 return 0;
665 #endif /* _WIN32 */
666 #endif /* CONFIG_TCC_BACKTRACE */
667 /* ------------------------------------------------------------- */
669 #ifdef CONFIG_TCC_STATIC
671 #define RTLD_LAZY 0x001
672 #define RTLD_NOW 0x002
673 #define RTLD_GLOBAL 0x100
674 #define RTLD_DEFAULT NULL
676 /* dummy function for profiling */
677 ST_FUNC void *dlopen(const char *filename, int flag)
679 return NULL;
682 ST_FUNC void dlclose(void *p)
686 const char *dlerror(void)
688 return "error";
691 typedef struct TCCSyms {
692 char *str;
693 void *ptr;
694 } TCCSyms;
696 #define TCCSYM(a) { #a, &a, },
698 /* add the symbol you want here if no dynamic linking is done */
699 static TCCSyms tcc_syms[] = {
700 #if !defined(CONFIG_TCCBOOT)
701 TCCSYM(printf)
702 TCCSYM(fprintf)
703 TCCSYM(fopen)
704 TCCSYM(fclose)
705 #endif
706 { NULL, NULL },
709 ST_FUNC void *resolve_sym(TCCState *s1, const char *symbol)
711 TCCSyms *p;
712 p = tcc_syms;
713 while (p->str != NULL) {
714 if (!strcmp(p->str, symbol))
715 return p->ptr;
716 p++;
718 return NULL;
721 #elif !defined(_WIN32)
723 ST_FUNC void *resolve_sym(TCCState *s1, const char *sym)
725 return dlsym(RTLD_DEFAULT, sym);
728 #endif /* CONFIG_TCC_STATIC */
730 /* ------------------------------------------------------------- */