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 ret
= (*prog_main
)(argc
, argv
);
132 /* unmark argv area */
133 for (i
=0; i
<argc
; ++i
)
134 bound_delete_region(argv
[i
]);
135 bound_delete_region(argv
);
140 ret
= (*prog_main
)(argc
, argv
);
144 /* relocate code. Return -1 on error, required size if ptr is NULL,
145 otherwise copy code into buffer passed by the caller */
146 static int tcc_relocate_ex(TCCState
*s1
, void *ptr
)
149 unsigned long offset
, length
;
156 pe_output_file(s1
, NULL
);
159 relocate_common_syms();
160 tcc_add_linker_symbols(s1
);
161 build_got_entries(s1
);
167 offset
= 0, mem
= (addr_t
)ptr
;
168 for(i
= 1; i
< s1
->nb_sections
; i
++) {
170 if (0 == (s
->sh_flags
& SHF_ALLOC
))
172 length
= s
->data_offset
;
173 s
->sh_addr
= mem
? (mem
+ offset
+ 15) & ~15 : 0;
174 offset
= (offset
+ length
+ 15) & ~15;
178 /* relocate symbols */
179 relocate_syms(s1
, 1);
183 #ifdef TCC_HAS_RUNTIME_PLTGOT
184 s1
->runtime_plt_and_got_offset
= 0;
185 s1
->runtime_plt_and_got
= (char *)(mem
+ offset
);
186 /* double the size of the buffer for got and plt entries
187 XXX: calculate exact size for them? */
194 /* relocate each section */
195 for(i
= 1; i
< s1
->nb_sections
; i
++) {
198 relocate_section(s1
, s
);
201 for(i
= 1; i
< s1
->nb_sections
; i
++) {
203 if (0 == (s
->sh_flags
& SHF_ALLOC
))
205 length
= s
->data_offset
;
206 // printf("%-12s %08x %04x\n", s->name, s->sh_addr, length);
207 ptr
= (void*)s
->sh_addr
;
208 if (NULL
== s
->data
|| s
->sh_type
== SHT_NOBITS
)
209 memset(ptr
, 0, length
);
211 memcpy(ptr
, s
->data
, length
);
212 /* mark executable sections as executable in memory */
213 if (s
->sh_flags
& SHF_EXECINSTR
)
214 set_pages_executable(ptr
, length
);
217 #ifdef TCC_HAS_RUNTIME_PLTGOT
218 set_pages_executable(s1
->runtime_plt_and_got
,
219 s1
->runtime_plt_and_got_offset
);
223 win64_add_function_table(s1
);
228 /* ------------------------------------------------------------- */
229 /* allow to run code in memory */
231 static void set_pages_executable(void *ptr
, unsigned long length
)
234 unsigned long old_protect
;
235 VirtualProtect(ptr
, length
, PAGE_EXECUTE_READWRITE
, &old_protect
);
238 # define PAGESIZE 4096
241 start
= (addr_t
)ptr
& ~(PAGESIZE
- 1);
242 end
= (addr_t
)ptr
+ length
;
243 end
= (end
+ PAGESIZE
- 1) & ~(PAGESIZE
- 1);
244 mprotect((void *)start
, end
- start
, PROT_READ
| PROT_WRITE
| PROT_EXEC
);
245 __clear_cache(ptr
, ptr
+ length
);
249 /* ------------------------------------------------------------- */
250 #ifdef CONFIG_TCC_BACKTRACE
252 ST_FUNC
void tcc_set_num_callers(int n
)
257 /* print the position in the source file of PC value 'pc' by reading
258 the stabs debug information */
259 static addr_t
rt_printline(addr_t wanted_pc
, const char *msg
)
261 char func_name
[128], last_func_name
[128];
262 addr_t func_addr
, last_pc
, pc
;
263 const char *incl_files
[INCLUDE_STACK_SIZE
];
264 int incl_index
, len
, last_line_num
, i
;
267 Stab_Sym
*stab_sym
= NULL
, *stab_sym_end
, *sym
;
269 char *stab_str
= NULL
;
272 stab_len
= stab_section
->data_offset
;
273 stab_sym
= (Stab_Sym
*)stab_section
->data
;
274 stab_str
= stabstr_section
->data
;
280 last_func_name
[0] = '\0';
281 last_pc
= (addr_t
)-1;
287 stab_sym_end
= (Stab_Sym
*)((char*)stab_sym
+ stab_len
);
288 for (sym
= stab_sym
+ 1; sym
< stab_sym_end
; ++sym
) {
289 switch(sym
->n_type
) {
290 /* function start or end */
292 if (sym
->n_strx
== 0) {
293 /* we test if between last line and end of function */
294 pc
= sym
->n_value
+ func_addr
;
295 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
300 str
= stab_str
+ sym
->n_strx
;
301 p
= strchr(str
, ':');
303 pstrcpy(func_name
, sizeof(func_name
), str
);
306 if (len
> sizeof(func_name
) - 1)
307 len
= sizeof(func_name
) - 1;
308 memcpy(func_name
, str
, len
);
309 func_name
[len
] = '\0';
311 func_addr
= sym
->n_value
;
314 /* line number info */
316 pc
= sym
->n_value
+ func_addr
;
317 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
320 last_line_num
= sym
->n_desc
;
322 strcpy(last_func_name
, func_name
);
326 str
= stab_str
+ sym
->n_strx
;
328 if (incl_index
< INCLUDE_STACK_SIZE
) {
329 incl_files
[incl_index
++] = str
;
337 if (sym
->n_strx
== 0) {
338 incl_index
= 0; /* end of translation unit */
340 str
= stab_str
+ sym
->n_strx
;
341 /* do not add path */
343 if (len
> 0 && str
[len
- 1] != '/')
351 /* second pass: we try symtab symbols (no line number info) */
355 ElfW(Sym
) *sym
, *sym_end
;
358 sym_end
= (ElfW(Sym
) *)(symtab_section
->data
+ symtab_section
->data_offset
);
359 for(sym
= (ElfW(Sym
) *)symtab_section
->data
+ 1;
362 type
= ELFW(ST_TYPE
)(sym
->st_info
);
363 if (type
== STT_FUNC
|| type
== STT_GNU_IFUNC
) {
364 if (wanted_pc
>= sym
->st_value
&&
365 wanted_pc
< sym
->st_value
+ sym
->st_size
) {
366 pstrcpy(last_func_name
, sizeof(last_func_name
),
367 strtab_section
->data
+ sym
->st_name
);
368 func_addr
= sym
->st_value
;
374 /* did not find any info: */
375 fprintf(stderr
, "%s %p ???\n", msg
, (void*)wanted_pc
);
381 fprintf(stderr
, "%s:%d: ", incl_files
[--i
], last_line_num
);
382 fprintf(stderr
, "%s %p", msg
, (void*)wanted_pc
);
383 if (last_func_name
[0] != '\0')
384 fprintf(stderr
, " %s()", last_func_name
);
386 fprintf(stderr
, " (included from ");
388 fprintf(stderr
, "%s", incl_files
[i
]);
391 fprintf(stderr
, ", ");
393 fprintf(stderr
, ")");
395 fprintf(stderr
, "\n");
400 /* emit a run time error at position 'pc' */
401 static void rt_error(ucontext_t
*uc
, const char *fmt
, ...)
407 fprintf(stderr
, "Runtime error: ");
409 vfprintf(stderr
, fmt
, ap
);
411 fprintf(stderr
, "\n");
413 for(i
=0;i
<rt_num_callers
;i
++) {
414 if (rt_get_caller_pc(&pc
, uc
, i
) < 0)
416 pc
= rt_printline(pc
, i
? "by" : "at");
417 if (pc
== (addr_t
)rt_prog_main
&& pc
)
422 /* ------------------------------------------------------------- */
425 /* signal handler for fatal errors */
426 static void sig_error(int signum
, siginfo_t
*siginf
, void *puc
)
428 ucontext_t
*uc
= puc
;
432 switch(siginf
->si_code
) {
435 rt_error(uc
, "division by zero");
438 rt_error(uc
, "floating point exception");
444 if (rt_bound_error_msg
&& *rt_bound_error_msg
)
445 rt_error(uc
, *rt_bound_error_msg
);
447 rt_error(uc
, "dereferencing invalid pointer");
450 rt_error(uc
, "illegal instruction");
453 rt_error(uc
, "abort() called");
456 rt_error(uc
, "caught signal %d", signum
);
463 # define SA_SIGINFO 0x00000004u
466 /* Generate a stack backtrace when a CPU exception occurs. */
467 static void set_exception_handler(void)
469 struct sigaction sigact
;
470 /* install TCC signal handlers to print debug info on fatal
472 sigact
.sa_flags
= SA_SIGINFO
| SA_RESETHAND
;
473 sigact
.sa_sigaction
= sig_error
;
474 sigemptyset(&sigact
.sa_mask
);
475 sigaction(SIGFPE
, &sigact
, NULL
);
476 sigaction(SIGILL
, &sigact
, NULL
);
477 sigaction(SIGSEGV
, &sigact
, NULL
);
478 sigaction(SIGBUS
, &sigact
, NULL
);
479 sigaction(SIGABRT
, &sigact
, NULL
);
482 /* ------------------------------------------------------------- */
485 /* fix for glibc 2.1 */
491 /* return the PC at frame level 'level'. Return negative if not found */
492 static int rt_get_caller_pc(addr_t
*paddr
, ucontext_t
*uc
, int level
)
498 #if defined(__APPLE__)
499 *paddr
= uc
->uc_mcontext
->__ss
.__eip
;
500 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
501 *paddr
= uc
->uc_mcontext
.mc_eip
;
502 #elif defined(__dietlibc__)
503 *paddr
= uc
->uc_mcontext
.eip
;
505 *paddr
= uc
->uc_mcontext
.gregs
[REG_EIP
];
509 #if defined(__APPLE__)
510 fp
= uc
->uc_mcontext
->__ss
.__ebp
;
511 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
512 fp
= uc
->uc_mcontext
.mc_ebp
;
513 #elif defined(__dietlibc__)
514 fp
= uc
->uc_mcontext
.ebp
;
516 fp
= uc
->uc_mcontext
.gregs
[REG_EBP
];
518 for(i
=1;i
<level
;i
++) {
519 /* XXX: check address validity with program info */
520 if (fp
<= 0x1000 || fp
>= 0xc0000000)
522 fp
= ((addr_t
*)fp
)[0];
524 *paddr
= ((addr_t
*)fp
)[1];
529 /* ------------------------------------------------------------- */
530 #elif defined(__x86_64__)
532 /* return the PC at frame level 'level'. Return negative if not found */
533 static int rt_get_caller_pc(addr_t
*paddr
, ucontext_t
*uc
, int level
)
539 /* XXX: only support linux */
540 #if defined(__APPLE__)
541 *paddr
= uc
->uc_mcontext
->__ss
.__rip
;
542 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
543 *paddr
= uc
->uc_mcontext
.mc_rip
;
545 *paddr
= uc
->uc_mcontext
.gregs
[REG_RIP
];
549 #if defined(__APPLE__)
550 fp
= uc
->uc_mcontext
->__ss
.__rbp
;
551 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
552 fp
= uc
->uc_mcontext
.mc_rbp
;
554 fp
= uc
->uc_mcontext
.gregs
[REG_RBP
];
556 for(i
=1;i
<level
;i
++) {
557 /* XXX: check address validity with program info */
560 fp
= ((addr_t
*)fp
)[0];
562 *paddr
= ((addr_t
*)fp
)[1];
567 /* ------------------------------------------------------------- */
568 #elif defined(__arm__)
570 /* return the PC at frame level 'level'. Return negative if not found */
571 static int rt_get_caller_pc(addr_t
*paddr
, ucontext_t
*uc
, int level
)
577 /* XXX: only supports linux */
578 #if defined(__linux__)
579 *paddr
= uc
->uc_mcontext
.arm_pc
;
585 #if defined(__linux__)
586 fp
= uc
->uc_mcontext
.arm_fp
;
587 sp
= uc
->uc_mcontext
.arm_sp
;
593 /* XXX: specific to tinycc stack frames */
594 if (fp
< sp
+ 12 || fp
& 3)
596 for(i
= 1; i
< level
; i
++) {
597 sp
= ((addr_t
*)fp
)[-2];
598 if (sp
< fp
|| sp
- fp
> 16 || sp
& 3)
600 fp
= ((addr_t
*)fp
)[-3];
601 if (fp
<= sp
|| fp
- sp
< 12 || fp
& 3)
604 /* XXX: check address validity with program info */
605 *paddr
= ((addr_t
*)fp
)[-1];
610 /* ------------------------------------------------------------- */
613 #warning add arch specific rt_get_caller_pc()
614 static int rt_get_caller_pc(addr_t
*paddr
, ucontext_t
*uc
, int level
)
619 #endif /* !__i386__ */
621 /* ------------------------------------------------------------- */
624 static long __stdcall
cpu_exception_handler(EXCEPTION_POINTERS
*ex_info
)
626 EXCEPTION_RECORD
*er
= ex_info
->ExceptionRecord
;
627 CONTEXT
*uc
= ex_info
->ContextRecord
;
628 switch (er
->ExceptionCode
) {
629 case EXCEPTION_ACCESS_VIOLATION
:
630 if (rt_bound_error_msg
&& *rt_bound_error_msg
)
631 rt_error(uc
, *rt_bound_error_msg
);
633 rt_error(uc
, "access violation");
635 case EXCEPTION_STACK_OVERFLOW
:
636 rt_error(uc
, "stack overflow");
638 case EXCEPTION_INT_DIVIDE_BY_ZERO
:
639 rt_error(uc
, "division by zero");
642 rt_error(uc
, "exception caught");
645 return EXCEPTION_EXECUTE_HANDLER
;
648 /* Generate a stack backtrace when a CPU exception occurs. */
649 static void set_exception_handler(void)
651 SetUnhandledExceptionFilter(cpu_exception_handler
);
655 static void win64_add_function_table(TCCState
*s1
)
658 (RUNTIME_FUNCTION
*)s1
->uw_pdata
->sh_addr
,
659 s1
->uw_pdata
->data_offset
/ sizeof (RUNTIME_FUNCTION
),
660 text_section
->sh_addr
665 /* return the PC at frame level 'level'. Return non zero if not found */
666 static int rt_get_caller_pc(addr_t
*paddr
, CONTEXT
*uc
, int level
)
678 for(i
=1;i
<level
;i
++) {
679 /* XXX: check address validity with program info */
680 if (fp
<= 0x1000 || fp
>= 0xc0000000)
682 fp
= ((addr_t
*)fp
)[0];
684 pc
= ((addr_t
*)fp
)[1];
691 #endif /* CONFIG_TCC_BACKTRACE */
692 /* ------------------------------------------------------------- */
693 #ifdef CONFIG_TCC_STATIC
695 /* dummy function for profiling */
696 ST_FUNC
void *dlopen(const char *filename
, int flag
)
701 ST_FUNC
void dlclose(void *p
)
705 ST_FUNC
const char *dlerror(void)
710 typedef struct TCCSyms
{
716 /* add the symbol you want here if no dynamic linking is done */
717 static TCCSyms tcc_syms
[] = {
718 #if !defined(CONFIG_TCCBOOT)
719 #define TCCSYM(a) { #a, &a, },
729 ST_FUNC
void *resolve_sym(TCCState
*s1
, const char *symbol
)
733 while (p
->str
!= NULL
) {
734 if (!strcmp(p
->str
, symbol
))
741 #elif !defined(_WIN32)
743 ST_FUNC
void *resolve_sym(TCCState
*s1
, const char *sym
)
745 return dlsym(RTLD_DEFAULT
, sym
);
748 #endif /* CONFIG_TCC_STATIC */
749 #endif /* TCC_IS_NATIVE */
750 /* ------------------------------------------------------------- */