x86-64: fix flags and zero-pad long doubles
[tinycc.git] / tccrun.c
blob9cb7588835eb0d46fc78c1ce61cbb42c9ccc3369
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 #ifdef _WIN64
34 static void win64_add_function_table(TCCState *s1);
35 #endif
37 /* ------------------------------------------------------------- */
38 /* Do all relocations (needed before using tcc_get_symbol())
39 Returns -1 on error. */
41 int tcc_relocate(TCCState *s1)
43 int ret;
44 #ifdef HAVE_SELINUX
45 /* Use mmap instead of malloc for Selinux
46 Ref http://www.gnu.org/s/libc/manual/html_node/File-Size.html */
47 char tmpfname[] = "/tmp/.tccrunXXXXXX";
48 int fd = mkstemp (tmpfname);
49 if ((ret= tcc_relocate_ex(s1,NULL)) < 0)return -1;
50 s1->mem_size=ret;
51 unlink (tmpfname); ftruncate (fd, s1->mem_size);
52 s1->write_mem = mmap (NULL, ret, PROT_READ|PROT_WRITE,
53 MAP_SHARED, fd, 0);
54 if(s1->write_mem == MAP_FAILED){
55 error("/tmp not writeable");
56 return -1;
58 s1->runtime_mem = mmap (NULL, ret, PROT_READ|PROT_EXEC,
59 MAP_SHARED, fd, 0);
60 if(s1->runtime_mem == MAP_FAILED){
61 error("/tmp not executable");
62 return -1;
64 ret = tcc_relocate_ex(s1, s1->write_mem);
65 #else
66 ret = tcc_relocate_ex(s1, NULL);
67 if (-1 != ret) {
68 s1->runtime_mem = tcc_malloc(ret);
69 ret = tcc_relocate_ex(s1, s1->runtime_mem);
71 #endif
72 return ret;
75 /* launch the compiled program with the given arguments */
76 int tcc_run(TCCState *s1, int argc, char **argv)
78 int (*prog_main)(int, char **);
79 int ret;
81 if (tcc_relocate(s1) < 0)
82 return -1;
84 prog_main = tcc_get_symbol_err(s1, "main");
86 #ifdef CONFIG_TCC_BACKTRACE
87 if (s1->do_debug) {
88 set_exception_handler();
89 rt_prog_main = prog_main;
91 #endif
93 #ifdef CONFIG_TCC_BCHECK
94 if (s1->do_bounds_check) {
95 void (*bound_init)(void);
96 void (*bound_exit)(void);
97 /* set error function */
98 rt_bound_error_msg = tcc_get_symbol_err(s1, "__bound_error_msg");
99 /* XXX: use .init section so that it also work in binary ? */
100 bound_init = tcc_get_symbol_err(s1, "__bound_init");
101 bound_exit = tcc_get_symbol_err(s1, "__bound_exit");
102 bound_init();
103 ret = (*prog_main)(argc, argv);
104 bound_exit();
105 } else
106 #endif
107 ret = (*prog_main)(argc, argv);
108 return ret;
111 /* relocate code. Return -1 on error, required size if ptr is NULL,
112 otherwise copy code into buffer passed by the caller */
113 static int tcc_relocate_ex(TCCState *s1, void *ptr)
115 Section *s;
116 unsigned long offset, length;
117 uplong mem;
118 int i;
120 if (0 == s1->runtime_added) {
121 s1->runtime_added = 1;
122 s1->nb_errors = 0;
123 #ifdef TCC_TARGET_PE
124 pe_output_file(s1, NULL);
125 #else
126 tcc_add_runtime(s1);
127 relocate_common_syms();
128 tcc_add_linker_symbols(s1);
129 build_got_entries(s1);
130 #endif
131 if (s1->nb_errors)
132 return -1;
135 offset = 0, mem = (uplong)ptr;
136 for(i = 1; i < s1->nb_sections; i++) {
137 s = s1->sections[i];
138 if (0 == (s->sh_flags & SHF_ALLOC))
139 continue;
140 length = s->data_offset;
141 s->sh_addr = mem ? (mem + offset + 15) & ~15 : 0;
142 offset = (offset + length + 15) & ~15;
144 offset += 16;
146 /* relocate symbols */
147 relocate_syms(s1, 1);
148 if (s1->nb_errors)
149 return -1;
151 #if (defined TCC_TARGET_X86_64 || defined TCC_TARGET_ARM) && !defined TCC_TARGET_PE
152 s1->runtime_plt_and_got_offset = 0;
153 s1->runtime_plt_and_got = (char *)(mem + offset);
154 /* double the size of the buffer for got and plt entries
155 XXX: calculate exact size for them? */
156 offset *= 2;
157 #endif
159 if (0 == mem)
160 return offset;
162 /* relocate each section */
163 for(i = 1; i < s1->nb_sections; i++) {
164 s = s1->sections[i];
165 if (s->reloc)
166 relocate_section(s1, s);
169 for(i = 1; i < s1->nb_sections; i++) {
170 s = s1->sections[i];
171 if (0 == (s->sh_flags & SHF_ALLOC))
172 continue;
173 length = s->data_offset;
174 // printf("%-12s %08x %04x\n", s->name, s->sh_addr, length);
175 ptr = (void*)(uplong)s->sh_addr;
176 if (NULL == s->data || s->sh_type == SHT_NOBITS)
177 memset(ptr, 0, length);
178 else
179 memcpy(ptr, s->data, length);
180 /* mark executable sections as executable in memory */
181 if (s->sh_flags & SHF_EXECINSTR)
182 set_pages_executable(ptr, length);
185 #if (defined TCC_TARGET_X86_64 || defined TCC_TARGET_ARM) && !defined TCC_TARGET_PE
186 set_pages_executable(s1->runtime_plt_and_got,
187 s1->runtime_plt_and_got_offset);
188 #endif
190 #ifdef _WIN64
191 win64_add_function_table(s1);
192 #endif
193 return 0;
196 /* ------------------------------------------------------------- */
197 /* allow to run code in memory */
199 static void set_pages_executable(void *ptr, unsigned long length)
201 #ifdef _WIN32
202 unsigned long old_protect;
203 VirtualProtect(ptr, length, PAGE_EXECUTE_READWRITE, &old_protect);
204 #else
205 unsigned long start, end;
206 start = (uplong)ptr & ~(PAGESIZE - 1);
207 end = (uplong)ptr + length;
208 end = (end + PAGESIZE - 1) & ~(PAGESIZE - 1);
209 mprotect((void *)start, end - start, PROT_READ | PROT_WRITE | PROT_EXEC);
210 #endif
213 /* ------------------------------------------------------------- */
214 #ifdef CONFIG_TCC_BACKTRACE
216 /* print the position in the source file of PC value 'pc' by reading
217 the stabs debug information */
218 static uplong rt_printline(uplong wanted_pc, const char *msg)
220 char func_name[128], last_func_name[128];
221 uplong func_addr, last_pc, pc;
222 const char *incl_files[INCLUDE_STACK_SIZE];
223 int incl_index, len, last_line_num, i;
224 const char *str, *p;
226 Stab_Sym *stab_sym = NULL, *stab_sym_end, *sym;
227 int stab_len = 0;
228 char *stab_str = NULL;
230 if (stab_section) {
231 stab_len = stab_section->data_offset;
232 stab_sym = (Stab_Sym *)stab_section->data;
233 stab_str = stabstr_section->data;
236 func_name[0] = '\0';
237 func_addr = 0;
238 incl_index = 0;
239 last_func_name[0] = '\0';
240 last_pc = (uplong)-1;
241 last_line_num = 1;
243 if (!stab_sym)
244 goto no_stabs;
246 stab_sym_end = (Stab_Sym*)((char*)stab_sym + stab_len);
247 for (sym = stab_sym + 1; sym < stab_sym_end; ++sym) {
248 switch(sym->n_type) {
249 /* function start or end */
250 case N_FUN:
251 if (sym->n_strx == 0) {
252 /* we test if between last line and end of function */
253 pc = sym->n_value + func_addr;
254 if (wanted_pc >= last_pc && wanted_pc < pc)
255 goto found;
256 func_name[0] = '\0';
257 func_addr = 0;
258 } else {
259 str = stab_str + sym->n_strx;
260 p = strchr(str, ':');
261 if (!p) {
262 pstrcpy(func_name, sizeof(func_name), str);
263 } else {
264 len = p - str;
265 if (len > sizeof(func_name) - 1)
266 len = sizeof(func_name) - 1;
267 memcpy(func_name, str, len);
268 func_name[len] = '\0';
270 func_addr = sym->n_value;
272 break;
273 /* line number info */
274 case N_SLINE:
275 pc = sym->n_value + func_addr;
276 if (wanted_pc >= last_pc && wanted_pc < pc)
277 goto found;
278 last_pc = pc;
279 last_line_num = sym->n_desc;
280 /* XXX: slow! */
281 strcpy(last_func_name, func_name);
282 break;
283 /* include files */
284 case N_BINCL:
285 str = stab_str + sym->n_strx;
286 add_incl:
287 if (incl_index < INCLUDE_STACK_SIZE) {
288 incl_files[incl_index++] = str;
290 break;
291 case N_EINCL:
292 if (incl_index > 1)
293 incl_index--;
294 break;
295 case N_SO:
296 if (sym->n_strx == 0) {
297 incl_index = 0; /* end of translation unit */
298 } else {
299 str = stab_str + sym->n_strx;
300 /* do not add path */
301 len = strlen(str);
302 if (len > 0 && str[len - 1] != '/')
303 goto add_incl;
305 break;
309 no_stabs:
310 /* second pass: we try symtab symbols (no line number info) */
311 incl_index = 0;
312 if (symtab_section)
314 ElfW(Sym) *sym, *sym_end;
315 int type;
317 sym_end = (ElfW(Sym) *)(symtab_section->data + symtab_section->data_offset);
318 for(sym = (ElfW(Sym) *)symtab_section->data + 1;
319 sym < sym_end;
320 sym++) {
321 type = ELFW(ST_TYPE)(sym->st_info);
322 if (type == STT_FUNC || type == STT_GNU_IFUNC) {
323 if (wanted_pc >= sym->st_value &&
324 wanted_pc < sym->st_value + sym->st_size) {
325 pstrcpy(last_func_name, sizeof(last_func_name),
326 strtab_section->data + sym->st_name);
327 func_addr = sym->st_value;
328 goto found;
333 /* did not find any info: */
334 fprintf(stderr, "%s %p ???\n", msg, (void*)wanted_pc);
335 fflush(stderr);
336 return 0;
337 found:
338 i = incl_index;
339 if (i > 0)
340 fprintf(stderr, "%s:%d: ", incl_files[--i], last_line_num);
341 fprintf(stderr, "%s %p", msg, (void*)wanted_pc);
342 if (last_func_name[0] != '\0')
343 fprintf(stderr, " %s()", last_func_name);
344 if (--i >= 0) {
345 fprintf(stderr, " (included from ");
346 for (;;) {
347 fprintf(stderr, "%s", incl_files[i]);
348 if (--i < 0)
349 break;
350 fprintf(stderr, ", ");
352 fprintf(stderr, ")");
354 fprintf(stderr, "\n");
355 fflush(stderr);
356 return func_addr;
359 /* emit a run time error at position 'pc' */
360 static void rt_error(ucontext_t *uc, const char *fmt, ...)
362 va_list ap;
363 uplong pc;
364 int i;
366 fprintf(stderr, "Runtime error: ");
367 va_start(ap, fmt);
368 vfprintf(stderr, fmt, ap);
369 va_end(ap);
370 fprintf(stderr, "\n");
372 for(i=0;i<num_callers;i++) {
373 if (rt_get_caller_pc(&pc, uc, i) < 0)
374 break;
375 pc = rt_printline(pc, i ? "by" : "at");
376 if (pc == (uplong)rt_prog_main && pc)
377 break;
381 /* ------------------------------------------------------------- */
382 #ifndef _WIN32
384 /* signal handler for fatal errors */
385 static void sig_error(int signum, siginfo_t *siginf, void *puc)
387 ucontext_t *uc = puc;
389 switch(signum) {
390 case SIGFPE:
391 switch(siginf->si_code) {
392 case FPE_INTDIV:
393 case FPE_FLTDIV:
394 rt_error(uc, "division by zero");
395 break;
396 default:
397 rt_error(uc, "floating point exception");
398 break;
400 break;
401 case SIGBUS:
402 case SIGSEGV:
403 if (rt_bound_error_msg && *rt_bound_error_msg)
404 rt_error(uc, *rt_bound_error_msg);
405 else
406 rt_error(uc, "dereferencing invalid pointer");
407 break;
408 case SIGILL:
409 rt_error(uc, "illegal instruction");
410 break;
411 case SIGABRT:
412 rt_error(uc, "abort() called");
413 break;
414 default:
415 rt_error(uc, "caught signal %d", signum);
416 break;
418 exit(255);
421 /* Generate a stack backtrace when a CPU exception occurs. */
422 static void set_exception_handler(void)
424 struct sigaction sigact;
425 /* install TCC signal handlers to print debug info on fatal
426 runtime errors */
427 sigact.sa_flags = SA_SIGINFO | SA_RESETHAND;
428 sigact.sa_sigaction = sig_error;
429 sigemptyset(&sigact.sa_mask);
430 sigaction(SIGFPE, &sigact, NULL);
431 sigaction(SIGILL, &sigact, NULL);
432 sigaction(SIGSEGV, &sigact, NULL);
433 sigaction(SIGBUS, &sigact, NULL);
434 sigaction(SIGABRT, &sigact, NULL);
437 /* ------------------------------------------------------------- */
438 #ifdef __i386__
440 /* fix for glibc 2.1 */
441 #ifndef REG_EIP
442 #define REG_EIP EIP
443 #define REG_EBP EBP
444 #endif
446 /* return the PC at frame level 'level'. Return non zero if not found */
447 static int rt_get_caller_pc(unsigned long *paddr, ucontext_t *uc, int level)
449 unsigned long fp;
450 int i;
452 if (level == 0) {
453 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
454 *paddr = uc->uc_mcontext.mc_eip;
455 #elif defined(__dietlibc__)
456 *paddr = uc->uc_mcontext.eip;
457 #else
458 *paddr = uc->uc_mcontext.gregs[REG_EIP];
459 #endif
460 return 0;
461 } else {
462 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
463 fp = uc->uc_mcontext.mc_ebp;
464 #elif defined(__dietlibc__)
465 fp = uc->uc_mcontext.ebp;
466 #else
467 fp = uc->uc_mcontext.gregs[REG_EBP];
468 #endif
469 for(i=1;i<level;i++) {
470 /* XXX: check address validity with program info */
471 if (fp <= 0x1000 || fp >= 0xc0000000)
472 return -1;
473 fp = ((unsigned long *)fp)[0];
475 *paddr = ((unsigned long *)fp)[1];
476 return 0;
480 /* ------------------------------------------------------------- */
481 #elif defined(__x86_64__)
483 /* return the PC at frame level 'level'. Return non zero if not found */
484 static int rt_get_caller_pc(unsigned long *paddr,
485 ucontext_t *uc, int level)
487 unsigned long fp;
488 int i;
490 if (level == 0) {
491 /* XXX: only support linux */
492 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
493 *paddr = uc->uc_mcontext.mc_rip;
494 #else
495 *paddr = uc->uc_mcontext.gregs[REG_RIP];
496 #endif
497 return 0;
498 } else {
499 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
500 fp = uc->uc_mcontext.mc_rbp;
501 #else
502 fp = uc->uc_mcontext.gregs[REG_RBP];
503 #endif
504 for(i=1;i<level;i++) {
505 /* XXX: check address validity with program info */
506 if (fp <= 0x1000)
507 return -1;
508 fp = ((unsigned long *)fp)[0];
510 *paddr = ((unsigned long *)fp)[1];
511 return 0;
515 /* ------------------------------------------------------------- */
516 #elif defined(__arm__)
518 /* return the PC at frame level 'level'. Return negative if not found */
519 static int rt_get_caller_pc(unsigned long *paddr,
520 ucontext_t *uc, int level)
522 uint32_t fp, sp;
523 int i;
525 if (level == 0) {
526 /* XXX: only supports linux */
527 #if defined(__linux__)
528 *paddr = uc->uc_mcontext.arm_pc;
529 #else
530 return -1;
531 #endif
532 return 0;
533 } else {
534 #if defined(__linux__)
535 fp = uc->uc_mcontext.arm_fp;
536 sp = uc->uc_mcontext.arm_sp;
537 if (sp < 0x1000)
538 sp = 0x1000;
539 #else
540 return -1;
541 #endif
542 /* XXX: specific to tinycc stack frames */
543 if (fp < sp + 12 || fp & 3)
544 return -1;
545 for(i = 1; i < level; i++) {
546 sp = ((uint32_t *)fp)[-2];
547 if (sp < fp || sp - fp > 16 || sp & 3)
548 return -1;
549 fp = ((uint32_t *)fp)[-3];
550 if (fp <= sp || fp - sp < 12 || fp & 3)
551 return -1;
553 /* XXX: check address validity with program info */
554 *paddr = ((uint32_t *)fp)[-1];
555 return 0;
559 /* ------------------------------------------------------------- */
560 #else
562 #warning add arch specific rt_get_caller_pc()
563 static int rt_get_caller_pc(unsigned long *paddr,
564 ucontext_t *uc, int level)
566 return -1;
569 #endif /* !__i386__ */
571 /* ------------------------------------------------------------- */
572 #else /* WIN32 */
574 static long __stdcall cpu_exception_handler(EXCEPTION_POINTERS *ex_info)
576 EXCEPTION_RECORD *er = ex_info->ExceptionRecord;
577 CONTEXT *uc = ex_info->ContextRecord;
578 switch (er->ExceptionCode) {
579 case EXCEPTION_ACCESS_VIOLATION:
580 if (rt_bound_error_msg && *rt_bound_error_msg)
581 rt_error(uc, *rt_bound_error_msg);
582 else
583 rt_error(uc, "access violation");
584 break;
585 case EXCEPTION_STACK_OVERFLOW:
586 rt_error(uc, "stack overflow");
587 break;
588 case EXCEPTION_INT_DIVIDE_BY_ZERO:
589 rt_error(uc, "division by zero");
590 break;
591 default:
592 rt_error(uc, "exception caught");
593 break;
595 exit(-1);
596 return EXCEPTION_CONTINUE_SEARCH;
599 /* Generate a stack backtrace when a CPU exception occurs. */
600 static void set_exception_handler(void)
602 SetUnhandledExceptionFilter(cpu_exception_handler);
605 #ifdef _WIN64
606 static void win64_add_function_table(TCCState *s1)
608 RtlAddFunctionTable(
609 (RUNTIME_FUNCTION*)(uplong)s1->uw_pdata->sh_addr,
610 s1->uw_pdata->data_offset / sizeof (RUNTIME_FUNCTION),
611 (uplong)text_section->sh_addr
614 #endif
616 /* return the PC at frame level 'level'. Return non zero if not found */
617 static int rt_get_caller_pc(uplong *paddr, CONTEXT *uc, int level)
619 uplong fp, pc;
620 int i;
621 #ifdef _WIN64
622 pc = uc->Rip;
623 fp = uc->Rbp;
624 #else
625 pc = uc->Eip;
626 fp = uc->Ebp;
627 #endif
628 if (level > 0) {
629 for(i=1;i<level;i++) {
630 /* XXX: check address validity with program info */
631 if (fp <= 0x1000 || fp >= 0xc0000000)
632 return -1;
633 fp = ((uplong*)fp)[0];
635 pc = ((uplong*)fp)[1];
637 *paddr = pc;
638 return 0;
641 #endif /* _WIN32 */
642 #endif /* CONFIG_TCC_BACKTRACE */
643 /* ------------------------------------------------------------- */
645 #ifdef CONFIG_TCC_STATIC
647 #define RTLD_LAZY 0x001
648 #define RTLD_NOW 0x002
649 #define RTLD_GLOBAL 0x100
650 #define RTLD_DEFAULT NULL
652 /* dummy function for profiling */
653 void *dlopen(const char *filename, int flag)
655 return NULL;
658 void dlclose(void *p)
662 const char *dlerror(void)
664 return "error";
667 typedef struct TCCSyms {
668 char *str;
669 void *ptr;
670 } TCCSyms;
672 #define TCCSYM(a) { #a, &a, },
674 /* add the symbol you want here if no dynamic linking is done */
675 static TCCSyms tcc_syms[] = {
676 #if !defined(CONFIG_TCCBOOT)
677 TCCSYM(printf)
678 TCCSYM(fprintf)
679 TCCSYM(fopen)
680 TCCSYM(fclose)
681 #endif
682 { NULL, NULL },
685 void *resolve_sym(TCCState *s1, const char *symbol)
687 TCCSyms *p;
688 p = tcc_syms;
689 while (p->str != NULL) {
690 if (!strcmp(p->str, symbol))
691 return p->ptr;
692 p++;
694 return NULL;
697 #elif !defined(_WIN32)
699 void *resolve_sym(TCCState *s1, const char *sym)
701 return dlsym(RTLD_DEFAULT, sym);
704 #endif /* CONFIG_TCC_STATIC */
706 /* ------------------------------------------------------------- */