Fix missing mem_size assignment when using mmap()
[tinycc.git] / tccrun.c
blob97f4761bb4ca6299b31398229d08f123a10dc3da
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. */
63 s1->mem_size = ret;
65 s1->write_mem = mmap (NULL, ret, PROT_READ|PROT_WRITE,
66 MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
67 if (s1->write_mem == MAP_FAILED)
68 tcc_error("mmap not writeable");
70 s1->runtime_mem = mmap (NULL, ret, PROT_READ|PROT_EXEC,
71 MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
72 if (s1->runtime_mem == MAP_FAILED)
73 tcc_error("mmap not executable");
75 ret = tcc_relocate_ex(s1, s1->write_mem);
77 #else
78 s1->runtime_mem = tcc_malloc(ret);
79 ret = tcc_relocate_ex(s1, s1->runtime_mem);
80 #endif
81 return ret;
84 /* launch the compiled program with the given arguments */
85 LIBTCCAPI int tcc_run(TCCState *s1, int argc, char **argv)
87 int (*prog_main)(int, char **);
88 int ret;
90 if (tcc_relocate(s1, TCC_RELOCATE_AUTO) < 0)
91 return -1;
93 prog_main = tcc_get_symbol_err(s1, s1->runtime_main);
95 #ifdef CONFIG_TCC_BACKTRACE
96 if (s1->do_debug) {
97 set_exception_handler();
98 rt_prog_main = prog_main;
100 #endif
102 #ifdef CONFIG_TCC_BCHECK
103 if (s1->do_bounds_check) {
104 void (*bound_init)(void);
105 void (*bound_exit)(void);
106 /* set error function */
107 rt_bound_error_msg = tcc_get_symbol_err(s1, "__bound_error_msg");
108 /* XXX: use .init section so that it also work in binary ? */
109 bound_init = tcc_get_symbol_err(s1, "__bound_init");
110 bound_exit = tcc_get_symbol_err(s1, "__bound_exit");
111 bound_init();
112 ret = (*prog_main)(argc, argv);
113 bound_exit();
114 } else
115 #endif
116 ret = (*prog_main)(argc, argv);
117 return ret;
120 /* relocate code. Return -1 on error, required size if ptr is NULL,
121 otherwise copy code into buffer passed by the caller */
122 static int tcc_relocate_ex(TCCState *s1, void *ptr)
124 Section *s;
125 unsigned long offset, length;
126 addr_t mem;
127 int i;
129 if (NULL == ptr) {
130 s1->nb_errors = 0;
131 #ifdef TCC_TARGET_PE
132 pe_output_file(s1, NULL);
133 #else
134 tcc_add_runtime(s1);
135 relocate_common_syms();
136 tcc_add_linker_symbols(s1);
137 build_got_entries(s1);
138 #endif
139 if (s1->nb_errors)
140 return -1;
143 offset = 0, mem = (addr_t)ptr;
144 for(i = 1; i < s1->nb_sections; i++) {
145 s = s1->sections[i];
146 if (0 == (s->sh_flags & SHF_ALLOC))
147 continue;
148 length = s->data_offset;
149 s->sh_addr = mem ? (mem + offset + 15) & ~15 : 0;
150 offset = (offset + length + 15) & ~15;
152 offset += 16;
154 /* relocate symbols */
155 relocate_syms(s1, 1);
156 if (s1->nb_errors)
157 return -1;
159 #ifdef TCC_HAS_RUNTIME_PLTGOT
160 s1->runtime_plt_and_got_offset = 0;
161 s1->runtime_plt_and_got = (char *)(mem + offset);
162 /* double the size of the buffer for got and plt entries
163 XXX: calculate exact size for them? */
164 offset *= 2;
165 #endif
167 if (0 == mem)
168 return offset;
170 /* relocate each section */
171 for(i = 1; i < s1->nb_sections; i++) {
172 s = s1->sections[i];
173 if (s->reloc)
174 relocate_section(s1, s);
177 for(i = 1; i < s1->nb_sections; i++) {
178 s = s1->sections[i];
179 if (0 == (s->sh_flags & SHF_ALLOC))
180 continue;
181 length = s->data_offset;
182 // printf("%-12s %08x %04x\n", s->name, s->sh_addr, length);
183 ptr = (void*)s->sh_addr;
184 if (NULL == s->data || s->sh_type == SHT_NOBITS)
185 memset(ptr, 0, length);
186 else
187 memcpy(ptr, s->data, length);
188 /* mark executable sections as executable in memory */
189 if (s->sh_flags & SHF_EXECINSTR)
190 set_pages_executable(ptr, length);
193 #ifdef TCC_HAS_RUNTIME_PLTGOT
194 set_pages_executable(s1->runtime_plt_and_got,
195 s1->runtime_plt_and_got_offset);
196 #endif
198 #ifdef _WIN64
199 win64_add_function_table(s1);
200 #endif
201 return 0;
204 /* ------------------------------------------------------------- */
205 /* allow to run code in memory */
207 static void set_pages_executable(void *ptr, unsigned long length)
209 #ifdef _WIN32
210 unsigned long old_protect;
211 VirtualProtect(ptr, length, PAGE_EXECUTE_READWRITE, &old_protect);
212 #else
213 #ifndef PAGESIZE
214 # define PAGESIZE 4096
215 #endif
216 addr_t start, end;
217 start = (addr_t)ptr & ~(PAGESIZE - 1);
218 end = (addr_t)ptr + length;
219 end = (end + PAGESIZE - 1) & ~(PAGESIZE - 1);
220 mprotect((void *)start, end - start, PROT_READ | PROT_WRITE | PROT_EXEC);
221 __clear_cache(ptr, ptr + length);
222 #endif
225 /* ------------------------------------------------------------- */
226 #ifdef CONFIG_TCC_BACKTRACE
228 ST_FUNC void tcc_set_num_callers(int n)
230 rt_num_callers = n;
233 /* print the position in the source file of PC value 'pc' by reading
234 the stabs debug information */
235 static addr_t rt_printline(addr_t wanted_pc, const char *msg)
237 char func_name[128], last_func_name[128];
238 addr_t func_addr, last_pc, pc;
239 const char *incl_files[INCLUDE_STACK_SIZE];
240 int incl_index, len, last_line_num, i;
241 const char *str, *p;
243 Stab_Sym *stab_sym = NULL, *stab_sym_end, *sym;
244 int stab_len = 0;
245 char *stab_str = NULL;
247 if (stab_section) {
248 stab_len = stab_section->data_offset;
249 stab_sym = (Stab_Sym *)stab_section->data;
250 stab_str = stabstr_section->data;
253 func_name[0] = '\0';
254 func_addr = 0;
255 incl_index = 0;
256 last_func_name[0] = '\0';
257 last_pc = (addr_t)-1;
258 last_line_num = 1;
260 if (!stab_sym)
261 goto no_stabs;
263 stab_sym_end = (Stab_Sym*)((char*)stab_sym + stab_len);
264 for (sym = stab_sym + 1; sym < stab_sym_end; ++sym) {
265 switch(sym->n_type) {
266 /* function start or end */
267 case N_FUN:
268 if (sym->n_strx == 0) {
269 /* we test if between last line and end of function */
270 pc = sym->n_value + func_addr;
271 if (wanted_pc >= last_pc && wanted_pc < pc)
272 goto found;
273 func_name[0] = '\0';
274 func_addr = 0;
275 } else {
276 str = stab_str + sym->n_strx;
277 p = strchr(str, ':');
278 if (!p) {
279 pstrcpy(func_name, sizeof(func_name), str);
280 } else {
281 len = p - str;
282 if (len > sizeof(func_name) - 1)
283 len = sizeof(func_name) - 1;
284 memcpy(func_name, str, len);
285 func_name[len] = '\0';
287 func_addr = sym->n_value;
289 break;
290 /* line number info */
291 case N_SLINE:
292 pc = sym->n_value + func_addr;
293 if (wanted_pc >= last_pc && wanted_pc < pc)
294 goto found;
295 last_pc = pc;
296 last_line_num = sym->n_desc;
297 /* XXX: slow! */
298 strcpy(last_func_name, func_name);
299 break;
300 /* include files */
301 case N_BINCL:
302 str = stab_str + sym->n_strx;
303 add_incl:
304 if (incl_index < INCLUDE_STACK_SIZE) {
305 incl_files[incl_index++] = str;
307 break;
308 case N_EINCL:
309 if (incl_index > 1)
310 incl_index--;
311 break;
312 case N_SO:
313 if (sym->n_strx == 0) {
314 incl_index = 0; /* end of translation unit */
315 } else {
316 str = stab_str + sym->n_strx;
317 /* do not add path */
318 len = strlen(str);
319 if (len > 0 && str[len - 1] != '/')
320 goto add_incl;
322 break;
326 no_stabs:
327 /* second pass: we try symtab symbols (no line number info) */
328 incl_index = 0;
329 if (symtab_section)
331 ElfW(Sym) *sym, *sym_end;
332 int type;
334 sym_end = (ElfW(Sym) *)(symtab_section->data + symtab_section->data_offset);
335 for(sym = (ElfW(Sym) *)symtab_section->data + 1;
336 sym < sym_end;
337 sym++) {
338 type = ELFW(ST_TYPE)(sym->st_info);
339 if (type == STT_FUNC || type == STT_GNU_IFUNC) {
340 if (wanted_pc >= sym->st_value &&
341 wanted_pc < sym->st_value + sym->st_size) {
342 pstrcpy(last_func_name, sizeof(last_func_name),
343 strtab_section->data + sym->st_name);
344 func_addr = sym->st_value;
345 goto found;
350 /* did not find any info: */
351 fprintf(stderr, "%s %p ???\n", msg, (void*)wanted_pc);
352 fflush(stderr);
353 return 0;
354 found:
355 i = incl_index;
356 if (i > 0)
357 fprintf(stderr, "%s:%d: ", incl_files[--i], last_line_num);
358 fprintf(stderr, "%s %p", msg, (void*)wanted_pc);
359 if (last_func_name[0] != '\0')
360 fprintf(stderr, " %s()", last_func_name);
361 if (--i >= 0) {
362 fprintf(stderr, " (included from ");
363 for (;;) {
364 fprintf(stderr, "%s", incl_files[i]);
365 if (--i < 0)
366 break;
367 fprintf(stderr, ", ");
369 fprintf(stderr, ")");
371 fprintf(stderr, "\n");
372 fflush(stderr);
373 return func_addr;
376 /* emit a run time error at position 'pc' */
377 static void rt_error(ucontext_t *uc, const char *fmt, ...)
379 va_list ap;
380 addr_t pc;
381 int i;
383 fprintf(stderr, "Runtime error: ");
384 va_start(ap, fmt);
385 vfprintf(stderr, fmt, ap);
386 va_end(ap);
387 fprintf(stderr, "\n");
389 for(i=0;i<rt_num_callers;i++) {
390 if (rt_get_caller_pc(&pc, uc, i) < 0)
391 break;
392 pc = rt_printline(pc, i ? "by" : "at");
393 if (pc == (addr_t)rt_prog_main && pc)
394 break;
398 /* ------------------------------------------------------------- */
399 #ifndef _WIN32
401 /* signal handler for fatal errors */
402 static void sig_error(int signum, siginfo_t *siginf, void *puc)
404 ucontext_t *uc = puc;
406 switch(signum) {
407 case SIGFPE:
408 switch(siginf->si_code) {
409 case FPE_INTDIV:
410 case FPE_FLTDIV:
411 rt_error(uc, "division by zero");
412 break;
413 default:
414 rt_error(uc, "floating point exception");
415 break;
417 break;
418 case SIGBUS:
419 case SIGSEGV:
420 if (rt_bound_error_msg && *rt_bound_error_msg)
421 rt_error(uc, *rt_bound_error_msg);
422 else
423 rt_error(uc, "dereferencing invalid pointer");
424 break;
425 case SIGILL:
426 rt_error(uc, "illegal instruction");
427 break;
428 case SIGABRT:
429 rt_error(uc, "abort() called");
430 break;
431 default:
432 rt_error(uc, "caught signal %d", signum);
433 break;
435 exit(255);
438 #ifndef SA_SIGINFO
439 # define SA_SIGINFO 0x00000004u
440 #endif
442 /* Generate a stack backtrace when a CPU exception occurs. */
443 static void set_exception_handler(void)
445 struct sigaction sigact;
446 /* install TCC signal handlers to print debug info on fatal
447 runtime errors */
448 sigact.sa_flags = SA_SIGINFO | SA_RESETHAND;
449 sigact.sa_sigaction = sig_error;
450 sigemptyset(&sigact.sa_mask);
451 sigaction(SIGFPE, &sigact, NULL);
452 sigaction(SIGILL, &sigact, NULL);
453 sigaction(SIGSEGV, &sigact, NULL);
454 sigaction(SIGBUS, &sigact, NULL);
455 sigaction(SIGABRT, &sigact, NULL);
458 /* ------------------------------------------------------------- */
459 #ifdef __i386__
461 /* fix for glibc 2.1 */
462 #ifndef REG_EIP
463 #define REG_EIP EIP
464 #define REG_EBP EBP
465 #endif
467 /* return the PC at frame level 'level'. Return negative if not found */
468 static int rt_get_caller_pc(addr_t *paddr, ucontext_t *uc, int level)
470 addr_t fp;
471 int i;
473 if (level == 0) {
474 #if defined(__APPLE__)
475 *paddr = uc->uc_mcontext->__ss.__eip;
476 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
477 *paddr = uc->uc_mcontext.mc_eip;
478 #elif defined(__dietlibc__)
479 *paddr = uc->uc_mcontext.eip;
480 #else
481 *paddr = uc->uc_mcontext.gregs[REG_EIP];
482 #endif
483 return 0;
484 } else {
485 #if defined(__APPLE__)
486 fp = uc->uc_mcontext->__ss.__ebp;
487 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
488 fp = uc->uc_mcontext.mc_ebp;
489 #elif defined(__dietlibc__)
490 fp = uc->uc_mcontext.ebp;
491 #else
492 fp = uc->uc_mcontext.gregs[REG_EBP];
493 #endif
494 for(i=1;i<level;i++) {
495 /* XXX: check address validity with program info */
496 if (fp <= 0x1000 || fp >= 0xc0000000)
497 return -1;
498 fp = ((addr_t *)fp)[0];
500 *paddr = ((addr_t *)fp)[1];
501 return 0;
505 /* ------------------------------------------------------------- */
506 #elif defined(__x86_64__)
508 /* return the PC at frame level 'level'. Return negative if not found */
509 static int rt_get_caller_pc(addr_t *paddr, ucontext_t *uc, int level)
511 addr_t fp;
512 int i;
514 if (level == 0) {
515 /* XXX: only support linux */
516 #if defined(__APPLE__)
517 *paddr = uc->uc_mcontext->__ss.__rip;
518 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
519 *paddr = uc->uc_mcontext.mc_rip;
520 #else
521 *paddr = uc->uc_mcontext.gregs[REG_RIP];
522 #endif
523 return 0;
524 } else {
525 #if defined(__APPLE__)
526 fp = uc->uc_mcontext->__ss.__rbp;
527 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
528 fp = uc->uc_mcontext.mc_rbp;
529 #else
530 fp = uc->uc_mcontext.gregs[REG_RBP];
531 #endif
532 for(i=1;i<level;i++) {
533 /* XXX: check address validity with program info */
534 if (fp <= 0x1000)
535 return -1;
536 fp = ((addr_t *)fp)[0];
538 *paddr = ((addr_t *)fp)[1];
539 return 0;
543 /* ------------------------------------------------------------- */
544 #elif defined(__arm__)
546 /* return the PC at frame level 'level'. Return negative if not found */
547 static int rt_get_caller_pc(addr_t *paddr, ucontext_t *uc, int level)
549 addr_t fp, sp;
550 int i;
552 if (level == 0) {
553 /* XXX: only supports linux */
554 #if defined(__linux__)
555 *paddr = uc->uc_mcontext.arm_pc;
556 #else
557 return -1;
558 #endif
559 return 0;
560 } else {
561 #if defined(__linux__)
562 fp = uc->uc_mcontext.arm_fp;
563 sp = uc->uc_mcontext.arm_sp;
564 if (sp < 0x1000)
565 sp = 0x1000;
566 #else
567 return -1;
568 #endif
569 /* XXX: specific to tinycc stack frames */
570 if (fp < sp + 12 || fp & 3)
571 return -1;
572 for(i = 1; i < level; i++) {
573 sp = ((addr_t *)fp)[-2];
574 if (sp < fp || sp - fp > 16 || sp & 3)
575 return -1;
576 fp = ((addr_t *)fp)[-3];
577 if (fp <= sp || fp - sp < 12 || fp & 3)
578 return -1;
580 /* XXX: check address validity with program info */
581 *paddr = ((addr_t *)fp)[-1];
582 return 0;
586 /* ------------------------------------------------------------- */
587 #else
589 #warning add arch specific rt_get_caller_pc()
590 static int rt_get_caller_pc(addr_t *paddr, ucontext_t *uc, int level)
592 return -1;
595 #endif /* !__i386__ */
597 /* ------------------------------------------------------------- */
598 #else /* WIN32 */
600 static long __stdcall cpu_exception_handler(EXCEPTION_POINTERS *ex_info)
602 EXCEPTION_RECORD *er = ex_info->ExceptionRecord;
603 CONTEXT *uc = ex_info->ContextRecord;
604 switch (er->ExceptionCode) {
605 case EXCEPTION_ACCESS_VIOLATION:
606 if (rt_bound_error_msg && *rt_bound_error_msg)
607 rt_error(uc, *rt_bound_error_msg);
608 else
609 rt_error(uc, "access violation");
610 break;
611 case EXCEPTION_STACK_OVERFLOW:
612 rt_error(uc, "stack overflow");
613 break;
614 case EXCEPTION_INT_DIVIDE_BY_ZERO:
615 rt_error(uc, "division by zero");
616 break;
617 default:
618 rt_error(uc, "exception caught");
619 break;
621 return EXCEPTION_EXECUTE_HANDLER;
624 /* Generate a stack backtrace when a CPU exception occurs. */
625 static void set_exception_handler(void)
627 SetUnhandledExceptionFilter(cpu_exception_handler);
630 #ifdef _WIN64
631 static void win64_add_function_table(TCCState *s1)
633 RtlAddFunctionTable(
634 (RUNTIME_FUNCTION*)s1->uw_pdata->sh_addr,
635 s1->uw_pdata->data_offset / sizeof (RUNTIME_FUNCTION),
636 text_section->sh_addr
639 #endif
641 /* return the PC at frame level 'level'. Return non zero if not found */
642 static int rt_get_caller_pc(addr_t *paddr, CONTEXT *uc, int level)
644 addr_t fp, pc;
645 int i;
646 #ifdef _WIN64
647 pc = uc->Rip;
648 fp = uc->Rbp;
649 #else
650 pc = uc->Eip;
651 fp = uc->Ebp;
652 #endif
653 if (level > 0) {
654 for(i=1;i<level;i++) {
655 /* XXX: check address validity with program info */
656 if (fp <= 0x1000 || fp >= 0xc0000000)
657 return -1;
658 fp = ((addr_t*)fp)[0];
660 pc = ((addr_t*)fp)[1];
662 *paddr = pc;
663 return 0;
666 #endif /* _WIN32 */
667 #endif /* CONFIG_TCC_BACKTRACE */
668 /* ------------------------------------------------------------- */
669 #ifdef CONFIG_TCC_STATIC
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 ST_FUNC const char *dlerror(void)
683 return "error";
686 typedef struct TCCSyms {
687 char *str;
688 void *ptr;
689 } TCCSyms;
692 /* add the symbol you want here if no dynamic linking is done */
693 static TCCSyms tcc_syms[] = {
694 #if !defined(CONFIG_TCCBOOT)
695 #define TCCSYM(a) { #a, &a, },
696 TCCSYM(printf)
697 TCCSYM(fprintf)
698 TCCSYM(fopen)
699 TCCSYM(fclose)
700 #undef TCCSYM
701 #endif
702 { NULL, NULL },
705 ST_FUNC void *resolve_sym(TCCState *s1, const char *symbol)
707 TCCSyms *p;
708 p = tcc_syms;
709 while (p->str != NULL) {
710 if (!strcmp(p->str, symbol))
711 return p->ptr;
712 p++;
714 return NULL;
717 #elif !defined(_WIN32)
719 ST_FUNC void *resolve_sym(TCCState *s1, const char *sym)
721 return dlsym(RTLD_DEFAULT, sym);
724 #endif /* CONFIG_TCC_STATIC */
725 #endif /* TCC_IS_NATIVE */
726 /* ------------------------------------------------------------- */