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 #ifdef CONFIG_TCC_BACKTRACE
24 ST_DATA
int rt_num_callers
= 6;
25 ST_DATA
const char **rt_bound_error_msg
;
26 ST_DATA
void *rt_prog_main
;
30 #define ucontext_t CONTEXT
33 static void set_pages_executable(void *ptr
, unsigned long length
);
34 static void set_exception_handler(void);
35 static int rt_get_caller_pc(uplong
*paddr
, ucontext_t
*uc
, int level
);
36 static void rt_error(ucontext_t
*uc
, const char *fmt
, ...);
37 static int tcc_relocate_ex(TCCState
*s1
, void *ptr
);
40 static void win64_add_function_table(TCCState
*s1
);
43 /* ------------------------------------------------------------- */
44 /* Do all relocations (needed before using tcc_get_symbol())
45 Returns -1 on error. */
47 LIBTCCAPI
int tcc_relocate(TCCState
*s1
)
51 /* Use mmap instead of malloc for Selinux
52 Ref http://www.gnu.org/s/libc/manual/html_node/File-Size.html */
53 char tmpfname
[] = "/tmp/.tccrunXXXXXX";
54 int fd
= mkstemp (tmpfname
);
55 if ((ret
= tcc_relocate_ex(s1
,NULL
)) < 0)return -1;
57 unlink (tmpfname
); ftruncate (fd
, s1
->mem_size
);
58 s1
->write_mem
= mmap (NULL
, ret
, PROT_READ
|PROT_WRITE
,
60 if(s1
->write_mem
== MAP_FAILED
){
61 tcc_error("/tmp not writeable");
64 s1
->runtime_mem
= mmap (NULL
, ret
, PROT_READ
|PROT_EXEC
,
66 if(s1
->runtime_mem
== MAP_FAILED
){
67 tcc_error("/tmp not executable");
70 ret
= tcc_relocate_ex(s1
, s1
->write_mem
);
72 ret
= tcc_relocate_ex(s1
, NULL
);
74 s1
->runtime_mem
= tcc_malloc(ret
);
75 ret
= tcc_relocate_ex(s1
, s1
->runtime_mem
);
81 /* launch the compiled program with the given arguments */
82 LIBTCCAPI
int tcc_run(TCCState
*s1
, int argc
, char **argv
)
84 int (*prog_main
)(int, char **);
87 if (tcc_relocate(s1
) < 0)
90 prog_main
= tcc_get_symbol_err(s1
, "main");
92 #ifdef CONFIG_TCC_BACKTRACE
94 set_exception_handler();
95 rt_prog_main
= prog_main
;
99 #ifdef CONFIG_TCC_BCHECK
100 if (s1
->do_bounds_check
) {
101 void (*bound_init
)(void);
102 void (*bound_exit
)(void);
103 /* set error function */
104 rt_bound_error_msg
= tcc_get_symbol_err(s1
, "__bound_error_msg");
105 /* XXX: use .init section so that it also work in binary ? */
106 bound_init
= tcc_get_symbol_err(s1
, "__bound_init");
107 bound_exit
= tcc_get_symbol_err(s1
, "__bound_exit");
109 ret
= (*prog_main
)(argc
, argv
);
113 ret
= (*prog_main
)(argc
, argv
);
117 /* relocate code. Return -1 on error, required size if ptr is NULL,
118 otherwise copy code into buffer passed by the caller */
119 static int tcc_relocate_ex(TCCState
*s1
, void *ptr
)
122 unsigned long offset
, length
;
126 if (0 == s1
->runtime_added
) {
127 s1
->runtime_added
= 1;
130 pe_output_file(s1
, NULL
);
133 relocate_common_syms();
134 tcc_add_linker_symbols(s1
);
135 build_got_entries(s1
);
141 offset
= 0, mem
= (uplong
)ptr
;
142 for(i
= 1; i
< s1
->nb_sections
; i
++) {
144 if (0 == (s
->sh_flags
& SHF_ALLOC
))
146 length
= s
->data_offset
;
147 s
->sh_addr
= mem
? (mem
+ offset
+ 15) & ~15 : 0;
148 offset
= (offset
+ length
+ 15) & ~15;
152 /* relocate symbols */
153 relocate_syms(s1
, 1);
157 #if (defined TCC_TARGET_X86_64 || defined TCC_TARGET_ARM) && !defined TCC_TARGET_PE
158 s1
->runtime_plt_and_got_offset
= 0;
159 s1
->runtime_plt_and_got
= (char *)(mem
+ offset
);
160 /* double the size of the buffer for got and plt entries
161 XXX: calculate exact size for them? */
168 /* relocate each section */
169 for(i
= 1; i
< s1
->nb_sections
; i
++) {
172 relocate_section(s1
, s
);
175 for(i
= 1; i
< s1
->nb_sections
; i
++) {
177 if (0 == (s
->sh_flags
& SHF_ALLOC
))
179 length
= s
->data_offset
;
180 // printf("%-12s %08x %04x\n", s->name, s->sh_addr, length);
181 ptr
= (void*)(uplong
)s
->sh_addr
;
182 if (NULL
== s
->data
|| s
->sh_type
== SHT_NOBITS
)
183 memset(ptr
, 0, length
);
185 memcpy(ptr
, s
->data
, length
);
186 /* mark executable sections as executable in memory */
187 if (s
->sh_flags
& SHF_EXECINSTR
)
188 set_pages_executable(ptr
, length
);
191 #if (defined TCC_TARGET_X86_64 || defined TCC_TARGET_ARM) && !defined TCC_TARGET_PE
192 set_pages_executable(s1
->runtime_plt_and_got
,
193 s1
->runtime_plt_and_got_offset
);
197 win64_add_function_table(s1
);
202 /* ------------------------------------------------------------- */
203 /* allow to run code in memory */
205 static void set_pages_executable(void *ptr
, unsigned long length
)
208 unsigned long old_protect
;
209 VirtualProtect(ptr
, length
, PAGE_EXECUTE_READWRITE
, &old_protect
);
211 unsigned long start
, end
;
212 start
= (uplong
)ptr
& ~(PAGESIZE
- 1);
213 end
= (uplong
)ptr
+ length
;
214 end
= (end
+ PAGESIZE
- 1) & ~(PAGESIZE
- 1);
215 mprotect((void *)start
, end
- start
, PROT_READ
| PROT_WRITE
| PROT_EXEC
);
219 /* ------------------------------------------------------------- */
220 #ifdef CONFIG_TCC_BACKTRACE
222 PUB_FUNC
void tcc_set_num_callers(int n
)
227 /* print the position in the source file of PC value 'pc' by reading
228 the stabs debug information */
229 static uplong
rt_printline(uplong wanted_pc
, const char *msg
)
231 char func_name
[128], last_func_name
[128];
232 uplong func_addr
, last_pc
, pc
;
233 const char *incl_files
[INCLUDE_STACK_SIZE
];
234 int incl_index
, len
, last_line_num
, i
;
237 Stab_Sym
*stab_sym
= NULL
, *stab_sym_end
, *sym
;
239 char *stab_str
= NULL
;
242 stab_len
= stab_section
->data_offset
;
243 stab_sym
= (Stab_Sym
*)stab_section
->data
;
244 stab_str
= stabstr_section
->data
;
250 last_func_name
[0] = '\0';
251 last_pc
= (uplong
)-1;
257 stab_sym_end
= (Stab_Sym
*)((char*)stab_sym
+ stab_len
);
258 for (sym
= stab_sym
+ 1; sym
< stab_sym_end
; ++sym
) {
259 switch(sym
->n_type
) {
260 /* function start or end */
262 if (sym
->n_strx
== 0) {
263 /* we test if between last line and end of function */
264 pc
= sym
->n_value
+ func_addr
;
265 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
270 str
= stab_str
+ sym
->n_strx
;
271 p
= strchr(str
, ':');
273 pstrcpy(func_name
, sizeof(func_name
), str
);
276 if (len
> sizeof(func_name
) - 1)
277 len
= sizeof(func_name
) - 1;
278 memcpy(func_name
, str
, len
);
279 func_name
[len
] = '\0';
281 func_addr
= sym
->n_value
;
284 /* line number info */
286 pc
= sym
->n_value
+ func_addr
;
287 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
290 last_line_num
= sym
->n_desc
;
292 strcpy(last_func_name
, func_name
);
296 str
= stab_str
+ sym
->n_strx
;
298 if (incl_index
< INCLUDE_STACK_SIZE
) {
299 incl_files
[incl_index
++] = str
;
307 if (sym
->n_strx
== 0) {
308 incl_index
= 0; /* end of translation unit */
310 str
= stab_str
+ sym
->n_strx
;
311 /* do not add path */
313 if (len
> 0 && str
[len
- 1] != '/')
321 /* second pass: we try symtab symbols (no line number info) */
325 ElfW(Sym
) *sym
, *sym_end
;
328 sym_end
= (ElfW(Sym
) *)(symtab_section
->data
+ symtab_section
->data_offset
);
329 for(sym
= (ElfW(Sym
) *)symtab_section
->data
+ 1;
332 type
= ELFW(ST_TYPE
)(sym
->st_info
);
333 if (type
== STT_FUNC
|| type
== STT_GNU_IFUNC
) {
334 if (wanted_pc
>= sym
->st_value
&&
335 wanted_pc
< sym
->st_value
+ sym
->st_size
) {
336 pstrcpy(last_func_name
, sizeof(last_func_name
),
337 strtab_section
->data
+ sym
->st_name
);
338 func_addr
= sym
->st_value
;
344 /* did not find any info: */
345 fprintf(stderr
, "%s %p ???\n", msg
, (void*)wanted_pc
);
351 fprintf(stderr
, "%s:%d: ", incl_files
[--i
], last_line_num
);
352 fprintf(stderr
, "%s %p", msg
, (void*)wanted_pc
);
353 if (last_func_name
[0] != '\0')
354 fprintf(stderr
, " %s()", last_func_name
);
356 fprintf(stderr
, " (included from ");
358 fprintf(stderr
, "%s", incl_files
[i
]);
361 fprintf(stderr
, ", ");
363 fprintf(stderr
, ")");
365 fprintf(stderr
, "\n");
370 /* emit a run time error at position 'pc' */
371 static void rt_error(ucontext_t
*uc
, const char *fmt
, ...)
377 fprintf(stderr
, "Runtime error: ");
379 vfprintf(stderr
, fmt
, ap
);
381 fprintf(stderr
, "\n");
383 for(i
=0;i
<rt_num_callers
;i
++) {
384 if (rt_get_caller_pc(&pc
, uc
, i
) < 0)
386 pc
= rt_printline(pc
, i
? "by" : "at");
387 if (pc
== (uplong
)rt_prog_main
&& pc
)
392 /* ------------------------------------------------------------- */
395 /* signal handler for fatal errors */
396 static void sig_error(int signum
, siginfo_t
*siginf
, void *puc
)
398 ucontext_t
*uc
= puc
;
402 switch(siginf
->si_code
) {
405 rt_error(uc
, "division by zero");
408 rt_error(uc
, "floating point exception");
414 if (rt_bound_error_msg
&& *rt_bound_error_msg
)
415 rt_error(uc
, *rt_bound_error_msg
);
417 rt_error(uc
, "dereferencing invalid pointer");
420 rt_error(uc
, "illegal instruction");
423 rt_error(uc
, "abort() called");
426 rt_error(uc
, "caught signal %d", signum
);
432 /* Generate a stack backtrace when a CPU exception occurs. */
433 static void set_exception_handler(void)
435 struct sigaction sigact
;
436 /* install TCC signal handlers to print debug info on fatal
438 sigact
.sa_flags
= SA_SIGINFO
| SA_RESETHAND
;
439 sigact
.sa_sigaction
= sig_error
;
440 sigemptyset(&sigact
.sa_mask
);
441 sigaction(SIGFPE
, &sigact
, NULL
);
442 sigaction(SIGILL
, &sigact
, NULL
);
443 sigaction(SIGSEGV
, &sigact
, NULL
);
444 sigaction(SIGBUS
, &sigact
, NULL
);
445 sigaction(SIGABRT
, &sigact
, NULL
);
448 /* ------------------------------------------------------------- */
451 /* fix for glibc 2.1 */
457 /* return the PC at frame level 'level'. Return non zero if not found */
458 static int rt_get_caller_pc(unsigned long *paddr
, ucontext_t
*uc
, int level
)
464 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
465 *paddr
= uc
->uc_mcontext
.mc_eip
;
466 #elif defined(__dietlibc__)
467 *paddr
= uc
->uc_mcontext
.eip
;
469 *paddr
= uc
->uc_mcontext
.gregs
[REG_EIP
];
473 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
474 fp
= uc
->uc_mcontext
.mc_ebp
;
475 #elif defined(__dietlibc__)
476 fp
= uc
->uc_mcontext
.ebp
;
478 fp
= uc
->uc_mcontext
.gregs
[REG_EBP
];
480 for(i
=1;i
<level
;i
++) {
481 /* XXX: check address validity with program info */
482 if (fp
<= 0x1000 || fp
>= 0xc0000000)
484 fp
= ((unsigned long *)fp
)[0];
486 *paddr
= ((unsigned long *)fp
)[1];
491 /* ------------------------------------------------------------- */
492 #elif defined(__x86_64__)
494 /* return the PC at frame level 'level'. Return non zero if not found */
495 static int rt_get_caller_pc(unsigned long *paddr
,
496 ucontext_t
*uc
, int level
)
502 /* XXX: only support linux */
503 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
504 *paddr
= uc
->uc_mcontext
.mc_rip
;
506 *paddr
= uc
->uc_mcontext
.gregs
[REG_RIP
];
510 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
511 fp
= uc
->uc_mcontext
.mc_rbp
;
513 fp
= uc
->uc_mcontext
.gregs
[REG_RBP
];
515 for(i
=1;i
<level
;i
++) {
516 /* XXX: check address validity with program info */
519 fp
= ((unsigned long *)fp
)[0];
521 *paddr
= ((unsigned long *)fp
)[1];
526 /* ------------------------------------------------------------- */
527 #elif defined(__arm__)
529 /* return the PC at frame level 'level'. Return negative if not found */
530 static int rt_get_caller_pc(unsigned long *paddr
,
531 ucontext_t
*uc
, int level
)
537 /* XXX: only supports linux */
538 #if defined(__linux__)
539 *paddr
= uc
->uc_mcontext
.arm_pc
;
545 #if defined(__linux__)
546 fp
= uc
->uc_mcontext
.arm_fp
;
547 sp
= uc
->uc_mcontext
.arm_sp
;
553 /* XXX: specific to tinycc stack frames */
554 if (fp
< sp
+ 12 || fp
& 3)
556 for(i
= 1; i
< level
; i
++) {
557 sp
= ((uint32_t *)fp
)[-2];
558 if (sp
< fp
|| sp
- fp
> 16 || sp
& 3)
560 fp
= ((uint32_t *)fp
)[-3];
561 if (fp
<= sp
|| fp
- sp
< 12 || fp
& 3)
564 /* XXX: check address validity with program info */
565 *paddr
= ((uint32_t *)fp
)[-1];
570 /* ------------------------------------------------------------- */
573 #warning add arch specific rt_get_caller_pc()
574 static int rt_get_caller_pc(unsigned long *paddr
,
575 ucontext_t
*uc
, int level
)
580 #endif /* !__i386__ */
582 /* ------------------------------------------------------------- */
585 static long __stdcall
cpu_exception_handler(EXCEPTION_POINTERS
*ex_info
)
587 EXCEPTION_RECORD
*er
= ex_info
->ExceptionRecord
;
588 CONTEXT
*uc
= ex_info
->ContextRecord
;
589 switch (er
->ExceptionCode
) {
590 case EXCEPTION_ACCESS_VIOLATION
:
591 if (rt_bound_error_msg
&& *rt_bound_error_msg
)
592 rt_error(uc
, *rt_bound_error_msg
);
594 rt_error(uc
, "access violation");
596 case EXCEPTION_STACK_OVERFLOW
:
597 rt_error(uc
, "stack overflow");
599 case EXCEPTION_INT_DIVIDE_BY_ZERO
:
600 rt_error(uc
, "division by zero");
603 rt_error(uc
, "exception caught");
607 return EXCEPTION_CONTINUE_SEARCH
;
610 /* Generate a stack backtrace when a CPU exception occurs. */
611 static void set_exception_handler(void)
613 SetUnhandledExceptionFilter(cpu_exception_handler
);
617 static void win64_add_function_table(TCCState
*s1
)
620 (RUNTIME_FUNCTION
*)(uplong
)s1
->uw_pdata
->sh_addr
,
621 s1
->uw_pdata
->data_offset
/ sizeof (RUNTIME_FUNCTION
),
622 (uplong
)text_section
->sh_addr
627 /* return the PC at frame level 'level'. Return non zero if not found */
628 static int rt_get_caller_pc(uplong
*paddr
, CONTEXT
*uc
, int level
)
640 for(i
=1;i
<level
;i
++) {
641 /* XXX: check address validity with program info */
642 if (fp
<= 0x1000 || fp
>= 0xc0000000)
644 fp
= ((uplong
*)fp
)[0];
646 pc
= ((uplong
*)fp
)[1];
653 #endif /* CONFIG_TCC_BACKTRACE */
654 /* ------------------------------------------------------------- */
656 #ifdef CONFIG_TCC_STATIC
658 #define RTLD_LAZY 0x001
659 #define RTLD_NOW 0x002
660 #define RTLD_GLOBAL 0x100
661 #define RTLD_DEFAULT NULL
663 /* dummy function for profiling */
664 ST_FUNC
void *dlopen(const char *filename
, int flag
)
669 ST_FUNC
void dlclose(void *p
)
673 const char *dlerror(void)
678 typedef struct TCCSyms
{
683 #define TCCSYM(a) { #a, &a, },
685 /* add the symbol you want here if no dynamic linking is done */
686 static TCCSyms tcc_syms
[] = {
687 #if !defined(CONFIG_TCCBOOT)
696 ST_FUNC
void *resolve_sym(TCCState
*s1
, const char *symbol
)
700 while (p
->str
!= NULL
) {
701 if (!strcmp(p
->str
, symbol
))
708 #elif !defined(_WIN32)
710 ST_FUNC
void *resolve_sym(TCCState
*s1
, const char *sym
)
712 return dlsym(RTLD_DEFAULT
, sym
);
715 #endif /* CONFIG_TCC_STATIC */
717 /* ------------------------------------------------------------- */