Relicensing TinyCC
[tinycc.git] / tccrun.c
1 /*
2  *  TCC - Tiny C Compiler - Support for -run switch
3  *
4  *  Copyright (c) 2001-2004 Fabrice Bellard
5  *
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.
10  *
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.
15  *
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
19  */
20
21 #include "tcc.h"
22
23 /* only native compiler supports -run */
24 #ifdef TCC_IS_NATIVE
25
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
31
32 #ifdef _WIN32
33 #define ucontext_t CONTEXT
34 #endif
35
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);
41
42 #ifdef _WIN64
43 static void win64_add_function_table(TCCState *s1);
44 #endif
45
46 /* ------------------------------------------------------------- */
47 /* Do all relocations (needed before using tcc_get_symbol())
48    Returns -1 on error. */
49
50 LIBTCCAPI int tcc_relocate(TCCState *s1, void *ptr)
51 {
52     int ret;
53
54     if (TCC_RELOCATE_AUTO != ptr)
55         return tcc_relocate_ex(s1, ptr);
56
57     ret = tcc_relocate_ex(s1, NULL);
58     if (ret < 0)
59         return ret;
60
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 */
64
65         char tmpfname[] = "/tmp/.tccrunXXXXXX";
66         int fd = mkstemp (tmpfname);
67
68         s1->mem_size = ret;
69         unlink (tmpfname);
70         ftruncate (fd, s1->mem_size);
71
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");
76
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");
81
82         ret = tcc_relocate_ex(s1, s1->write_mem);
83     }
84 #else
85     s1->runtime_mem = tcc_malloc(ret);
86     ret = tcc_relocate_ex(s1, s1->runtime_mem);
87 #endif
88     return ret;
89 }
90
91 /* launch the compiled program with the given arguments */
92 LIBTCCAPI int tcc_run(TCCState *s1, int argc, char **argv)
93 {
94     int (*prog_main)(int, char **);
95     int ret;
96
97     if (tcc_relocate(s1, TCC_RELOCATE_AUTO) < 0)
98         return -1;
99
100     prog_main = tcc_get_symbol_err(s1, "main");
101
102 #ifdef CONFIG_TCC_BACKTRACE
103     if (s1->do_debug) {
104         set_exception_handler();
105         rt_prog_main = prog_main;
106     }
107 #endif
108
109 #ifdef CONFIG_TCC_BCHECK
110     if (s1->do_bounds_check) {
111         void (*bound_init)(void);
112         void (*bound_exit)(void);
113         /* set error function */
114         rt_bound_error_msg = tcc_get_symbol_err(s1, "__bound_error_msg");
115         /* XXX: use .init section so that it also work in binary ? */
116         bound_init = tcc_get_symbol_err(s1, "__bound_init");
117         bound_exit = tcc_get_symbol_err(s1, "__bound_exit");
118         bound_init();
119         ret = (*prog_main)(argc, argv);
120         bound_exit();
121     } else
122 #endif
123         ret = (*prog_main)(argc, argv);
124     return ret;
125 }
126
127 /* relocate code. Return -1 on error, required size if ptr is NULL,
128    otherwise copy code into buffer passed by the caller */
129 static int tcc_relocate_ex(TCCState *s1, void *ptr)
130 {
131     Section *s;
132     unsigned long offset, length;
133     addr_t mem;
134     int i;
135
136     if (NULL == ptr) {
137         s1->nb_errors = 0;
138 #ifdef TCC_TARGET_PE
139         pe_output_file(s1, NULL);
140 #else
141         tcc_add_runtime(s1);
142         relocate_common_syms();
143         tcc_add_linker_symbols(s1);
144         build_got_entries(s1);
145 #endif
146         if (s1->nb_errors)
147             return -1;
148     }
149
150     offset = 0, mem = (addr_t)ptr;
151     for(i = 1; i < s1->nb_sections; i++) {
152         s = s1->sections[i];
153         if (0 == (s->sh_flags & SHF_ALLOC))
154             continue;
155         length = s->data_offset;
156         s->sh_addr = mem ? (mem + offset + 15) & ~15 : 0;
157         offset = (offset + length + 15) & ~15;
158     }
159     offset += 16;
160
161     /* relocate symbols */
162     relocate_syms(s1, 1);
163     if (s1->nb_errors)
164         return -1;
165
166 #ifdef TCC_HAS_RUNTIME_PLTGOT
167     s1->runtime_plt_and_got_offset = 0;
168     s1->runtime_plt_and_got = (char *)(mem + offset);
169     /* double the size of the buffer for got and plt entries
170        XXX: calculate exact size for them? */
171     offset *= 2;
172 #endif
173
174     if (0 == mem)
175         return offset;
176
177     /* relocate each section */
178     for(i = 1; i < s1->nb_sections; i++) {
179         s = s1->sections[i];
180         if (s->reloc)
181             relocate_section(s1, s);
182     }
183
184     for(i = 1; i < s1->nb_sections; i++) {
185         s = s1->sections[i];
186         if (0 == (s->sh_flags & SHF_ALLOC))
187             continue;
188         length = s->data_offset;
189         // printf("%-12s %08x %04x\n", s->name, s->sh_addr, length);
190         ptr = (void*)s->sh_addr;
191         if (NULL == s->data || s->sh_type == SHT_NOBITS)
192             memset(ptr, 0, length);
193         else
194             memcpy(ptr, s->data, length);
195         /* mark executable sections as executable in memory */
196         if (s->sh_flags & SHF_EXECINSTR)
197             set_pages_executable(ptr, length);
198     }
199
200 #ifdef TCC_HAS_RUNTIME_PLTGOT
201     set_pages_executable(s1->runtime_plt_and_got,
202                          s1->runtime_plt_and_got_offset);
203 #endif
204
205 #ifdef _WIN64
206     win64_add_function_table(s1);
207 #endif
208     return 0;
209 }
210
211 /* ------------------------------------------------------------- */
212 /* allow to run code in memory */
213
214 static void set_pages_executable(void *ptr, unsigned long length)
215 {
216 #ifdef _WIN32
217     unsigned long old_protect;
218     VirtualProtect(ptr, length, PAGE_EXECUTE_READWRITE, &old_protect);
219 #else
220 #ifndef PAGESIZE
221 # define PAGESIZE 4096
222 #endif
223     addr_t start, end;
224     start = (addr_t)ptr & ~(PAGESIZE - 1);
225     end = (addr_t)ptr + length;
226     end = (end + PAGESIZE - 1) & ~(PAGESIZE - 1);
227     mprotect((void *)start, end - start, PROT_READ | PROT_WRITE | PROT_EXEC);
228     __clear_cache(ptr, ptr + length);
229 #endif
230 }
231
232 /* ------------------------------------------------------------- */
233 #ifdef CONFIG_TCC_BACKTRACE
234
235 ST_FUNC void tcc_set_num_callers(int n)
236 {
237     rt_num_callers = n;
238 }
239
240 /* print the position in the source file of PC value 'pc' by reading
241    the stabs debug information */
242 static addr_t rt_printline(addr_t wanted_pc, const char *msg)
243 {
244     char func_name[128], last_func_name[128];
245     addr_t func_addr, last_pc, pc;
246     const char *incl_files[INCLUDE_STACK_SIZE];
247     int incl_index, len, last_line_num, i;
248     const char *str, *p;
249
250     Stab_Sym *stab_sym = NULL, *stab_sym_end, *sym;
251     int stab_len = 0;
252     char *stab_str = NULL;
253
254     if (stab_section) {
255         stab_len = stab_section->data_offset;
256         stab_sym = (Stab_Sym *)stab_section->data;
257         stab_str = stabstr_section->data;
258     }
259
260     func_name[0] = '\0';
261     func_addr = 0;
262     incl_index = 0;
263     last_func_name[0] = '\0';
264     last_pc = (addr_t)-1;
265     last_line_num = 1;
266
267     if (!stab_sym)
268         goto no_stabs;
269
270     stab_sym_end = (Stab_Sym*)((char*)stab_sym + stab_len);
271     for (sym = stab_sym + 1; sym < stab_sym_end; ++sym) {
272         switch(sym->n_type) {
273             /* function start or end */
274         case N_FUN:
275             if (sym->n_strx == 0) {
276                 /* we test if between last line and end of function */
277                 pc = sym->n_value + func_addr;
278                 if (wanted_pc >= last_pc && wanted_pc < pc)
279                     goto found;
280                 func_name[0] = '\0';
281                 func_addr = 0;
282             } else {
283                 str = stab_str + sym->n_strx;
284                 p = strchr(str, ':');
285                 if (!p) {
286                     pstrcpy(func_name, sizeof(func_name), str);
287                 } else {
288                     len = p - str;
289                     if (len > sizeof(func_name) - 1)
290                         len = sizeof(func_name) - 1;
291                     memcpy(func_name, str, len);
292                     func_name[len] = '\0';
293                 }
294                 func_addr = sym->n_value;
295             }
296             break;
297             /* line number info */
298         case N_SLINE:
299             pc = sym->n_value + func_addr;
300             if (wanted_pc >= last_pc && wanted_pc < pc)
301                 goto found;
302             last_pc = pc;
303             last_line_num = sym->n_desc;
304             /* XXX: slow! */
305             strcpy(last_func_name, func_name);
306             break;
307             /* include files */
308         case N_BINCL:
309             str = stab_str + sym->n_strx;
310         add_incl:
311             if (incl_index < INCLUDE_STACK_SIZE) {
312                 incl_files[incl_index++] = str;
313             }
314             break;
315         case N_EINCL:
316             if (incl_index > 1)
317                 incl_index--;
318             break;
319         case N_SO:
320             if (sym->n_strx == 0) {
321                 incl_index = 0; /* end of translation unit */
322             } else {
323                 str = stab_str + sym->n_strx;
324                 /* do not add path */
325                 len = strlen(str);
326                 if (len > 0 && str[len - 1] != '/')
327                     goto add_incl;
328             }
329             break;
330         }
331     }
332
333 no_stabs:
334     /* second pass: we try symtab symbols (no line number info) */
335     incl_index = 0;
336     if (symtab_section)
337     {
338         ElfW(Sym) *sym, *sym_end;
339         int type;
340
341         sym_end = (ElfW(Sym) *)(symtab_section->data + symtab_section->data_offset);
342         for(sym = (ElfW(Sym) *)symtab_section->data + 1;
343             sym < sym_end;
344             sym++) {
345             type = ELFW(ST_TYPE)(sym->st_info);
346             if (type == STT_FUNC || type == STT_GNU_IFUNC) {
347                 if (wanted_pc >= sym->st_value &&
348                     wanted_pc < sym->st_value + sym->st_size) {
349                     pstrcpy(last_func_name, sizeof(last_func_name),
350                             strtab_section->data + sym->st_name);
351                     func_addr = sym->st_value;
352                     goto found;
353                 }
354             }
355         }
356     }
357     /* did not find any info: */
358     fprintf(stderr, "%s %p ???\n", msg, (void*)wanted_pc);
359     fflush(stderr);
360     return 0;
361  found:
362     i = incl_index;
363     if (i > 0)
364         fprintf(stderr, "%s:%d: ", incl_files[--i], last_line_num);
365     fprintf(stderr, "%s %p", msg, (void*)wanted_pc);
366     if (last_func_name[0] != '\0')
367         fprintf(stderr, " %s()", last_func_name);
368     if (--i >= 0) {
369         fprintf(stderr, " (included from ");
370         for (;;) {
371             fprintf(stderr, "%s", incl_files[i]);
372             if (--i < 0)
373                 break;
374             fprintf(stderr, ", ");
375         }
376         fprintf(stderr, ")");
377     }
378     fprintf(stderr, "\n");
379     fflush(stderr);
380     return func_addr;
381 }
382
383 /* emit a run time error at position 'pc' */
384 static void rt_error(ucontext_t *uc, const char *fmt, ...)
385 {
386     va_list ap;
387     addr_t pc;
388     int i;
389
390     fprintf(stderr, "Runtime error: ");
391     va_start(ap, fmt);
392     vfprintf(stderr, fmt, ap);
393     va_end(ap);
394     fprintf(stderr, "\n");
395
396     for(i=0;i<rt_num_callers;i++) {
397         if (rt_get_caller_pc(&pc, uc, i) < 0)
398             break;
399         pc = rt_printline(pc, i ? "by" : "at");
400         if (pc == (addr_t)rt_prog_main && pc)
401             break;
402     }
403 }
404
405 /* ------------------------------------------------------------- */
406 #ifndef _WIN32
407
408 /* signal handler for fatal errors */
409 static void sig_error(int signum, siginfo_t *siginf, void *puc)
410 {
411     ucontext_t *uc = puc;
412
413     switch(signum) {
414     case SIGFPE:
415         switch(siginf->si_code) {
416         case FPE_INTDIV:
417         case FPE_FLTDIV:
418             rt_error(uc, "division by zero");
419             break;
420         default:
421             rt_error(uc, "floating point exception");
422             break;
423         }
424         break;
425     case SIGBUS:
426     case SIGSEGV:
427         if (rt_bound_error_msg && *rt_bound_error_msg)
428             rt_error(uc, *rt_bound_error_msg);
429         else
430             rt_error(uc, "dereferencing invalid pointer");
431         break;
432     case SIGILL:
433         rt_error(uc, "illegal instruction");
434         break;
435     case SIGABRT:
436         rt_error(uc, "abort() called");
437         break;
438     default:
439         rt_error(uc, "caught signal %d", signum);
440         break;
441     }
442     exit(255);
443 }
444
445 #ifndef SA_SIGINFO
446 # define SA_SIGINFO 0x00000004u
447 #endif
448
449 /* Generate a stack backtrace when a CPU exception occurs. */
450 static void set_exception_handler(void)
451 {
452     struct sigaction sigact;
453     /* install TCC signal handlers to print debug info on fatal
454        runtime errors */
455     sigact.sa_flags = SA_SIGINFO | SA_RESETHAND;
456     sigact.sa_sigaction = sig_error;
457     sigemptyset(&sigact.sa_mask);
458     sigaction(SIGFPE, &sigact, NULL);
459     sigaction(SIGILL, &sigact, NULL);
460     sigaction(SIGSEGV, &sigact, NULL);
461     sigaction(SIGBUS, &sigact, NULL);
462     sigaction(SIGABRT, &sigact, NULL);
463 }
464
465 /* ------------------------------------------------------------- */
466 #ifdef __i386__
467
468 /* fix for glibc 2.1 */
469 #ifndef REG_EIP
470 #define REG_EIP EIP
471 #define REG_EBP EBP
472 #endif
473
474 /* return the PC at frame level 'level'. Return negative if not found */
475 static int rt_get_caller_pc(addr_t *paddr, ucontext_t *uc, int level)
476 {
477     addr_t fp;
478     int i;
479
480     if (level == 0) {
481 #if defined(__APPLE__)
482         *paddr = uc->uc_mcontext->__ss.__eip;
483 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
484         *paddr = uc->uc_mcontext.mc_eip;
485 #elif defined(__dietlibc__)
486         *paddr = uc->uc_mcontext.eip;
487 #else
488         *paddr = uc->uc_mcontext.gregs[REG_EIP];
489 #endif
490         return 0;
491     } else {
492 #if defined(__APPLE__)
493         fp = uc->uc_mcontext->__ss.__ebp;
494 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
495         fp = uc->uc_mcontext.mc_ebp;
496 #elif defined(__dietlibc__)
497         fp = uc->uc_mcontext.ebp;
498 #else
499         fp = uc->uc_mcontext.gregs[REG_EBP];
500 #endif
501         for(i=1;i<level;i++) {
502             /* XXX: check address validity with program info */
503             if (fp <= 0x1000 || fp >= 0xc0000000)
504                 return -1;
505             fp = ((addr_t *)fp)[0];
506         }
507         *paddr = ((addr_t *)fp)[1];
508         return 0;
509     }
510 }
511
512 /* ------------------------------------------------------------- */
513 #elif defined(__x86_64__)
514
515 /* return the PC at frame level 'level'. Return negative if not found */
516 static int rt_get_caller_pc(addr_t *paddr, ucontext_t *uc, int level)
517 {
518     addr_t fp;
519     int i;
520
521     if (level == 0) {
522         /* XXX: only support linux */
523 #if defined(__APPLE__)
524         *paddr = uc->uc_mcontext->__ss.__rip;
525 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) 
526         *paddr = uc->uc_mcontext.mc_rip;
527 #else
528         *paddr = uc->uc_mcontext.gregs[REG_RIP];
529 #endif
530         return 0;
531     } else {
532 #if defined(__APPLE__)
533         fp = uc->uc_mcontext->__ss.__rbp;
534 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
535         fp = uc->uc_mcontext.mc_rbp;
536 #else
537         fp = uc->uc_mcontext.gregs[REG_RBP];
538 #endif
539         for(i=1;i<level;i++) {
540             /* XXX: check address validity with program info */
541             if (fp <= 0x1000)
542                 return -1;
543             fp = ((addr_t *)fp)[0];
544         }
545         *paddr = ((addr_t *)fp)[1];
546         return 0;
547     }
548 }
549
550 /* ------------------------------------------------------------- */
551 #elif defined(__arm__)
552
553 /* return the PC at frame level 'level'. Return negative if not found */
554 static int rt_get_caller_pc(addr_t *paddr, ucontext_t *uc, int level)
555 {
556     addr_t fp, sp;
557     int i;
558
559     if (level == 0) {
560         /* XXX: only supports linux */
561 #if defined(__linux__)
562         *paddr = uc->uc_mcontext.arm_pc;
563 #else
564         return -1;
565 #endif
566         return 0;
567     } else {
568 #if defined(__linux__)
569         fp = uc->uc_mcontext.arm_fp;
570         sp = uc->uc_mcontext.arm_sp;
571         if (sp < 0x1000)
572             sp = 0x1000;
573 #else
574         return -1;
575 #endif
576         /* XXX: specific to tinycc stack frames */
577         if (fp < sp + 12 || fp & 3)
578             return -1;
579         for(i = 1; i < level; i++) {
580             sp = ((addr_t *)fp)[-2];
581             if (sp < fp || sp - fp > 16 || sp & 3)
582                 return -1;
583             fp = ((addr_t *)fp)[-3];
584             if (fp <= sp || fp - sp < 12 || fp & 3)
585                 return -1;
586         }
587         /* XXX: check address validity with program info */
588         *paddr = ((addr_t *)fp)[-1];
589         return 0;
590     }
591 }
592
593 /* ------------------------------------------------------------- */
594 #else
595
596 #warning add arch specific rt_get_caller_pc()
597 static int rt_get_caller_pc(addr_t *paddr, ucontext_t *uc, int level)
598 {
599     return -1;
600 }
601
602 #endif /* !__i386__ */
603
604 /* ------------------------------------------------------------- */
605 #else /* WIN32 */
606
607 static long __stdcall cpu_exception_handler(EXCEPTION_POINTERS *ex_info)
608 {
609     EXCEPTION_RECORD *er = ex_info->ExceptionRecord;
610     CONTEXT *uc = ex_info->ContextRecord;
611     switch (er->ExceptionCode) {
612     case EXCEPTION_ACCESS_VIOLATION:
613         if (rt_bound_error_msg && *rt_bound_error_msg)
614             rt_error(uc, *rt_bound_error_msg);
615         else
616             rt_error(uc, "access violation");
617         break;
618     case EXCEPTION_STACK_OVERFLOW:
619         rt_error(uc, "stack overflow");
620         break;
621     case EXCEPTION_INT_DIVIDE_BY_ZERO:
622         rt_error(uc, "division by zero");
623         break;
624     default:
625         rt_error(uc, "exception caught");
626         break;
627     }
628     return EXCEPTION_EXECUTE_HANDLER;
629 }
630
631 /* Generate a stack backtrace when a CPU exception occurs. */
632 static void set_exception_handler(void)
633 {
634     SetUnhandledExceptionFilter(cpu_exception_handler);
635 }
636
637 #ifdef _WIN64
638 static void win64_add_function_table(TCCState *s1)
639 {
640     RtlAddFunctionTable(
641         (RUNTIME_FUNCTION*)s1->uw_pdata->sh_addr,
642         s1->uw_pdata->data_offset / sizeof (RUNTIME_FUNCTION),
643         text_section->sh_addr
644         );
645 }
646 #endif
647
648 /* return the PC at frame level 'level'. Return non zero if not found */
649 static int rt_get_caller_pc(addr_t *paddr, CONTEXT *uc, int level)
650 {
651     addr_t fp, pc;
652     int i;
653 #ifdef _WIN64
654     pc = uc->Rip;
655     fp = uc->Rbp;
656 #else
657     pc = uc->Eip;
658     fp = uc->Ebp;
659 #endif
660     if (level > 0) {
661         for(i=1;i<level;i++) {
662             /* XXX: check address validity with program info */
663             if (fp <= 0x1000 || fp >= 0xc0000000)
664                 return -1;
665             fp = ((addr_t*)fp)[0];
666         }
667         pc = ((addr_t*)fp)[1];
668     }
669     *paddr = pc;
670     return 0;
671 }
672
673 #endif /* _WIN32 */
674 #endif /* CONFIG_TCC_BACKTRACE */
675 /* ------------------------------------------------------------- */
676 #ifdef CONFIG_TCC_STATIC
677
678 /* dummy function for profiling */
679 ST_FUNC void *dlopen(const char *filename, int flag)
680 {
681     return NULL;
682 }
683
684 ST_FUNC void dlclose(void *p)
685 {
686 }
687
688 ST_FUNC const char *dlerror(void)
689 {
690     return "error";
691 }
692
693 typedef struct TCCSyms {
694     char *str;
695     void *ptr;
696 } TCCSyms;
697
698
699 /* add the symbol you want here if no dynamic linking is done */
700 static TCCSyms tcc_syms[] = {
701 #if !defined(CONFIG_TCCBOOT)
702 #define TCCSYM(a) { #a, &a, },
703     TCCSYM(printf)
704     TCCSYM(fprintf)
705     TCCSYM(fopen)
706     TCCSYM(fclose)
707 #undef TCCSYM
708 #endif
709     { NULL, NULL },
710 };
711
712 ST_FUNC void *resolve_sym(TCCState *s1, const char *symbol)
713 {
714     TCCSyms *p;
715     p = tcc_syms;
716     while (p->str != NULL) {
717         if (!strcmp(p->str, symbol))
718             return p->ptr;
719         p++;
720     }
721     return NULL;
722 }
723
724 #elif !defined(_WIN32)
725
726 ST_FUNC void *resolve_sym(TCCState *s1, const char *sym)
727 {
728     return dlsym(RTLD_DEFAULT, sym);
729 }
730
731 #endif /* CONFIG_TCC_STATIC */
732 #endif /* TCC_IS_NATIVE */
733 /* ------------------------------------------------------------- */