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 */
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
;
33 #define ucontext_t CONTEXT
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
);
43 static void win64_add_function_table(TCCState
*s1
);
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
)
54 if (TCC_RELOCATE_AUTO
!= ptr
)
55 return tcc_relocate_ex(s1
, ptr
);
57 ret
= tcc_relocate_ex(s1
, NULL
);
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
);
70 ftruncate (fd
, s1
->mem_size
);
72 s1
->write_mem
= mmap (NULL
, ret
, PROT_READ
|PROT_WRITE
,
74 if (s1
->write_mem
== MAP_FAILED
)
75 tcc_error("/tmp not writeable");
77 s1
->runtime_mem
= mmap (NULL
, ret
, PROT_READ
|PROT_EXEC
,
79 if (s1
->runtime_mem
== MAP_FAILED
)
80 tcc_error("/tmp not executable");
82 ret
= tcc_relocate_ex(s1
, s1
->write_mem
);
85 s1
->runtime_mem
= tcc_malloc(ret
);
86 ret
= tcc_relocate_ex(s1
, s1
->runtime_mem
);
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 **);
97 if (tcc_relocate(s1
, TCC_RELOCATE_AUTO
) < 0)
100 prog_main
= tcc_get_symbol_err(s1
, s1
->runtime_main
);
102 #ifdef CONFIG_TCC_BACKTRACE
104 set_exception_handler();
105 rt_prog_main
= prog_main
;
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
);
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");
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 errno
= 0; /* clean errno value */
131 ret
= (*prog_main
)(argc
, argv
);
133 /* unmark argv area */
134 for (i
=0; i
<argc
; ++i
)
135 bound_delete_region(argv
[i
]);
136 bound_delete_region(argv
);
142 errno
= 0; /* clean errno value */
143 ret
= (*prog_main
)(argc
, argv
);
148 /* relocate code. Return -1 on error, required size if ptr is NULL,
149 otherwise copy code into buffer passed by the caller */
150 static int tcc_relocate_ex(TCCState
*s1
, void *ptr
)
153 unsigned long offset
, length
;
160 pe_output_file(s1
, NULL
);
163 relocate_common_syms();
164 tcc_add_linker_symbols(s1
);
165 build_got_entries(s1
);
171 offset
= 0, mem
= (addr_t
)ptr
;
172 for(i
= 1; i
< s1
->nb_sections
; i
++) {
174 if (0 == (s
->sh_flags
& SHF_ALLOC
))
176 length
= s
->data_offset
;
177 s
->sh_addr
= mem
? (mem
+ offset
+ 15) & ~15 : 0;
178 offset
= (offset
+ length
+ 15) & ~15;
182 /* relocate symbols */
183 relocate_syms(s1
, 1);
190 /* relocate each section */
191 for(i
= 1; i
< s1
->nb_sections
; i
++) {
194 relocate_section(s1
, s
);
198 for(i
= 1; i
< s1
->nb_sections
; i
++) {
200 if (0 == (s
->sh_flags
& SHF_ALLOC
))
202 length
= s
->data_offset
;
203 // printf("%-12s %08lx %04x\n", s->name, s->sh_addr, length);
204 ptr
= (void*)s
->sh_addr
;
205 if (NULL
== s
->data
|| s
->sh_type
== SHT_NOBITS
)
206 memset(ptr
, 0, length
);
208 memcpy(ptr
, s
->data
, length
);
209 /* mark executable sections as executable in memory */
210 if (s
->sh_flags
& SHF_EXECINSTR
)
211 set_pages_executable(ptr
, length
);
215 win64_add_function_table(s1
);
220 /* ------------------------------------------------------------- */
221 /* allow to run code in memory */
223 static void set_pages_executable(void *ptr
, unsigned long length
)
226 unsigned long old_protect
;
227 VirtualProtect(ptr
, length
, PAGE_EXECUTE_READWRITE
, &old_protect
);
229 extern void __clear_cache(char *beginning
, char *end
);
231 # define PAGESIZE 4096
234 start
= (addr_t
)ptr
& ~(PAGESIZE
- 1);
235 end
= (addr_t
)ptr
+ length
;
236 end
= (end
+ PAGESIZE
- 1) & ~(PAGESIZE
- 1);
237 mprotect((void *)start
, end
- start
, PROT_READ
| PROT_WRITE
| PROT_EXEC
);
238 __clear_cache(ptr
, ptr
+ length
);
242 /* ------------------------------------------------------------- */
243 #ifdef CONFIG_TCC_BACKTRACE
245 ST_FUNC
void tcc_set_num_callers(int n
)
250 /* print the position in the source file of PC value 'pc' by reading
251 the stabs debug information */
252 static addr_t
rt_printline(addr_t wanted_pc
, const char *msg
)
254 char func_name
[128], last_func_name
[128];
255 addr_t func_addr
, last_pc
, pc
;
256 const char *incl_files
[INCLUDE_STACK_SIZE
];
257 int incl_index
, len
, last_line_num
, i
;
260 Stab_Sym
*stab_sym
= NULL
, *stab_sym_end
, *sym
;
262 char *stab_str
= NULL
;
265 stab_len
= stab_section
->data_offset
;
266 stab_sym
= (Stab_Sym
*)stab_section
->data
;
267 stab_str
= (char *) stabstr_section
->data
;
273 last_func_name
[0] = '\0';
274 last_pc
= (addr_t
)-1;
280 stab_sym_end
= (Stab_Sym
*)((char*)stab_sym
+ stab_len
);
281 for (sym
= stab_sym
+ 1; sym
< stab_sym_end
; ++sym
) {
282 switch(sym
->n_type
) {
283 /* function start or end */
285 if (sym
->n_strx
== 0) {
286 /* we test if between last line and end of function */
287 pc
= sym
->n_value
+ func_addr
;
288 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
293 str
= stab_str
+ sym
->n_strx
;
294 p
= strchr(str
, ':');
296 pstrcpy(func_name
, sizeof(func_name
), str
);
299 if (len
> sizeof(func_name
) - 1)
300 len
= sizeof(func_name
) - 1;
301 memcpy(func_name
, str
, len
);
302 func_name
[len
] = '\0';
304 func_addr
= sym
->n_value
;
307 /* line number info */
309 pc
= sym
->n_value
+ func_addr
;
310 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
313 last_line_num
= sym
->n_desc
;
315 strcpy(last_func_name
, func_name
);
319 str
= stab_str
+ sym
->n_strx
;
321 if (incl_index
< INCLUDE_STACK_SIZE
) {
322 incl_files
[incl_index
++] = str
;
330 if (sym
->n_strx
== 0) {
331 incl_index
= 0; /* end of translation unit */
333 str
= stab_str
+ sym
->n_strx
;
334 /* do not add path */
336 if (len
> 0 && str
[len
- 1] != '/')
344 /* second pass: we try symtab symbols (no line number info) */
348 ElfW(Sym
) *sym
, *sym_end
;
351 sym_end
= (ElfW(Sym
) *)(symtab_section
->data
+ symtab_section
->data_offset
);
352 for(sym
= (ElfW(Sym
) *)symtab_section
->data
+ 1;
355 type
= ELFW(ST_TYPE
)(sym
->st_info
);
356 if (type
== STT_FUNC
|| type
== STT_GNU_IFUNC
) {
357 if (wanted_pc
>= sym
->st_value
&&
358 wanted_pc
< sym
->st_value
+ sym
->st_size
) {
359 pstrcpy(last_func_name
, sizeof(last_func_name
),
360 (char *) strtab_section
->data
+ sym
->st_name
);
361 func_addr
= sym
->st_value
;
367 /* did not find any info: */
368 fprintf(stderr
, "%s %p ???\n", msg
, (void*)wanted_pc
);
374 fprintf(stderr
, "%s:%d: ", incl_files
[--i
], last_line_num
);
375 fprintf(stderr
, "%s %p", msg
, (void*)wanted_pc
);
376 if (last_func_name
[0] != '\0')
377 fprintf(stderr
, " %s()", last_func_name
);
379 fprintf(stderr
, " (included from ");
381 fprintf(stderr
, "%s", incl_files
[i
]);
384 fprintf(stderr
, ", ");
386 fprintf(stderr
, ")");
388 fprintf(stderr
, "\n");
393 /* emit a run time error at position 'pc' */
394 static void rt_error(ucontext_t
*uc
, const char *fmt
, ...)
400 fprintf(stderr
, "Runtime error: ");
402 vfprintf(stderr
, fmt
, ap
);
404 fprintf(stderr
, "\n");
406 for(i
=0;i
<rt_num_callers
;i
++) {
407 if (rt_get_caller_pc(&pc
, uc
, i
) < 0)
409 pc
= rt_printline(pc
, i
? "by" : "at");
410 if (pc
== (addr_t
)rt_prog_main
&& pc
)
415 /* ------------------------------------------------------------- */
418 /* signal handler for fatal errors */
419 static void sig_error(int signum
, siginfo_t
*siginf
, void *puc
)
421 ucontext_t
*uc
= puc
;
425 switch(siginf
->si_code
) {
428 rt_error(uc
, "division by zero");
431 rt_error(uc
, "floating point exception");
437 if (rt_bound_error_msg
&& *rt_bound_error_msg
)
438 rt_error(uc
, *rt_bound_error_msg
);
440 rt_error(uc
, "dereferencing invalid pointer");
443 rt_error(uc
, "illegal instruction");
446 rt_error(uc
, "abort() called");
449 rt_error(uc
, "caught signal %d", signum
);
456 # define SA_SIGINFO 0x00000004u
459 /* Generate a stack backtrace when a CPU exception occurs. */
460 static void set_exception_handler(void)
462 struct sigaction sigact
;
463 /* install TCC signal handlers to print debug info on fatal
465 sigact
.sa_flags
= SA_SIGINFO
| SA_RESETHAND
;
466 sigact
.sa_sigaction
= sig_error
;
467 sigemptyset(&sigact
.sa_mask
);
468 sigaction(SIGFPE
, &sigact
, NULL
);
469 sigaction(SIGILL
, &sigact
, NULL
);
470 sigaction(SIGSEGV
, &sigact
, NULL
);
471 sigaction(SIGBUS
, &sigact
, NULL
);
472 sigaction(SIGABRT
, &sigact
, NULL
);
475 /* ------------------------------------------------------------- */
478 /* fix for glibc 2.1 */
484 /* return the PC at frame level 'level'. Return negative if not found */
485 static int rt_get_caller_pc(addr_t
*paddr
, ucontext_t
*uc
, int level
)
491 #if defined(__APPLE__)
492 *paddr
= uc
->uc_mcontext
->__ss
.__eip
;
493 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
494 *paddr
= uc
->uc_mcontext
.mc_eip
;
495 #elif defined(__dietlibc__)
496 *paddr
= uc
->uc_mcontext
.eip
;
497 #elif defined(__NetBSD__)
498 *paddr
= uc
->uc_mcontext
.__gregs
[_REG_EIP
];
500 *paddr
= uc
->uc_mcontext
.gregs
[REG_EIP
];
504 #if defined(__APPLE__)
505 fp
= uc
->uc_mcontext
->__ss
.__ebp
;
506 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
507 fp
= uc
->uc_mcontext
.mc_ebp
;
508 #elif defined(__dietlibc__)
509 fp
= uc
->uc_mcontext
.ebp
;
510 #elif defined(__NetBSD__)
511 fp
= uc
->uc_mcontext
.__gregs
[_REG_EBP
];
513 fp
= uc
->uc_mcontext
.gregs
[REG_EBP
];
515 for(i
=1;i
<level
;i
++) {
516 /* XXX: check address validity with program info */
517 if (fp
<= 0x1000 || fp
>= 0xc0000000)
519 fp
= ((addr_t
*)fp
)[0];
521 *paddr
= ((addr_t
*)fp
)[1];
526 /* ------------------------------------------------------------- */
527 #elif defined(__x86_64__)
529 /* return the PC at frame level 'level'. Return negative if not found */
530 static int rt_get_caller_pc(addr_t
*paddr
, ucontext_t
*uc
, int level
)
536 /* XXX: only support linux */
537 #if defined(__APPLE__)
538 *paddr
= uc
->uc_mcontext
->__ss
.__rip
;
539 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
540 *paddr
= uc
->uc_mcontext
.mc_rip
;
541 #elif defined(__NetBSD__)
542 *paddr
= uc
->uc_mcontext
.__gregs
[_REG_RIP
];
544 *paddr
= uc
->uc_mcontext
.gregs
[REG_RIP
];
548 #if defined(__APPLE__)
549 fp
= uc
->uc_mcontext
->__ss
.__rbp
;
550 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
551 fp
= uc
->uc_mcontext
.mc_rbp
;
552 #elif defined(__NetBSD__)
553 fp
= uc
->uc_mcontext
.__gregs
[_REG_RBP
];
555 fp
= uc
->uc_mcontext
.gregs
[REG_RBP
];
557 for(i
=1;i
<level
;i
++) {
558 /* XXX: check address validity with program info */
561 fp
= ((addr_t
*)fp
)[0];
563 *paddr
= ((addr_t
*)fp
)[1];
568 /* ------------------------------------------------------------- */
569 #elif defined(__arm__)
571 /* return the PC at frame level 'level'. Return negative if not found */
572 static int rt_get_caller_pc(addr_t
*paddr
, ucontext_t
*uc
, int level
)
578 /* XXX: only supports linux */
579 #if defined(__linux__)
580 *paddr
= uc
->uc_mcontext
.arm_pc
;
586 #if defined(__linux__)
587 fp
= uc
->uc_mcontext
.arm_fp
;
588 sp
= uc
->uc_mcontext
.arm_sp
;
594 /* XXX: specific to tinycc stack frames */
595 if (fp
< sp
+ 12 || fp
& 3)
597 for(i
= 1; i
< level
; i
++) {
598 sp
= ((addr_t
*)fp
)[-2];
599 if (sp
< fp
|| sp
- fp
> 16 || sp
& 3)
601 fp
= ((addr_t
*)fp
)[-3];
602 if (fp
<= sp
|| fp
- sp
< 12 || fp
& 3)
605 /* XXX: check address validity with program info */
606 *paddr
= ((addr_t
*)fp
)[-1];
611 /* ------------------------------------------------------------- */
612 #elif defined(__aarch64__)
614 static int rt_get_caller_pc(addr_t
*paddr
, ucontext_t
*uc
, int level
)
618 else if (level
== 0) {
619 *paddr
= uc
->uc_mcontext
.pc
;
623 addr_t
*fp
= (addr_t
*)uc
->uc_mcontext
.regs
[29];
625 for (i
= 1; i
< level
; i
++)
626 fp
= (addr_t
*)fp
[0];
632 /* ------------------------------------------------------------- */
635 #warning add arch specific rt_get_caller_pc()
636 static int rt_get_caller_pc(addr_t
*paddr
, ucontext_t
*uc
, int level
)
641 #endif /* !__i386__ */
643 /* ------------------------------------------------------------- */
646 static long __stdcall
cpu_exception_handler(EXCEPTION_POINTERS
*ex_info
)
648 EXCEPTION_RECORD
*er
= ex_info
->ExceptionRecord
;
649 CONTEXT
*uc
= ex_info
->ContextRecord
;
650 switch (er
->ExceptionCode
) {
651 case EXCEPTION_ACCESS_VIOLATION
:
652 if (rt_bound_error_msg
&& *rt_bound_error_msg
)
653 rt_error(uc
, *rt_bound_error_msg
);
655 rt_error(uc
, "access violation");
657 case EXCEPTION_STACK_OVERFLOW
:
658 rt_error(uc
, "stack overflow");
660 case EXCEPTION_INT_DIVIDE_BY_ZERO
:
661 rt_error(uc
, "division by zero");
664 rt_error(uc
, "exception caught");
667 return EXCEPTION_EXECUTE_HANDLER
;
670 /* Generate a stack backtrace when a CPU exception occurs. */
671 static void set_exception_handler(void)
673 SetUnhandledExceptionFilter(cpu_exception_handler
);
677 static void win64_add_function_table(TCCState
*s1
)
680 (RUNTIME_FUNCTION
*)s1
->uw_pdata
->sh_addr
,
681 s1
->uw_pdata
->data_offset
/ sizeof (RUNTIME_FUNCTION
),
682 text_section
->sh_addr
687 /* return the PC at frame level 'level'. Return non zero if not found */
688 static int rt_get_caller_pc(addr_t
*paddr
, CONTEXT
*uc
, int level
)
700 for(i
=1;i
<level
;i
++) {
701 /* XXX: check address validity with program info */
702 if (fp
<= 0x1000 || fp
>= 0xc0000000)
704 fp
= ((addr_t
*)fp
)[0];
706 pc
= ((addr_t
*)fp
)[1];
713 #endif /* CONFIG_TCC_BACKTRACE */
714 /* ------------------------------------------------------------- */
715 #ifdef CONFIG_TCC_STATIC
717 /* dummy function for profiling */
718 ST_FUNC
void *dlopen(const char *filename
, int flag
)
723 ST_FUNC
void dlclose(void *p
)
727 ST_FUNC
const char *dlerror(void)
732 typedef struct TCCSyms
{
738 /* add the symbol you want here if no dynamic linking is done */
739 static TCCSyms tcc_syms
[] = {
740 #if !defined(CONFIG_TCCBOOT)
741 #define TCCSYM(a) { #a, &a, },
751 ST_FUNC
void *resolve_sym(TCCState
*s1
, const char *symbol
)
755 while (p
->str
!= NULL
) {
756 if (!strcmp(p
->str
, symbol
))
763 #elif !defined(_WIN32)
765 ST_FUNC
void *resolve_sym(TCCState
*s1
, const char *sym
)
767 return dlsym(RTLD_DEFAULT
, sym
);
770 #endif /* CONFIG_TCC_STATIC */
771 #endif /* TCC_IS_NATIVE */
772 /* ------------------------------------------------------------- */