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 char tmpfname
[] = "/tmp/.tccrunXXXXXX";
42 int fd
= mkstemp (tmpfname
);
43 unlink (tmpfname
); ftruncate (fd
, 1000);
44 if ((ret
= tcc_relocate_ex(s1
,NULL
)) < 0)return -1;
46 /* Use mmap instead of malloc for Selinux */
47 s1
->write_mem
= mmap (NULL
, ret
, PROT_READ
|PROT_WRITE
,
49 if(s1
->write_mem
== MAP_FAILED
){
50 error("/tmp not writeable");
53 s1
->runtime_mem
= mmap (NULL
, ret
, PROT_READ
|PROT_EXEC
,
55 if(s1
->runtime_mem
== MAP_FAILED
){
56 error("/tmp not executable");
59 ret
= tcc_relocate_ex(s1
, s1
->write_mem
);
61 ret
= tcc_relocate_ex(s1
, NULL
);
63 s1
->runtime_mem
= tcc_malloc(ret
);
64 ret
= tcc_relocate_ex(s1
, s1
->runtime_mem
);
70 /* launch the compiled program with the given arguments */
71 int tcc_run(TCCState
*s1
, int argc
, char **argv
)
73 int (*prog_main
)(int, char **);
75 if (tcc_relocate(s1
) < 0)
78 prog_main
= tcc_get_symbol_err(s1
, "main");
80 #ifdef CONFIG_TCC_BACKTRACE
82 set_exception_handler();
85 #ifdef CONFIG_TCC_BCHECK
86 if (s1
->do_bounds_check
) {
87 void (*bound_init
)(void);
88 void (*bound_exit
)(void);
90 /* set error function */
91 rt_bound_error_msg
= tcc_get_symbol_err(s1
, "__bound_error_msg");
92 rt_prog_main
= prog_main
;
93 /* XXX: use .init section so that it also work in binary ? */
94 bound_init
= tcc_get_symbol_err(s1
, "__bound_init");
95 bound_exit
= tcc_get_symbol_err(s1
, "__bound_exit");
97 ret
= (*prog_main
)(argc
, argv
);
105 unsigned char *p
= tcc_get_symbol(s1
, "tinyc_no_getbp");
109 return (*prog_main
)(argc
, argv
);
113 /* relocate code. Return -1 on error, required size if ptr is NULL,
114 otherwise copy code into buffer passed by the caller */
115 static int tcc_relocate_ex(TCCState
*s1
, void *ptr
)
118 unsigned long offset
, length
;
122 if (0 == s1
->runtime_added
) {
123 s1
->runtime_added
= 1;
126 pe_output_file(s1
, NULL
);
129 relocate_common_syms();
130 tcc_add_linker_symbols(s1
);
131 build_got_entries(s1
);
137 offset
= 0, mem
= (uplong
)ptr
;
138 for(i
= 1; i
< s1
->nb_sections
; i
++) {
140 if (0 == (s
->sh_flags
& SHF_ALLOC
))
142 length
= s
->data_offset
;
143 s
->sh_addr
= mem
? (mem
+ offset
+ 15) & ~15 : 0;
144 offset
= (offset
+ length
+ 15) & ~15;
148 /* relocate symbols */
149 relocate_syms(s1
, 1);
153 #if (defined TCC_TARGET_X86_64 || defined TCC_TARGET_ARM) && !defined TCC_TARGET_PE
154 s1
->runtime_plt_and_got_offset
= 0;
155 s1
->runtime_plt_and_got
= (char *)(mem
+ offset
);
156 /* double the size of the buffer for got and plt entries
157 XXX: calculate exact size for them? */
164 /* relocate each section */
165 for(i
= 1; i
< s1
->nb_sections
; i
++) {
168 relocate_section(s1
, s
);
171 for(i
= 1; i
< s1
->nb_sections
; i
++) {
173 if (0 == (s
->sh_flags
& SHF_ALLOC
))
175 length
= s
->data_offset
;
176 // printf("%-12s %08x %04x\n", s->name, s->sh_addr, length);
177 ptr
= (void*)(uplong
)s
->sh_addr
;
178 if (NULL
== s
->data
|| s
->sh_type
== SHT_NOBITS
)
179 memset(ptr
, 0, length
);
181 memcpy(ptr
, s
->data
, length
);
182 /* mark executable sections as executable in memory */
183 if (s
->sh_flags
& SHF_EXECINSTR
)
184 set_pages_executable(ptr
, length
);
187 #if (defined TCC_TARGET_X86_64 || defined TCC_TARGET_ARM) && !defined TCC_TARGET_PE
188 set_pages_executable(s1
->runtime_plt_and_got
,
189 s1
->runtime_plt_and_got_offset
);
194 /* ------------------------------------------------------------- */
195 /* allow to run code in memory */
197 static void set_pages_executable(void *ptr
, unsigned long length
)
200 unsigned long old_protect
;
201 VirtualProtect(ptr
, length
, PAGE_EXECUTE_READWRITE
, &old_protect
);
203 unsigned long start
, end
;
204 start
= (uplong
)ptr
& ~(PAGESIZE
- 1);
205 end
= (uplong
)ptr
+ length
;
206 end
= (end
+ PAGESIZE
- 1) & ~(PAGESIZE
- 1);
207 mprotect((void *)start
, end
- start
, PROT_READ
| PROT_WRITE
| PROT_EXEC
);
211 /* ------------------------------------------------------------- */
212 #ifdef CONFIG_TCC_BACKTRACE
214 /* print the position in the source file of PC value 'pc' by reading
215 the stabs debug information */
216 static uplong
rt_printline(uplong wanted_pc
)
218 Stab_Sym
*sym
, *sym_end
;
219 char func_name
[128], last_func_name
[128];
220 unsigned long func_addr
, last_pc
, pc
;
221 const char *incl_files
[INCLUDE_STACK_SIZE
];
222 int incl_index
, len
, last_line_num
, i
;
225 fprintf(stderr
, "0x%08lx:", (unsigned long)wanted_pc
);
230 last_func_name
[0] = '\0';
231 last_pc
= 0xffffffff;
233 sym
= (Stab_Sym
*)stab_section
->data
+ 1;
234 sym_end
= (Stab_Sym
*)(stab_section
->data
+ stab_section
->data_offset
);
235 while (sym
< sym_end
) {
236 switch(sym
->n_type
) {
237 /* function start or end */
239 if (sym
->n_strx
== 0) {
240 /* we test if between last line and end of function */
241 pc
= sym
->n_value
+ func_addr
;
242 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
247 str
= stabstr_section
->data
+ sym
->n_strx
;
248 p
= strchr(str
, ':');
250 pstrcpy(func_name
, sizeof(func_name
), str
);
253 if (len
> sizeof(func_name
) - 1)
254 len
= sizeof(func_name
) - 1;
255 memcpy(func_name
, str
, len
);
256 func_name
[len
] = '\0';
258 func_addr
= sym
->n_value
;
261 /* line number info */
263 pc
= sym
->n_value
+ func_addr
;
264 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
267 last_line_num
= sym
->n_desc
;
269 strcpy(last_func_name
, func_name
);
273 str
= stabstr_section
->data
+ sym
->n_strx
;
275 if (incl_index
< INCLUDE_STACK_SIZE
) {
276 incl_files
[incl_index
++] = str
;
284 if (sym
->n_strx
== 0) {
285 incl_index
= 0; /* end of translation unit */
287 str
= stabstr_section
->data
+ sym
->n_strx
;
288 /* do not add path */
290 if (len
> 0 && str
[len
- 1] != '/')
298 /* second pass: we try symtab symbols (no line number info) */
301 ElfW(Sym
) *sym
, *sym_end
;
304 sym_end
= (ElfW(Sym
) *)(symtab_section
->data
+ symtab_section
->data_offset
);
305 for(sym
= (ElfW(Sym
) *)symtab_section
->data
+ 1;
308 type
= ELFW(ST_TYPE
)(sym
->st_info
);
311 || type
== STT_GNU_IFUNC
314 if (wanted_pc
>= sym
->st_value
&&
315 wanted_pc
< sym
->st_value
+ sym
->st_size
) {
316 pstrcpy(last_func_name
, sizeof(last_func_name
),
317 strtab_section
->data
+ sym
->st_name
);
318 func_addr
= sym
->st_value
;
324 /* did not find any info: */
325 fprintf(stderr
, " ???\n");
328 if (last_func_name
[0] != '\0') {
329 fprintf(stderr
, " %s()", last_func_name
);
331 if (incl_index
> 0) {
332 fprintf(stderr
, " (%s:%d",
333 incl_files
[incl_index
- 1], last_line_num
);
334 for(i
= incl_index
- 2; i
>= 0; i
--)
335 fprintf(stderr
, ", included from %s", incl_files
[i
]);
336 fprintf(stderr
, ")");
338 fprintf(stderr
, "\n");
342 /* emit a run time error at position 'pc' */
343 static void rt_error(ucontext_t
*uc
, const char *fmt
, ...)
350 fprintf(stderr
, "Runtime error: ");
351 vfprintf(stderr
, fmt
, ap
);
352 fprintf(stderr
, "\n");
354 for(i
=0;i
<num_callers
;i
++) {
355 if (rt_get_caller_pc(&pc
, uc
, i
) < 0)
358 fprintf(stderr
, "at ");
360 fprintf(stderr
, "by ");
361 pc
= rt_printline(pc
);
362 if (pc
== (uplong
)rt_prog_main
&& pc
)
369 /* ------------------------------------------------------------- */
372 /* signal handler for fatal errors */
373 static void sig_error(int signum
, siginfo_t
*siginf
, void *puc
)
375 ucontext_t
*uc
= puc
;
379 switch(siginf
->si_code
) {
382 rt_error(uc
, "division by zero");
385 rt_error(uc
, "floating point exception");
391 if (rt_bound_error_msg
&& *rt_bound_error_msg
)
392 rt_error(uc
, *rt_bound_error_msg
);
394 rt_error(uc
, "dereferencing invalid pointer");
397 rt_error(uc
, "illegal instruction");
400 rt_error(uc
, "abort() called");
403 rt_error(uc
, "caught signal %d", signum
);
409 /* Generate a stack backtrace when a CPU exception occurs. */
410 static void set_exception_handler(void)
412 struct sigaction sigact
;
413 /* install TCC signal handlers to print debug info on fatal
415 sigact
.sa_flags
= SA_SIGINFO
| SA_RESETHAND
;
416 sigact
.sa_sigaction
= sig_error
;
417 sigemptyset(&sigact
.sa_mask
);
418 sigaction(SIGFPE
, &sigact
, NULL
);
419 sigaction(SIGILL
, &sigact
, NULL
);
420 sigaction(SIGSEGV
, &sigact
, NULL
);
421 sigaction(SIGBUS
, &sigact
, NULL
);
422 sigaction(SIGABRT
, &sigact
, NULL
);
425 /* ------------------------------------------------------------- */
428 /* fix for glibc 2.1 */
434 /* return the PC at frame level 'level'. Return non zero if not found */
435 static int rt_get_caller_pc(unsigned long *paddr
, ucontext_t
*uc
, int level
)
441 #if defined(__FreeBSD__)
442 *paddr
= uc
->uc_mcontext
.mc_eip
;
443 #elif defined(__dietlibc__)
444 *paddr
= uc
->uc_mcontext
.eip
;
446 *paddr
= uc
->uc_mcontext
.gregs
[REG_EIP
];
450 #if defined(__FreeBSD__)
451 fp
= uc
->uc_mcontext
.mc_ebp
;
452 #elif defined(__dietlibc__)
453 fp
= uc
->uc_mcontext
.ebp
;
455 fp
= uc
->uc_mcontext
.gregs
[REG_EBP
];
457 for(i
=1;i
<level
;i
++) {
458 /* XXX: check address validity with program info */
459 if (fp
<= 0x1000 || fp
>= 0xc0000000)
461 fp
= ((unsigned long *)fp
)[0];
463 *paddr
= ((unsigned long *)fp
)[1];
468 /* ------------------------------------------------------------- */
469 #elif defined(__x86_64__)
471 /* return the PC at frame level 'level'. Return non zero if not found */
472 static int rt_get_caller_pc(unsigned long *paddr
,
473 ucontext_t
*uc
, int level
)
479 /* XXX: only support linux */
480 #if defined(__FreeBSD__)
481 *paddr
= uc
->uc_mcontext
.mc_rip
;
483 *paddr
= uc
->uc_mcontext
.gregs
[REG_RIP
];
487 #if defined(__FreeBSD__)
488 fp
= uc
->uc_mcontext
.mc_rbp
;
490 fp
= uc
->uc_mcontext
.gregs
[REG_RBP
];
492 for(i
=1;i
<level
;i
++) {
493 /* XXX: check address validity with program info */
496 fp
= ((unsigned long *)fp
)[0];
498 *paddr
= ((unsigned long *)fp
)[1];
503 /* ------------------------------------------------------------- */
504 #elif defined(__arm__)
506 /* return the PC at frame level 'level'. Return negative if not found */
507 static int rt_get_caller_pc(unsigned long *paddr
,
508 ucontext_t
*uc
, int level
)
514 /* XXX: only supports linux */
515 #if defined(__linux__)
516 *paddr
= uc
->uc_mcontext
.arm_pc
;
522 #if defined(__linux__)
523 fp
= uc
->uc_mcontext
.arm_fp
;
524 sp
= uc
->uc_mcontext
.arm_sp
;
530 /* XXX: specific to tinycc stack frames */
531 if (fp
< sp
+ 12 || fp
& 3)
533 for(i
= 1; i
< level
; i
++) {
534 sp
= ((uint32_t *)fp
)[-2];
535 if (sp
< fp
|| sp
- fp
> 16 || sp
& 3)
537 fp
= ((uint32_t *)fp
)[-3];
538 if (fp
<= sp
|| fp
- sp
< 12 || fp
& 3)
541 /* XXX: check address validity with program info */
542 *paddr
= ((uint32_t *)fp
)[-1];
547 /* ------------------------------------------------------------- */
550 #warning add arch specific rt_get_caller_pc()
551 static int rt_get_caller_pc(unsigned long *paddr
,
552 ucontext_t
*uc
, int level
)
557 #endif /* !__i386__ */
559 /* ------------------------------------------------------------- */
562 static long __stdcall
cpu_exception_handler(EXCEPTION_POINTERS
*ex_info
)
564 CONTEXT
*uc
= ex_info
->ContextRecord
;
566 EXCEPTION_RECORD *er = ex_info->ExceptionRecord;
567 printf("CPU exception: code=%08lx addr=%p\n",
568 er->ExceptionCode, er->ExceptionAddress);
570 if (rt_bound_error_msg
&& *rt_bound_error_msg
)
571 rt_error(uc
, *rt_bound_error_msg
);
573 rt_error(uc
, "dereferencing invalid pointer");
575 //return EXCEPTION_CONTINUE_SEARCH;
578 /* Generate a stack backtrace when a CPU exception occurs. */
579 static void set_exception_handler(void)
581 SetUnhandledExceptionFilter(cpu_exception_handler
);
589 /* return the PC at frame level 'level'. Return non zero if not found */
590 static int rt_get_caller_pc(uplong
*paddr
, CONTEXT
*uc
, int level
)
600 for(i
=1;i
<level
;i
++) {
601 /* XXX: check address validity with program info */
602 if (fp
<= 0x1000 || fp
>= 0xc0000000)
604 fp
= ((uplong
*)fp
)[0];
606 *paddr
= ((uplong
*)fp
)[1];
615 #endif /* CONFIG_TCC_BACKTRACE */
616 /* ------------------------------------------------------------- */
618 #ifdef CONFIG_TCC_STATIC
620 #define RTLD_LAZY 0x001
621 #define RTLD_NOW 0x002
622 #define RTLD_GLOBAL 0x100
623 #define RTLD_DEFAULT NULL
625 /* dummy function for profiling */
626 void *dlopen(const char *filename
, int flag
)
631 void dlclose(void *p
)
635 const char *dlerror(void)
640 typedef struct TCCSyms
{
645 #define TCCSYM(a) { #a, &a, },
647 /* add the symbol you want here if no dynamic linking is done */
648 static TCCSyms tcc_syms
[] = {
649 #if !defined(CONFIG_TCCBOOT)
658 void *resolve_sym(TCCState
*s1
, const char *symbol
)
662 while (p
->str
!= NULL
) {
663 if (!strcmp(p
->str
, symbol
))
670 #elif !defined(_WIN32)
672 void *resolve_sym(TCCState
*s1
, const char *sym
)
674 return dlsym(RTLD_DEFAULT
, sym
);
677 #endif /* CONFIG_TCC_STATIC */
679 /* ------------------------------------------------------------- */