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 #ifdef TCC_TARGET_X86_64
178 #define SECTION_ALIGNMENT 511
180 #define SECTION_ALIGNMENT 15
183 /* relocate code. Return -1 on error, required size if ptr is NULL,
184 otherwise copy code into buffer passed by the caller */
185 static int tcc_relocate_ex(TCCState
*s1
, void *ptr
)
188 unsigned long offset
, length
;
195 pe_output_file(s1
, NULL
);
198 relocate_common_syms();
199 tcc_add_linker_symbols(s1
);
200 build_got_entries(s1
);
206 offset
= 0, mem
= (addr_t
)ptr
;
208 offset
+= sizeof (void*);
210 for(i
= 1; i
< s1
->nb_sections
; i
++) {
212 if (0 == (s
->sh_flags
& SHF_ALLOC
))
214 offset
= (offset
+ SECTION_ALIGNMENT
) & ~SECTION_ALIGNMENT
;
215 s
->sh_addr
= mem
? mem
+ offset
: 0;
216 offset
+= s
->data_offset
;
219 /* relocate symbols */
220 relocate_syms(s1
, s1
->symtab
, 1);
227 /* relocate each section */
228 for(i
= 1; i
< s1
->nb_sections
; i
++) {
231 relocate_section(s1
, s
);
236 *(void**)ptr
= win64_add_function_table(s1
);
239 for(i
= 1; i
< s1
->nb_sections
; i
++) {
241 if (0 == (s
->sh_flags
& SHF_ALLOC
))
243 length
= s
->data_offset
;
244 // printf("%-12s %08lx %04x\n", s->name, s->sh_addr, length);
245 ptr
= (void*)s
->sh_addr
;
246 if (NULL
== s
->data
|| s
->sh_type
== SHT_NOBITS
)
247 memset(ptr
, 0, length
);
249 memcpy(ptr
, s
->data
, length
);
250 /* mark executable sections as executable in memory */
251 if (s
->sh_flags
& SHF_EXECINSTR
)
252 set_pages_executable(ptr
, length
);
257 /* ------------------------------------------------------------- */
258 /* allow to run code in memory */
260 static void set_pages_executable(void *ptr
, unsigned long length
)
263 unsigned long old_protect
;
264 VirtualProtect(ptr
, length
, PAGE_EXECUTE_READWRITE
, &old_protect
);
267 # define PAGESIZE 4096
270 start
= (addr_t
)ptr
& ~(PAGESIZE
- 1);
271 end
= (addr_t
)ptr
+ length
;
272 end
= (end
+ PAGESIZE
- 1) & ~(PAGESIZE
- 1);
273 if (mprotect((void *)start
, end
- start
, PROT_READ
| PROT_WRITE
| PROT_EXEC
))
274 tcc_error("mprotect failed: did you mean to configure --with-selinux?");
275 #if defined TCC_TARGET_ARM || defined TCC_TARGET_ARM64
276 { extern void __clear_cache(void *beginning
, void *end
);
277 __clear_cache(ptr
, (char *)ptr
+ length
); }
283 static void *win64_add_function_table(TCCState
*s1
)
287 p
= (void*)s1
->uw_pdata
->sh_addr
;
289 (RUNTIME_FUNCTION
*)p
,
290 s1
->uw_pdata
->data_offset
/ sizeof (RUNTIME_FUNCTION
),
291 text_section
->sh_addr
298 static void win64_del_function_table(void *p
)
301 RtlDeleteFunctionTable((RUNTIME_FUNCTION
*)p
);
306 /* ------------------------------------------------------------- */
307 #ifdef CONFIG_TCC_BACKTRACE
309 ST_FUNC
void tcc_set_num_callers(int n
)
314 /* print the position in the source file of PC value 'pc' by reading
315 the stabs debug information */
316 static addr_t
rt_printline(addr_t wanted_pc
, const char *msg
)
318 char func_name
[128], last_func_name
[128];
319 addr_t func_addr
, last_pc
, pc
;
320 const char *incl_files
[INCLUDE_STACK_SIZE
];
321 int incl_index
, len
, last_line_num
, i
;
324 Stab_Sym
*stab_sym
= NULL
, *stab_sym_end
, *sym
;
326 char *stab_str
= NULL
;
329 stab_len
= stab_section
->data_offset
;
330 stab_sym
= (Stab_Sym
*)stab_section
->data
;
331 stab_str
= (char *) stabstr_section
->data
;
337 last_func_name
[0] = '\0';
338 last_pc
= (addr_t
)-1;
344 stab_sym_end
= (Stab_Sym
*)((char*)stab_sym
+ stab_len
);
345 for (sym
= stab_sym
+ 1; sym
< stab_sym_end
; ++sym
) {
346 switch(sym
->n_type
) {
347 /* function start or end */
349 if (sym
->n_strx
== 0) {
350 /* we test if between last line and end of function */
351 pc
= sym
->n_value
+ func_addr
;
352 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
357 str
= stab_str
+ sym
->n_strx
;
358 p
= strchr(str
, ':');
360 pstrcpy(func_name
, sizeof(func_name
), str
);
363 if (len
> sizeof(func_name
) - 1)
364 len
= sizeof(func_name
) - 1;
365 memcpy(func_name
, str
, len
);
366 func_name
[len
] = '\0';
368 func_addr
= sym
->n_value
;
371 /* line number info */
373 pc
= sym
->n_value
+ func_addr
;
374 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
377 last_line_num
= sym
->n_desc
;
379 strcpy(last_func_name
, func_name
);
383 str
= stab_str
+ sym
->n_strx
;
385 if (incl_index
< INCLUDE_STACK_SIZE
) {
386 incl_files
[incl_index
++] = str
;
394 if (sym
->n_strx
== 0) {
395 incl_index
= 0; /* end of translation unit */
397 str
= stab_str
+ sym
->n_strx
;
398 /* do not add path */
400 if (len
> 0 && str
[len
- 1] != '/')
408 /* second pass: we try symtab symbols (no line number info) */
412 ElfW(Sym
) *sym
, *sym_end
;
415 sym_end
= (ElfW(Sym
) *)(symtab_section
->data
+ symtab_section
->data_offset
);
416 for(sym
= (ElfW(Sym
) *)symtab_section
->data
+ 1;
419 type
= ELFW(ST_TYPE
)(sym
->st_info
);
420 if (type
== STT_FUNC
|| type
== STT_GNU_IFUNC
) {
421 if (wanted_pc
>= sym
->st_value
&&
422 wanted_pc
< sym
->st_value
+ sym
->st_size
) {
423 pstrcpy(last_func_name
, sizeof(last_func_name
),
424 (char *) strtab_section
->data
+ sym
->st_name
);
425 func_addr
= sym
->st_value
;
431 /* did not find any info: */
432 fprintf(stderr
, "%s %p ???\n", msg
, (void*)wanted_pc
);
438 fprintf(stderr
, "%s:%d: ", incl_files
[--i
], last_line_num
);
439 fprintf(stderr
, "%s %p", msg
, (void*)wanted_pc
);
440 if (last_func_name
[0] != '\0')
441 fprintf(stderr
, " %s()", last_func_name
);
443 fprintf(stderr
, " (included from ");
445 fprintf(stderr
, "%s", incl_files
[i
]);
448 fprintf(stderr
, ", ");
450 fprintf(stderr
, ")");
452 fprintf(stderr
, "\n");
457 /* emit a run time error at position 'pc' */
458 static void rt_error(ucontext_t
*uc
, const char *fmt
, ...)
464 fprintf(stderr
, "Runtime error: ");
466 vfprintf(stderr
, fmt
, ap
);
468 fprintf(stderr
, "\n");
470 for(i
=0;i
<rt_num_callers
;i
++) {
471 if (rt_get_caller_pc(&pc
, uc
, i
) < 0)
473 pc
= rt_printline(pc
, i
? "by" : "at");
474 if (pc
== (addr_t
)rt_prog_main
&& pc
)
479 /* ------------------------------------------------------------- */
482 /* signal handler for fatal errors */
483 static void sig_error(int signum
, siginfo_t
*siginf
, void *puc
)
485 ucontext_t
*uc
= puc
;
489 switch(siginf
->si_code
) {
492 rt_error(uc
, "division by zero");
495 rt_error(uc
, "floating point exception");
501 if (rt_bound_error_msg
&& *rt_bound_error_msg
)
502 rt_error(uc
, *rt_bound_error_msg
);
504 rt_error(uc
, "dereferencing invalid pointer");
507 rt_error(uc
, "illegal instruction");
510 rt_error(uc
, "abort() called");
513 rt_error(uc
, "caught signal %d", signum
);
520 # define SA_SIGINFO 0x00000004u
523 /* Generate a stack backtrace when a CPU exception occurs. */
524 static void set_exception_handler(void)
526 struct sigaction sigact
;
527 /* install TCC signal handlers to print debug info on fatal
529 sigact
.sa_flags
= SA_SIGINFO
| SA_RESETHAND
;
530 sigact
.sa_sigaction
= sig_error
;
531 sigemptyset(&sigact
.sa_mask
);
532 sigaction(SIGFPE
, &sigact
, NULL
);
533 sigaction(SIGILL
, &sigact
, NULL
);
534 sigaction(SIGSEGV
, &sigact
, NULL
);
535 sigaction(SIGBUS
, &sigact
, NULL
);
536 sigaction(SIGABRT
, &sigact
, NULL
);
539 /* ------------------------------------------------------------- */
542 /* fix for glibc 2.1 */
548 /* return the PC at frame level 'level'. Return negative if not found */
549 static int rt_get_caller_pc(addr_t
*paddr
, ucontext_t
*uc
, int level
)
555 #if defined(__APPLE__)
556 *paddr
= uc
->uc_mcontext
->__ss
.__eip
;
557 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
558 *paddr
= uc
->uc_mcontext
.mc_eip
;
559 #elif defined(__dietlibc__)
560 *paddr
= uc
->uc_mcontext
.eip
;
561 #elif defined(__NetBSD__)
562 *paddr
= uc
->uc_mcontext
.__gregs
[_REG_EIP
];
563 #elif defined(__OpenBSD__)
566 *paddr
= uc
->uc_mcontext
.gregs
[REG_EIP
];
570 #if defined(__APPLE__)
571 fp
= uc
->uc_mcontext
->__ss
.__ebp
;
572 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
573 fp
= uc
->uc_mcontext
.mc_ebp
;
574 #elif defined(__dietlibc__)
575 fp
= uc
->uc_mcontext
.ebp
;
576 #elif defined(__NetBSD__)
577 fp
= uc
->uc_mcontext
.__gregs
[_REG_EBP
];
578 #elif defined(__OpenBSD__)
581 fp
= uc
->uc_mcontext
.gregs
[REG_EBP
];
583 for(i
=1;i
<level
;i
++) {
584 /* XXX: check address validity with program info */
585 if (fp
<= 0x1000 || fp
>= 0xc0000000)
587 fp
= ((addr_t
*)fp
)[0];
589 *paddr
= ((addr_t
*)fp
)[1];
594 /* ------------------------------------------------------------- */
595 #elif defined(__x86_64__)
597 /* return the PC at frame level 'level'. Return negative if not found */
598 static int rt_get_caller_pc(addr_t
*paddr
, ucontext_t
*uc
, int level
)
604 /* XXX: only support linux */
605 #if defined(__APPLE__)
606 *paddr
= uc
->uc_mcontext
->__ss
.__rip
;
607 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
608 *paddr
= uc
->uc_mcontext
.mc_rip
;
609 #elif defined(__NetBSD__)
610 *paddr
= uc
->uc_mcontext
.__gregs
[_REG_RIP
];
612 *paddr
= uc
->uc_mcontext
.gregs
[REG_RIP
];
616 #if defined(__APPLE__)
617 fp
= uc
->uc_mcontext
->__ss
.__rbp
;
618 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
619 fp
= uc
->uc_mcontext
.mc_rbp
;
620 #elif defined(__NetBSD__)
621 fp
= uc
->uc_mcontext
.__gregs
[_REG_RBP
];
623 fp
= uc
->uc_mcontext
.gregs
[REG_RBP
];
625 for(i
=1;i
<level
;i
++) {
626 /* XXX: check address validity with program info */
629 fp
= ((addr_t
*)fp
)[0];
631 *paddr
= ((addr_t
*)fp
)[1];
636 /* ------------------------------------------------------------- */
637 #elif defined(__arm__)
639 /* return the PC at frame level 'level'. Return negative if not found */
640 static int rt_get_caller_pc(addr_t
*paddr
, ucontext_t
*uc
, int level
)
646 /* XXX: only supports linux */
647 #if defined(__linux__)
648 *paddr
= uc
->uc_mcontext
.arm_pc
;
654 #if defined(__linux__)
655 fp
= uc
->uc_mcontext
.arm_fp
;
656 sp
= uc
->uc_mcontext
.arm_sp
;
662 /* XXX: specific to tinycc stack frames */
663 if (fp
< sp
+ 12 || fp
& 3)
665 for(i
= 1; i
< level
; i
++) {
666 sp
= ((addr_t
*)fp
)[-2];
667 if (sp
< fp
|| sp
- fp
> 16 || sp
& 3)
669 fp
= ((addr_t
*)fp
)[-3];
670 if (fp
<= sp
|| fp
- sp
< 12 || fp
& 3)
673 /* XXX: check address validity with program info */
674 *paddr
= ((addr_t
*)fp
)[-1];
679 /* ------------------------------------------------------------- */
680 #elif defined(__aarch64__)
682 static int rt_get_caller_pc(addr_t
*paddr
, ucontext_t
*uc
, int level
)
686 else if (level
== 0) {
687 *paddr
= uc
->uc_mcontext
.pc
;
691 addr_t
*fp
= (addr_t
*)uc
->uc_mcontext
.regs
[29];
693 for (i
= 1; i
< level
; i
++)
694 fp
= (addr_t
*)fp
[0];
700 /* ------------------------------------------------------------- */
703 #warning add arch specific rt_get_caller_pc()
704 static int rt_get_caller_pc(addr_t
*paddr
, ucontext_t
*uc
, int level
)
709 #endif /* !__i386__ */
711 /* ------------------------------------------------------------- */
714 static long __stdcall
cpu_exception_handler(EXCEPTION_POINTERS
*ex_info
)
716 EXCEPTION_RECORD
*er
= ex_info
->ExceptionRecord
;
717 CONTEXT
*uc
= ex_info
->ContextRecord
;
718 switch (er
->ExceptionCode
) {
719 case EXCEPTION_ACCESS_VIOLATION
:
720 if (rt_bound_error_msg
&& *rt_bound_error_msg
)
721 rt_error(uc
, *rt_bound_error_msg
);
723 rt_error(uc
, "access violation");
725 case EXCEPTION_STACK_OVERFLOW
:
726 rt_error(uc
, "stack overflow");
728 case EXCEPTION_INT_DIVIDE_BY_ZERO
:
729 rt_error(uc
, "division by zero");
732 rt_error(uc
, "exception caught");
735 return EXCEPTION_EXECUTE_HANDLER
;
738 /* Generate a stack backtrace when a CPU exception occurs. */
739 static void set_exception_handler(void)
741 SetUnhandledExceptionFilter(cpu_exception_handler
);
744 /* return the PC at frame level 'level'. Return non zero if not found */
745 static int rt_get_caller_pc(addr_t
*paddr
, CONTEXT
*uc
, int level
)
757 for(i
=1;i
<level
;i
++) {
758 /* XXX: check address validity with program info */
759 if (fp
<= 0x1000 || fp
>= 0xc0000000)
761 fp
= ((addr_t
*)fp
)[0];
763 pc
= ((addr_t
*)fp
)[1];
770 #endif /* CONFIG_TCC_BACKTRACE */
771 /* ------------------------------------------------------------- */
772 #ifdef CONFIG_TCC_STATIC
774 /* dummy function for profiling */
775 ST_FUNC
void *dlopen(const char *filename
, int flag
)
780 ST_FUNC
void dlclose(void *p
)
784 ST_FUNC
const char *dlerror(void)
789 typedef struct TCCSyms
{
795 /* add the symbol you want here if no dynamic linking is done */
796 static TCCSyms tcc_syms
[] = {
797 #if !defined(CONFIG_TCCBOOT)
798 #define TCCSYM(a) { #a, &a, },
808 ST_FUNC
void *dlsym(void *handle
, const char *symbol
)
812 while (p
->str
!= NULL
) {
813 if (!strcmp(p
->str
, symbol
))
820 #endif /* CONFIG_TCC_STATIC */
821 #endif /* TCC_IS_NATIVE */
822 /* ------------------------------------------------------------- */