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. */
65 s1
->write_mem
= mmap (NULL
, ret
, PROT_READ
|PROT_WRITE
,
66 MAP_PRIVATE
|MAP_ANONYMOUS
, -1, 0);
67 if (s1
->write_mem
== MAP_FAILED
)
68 tcc_error("mmap not writeable");
70 s1
->runtime_mem
= mmap (NULL
, ret
, PROT_READ
|PROT_EXEC
,
71 MAP_PRIVATE
|MAP_ANONYMOUS
, -1, 0);
72 if (s1
->runtime_mem
== MAP_FAILED
)
73 tcc_error("mmap not executable");
75 ret
= tcc_relocate_ex(s1
, s1
->write_mem
);
78 s1
->runtime_mem
= tcc_malloc(ret
);
79 ret
= tcc_relocate_ex(s1
, s1
->runtime_mem
);
84 /* launch the compiled program with the given arguments */
85 LIBTCCAPI
int tcc_run(TCCState
*s1
, int argc
, char **argv
)
87 int (*prog_main
)(int, char **);
90 if (tcc_relocate(s1
, TCC_RELOCATE_AUTO
) < 0)
93 prog_main
= tcc_get_symbol_err(s1
, s1
->runtime_main
);
95 #ifdef CONFIG_TCC_BACKTRACE
97 set_exception_handler();
98 rt_prog_main
= prog_main
;
102 #ifdef CONFIG_TCC_BCHECK
103 if (s1
->do_bounds_check
) {
104 void (*bound_init
)(void);
105 void (*bound_exit
)(void);
106 /* set error function */
107 rt_bound_error_msg
= tcc_get_symbol_err(s1
, "__bound_error_msg");
108 /* XXX: use .init section so that it also work in binary ? */
109 bound_init
= tcc_get_symbol_err(s1
, "__bound_init");
110 bound_exit
= tcc_get_symbol_err(s1
, "__bound_exit");
112 ret
= (*prog_main
)(argc
, argv
);
116 ret
= (*prog_main
)(argc
, argv
);
120 /* relocate code. Return -1 on error, required size if ptr is NULL,
121 otherwise copy code into buffer passed by the caller */
122 static int tcc_relocate_ex(TCCState
*s1
, void *ptr
)
125 unsigned long offset
, length
;
132 pe_output_file(s1
, NULL
);
135 relocate_common_syms();
136 tcc_add_linker_symbols(s1
);
137 build_got_entries(s1
);
143 offset
= 0, mem
= (addr_t
)ptr
;
144 for(i
= 1; i
< s1
->nb_sections
; i
++) {
146 if (0 == (s
->sh_flags
& SHF_ALLOC
))
148 length
= s
->data_offset
;
149 s
->sh_addr
= mem
? (mem
+ offset
+ 15) & ~15 : 0;
150 offset
= (offset
+ length
+ 15) & ~15;
154 /* relocate symbols */
155 relocate_syms(s1
, 1);
159 #ifdef TCC_HAS_RUNTIME_PLTGOT
160 s1
->runtime_plt_and_got_offset
= 0;
161 s1
->runtime_plt_and_got
= (char *)(mem
+ offset
);
162 /* double the size of the buffer for got and plt entries
163 XXX: calculate exact size for them? */
170 /* relocate each section */
171 for(i
= 1; i
< s1
->nb_sections
; i
++) {
174 relocate_section(s1
, s
);
177 for(i
= 1; i
< s1
->nb_sections
; i
++) {
179 if (0 == (s
->sh_flags
& SHF_ALLOC
))
181 length
= s
->data_offset
;
182 // printf("%-12s %08x %04x\n", s->name, s->sh_addr, length);
183 ptr
= (void*)s
->sh_addr
;
184 if (NULL
== s
->data
|| s
->sh_type
== SHT_NOBITS
)
185 memset(ptr
, 0, length
);
187 memcpy(ptr
, s
->data
, length
);
188 /* mark executable sections as executable in memory */
189 if (s
->sh_flags
& SHF_EXECINSTR
)
190 set_pages_executable(ptr
, length
);
193 #ifdef TCC_HAS_RUNTIME_PLTGOT
194 set_pages_executable(s1
->runtime_plt_and_got
,
195 s1
->runtime_plt_and_got_offset
);
199 win64_add_function_table(s1
);
204 /* ------------------------------------------------------------- */
205 /* allow to run code in memory */
207 static void set_pages_executable(void *ptr
, unsigned long length
)
210 unsigned long old_protect
;
211 VirtualProtect(ptr
, length
, PAGE_EXECUTE_READWRITE
, &old_protect
);
214 # define PAGESIZE 4096
217 start
= (addr_t
)ptr
& ~(PAGESIZE
- 1);
218 end
= (addr_t
)ptr
+ length
;
219 end
= (end
+ PAGESIZE
- 1) & ~(PAGESIZE
- 1);
220 mprotect((void *)start
, end
- start
, PROT_READ
| PROT_WRITE
| PROT_EXEC
);
221 __clear_cache(ptr
, ptr
+ length
);
225 /* ------------------------------------------------------------- */
226 #ifdef CONFIG_TCC_BACKTRACE
228 ST_FUNC
void tcc_set_num_callers(int n
)
233 /* print the position in the source file of PC value 'pc' by reading
234 the stabs debug information */
235 static addr_t
rt_printline(addr_t wanted_pc
, const char *msg
)
237 char func_name
[128], last_func_name
[128];
238 addr_t func_addr
, last_pc
, pc
;
239 const char *incl_files
[INCLUDE_STACK_SIZE
];
240 int incl_index
, len
, last_line_num
, i
;
243 Stab_Sym
*stab_sym
= NULL
, *stab_sym_end
, *sym
;
245 char *stab_str
= NULL
;
248 stab_len
= stab_section
->data_offset
;
249 stab_sym
= (Stab_Sym
*)stab_section
->data
;
250 stab_str
= stabstr_section
->data
;
256 last_func_name
[0] = '\0';
257 last_pc
= (addr_t
)-1;
263 stab_sym_end
= (Stab_Sym
*)((char*)stab_sym
+ stab_len
);
264 for (sym
= stab_sym
+ 1; sym
< stab_sym_end
; ++sym
) {
265 switch(sym
->n_type
) {
266 /* function start or end */
268 if (sym
->n_strx
== 0) {
269 /* we test if between last line and end of function */
270 pc
= sym
->n_value
+ func_addr
;
271 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
276 str
= stab_str
+ sym
->n_strx
;
277 p
= strchr(str
, ':');
279 pstrcpy(func_name
, sizeof(func_name
), str
);
282 if (len
> sizeof(func_name
) - 1)
283 len
= sizeof(func_name
) - 1;
284 memcpy(func_name
, str
, len
);
285 func_name
[len
] = '\0';
287 func_addr
= sym
->n_value
;
290 /* line number info */
292 pc
= sym
->n_value
+ func_addr
;
293 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
296 last_line_num
= sym
->n_desc
;
298 strcpy(last_func_name
, func_name
);
302 str
= stab_str
+ sym
->n_strx
;
304 if (incl_index
< INCLUDE_STACK_SIZE
) {
305 incl_files
[incl_index
++] = str
;
313 if (sym
->n_strx
== 0) {
314 incl_index
= 0; /* end of translation unit */
316 str
= stab_str
+ sym
->n_strx
;
317 /* do not add path */
319 if (len
> 0 && str
[len
- 1] != '/')
327 /* second pass: we try symtab symbols (no line number info) */
331 ElfW(Sym
) *sym
, *sym_end
;
334 sym_end
= (ElfW(Sym
) *)(symtab_section
->data
+ symtab_section
->data_offset
);
335 for(sym
= (ElfW(Sym
) *)symtab_section
->data
+ 1;
338 type
= ELFW(ST_TYPE
)(sym
->st_info
);
339 if (type
== STT_FUNC
|| type
== STT_GNU_IFUNC
) {
340 if (wanted_pc
>= sym
->st_value
&&
341 wanted_pc
< sym
->st_value
+ sym
->st_size
) {
342 pstrcpy(last_func_name
, sizeof(last_func_name
),
343 strtab_section
->data
+ sym
->st_name
);
344 func_addr
= sym
->st_value
;
350 /* did not find any info: */
351 fprintf(stderr
, "%s %p ???\n", msg
, (void*)wanted_pc
);
357 fprintf(stderr
, "%s:%d: ", incl_files
[--i
], last_line_num
);
358 fprintf(stderr
, "%s %p", msg
, (void*)wanted_pc
);
359 if (last_func_name
[0] != '\0')
360 fprintf(stderr
, " %s()", last_func_name
);
362 fprintf(stderr
, " (included from ");
364 fprintf(stderr
, "%s", incl_files
[i
]);
367 fprintf(stderr
, ", ");
369 fprintf(stderr
, ")");
371 fprintf(stderr
, "\n");
376 /* emit a run time error at position 'pc' */
377 static void rt_error(ucontext_t
*uc
, const char *fmt
, ...)
383 fprintf(stderr
, "Runtime error: ");
385 vfprintf(stderr
, fmt
, ap
);
387 fprintf(stderr
, "\n");
389 for(i
=0;i
<rt_num_callers
;i
++) {
390 if (rt_get_caller_pc(&pc
, uc
, i
) < 0)
392 pc
= rt_printline(pc
, i
? "by" : "at");
393 if (pc
== (addr_t
)rt_prog_main
&& pc
)
398 /* ------------------------------------------------------------- */
401 /* signal handler for fatal errors */
402 static void sig_error(int signum
, siginfo_t
*siginf
, void *puc
)
404 ucontext_t
*uc
= puc
;
408 switch(siginf
->si_code
) {
411 rt_error(uc
, "division by zero");
414 rt_error(uc
, "floating point exception");
420 if (rt_bound_error_msg
&& *rt_bound_error_msg
)
421 rt_error(uc
, *rt_bound_error_msg
);
423 rt_error(uc
, "dereferencing invalid pointer");
426 rt_error(uc
, "illegal instruction");
429 rt_error(uc
, "abort() called");
432 rt_error(uc
, "caught signal %d", signum
);
439 # define SA_SIGINFO 0x00000004u
442 /* Generate a stack backtrace when a CPU exception occurs. */
443 static void set_exception_handler(void)
445 struct sigaction sigact
;
446 /* install TCC signal handlers to print debug info on fatal
448 sigact
.sa_flags
= SA_SIGINFO
| SA_RESETHAND
;
449 sigact
.sa_sigaction
= sig_error
;
450 sigemptyset(&sigact
.sa_mask
);
451 sigaction(SIGFPE
, &sigact
, NULL
);
452 sigaction(SIGILL
, &sigact
, NULL
);
453 sigaction(SIGSEGV
, &sigact
, NULL
);
454 sigaction(SIGBUS
, &sigact
, NULL
);
455 sigaction(SIGABRT
, &sigact
, NULL
);
458 /* ------------------------------------------------------------- */
461 /* fix for glibc 2.1 */
467 /* return the PC at frame level 'level'. Return negative if not found */
468 static int rt_get_caller_pc(addr_t
*paddr
, ucontext_t
*uc
, int level
)
474 #if defined(__APPLE__)
475 *paddr
= uc
->uc_mcontext
->__ss
.__eip
;
476 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
477 *paddr
= uc
->uc_mcontext
.mc_eip
;
478 #elif defined(__dietlibc__)
479 *paddr
= uc
->uc_mcontext
.eip
;
481 *paddr
= uc
->uc_mcontext
.gregs
[REG_EIP
];
485 #if defined(__APPLE__)
486 fp
= uc
->uc_mcontext
->__ss
.__ebp
;
487 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
488 fp
= uc
->uc_mcontext
.mc_ebp
;
489 #elif defined(__dietlibc__)
490 fp
= uc
->uc_mcontext
.ebp
;
492 fp
= uc
->uc_mcontext
.gregs
[REG_EBP
];
494 for(i
=1;i
<level
;i
++) {
495 /* XXX: check address validity with program info */
496 if (fp
<= 0x1000 || fp
>= 0xc0000000)
498 fp
= ((addr_t
*)fp
)[0];
500 *paddr
= ((addr_t
*)fp
)[1];
505 /* ------------------------------------------------------------- */
506 #elif defined(__x86_64__)
508 /* return the PC at frame level 'level'. Return negative if not found */
509 static int rt_get_caller_pc(addr_t
*paddr
, ucontext_t
*uc
, int level
)
515 /* XXX: only support linux */
516 #if defined(__APPLE__)
517 *paddr
= uc
->uc_mcontext
->__ss
.__rip
;
518 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
519 *paddr
= uc
->uc_mcontext
.mc_rip
;
521 *paddr
= uc
->uc_mcontext
.gregs
[REG_RIP
];
525 #if defined(__APPLE__)
526 fp
= uc
->uc_mcontext
->__ss
.__rbp
;
527 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
528 fp
= uc
->uc_mcontext
.mc_rbp
;
530 fp
= uc
->uc_mcontext
.gregs
[REG_RBP
];
532 for(i
=1;i
<level
;i
++) {
533 /* XXX: check address validity with program info */
536 fp
= ((addr_t
*)fp
)[0];
538 *paddr
= ((addr_t
*)fp
)[1];
543 /* ------------------------------------------------------------- */
544 #elif defined(__arm__)
546 /* return the PC at frame level 'level'. Return negative if not found */
547 static int rt_get_caller_pc(addr_t
*paddr
, ucontext_t
*uc
, int level
)
553 /* XXX: only supports linux */
554 #if defined(__linux__)
555 *paddr
= uc
->uc_mcontext
.arm_pc
;
561 #if defined(__linux__)
562 fp
= uc
->uc_mcontext
.arm_fp
;
563 sp
= uc
->uc_mcontext
.arm_sp
;
569 /* XXX: specific to tinycc stack frames */
570 if (fp
< sp
+ 12 || fp
& 3)
572 for(i
= 1; i
< level
; i
++) {
573 sp
= ((addr_t
*)fp
)[-2];
574 if (sp
< fp
|| sp
- fp
> 16 || sp
& 3)
576 fp
= ((addr_t
*)fp
)[-3];
577 if (fp
<= sp
|| fp
- sp
< 12 || fp
& 3)
580 /* XXX: check address validity with program info */
581 *paddr
= ((addr_t
*)fp
)[-1];
586 /* ------------------------------------------------------------- */
589 #warning add arch specific rt_get_caller_pc()
590 static int rt_get_caller_pc(addr_t
*paddr
, ucontext_t
*uc
, int level
)
595 #endif /* !__i386__ */
597 /* ------------------------------------------------------------- */
600 static long __stdcall
cpu_exception_handler(EXCEPTION_POINTERS
*ex_info
)
602 EXCEPTION_RECORD
*er
= ex_info
->ExceptionRecord
;
603 CONTEXT
*uc
= ex_info
->ContextRecord
;
604 switch (er
->ExceptionCode
) {
605 case EXCEPTION_ACCESS_VIOLATION
:
606 if (rt_bound_error_msg
&& *rt_bound_error_msg
)
607 rt_error(uc
, *rt_bound_error_msg
);
609 rt_error(uc
, "access violation");
611 case EXCEPTION_STACK_OVERFLOW
:
612 rt_error(uc
, "stack overflow");
614 case EXCEPTION_INT_DIVIDE_BY_ZERO
:
615 rt_error(uc
, "division by zero");
618 rt_error(uc
, "exception caught");
621 return EXCEPTION_EXECUTE_HANDLER
;
624 /* Generate a stack backtrace when a CPU exception occurs. */
625 static void set_exception_handler(void)
627 SetUnhandledExceptionFilter(cpu_exception_handler
);
631 static void win64_add_function_table(TCCState
*s1
)
634 (RUNTIME_FUNCTION
*)s1
->uw_pdata
->sh_addr
,
635 s1
->uw_pdata
->data_offset
/ sizeof (RUNTIME_FUNCTION
),
636 text_section
->sh_addr
641 /* return the PC at frame level 'level'. Return non zero if not found */
642 static int rt_get_caller_pc(addr_t
*paddr
, CONTEXT
*uc
, int level
)
654 for(i
=1;i
<level
;i
++) {
655 /* XXX: check address validity with program info */
656 if (fp
<= 0x1000 || fp
>= 0xc0000000)
658 fp
= ((addr_t
*)fp
)[0];
660 pc
= ((addr_t
*)fp
)[1];
667 #endif /* CONFIG_TCC_BACKTRACE */
668 /* ------------------------------------------------------------- */
669 #ifdef CONFIG_TCC_STATIC
671 /* dummy function for profiling */
672 ST_FUNC
void *dlopen(const char *filename
, int flag
)
677 ST_FUNC
void dlclose(void *p
)
681 ST_FUNC
const char *dlerror(void)
686 typedef struct TCCSyms
{
692 /* add the symbol you want here if no dynamic linking is done */
693 static TCCSyms tcc_syms
[] = {
694 #if !defined(CONFIG_TCCBOOT)
695 #define TCCSYM(a) { #a, &a, },
705 ST_FUNC
void *resolve_sym(TCCState
*s1
, const char *symbol
)
709 while (p
->str
!= NULL
) {
710 if (!strcmp(p
->str
, symbol
))
717 #elif !defined(_WIN32)
719 ST_FUNC
void *resolve_sym(TCCState
*s1
, const char *sym
)
721 return dlsym(RTLD_DEFAULT
, sym
);
724 #endif /* CONFIG_TCC_STATIC */
725 #endif /* TCC_IS_NATIVE */
726 /* ------------------------------------------------------------- */