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
24 #define ucontext_t CONTEXT
27 static void set_pages_executable(void *ptr
, unsigned long length
);
28 static void set_exception_handler(void);
29 static int rt_get_caller_pc(uplong
*paddr
, ucontext_t
*uc
, int level
);
30 static void rt_error(ucontext_t
*uc
, const char *fmt
, ...);
31 static int tcc_relocate_ex(TCCState
*s1
, void *ptr
);
33 /* ------------------------------------------------------------- */
34 /* Do all relocations (needed before using tcc_get_symbol())
35 Returns -1 on error. */
37 int tcc_relocate(TCCState
*s1
)
41 /* Use mmap instead of malloc for Selinux
42 Ref http://www.gnu.org/s/libc/manual/html_node/File-Size.html */
43 char tmpfname
[] = "/tmp/.tccrunXXXXXX";
44 int fd
= mkstemp (tmpfname
);
45 if ((ret
= tcc_relocate_ex(s1
,NULL
)) < 0)return -1;
47 unlink (tmpfname
); ftruncate (fd
, s1
->mem_size
);
48 s1
->write_mem
= mmap (NULL
, ret
, PROT_READ
|PROT_WRITE
,
50 if(s1
->write_mem
== MAP_FAILED
){
51 error("/tmp not writeable");
54 s1
->runtime_mem
= mmap (NULL
, ret
, PROT_READ
|PROT_EXEC
,
56 if(s1
->runtime_mem
== MAP_FAILED
){
57 error("/tmp not executable");
60 ret
= tcc_relocate_ex(s1
, s1
->write_mem
);
62 ret
= tcc_relocate_ex(s1
, NULL
);
64 s1
->runtime_mem
= tcc_malloc(ret
);
65 ret
= tcc_relocate_ex(s1
, s1
->runtime_mem
);
71 /* launch the compiled program with the given arguments */
72 int tcc_run(TCCState
*s1
, int argc
, char **argv
)
74 int (*prog_main
)(int, char **);
76 if (tcc_relocate(s1
) < 0)
79 prog_main
= tcc_get_symbol_err(s1
, "main");
81 #ifdef CONFIG_TCC_BACKTRACE
83 set_exception_handler();
86 #ifdef CONFIG_TCC_BCHECK
87 if (s1
->do_bounds_check
) {
88 void (*bound_init
)(void);
89 void (*bound_exit
)(void);
91 /* set error function */
92 rt_bound_error_msg
= tcc_get_symbol_err(s1
, "__bound_error_msg");
93 rt_prog_main
= prog_main
;
94 /* XXX: use .init section so that it also work in binary ? */
95 bound_init
= tcc_get_symbol_err(s1
, "__bound_init");
96 bound_exit
= tcc_get_symbol_err(s1
, "__bound_exit");
98 ret
= (*prog_main
)(argc
, argv
);
106 unsigned char *p
= tcc_get_symbol(s1
, "tinyc_no_getbp");
110 return (*prog_main
)(argc
, argv
);
114 /* relocate code. Return -1 on error, required size if ptr is NULL,
115 otherwise copy code into buffer passed by the caller */
116 static int tcc_relocate_ex(TCCState
*s1
, void *ptr
)
119 unsigned long offset
, length
;
123 if (0 == s1
->runtime_added
) {
124 s1
->runtime_added
= 1;
127 pe_output_file(s1
, NULL
);
130 relocate_common_syms();
131 tcc_add_linker_symbols(s1
);
132 build_got_entries(s1
);
138 offset
= 0, mem
= (uplong
)ptr
;
139 for(i
= 1; i
< s1
->nb_sections
; i
++) {
141 if (0 == (s
->sh_flags
& SHF_ALLOC
))
143 length
= s
->data_offset
;
144 s
->sh_addr
= mem
? (mem
+ offset
+ 15) & ~15 : 0;
145 offset
= (offset
+ length
+ 15) & ~15;
149 /* relocate symbols */
150 relocate_syms(s1
, 1);
154 #if (defined TCC_TARGET_X86_64 || defined TCC_TARGET_ARM) && !defined TCC_TARGET_PE
155 s1
->runtime_plt_and_got_offset
= 0;
156 s1
->runtime_plt_and_got
= (char *)(mem
+ offset
);
157 /* double the size of the buffer for got and plt entries
158 XXX: calculate exact size for them? */
165 /* relocate each section */
166 for(i
= 1; i
< s1
->nb_sections
; i
++) {
169 relocate_section(s1
, s
);
172 for(i
= 1; i
< s1
->nb_sections
; i
++) {
174 if (0 == (s
->sh_flags
& SHF_ALLOC
))
176 length
= s
->data_offset
;
177 // printf("%-12s %08x %04x\n", s->name, s->sh_addr, length);
178 ptr
= (void*)(uplong
)s
->sh_addr
;
179 if (NULL
== s
->data
|| s
->sh_type
== SHT_NOBITS
)
180 memset(ptr
, 0, length
);
182 memcpy(ptr
, s
->data
, length
);
183 /* mark executable sections as executable in memory */
184 if (s
->sh_flags
& SHF_EXECINSTR
)
185 set_pages_executable(ptr
, length
);
188 #if (defined TCC_TARGET_X86_64 || defined TCC_TARGET_ARM) && !defined TCC_TARGET_PE
189 set_pages_executable(s1
->runtime_plt_and_got
,
190 s1
->runtime_plt_and_got_offset
);
195 /* ------------------------------------------------------------- */
196 /* allow to run code in memory */
198 static void set_pages_executable(void *ptr
, unsigned long length
)
201 unsigned long old_protect
;
202 VirtualProtect(ptr
, length
, PAGE_EXECUTE_READWRITE
, &old_protect
);
204 unsigned long start
, end
;
205 start
= (uplong
)ptr
& ~(PAGESIZE
- 1);
206 end
= (uplong
)ptr
+ length
;
207 end
= (end
+ PAGESIZE
- 1) & ~(PAGESIZE
- 1);
208 mprotect((void *)start
, end
- start
, PROT_READ
| PROT_WRITE
| PROT_EXEC
);
212 /* ------------------------------------------------------------- */
213 #ifdef CONFIG_TCC_BACKTRACE
215 /* print the position in the source file of PC value 'pc' by reading
216 the stabs debug information */
217 static uplong
rt_printline(uplong wanted_pc
)
219 Stab_Sym
*sym
, *sym_end
;
220 char func_name
[128], last_func_name
[128];
221 unsigned long func_addr
, last_pc
, pc
;
222 const char *incl_files
[INCLUDE_STACK_SIZE
];
223 int incl_index
, len
, last_line_num
, i
;
226 fprintf(stderr
, "0x%08lx:", (unsigned long)wanted_pc
);
231 last_func_name
[0] = '\0';
232 last_pc
= 0xffffffff;
234 sym
= (Stab_Sym
*)stab_section
->data
+ 1;
235 sym_end
= (Stab_Sym
*)(stab_section
->data
+ stab_section
->data_offset
);
236 while (sym
< sym_end
) {
237 switch(sym
->n_type
) {
238 /* function start or end */
240 if (sym
->n_strx
== 0) {
241 /* we test if between last line and end of function */
242 pc
= sym
->n_value
+ func_addr
;
243 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
248 str
= stabstr_section
->data
+ sym
->n_strx
;
249 p
= strchr(str
, ':');
251 pstrcpy(func_name
, sizeof(func_name
), str
);
254 if (len
> sizeof(func_name
) - 1)
255 len
= sizeof(func_name
) - 1;
256 memcpy(func_name
, str
, len
);
257 func_name
[len
] = '\0';
259 func_addr
= sym
->n_value
;
262 /* line number info */
264 pc
= sym
->n_value
+ func_addr
;
265 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
268 last_line_num
= sym
->n_desc
;
270 strcpy(last_func_name
, func_name
);
274 str
= stabstr_section
->data
+ sym
->n_strx
;
276 if (incl_index
< INCLUDE_STACK_SIZE
) {
277 incl_files
[incl_index
++] = str
;
285 if (sym
->n_strx
== 0) {
286 incl_index
= 0; /* end of translation unit */
288 str
= stabstr_section
->data
+ sym
->n_strx
;
289 /* do not add path */
291 if (len
> 0 && str
[len
- 1] != '/')
299 /* second pass: we try symtab symbols (no line number info) */
302 ElfW(Sym
) *sym
, *sym_end
;
305 sym_end
= (ElfW(Sym
) *)(symtab_section
->data
+ symtab_section
->data_offset
);
306 for(sym
= (ElfW(Sym
) *)symtab_section
->data
+ 1;
309 type
= ELFW(ST_TYPE
)(sym
->st_info
);
310 if (type
== STT_FUNC
|| type
== STT_GNU_IFUNC
) {
311 if (wanted_pc
>= sym
->st_value
&&
312 wanted_pc
< sym
->st_value
+ sym
->st_size
) {
313 pstrcpy(last_func_name
, sizeof(last_func_name
),
314 strtab_section
->data
+ sym
->st_name
);
315 func_addr
= sym
->st_value
;
321 /* did not find any info: */
322 fprintf(stderr
, " ???\n");
325 if (last_func_name
[0] != '\0') {
326 fprintf(stderr
, " %s()", last_func_name
);
328 if (incl_index
> 0) {
329 fprintf(stderr
, " (%s:%d",
330 incl_files
[incl_index
- 1], last_line_num
);
331 for(i
= incl_index
- 2; i
>= 0; i
--)
332 fprintf(stderr
, ", included from %s", incl_files
[i
]);
333 fprintf(stderr
, ")");
335 fprintf(stderr
, "\n");
339 /* emit a run time error at position 'pc' */
340 static void rt_error(ucontext_t
*uc
, const char *fmt
, ...)
347 fprintf(stderr
, "Runtime error: ");
348 vfprintf(stderr
, fmt
, ap
);
349 fprintf(stderr
, "\n");
351 for(i
=0;i
<num_callers
;i
++) {
352 if (rt_get_caller_pc(&pc
, uc
, i
) < 0)
355 fprintf(stderr
, "at ");
357 fprintf(stderr
, "by ");
358 pc
= rt_printline(pc
);
359 if (pc
== (uplong
)rt_prog_main
&& pc
)
366 /* ------------------------------------------------------------- */
369 /* signal handler for fatal errors */
370 static void sig_error(int signum
, siginfo_t
*siginf
, void *puc
)
372 ucontext_t
*uc
= puc
;
376 switch(siginf
->si_code
) {
379 rt_error(uc
, "division by zero");
382 rt_error(uc
, "floating point exception");
388 if (rt_bound_error_msg
&& *rt_bound_error_msg
)
389 rt_error(uc
, *rt_bound_error_msg
);
391 rt_error(uc
, "dereferencing invalid pointer");
394 rt_error(uc
, "illegal instruction");
397 rt_error(uc
, "abort() called");
400 rt_error(uc
, "caught signal %d", signum
);
406 /* Generate a stack backtrace when a CPU exception occurs. */
407 static void set_exception_handler(void)
409 struct sigaction sigact
;
410 /* install TCC signal handlers to print debug info on fatal
412 sigact
.sa_flags
= SA_SIGINFO
| SA_RESETHAND
;
413 sigact
.sa_sigaction
= sig_error
;
414 sigemptyset(&sigact
.sa_mask
);
415 sigaction(SIGFPE
, &sigact
, NULL
);
416 sigaction(SIGILL
, &sigact
, NULL
);
417 sigaction(SIGSEGV
, &sigact
, NULL
);
418 sigaction(SIGBUS
, &sigact
, NULL
);
419 sigaction(SIGABRT
, &sigact
, NULL
);
422 /* ------------------------------------------------------------- */
425 /* fix for glibc 2.1 */
431 /* return the PC at frame level 'level'. Return non zero if not found */
432 static int rt_get_caller_pc(unsigned long *paddr
, ucontext_t
*uc
, int level
)
438 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
439 *paddr
= uc
->uc_mcontext
.mc_eip
;
440 #elif defined(__dietlibc__)
441 *paddr
= uc
->uc_mcontext
.eip
;
443 *paddr
= uc
->uc_mcontext
.gregs
[REG_EIP
];
447 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
448 fp
= uc
->uc_mcontext
.mc_ebp
;
449 #elif defined(__dietlibc__)
450 fp
= uc
->uc_mcontext
.ebp
;
452 fp
= uc
->uc_mcontext
.gregs
[REG_EBP
];
454 for(i
=1;i
<level
;i
++) {
455 /* XXX: check address validity with program info */
456 if (fp
<= 0x1000 || fp
>= 0xc0000000)
458 fp
= ((unsigned long *)fp
)[0];
460 *paddr
= ((unsigned long *)fp
)[1];
465 /* ------------------------------------------------------------- */
466 #elif defined(__x86_64__)
468 /* return the PC at frame level 'level'. Return non zero if not found */
469 static int rt_get_caller_pc(unsigned long *paddr
,
470 ucontext_t
*uc
, int level
)
476 /* XXX: only support linux */
477 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
478 *paddr
= uc
->uc_mcontext
.mc_rip
;
480 *paddr
= uc
->uc_mcontext
.gregs
[REG_RIP
];
484 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
485 fp
= uc
->uc_mcontext
.mc_rbp
;
487 fp
= uc
->uc_mcontext
.gregs
[REG_RBP
];
489 for(i
=1;i
<level
;i
++) {
490 /* XXX: check address validity with program info */
493 fp
= ((unsigned long *)fp
)[0];
495 *paddr
= ((unsigned long *)fp
)[1];
500 /* ------------------------------------------------------------- */
501 #elif defined(__arm__)
503 /* return the PC at frame level 'level'. Return negative if not found */
504 static int rt_get_caller_pc(unsigned long *paddr
,
505 ucontext_t
*uc
, int level
)
511 /* XXX: only supports linux */
512 #if defined(__linux__)
513 *paddr
= uc
->uc_mcontext
.arm_pc
;
519 #if defined(__linux__)
520 fp
= uc
->uc_mcontext
.arm_fp
;
521 sp
= uc
->uc_mcontext
.arm_sp
;
527 /* XXX: specific to tinycc stack frames */
528 if (fp
< sp
+ 12 || fp
& 3)
530 for(i
= 1; i
< level
; i
++) {
531 sp
= ((uint32_t *)fp
)[-2];
532 if (sp
< fp
|| sp
- fp
> 16 || sp
& 3)
534 fp
= ((uint32_t *)fp
)[-3];
535 if (fp
<= sp
|| fp
- sp
< 12 || fp
& 3)
538 /* XXX: check address validity with program info */
539 *paddr
= ((uint32_t *)fp
)[-1];
544 /* ------------------------------------------------------------- */
547 #warning add arch specific rt_get_caller_pc()
548 static int rt_get_caller_pc(unsigned long *paddr
,
549 ucontext_t
*uc
, int level
)
554 #endif /* !__i386__ */
556 /* ------------------------------------------------------------- */
559 static long __stdcall
cpu_exception_handler(EXCEPTION_POINTERS
*ex_info
)
561 CONTEXT
*uc
= ex_info
->ContextRecord
;
563 EXCEPTION_RECORD *er = ex_info->ExceptionRecord;
564 printf("CPU exception: code=%08lx addr=%p\n",
565 er->ExceptionCode, er->ExceptionAddress);
567 if (rt_bound_error_msg
&& *rt_bound_error_msg
)
568 rt_error(uc
, *rt_bound_error_msg
);
570 rt_error(uc
, "dereferencing invalid pointer");
572 //return EXCEPTION_CONTINUE_SEARCH;
575 /* Generate a stack backtrace when a CPU exception occurs. */
576 static void set_exception_handler(void)
578 SetUnhandledExceptionFilter(cpu_exception_handler
);
586 /* return the PC at frame level 'level'. Return non zero if not found */
587 static int rt_get_caller_pc(uplong
*paddr
, CONTEXT
*uc
, int level
)
597 for(i
=1;i
<level
;i
++) {
598 /* XXX: check address validity with program info */
599 if (fp
<= 0x1000 || fp
>= 0xc0000000)
601 fp
= ((uplong
*)fp
)[0];
603 *paddr
= ((uplong
*)fp
)[1];
612 #endif /* CONFIG_TCC_BACKTRACE */
613 /* ------------------------------------------------------------- */
615 #ifdef CONFIG_TCC_STATIC
617 #define RTLD_LAZY 0x001
618 #define RTLD_NOW 0x002
619 #define RTLD_GLOBAL 0x100
620 #define RTLD_DEFAULT NULL
622 /* dummy function for profiling */
623 void *dlopen(const char *filename
, int flag
)
628 void dlclose(void *p
)
632 const char *dlerror(void)
637 typedef struct TCCSyms
{
642 #define TCCSYM(a) { #a, &a, },
644 /* add the symbol you want here if no dynamic linking is done */
645 static TCCSyms tcc_syms
[] = {
646 #if !defined(CONFIG_TCCBOOT)
655 void *resolve_sym(TCCState
*s1
, const char *symbol
)
659 while (p
->str
!= NULL
) {
660 if (!strcmp(p
->str
, symbol
))
667 #elif !defined(_WIN32)
669 void *resolve_sym(TCCState
*s1
, const char *sym
)
671 return dlsym(RTLD_DEFAULT
, sym
);
674 #endif /* CONFIG_TCC_STATIC */
676 /* ------------------------------------------------------------- */