Make TOK_alloca available for x86-64
[tinycc.git] / tccrun.c
blob0423a1d3ff04482a7ce33b562c5b066a891ad1eb
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 /* ------------------------------------------------------------- */
34 /* Do all relocations (needed before using tcc_get_symbol())
35 Returns -1 on error. */
37 int tcc_relocate(TCCState *s1)
39 int ret;
40 #ifdef HAVE_SELINUX
41 /* Use mmap instead of malloc for Selinux
42 Ref http://www.gnu.org/s/libc/manual/html_node/File-Size.html */
43 char tmpfname[] = "/tmp/.tccrunXXXXXX";
44 int fd = mkstemp (tmpfname);
45 if ((ret= tcc_relocate_ex(s1,NULL)) < 0)return -1;
46 s1->mem_size=ret;
47 unlink (tmpfname); ftruncate (fd, s1->mem_size);
48 s1->write_mem = mmap (NULL, ret, PROT_READ|PROT_WRITE,
49 MAP_SHARED, fd, 0);
50 if(s1->write_mem == MAP_FAILED){
51 error("/tmp not writeable");
52 return -1;
54 s1->runtime_mem = mmap (NULL, ret, PROT_READ|PROT_EXEC,
55 MAP_SHARED, fd, 0);
56 if(s1->runtime_mem == MAP_FAILED){
57 error("/tmp not executable");
58 return -1;
60 ret = tcc_relocate_ex(s1, s1->write_mem);
61 #else
62 ret = tcc_relocate_ex(s1, NULL);
63 if (-1 != ret) {
64 s1->runtime_mem = tcc_malloc(ret);
65 ret = tcc_relocate_ex(s1, s1->runtime_mem);
67 #endif
68 return ret;
71 /* launch the compiled program with the given arguments */
72 int tcc_run(TCCState *s1, int argc, char **argv)
74 int (*prog_main)(int, char **);
76 if (tcc_relocate(s1) < 0)
77 return -1;
79 prog_main = tcc_get_symbol_err(s1, "main");
81 #ifdef CONFIG_TCC_BACKTRACE
82 if (s1->do_debug)
83 set_exception_handler();
84 #endif
86 #ifdef CONFIG_TCC_BCHECK
87 if (s1->do_bounds_check) {
88 void (*bound_init)(void);
89 void (*bound_exit)(void);
90 int ret;
91 /* set error function */
92 rt_bound_error_msg = tcc_get_symbol_err(s1, "__bound_error_msg");
93 rt_prog_main = prog_main;
94 /* XXX: use .init section so that it also work in binary ? */
95 bound_init = tcc_get_symbol_err(s1, "__bound_init");
96 bound_exit = tcc_get_symbol_err(s1, "__bound_exit");
97 bound_init();
98 ret = (*prog_main)(argc, argv);
99 bound_exit();
100 return ret;
102 #endif
104 #ifdef TCC_TARGET_PE
106 unsigned char *p = tcc_get_symbol(s1, "tinyc_no_getbp");
107 if (p) *p = 0;
109 #endif
110 return (*prog_main)(argc, argv);
114 /* relocate code. Return -1 on error, required size if ptr is NULL,
115 otherwise copy code into buffer passed by the caller */
116 static int tcc_relocate_ex(TCCState *s1, void *ptr)
118 Section *s;
119 unsigned long offset, length;
120 uplong mem;
121 int i;
123 if (0 == s1->runtime_added) {
124 s1->runtime_added = 1;
125 s1->nb_errors = 0;
126 #ifdef TCC_TARGET_PE
127 pe_output_file(s1, NULL);
128 #else
129 tcc_add_runtime(s1);
130 relocate_common_syms();
131 tcc_add_linker_symbols(s1);
132 build_got_entries(s1);
133 #endif
134 if (s1->nb_errors)
135 return -1;
138 offset = 0, mem = (uplong)ptr;
139 for(i = 1; i < s1->nb_sections; i++) {
140 s = s1->sections[i];
141 if (0 == (s->sh_flags & SHF_ALLOC))
142 continue;
143 length = s->data_offset;
144 s->sh_addr = mem ? (mem + offset + 15) & ~15 : 0;
145 offset = (offset + length + 15) & ~15;
147 offset += 16;
149 /* relocate symbols */
150 relocate_syms(s1, 1);
151 if (s1->nb_errors)
152 return -1;
154 #if (defined TCC_TARGET_X86_64 || defined TCC_TARGET_ARM) && !defined TCC_TARGET_PE
155 s1->runtime_plt_and_got_offset = 0;
156 s1->runtime_plt_and_got = (char *)(mem + offset);
157 /* double the size of the buffer for got and plt entries
158 XXX: calculate exact size for them? */
159 offset *= 2;
160 #endif
162 if (0 == mem)
163 return offset;
165 /* relocate each section */
166 for(i = 1; i < s1->nb_sections; i++) {
167 s = s1->sections[i];
168 if (s->reloc)
169 relocate_section(s1, s);
172 for(i = 1; i < s1->nb_sections; i++) {
173 s = s1->sections[i];
174 if (0 == (s->sh_flags & SHF_ALLOC))
175 continue;
176 length = s->data_offset;
177 // printf("%-12s %08x %04x\n", s->name, s->sh_addr, length);
178 ptr = (void*)(uplong)s->sh_addr;
179 if (NULL == s->data || s->sh_type == SHT_NOBITS)
180 memset(ptr, 0, length);
181 else
182 memcpy(ptr, s->data, length);
183 /* mark executable sections as executable in memory */
184 if (s->sh_flags & SHF_EXECINSTR)
185 set_pages_executable(ptr, length);
188 #if (defined TCC_TARGET_X86_64 || defined TCC_TARGET_ARM) && !defined TCC_TARGET_PE
189 set_pages_executable(s1->runtime_plt_and_got,
190 s1->runtime_plt_and_got_offset);
191 #endif
192 return 0;
195 /* ------------------------------------------------------------- */
196 /* allow to run code in memory */
198 static void set_pages_executable(void *ptr, unsigned long length)
200 #ifdef _WIN32
201 unsigned long old_protect;
202 VirtualProtect(ptr, length, PAGE_EXECUTE_READWRITE, &old_protect);
203 #else
204 unsigned long start, end;
205 start = (uplong)ptr & ~(PAGESIZE - 1);
206 end = (uplong)ptr + length;
207 end = (end + PAGESIZE - 1) & ~(PAGESIZE - 1);
208 mprotect((void *)start, end - start, PROT_READ | PROT_WRITE | PROT_EXEC);
209 #endif
212 /* ------------------------------------------------------------- */
213 #ifdef CONFIG_TCC_BACKTRACE
215 /* print the position in the source file of PC value 'pc' by reading
216 the stabs debug information */
217 static uplong rt_printline(uplong wanted_pc)
219 Stab_Sym *sym, *sym_end;
220 char func_name[128], last_func_name[128];
221 unsigned long 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 fprintf(stderr, "0x%08lx:", (unsigned long)wanted_pc);
228 func_name[0] = '\0';
229 func_addr = 0;
230 incl_index = 0;
231 last_func_name[0] = '\0';
232 last_pc = 0xffffffff;
233 last_line_num = 1;
234 sym = (Stab_Sym *)stab_section->data + 1;
235 sym_end = (Stab_Sym *)(stab_section->data + stab_section->data_offset);
236 while (sym < sym_end) {
237 switch(sym->n_type) {
238 /* function start or end */
239 case N_FUN:
240 if (sym->n_strx == 0) {
241 /* we test if between last line and end of function */
242 pc = sym->n_value + func_addr;
243 if (wanted_pc >= last_pc && wanted_pc < pc)
244 goto found;
245 func_name[0] = '\0';
246 func_addr = 0;
247 } else {
248 str = stabstr_section->data + sym->n_strx;
249 p = strchr(str, ':');
250 if (!p) {
251 pstrcpy(func_name, sizeof(func_name), str);
252 } else {
253 len = p - str;
254 if (len > sizeof(func_name) - 1)
255 len = sizeof(func_name) - 1;
256 memcpy(func_name, str, len);
257 func_name[len] = '\0';
259 func_addr = sym->n_value;
261 break;
262 /* line number info */
263 case N_SLINE:
264 pc = sym->n_value + func_addr;
265 if (wanted_pc >= last_pc && wanted_pc < pc)
266 goto found;
267 last_pc = pc;
268 last_line_num = sym->n_desc;
269 /* XXX: slow! */
270 strcpy(last_func_name, func_name);
271 break;
272 /* include files */
273 case N_BINCL:
274 str = stabstr_section->data + sym->n_strx;
275 add_incl:
276 if (incl_index < INCLUDE_STACK_SIZE) {
277 incl_files[incl_index++] = str;
279 break;
280 case N_EINCL:
281 if (incl_index > 1)
282 incl_index--;
283 break;
284 case N_SO:
285 if (sym->n_strx == 0) {
286 incl_index = 0; /* end of translation unit */
287 } else {
288 str = stabstr_section->data + sym->n_strx;
289 /* do not add path */
290 len = strlen(str);
291 if (len > 0 && str[len - 1] != '/')
292 goto add_incl;
294 break;
296 sym++;
299 /* second pass: we try symtab symbols (no line number info) */
300 incl_index = 0;
302 ElfW(Sym) *sym, *sym_end;
303 int type;
305 sym_end = (ElfW(Sym) *)(symtab_section->data + symtab_section->data_offset);
306 for(sym = (ElfW(Sym) *)symtab_section->data + 1;
307 sym < sym_end;
308 sym++) {
309 type = ELFW(ST_TYPE)(sym->st_info);
310 if (type == STT_FUNC || type == STT_GNU_IFUNC) {
311 if (wanted_pc >= sym->st_value &&
312 wanted_pc < sym->st_value + sym->st_size) {
313 pstrcpy(last_func_name, sizeof(last_func_name),
314 strtab_section->data + sym->st_name);
315 func_addr = sym->st_value;
316 goto found;
321 /* did not find any info: */
322 fprintf(stderr, " ???\n");
323 return 0;
324 found:
325 if (last_func_name[0] != '\0') {
326 fprintf(stderr, " %s()", last_func_name);
328 if (incl_index > 0) {
329 fprintf(stderr, " (%s:%d",
330 incl_files[incl_index - 1], last_line_num);
331 for(i = incl_index - 2; i >= 0; i--)
332 fprintf(stderr, ", included from %s", incl_files[i]);
333 fprintf(stderr, ")");
335 fprintf(stderr, "\n");
336 return func_addr;
339 /* emit a run time error at position 'pc' */
340 static void rt_error(ucontext_t *uc, const char *fmt, ...)
342 va_list ap;
343 uplong pc;
344 int i;
346 va_start(ap, fmt);
347 fprintf(stderr, "Runtime error: ");
348 vfprintf(stderr, fmt, ap);
349 fprintf(stderr, "\n");
351 for(i=0;i<num_callers;i++) {
352 if (rt_get_caller_pc(&pc, uc, i) < 0)
353 break;
354 if (i == 0)
355 fprintf(stderr, "at ");
356 else
357 fprintf(stderr, "by ");
358 pc = rt_printline(pc);
359 if (pc == (uplong)rt_prog_main && pc)
360 break;
362 exit(255);
363 va_end(ap);
366 /* ------------------------------------------------------------- */
367 #ifndef _WIN32
369 /* signal handler for fatal errors */
370 static void sig_error(int signum, siginfo_t *siginf, void *puc)
372 ucontext_t *uc = puc;
374 switch(signum) {
375 case SIGFPE:
376 switch(siginf->si_code) {
377 case FPE_INTDIV:
378 case FPE_FLTDIV:
379 rt_error(uc, "division by zero");
380 break;
381 default:
382 rt_error(uc, "floating point exception");
383 break;
385 break;
386 case SIGBUS:
387 case SIGSEGV:
388 if (rt_bound_error_msg && *rt_bound_error_msg)
389 rt_error(uc, *rt_bound_error_msg);
390 else
391 rt_error(uc, "dereferencing invalid pointer");
392 break;
393 case SIGILL:
394 rt_error(uc, "illegal instruction");
395 break;
396 case SIGABRT:
397 rt_error(uc, "abort() called");
398 break;
399 default:
400 rt_error(uc, "caught signal %d", signum);
401 break;
403 exit(255);
406 /* Generate a stack backtrace when a CPU exception occurs. */
407 static void set_exception_handler(void)
409 struct sigaction sigact;
410 /* install TCC signal handlers to print debug info on fatal
411 runtime errors */
412 sigact.sa_flags = SA_SIGINFO | SA_RESETHAND;
413 sigact.sa_sigaction = sig_error;
414 sigemptyset(&sigact.sa_mask);
415 sigaction(SIGFPE, &sigact, NULL);
416 sigaction(SIGILL, &sigact, NULL);
417 sigaction(SIGSEGV, &sigact, NULL);
418 sigaction(SIGBUS, &sigact, NULL);
419 sigaction(SIGABRT, &sigact, NULL);
422 /* ------------------------------------------------------------- */
423 #ifdef __i386__
425 /* fix for glibc 2.1 */
426 #ifndef REG_EIP
427 #define REG_EIP EIP
428 #define REG_EBP EBP
429 #endif
431 /* return the PC at frame level 'level'. Return non zero if not found */
432 static int rt_get_caller_pc(unsigned long *paddr, ucontext_t *uc, int level)
434 unsigned long fp;
435 int i;
437 if (level == 0) {
438 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
439 *paddr = uc->uc_mcontext.mc_eip;
440 #elif defined(__dietlibc__)
441 *paddr = uc->uc_mcontext.eip;
442 #else
443 *paddr = uc->uc_mcontext.gregs[REG_EIP];
444 #endif
445 return 0;
446 } else {
447 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
448 fp = uc->uc_mcontext.mc_ebp;
449 #elif defined(__dietlibc__)
450 fp = uc->uc_mcontext.ebp;
451 #else
452 fp = uc->uc_mcontext.gregs[REG_EBP];
453 #endif
454 for(i=1;i<level;i++) {
455 /* XXX: check address validity with program info */
456 if (fp <= 0x1000 || fp >= 0xc0000000)
457 return -1;
458 fp = ((unsigned long *)fp)[0];
460 *paddr = ((unsigned long *)fp)[1];
461 return 0;
465 /* ------------------------------------------------------------- */
466 #elif defined(__x86_64__)
468 /* return the PC at frame level 'level'. Return non zero if not found */
469 static int rt_get_caller_pc(unsigned long *paddr,
470 ucontext_t *uc, int level)
472 unsigned long fp;
473 int i;
475 if (level == 0) {
476 /* XXX: only support linux */
477 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
478 *paddr = uc->uc_mcontext.mc_rip;
479 #else
480 *paddr = uc->uc_mcontext.gregs[REG_RIP];
481 #endif
482 return 0;
483 } else {
484 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
485 fp = uc->uc_mcontext.mc_rbp;
486 #else
487 fp = uc->uc_mcontext.gregs[REG_RBP];
488 #endif
489 for(i=1;i<level;i++) {
490 /* XXX: check address validity with program info */
491 if (fp <= 0x1000)
492 return -1;
493 fp = ((unsigned long *)fp)[0];
495 *paddr = ((unsigned long *)fp)[1];
496 return 0;
500 /* ------------------------------------------------------------- */
501 #elif defined(__arm__)
503 /* return the PC at frame level 'level'. Return negative if not found */
504 static int rt_get_caller_pc(unsigned long *paddr,
505 ucontext_t *uc, int level)
507 uint32_t fp, sp;
508 int i;
510 if (level == 0) {
511 /* XXX: only supports linux */
512 #if defined(__linux__)
513 *paddr = uc->uc_mcontext.arm_pc;
514 #else
515 return -1;
516 #endif
517 return 0;
518 } else {
519 #if defined(__linux__)
520 fp = uc->uc_mcontext.arm_fp;
521 sp = uc->uc_mcontext.arm_sp;
522 if (sp < 0x1000)
523 sp = 0x1000;
524 #else
525 return -1;
526 #endif
527 /* XXX: specific to tinycc stack frames */
528 if (fp < sp + 12 || fp & 3)
529 return -1;
530 for(i = 1; i < level; i++) {
531 sp = ((uint32_t *)fp)[-2];
532 if (sp < fp || sp - fp > 16 || sp & 3)
533 return -1;
534 fp = ((uint32_t *)fp)[-3];
535 if (fp <= sp || fp - sp < 12 || fp & 3)
536 return -1;
538 /* XXX: check address validity with program info */
539 *paddr = ((uint32_t *)fp)[-1];
540 return 0;
544 /* ------------------------------------------------------------- */
545 #else
547 #warning add arch specific rt_get_caller_pc()
548 static int rt_get_caller_pc(unsigned long *paddr,
549 ucontext_t *uc, int level)
551 return -1;
554 #endif /* !__i386__ */
556 /* ------------------------------------------------------------- */
557 #else /* WIN32 */
559 static long __stdcall cpu_exception_handler(EXCEPTION_POINTERS *ex_info)
561 CONTEXT *uc = ex_info->ContextRecord;
563 EXCEPTION_RECORD *er = ex_info->ExceptionRecord;
564 printf("CPU exception: code=%08lx addr=%p\n",
565 er->ExceptionCode, er->ExceptionAddress);
567 if (rt_bound_error_msg && *rt_bound_error_msg)
568 rt_error(uc, *rt_bound_error_msg);
569 else
570 rt_error(uc, "dereferencing invalid pointer");
571 exit(255);
572 //return EXCEPTION_CONTINUE_SEARCH;
575 /* Generate a stack backtrace when a CPU exception occurs. */
576 static void set_exception_handler(void)
578 SetUnhandledExceptionFilter(cpu_exception_handler);
581 #ifdef _WIN64
582 #define Eip Rip
583 #define Ebp Rbp
584 #endif
586 /* return the PC at frame level 'level'. Return non zero if not found */
587 static int rt_get_caller_pc(uplong *paddr, CONTEXT *uc, int level)
589 uplong fp;
590 int i;
592 if (level == 0) {
593 *paddr = uc->Eip;
594 return 0;
595 } else {
596 fp = uc->Ebp;
597 for(i=1;i<level;i++) {
598 /* XXX: check address validity with program info */
599 if (fp <= 0x1000 || fp >= 0xc0000000)
600 return -1;
601 fp = ((uplong*)fp)[0];
603 *paddr = ((uplong*)fp)[1];
604 return 0;
608 #undef Eip
609 #undef Ebp
611 #endif /* _WIN32 */
612 #endif /* CONFIG_TCC_BACKTRACE */
613 /* ------------------------------------------------------------- */
615 #ifdef CONFIG_TCC_STATIC
617 #define RTLD_LAZY 0x001
618 #define RTLD_NOW 0x002
619 #define RTLD_GLOBAL 0x100
620 #define RTLD_DEFAULT NULL
622 /* dummy function for profiling */
623 void *dlopen(const char *filename, int flag)
625 return NULL;
628 void dlclose(void *p)
632 const char *dlerror(void)
634 return "error";
637 typedef struct TCCSyms {
638 char *str;
639 void *ptr;
640 } TCCSyms;
642 #define TCCSYM(a) { #a, &a, },
644 /* add the symbol you want here if no dynamic linking is done */
645 static TCCSyms tcc_syms[] = {
646 #if !defined(CONFIG_TCCBOOT)
647 TCCSYM(printf)
648 TCCSYM(fprintf)
649 TCCSYM(fopen)
650 TCCSYM(fclose)
651 #endif
652 { NULL, NULL },
655 void *resolve_sym(TCCState *s1, const char *symbol)
657 TCCSyms *p;
658 p = tcc_syms;
659 while (p->str != NULL) {
660 if (!strcmp(p->str, symbol))
661 return p->ptr;
662 p++;
664 return NULL;
667 #elif !defined(_WIN32)
669 void *resolve_sym(TCCState *s1, const char *sym)
671 return dlsym(RTLD_DEFAULT, sym);
674 #endif /* CONFIG_TCC_STATIC */
676 /* ------------------------------------------------------------- */