win64: try to fix linkage
[tinycc.git] / tccrun.c
blob13c20120d2e68d38a3f13089d66dcca8e8100c0f
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 ret = tcc_relocate_ex(s1, NULL);
58 if (ret < 0)
59 return ret;
61 #ifdef HAVE_SELINUX
62 { /* Use mmap instead of malloc for Selinux. Ref:
63 http://www.gnu.org/s/libc/manual/html_node/File-Size.html */
65 char tmpfname[] = "/tmp/.tccrunXXXXXX";
66 int fd = mkstemp (tmpfname);
68 s1->mem_size = ret;
69 unlink (tmpfname);
70 ftruncate (fd, s1->mem_size);
72 s1->write_mem = mmap (NULL, ret, PROT_READ|PROT_WRITE,
73 MAP_SHARED, fd, 0);
74 if (s1->write_mem == MAP_FAILED)
75 tcc_error("/tmp not writeable");
77 s1->runtime_mem = mmap (NULL, ret, PROT_READ|PROT_EXEC,
78 MAP_SHARED, fd, 0);
79 if (s1->runtime_mem == MAP_FAILED)
80 tcc_error("/tmp not executable");
82 ret = tcc_relocate_ex(s1, s1->write_mem);
84 #else
85 s1->runtime_mem = tcc_malloc(ret);
86 ret = tcc_relocate_ex(s1, s1->runtime_mem);
87 #endif
88 return ret;
91 /* launch the compiled program with the given arguments */
92 LIBTCCAPI int tcc_run(TCCState *s1, int argc, char **argv)
94 int (*prog_main)(int, char **);
95 int ret;
97 if (tcc_relocate(s1, TCC_RELOCATE_AUTO) < 0)
98 return -1;
100 prog_main = tcc_get_symbol_err(s1, s1->runtime_main);
102 #ifdef CONFIG_TCC_BACKTRACE
103 if (s1->do_debug) {
104 set_exception_handler();
105 rt_prog_main = prog_main;
107 #endif
109 #ifdef CONFIG_TCC_BCHECK
110 if (s1->do_bounds_check) {
111 void (*bound_init)(void);
112 void (*bound_exit)(void);
113 void (*bound_new_region)(void *p, unsigned long size);
114 int (*bound_delete_region)(void *p);
115 int i;
117 /* set error function */
118 rt_bound_error_msg = tcc_get_symbol_err(s1, "__bound_error_msg");
119 /* XXX: use .init section so that it also work in binary ? */
120 bound_init = tcc_get_symbol_err(s1, "__bound_init");
121 bound_exit = tcc_get_symbol_err(s1, "__bound_exit");
122 bound_new_region = tcc_get_symbol_err(s1, "__bound_new_region");
123 bound_delete_region = tcc_get_symbol_err(s1, "__bound_delete_region");
124 bound_init();
125 /* mark argv area as valid */
126 bound_new_region(argv, argc*sizeof(argv[0]));
127 for (i=0; i<argc; ++i)
128 bound_new_region(argv[i], strlen(argv[i]));
130 ret = (*prog_main)(argc, argv);
132 /* unmark argv area */
133 for (i=0; i<argc; ++i)
134 bound_delete_region(argv[i]);
135 bound_delete_region(argv);
137 bound_exit();
138 } else
139 #endif
140 ret = (*prog_main)(argc, argv);
141 return ret;
144 /* relocate code. Return -1 on error, required size if ptr is NULL,
145 otherwise copy code into buffer passed by the caller */
146 static int tcc_relocate_ex(TCCState *s1, void *ptr)
148 Section *s;
149 unsigned long offset, length;
150 addr_t mem;
151 int i;
153 if (NULL == ptr) {
154 s1->nb_errors = 0;
155 #ifdef TCC_TARGET_PE
156 pe_output_file(s1, NULL);
157 #else
158 tcc_add_runtime(s1);
159 relocate_common_syms();
160 tcc_add_linker_symbols(s1);
161 build_got_entries(s1);
162 #endif
163 if (s1->nb_errors)
164 return -1;
167 offset = 0, mem = (addr_t)ptr;
168 for(i = 1; i < s1->nb_sections; i++) {
169 s = s1->sections[i];
170 if (0 == (s->sh_flags & SHF_ALLOC))
171 continue;
172 length = s->data_offset;
173 s->sh_addr = mem ? (mem + offset + 15) & ~15 : 0;
174 offset = (offset + length + 15) & ~15;
176 offset += 16;
178 /* relocate symbols */
179 relocate_syms(s1, 1);
180 if (s1->nb_errors)
181 return -1;
183 if (0 == mem)
184 return offset;
186 /* relocate each section */
187 for(i = 1; i < s1->nb_sections; i++) {
188 s = s1->sections[i];
189 if (s->reloc)
190 relocate_section(s1, s);
192 relocate_plt(s1);
194 for(i = 1; i < s1->nb_sections; i++) {
195 s = s1->sections[i];
196 if (0 == (s->sh_flags & SHF_ALLOC))
197 continue;
198 length = s->data_offset;
199 // printf("%-12s %08x %04x\n", s->name, s->sh_addr, length);
200 ptr = (void*)s->sh_addr;
201 if (NULL == s->data || s->sh_type == SHT_NOBITS)
202 memset(ptr, 0, length);
203 else
204 memcpy(ptr, s->data, length);
205 /* mark executable sections as executable in memory */
206 if (s->sh_flags & SHF_EXECINSTR)
207 set_pages_executable(ptr, length);
210 #ifdef _WIN64
211 win64_add_function_table(s1);
212 #endif
213 return 0;
216 /* ------------------------------------------------------------- */
217 /* allow to run code in memory */
219 static void set_pages_executable(void *ptr, unsigned long length)
221 #ifdef _WIN32
222 unsigned long old_protect;
223 VirtualProtect(ptr, length, PAGE_EXECUTE_READWRITE, &old_protect);
224 #else
225 extern void __clear_cache(char *beginning, char *end);
226 #ifndef PAGESIZE
227 # define PAGESIZE 4096
228 #endif
229 addr_t start, end;
230 start = (addr_t)ptr & ~(PAGESIZE - 1);
231 end = (addr_t)ptr + length;
232 end = (end + PAGESIZE - 1) & ~(PAGESIZE - 1);
233 mprotect((void *)start, end - start, PROT_READ | PROT_WRITE | PROT_EXEC);
234 __clear_cache(ptr, ptr + length);
235 #endif
238 /* ------------------------------------------------------------- */
239 #ifdef CONFIG_TCC_BACKTRACE
241 ST_FUNC void tcc_set_num_callers(int n)
243 rt_num_callers = n;
246 /* print the position in the source file of PC value 'pc' by reading
247 the stabs debug information */
248 static addr_t rt_printline(addr_t wanted_pc, const char *msg)
250 char func_name[128], last_func_name[128];
251 addr_t func_addr, last_pc, pc;
252 const char *incl_files[INCLUDE_STACK_SIZE];
253 int incl_index, len, last_line_num, i;
254 const char *str, *p;
256 Stab_Sym *stab_sym = NULL, *stab_sym_end, *sym;
257 int stab_len = 0;
258 char *stab_str = NULL;
260 if (stab_section) {
261 stab_len = stab_section->data_offset;
262 stab_sym = (Stab_Sym *)stab_section->data;
263 stab_str = (char *) stabstr_section->data;
266 func_name[0] = '\0';
267 func_addr = 0;
268 incl_index = 0;
269 last_func_name[0] = '\0';
270 last_pc = (addr_t)-1;
271 last_line_num = 1;
273 if (!stab_sym)
274 goto no_stabs;
276 stab_sym_end = (Stab_Sym*)((char*)stab_sym + stab_len);
277 for (sym = stab_sym + 1; sym < stab_sym_end; ++sym) {
278 switch(sym->n_type) {
279 /* function start or end */
280 case N_FUN:
281 if (sym->n_strx == 0) {
282 /* we test if between last line and end of function */
283 pc = sym->n_value + func_addr;
284 if (wanted_pc >= last_pc && wanted_pc < pc)
285 goto found;
286 func_name[0] = '\0';
287 func_addr = 0;
288 } else {
289 str = stab_str + sym->n_strx;
290 p = strchr(str, ':');
291 if (!p) {
292 pstrcpy(func_name, sizeof(func_name), str);
293 } else {
294 len = p - str;
295 if (len > sizeof(func_name) - 1)
296 len = sizeof(func_name) - 1;
297 memcpy(func_name, str, len);
298 func_name[len] = '\0';
300 func_addr = sym->n_value;
302 break;
303 /* line number info */
304 case N_SLINE:
305 pc = sym->n_value + func_addr;
306 if (wanted_pc >= last_pc && wanted_pc < pc)
307 goto found;
308 last_pc = pc;
309 last_line_num = sym->n_desc;
310 /* XXX: slow! */
311 strcpy(last_func_name, func_name);
312 break;
313 /* include files */
314 case N_BINCL:
315 str = stab_str + sym->n_strx;
316 add_incl:
317 if (incl_index < INCLUDE_STACK_SIZE) {
318 incl_files[incl_index++] = str;
320 break;
321 case N_EINCL:
322 if (incl_index > 1)
323 incl_index--;
324 break;
325 case N_SO:
326 if (sym->n_strx == 0) {
327 incl_index = 0; /* end of translation unit */
328 } else {
329 str = stab_str + sym->n_strx;
330 /* do not add path */
331 len = strlen(str);
332 if (len > 0 && str[len - 1] != '/')
333 goto add_incl;
335 break;
339 no_stabs:
340 /* second pass: we try symtab symbols (no line number info) */
341 incl_index = 0;
342 if (symtab_section)
344 ElfW(Sym) *sym, *sym_end;
345 int type;
347 sym_end = (ElfW(Sym) *)(symtab_section->data + symtab_section->data_offset);
348 for(sym = (ElfW(Sym) *)symtab_section->data + 1;
349 sym < sym_end;
350 sym++) {
351 type = ELFW(ST_TYPE)(sym->st_info);
352 if (type == STT_FUNC || type == STT_GNU_IFUNC) {
353 if (wanted_pc >= sym->st_value &&
354 wanted_pc < sym->st_value + sym->st_size) {
355 pstrcpy(last_func_name, sizeof(last_func_name),
356 (char *) strtab_section->data + sym->st_name);
357 func_addr = sym->st_value;
358 goto found;
363 /* did not find any info: */
364 fprintf(stderr, "%s %p ???\n", msg, (void*)wanted_pc);
365 fflush(stderr);
366 return 0;
367 found:
368 i = incl_index;
369 if (i > 0)
370 fprintf(stderr, "%s:%d: ", incl_files[--i], last_line_num);
371 fprintf(stderr, "%s %p", msg, (void*)wanted_pc);
372 if (last_func_name[0] != '\0')
373 fprintf(stderr, " %s()", last_func_name);
374 if (--i >= 0) {
375 fprintf(stderr, " (included from ");
376 for (;;) {
377 fprintf(stderr, "%s", incl_files[i]);
378 if (--i < 0)
379 break;
380 fprintf(stderr, ", ");
382 fprintf(stderr, ")");
384 fprintf(stderr, "\n");
385 fflush(stderr);
386 return func_addr;
389 /* emit a run time error at position 'pc' */
390 static void rt_error(ucontext_t *uc, const char *fmt, ...)
392 va_list ap;
393 addr_t pc;
394 int i;
396 fprintf(stderr, "Runtime error: ");
397 va_start(ap, fmt);
398 vfprintf(stderr, fmt, ap);
399 va_end(ap);
400 fprintf(stderr, "\n");
402 for(i=0;i<rt_num_callers;i++) {
403 if (rt_get_caller_pc(&pc, uc, i) < 0)
404 break;
405 pc = rt_printline(pc, i ? "by" : "at");
406 if (pc == (addr_t)rt_prog_main && pc)
407 break;
411 /* ------------------------------------------------------------- */
412 #ifndef _WIN32
414 /* signal handler for fatal errors */
415 static void sig_error(int signum, siginfo_t *siginf, void *puc)
417 ucontext_t *uc = puc;
419 switch(signum) {
420 case SIGFPE:
421 switch(siginf->si_code) {
422 case FPE_INTDIV:
423 case FPE_FLTDIV:
424 rt_error(uc, "division by zero");
425 break;
426 default:
427 rt_error(uc, "floating point exception");
428 break;
430 break;
431 case SIGBUS:
432 case SIGSEGV:
433 if (rt_bound_error_msg && *rt_bound_error_msg)
434 rt_error(uc, *rt_bound_error_msg);
435 else
436 rt_error(uc, "dereferencing invalid pointer");
437 break;
438 case SIGILL:
439 rt_error(uc, "illegal instruction");
440 break;
441 case SIGABRT:
442 rt_error(uc, "abort() called");
443 break;
444 default:
445 rt_error(uc, "caught signal %d", signum);
446 break;
448 exit(255);
451 #ifndef SA_SIGINFO
452 # define SA_SIGINFO 0x00000004u
453 #endif
455 /* Generate a stack backtrace when a CPU exception occurs. */
456 static void set_exception_handler(void)
458 struct sigaction sigact;
459 /* install TCC signal handlers to print debug info on fatal
460 runtime errors */
461 sigact.sa_flags = SA_SIGINFO | SA_RESETHAND;
462 sigact.sa_sigaction = sig_error;
463 sigemptyset(&sigact.sa_mask);
464 sigaction(SIGFPE, &sigact, NULL);
465 sigaction(SIGILL, &sigact, NULL);
466 sigaction(SIGSEGV, &sigact, NULL);
467 sigaction(SIGBUS, &sigact, NULL);
468 sigaction(SIGABRT, &sigact, NULL);
471 /* ------------------------------------------------------------- */
472 #ifdef __i386__
474 /* fix for glibc 2.1 */
475 #ifndef REG_EIP
476 #define REG_EIP EIP
477 #define REG_EBP EBP
478 #endif
480 /* return the PC at frame level 'level'. Return negative if not found */
481 static int rt_get_caller_pc(addr_t *paddr, ucontext_t *uc, int level)
483 addr_t fp;
484 int i;
486 if (level == 0) {
487 #if defined(__APPLE__)
488 *paddr = uc->uc_mcontext->__ss.__eip;
489 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
490 *paddr = uc->uc_mcontext.mc_eip;
491 #elif defined(__dietlibc__)
492 *paddr = uc->uc_mcontext.eip;
493 #elif defined(__NetBSD__)
494 *paddr = uc->uc_mcontext.__gregs[_REG_EIP];
495 #else
496 *paddr = uc->uc_mcontext.gregs[REG_EIP];
497 #endif
498 return 0;
499 } else {
500 #if defined(__APPLE__)
501 fp = uc->uc_mcontext->__ss.__ebp;
502 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
503 fp = uc->uc_mcontext.mc_ebp;
504 #elif defined(__dietlibc__)
505 fp = uc->uc_mcontext.ebp;
506 #elif defined(__NetBSD__)
507 fp = uc->uc_mcontext.__gregs[_REG_EBP];
508 #else
509 fp = uc->uc_mcontext.gregs[REG_EBP];
510 #endif
511 for(i=1;i<level;i++) {
512 /* XXX: check address validity with program info */
513 if (fp <= 0x1000 || fp >= 0xc0000000)
514 return -1;
515 fp = ((addr_t *)fp)[0];
517 *paddr = ((addr_t *)fp)[1];
518 return 0;
522 /* ------------------------------------------------------------- */
523 #elif defined(__x86_64__)
525 /* return the PC at frame level 'level'. Return negative if not found */
526 static int rt_get_caller_pc(addr_t *paddr, ucontext_t *uc, int level)
528 addr_t fp;
529 int i;
531 if (level == 0) {
532 /* XXX: only support linux */
533 #if defined(__APPLE__)
534 *paddr = uc->uc_mcontext->__ss.__rip;
535 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
536 *paddr = uc->uc_mcontext.mc_rip;
537 #elif defined(__NetBSD__)
538 *paddr = uc->uc_mcontext.__gregs[_REG_RIP];
539 #else
540 *paddr = uc->uc_mcontext.gregs[REG_RIP];
541 #endif
542 return 0;
543 } else {
544 #if defined(__APPLE__)
545 fp = uc->uc_mcontext->__ss.__rbp;
546 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
547 fp = uc->uc_mcontext.mc_rbp;
548 #elif defined(__NetBSD__)
549 fp = uc->uc_mcontext.__gregs[_REG_RBP];
550 #else
551 fp = uc->uc_mcontext.gregs[REG_RBP];
552 #endif
553 for(i=1;i<level;i++) {
554 /* XXX: check address validity with program info */
555 if (fp <= 0x1000)
556 return -1;
557 fp = ((addr_t *)fp)[0];
559 *paddr = ((addr_t *)fp)[1];
560 return 0;
564 /* ------------------------------------------------------------- */
565 #elif defined(__arm__)
567 /* return the PC at frame level 'level'. Return negative if not found */
568 static int rt_get_caller_pc(addr_t *paddr, ucontext_t *uc, int level)
570 addr_t fp, sp;
571 int i;
573 if (level == 0) {
574 /* XXX: only supports linux */
575 #if defined(__linux__)
576 *paddr = uc->uc_mcontext.arm_pc;
577 #else
578 return -1;
579 #endif
580 return 0;
581 } else {
582 #if defined(__linux__)
583 fp = uc->uc_mcontext.arm_fp;
584 sp = uc->uc_mcontext.arm_sp;
585 if (sp < 0x1000)
586 sp = 0x1000;
587 #else
588 return -1;
589 #endif
590 /* XXX: specific to tinycc stack frames */
591 if (fp < sp + 12 || fp & 3)
592 return -1;
593 for(i = 1; i < level; i++) {
594 sp = ((addr_t *)fp)[-2];
595 if (sp < fp || sp - fp > 16 || sp & 3)
596 return -1;
597 fp = ((addr_t *)fp)[-3];
598 if (fp <= sp || fp - sp < 12 || fp & 3)
599 return -1;
601 /* XXX: check address validity with program info */
602 *paddr = ((addr_t *)fp)[-1];
603 return 0;
607 /* ------------------------------------------------------------- */
608 #else
610 #warning add arch specific rt_get_caller_pc()
611 static int rt_get_caller_pc(addr_t *paddr, ucontext_t *uc, int level)
613 return -1;
616 #endif /* !__i386__ */
618 /* ------------------------------------------------------------- */
619 #else /* WIN32 */
621 static long __stdcall cpu_exception_handler(EXCEPTION_POINTERS *ex_info)
623 EXCEPTION_RECORD *er = ex_info->ExceptionRecord;
624 CONTEXT *uc = ex_info->ContextRecord;
625 switch (er->ExceptionCode) {
626 case EXCEPTION_ACCESS_VIOLATION:
627 if (rt_bound_error_msg && *rt_bound_error_msg)
628 rt_error(uc, *rt_bound_error_msg);
629 else
630 rt_error(uc, "access violation");
631 break;
632 case EXCEPTION_STACK_OVERFLOW:
633 rt_error(uc, "stack overflow");
634 break;
635 case EXCEPTION_INT_DIVIDE_BY_ZERO:
636 rt_error(uc, "division by zero");
637 break;
638 default:
639 rt_error(uc, "exception caught");
640 break;
642 return EXCEPTION_EXECUTE_HANDLER;
645 /* Generate a stack backtrace when a CPU exception occurs. */
646 static void set_exception_handler(void)
648 SetUnhandledExceptionFilter(cpu_exception_handler);
651 #ifdef _WIN64
652 static void win64_add_function_table(TCCState *s1)
654 RtlAddFunctionTable(
655 (RUNTIME_FUNCTION*)s1->uw_pdata->sh_addr,
656 s1->uw_pdata->data_offset / sizeof (RUNTIME_FUNCTION),
657 text_section->sh_addr
660 #endif
662 /* return the PC at frame level 'level'. Return non zero if not found */
663 static int rt_get_caller_pc(addr_t *paddr, CONTEXT *uc, int level)
665 addr_t fp, pc;
666 int i;
667 #ifdef _WIN64
668 pc = uc->Rip;
669 fp = uc->Rbp;
670 #else
671 pc = uc->Eip;
672 fp = uc->Ebp;
673 #endif
674 if (level > 0) {
675 for(i=1;i<level;i++) {
676 /* XXX: check address validity with program info */
677 if (fp <= 0x1000 || fp >= 0xc0000000)
678 return -1;
679 fp = ((addr_t*)fp)[0];
681 pc = ((addr_t*)fp)[1];
683 *paddr = pc;
684 return 0;
687 #endif /* _WIN32 */
688 #endif /* CONFIG_TCC_BACKTRACE */
689 /* ------------------------------------------------------------- */
690 #ifdef CONFIG_TCC_STATIC
692 /* dummy function for profiling */
693 ST_FUNC void *dlopen(const char *filename, int flag)
695 return NULL;
698 ST_FUNC void dlclose(void *p)
702 ST_FUNC const char *dlerror(void)
704 return "error";
707 typedef struct TCCSyms {
708 char *str;
709 void *ptr;
710 } TCCSyms;
713 /* add the symbol you want here if no dynamic linking is done */
714 static TCCSyms tcc_syms[] = {
715 #if !defined(CONFIG_TCCBOOT)
716 #define TCCSYM(a) { #a, &a, },
717 TCCSYM(printf)
718 TCCSYM(fprintf)
719 TCCSYM(fopen)
720 TCCSYM(fclose)
721 #undef TCCSYM
722 #endif
723 { NULL, NULL },
726 ST_FUNC void *resolve_sym(TCCState *s1, const char *symbol)
728 TCCSyms *p;
729 p = tcc_syms;
730 while (p->str != NULL) {
731 if (!strcmp(p->str, symbol))
732 return p->ptr;
733 p++;
735 return NULL;
738 #elif !defined(_WIN32)
740 ST_FUNC void *resolve_sym(TCCState *s1, const char *sym)
742 return dlsym(RTLD_DEFAULT, sym);
745 #endif /* CONFIG_TCC_STATIC */
746 #endif /* TCC_IS_NATIVE */
747 /* ------------------------------------------------------------- */