Makefile: fix "allow CONFIG_LDDIR=lib64 configuration"
[tinycc.git] / tccrun.c
bloba2cc82f37aeaede2fbf19b7a7c98deef34adeffe
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(addr_t *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, void *ptr)
52 int ret;
54 if (TCC_RELOCATE_AUTO != ptr)
55 return tcc_relocate_ex(s1, ptr);
57 #ifdef HAVE_SELINUX
58 /* Use mmap instead of malloc for Selinux
59 Ref http://www.gnu.org/s/libc/manual/html_node/File-Size.html */
60 char tmpfname[] = "/tmp/.tccrunXXXXXX";
61 int fd = mkstemp (tmpfname);
62 if ((ret= tcc_relocate_ex(s1,NULL)) < 0)return -1;
63 s1->mem_size=ret;
64 unlink (tmpfname); ftruncate (fd, s1->mem_size);
65 s1->write_mem = mmap (NULL, ret, PROT_READ|PROT_WRITE,
66 MAP_SHARED, fd, 0);
67 if(s1->write_mem == MAP_FAILED){
68 tcc_error("/tmp not writeable");
69 return -1;
71 s1->runtime_mem = mmap (NULL, ret, PROT_READ|PROT_EXEC,
72 MAP_SHARED, fd, 0);
73 if(s1->runtime_mem == MAP_FAILED){
74 tcc_error("/tmp not executable");
75 return -1;
77 ret = tcc_relocate_ex(s1, s1->write_mem);
78 #else
79 ret = tcc_relocate_ex(s1, NULL);
80 if (-1 != ret) {
81 s1->runtime_mem = tcc_malloc(ret);
82 ret = tcc_relocate_ex(s1, s1->runtime_mem);
84 #endif
85 return ret;
88 /* launch the compiled program with the given arguments */
89 LIBTCCAPI int tcc_run(TCCState *s1, int argc, char **argv)
91 int (*prog_main)(int, char **);
92 int ret;
94 if (tcc_relocate(s1, TCC_RELOCATE_AUTO) < 0)
95 return -1;
97 prog_main = tcc_get_symbol_err(s1, "main");
99 #ifdef CONFIG_TCC_BACKTRACE
100 if (s1->do_debug) {
101 set_exception_handler();
102 rt_prog_main = prog_main;
104 #endif
106 #ifdef CONFIG_TCC_BCHECK
107 if (s1->do_bounds_check) {
108 void (*bound_init)(void);
109 void (*bound_exit)(void);
110 /* set error function */
111 rt_bound_error_msg = tcc_get_symbol_err(s1, "__bound_error_msg");
112 /* XXX: use .init section so that it also work in binary ? */
113 bound_init = tcc_get_symbol_err(s1, "__bound_init");
114 bound_exit = tcc_get_symbol_err(s1, "__bound_exit");
115 bound_init();
116 ret = (*prog_main)(argc, argv);
117 bound_exit();
118 } else
119 #endif
120 ret = (*prog_main)(argc, argv);
121 return ret;
124 /* relocate code. Return -1 on error, required size if ptr is NULL,
125 otherwise copy code into buffer passed by the caller */
126 static int tcc_relocate_ex(TCCState *s1, void *ptr)
128 Section *s;
129 unsigned long offset, length;
130 addr_t mem;
131 int i;
133 if (0 == s1->runtime_added) {
134 s1->runtime_added = 1;
135 s1->nb_errors = 0;
136 #ifdef TCC_TARGET_PE
137 pe_output_file(s1, NULL);
138 #else
139 tcc_add_runtime(s1);
140 relocate_common_syms();
141 tcc_add_linker_symbols(s1);
142 build_got_entries(s1);
143 #endif
144 if (s1->nb_errors)
145 return -1;
148 offset = 0, mem = (addr_t)ptr;
149 for(i = 1; i < s1->nb_sections; i++) {
150 s = s1->sections[i];
151 if (0 == (s->sh_flags & SHF_ALLOC))
152 continue;
153 length = s->data_offset;
154 s->sh_addr = mem ? (mem + offset + 15) & ~15 : 0;
155 offset = (offset + length + 15) & ~15;
157 offset += 16;
159 /* relocate symbols */
160 relocate_syms(s1, 1);
161 if (s1->nb_errors)
162 return -1;
164 #ifdef TCC_HAS_RUNTIME_PLTGOT
165 s1->runtime_plt_and_got_offset = 0;
166 s1->runtime_plt_and_got = (char *)(mem + offset);
167 /* double the size of the buffer for got and plt entries
168 XXX: calculate exact size for them? */
169 offset *= 2;
170 #endif
172 if (0 == mem)
173 return offset;
175 /* relocate each section */
176 for(i = 1; i < s1->nb_sections; i++) {
177 s = s1->sections[i];
178 if (s->reloc)
179 relocate_section(s1, s);
182 for(i = 1; i < s1->nb_sections; i++) {
183 s = s1->sections[i];
184 if (0 == (s->sh_flags & SHF_ALLOC))
185 continue;
186 length = s->data_offset;
187 // printf("%-12s %08x %04x\n", s->name, s->sh_addr, length);
188 ptr = (void*)s->sh_addr;
189 if (NULL == s->data || s->sh_type == SHT_NOBITS)
190 memset(ptr, 0, length);
191 else
192 memcpy(ptr, s->data, length);
193 /* mark executable sections as executable in memory */
194 if (s->sh_flags & SHF_EXECINSTR)
195 set_pages_executable(ptr, length);
198 #ifdef TCC_HAS_RUNTIME_PLTGOT
199 set_pages_executable(s1->runtime_plt_and_got,
200 s1->runtime_plt_and_got_offset);
201 #endif
203 #ifdef _WIN64
204 win64_add_function_table(s1);
205 #endif
206 return 0;
209 /* ------------------------------------------------------------- */
210 /* allow to run code in memory */
212 static void set_pages_executable(void *ptr, unsigned long length)
214 #ifdef _WIN32
215 unsigned long old_protect;
216 VirtualProtect(ptr, length, PAGE_EXECUTE_READWRITE, &old_protect);
217 #else
218 addr_t start, end;
219 start = (addr_t)ptr & ~(PAGESIZE - 1);
220 end = (addr_t)ptr + length;
221 end = (end + PAGESIZE - 1) & ~(PAGESIZE - 1);
222 mprotect((void *)start, end - start, PROT_READ | PROT_WRITE | PROT_EXEC);
223 #endif
226 /* ------------------------------------------------------------- */
227 #ifdef CONFIG_TCC_BACKTRACE
229 PUB_FUNC void tcc_set_num_callers(int n)
231 rt_num_callers = n;
234 /* print the position in the source file of PC value 'pc' by reading
235 the stabs debug information */
236 static addr_t rt_printline(addr_t wanted_pc, const char *msg)
238 char func_name[128], last_func_name[128];
239 addr_t func_addr, last_pc, pc;
240 const char *incl_files[INCLUDE_STACK_SIZE];
241 int incl_index, len, last_line_num, i;
242 const char *str, *p;
244 Stab_Sym *stab_sym = NULL, *stab_sym_end, *sym;
245 int stab_len = 0;
246 char *stab_str = NULL;
248 if (stab_section) {
249 stab_len = stab_section->data_offset;
250 stab_sym = (Stab_Sym *)stab_section->data;
251 stab_str = stabstr_section->data;
254 func_name[0] = '\0';
255 func_addr = 0;
256 incl_index = 0;
257 last_func_name[0] = '\0';
258 last_pc = (addr_t)-1;
259 last_line_num = 1;
261 if (!stab_sym)
262 goto no_stabs;
264 stab_sym_end = (Stab_Sym*)((char*)stab_sym + stab_len);
265 for (sym = stab_sym + 1; sym < stab_sym_end; ++sym) {
266 switch(sym->n_type) {
267 /* function start or end */
268 case N_FUN:
269 if (sym->n_strx == 0) {
270 /* we test if between last line and end of function */
271 pc = sym->n_value + func_addr;
272 if (wanted_pc >= last_pc && wanted_pc < pc)
273 goto found;
274 func_name[0] = '\0';
275 func_addr = 0;
276 } else {
277 str = stab_str + sym->n_strx;
278 p = strchr(str, ':');
279 if (!p) {
280 pstrcpy(func_name, sizeof(func_name), str);
281 } else {
282 len = p - str;
283 if (len > sizeof(func_name) - 1)
284 len = sizeof(func_name) - 1;
285 memcpy(func_name, str, len);
286 func_name[len] = '\0';
288 func_addr = sym->n_value;
290 break;
291 /* line number info */
292 case N_SLINE:
293 pc = sym->n_value + func_addr;
294 if (wanted_pc >= last_pc && wanted_pc < pc)
295 goto found;
296 last_pc = pc;
297 last_line_num = sym->n_desc;
298 /* XXX: slow! */
299 strcpy(last_func_name, func_name);
300 break;
301 /* include files */
302 case N_BINCL:
303 str = stab_str + sym->n_strx;
304 add_incl:
305 if (incl_index < INCLUDE_STACK_SIZE) {
306 incl_files[incl_index++] = str;
308 break;
309 case N_EINCL:
310 if (incl_index > 1)
311 incl_index--;
312 break;
313 case N_SO:
314 if (sym->n_strx == 0) {
315 incl_index = 0; /* end of translation unit */
316 } else {
317 str = stab_str + sym->n_strx;
318 /* do not add path */
319 len = strlen(str);
320 if (len > 0 && str[len - 1] != '/')
321 goto add_incl;
323 break;
327 no_stabs:
328 /* second pass: we try symtab symbols (no line number info) */
329 incl_index = 0;
330 if (symtab_section)
332 ElfW(Sym) *sym, *sym_end;
333 int type;
335 sym_end = (ElfW(Sym) *)(symtab_section->data + symtab_section->data_offset);
336 for(sym = (ElfW(Sym) *)symtab_section->data + 1;
337 sym < sym_end;
338 sym++) {
339 type = ELFW(ST_TYPE)(sym->st_info);
340 if (type == STT_FUNC || type == STT_GNU_IFUNC) {
341 if (wanted_pc >= sym->st_value &&
342 wanted_pc < sym->st_value + sym->st_size) {
343 pstrcpy(last_func_name, sizeof(last_func_name),
344 strtab_section->data + sym->st_name);
345 func_addr = sym->st_value;
346 goto found;
351 /* did not find any info: */
352 fprintf(stderr, "%s %p ???\n", msg, (void*)wanted_pc);
353 fflush(stderr);
354 return 0;
355 found:
356 i = incl_index;
357 if (i > 0)
358 fprintf(stderr, "%s:%d: ", incl_files[--i], last_line_num);
359 fprintf(stderr, "%s %p", msg, (void*)wanted_pc);
360 if (last_func_name[0] != '\0')
361 fprintf(stderr, " %s()", last_func_name);
362 if (--i >= 0) {
363 fprintf(stderr, " (included from ");
364 for (;;) {
365 fprintf(stderr, "%s", incl_files[i]);
366 if (--i < 0)
367 break;
368 fprintf(stderr, ", ");
370 fprintf(stderr, ")");
372 fprintf(stderr, "\n");
373 fflush(stderr);
374 return func_addr;
377 /* emit a run time error at position 'pc' */
378 static void rt_error(ucontext_t *uc, const char *fmt, ...)
380 va_list ap;
381 addr_t pc;
382 int i;
384 fprintf(stderr, "Runtime error: ");
385 va_start(ap, fmt);
386 vfprintf(stderr, fmt, ap);
387 va_end(ap);
388 fprintf(stderr, "\n");
390 for(i=0;i<rt_num_callers;i++) {
391 if (rt_get_caller_pc(&pc, uc, i) < 0)
392 break;
393 pc = rt_printline(pc, i ? "by" : "at");
394 if (pc == (addr_t)rt_prog_main && pc)
395 break;
399 /* ------------------------------------------------------------- */
400 #ifndef _WIN32
402 /* signal handler for fatal errors */
403 static void sig_error(int signum, siginfo_t *siginf, void *puc)
405 ucontext_t *uc = puc;
407 switch(signum) {
408 case SIGFPE:
409 switch(siginf->si_code) {
410 case FPE_INTDIV:
411 case FPE_FLTDIV:
412 rt_error(uc, "division by zero");
413 break;
414 default:
415 rt_error(uc, "floating point exception");
416 break;
418 break;
419 case SIGBUS:
420 case SIGSEGV:
421 if (rt_bound_error_msg && *rt_bound_error_msg)
422 rt_error(uc, *rt_bound_error_msg);
423 else
424 rt_error(uc, "dereferencing invalid pointer");
425 break;
426 case SIGILL:
427 rt_error(uc, "illegal instruction");
428 break;
429 case SIGABRT:
430 rt_error(uc, "abort() called");
431 break;
432 default:
433 rt_error(uc, "caught signal %d", signum);
434 break;
436 exit(255);
439 /* Generate a stack backtrace when a CPU exception occurs. */
440 static void set_exception_handler(void)
442 struct sigaction sigact;
443 /* install TCC signal handlers to print debug info on fatal
444 runtime errors */
445 sigact.sa_flags = SA_SIGINFO | SA_RESETHAND;
446 sigact.sa_sigaction = sig_error;
447 sigemptyset(&sigact.sa_mask);
448 sigaction(SIGFPE, &sigact, NULL);
449 sigaction(SIGILL, &sigact, NULL);
450 sigaction(SIGSEGV, &sigact, NULL);
451 sigaction(SIGBUS, &sigact, NULL);
452 sigaction(SIGABRT, &sigact, NULL);
455 /* ------------------------------------------------------------- */
456 #ifdef __i386__
458 /* fix for glibc 2.1 */
459 #ifndef REG_EIP
460 #define REG_EIP EIP
461 #define REG_EBP EBP
462 #endif
464 /* return the PC at frame level 'level'. Return non zero if not found */
465 static int rt_get_caller_pc(addr_t *paddr, ucontext_t *uc, int level)
467 unsigned long fp;
468 int i;
470 if (level == 0) {
471 #if defined(__APPLE__)
472 *paddr = uc->uc_mcontext->__ss.__eip;
473 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
474 *paddr = uc->uc_mcontext.mc_eip;
475 #elif defined(__dietlibc__)
476 *paddr = uc->uc_mcontext.eip;
477 #else
478 *paddr = uc->uc_mcontext.gregs[REG_EIP];
479 #endif
480 return 0;
481 } else {
482 #if defined(__APPLE__)
483 fp = uc->uc_mcontext->__ss.__ebp;
484 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
485 fp = uc->uc_mcontext.mc_ebp;
486 #elif defined(__dietlibc__)
487 fp = uc->uc_mcontext.ebp;
488 #else
489 fp = uc->uc_mcontext.gregs[REG_EBP];
490 #endif
491 for(i=1;i<level;i++) {
492 /* XXX: check address validity with program info */
493 if (fp <= 0x1000 || fp >= 0xc0000000)
494 return -1;
495 fp = ((unsigned long *)fp)[0];
497 *paddr = ((unsigned long *)fp)[1];
498 return 0;
502 /* ------------------------------------------------------------- */
503 #elif defined(__x86_64__)
505 /* return the PC at frame level 'level'. Return non zero if not found */
506 static int rt_get_caller_pc(unsigned long *paddr,
507 ucontext_t *uc, int level)
509 unsigned long fp;
510 int i;
512 if (level == 0) {
513 /* XXX: only support linux */
514 #if defined(__APPLE__)
515 *paddr = uc->uc_mcontext->__ss.__rip;
516 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
517 *paddr = uc->uc_mcontext.mc_rip;
518 #else
519 *paddr = uc->uc_mcontext.gregs[REG_RIP];
520 #endif
521 return 0;
522 } else {
523 #if defined(__APPLE__)
524 fp = uc->uc_mcontext->__ss.__rbp;
525 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
526 fp = uc->uc_mcontext.mc_rbp;
527 #else
528 fp = uc->uc_mcontext.gregs[REG_RBP];
529 #endif
530 for(i=1;i<level;i++) {
531 /* XXX: check address validity with program info */
532 if (fp <= 0x1000)
533 return -1;
534 fp = ((unsigned long *)fp)[0];
536 *paddr = ((unsigned long *)fp)[1];
537 return 0;
541 /* ------------------------------------------------------------- */
542 #elif defined(__arm__)
544 /* return the PC at frame level 'level'. Return negative if not found */
545 static int rt_get_caller_pc(unsigned long *paddr,
546 ucontext_t *uc, int level)
548 uint32_t fp, sp;
549 int i;
551 if (level == 0) {
552 /* XXX: only supports linux */
553 #if defined(__linux__)
554 *paddr = uc->uc_mcontext.arm_pc;
555 #else
556 return -1;
557 #endif
558 return 0;
559 } else {
560 #if defined(__linux__)
561 fp = uc->uc_mcontext.arm_fp;
562 sp = uc->uc_mcontext.arm_sp;
563 if (sp < 0x1000)
564 sp = 0x1000;
565 #else
566 return -1;
567 #endif
568 /* XXX: specific to tinycc stack frames */
569 if (fp < sp + 12 || fp & 3)
570 return -1;
571 for(i = 1; i < level; i++) {
572 sp = ((uint32_t *)fp)[-2];
573 if (sp < fp || sp - fp > 16 || sp & 3)
574 return -1;
575 fp = ((uint32_t *)fp)[-3];
576 if (fp <= sp || fp - sp < 12 || fp & 3)
577 return -1;
579 /* XXX: check address validity with program info */
580 *paddr = ((uint32_t *)fp)[-1];
581 return 0;
585 /* ------------------------------------------------------------- */
586 #else
588 #warning add arch specific rt_get_caller_pc()
589 static int rt_get_caller_pc(unsigned long *paddr,
590 ucontext_t *uc, int level)
592 return -1;
595 #endif /* !__i386__ */
597 /* ------------------------------------------------------------- */
598 #else /* WIN32 */
600 static long __stdcall cpu_exception_handler(EXCEPTION_POINTERS *ex_info)
602 EXCEPTION_RECORD *er = ex_info->ExceptionRecord;
603 CONTEXT *uc = ex_info->ContextRecord;
604 switch (er->ExceptionCode) {
605 case EXCEPTION_ACCESS_VIOLATION:
606 if (rt_bound_error_msg && *rt_bound_error_msg)
607 rt_error(uc, *rt_bound_error_msg);
608 else
609 rt_error(uc, "access violation");
610 break;
611 case EXCEPTION_STACK_OVERFLOW:
612 rt_error(uc, "stack overflow");
613 break;
614 case EXCEPTION_INT_DIVIDE_BY_ZERO:
615 rt_error(uc, "division by zero");
616 break;
617 default:
618 rt_error(uc, "exception caught");
619 break;
621 exit(-1);
622 return EXCEPTION_CONTINUE_SEARCH;
625 /* Generate a stack backtrace when a CPU exception occurs. */
626 static void set_exception_handler(void)
628 SetUnhandledExceptionFilter(cpu_exception_handler);
631 #ifdef _WIN64
632 static void win64_add_function_table(TCCState *s1)
634 RtlAddFunctionTable(
635 (RUNTIME_FUNCTION*)s1->uw_pdata->sh_addr,
636 s1->uw_pdata->data_offset / sizeof (RUNTIME_FUNCTION),
637 text_section->sh_addr
640 #endif
642 /* return the PC at frame level 'level'. Return non zero if not found */
643 static int rt_get_caller_pc(addr_t *paddr, CONTEXT *uc, int level)
645 addr_t fp, pc;
646 int i;
647 #ifdef _WIN64
648 pc = uc->Rip;
649 fp = uc->Rbp;
650 #else
651 pc = uc->Eip;
652 fp = uc->Ebp;
653 #endif
654 if (level > 0) {
655 for(i=1;i<level;i++) {
656 /* XXX: check address validity with program info */
657 if (fp <= 0x1000 || fp >= 0xc0000000)
658 return -1;
659 fp = ((addr_t*)fp)[0];
661 pc = ((addr_t*)fp)[1];
663 *paddr = pc;
664 return 0;
667 #endif /* _WIN32 */
668 #endif /* CONFIG_TCC_BACKTRACE */
669 /* ------------------------------------------------------------- */
671 #ifdef CONFIG_TCC_STATIC
673 #define RTLD_LAZY 0x001
674 #define RTLD_NOW 0x002
675 #define RTLD_GLOBAL 0x100
676 #define RTLD_DEFAULT NULL
678 /* dummy function for profiling */
679 ST_FUNC void *dlopen(const char *filename, int flag)
681 return NULL;
684 ST_FUNC void dlclose(void *p)
688 const char *dlerror(void)
690 return "error";
693 typedef struct TCCSyms {
694 char *str;
695 void *ptr;
696 } TCCSyms;
698 #define TCCSYM(a) { #a, &a, },
700 /* add the symbol you want here if no dynamic linking is done */
701 static TCCSyms tcc_syms[] = {
702 #if !defined(CONFIG_TCCBOOT)
703 TCCSYM(printf)
704 TCCSYM(fprintf)
705 TCCSYM(fopen)
706 TCCSYM(fclose)
707 #endif
708 { NULL, NULL },
711 ST_FUNC void *resolve_sym(TCCState *s1, const char *symbol)
713 TCCSyms *p;
714 p = tcc_syms;
715 while (p->str != NULL) {
716 if (!strcmp(p->str, symbol))
717 return p->ptr;
718 p++;
720 return NULL;
723 #elif !defined(_WIN32)
725 ST_FUNC void *resolve_sym(TCCState *s1, const char *sym)
727 return dlsym(RTLD_DEFAULT, sym);
730 #endif /* CONFIG_TCC_STATIC */
731 #endif /* TCC_IS_NATIVE */
732 /* ------------------------------------------------------------- */