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
);
81 return (*prog_main
)(argc
, argv
);
85 /* relocate code. Return -1 on error, required size if ptr is NULL,
86 otherwise copy code into buffer passed by the caller */
87 static int tcc_relocate_ex(TCCState
*s1
, void *ptr
)
90 unsigned long offset
, length
;
94 if (0 == s1
->runtime_added
) {
95 s1
->runtime_added
= 1;
98 pe_output_file(s1
, NULL
);
101 relocate_common_syms();
102 tcc_add_linker_symbols(s1
);
103 build_got_entries(s1
);
109 offset
= 0, mem
= (uplong
)ptr
;
110 for(i
= 1; i
< s1
->nb_sections
; i
++) {
112 if (0 == (s
->sh_flags
& SHF_ALLOC
))
114 length
= s
->data_offset
;
115 s
->sh_addr
= mem
? (mem
+ offset
+ 15) & ~15 : 0;
116 offset
= (offset
+ length
+ 15) & ~15;
120 /* relocate symbols */
121 relocate_syms(s1
, 1);
125 #if defined TCC_TARGET_X86_64 && !defined TCC_TARGET_PE
126 s1
->runtime_plt_and_got_offset
= 0;
127 s1
->runtime_plt_and_got
= (char *)(mem
+ offset
);
128 /* double the size of the buffer for got and plt entries
129 XXX: calculate exact size for them? */
136 /* relocate each section */
137 for(i
= 1; i
< s1
->nb_sections
; i
++) {
140 relocate_section(s1
, s
);
143 for(i
= 1; i
< s1
->nb_sections
; i
++) {
145 if (0 == (s
->sh_flags
& SHF_ALLOC
))
147 length
= s
->data_offset
;
148 // printf("%-12s %08x %04x\n", s->name, s->sh_addr, length);
149 ptr
= (void*)(uplong
)s
->sh_addr
;
150 if (NULL
== s
->data
|| s
->sh_type
== SHT_NOBITS
)
151 memset(ptr
, 0, length
);
153 memcpy(ptr
, s
->data
, length
);
154 /* mark executable sections as executable in memory */
155 if (s
->sh_flags
& SHF_EXECINSTR
)
156 set_pages_executable(ptr
, length
);
159 #if defined TCC_TARGET_X86_64 && !defined TCC_TARGET_PE
160 set_pages_executable(s1
->runtime_plt_and_got
,
161 s1
->runtime_plt_and_got_offset
);
166 /* ------------------------------------------------------------- */
167 /* allow to run code in memory */
169 static void set_pages_executable(void *ptr
, unsigned long length
)
172 unsigned long old_protect
;
173 VirtualProtect(ptr
, length
, PAGE_EXECUTE_READWRITE
, &old_protect
);
175 unsigned long start
, end
;
176 start
= (uplong
)ptr
& ~(PAGESIZE
- 1);
177 end
= (uplong
)ptr
+ length
;
178 end
= (end
+ PAGESIZE
- 1) & ~(PAGESIZE
- 1);
179 mprotect((void *)start
, end
- start
, PROT_READ
| PROT_WRITE
| PROT_EXEC
);
183 /* ------------------------------------------------------------- */
184 #ifdef CONFIG_TCC_BACKTRACE
186 /* print the position in the source file of PC value 'pc' by reading
187 the stabs debug information */
188 static uplong
rt_printline(uplong wanted_pc
)
190 Stab_Sym
*sym
, *sym_end
;
191 char func_name
[128], last_func_name
[128];
192 unsigned long func_addr
, last_pc
, pc
;
193 const char *incl_files
[INCLUDE_STACK_SIZE
];
194 int incl_index
, len
, last_line_num
, i
;
197 fprintf(stderr
, "0x%08lx:", (unsigned long)wanted_pc
);
202 last_func_name
[0] = '\0';
203 last_pc
= 0xffffffff;
205 sym
= (Stab_Sym
*)stab_section
->data
+ 1;
206 sym_end
= (Stab_Sym
*)(stab_section
->data
+ stab_section
->data_offset
);
207 while (sym
< sym_end
) {
208 switch(sym
->n_type
) {
209 /* function start or end */
211 if (sym
->n_strx
== 0) {
212 /* we test if between last line and end of function */
213 pc
= sym
->n_value
+ func_addr
;
214 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
219 str
= stabstr_section
->data
+ sym
->n_strx
;
220 p
= strchr(str
, ':');
222 pstrcpy(func_name
, sizeof(func_name
), str
);
225 if (len
> sizeof(func_name
) - 1)
226 len
= sizeof(func_name
) - 1;
227 memcpy(func_name
, str
, len
);
228 func_name
[len
] = '\0';
230 func_addr
= sym
->n_value
;
233 /* line number info */
235 pc
= sym
->n_value
+ func_addr
;
236 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
239 last_line_num
= sym
->n_desc
;
241 strcpy(last_func_name
, func_name
);
245 str
= stabstr_section
->data
+ sym
->n_strx
;
247 if (incl_index
< INCLUDE_STACK_SIZE
) {
248 incl_files
[incl_index
++] = str
;
256 if (sym
->n_strx
== 0) {
257 incl_index
= 0; /* end of translation unit */
259 str
= stabstr_section
->data
+ sym
->n_strx
;
260 /* do not add path */
262 if (len
> 0 && str
[len
- 1] != '/')
270 /* second pass: we try symtab symbols (no line number info) */
273 ElfW(Sym
) *sym
, *sym_end
;
276 sym_end
= (ElfW(Sym
) *)(symtab_section
->data
+ symtab_section
->data_offset
);
277 for(sym
= (ElfW(Sym
) *)symtab_section
->data
+ 1;
280 type
= ELFW(ST_TYPE
)(sym
->st_info
);
281 if (type
== STT_FUNC
) {
282 if (wanted_pc
>= sym
->st_value
&&
283 wanted_pc
< sym
->st_value
+ sym
->st_size
) {
284 pstrcpy(last_func_name
, sizeof(last_func_name
),
285 strtab_section
->data
+ sym
->st_name
);
286 func_addr
= sym
->st_value
;
292 /* did not find any info: */
293 fprintf(stderr
, " ???\n");
296 if (last_func_name
[0] != '\0') {
297 fprintf(stderr
, " %s()", last_func_name
);
299 if (incl_index
> 0) {
300 fprintf(stderr
, " (%s:%d",
301 incl_files
[incl_index
- 1], last_line_num
);
302 for(i
= incl_index
- 2; i
>= 0; i
--)
303 fprintf(stderr
, ", included from %s", incl_files
[i
]);
304 fprintf(stderr
, ")");
306 fprintf(stderr
, "\n");
310 /* emit a run time error at position 'pc' */
311 static void rt_error(ucontext_t
*uc
, const char *fmt
, ...)
318 fprintf(stderr
, "Runtime error: ");
319 vfprintf(stderr
, fmt
, ap
);
320 fprintf(stderr
, "\n");
322 for(i
=0;i
<num_callers
;i
++) {
323 if (rt_get_caller_pc(&pc
, uc
, i
) < 0)
326 fprintf(stderr
, "at ");
328 fprintf(stderr
, "by ");
329 pc
= rt_printline(pc
);
330 if (pc
== (uplong
)rt_prog_main
&& pc
)
337 /* ------------------------------------------------------------- */
340 /* signal handler for fatal errors */
341 static void sig_error(int signum
, siginfo_t
*siginf
, void *puc
)
343 ucontext_t
*uc
= puc
;
347 switch(siginf
->si_code
) {
350 rt_error(uc
, "division by zero");
353 rt_error(uc
, "floating point exception");
359 if (rt_bound_error_msg
&& *rt_bound_error_msg
)
360 rt_error(uc
, *rt_bound_error_msg
);
362 rt_error(uc
, "dereferencing invalid pointer");
365 rt_error(uc
, "illegal instruction");
368 rt_error(uc
, "abort() called");
371 rt_error(uc
, "caught signal %d", signum
);
377 /* Generate a stack backtrace when a CPU exception occurs. */
378 static void set_exception_handler(void)
380 struct sigaction sigact
;
381 /* install TCC signal handlers to print debug info on fatal
383 sigact
.sa_flags
= SA_SIGINFO
| SA_RESETHAND
;
384 sigact
.sa_sigaction
= sig_error
;
385 sigemptyset(&sigact
.sa_mask
);
386 sigaction(SIGFPE
, &sigact
, NULL
);
387 sigaction(SIGILL
, &sigact
, NULL
);
388 sigaction(SIGSEGV
, &sigact
, NULL
);
389 sigaction(SIGBUS
, &sigact
, NULL
);
390 sigaction(SIGABRT
, &sigact
, NULL
);
393 /* ------------------------------------------------------------- */
396 /* fix for glibc 2.1 */
402 /* return the PC at frame level 'level'. Return non zero if not found */
403 static int rt_get_caller_pc(unsigned long *paddr
, ucontext_t
*uc
, int level
)
409 #if defined(__FreeBSD__)
410 *paddr
= uc
->uc_mcontext
.mc_eip
;
411 #elif defined(__dietlibc__)
412 *paddr
= uc
->uc_mcontext
.eip
;
414 *paddr
= uc
->uc_mcontext
.gregs
[REG_EIP
];
418 #if defined(__FreeBSD__)
419 fp
= uc
->uc_mcontext
.mc_ebp
;
420 #elif defined(__dietlibc__)
421 fp
= uc
->uc_mcontext
.ebp
;
423 fp
= uc
->uc_mcontext
.gregs
[REG_EBP
];
425 for(i
=1;i
<level
;i
++) {
426 /* XXX: check address validity with program info */
427 if (fp
<= 0x1000 || fp
>= 0xc0000000)
429 fp
= ((unsigned long *)fp
)[0];
431 *paddr
= ((unsigned long *)fp
)[1];
436 /* ------------------------------------------------------------- */
437 #elif defined(__x86_64__)
439 /* return the PC at frame level 'level'. Return non zero if not found */
440 static int rt_get_caller_pc(unsigned long *paddr
,
441 ucontext_t
*uc
, int level
)
447 /* XXX: only support linux */
448 #if defined(__FreeBSD__)
449 *paddr
= uc
->uc_mcontext
.mc_rip
;
451 *paddr
= uc
->uc_mcontext
.gregs
[REG_RIP
];
455 #if defined(__FreeBSD__)
456 fp
= uc
->uc_mcontext
.mc_rbp
;
458 fp
= uc
->uc_mcontext
.gregs
[REG_RBP
];
460 for(i
=1;i
<level
;i
++) {
461 /* XXX: check address validity with program info */
464 fp
= ((unsigned long *)fp
)[0];
466 *paddr
= ((unsigned long *)fp
)[1];
471 /* ------------------------------------------------------------- */
474 #warning add arch specific rt_get_caller_pc()
475 static int rt_get_caller_pc(unsigned long *paddr
,
476 ucontext_t
*uc
, int level
)
481 #endif /* !__i386__ */
483 /* ------------------------------------------------------------- */
486 static long __stdcall
cpu_exception_handler(EXCEPTION_POINTERS
*ex_info
)
488 CONTEXT
*uc
= ex_info
->ContextRecord
;
490 EXCEPTION_RECORD *er = ex_info->ExceptionRecord;
491 printf("CPU exception: code=%08lx addr=%p\n",
492 er->ExceptionCode, er->ExceptionAddress);
494 if (rt_bound_error_msg
&& *rt_bound_error_msg
)
495 rt_error(uc
, *rt_bound_error_msg
);
497 rt_error(uc
, "dereferencing invalid pointer");
499 //return EXCEPTION_CONTINUE_SEARCH;
502 /* Generate a stack backtrace when a CPU exception occurs. */
503 static void set_exception_handler(void)
505 SetUnhandledExceptionFilter(cpu_exception_handler
);
513 /* return the PC at frame level 'level'. Return non zero if not found */
514 static int rt_get_caller_pc(uplong
*paddr
, CONTEXT
*uc
, int level
)
524 for(i
=1;i
<level
;i
++) {
525 /* XXX: check address validity with program info */
526 if (fp
<= 0x1000 || fp
>= 0xc0000000)
528 fp
= ((uplong
*)fp
)[0];
530 *paddr
= ((uplong
*)fp
)[1];
539 #endif /* CONFIG_TCC_BACKTRACE */
540 /* ------------------------------------------------------------- */
542 #ifdef CONFIG_TCC_STATIC
544 #define RTLD_LAZY 0x001
545 #define RTLD_NOW 0x002
546 #define RTLD_GLOBAL 0x100
547 #define RTLD_DEFAULT NULL
549 /* dummy function for profiling */
550 void *dlopen(const char *filename
, int flag
)
555 void dlclose(void *p
)
559 const char *dlerror(void)
564 typedef struct TCCSyms
{
569 #define TCCSYM(a) { #a, &a, },
571 /* add the symbol you want here if no dynamic linking is done */
572 static TCCSyms tcc_syms
[] = {
573 #if !defined(CONFIG_TCCBOOT)
582 void *resolve_sym(TCCState
*s1
, const char *symbol
)
586 while (p
->str
!= NULL
) {
587 if (!strcmp(p
->str
, symbol
))
594 #elif !defined(_WIN32)
596 void *resolve_sym(TCCState
*s1
, const char *sym
)
598 return dlsym(RTLD_DEFAULT
, sym
);
601 #endif /* CONFIG_TCC_STATIC */
603 /* ------------------------------------------------------------- */