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 **);
57 char tmpfname
[] = "/tmp/.tccrunXXXXXX";
58 int fd
= mkstemp (tmpfname
);
61 if ((rret
= tcc_relocate_ex(s1
,NULL
)) < 0)
63 /* Use mmap instead of malloc for Selinux */
64 writep
= mmap (NULL
, rret
, PROT_READ
|PROT_WRITE
,
66 if(writep
== MAP_FAILED
){
67 error("/tmp not writeable");
70 ptr
= mmap (NULL
, rret
, PROT_READ
|PROT_EXEC
,
72 if(ptr
== MAP_FAILED
){
73 error("/tmp not executable");
76 tcc_relocate_ex(s1
, writep
);
78 if (tcc_relocate(s1
) < 0)
81 prog_main
= tcc_get_symbol_err(s1
, "main");
83 #ifdef CONFIG_TCC_BACKTRACE
85 set_exception_handler();
88 #ifdef CONFIG_TCC_BCHECK
89 if (s1
->do_bounds_check
) {
90 void (*bound_init
)(void);
91 void (*bound_exit
)(void);
92 /* set error function */
93 rt_bound_error_msg
= tcc_get_symbol_err(s1
, "__bound_error_msg");
94 rt_prog_main
= prog_main
;
95 /* XXX: use .init section so that it also work in binary ? */
96 bound_init
= tcc_get_symbol_err(s1
, "__bound_init");
97 bound_exit
= tcc_get_symbol_err(s1
, "__bound_exit");
99 ret
= (*prog_main
)(argc
, argv
);
107 unsigned char *p
= tcc_get_symbol(s1
, "tinyc_no_getbp");
111 ret
=(*prog_main
)(argc
, argv
);
113 munmap (writep
, rret
);
121 /* relocate code. Return -1 on error, required size if ptr is NULL,
122 otherwise copy code into buffer passed by the caller */
123 static int tcc_relocate_ex(TCCState
*s1
, void *ptr
)
126 unsigned long offset
, length
;
130 if (0 == s1
->runtime_added
) {
131 s1
->runtime_added
= 1;
134 pe_output_file(s1
, NULL
);
137 relocate_common_syms();
138 tcc_add_linker_symbols(s1
);
139 build_got_entries(s1
);
145 offset
= 0, mem
= (uplong
)ptr
;
146 for(i
= 1; i
< s1
->nb_sections
; i
++) {
148 if (0 == (s
->sh_flags
& SHF_ALLOC
))
150 length
= s
->data_offset
;
151 s
->sh_addr
= mem
? (mem
+ offset
+ 15) & ~15 : 0;
152 offset
= (offset
+ length
+ 15) & ~15;
156 /* relocate symbols */
157 relocate_syms(s1
, 1);
161 #if defined TCC_TARGET_X86_64 && !defined TCC_TARGET_PE
162 s1
->runtime_plt_and_got_offset
= 0;
163 s1
->runtime_plt_and_got
= (char *)(mem
+ offset
);
164 /* double the size of the buffer for got and plt entries
165 XXX: calculate exact size for them? */
172 /* relocate each section */
173 for(i
= 1; i
< s1
->nb_sections
; i
++) {
176 relocate_section(s1
, s
);
179 for(i
= 1; i
< s1
->nb_sections
; i
++) {
181 if (0 == (s
->sh_flags
& SHF_ALLOC
))
183 length
= s
->data_offset
;
184 // printf("%-12s %08x %04x\n", s->name, s->sh_addr, length);
185 ptr
= (void*)(uplong
)s
->sh_addr
;
186 if (NULL
== s
->data
|| s
->sh_type
== SHT_NOBITS
)
187 memset(ptr
, 0, length
);
189 memcpy(ptr
, s
->data
, length
);
190 /* mark executable sections as executable in memory */
191 if (s
->sh_flags
& SHF_EXECINSTR
)
192 set_pages_executable(ptr
, length
);
195 #if defined TCC_TARGET_X86_64 && !defined TCC_TARGET_PE
196 set_pages_executable(s1
->runtime_plt_and_got
,
197 s1
->runtime_plt_and_got_offset
);
202 /* ------------------------------------------------------------- */
203 /* allow to run code in memory */
205 static void set_pages_executable(void *ptr
, unsigned long length
)
208 unsigned long old_protect
;
209 VirtualProtect(ptr
, length
, PAGE_EXECUTE_READWRITE
, &old_protect
);
211 unsigned long start
, end
;
212 start
= (uplong
)ptr
& ~(PAGESIZE
- 1);
213 end
= (uplong
)ptr
+ length
;
214 end
= (end
+ PAGESIZE
- 1) & ~(PAGESIZE
- 1);
215 mprotect((void *)start
, end
- start
, PROT_READ
| PROT_WRITE
| PROT_EXEC
);
219 /* ------------------------------------------------------------- */
220 #ifdef CONFIG_TCC_BACKTRACE
222 /* print the position in the source file of PC value 'pc' by reading
223 the stabs debug information */
224 static uplong
rt_printline(uplong wanted_pc
)
226 Stab_Sym
*sym
, *sym_end
;
227 char func_name
[128], last_func_name
[128];
228 unsigned long func_addr
, last_pc
, pc
;
229 const char *incl_files
[INCLUDE_STACK_SIZE
];
230 int incl_index
, len
, last_line_num
, i
;
233 fprintf(stderr
, "0x%08lx:", (unsigned long)wanted_pc
);
238 last_func_name
[0] = '\0';
239 last_pc
= 0xffffffff;
241 sym
= (Stab_Sym
*)stab_section
->data
+ 1;
242 sym_end
= (Stab_Sym
*)(stab_section
->data
+ stab_section
->data_offset
);
243 while (sym
< sym_end
) {
244 switch(sym
->n_type
) {
245 /* function start or end */
247 if (sym
->n_strx
== 0) {
248 /* we test if between last line and end of function */
249 pc
= sym
->n_value
+ func_addr
;
250 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
255 str
= stabstr_section
->data
+ sym
->n_strx
;
256 p
= strchr(str
, ':');
258 pstrcpy(func_name
, sizeof(func_name
), str
);
261 if (len
> sizeof(func_name
) - 1)
262 len
= sizeof(func_name
) - 1;
263 memcpy(func_name
, str
, len
);
264 func_name
[len
] = '\0';
266 func_addr
= sym
->n_value
;
269 /* line number info */
271 pc
= sym
->n_value
+ func_addr
;
272 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
275 last_line_num
= sym
->n_desc
;
277 strcpy(last_func_name
, func_name
);
281 str
= stabstr_section
->data
+ sym
->n_strx
;
283 if (incl_index
< INCLUDE_STACK_SIZE
) {
284 incl_files
[incl_index
++] = str
;
292 if (sym
->n_strx
== 0) {
293 incl_index
= 0; /* end of translation unit */
295 str
= stabstr_section
->data
+ sym
->n_strx
;
296 /* do not add path */
298 if (len
> 0 && str
[len
- 1] != '/')
306 /* second pass: we try symtab symbols (no line number info) */
309 ElfW(Sym
) *sym
, *sym_end
;
312 sym_end
= (ElfW(Sym
) *)(symtab_section
->data
+ symtab_section
->data_offset
);
313 for(sym
= (ElfW(Sym
) *)symtab_section
->data
+ 1;
316 type
= ELFW(ST_TYPE
)(sym
->st_info
);
317 if (type
== STT_FUNC
) {
318 if (wanted_pc
>= sym
->st_value
&&
319 wanted_pc
< sym
->st_value
+ sym
->st_size
) {
320 pstrcpy(last_func_name
, sizeof(last_func_name
),
321 strtab_section
->data
+ sym
->st_name
);
322 func_addr
= sym
->st_value
;
328 /* did not find any info: */
329 fprintf(stderr
, " ???\n");
332 if (last_func_name
[0] != '\0') {
333 fprintf(stderr
, " %s()", last_func_name
);
335 if (incl_index
> 0) {
336 fprintf(stderr
, " (%s:%d",
337 incl_files
[incl_index
- 1], last_line_num
);
338 for(i
= incl_index
- 2; i
>= 0; i
--)
339 fprintf(stderr
, ", included from %s", incl_files
[i
]);
340 fprintf(stderr
, ")");
342 fprintf(stderr
, "\n");
346 /* emit a run time error at position 'pc' */
347 static void rt_error(ucontext_t
*uc
, const char *fmt
, ...)
354 fprintf(stderr
, "Runtime error: ");
355 vfprintf(stderr
, fmt
, ap
);
356 fprintf(stderr
, "\n");
358 for(i
=0;i
<num_callers
;i
++) {
359 if (rt_get_caller_pc(&pc
, uc
, i
) < 0)
362 fprintf(stderr
, "at ");
364 fprintf(stderr
, "by ");
365 pc
= rt_printline(pc
);
366 if (pc
== (uplong
)rt_prog_main
&& pc
)
373 /* ------------------------------------------------------------- */
376 /* signal handler for fatal errors */
377 static void sig_error(int signum
, siginfo_t
*siginf
, void *puc
)
379 ucontext_t
*uc
= puc
;
383 switch(siginf
->si_code
) {
386 rt_error(uc
, "division by zero");
389 rt_error(uc
, "floating point exception");
395 if (rt_bound_error_msg
&& *rt_bound_error_msg
)
396 rt_error(uc
, *rt_bound_error_msg
);
398 rt_error(uc
, "dereferencing invalid pointer");
401 rt_error(uc
, "illegal instruction");
404 rt_error(uc
, "abort() called");
407 rt_error(uc
, "caught signal %d", signum
);
413 /* Generate a stack backtrace when a CPU exception occurs. */
414 static void set_exception_handler(void)
416 struct sigaction sigact
;
417 /* install TCC signal handlers to print debug info on fatal
419 sigact
.sa_flags
= SA_SIGINFO
| SA_RESETHAND
;
420 sigact
.sa_sigaction
= sig_error
;
421 sigemptyset(&sigact
.sa_mask
);
422 sigaction(SIGFPE
, &sigact
, NULL
);
423 sigaction(SIGILL
, &sigact
, NULL
);
424 sigaction(SIGSEGV
, &sigact
, NULL
);
425 sigaction(SIGBUS
, &sigact
, NULL
);
426 sigaction(SIGABRT
, &sigact
, NULL
);
429 /* ------------------------------------------------------------- */
432 /* fix for glibc 2.1 */
438 /* return the PC at frame level 'level'. Return non zero if not found */
439 static int rt_get_caller_pc(unsigned long *paddr
, ucontext_t
*uc
, int level
)
445 #if defined(__FreeBSD__)
446 *paddr
= uc
->uc_mcontext
.mc_eip
;
447 #elif defined(__dietlibc__)
448 *paddr
= uc
->uc_mcontext
.eip
;
450 *paddr
= uc
->uc_mcontext
.gregs
[REG_EIP
];
454 #if defined(__FreeBSD__)
455 fp
= uc
->uc_mcontext
.mc_ebp
;
456 #elif defined(__dietlibc__)
457 fp
= uc
->uc_mcontext
.ebp
;
459 fp
= uc
->uc_mcontext
.gregs
[REG_EBP
];
461 for(i
=1;i
<level
;i
++) {
462 /* XXX: check address validity with program info */
463 if (fp
<= 0x1000 || fp
>= 0xc0000000)
465 fp
= ((unsigned long *)fp
)[0];
467 *paddr
= ((unsigned long *)fp
)[1];
472 /* ------------------------------------------------------------- */
473 #elif defined(__x86_64__)
475 /* return the PC at frame level 'level'. Return non zero if not found */
476 static int rt_get_caller_pc(unsigned long *paddr
,
477 ucontext_t
*uc
, int level
)
483 /* XXX: only support linux */
484 #if defined(__FreeBSD__)
485 *paddr
= uc
->uc_mcontext
.mc_rip
;
487 *paddr
= uc
->uc_mcontext
.gregs
[REG_RIP
];
491 #if defined(__FreeBSD__)
492 fp
= uc
->uc_mcontext
.mc_rbp
;
494 fp
= uc
->uc_mcontext
.gregs
[REG_RBP
];
496 for(i
=1;i
<level
;i
++) {
497 /* XXX: check address validity with program info */
500 fp
= ((unsigned long *)fp
)[0];
502 *paddr
= ((unsigned long *)fp
)[1];
507 /* ------------------------------------------------------------- */
510 #warning add arch specific rt_get_caller_pc()
511 static int rt_get_caller_pc(unsigned long *paddr
,
512 ucontext_t
*uc
, int level
)
517 #endif /* !__i386__ */
519 /* ------------------------------------------------------------- */
522 static long __stdcall
cpu_exception_handler(EXCEPTION_POINTERS
*ex_info
)
524 CONTEXT
*uc
= ex_info
->ContextRecord
;
526 EXCEPTION_RECORD *er = ex_info->ExceptionRecord;
527 printf("CPU exception: code=%08lx addr=%p\n",
528 er->ExceptionCode, er->ExceptionAddress);
530 if (rt_bound_error_msg
&& *rt_bound_error_msg
)
531 rt_error(uc
, *rt_bound_error_msg
);
533 rt_error(uc
, "dereferencing invalid pointer");
535 //return EXCEPTION_CONTINUE_SEARCH;
538 /* Generate a stack backtrace when a CPU exception occurs. */
539 static void set_exception_handler(void)
541 SetUnhandledExceptionFilter(cpu_exception_handler
);
549 /* return the PC at frame level 'level'. Return non zero if not found */
550 static int rt_get_caller_pc(uplong
*paddr
, CONTEXT
*uc
, int level
)
560 for(i
=1;i
<level
;i
++) {
561 /* XXX: check address validity with program info */
562 if (fp
<= 0x1000 || fp
>= 0xc0000000)
564 fp
= ((uplong
*)fp
)[0];
566 *paddr
= ((uplong
*)fp
)[1];
575 #endif /* CONFIG_TCC_BACKTRACE */
576 /* ------------------------------------------------------------- */
578 #ifdef CONFIG_TCC_STATIC
580 #define RTLD_LAZY 0x001
581 #define RTLD_NOW 0x002
582 #define RTLD_GLOBAL 0x100
583 #define RTLD_DEFAULT NULL
585 /* dummy function for profiling */
586 void *dlopen(const char *filename
, int flag
)
591 void dlclose(void *p
)
595 const char *dlerror(void)
600 typedef struct TCCSyms
{
605 #define TCCSYM(a) { #a, &a, },
607 /* add the symbol you want here if no dynamic linking is done */
608 static TCCSyms tcc_syms
[] = {
609 #if !defined(CONFIG_TCCBOOT)
618 void *resolve_sym(TCCState
*s1
, const char *symbol
)
622 while (p
->str
!= NULL
) {
623 if (!strcmp(p
->str
, symbol
))
630 #elif !defined(_WIN32)
632 void *resolve_sym(TCCState
*s1
, const char *sym
)
634 return dlsym(RTLD_DEFAULT
, sym
);
637 #endif /* CONFIG_TCC_STATIC */
639 /* ------------------------------------------------------------- */