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
23 /* only native compiler supports -run */
27 # include <sys/mman.h>
30 #ifdef CONFIG_TCC_BACKTRACE
34 # include <sys/ucontext.h>
37 # define ucontext_t CONTEXT
39 ST_DATA
int rt_num_callers
= 6;
40 ST_DATA
const char **rt_bound_error_msg
;
41 ST_DATA
void *rt_prog_main
;
42 static int rt_get_caller_pc(addr_t
*paddr
, ucontext_t
*uc
, int level
);
43 static void rt_error(ucontext_t
*uc
, const char *fmt
, ...);
44 static void set_exception_handler(void);
47 static void set_pages_executable(void *ptr
, unsigned long length
);
48 static int tcc_relocate_ex(TCCState
*s1
, void *ptr
);
51 static void *win64_add_function_table(TCCState
*s1
);
52 static void win64_del_function_table(void *);
55 // #define HAVE_SELINUX
57 /* ------------------------------------------------------------- */
58 /* Do all relocations (needed before using tcc_get_symbol())
59 Returns -1 on error. */
61 LIBTCCAPI
int tcc_relocate(TCCState
*s1
, void *ptr
)
65 if (TCC_RELOCATE_AUTO
!= ptr
)
66 return tcc_relocate_ex(s1
, ptr
);
68 size
= tcc_relocate_ex(s1
, NULL
);
73 { /* Use mmap instead of malloc for Selinux. Ref:
74 http://www.gnu.org/s/libc/manual/html_node/File-Size.html */
76 char tmpfname
[] = "/tmp/.tccrunXXXXXX";
77 int fd
= mkstemp (tmpfname
);
83 wr_mem
= mmap (NULL
, size
, PROT_READ
|PROT_WRITE
,
85 if (wr_mem
== MAP_FAILED
)
86 tcc_error("/tmp not writeable");
87 mem
= mmap (NULL
, size
, PROT_READ
|PROT_EXEC
,
89 if (mem
== MAP_FAILED
)
90 tcc_error("/tmp not executable");
92 tcc_relocate_ex(s1
, wr_mem
);
93 dynarray_add(&s1
->runtime_mem
, &s1
->nb_runtime_mem
, (void*)(addr_t
)size
);
94 dynarray_add(&s1
->runtime_mem
, &s1
->nb_runtime_mem
, wr_mem
);
95 dynarray_add(&s1
->runtime_mem
, &s1
->nb_runtime_mem
, mem
);
98 mem
= tcc_malloc(size
);
99 tcc_relocate_ex(s1
, mem
); /* no more errors expected */
100 dynarray_add(&s1
->runtime_mem
, &s1
->nb_runtime_mem
, mem
);
105 ST_FUNC
void tcc_run_free(TCCState
*s1
)
109 for (i
= 0; i
< s1
->nb_runtime_mem
; ++i
) {
111 int size
= (int)(addr_t
)s1
->runtime_mem
[i
];
112 munmap(s1
->runtime_mem
[++i
], size
);
113 munmap(s1
->runtime_mem
[++i
], size
);
116 win64_del_function_table(*(void**)s1
->runtime_mem
[i
]);
118 tcc_free(s1
->runtime_mem
[i
]);
121 tcc_free(s1
->runtime_mem
);
124 /* launch the compiled program with the given arguments */
125 LIBTCCAPI
int tcc_run(TCCState
*s1
, int argc
, char **argv
)
127 int (*prog_main
)(int, char **);
129 if (tcc_relocate(s1
, TCC_RELOCATE_AUTO
) < 0)
131 prog_main
= tcc_get_symbol_err(s1
, s1
->runtime_main
);
133 #ifdef CONFIG_TCC_BACKTRACE
135 set_exception_handler();
136 rt_prog_main
= prog_main
;
140 errno
= 0; /* clean errno value */
142 #ifdef CONFIG_TCC_BCHECK
143 if (s1
->do_bounds_check
) {
144 void (*bound_init
)(void);
145 void (*bound_exit
)(void);
146 void (*bound_new_region
)(void *p
, addr_t size
);
147 int (*bound_delete_region
)(void *p
);
150 /* set error function */
151 rt_bound_error_msg
= tcc_get_symbol_err(s1
, "__bound_error_msg");
152 /* XXX: use .init section so that it also work in binary ? */
153 bound_init
= tcc_get_symbol_err(s1
, "__bound_init");
154 bound_exit
= tcc_get_symbol_err(s1
, "__bound_exit");
155 bound_new_region
= tcc_get_symbol_err(s1
, "__bound_new_region");
156 bound_delete_region
= tcc_get_symbol_err(s1
, "__bound_delete_region");
159 /* mark argv area as valid */
160 bound_new_region(argv
, argc
*sizeof(argv
[0]));
161 for (i
=0; i
<argc
; ++i
)
162 bound_new_region(argv
[i
], strlen(argv
[i
]) + 1);
164 ret
= (*prog_main
)(argc
, argv
);
166 /* unmark argv area */
167 for (i
=0; i
<argc
; ++i
)
168 bound_delete_region(argv
[i
]);
169 bound_delete_region(argv
);
174 return (*prog_main
)(argc
, argv
);
177 /* relocate code. Return -1 on error, required size if ptr is NULL,
178 otherwise copy code into buffer passed by the caller */
179 static int tcc_relocate_ex(TCCState
*s1
, void *ptr
)
182 unsigned long offset
, length
;
189 pe_output_file(s1
, NULL
);
192 relocate_common_syms();
193 tcc_add_linker_symbols(s1
);
194 build_got_entries(s1
);
200 offset
= 0, mem
= (addr_t
)ptr
;
202 offset
+= sizeof (void*);
204 for(i
= 1; i
< s1
->nb_sections
; i
++) {
206 if (0 == (s
->sh_flags
& SHF_ALLOC
))
208 offset
= (offset
+ 15) & ~15;
209 s
->sh_addr
= mem
? mem
+ offset
: 0;
210 offset
+= s
->data_offset
;
213 /* relocate symbols */
214 relocate_syms(s1
, s1
->symtab
, 1);
221 /* relocate each section */
222 for(i
= 1; i
< s1
->nb_sections
; i
++) {
225 relocate_section(s1
, s
);
230 *(void**)ptr
= win64_add_function_table(s1
);
233 for(i
= 1; i
< s1
->nb_sections
; i
++) {
235 if (0 == (s
->sh_flags
& SHF_ALLOC
))
237 length
= s
->data_offset
;
238 // printf("%-12s %08lx %04x\n", s->name, s->sh_addr, length);
239 ptr
= (void*)s
->sh_addr
;
240 if (NULL
== s
->data
|| s
->sh_type
== SHT_NOBITS
)
241 memset(ptr
, 0, length
);
243 memcpy(ptr
, s
->data
, length
);
244 /* mark executable sections as executable in memory */
245 if (s
->sh_flags
& SHF_EXECINSTR
)
246 set_pages_executable(ptr
, length
);
251 /* ------------------------------------------------------------- */
252 /* allow to run code in memory */
254 static void set_pages_executable(void *ptr
, unsigned long length
)
257 unsigned long old_protect
;
258 VirtualProtect(ptr
, length
, PAGE_EXECUTE_READWRITE
, &old_protect
);
261 # define PAGESIZE 4096
264 start
= (addr_t
)ptr
& ~(PAGESIZE
- 1);
265 end
= (addr_t
)ptr
+ length
;
266 end
= (end
+ PAGESIZE
- 1) & ~(PAGESIZE
- 1);
267 if (mprotect((void *)start
, end
- start
, PROT_READ
| PROT_WRITE
| PROT_EXEC
))
268 tcc_error("mprotect failed: did you mean to configure --with-selinux?");
269 #if defined TCC_TARGET_ARM || defined TCC_TARGET_ARM64
270 { extern void __clear_cache(void *beginning
, void *end
);
271 __clear_cache(ptr
, (char *)ptr
+ length
); }
277 static void *win64_add_function_table(TCCState
*s1
)
281 p
= (void*)s1
->uw_pdata
->sh_addr
;
283 (RUNTIME_FUNCTION
*)p
,
284 s1
->uw_pdata
->data_offset
/ sizeof (RUNTIME_FUNCTION
),
285 text_section
->sh_addr
292 static void win64_del_function_table(void *p
)
295 RtlDeleteFunctionTable((RUNTIME_FUNCTION
*)p
);
300 /* ------------------------------------------------------------- */
301 #ifdef CONFIG_TCC_BACKTRACE
303 ST_FUNC
void tcc_set_num_callers(int n
)
308 /* print the position in the source file of PC value 'pc' by reading
309 the stabs debug information */
310 static addr_t
rt_printline(addr_t wanted_pc
, const char *msg
)
312 char func_name
[128], last_func_name
[128];
313 addr_t func_addr
, last_pc
, pc
;
314 const char *incl_files
[INCLUDE_STACK_SIZE
];
315 int incl_index
, len
, last_line_num
, i
;
318 Stab_Sym
*stab_sym
= NULL
, *stab_sym_end
, *sym
;
320 char *stab_str
= NULL
;
323 stab_len
= stab_section
->data_offset
;
324 stab_sym
= (Stab_Sym
*)stab_section
->data
;
325 stab_str
= (char *) stabstr_section
->data
;
331 last_func_name
[0] = '\0';
332 last_pc
= (addr_t
)-1;
338 stab_sym_end
= (Stab_Sym
*)((char*)stab_sym
+ stab_len
);
339 for (sym
= stab_sym
+ 1; sym
< stab_sym_end
; ++sym
) {
340 switch(sym
->n_type
) {
341 /* function start or end */
343 if (sym
->n_strx
== 0) {
344 /* we test if between last line and end of function */
345 pc
= sym
->n_value
+ func_addr
;
346 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
351 str
= stab_str
+ sym
->n_strx
;
352 p
= strchr(str
, ':');
354 pstrcpy(func_name
, sizeof(func_name
), str
);
357 if (len
> sizeof(func_name
) - 1)
358 len
= sizeof(func_name
) - 1;
359 memcpy(func_name
, str
, len
);
360 func_name
[len
] = '\0';
362 func_addr
= sym
->n_value
;
365 /* line number info */
367 pc
= sym
->n_value
+ func_addr
;
368 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
371 last_line_num
= sym
->n_desc
;
373 strcpy(last_func_name
, func_name
);
377 str
= stab_str
+ sym
->n_strx
;
379 if (incl_index
< INCLUDE_STACK_SIZE
) {
380 incl_files
[incl_index
++] = str
;
388 if (sym
->n_strx
== 0) {
389 incl_index
= 0; /* end of translation unit */
391 str
= stab_str
+ sym
->n_strx
;
392 /* do not add path */
394 if (len
> 0 && str
[len
- 1] != '/')
402 /* second pass: we try symtab symbols (no line number info) */
406 ElfW(Sym
) *sym
, *sym_end
;
409 sym_end
= (ElfW(Sym
) *)(symtab_section
->data
+ symtab_section
->data_offset
);
410 for(sym
= (ElfW(Sym
) *)symtab_section
->data
+ 1;
413 type
= ELFW(ST_TYPE
)(sym
->st_info
);
414 if (type
== STT_FUNC
|| type
== STT_GNU_IFUNC
) {
415 if (wanted_pc
>= sym
->st_value
&&
416 wanted_pc
< sym
->st_value
+ sym
->st_size
) {
417 pstrcpy(last_func_name
, sizeof(last_func_name
),
418 (char *) strtab_section
->data
+ sym
->st_name
);
419 func_addr
= sym
->st_value
;
425 /* did not find any info: */
426 fprintf(stderr
, "%s %p ???\n", msg
, (void*)wanted_pc
);
432 fprintf(stderr
, "%s:%d: ", incl_files
[--i
], last_line_num
);
433 fprintf(stderr
, "%s %p", msg
, (void*)wanted_pc
);
434 if (last_func_name
[0] != '\0')
435 fprintf(stderr
, " %s()", last_func_name
);
437 fprintf(stderr
, " (included from ");
439 fprintf(stderr
, "%s", incl_files
[i
]);
442 fprintf(stderr
, ", ");
444 fprintf(stderr
, ")");
446 fprintf(stderr
, "\n");
451 /* emit a run time error at position 'pc' */
452 static void rt_error(ucontext_t
*uc
, const char *fmt
, ...)
458 fprintf(stderr
, "Runtime error: ");
460 vfprintf(stderr
, fmt
, ap
);
462 fprintf(stderr
, "\n");
464 for(i
=0;i
<rt_num_callers
;i
++) {
465 if (rt_get_caller_pc(&pc
, uc
, i
) < 0)
467 pc
= rt_printline(pc
, i
? "by" : "at");
468 if (pc
== (addr_t
)rt_prog_main
&& pc
)
473 /* ------------------------------------------------------------- */
476 /* signal handler for fatal errors */
477 static void sig_error(int signum
, siginfo_t
*siginf
, void *puc
)
479 ucontext_t
*uc
= puc
;
483 switch(siginf
->si_code
) {
486 rt_error(uc
, "division by zero");
489 rt_error(uc
, "floating point exception");
495 if (rt_bound_error_msg
&& *rt_bound_error_msg
)
496 rt_error(uc
, *rt_bound_error_msg
);
498 rt_error(uc
, "dereferencing invalid pointer");
501 rt_error(uc
, "illegal instruction");
504 rt_error(uc
, "abort() called");
507 rt_error(uc
, "caught signal %d", signum
);
514 # define SA_SIGINFO 0x00000004u
517 /* Generate a stack backtrace when a CPU exception occurs. */
518 static void set_exception_handler(void)
520 struct sigaction sigact
;
521 /* install TCC signal handlers to print debug info on fatal
523 sigact
.sa_flags
= SA_SIGINFO
| SA_RESETHAND
;
524 sigact
.sa_sigaction
= sig_error
;
525 sigemptyset(&sigact
.sa_mask
);
526 sigaction(SIGFPE
, &sigact
, NULL
);
527 sigaction(SIGILL
, &sigact
, NULL
);
528 sigaction(SIGSEGV
, &sigact
, NULL
);
529 sigaction(SIGBUS
, &sigact
, NULL
);
530 sigaction(SIGABRT
, &sigact
, NULL
);
533 /* ------------------------------------------------------------- */
536 /* fix for glibc 2.1 */
542 /* return the PC at frame level 'level'. Return negative if not found */
543 static int rt_get_caller_pc(addr_t
*paddr
, ucontext_t
*uc
, int level
)
549 #if defined(__APPLE__)
550 *paddr
= uc
->uc_mcontext
->__ss
.__eip
;
551 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
552 *paddr
= uc
->uc_mcontext
.mc_eip
;
553 #elif defined(__dietlibc__)
554 *paddr
= uc
->uc_mcontext
.eip
;
555 #elif defined(__NetBSD__)
556 *paddr
= uc
->uc_mcontext
.__gregs
[_REG_EIP
];
557 #elif defined(__OpenBSD__)
560 *paddr
= uc
->uc_mcontext
.gregs
[REG_EIP
];
564 #if defined(__APPLE__)
565 fp
= uc
->uc_mcontext
->__ss
.__ebp
;
566 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
567 fp
= uc
->uc_mcontext
.mc_ebp
;
568 #elif defined(__dietlibc__)
569 fp
= uc
->uc_mcontext
.ebp
;
570 #elif defined(__NetBSD__)
571 fp
= uc
->uc_mcontext
.__gregs
[_REG_EBP
];
572 #elif defined(__OpenBSD__)
575 fp
= uc
->uc_mcontext
.gregs
[REG_EBP
];
577 for(i
=1;i
<level
;i
++) {
578 /* XXX: check address validity with program info */
579 if (fp
<= 0x1000 || fp
>= 0xc0000000)
581 fp
= ((addr_t
*)fp
)[0];
583 *paddr
= ((addr_t
*)fp
)[1];
588 /* ------------------------------------------------------------- */
589 #elif defined(__x86_64__)
591 /* return the PC at frame level 'level'. Return negative if not found */
592 static int rt_get_caller_pc(addr_t
*paddr
, ucontext_t
*uc
, int level
)
598 /* XXX: only support linux */
599 #if defined(__APPLE__)
600 *paddr
= uc
->uc_mcontext
->__ss
.__rip
;
601 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
602 *paddr
= uc
->uc_mcontext
.mc_rip
;
603 #elif defined(__NetBSD__)
604 *paddr
= uc
->uc_mcontext
.__gregs
[_REG_RIP
];
606 *paddr
= uc
->uc_mcontext
.gregs
[REG_RIP
];
610 #if defined(__APPLE__)
611 fp
= uc
->uc_mcontext
->__ss
.__rbp
;
612 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
613 fp
= uc
->uc_mcontext
.mc_rbp
;
614 #elif defined(__NetBSD__)
615 fp
= uc
->uc_mcontext
.__gregs
[_REG_RBP
];
617 fp
= uc
->uc_mcontext
.gregs
[REG_RBP
];
619 for(i
=1;i
<level
;i
++) {
620 /* XXX: check address validity with program info */
623 fp
= ((addr_t
*)fp
)[0];
625 *paddr
= ((addr_t
*)fp
)[1];
630 /* ------------------------------------------------------------- */
631 #elif defined(__arm__)
633 /* return the PC at frame level 'level'. Return negative if not found */
634 static int rt_get_caller_pc(addr_t
*paddr
, ucontext_t
*uc
, int level
)
640 /* XXX: only supports linux */
641 #if defined(__linux__)
642 *paddr
= uc
->uc_mcontext
.arm_pc
;
648 #if defined(__linux__)
649 fp
= uc
->uc_mcontext
.arm_fp
;
650 sp
= uc
->uc_mcontext
.arm_sp
;
656 /* XXX: specific to tinycc stack frames */
657 if (fp
< sp
+ 12 || fp
& 3)
659 for(i
= 1; i
< level
; i
++) {
660 sp
= ((addr_t
*)fp
)[-2];
661 if (sp
< fp
|| sp
- fp
> 16 || sp
& 3)
663 fp
= ((addr_t
*)fp
)[-3];
664 if (fp
<= sp
|| fp
- sp
< 12 || fp
& 3)
667 /* XXX: check address validity with program info */
668 *paddr
= ((addr_t
*)fp
)[-1];
673 /* ------------------------------------------------------------- */
674 #elif defined(__aarch64__)
676 static int rt_get_caller_pc(addr_t
*paddr
, ucontext_t
*uc
, int level
)
680 else if (level
== 0) {
681 *paddr
= uc
->uc_mcontext
.pc
;
685 addr_t
*fp
= (addr_t
*)uc
->uc_mcontext
.regs
[29];
687 for (i
= 1; i
< level
; i
++)
688 fp
= (addr_t
*)fp
[0];
694 /* ------------------------------------------------------------- */
697 #warning add arch specific rt_get_caller_pc()
698 static int rt_get_caller_pc(addr_t
*paddr
, ucontext_t
*uc
, int level
)
703 #endif /* !__i386__ */
705 /* ------------------------------------------------------------- */
708 static long __stdcall
cpu_exception_handler(EXCEPTION_POINTERS
*ex_info
)
710 EXCEPTION_RECORD
*er
= ex_info
->ExceptionRecord
;
711 CONTEXT
*uc
= ex_info
->ContextRecord
;
712 switch (er
->ExceptionCode
) {
713 case EXCEPTION_ACCESS_VIOLATION
:
714 if (rt_bound_error_msg
&& *rt_bound_error_msg
)
715 rt_error(uc
, *rt_bound_error_msg
);
717 rt_error(uc
, "access violation");
719 case EXCEPTION_STACK_OVERFLOW
:
720 rt_error(uc
, "stack overflow");
722 case EXCEPTION_INT_DIVIDE_BY_ZERO
:
723 rt_error(uc
, "division by zero");
726 rt_error(uc
, "exception caught");
729 return EXCEPTION_EXECUTE_HANDLER
;
732 /* Generate a stack backtrace when a CPU exception occurs. */
733 static void set_exception_handler(void)
735 SetUnhandledExceptionFilter(cpu_exception_handler
);
738 /* return the PC at frame level 'level'. Return non zero if not found */
739 static int rt_get_caller_pc(addr_t
*paddr
, CONTEXT
*uc
, int level
)
751 for(i
=1;i
<level
;i
++) {
752 /* XXX: check address validity with program info */
753 if (fp
<= 0x1000 || fp
>= 0xc0000000)
755 fp
= ((addr_t
*)fp
)[0];
757 pc
= ((addr_t
*)fp
)[1];
764 #endif /* CONFIG_TCC_BACKTRACE */
765 /* ------------------------------------------------------------- */
766 #ifdef CONFIG_TCC_STATIC
768 /* dummy function for profiling */
769 ST_FUNC
void *dlopen(const char *filename
, int flag
)
774 ST_FUNC
void dlclose(void *p
)
778 ST_FUNC
const char *dlerror(void)
783 typedef struct TCCSyms
{
789 /* add the symbol you want here if no dynamic linking is done */
790 static TCCSyms tcc_syms
[] = {
791 #if !defined(CONFIG_TCCBOOT)
792 #define TCCSYM(a) { #a, &a, },
802 ST_FUNC
void *dlsym(void *handle
, const char *symbol
)
806 while (p
->str
!= NULL
) {
807 if (!strcmp(p
->str
, symbol
))
814 #endif /* CONFIG_TCC_STATIC */
815 #endif /* TCC_IS_NATIVE */
816 /* ------------------------------------------------------------- */