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
);
39 #if defined TCC_TARGET_X86_64 && defined TCC_TARGET_PE
40 static void win64_add_function_table(TCCState
*s1
);
44 /* ------------------------------------------------------------- */
45 /* Do all relocations (needed before using tcc_get_symbol())
46 Returns -1 on error. */
48 LIBTCCAPI
int tcc_relocate(TCCState
*s1
)
52 /* Use mmap instead of malloc for Selinux
53 Ref http://www.gnu.org/s/libc/manual/html_node/File-Size.html */
54 char tmpfname
[] = "/tmp/.tccrunXXXXXX";
55 int fd
= mkstemp (tmpfname
);
56 if ((ret
= tcc_relocate_ex(s1
,NULL
)) < 0)return -1;
58 unlink (tmpfname
); ftruncate (fd
, s1
->mem_size
);
59 s1
->write_mem
= mmap (NULL
, ret
, PROT_READ
|PROT_WRITE
,
61 if(s1
->write_mem
== MAP_FAILED
){
62 tcc_error("/tmp not writeable");
65 s1
->runtime_mem
= mmap (NULL
, ret
, PROT_READ
|PROT_EXEC
,
67 if(s1
->runtime_mem
== MAP_FAILED
){
68 tcc_error("/tmp not executable");
71 ret
= tcc_relocate_ex(s1
, s1
->write_mem
);
73 ret
= tcc_relocate_ex(s1
, NULL
);
75 s1
->runtime_mem
= tcc_malloc(ret
);
76 ret
= tcc_relocate_ex(s1
, s1
->runtime_mem
);
82 /* launch the compiled program with the given arguments */
83 LIBTCCAPI
int tcc_run(TCCState
*s1
, int argc
, char **argv
)
85 int (*prog_main
)(int, char **);
88 if (tcc_relocate(s1
) < 0)
91 prog_main
= tcc_get_symbol_err(s1
, "main");
93 #ifdef CONFIG_TCC_BACKTRACE
95 set_exception_handler();
96 rt_prog_main
= prog_main
;
100 #ifdef CONFIG_TCC_BCHECK
101 if (s1
->do_bounds_check
) {
102 void (*bound_init
)(void);
103 void (*bound_exit
)(void);
104 /* set error function */
105 rt_bound_error_msg
= tcc_get_symbol_err(s1
, "__bound_error_msg");
106 /* XXX: use .init section so that it also work in binary ? */
107 bound_init
= tcc_get_symbol_err(s1
, "__bound_init");
108 bound_exit
= tcc_get_symbol_err(s1
, "__bound_exit");
110 ret
= (*prog_main
)(argc
, argv
);
114 ret
= (*prog_main
)(argc
, argv
);
118 /* relocate code. Return -1 on error, required size if ptr is NULL,
119 otherwise copy code into buffer passed by the caller */
120 static int tcc_relocate_ex(TCCState
*s1
, void *ptr
)
123 unsigned long offset
, length
;
127 if (0 == s1
->runtime_added
) {
128 s1
->runtime_added
= 1;
131 pe_output_file(s1
, NULL
);
134 relocate_common_syms();
135 tcc_add_linker_symbols(s1
);
136 build_got_entries(s1
);
142 offset
= 0, mem
= (uplong
)ptr
;
143 for(i
= 1; i
< s1
->nb_sections
; i
++) {
145 if (0 == (s
->sh_flags
& SHF_ALLOC
))
147 length
= s
->data_offset
;
148 s
->sh_addr
= mem
? (mem
+ offset
+ 15) & ~15 : 0;
149 offset
= (offset
+ length
+ 15) & ~15;
153 /* relocate symbols */
154 relocate_syms(s1
, 1);
158 #if (defined TCC_TARGET_X86_64 || defined TCC_TARGET_ARM) && !defined TCC_TARGET_PE
159 s1
->runtime_plt_and_got_offset
= 0;
160 s1
->runtime_plt_and_got
= (char *)(mem
+ offset
);
161 /* double the size of the buffer for got and plt entries
162 XXX: calculate exact size for them? */
169 /* relocate each section */
170 for(i
= 1; i
< s1
->nb_sections
; i
++) {
173 relocate_section(s1
, s
);
176 for(i
= 1; i
< s1
->nb_sections
; i
++) {
178 if (0 == (s
->sh_flags
& SHF_ALLOC
))
180 length
= s
->data_offset
;
181 // printf("%-12s %08x %04x\n", s->name, s->sh_addr, length);
182 ptr
= (void*)(uplong
)s
->sh_addr
;
183 if (NULL
== s
->data
|| s
->sh_type
== SHT_NOBITS
)
184 memset(ptr
, 0, length
);
186 memcpy(ptr
, s
->data
, length
);
187 /* mark executable sections as executable in memory */
188 if (s
->sh_flags
& SHF_EXECINSTR
)
189 set_pages_executable(ptr
, length
);
192 #if (defined TCC_TARGET_X86_64 || defined TCC_TARGET_ARM) && !defined TCC_TARGET_PE
193 set_pages_executable(s1
->runtime_plt_and_got
,
194 s1
->runtime_plt_and_got_offset
);
197 #if defined TCC_TARGET_X86_64 && defined TCC_TARGET_PE
198 win64_add_function_table(s1
);
203 /* ------------------------------------------------------------- */
204 /* allow to run code in memory */
206 static void set_pages_executable(void *ptr
, unsigned long length
)
209 unsigned long old_protect
;
210 VirtualProtect(ptr
, length
, PAGE_EXECUTE_READWRITE
, &old_protect
);
212 unsigned long start
, end
;
213 start
= (uplong
)ptr
& ~(PAGESIZE
- 1);
214 end
= (uplong
)ptr
+ length
;
215 end
= (end
+ PAGESIZE
- 1) & ~(PAGESIZE
- 1);
216 mprotect((void *)start
, end
- start
, PROT_READ
| PROT_WRITE
| PROT_EXEC
);
220 /* ------------------------------------------------------------- */
221 #ifdef CONFIG_TCC_BACKTRACE
223 PUB_FUNC
void tcc_set_num_callers(int n
)
228 /* print the position in the source file of PC value 'pc' by reading
229 the stabs debug information */
230 static uplong
rt_printline(uplong wanted_pc
, const char *msg
)
232 char func_name
[128], last_func_name
[128];
233 uplong func_addr
, last_pc
, pc
;
234 const char *incl_files
[INCLUDE_STACK_SIZE
];
235 int incl_index
, len
, last_line_num
, i
;
238 Stab_Sym
*stab_sym
= NULL
, *stab_sym_end
, *sym
;
240 char *stab_str
= NULL
;
243 stab_len
= stab_section
->data_offset
;
244 stab_sym
= (Stab_Sym
*)stab_section
->data
;
245 stab_str
= stabstr_section
->data
;
251 last_func_name
[0] = '\0';
252 last_pc
= (uplong
)-1;
258 stab_sym_end
= (Stab_Sym
*)((char*)stab_sym
+ stab_len
);
259 for (sym
= stab_sym
+ 1; sym
< stab_sym_end
; ++sym
) {
260 switch(sym
->n_type
) {
261 /* function start or end */
263 if (sym
->n_strx
== 0) {
264 /* we test if between last line and end of function */
265 pc
= sym
->n_value
+ func_addr
;
266 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
271 str
= stab_str
+ sym
->n_strx
;
272 p
= strchr(str
, ':');
274 pstrcpy(func_name
, sizeof(func_name
), str
);
277 if (len
> sizeof(func_name
) - 1)
278 len
= sizeof(func_name
) - 1;
279 memcpy(func_name
, str
, len
);
280 func_name
[len
] = '\0';
282 func_addr
= sym
->n_value
;
285 /* line number info */
287 pc
= sym
->n_value
+ func_addr
;
288 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
291 last_line_num
= sym
->n_desc
;
293 strcpy(last_func_name
, func_name
);
297 str
= stab_str
+ sym
->n_strx
;
299 if (incl_index
< INCLUDE_STACK_SIZE
) {
300 incl_files
[incl_index
++] = str
;
308 if (sym
->n_strx
== 0) {
309 incl_index
= 0; /* end of translation unit */
311 str
= stab_str
+ sym
->n_strx
;
312 /* do not add path */
314 if (len
> 0 && str
[len
- 1] != '/')
322 /* second pass: we try symtab symbols (no line number info) */
326 ElfW(Sym
) *sym
, *sym_end
;
329 sym_end
= (ElfW(Sym
) *)(symtab_section
->data
+ symtab_section
->data_offset
);
330 for(sym
= (ElfW(Sym
) *)symtab_section
->data
+ 1;
333 type
= ELFW(ST_TYPE
)(sym
->st_info
);
334 if (type
== STT_FUNC
|| type
== STT_GNU_IFUNC
) {
335 if (wanted_pc
>= sym
->st_value
&&
336 wanted_pc
< sym
->st_value
+ sym
->st_size
) {
337 pstrcpy(last_func_name
, sizeof(last_func_name
),
338 strtab_section
->data
+ sym
->st_name
);
339 func_addr
= sym
->st_value
;
345 /* did not find any info: */
346 fprintf(stderr
, "%s %p ???\n", msg
, (void*)wanted_pc
);
352 fprintf(stderr
, "%s:%d: ", incl_files
[--i
], last_line_num
);
353 fprintf(stderr
, "%s %p", msg
, (void*)wanted_pc
);
354 if (last_func_name
[0] != '\0')
355 fprintf(stderr
, " %s()", last_func_name
);
357 fprintf(stderr
, " (included from ");
359 fprintf(stderr
, "%s", incl_files
[i
]);
362 fprintf(stderr
, ", ");
364 fprintf(stderr
, ")");
366 fprintf(stderr
, "\n");
371 /* emit a run time error at position 'pc' */
372 static void rt_error(ucontext_t
*uc
, const char *fmt
, ...)
378 fprintf(stderr
, "Runtime error: ");
380 vfprintf(stderr
, fmt
, ap
);
382 fprintf(stderr
, "\n");
384 for(i
=0;i
<rt_num_callers
;i
++) {
385 if (rt_get_caller_pc(&pc
, uc
, i
) < 0)
387 pc
= rt_printline(pc
, i
? "by" : "at");
388 if (pc
== (uplong
)rt_prog_main
&& pc
)
393 /* ------------------------------------------------------------- */
396 /* signal handler for fatal errors */
397 static void sig_error(int signum
, siginfo_t
*siginf
, void *puc
)
399 ucontext_t
*uc
= puc
;
403 switch(siginf
->si_code
) {
406 rt_error(uc
, "division by zero");
409 rt_error(uc
, "floating point exception");
415 if (rt_bound_error_msg
&& *rt_bound_error_msg
)
416 rt_error(uc
, *rt_bound_error_msg
);
418 rt_error(uc
, "dereferencing invalid pointer");
421 rt_error(uc
, "illegal instruction");
424 rt_error(uc
, "abort() called");
427 rt_error(uc
, "caught signal %d", signum
);
433 /* Generate a stack backtrace when a CPU exception occurs. */
434 static void set_exception_handler(void)
436 struct sigaction sigact
;
437 /* install TCC signal handlers to print debug info on fatal
439 sigact
.sa_flags
= SA_SIGINFO
| SA_RESETHAND
;
440 sigact
.sa_sigaction
= sig_error
;
441 sigemptyset(&sigact
.sa_mask
);
442 sigaction(SIGFPE
, &sigact
, NULL
);
443 sigaction(SIGILL
, &sigact
, NULL
);
444 sigaction(SIGSEGV
, &sigact
, NULL
);
445 sigaction(SIGBUS
, &sigact
, NULL
);
446 sigaction(SIGABRT
, &sigact
, NULL
);
449 /* ------------------------------------------------------------- */
452 /* fix for glibc 2.1 */
458 /* return the PC at frame level 'level'. Return non zero if not found */
459 static int rt_get_caller_pc(unsigned long *paddr
, ucontext_t
*uc
, int level
)
465 #if defined(__APPLE__)
466 *paddr
= uc
->uc_mcontext
->__ss
.__eip
;
467 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
468 *paddr
= uc
->uc_mcontext
.mc_eip
;
469 #elif defined(__dietlibc__)
470 *paddr
= uc
->uc_mcontext
.eip
;
472 *paddr
= uc
->uc_mcontext
.gregs
[REG_EIP
];
476 #if defined(__APPLE__)
477 fp
= uc
->uc_mcontext
->__ss
.__ebp
;
478 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
479 fp
= uc
->uc_mcontext
.mc_ebp
;
480 #elif defined(__dietlibc__)
481 fp
= uc
->uc_mcontext
.ebp
;
483 fp
= uc
->uc_mcontext
.gregs
[REG_EBP
];
485 for(i
=1;i
<level
;i
++) {
486 /* XXX: check address validity with program info */
487 if (fp
<= 0x1000 || fp
>= 0xc0000000)
489 fp
= ((unsigned long *)fp
)[0];
491 *paddr
= ((unsigned long *)fp
)[1];
496 /* ------------------------------------------------------------- */
497 #elif defined(__x86_64__)
499 /* return the PC at frame level 'level'. Return non zero if not found */
500 static int rt_get_caller_pc(unsigned long *paddr
,
501 ucontext_t
*uc
, int level
)
507 /* XXX: only support linux */
508 #if defined(__APPLE__)
509 *paddr
= uc
->uc_mcontext
->__ss
.__rip
;
510 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
511 *paddr
= uc
->uc_mcontext
.mc_rip
;
513 *paddr
= uc
->uc_mcontext
.gregs
[REG_RIP
];
517 #if defined(__APPLE__)
518 fp
= uc
->uc_mcontext
->__ss
.__rbp
;
519 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
520 fp
= uc
->uc_mcontext
.mc_rbp
;
522 fp
= uc
->uc_mcontext
.gregs
[REG_RBP
];
524 for(i
=1;i
<level
;i
++) {
525 /* XXX: check address validity with program info */
528 fp
= ((unsigned long *)fp
)[0];
530 *paddr
= ((unsigned long *)fp
)[1];
535 /* ------------------------------------------------------------- */
536 #elif defined(__arm__)
538 /* return the PC at frame level 'level'. Return negative if not found */
539 static int rt_get_caller_pc(unsigned long *paddr
,
540 ucontext_t
*uc
, int level
)
546 /* XXX: only supports linux */
547 #if defined(__linux__)
548 *paddr
= uc
->uc_mcontext
.arm_pc
;
554 #if defined(__linux__)
555 fp
= uc
->uc_mcontext
.arm_fp
;
556 sp
= uc
->uc_mcontext
.arm_sp
;
562 /* XXX: specific to tinycc stack frames */
563 if (fp
< sp
+ 12 || fp
& 3)
565 for(i
= 1; i
< level
; i
++) {
566 sp
= ((uint32_t *)fp
)[-2];
567 if (sp
< fp
|| sp
- fp
> 16 || sp
& 3)
569 fp
= ((uint32_t *)fp
)[-3];
570 if (fp
<= sp
|| fp
- sp
< 12 || fp
& 3)
573 /* XXX: check address validity with program info */
574 *paddr
= ((uint32_t *)fp
)[-1];
579 /* ------------------------------------------------------------- */
582 #warning add arch specific rt_get_caller_pc()
583 static int rt_get_caller_pc(unsigned long *paddr
,
584 ucontext_t
*uc
, int level
)
589 #endif /* !__i386__ */
591 /* ------------------------------------------------------------- */
594 static long __stdcall
cpu_exception_handler(EXCEPTION_POINTERS
*ex_info
)
596 EXCEPTION_RECORD
*er
= ex_info
->ExceptionRecord
;
597 CONTEXT
*uc
= ex_info
->ContextRecord
;
598 switch (er
->ExceptionCode
) {
599 case EXCEPTION_ACCESS_VIOLATION
:
600 if (rt_bound_error_msg
&& *rt_bound_error_msg
)
601 rt_error(uc
, *rt_bound_error_msg
);
603 rt_error(uc
, "access violation");
605 case EXCEPTION_STACK_OVERFLOW
:
606 rt_error(uc
, "stack overflow");
608 case EXCEPTION_INT_DIVIDE_BY_ZERO
:
609 rt_error(uc
, "division by zero");
612 rt_error(uc
, "exception caught");
616 return EXCEPTION_CONTINUE_SEARCH
;
619 /* Generate a stack backtrace when a CPU exception occurs. */
620 static void set_exception_handler(void)
622 SetUnhandledExceptionFilter(cpu_exception_handler
);
626 #ifdef TCC_TARGET_X86_64
627 static void win64_add_function_table(TCCState
*s1
)
630 (RUNTIME_FUNCTION
*)(uplong
)s1
->uw_pdata
->sh_addr
,
631 s1
->uw_pdata
->data_offset
/ sizeof (RUNTIME_FUNCTION
),
632 (uplong
)text_section
->sh_addr
638 /* return the PC at frame level 'level'. Return non zero if not found */
639 static int rt_get_caller_pc(uplong
*paddr
, CONTEXT
*uc
, int level
)
651 for(i
=1;i
<level
;i
++) {
652 /* XXX: check address validity with program info */
653 if (fp
<= 0x1000 || fp
>= 0xc0000000)
655 fp
= ((uplong
*)fp
)[0];
657 pc
= ((uplong
*)fp
)[1];
664 #endif /* CONFIG_TCC_BACKTRACE */
665 /* ------------------------------------------------------------- */
667 #ifdef CONFIG_TCC_STATIC
669 #define RTLD_LAZY 0x001
670 #define RTLD_NOW 0x002
671 #define RTLD_GLOBAL 0x100
672 #define RTLD_DEFAULT NULL
674 /* dummy function for profiling */
675 ST_FUNC
void *dlopen(const char *filename
, int flag
)
680 ST_FUNC
void dlclose(void *p
)
684 const char *dlerror(void)
689 typedef struct TCCSyms
{
694 #define TCCSYM(a) { #a, &a, },
696 /* add the symbol you want here if no dynamic linking is done */
697 static TCCSyms tcc_syms
[] = {
698 #if !defined(CONFIG_TCCBOOT)
707 ST_FUNC
void *resolve_sym(TCCState
*s1
, const char *symbol
)
711 while (p
->str
!= NULL
) {
712 if (!strcmp(p
->str
, symbol
))
719 #elif !defined(_WIN32)
721 ST_FUNC
void *resolve_sym(TCCState
*s1
, const char *sym
)
723 return dlsym(RTLD_DEFAULT
, sym
);
726 #endif /* CONFIG_TCC_STATIC */
728 /* ------------------------------------------------------------- */