Patch attempting to build OSX TinyCC.
[tinycc.git] / tccrun.c
blobde0ef89173ea2ac977b50536fe50b58230bf9e8e
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 tcc_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 tcc_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(__APPLE__)
465 *paddr = uc->uc_mcontext->__ss.__eip;
466 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
467 *paddr = uc->uc_mcontext.mc_eip;
468 #elif defined(__dietlibc__)
469 *paddr = uc->uc_mcontext.eip;
470 #else
471 *paddr = uc->uc_mcontext.gregs[REG_EIP];
472 #endif
473 return 0;
474 } else {
475 #if defined(__APPLE__)
476 fp = uc->uc_mcontext->__ss.__ebp;
477 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
478 fp = uc->uc_mcontext.mc_ebp;
479 #elif defined(__dietlibc__)
480 fp = uc->uc_mcontext.ebp;
481 #else
482 fp = uc->uc_mcontext.gregs[REG_EBP];
483 #endif
484 for(i=1;i<level;i++) {
485 /* XXX: check address validity with program info */
486 if (fp <= 0x1000 || fp >= 0xc0000000)
487 return -1;
488 fp = ((unsigned long *)fp)[0];
490 *paddr = ((unsigned long *)fp)[1];
491 return 0;
495 /* ------------------------------------------------------------- */
496 #elif defined(__x86_64__)
498 /* return the PC at frame level 'level'. Return non zero if not found */
499 static int rt_get_caller_pc(unsigned long *paddr,
500 ucontext_t *uc, int level)
502 unsigned long fp;
503 int i;
505 if (level == 0) {
506 /* XXX: only support linux */
507 #if defined(__APPLE__)
508 *paddr = uc->uc_mcontext->__ss.__rip;
509 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
510 *paddr = uc->uc_mcontext.mc_rip;
511 #else
512 *paddr = uc->uc_mcontext.gregs[REG_RIP];
513 #endif
514 return 0;
515 } else {
516 #if defined(__APPLE__)
517 fp = uc->uc_mcontext->__ss.__rbp;
518 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
519 fp = uc->uc_mcontext.mc_rbp;
520 #else
521 fp = uc->uc_mcontext.gregs[REG_RBP];
522 #endif
523 for(i=1;i<level;i++) {
524 /* XXX: check address validity with program info */
525 if (fp <= 0x1000)
526 return -1;
527 fp = ((unsigned long *)fp)[0];
529 *paddr = ((unsigned long *)fp)[1];
530 return 0;
534 /* ------------------------------------------------------------- */
535 #elif defined(__arm__)
537 /* return the PC at frame level 'level'. Return negative if not found */
538 static int rt_get_caller_pc(unsigned long *paddr,
539 ucontext_t *uc, int level)
541 uint32_t fp, sp;
542 int i;
544 if (level == 0) {
545 /* XXX: only supports linux */
546 #if defined(__linux__)
547 *paddr = uc->uc_mcontext.arm_pc;
548 #else
549 return -1;
550 #endif
551 return 0;
552 } else {
553 #if defined(__linux__)
554 fp = uc->uc_mcontext.arm_fp;
555 sp = uc->uc_mcontext.arm_sp;
556 if (sp < 0x1000)
557 sp = 0x1000;
558 #else
559 return -1;
560 #endif
561 /* XXX: specific to tinycc stack frames */
562 if (fp < sp + 12 || fp & 3)
563 return -1;
564 for(i = 1; i < level; i++) {
565 sp = ((uint32_t *)fp)[-2];
566 if (sp < fp || sp - fp > 16 || sp & 3)
567 return -1;
568 fp = ((uint32_t *)fp)[-3];
569 if (fp <= sp || fp - sp < 12 || fp & 3)
570 return -1;
572 /* XXX: check address validity with program info */
573 *paddr = ((uint32_t *)fp)[-1];
574 return 0;
578 /* ------------------------------------------------------------- */
579 #else
581 #warning add arch specific rt_get_caller_pc()
582 static int rt_get_caller_pc(unsigned long *paddr,
583 ucontext_t *uc, int level)
585 return -1;
588 #endif /* !__i386__ */
590 /* ------------------------------------------------------------- */
591 #else /* WIN32 */
593 static long __stdcall cpu_exception_handler(EXCEPTION_POINTERS *ex_info)
595 EXCEPTION_RECORD *er = ex_info->ExceptionRecord;
596 CONTEXT *uc = ex_info->ContextRecord;
597 switch (er->ExceptionCode) {
598 case EXCEPTION_ACCESS_VIOLATION:
599 if (rt_bound_error_msg && *rt_bound_error_msg)
600 rt_error(uc, *rt_bound_error_msg);
601 else
602 rt_error(uc, "access violation");
603 break;
604 case EXCEPTION_STACK_OVERFLOW:
605 rt_error(uc, "stack overflow");
606 break;
607 case EXCEPTION_INT_DIVIDE_BY_ZERO:
608 rt_error(uc, "division by zero");
609 break;
610 default:
611 rt_error(uc, "exception caught");
612 break;
614 exit(-1);
615 return EXCEPTION_CONTINUE_SEARCH;
618 /* Generate a stack backtrace when a CPU exception occurs. */
619 static void set_exception_handler(void)
621 SetUnhandledExceptionFilter(cpu_exception_handler);
624 #ifdef _WIN64
625 static void win64_add_function_table(TCCState *s1)
627 RtlAddFunctionTable(
628 (RUNTIME_FUNCTION*)(uplong)s1->uw_pdata->sh_addr,
629 s1->uw_pdata->data_offset / sizeof (RUNTIME_FUNCTION),
630 (uplong)text_section->sh_addr
633 #endif
635 /* return the PC at frame level 'level'. Return non zero if not found */
636 static int rt_get_caller_pc(uplong *paddr, CONTEXT *uc, int level)
638 uplong fp, pc;
639 int i;
640 #ifdef _WIN64
641 pc = uc->Rip;
642 fp = uc->Rbp;
643 #else
644 pc = uc->Eip;
645 fp = uc->Ebp;
646 #endif
647 if (level > 0) {
648 for(i=1;i<level;i++) {
649 /* XXX: check address validity with program info */
650 if (fp <= 0x1000 || fp >= 0xc0000000)
651 return -1;
652 fp = ((uplong*)fp)[0];
654 pc = ((uplong*)fp)[1];
656 *paddr = pc;
657 return 0;
660 #endif /* _WIN32 */
661 #endif /* CONFIG_TCC_BACKTRACE */
662 /* ------------------------------------------------------------- */
664 #ifdef CONFIG_TCC_STATIC
666 #define RTLD_LAZY 0x001
667 #define RTLD_NOW 0x002
668 #define RTLD_GLOBAL 0x100
669 #define RTLD_DEFAULT NULL
671 /* dummy function for profiling */
672 ST_FUNC void *dlopen(const char *filename, int flag)
674 return NULL;
677 ST_FUNC void dlclose(void *p)
681 const char *dlerror(void)
683 return "error";
686 typedef struct TCCSyms {
687 char *str;
688 void *ptr;
689 } TCCSyms;
691 #define TCCSYM(a) { #a, &a, },
693 /* add the symbol you want here if no dynamic linking is done */
694 static TCCSyms tcc_syms[] = {
695 #if !defined(CONFIG_TCCBOOT)
696 TCCSYM(printf)
697 TCCSYM(fprintf)
698 TCCSYM(fopen)
699 TCCSYM(fclose)
700 #endif
701 { NULL, NULL },
704 ST_FUNC void *resolve_sym(TCCState *s1, const char *symbol)
706 TCCSyms *p;
707 p = tcc_syms;
708 while (p->str != NULL) {
709 if (!strcmp(p->str, symbol))
710 return p->ptr;
711 p++;
713 return NULL;
716 #elif !defined(_WIN32)
718 ST_FUNC void *resolve_sym(TCCState *s1, const char *sym)
720 return dlsym(RTLD_DEFAULT, sym);
723 #endif /* CONFIG_TCC_STATIC */
725 /* ------------------------------------------------------------- */