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 ret
= tcc_relocate_ex(s1
, NULL
);
43 s1
->runtime_mem
= tcc_malloc(ret
);
44 ret
= tcc_relocate_ex(s1
, s1
->runtime_mem
);
49 /* launch the compiled program with the given arguments */
50 int tcc_run(TCCState
*s1
, int argc
, char **argv
)
52 int (*prog_main
)(int, char **);
54 if (tcc_relocate(s1
) < 0)
57 prog_main
= tcc_get_symbol_err(s1
, "main");
59 #ifdef CONFIG_TCC_BACKTRACE
61 set_exception_handler();
64 #ifdef CONFIG_TCC_BCHECK
65 if (s1
->do_bounds_check
) {
66 void (*bound_init
)(void);
67 void (*bound_exit
)(void);
69 /* set error function */
70 rt_bound_error_msg
= tcc_get_symbol_err(s1
, "__bound_error_msg");
71 rt_prog_main
= prog_main
;
72 /* XXX: use .init section so that it also work in binary ? */
73 bound_init
= tcc_get_symbol_err(s1
, "__bound_init");
74 bound_exit
= tcc_get_symbol_err(s1
, "__bound_exit");
76 ret
= (*prog_main
)(argc
, argv
);
84 unsigned char *p
= tcc_get_symbol(s1
, "tinyc_no_getbp");
88 return (*prog_main
)(argc
, argv
);
92 /* relocate code. Return -1 on error, required size if ptr is NULL,
93 otherwise copy code into buffer passed by the caller */
94 static int tcc_relocate_ex(TCCState
*s1
, void *ptr
)
97 unsigned long offset
, length
;
101 if (0 == s1
->runtime_added
) {
102 s1
->runtime_added
= 1;
105 pe_output_file(s1
, NULL
);
108 relocate_common_syms();
109 tcc_add_linker_symbols(s1
);
110 build_got_entries(s1
);
116 offset
= 0, mem
= (uplong
)ptr
;
117 for(i
= 1; i
< s1
->nb_sections
; i
++) {
119 if (0 == (s
->sh_flags
& SHF_ALLOC
))
121 length
= s
->data_offset
;
122 s
->sh_addr
= mem
? (mem
+ offset
+ 15) & ~15 : 0;
123 offset
= (offset
+ length
+ 15) & ~15;
127 /* relocate symbols */
128 relocate_syms(s1
, 1);
132 #if defined TCC_TARGET_X86_64 && !defined TCC_TARGET_PE
133 s1
->runtime_plt_and_got_offset
= 0;
134 s1
->runtime_plt_and_got
= (char *)(mem
+ offset
);
135 /* double the size of the buffer for got and plt entries
136 XXX: calculate exact size for them? */
143 /* relocate each section */
144 for(i
= 1; i
< s1
->nb_sections
; i
++) {
147 relocate_section(s1
, s
);
150 for(i
= 1; i
< s1
->nb_sections
; i
++) {
152 if (0 == (s
->sh_flags
& SHF_ALLOC
))
154 length
= s
->data_offset
;
155 // printf("%-12s %08x %04x\n", s->name, s->sh_addr, length);
156 ptr
= (void*)(uplong
)s
->sh_addr
;
157 if (NULL
== s
->data
|| s
->sh_type
== SHT_NOBITS
)
158 memset(ptr
, 0, length
);
160 memcpy(ptr
, s
->data
, length
);
161 /* mark executable sections as executable in memory */
162 if (s
->sh_flags
& SHF_EXECINSTR
)
163 set_pages_executable(ptr
, length
);
166 #if defined TCC_TARGET_X86_64 && !defined TCC_TARGET_PE
167 set_pages_executable(s1
->runtime_plt_and_got
,
168 s1
->runtime_plt_and_got_offset
);
173 /* ------------------------------------------------------------- */
174 /* allow to run code in memory */
176 static void set_pages_executable(void *ptr
, unsigned long length
)
179 unsigned long old_protect
;
180 VirtualProtect(ptr
, length
, PAGE_EXECUTE_READWRITE
, &old_protect
);
182 unsigned long start
, end
;
183 start
= (uplong
)ptr
& ~(PAGESIZE
- 1);
184 end
= (uplong
)ptr
+ length
;
185 end
= (end
+ PAGESIZE
- 1) & ~(PAGESIZE
- 1);
186 mprotect((void *)start
, end
- start
, PROT_READ
| PROT_WRITE
| PROT_EXEC
);
190 /* ------------------------------------------------------------- */
191 #ifdef CONFIG_TCC_BACKTRACE
193 /* print the position in the source file of PC value 'pc' by reading
194 the stabs debug information */
195 static uplong
rt_printline(uplong wanted_pc
)
197 Stab_Sym
*sym
, *sym_end
;
198 char func_name
[128], last_func_name
[128];
199 unsigned long func_addr
, last_pc
, pc
;
200 const char *incl_files
[INCLUDE_STACK_SIZE
];
201 int incl_index
, len
, last_line_num
, i
;
204 fprintf(stderr
, "0x%08lx:", (unsigned long)wanted_pc
);
209 last_func_name
[0] = '\0';
210 last_pc
= 0xffffffff;
212 sym
= (Stab_Sym
*)stab_section
->data
+ 1;
213 sym_end
= (Stab_Sym
*)(stab_section
->data
+ stab_section
->data_offset
);
214 while (sym
< sym_end
) {
215 switch(sym
->n_type
) {
216 /* function start or end */
218 if (sym
->n_strx
== 0) {
219 /* we test if between last line and end of function */
220 pc
= sym
->n_value
+ func_addr
;
221 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
226 str
= stabstr_section
->data
+ sym
->n_strx
;
227 p
= strchr(str
, ':');
229 pstrcpy(func_name
, sizeof(func_name
), str
);
232 if (len
> sizeof(func_name
) - 1)
233 len
= sizeof(func_name
) - 1;
234 memcpy(func_name
, str
, len
);
235 func_name
[len
] = '\0';
237 func_addr
= sym
->n_value
;
240 /* line number info */
242 pc
= sym
->n_value
+ func_addr
;
243 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
246 last_line_num
= sym
->n_desc
;
248 strcpy(last_func_name
, func_name
);
252 str
= stabstr_section
->data
+ sym
->n_strx
;
254 if (incl_index
< INCLUDE_STACK_SIZE
) {
255 incl_files
[incl_index
++] = str
;
263 if (sym
->n_strx
== 0) {
264 incl_index
= 0; /* end of translation unit */
266 str
= stabstr_section
->data
+ sym
->n_strx
;
267 /* do not add path */
269 if (len
> 0 && str
[len
- 1] != '/')
277 /* second pass: we try symtab symbols (no line number info) */
280 ElfW(Sym
) *sym
, *sym_end
;
283 sym_end
= (ElfW(Sym
) *)(symtab_section
->data
+ symtab_section
->data_offset
);
284 for(sym
= (ElfW(Sym
) *)symtab_section
->data
+ 1;
287 type
= ELFW(ST_TYPE
)(sym
->st_info
);
288 if (type
== STT_FUNC
) {
289 if (wanted_pc
>= sym
->st_value
&&
290 wanted_pc
< sym
->st_value
+ sym
->st_size
) {
291 pstrcpy(last_func_name
, sizeof(last_func_name
),
292 strtab_section
->data
+ sym
->st_name
);
293 func_addr
= sym
->st_value
;
299 /* did not find any info: */
300 fprintf(stderr
, " ???\n");
303 if (last_func_name
[0] != '\0') {
304 fprintf(stderr
, " %s()", last_func_name
);
306 if (incl_index
> 0) {
307 fprintf(stderr
, " (%s:%d",
308 incl_files
[incl_index
- 1], last_line_num
);
309 for(i
= incl_index
- 2; i
>= 0; i
--)
310 fprintf(stderr
, ", included from %s", incl_files
[i
]);
311 fprintf(stderr
, ")");
313 fprintf(stderr
, "\n");
317 /* emit a run time error at position 'pc' */
318 static void rt_error(ucontext_t
*uc
, const char *fmt
, ...)
325 fprintf(stderr
, "Runtime error: ");
326 vfprintf(stderr
, fmt
, ap
);
327 fprintf(stderr
, "\n");
329 for(i
=0;i
<num_callers
;i
++) {
330 if (rt_get_caller_pc(&pc
, uc
, i
) < 0)
333 fprintf(stderr
, "at ");
335 fprintf(stderr
, "by ");
336 pc
= rt_printline(pc
);
337 if (pc
== (uplong
)rt_prog_main
&& pc
)
344 /* ------------------------------------------------------------- */
347 /* signal handler for fatal errors */
348 static void sig_error(int signum
, siginfo_t
*siginf
, void *puc
)
350 ucontext_t
*uc
= puc
;
354 switch(siginf
->si_code
) {
357 rt_error(uc
, "division by zero");
360 rt_error(uc
, "floating point exception");
366 if (rt_bound_error_msg
&& *rt_bound_error_msg
)
367 rt_error(uc
, *rt_bound_error_msg
);
369 rt_error(uc
, "dereferencing invalid pointer");
372 rt_error(uc
, "illegal instruction");
375 rt_error(uc
, "abort() called");
378 rt_error(uc
, "caught signal %d", signum
);
384 /* Generate a stack backtrace when a CPU exception occurs. */
385 static void set_exception_handler(void)
387 struct sigaction sigact
;
388 /* install TCC signal handlers to print debug info on fatal
390 sigact
.sa_flags
= SA_SIGINFO
| SA_RESETHAND
;
391 sigact
.sa_sigaction
= sig_error
;
392 sigemptyset(&sigact
.sa_mask
);
393 sigaction(SIGFPE
, &sigact
, NULL
);
394 sigaction(SIGILL
, &sigact
, NULL
);
395 sigaction(SIGSEGV
, &sigact
, NULL
);
396 sigaction(SIGBUS
, &sigact
, NULL
);
397 sigaction(SIGABRT
, &sigact
, NULL
);
400 /* ------------------------------------------------------------- */
403 /* fix for glibc 2.1 */
409 /* return the PC at frame level 'level'. Return non zero if not found */
410 static int rt_get_caller_pc(unsigned long *paddr
, ucontext_t
*uc
, int level
)
416 #if defined(__FreeBSD__)
417 *paddr
= uc
->uc_mcontext
.mc_eip
;
418 #elif defined(__dietlibc__)
419 *paddr
= uc
->uc_mcontext
.eip
;
421 *paddr
= uc
->uc_mcontext
.gregs
[REG_EIP
];
425 #if defined(__FreeBSD__)
426 fp
= uc
->uc_mcontext
.mc_ebp
;
427 #elif defined(__dietlibc__)
428 fp
= uc
->uc_mcontext
.ebp
;
430 fp
= uc
->uc_mcontext
.gregs
[REG_EBP
];
432 for(i
=1;i
<level
;i
++) {
433 /* XXX: check address validity with program info */
434 if (fp
<= 0x1000 || fp
>= 0xc0000000)
436 fp
= ((unsigned long *)fp
)[0];
438 *paddr
= ((unsigned long *)fp
)[1];
443 /* ------------------------------------------------------------- */
444 #elif defined(__x86_64__)
446 /* return the PC at frame level 'level'. Return non zero if not found */
447 static int rt_get_caller_pc(unsigned long *paddr
,
448 ucontext_t
*uc
, int level
)
454 /* XXX: only support linux */
455 #if defined(__FreeBSD__)
456 *paddr
= uc
->uc_mcontext
.mc_rip
;
458 *paddr
= uc
->uc_mcontext
.gregs
[REG_RIP
];
462 #if defined(__FreeBSD__)
463 fp
= uc
->uc_mcontext
.mc_rbp
;
465 fp
= uc
->uc_mcontext
.gregs
[REG_RBP
];
467 for(i
=1;i
<level
;i
++) {
468 /* XXX: check address validity with program info */
471 fp
= ((unsigned long *)fp
)[0];
473 *paddr
= ((unsigned long *)fp
)[1];
478 /* ------------------------------------------------------------- */
481 #warning add arch specific rt_get_caller_pc()
482 static int rt_get_caller_pc(unsigned long *paddr
,
483 ucontext_t
*uc
, int level
)
488 #endif /* !__i386__ */
490 /* ------------------------------------------------------------- */
493 static long __stdcall
cpu_exception_handler(EXCEPTION_POINTERS
*ex_info
)
495 CONTEXT
*uc
= ex_info
->ContextRecord
;
497 EXCEPTION_RECORD *er = ex_info->ExceptionRecord;
498 printf("CPU exception: code=%08lx addr=%p\n",
499 er->ExceptionCode, er->ExceptionAddress);
501 if (rt_bound_error_msg
&& *rt_bound_error_msg
)
502 rt_error(uc
, *rt_bound_error_msg
);
504 rt_error(uc
, "dereferencing invalid pointer");
506 //return EXCEPTION_CONTINUE_SEARCH;
509 /* Generate a stack backtrace when a CPU exception occurs. */
510 static void set_exception_handler(void)
512 SetUnhandledExceptionFilter(cpu_exception_handler
);
520 /* return the PC at frame level 'level'. Return non zero if not found */
521 static int rt_get_caller_pc(uplong
*paddr
, CONTEXT
*uc
, int level
)
531 for(i
=1;i
<level
;i
++) {
532 /* XXX: check address validity with program info */
533 if (fp
<= 0x1000 || fp
>= 0xc0000000)
535 fp
= ((uplong
*)fp
)[0];
537 *paddr
= ((uplong
*)fp
)[1];
546 #endif /* CONFIG_TCC_BACKTRACE */
547 /* ------------------------------------------------------------- */
549 #ifdef CONFIG_TCC_STATIC
551 #define RTLD_LAZY 0x001
552 #define RTLD_NOW 0x002
553 #define RTLD_GLOBAL 0x100
554 #define RTLD_DEFAULT NULL
556 /* dummy function for profiling */
557 void *dlopen(const char *filename
, int flag
)
562 void dlclose(void *p
)
566 const char *dlerror(void)
571 typedef struct TCCSyms
{
576 #define TCCSYM(a) { #a, &a, },
578 /* add the symbol you want here if no dynamic linking is done */
579 static TCCSyms tcc_syms
[] = {
580 #if !defined(CONFIG_TCCBOOT)
589 void *resolve_sym(TCCState
*s1
, const char *symbol
)
593 while (p
->str
!= NULL
) {
594 if (!strcmp(p
->str
, symbol
))
601 #elif !defined(_WIN32)
603 void *resolve_sym(TCCState
*s1
, const char *sym
)
605 return dlsym(RTLD_DEFAULT
, sym
);
608 #endif /* CONFIG_TCC_STATIC */
610 /* ------------------------------------------------------------- */