libtcc: minor adjustments
[tinycc.git] / tccrun.c
blob80d18349c6a45c3221034da6cc9a77c36329891f
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 #ifdef _WIN64
40 static void win64_add_function_table(TCCState *s1);
41 #endif
43 /* ------------------------------------------------------------- */
44 /* Do all relocations (needed before using tcc_get_symbol())
45 Returns -1 on error. */
47 LIBTCCAPI int tcc_relocate(TCCState *s1)
49 int ret;
50 #ifdef HAVE_SELINUX
51 /* Use mmap instead of malloc for Selinux
52 Ref http://www.gnu.org/s/libc/manual/html_node/File-Size.html */
53 char tmpfname[] = "/tmp/.tccrunXXXXXX";
54 int fd = mkstemp (tmpfname);
55 if ((ret= tcc_relocate_ex(s1,NULL)) < 0)return -1;
56 s1->mem_size=ret;
57 unlink (tmpfname); ftruncate (fd, s1->mem_size);
58 s1->write_mem = mmap (NULL, ret, PROT_READ|PROT_WRITE,
59 MAP_SHARED, fd, 0);
60 if(s1->write_mem == MAP_FAILED){
61 error("/tmp not writeable");
62 return -1;
64 s1->runtime_mem = mmap (NULL, ret, PROT_READ|PROT_EXEC,
65 MAP_SHARED, fd, 0);
66 if(s1->runtime_mem == MAP_FAILED){
67 error("/tmp not executable");
68 return -1;
70 ret = tcc_relocate_ex(s1, s1->write_mem);
71 #else
72 ret = tcc_relocate_ex(s1, NULL);
73 if (-1 != ret) {
74 s1->runtime_mem = tcc_malloc(ret);
75 ret = tcc_relocate_ex(s1, s1->runtime_mem);
77 #endif
78 return ret;
81 /* launch the compiled program with the given arguments */
82 LIBTCCAPI int tcc_run(TCCState *s1, int argc, char **argv)
84 int (*prog_main)(int, char **);
85 int ret;
87 if (tcc_relocate(s1) < 0)
88 return -1;
90 prog_main = tcc_get_symbol_err(s1, "main");
92 #ifdef CONFIG_TCC_BACKTRACE
93 if (s1->do_debug) {
94 set_exception_handler();
95 rt_prog_main = prog_main;
97 #endif
99 #ifdef CONFIG_TCC_BCHECK
100 if (s1->do_bounds_check) {
101 void (*bound_init)(void);
102 void (*bound_exit)(void);
103 /* set error function */
104 rt_bound_error_msg = tcc_get_symbol_err(s1, "__bound_error_msg");
105 /* XXX: use .init section so that it also work in binary ? */
106 bound_init = tcc_get_symbol_err(s1, "__bound_init");
107 bound_exit = tcc_get_symbol_err(s1, "__bound_exit");
108 bound_init();
109 ret = (*prog_main)(argc, argv);
110 bound_exit();
111 } else
112 #endif
113 ret = (*prog_main)(argc, argv);
114 return ret;
117 /* relocate code. Return -1 on error, required size if ptr is NULL,
118 otherwise copy code into buffer passed by the caller */
119 static int tcc_relocate_ex(TCCState *s1, void *ptr)
121 Section *s;
122 unsigned long offset, length;
123 uplong mem;
124 int i;
126 if (0 == s1->runtime_added) {
127 s1->runtime_added = 1;
128 s1->nb_errors = 0;
129 #ifdef TCC_TARGET_PE
130 pe_output_file(s1, NULL);
131 #else
132 tcc_add_runtime(s1);
133 relocate_common_syms();
134 tcc_add_linker_symbols(s1);
135 build_got_entries(s1);
136 #endif
137 if (s1->nb_errors)
138 return -1;
141 offset = 0, mem = (uplong)ptr;
142 for(i = 1; i < s1->nb_sections; i++) {
143 s = s1->sections[i];
144 if (0 == (s->sh_flags & SHF_ALLOC))
145 continue;
146 length = s->data_offset;
147 s->sh_addr = mem ? (mem + offset + 15) & ~15 : 0;
148 offset = (offset + length + 15) & ~15;
150 offset += 16;
152 /* relocate symbols */
153 relocate_syms(s1, 1);
154 if (s1->nb_errors)
155 return -1;
157 #if (defined TCC_TARGET_X86_64 || defined TCC_TARGET_ARM) && !defined TCC_TARGET_PE
158 s1->runtime_plt_and_got_offset = 0;
159 s1->runtime_plt_and_got = (char *)(mem + offset);
160 /* double the size of the buffer for got and plt entries
161 XXX: calculate exact size for them? */
162 offset *= 2;
163 #endif
165 if (0 == mem)
166 return offset;
168 /* relocate each section */
169 for(i = 1; i < s1->nb_sections; i++) {
170 s = s1->sections[i];
171 if (s->reloc)
172 relocate_section(s1, s);
175 for(i = 1; i < s1->nb_sections; i++) {
176 s = s1->sections[i];
177 if (0 == (s->sh_flags & SHF_ALLOC))
178 continue;
179 length = s->data_offset;
180 // printf("%-12s %08x %04x\n", s->name, s->sh_addr, length);
181 ptr = (void*)(uplong)s->sh_addr;
182 if (NULL == s->data || s->sh_type == SHT_NOBITS)
183 memset(ptr, 0, length);
184 else
185 memcpy(ptr, s->data, length);
186 /* mark executable sections as executable in memory */
187 if (s->sh_flags & SHF_EXECINSTR)
188 set_pages_executable(ptr, length);
191 #if (defined TCC_TARGET_X86_64 || defined TCC_TARGET_ARM) && !defined TCC_TARGET_PE
192 set_pages_executable(s1->runtime_plt_and_got,
193 s1->runtime_plt_and_got_offset);
194 #endif
196 #ifdef _WIN64
197 win64_add_function_table(s1);
198 #endif
199 return 0;
202 /* ------------------------------------------------------------- */
203 /* allow to run code in memory */
205 static void set_pages_executable(void *ptr, unsigned long length)
207 #ifdef _WIN32
208 unsigned long old_protect;
209 VirtualProtect(ptr, length, PAGE_EXECUTE_READWRITE, &old_protect);
210 #else
211 unsigned long start, end;
212 start = (uplong)ptr & ~(PAGESIZE - 1);
213 end = (uplong)ptr + length;
214 end = (end + PAGESIZE - 1) & ~(PAGESIZE - 1);
215 mprotect((void *)start, end - start, PROT_READ | PROT_WRITE | PROT_EXEC);
216 #endif
219 /* ------------------------------------------------------------- */
220 #ifdef CONFIG_TCC_BACKTRACE
222 PUB_FUNC void tcc_set_num_callers(int n)
224 rt_num_callers = n;
227 /* print the position in the source file of PC value 'pc' by reading
228 the stabs debug information */
229 static uplong rt_printline(uplong wanted_pc, const char *msg)
231 char func_name[128], last_func_name[128];
232 uplong func_addr, last_pc, pc;
233 const char *incl_files[INCLUDE_STACK_SIZE];
234 int incl_index, len, last_line_num, i;
235 const char *str, *p;
237 Stab_Sym *stab_sym = NULL, *stab_sym_end, *sym;
238 int stab_len = 0;
239 char *stab_str = NULL;
241 if (stab_section) {
242 stab_len = stab_section->data_offset;
243 stab_sym = (Stab_Sym *)stab_section->data;
244 stab_str = stabstr_section->data;
247 func_name[0] = '\0';
248 func_addr = 0;
249 incl_index = 0;
250 last_func_name[0] = '\0';
251 last_pc = (uplong)-1;
252 last_line_num = 1;
254 if (!stab_sym)
255 goto no_stabs;
257 stab_sym_end = (Stab_Sym*)((char*)stab_sym + stab_len);
258 for (sym = stab_sym + 1; sym < stab_sym_end; ++sym) {
259 switch(sym->n_type) {
260 /* function start or end */
261 case N_FUN:
262 if (sym->n_strx == 0) {
263 /* we test if between last line and end of function */
264 pc = sym->n_value + func_addr;
265 if (wanted_pc >= last_pc && wanted_pc < pc)
266 goto found;
267 func_name[0] = '\0';
268 func_addr = 0;
269 } else {
270 str = stab_str + sym->n_strx;
271 p = strchr(str, ':');
272 if (!p) {
273 pstrcpy(func_name, sizeof(func_name), str);
274 } else {
275 len = p - str;
276 if (len > sizeof(func_name) - 1)
277 len = sizeof(func_name) - 1;
278 memcpy(func_name, str, len);
279 func_name[len] = '\0';
281 func_addr = sym->n_value;
283 break;
284 /* line number info */
285 case N_SLINE:
286 pc = sym->n_value + func_addr;
287 if (wanted_pc >= last_pc && wanted_pc < pc)
288 goto found;
289 last_pc = pc;
290 last_line_num = sym->n_desc;
291 /* XXX: slow! */
292 strcpy(last_func_name, func_name);
293 break;
294 /* include files */
295 case N_BINCL:
296 str = stab_str + sym->n_strx;
297 add_incl:
298 if (incl_index < INCLUDE_STACK_SIZE) {
299 incl_files[incl_index++] = str;
301 break;
302 case N_EINCL:
303 if (incl_index > 1)
304 incl_index--;
305 break;
306 case N_SO:
307 if (sym->n_strx == 0) {
308 incl_index = 0; /* end of translation unit */
309 } else {
310 str = stab_str + sym->n_strx;
311 /* do not add path */
312 len = strlen(str);
313 if (len > 0 && str[len - 1] != '/')
314 goto add_incl;
316 break;
320 no_stabs:
321 /* second pass: we try symtab symbols (no line number info) */
322 incl_index = 0;
323 if (symtab_section)
325 ElfW(Sym) *sym, *sym_end;
326 int type;
328 sym_end = (ElfW(Sym) *)(symtab_section->data + symtab_section->data_offset);
329 for(sym = (ElfW(Sym) *)symtab_section->data + 1;
330 sym < sym_end;
331 sym++) {
332 type = ELFW(ST_TYPE)(sym->st_info);
333 if (type == STT_FUNC || type == STT_GNU_IFUNC) {
334 if (wanted_pc >= sym->st_value &&
335 wanted_pc < sym->st_value + sym->st_size) {
336 pstrcpy(last_func_name, sizeof(last_func_name),
337 strtab_section->data + sym->st_name);
338 func_addr = sym->st_value;
339 goto found;
344 /* did not find any info: */
345 fprintf(stderr, "%s %p ???\n", msg, (void*)wanted_pc);
346 fflush(stderr);
347 return 0;
348 found:
349 i = incl_index;
350 if (i > 0)
351 fprintf(stderr, "%s:%d: ", incl_files[--i], last_line_num);
352 fprintf(stderr, "%s %p", msg, (void*)wanted_pc);
353 if (last_func_name[0] != '\0')
354 fprintf(stderr, " %s()", last_func_name);
355 if (--i >= 0) {
356 fprintf(stderr, " (included from ");
357 for (;;) {
358 fprintf(stderr, "%s", incl_files[i]);
359 if (--i < 0)
360 break;
361 fprintf(stderr, ", ");
363 fprintf(stderr, ")");
365 fprintf(stderr, "\n");
366 fflush(stderr);
367 return func_addr;
370 /* emit a run time error at position 'pc' */
371 static void rt_error(ucontext_t *uc, const char *fmt, ...)
373 va_list ap;
374 uplong pc;
375 int i;
377 fprintf(stderr, "Runtime error: ");
378 va_start(ap, fmt);
379 vfprintf(stderr, fmt, ap);
380 va_end(ap);
381 fprintf(stderr, "\n");
383 for(i=0;i<rt_num_callers;i++) {
384 if (rt_get_caller_pc(&pc, uc, i) < 0)
385 break;
386 pc = rt_printline(pc, i ? "by" : "at");
387 if (pc == (uplong)rt_prog_main && pc)
388 break;
392 /* ------------------------------------------------------------- */
393 #ifndef _WIN32
395 /* signal handler for fatal errors */
396 static void sig_error(int signum, siginfo_t *siginf, void *puc)
398 ucontext_t *uc = puc;
400 switch(signum) {
401 case SIGFPE:
402 switch(siginf->si_code) {
403 case FPE_INTDIV:
404 case FPE_FLTDIV:
405 rt_error(uc, "division by zero");
406 break;
407 default:
408 rt_error(uc, "floating point exception");
409 break;
411 break;
412 case SIGBUS:
413 case SIGSEGV:
414 if (rt_bound_error_msg && *rt_bound_error_msg)
415 rt_error(uc, *rt_bound_error_msg);
416 else
417 rt_error(uc, "dereferencing invalid pointer");
418 break;
419 case SIGILL:
420 rt_error(uc, "illegal instruction");
421 break;
422 case SIGABRT:
423 rt_error(uc, "abort() called");
424 break;
425 default:
426 rt_error(uc, "caught signal %d", signum);
427 break;
429 exit(255);
432 /* Generate a stack backtrace when a CPU exception occurs. */
433 static void set_exception_handler(void)
435 struct sigaction sigact;
436 /* install TCC signal handlers to print debug info on fatal
437 runtime errors */
438 sigact.sa_flags = SA_SIGINFO | SA_RESETHAND;
439 sigact.sa_sigaction = sig_error;
440 sigemptyset(&sigact.sa_mask);
441 sigaction(SIGFPE, &sigact, NULL);
442 sigaction(SIGILL, &sigact, NULL);
443 sigaction(SIGSEGV, &sigact, NULL);
444 sigaction(SIGBUS, &sigact, NULL);
445 sigaction(SIGABRT, &sigact, NULL);
448 /* ------------------------------------------------------------- */
449 #ifdef __i386__
451 /* fix for glibc 2.1 */
452 #ifndef REG_EIP
453 #define REG_EIP EIP
454 #define REG_EBP EBP
455 #endif
457 /* return the PC at frame level 'level'. Return non zero if not found */
458 static int rt_get_caller_pc(unsigned long *paddr, ucontext_t *uc, int level)
460 unsigned long fp;
461 int i;
463 if (level == 0) {
464 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
465 *paddr = uc->uc_mcontext.mc_eip;
466 #elif defined(__dietlibc__)
467 *paddr = uc->uc_mcontext.eip;
468 #else
469 *paddr = uc->uc_mcontext.gregs[REG_EIP];
470 #endif
471 return 0;
472 } else {
473 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
474 fp = uc->uc_mcontext.mc_ebp;
475 #elif defined(__dietlibc__)
476 fp = uc->uc_mcontext.ebp;
477 #else
478 fp = uc->uc_mcontext.gregs[REG_EBP];
479 #endif
480 for(i=1;i<level;i++) {
481 /* XXX: check address validity with program info */
482 if (fp <= 0x1000 || fp >= 0xc0000000)
483 return -1;
484 fp = ((unsigned long *)fp)[0];
486 *paddr = ((unsigned long *)fp)[1];
487 return 0;
491 /* ------------------------------------------------------------- */
492 #elif defined(__x86_64__)
494 /* return the PC at frame level 'level'. Return non zero if not found */
495 static int rt_get_caller_pc(unsigned long *paddr,
496 ucontext_t *uc, int level)
498 unsigned long fp;
499 int i;
501 if (level == 0) {
502 /* XXX: only support linux */
503 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
504 *paddr = uc->uc_mcontext.mc_rip;
505 #else
506 *paddr = uc->uc_mcontext.gregs[REG_RIP];
507 #endif
508 return 0;
509 } else {
510 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
511 fp = uc->uc_mcontext.mc_rbp;
512 #else
513 fp = uc->uc_mcontext.gregs[REG_RBP];
514 #endif
515 for(i=1;i<level;i++) {
516 /* XXX: check address validity with program info */
517 if (fp <= 0x1000)
518 return -1;
519 fp = ((unsigned long *)fp)[0];
521 *paddr = ((unsigned long *)fp)[1];
522 return 0;
526 /* ------------------------------------------------------------- */
527 #elif defined(__arm__)
529 /* return the PC at frame level 'level'. Return negative if not found */
530 static int rt_get_caller_pc(unsigned long *paddr,
531 ucontext_t *uc, int level)
533 uint32_t fp, sp;
534 int i;
536 if (level == 0) {
537 /* XXX: only supports linux */
538 #if defined(__linux__)
539 *paddr = uc->uc_mcontext.arm_pc;
540 #else
541 return -1;
542 #endif
543 return 0;
544 } else {
545 #if defined(__linux__)
546 fp = uc->uc_mcontext.arm_fp;
547 sp = uc->uc_mcontext.arm_sp;
548 if (sp < 0x1000)
549 sp = 0x1000;
550 #else
551 return -1;
552 #endif
553 /* XXX: specific to tinycc stack frames */
554 if (fp < sp + 12 || fp & 3)
555 return -1;
556 for(i = 1; i < level; i++) {
557 sp = ((uint32_t *)fp)[-2];
558 if (sp < fp || sp - fp > 16 || sp & 3)
559 return -1;
560 fp = ((uint32_t *)fp)[-3];
561 if (fp <= sp || fp - sp < 12 || fp & 3)
562 return -1;
564 /* XXX: check address validity with program info */
565 *paddr = ((uint32_t *)fp)[-1];
566 return 0;
570 /* ------------------------------------------------------------- */
571 #else
573 #warning add arch specific rt_get_caller_pc()
574 static int rt_get_caller_pc(unsigned long *paddr,
575 ucontext_t *uc, int level)
577 return -1;
580 #endif /* !__i386__ */
582 /* ------------------------------------------------------------- */
583 #else /* WIN32 */
585 static long __stdcall cpu_exception_handler(EXCEPTION_POINTERS *ex_info)
587 EXCEPTION_RECORD *er = ex_info->ExceptionRecord;
588 CONTEXT *uc = ex_info->ContextRecord;
589 switch (er->ExceptionCode) {
590 case EXCEPTION_ACCESS_VIOLATION:
591 if (rt_bound_error_msg && *rt_bound_error_msg)
592 rt_error(uc, *rt_bound_error_msg);
593 else
594 rt_error(uc, "access violation");
595 break;
596 case EXCEPTION_STACK_OVERFLOW:
597 rt_error(uc, "stack overflow");
598 break;
599 case EXCEPTION_INT_DIVIDE_BY_ZERO:
600 rt_error(uc, "division by zero");
601 break;
602 default:
603 rt_error(uc, "exception caught");
604 break;
606 exit(-1);
607 return EXCEPTION_CONTINUE_SEARCH;
610 /* Generate a stack backtrace when a CPU exception occurs. */
611 static void set_exception_handler(void)
613 SetUnhandledExceptionFilter(cpu_exception_handler);
616 #ifdef _WIN64
617 static void win64_add_function_table(TCCState *s1)
619 RtlAddFunctionTable(
620 (RUNTIME_FUNCTION*)(uplong)s1->uw_pdata->sh_addr,
621 s1->uw_pdata->data_offset / sizeof (RUNTIME_FUNCTION),
622 (uplong)text_section->sh_addr
625 #endif
627 /* return the PC at frame level 'level'. Return non zero if not found */
628 static int rt_get_caller_pc(uplong *paddr, CONTEXT *uc, int level)
630 uplong fp, pc;
631 int i;
632 #ifdef _WIN64
633 pc = uc->Rip;
634 fp = uc->Rbp;
635 #else
636 pc = uc->Eip;
637 fp = uc->Ebp;
638 #endif
639 if (level > 0) {
640 for(i=1;i<level;i++) {
641 /* XXX: check address validity with program info */
642 if (fp <= 0x1000 || fp >= 0xc0000000)
643 return -1;
644 fp = ((uplong*)fp)[0];
646 pc = ((uplong*)fp)[1];
648 *paddr = pc;
649 return 0;
652 #endif /* _WIN32 */
653 #endif /* CONFIG_TCC_BACKTRACE */
654 /* ------------------------------------------------------------- */
656 #ifdef CONFIG_TCC_STATIC
658 #define RTLD_LAZY 0x001
659 #define RTLD_NOW 0x002
660 #define RTLD_GLOBAL 0x100
661 #define RTLD_DEFAULT NULL
663 /* dummy function for profiling */
664 ST_FUNC void *dlopen(const char *filename, int flag)
666 return NULL;
669 ST_FUNC void dlclose(void *p)
673 const char *dlerror(void)
675 return "error";
678 typedef struct TCCSyms {
679 char *str;
680 void *ptr;
681 } TCCSyms;
683 #define TCCSYM(a) { #a, &a, },
685 /* add the symbol you want here if no dynamic linking is done */
686 static TCCSyms tcc_syms[] = {
687 #if !defined(CONFIG_TCCBOOT)
688 TCCSYM(printf)
689 TCCSYM(fprintf)
690 TCCSYM(fopen)
691 TCCSYM(fclose)
692 #endif
693 { NULL, NULL },
696 ST_FUNC void *resolve_sym(TCCState *s1, const char *symbol)
698 TCCSyms *p;
699 p = tcc_syms;
700 while (p->str != NULL) {
701 if (!strcmp(p->str, symbol))
702 return p->ptr;
703 p++;
705 return NULL;
708 #elif !defined(_WIN32)
710 ST_FUNC void *resolve_sym(TCCState *s1, const char *sym)
712 return dlsym(RTLD_DEFAULT, sym);
715 #endif /* CONFIG_TCC_STATIC */
717 /* ------------------------------------------------------------- */