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
23 /* only native compiler supports -run */
26 #ifdef CONFIG_TCC_BACKTRACE
27 typedef struct rt_context
29 /* --> tccelf.c:tcc_add_btstub wants those below in that order: */
32 Stab_Sym
*stab_sym
, *stab_sym_end
;
36 unsigned char *dwarf_line
, *dwarf_line_end
, *dwarf_line_str
;
40 ElfW(Sym
) *esym_start
, *esym_end
;
44 struct rt_context
*next
;
53 static rt_context g_rtctxt
;
54 static void set_exception_handler(void);
55 static int _rt_error(void *fp
, void *ip
, const char *fmt
, va_list ap
);
56 static void rt_exit(int code
);
57 #endif /* CONFIG_TCC_BACKTRACE */
59 /* defined when included from lib/bt-exe.c */
60 #ifndef CONFIG_TCC_BACKTRACE_ONLY
63 # include <sys/mman.h>
66 static void set_pages_executable(TCCState
*s1
, int mode
, void *ptr
, unsigned long length
);
67 static int tcc_relocate_ex(TCCState
*s1
, void *ptr
, addr_t ptr_diff
);
70 static void *win64_add_function_table(TCCState
*s1
);
71 static void win64_del_function_table(void *);
74 /* ------------------------------------------------------------- */
75 /* Do all relocations (needed before using tcc_get_symbol())
76 Returns -1 on error. */
78 LIBTCCAPI
int tcc_relocate(TCCState
*s1
, void *ptr
)
83 if (TCC_RELOCATE_AUTO
!= ptr
)
84 return tcc_relocate_ex(s1
, ptr
, 0);
86 size
= tcc_relocate_ex(s1
, NULL
, 0);
92 /* Using mmap instead of malloc */
94 char tmpfname
[] = "/tmp/.tccrunXXXXXX";
95 int fd
= mkstemp(tmpfname
);
99 size
= (size
+ (PAGESIZE
-1)) & ~(PAGESIZE
-1);
100 ptr
= mmap(NULL
, size
* 2, PROT_READ
|PROT_WRITE
, MAP_SHARED
, fd
, 0);
101 /* mmap RX memory at a fixed distance */
102 prx
= mmap((char*)ptr
+ size
, size
, PROT_READ
|PROT_EXEC
, MAP_SHARED
|MAP_FIXED
, fd
, 0);
103 if (ptr
== MAP_FAILED
|| prx
== MAP_FAILED
)
104 tcc_error("tccrun: could not map memory");
105 ptr_diff
= (char*)prx
- (char*)ptr
;
107 //printf("map %p %p %p\n", ptr, prx, (void*)ptr_diff);
110 ptr
= tcc_malloc(size
);
112 tcc_relocate_ex(s1
, ptr
, ptr_diff
); /* no more errors expected */
113 dynarray_add(&s1
->runtime_mem
, &s1
->nb_runtime_mem
, (void*)(addr_t
)size
);
114 dynarray_add(&s1
->runtime_mem
, &s1
->nb_runtime_mem
, ptr
);
118 ST_FUNC
void tcc_run_free(TCCState
*s1
)
122 for (i
= 0; i
< s1
->nb_runtime_mem
; i
+= 2) {
123 unsigned size
= (unsigned)(addr_t
)s1
->runtime_mem
[i
];
124 void *ptr
= s1
->runtime_mem
[i
+1];
126 munmap(ptr
, size
* 2);
128 /* unprotect memory to make it usable for malloc again */
129 set_pages_executable(s1
, 2, ptr
, size
);
131 win64_del_function_table(*(void**)ptr
);
136 tcc_free(s1
->runtime_mem
);
139 static void run_cdtors(TCCState
*s1
, const char *start
, const char *end
,
140 int argc
, char **argv
, char **envp
)
142 void **a
= (void **)get_sym_addr(s1
, start
, 0, 0);
143 void **b
= (void **)get_sym_addr(s1
, end
, 0, 0);
145 ((void(*)(int, char **, char **))*a
++)(argc
, argv
, envp
);
148 #define NR_AT_EXIT 32
150 static struct exit_context
{
153 void (*exitfunc
[NR_AT_EXIT
])(int, void *);
154 void *exitarg
[NR_AT_EXIT
];
155 #ifndef CONFIG_TCC_BACKTRACE
160 static void init_exit(void)
162 struct exit_context
*e
= &g_exit_context
;
168 static void call_exit(int ret
)
170 struct exit_context
*e
= &g_exit_context
;
174 e
->exitfunc
[e
->nr_exit
](ret
, e
->exitarg
[e
->nr_exit
]);
178 static int rt_atexit(void (*function
)(void))
180 struct exit_context
*e
= &g_exit_context
;
182 if (e
->nr_exit
< NR_AT_EXIT
) {
183 e
->exitfunc
[e
->nr_exit
] = (void (*)(int, void *))function
;
184 e
->exitarg
[e
->nr_exit
++] = NULL
;
190 static int rt_on_exit(void (*function
)(int, void *), void *arg
)
192 struct exit_context
*e
= &g_exit_context
;
194 if (e
->nr_exit
< NR_AT_EXIT
) {
195 e
->exitfunc
[e
->nr_exit
] = function
;
196 e
->exitarg
[e
->nr_exit
++] = arg
;
202 static void run_exit(int code
)
204 struct exit_context
*e
= &g_exit_context
;
207 #ifdef CONFIG_TCC_BACKTRACE
208 longjmp((&g_rtctxt
)->jmp_buf, code
? code
: 256);
210 longjmp(e
->run_jmp_buf
, code
? code
: 256);
214 /* launch the compiled program with the given arguments */
215 LIBTCCAPI
int tcc_run(TCCState
*s1
, int argc
, char **argv
)
217 int (*prog_main
)(int, char **, char **), ret
;
218 #ifdef CONFIG_TCC_BACKTRACE
219 rt_context
*rc
= &g_rtctxt
;
222 #if defined(__APPLE__) || defined(__FreeBSD__)
224 #elif defined(__OpenBSD__) || defined(__NetBSD__)
225 extern char **environ
;
226 char **envp
= environ
;
228 char **envp
= environ
;
231 s1
->runtime_main
= s1
->nostdlib
? "_start" : "main";
232 if ((s1
->dflag
& 16) && (addr_t
)-1 == get_sym_addr(s1
, s1
->runtime_main
, 0, 1))
234 tcc_add_symbol(s1
, "exit", run_exit
);
235 tcc_add_symbol(s1
, "atexit", rt_atexit
);
236 tcc_add_symbol(s1
, "on_exit", rt_on_exit
);
237 if (tcc_relocate(s1
, TCC_RELOCATE_AUTO
) < 0)
239 prog_main
= (void*)get_sym_addr(s1
, s1
->runtime_main
, 1, 1);
241 #ifdef CONFIG_TCC_BACKTRACE
242 memset(rc
, 0, sizeof *rc
);
246 rc
->dwarf_line
= dwarf_line_section
->data
;
247 rc
->dwarf_line_end
= dwarf_line_section
->data
+ dwarf_line_section
->data_offset
;
248 if (dwarf_line_str_section
)
249 rc
->dwarf_line_str
= dwarf_line_str_section
->data
;
253 rc
->stab_sym
= (Stab_Sym
*)stab_section
->data
;
254 rc
->stab_sym_end
= (Stab_Sym
*)(stab_section
->data
+ stab_section
->data_offset
);
255 rc
->stab_str
= (char *)stab_section
->link
->data
;
257 rc
->dwarf
= s1
->dwarf
;
258 rc
->esym_start
= (ElfW(Sym
) *)(symtab_section
->data
);
259 rc
->esym_end
= (ElfW(Sym
) *)(symtab_section
->data
+ symtab_section
->data_offset
);
260 rc
->elf_str
= (char *)symtab_section
->link
->data
;
262 rc
->prog_base
= text_section
->sh_addr
& 0xffffffff00000000ULL
;
263 #if defined TCC_TARGET_MACHO
265 rc
->prog_base
= (addr_t
) -1;
269 rc
->top_func
= tcc_get_symbol(s1
, "main");
270 rc
->num_callers
= s1
->rt_num_callers
;
272 if ((p
= tcc_get_symbol(s1
, "__rt_error")))
273 *(void**)p
= _rt_error
;
274 #ifdef CONFIG_TCC_BCHECK
275 if (s1
->do_bounds_check
) {
276 rc
->bounds_start
= (void*)bounds_section
->sh_addr
;
277 if ((p
= tcc_get_symbol(s1
, "__bound_init")))
278 ((void(*)(void*,int))p
)(rc
->bounds_start
, 1);
281 set_exception_handler();
285 errno
= 0; /* clean errno value */
289 /* These aren't C symbols, so don't need leading underscore handling. */
290 run_cdtors(s1
, "__init_array_start", "__init_array_end", argc
, argv
, envp
);
291 #ifdef CONFIG_TCC_BACKTRACE
292 if (!(ret
= setjmp(rc
->jmp_buf)))
294 if (!(ret
= setjmp((&g_exit_context
)->run_jmp_buf
)))
297 ret
= prog_main(argc
, argv
, envp
);
299 run_cdtors(s1
, "__fini_array_start", "__fini_array_end", 0, NULL
, NULL
);
301 if ((s1
->dflag
& 16) && ret
)
302 fprintf(s1
->ppfp
, "[returns %d]\n", ret
), fflush(s1
->ppfp
);
303 if ((s1
->dflag
& 16) == 0 && (&g_exit_context
)->exit_called
)
308 #define DEBUG_RUNMEN 0
310 /* enable rx/ro/rw permissions */
311 #define CONFIG_RUNMEM_RO 1
314 # define PAGE_ALIGN PAGESIZE
315 #elif defined TCC_TARGET_I386 || defined TCC_TARGET_X86_64
316 /* To avoid that x86 processors would reload cached instructions
317 each time when data is written in the near, we need to make
318 sure that code and data do not share the same 64 byte unit */
319 # define PAGE_ALIGN 64
321 # define PAGE_ALIGN 1
324 /* relocate code. Return -1 on error, required size if ptr is NULL,
325 otherwise copy code into buffer passed by the caller */
326 static int tcc_relocate_ex(TCCState
*s1
, void *ptr
, addr_t ptr_diff
)
329 unsigned offset
, length
, align
, max_align
, i
, k
, f
;
336 pe_output_file(s1
, NULL
);
339 resolve_common_syms(s1
);
340 build_got_entries(s1
, 0);
346 offset
= max_align
= 0, mem
= (addr_t
)ptr
;
348 offset
+= sizeof (void*); /* space for function_table pointer */
352 for (k
= 0; k
< 3; ++k
) { /* 0:rx, 1:ro, 2:rw sections */
354 for(i
= 1; i
< s1
->nb_sections
; i
++) {
355 static const char shf
[] = {
356 SHF_ALLOC
|SHF_EXECINSTR
, SHF_ALLOC
, SHF_ALLOC
|SHF_WRITE
359 if (shf
[k
] != (s
->sh_flags
& (SHF_ALLOC
|SHF_WRITE
|SHF_EXECINSTR
)))
361 length
= s
->data_offset
;
365 n
= (s
->sh_addr
- addr
) + length
;
366 ptr
= (void*)s
->sh_addr
;
368 ptr
= (void*)(s
->sh_addr
- ptr_diff
);
369 if (NULL
== s
->data
|| s
->sh_type
== SHT_NOBITS
)
370 memset(ptr
, 0, length
);
372 memcpy(ptr
, s
->data
, length
);
374 if (s
== s1
->uw_pdata
)
375 *(void**)mem
= win64_add_function_table(s1
);
380 s
->data_allocated
= 0;
385 align
= s
->sh_addralign
- 1;
386 if (++n
== 1 && align
< (PAGE_ALIGN
- 1))
387 align
= (PAGE_ALIGN
- 1);
388 if (max_align
< align
)
390 addr
= k
? mem
: mem
+ ptr_diff
;
391 offset
+= -(addr
+ offset
) & align
;
392 s
->sh_addr
= mem
? addr
+ offset
: 0;
396 printf("%d: %-16s %p len %04x align %04x\n",
397 k
, s
->name
, (void*)s
->sh_addr
, length
, align
+ 1);
400 if (copy
) { /* set permissions */
401 if (k
== 0 && ptr_diff
)
402 continue; /* not with HAVE_SELINUX */
404 #if !CONFIG_RUNMEM_RO
407 f
= 3; /* change only SHF_EXECINSTR to rwx */
410 printf("protect %d %p %04x\n", f
, (void*)addr
, n
);
413 set_pages_executable(s1
, f
, (void*)addr
, n
);
420 /* relocate symbols */
421 relocate_syms(s1
, s1
->symtab
, !(s1
->nostdlib
));
425 return offset
+ max_align
;
428 s1
->pe_imagebase
= mem
;
431 /* relocate sections */
432 #ifndef TCC_TARGET_PE
435 relocate_sections(s1
);
440 /* ------------------------------------------------------------- */
441 /* allow to run code in memory */
443 static void set_pages_executable(TCCState
*s1
, int mode
, void *ptr
, unsigned long length
)
446 static const unsigned char protect
[] = {
450 PAGE_EXECUTE_READWRITE
453 VirtualProtect(ptr
, length
, protect
[mode
], &old
);
455 static const unsigned char protect
[] = {
456 PROT_READ
| PROT_EXEC
,
458 PROT_READ
| PROT_WRITE
,
459 PROT_READ
| PROT_WRITE
| PROT_EXEC
462 start
= (addr_t
)ptr
& ~(PAGESIZE
- 1);
463 end
= (addr_t
)ptr
+ length
;
464 end
= (end
+ PAGESIZE
- 1) & ~(PAGESIZE
- 1);
465 if (mprotect((void *)start
, end
- start
, protect
[mode
]))
466 tcc_error("mprotect failed: did you mean to configure --with-selinux?");
468 /* XXX: BSD sometimes dump core with bad system call */
469 # if (defined TCC_TARGET_ARM && !TARGETOS_BSD) || defined TCC_TARGET_ARM64
470 if (mode
== 0 || mode
== 3) {
471 void __clear_cache(void *beginning
, void *end
);
472 __clear_cache(ptr
, (char *)ptr
+ length
);
480 static void *win64_add_function_table(TCCState
*s1
)
484 p
= (void*)s1
->uw_pdata
->sh_addr
;
486 (RUNTIME_FUNCTION
*)p
,
487 s1
->uw_pdata
->data_offset
/ sizeof (RUNTIME_FUNCTION
),
495 static void win64_del_function_table(void *p
)
498 RtlDeleteFunctionTable((RUNTIME_FUNCTION
*)p
);
502 #endif //ndef CONFIG_TCC_BACKTRACE_ONLY
503 /* ------------------------------------------------------------- */
504 #ifdef CONFIG_TCC_BACKTRACE
506 static int rt_vprintf(const char *fmt
, va_list ap
)
508 int ret
= vfprintf(stderr
, fmt
, ap
);
513 static int rt_printf(const char *fmt
, ...)
518 r
= rt_vprintf(fmt
, ap
);
523 static char *rt_elfsym(rt_context
*rc
, addr_t wanted_pc
, addr_t
*func_addr
)
526 for (esym
= rc
->esym_start
+ 1; esym
< rc
->esym_end
; ++esym
) {
527 int type
= ELFW(ST_TYPE
)(esym
->st_info
);
528 if ((type
== STT_FUNC
|| type
== STT_GNU_IFUNC
)
529 && wanted_pc
>= esym
->st_value
530 && wanted_pc
< esym
->st_value
+ esym
->st_size
) {
531 *func_addr
= esym
->st_value
;
532 return rc
->elf_str
+ esym
->st_name
;
538 #define INCLUDE_STACK_SIZE 32
540 /* print the position in the source file of PC value 'pc' by reading
541 the stabs debug information */
542 static addr_t
rt_printline (rt_context
*rc
, addr_t wanted_pc
,
543 const char *msg
, const char *skip
)
546 addr_t func_addr
, last_pc
, pc
;
547 const char *incl_files
[INCLUDE_STACK_SIZE
];
548 int incl_index
, last_incl_index
, len
, last_line_num
, i
;
556 last_pc
= (addr_t
)-1;
560 for (sym
= rc
->stab_sym
+ 1; sym
< rc
->stab_sym_end
; ++sym
) {
561 str
= rc
->stab_str
+ sym
->n_strx
;
564 switch(sym
->n_type
) {
572 if (sym
->n_strx
== 0) /* end of function */
576 /* Stab_Sym.n_value is only 32bits */
583 if (pc
>= wanted_pc
&& wanted_pc
>= last_pc
)
588 switch(sym
->n_type
) {
589 /* function start or end */
591 if (sym
->n_strx
== 0)
593 p
= strchr(str
, ':');
594 if (0 == p
|| (len
= p
- str
+ 1, len
> sizeof func_name
))
595 len
= sizeof func_name
;
596 pstrcpy(func_name
, len
, str
);
599 /* line number info */
602 last_line_num
= sym
->n_desc
;
603 last_incl_index
= incl_index
;
607 if (incl_index
< INCLUDE_STACK_SIZE
)
608 incl_files
[incl_index
++] = str
;
614 /* start/end of translation unit */
618 /* do not add path */
620 if (len
> 0 && str
[len
- 1] != '/')
621 incl_files
[incl_index
++] = str
;
626 last_pc
= (addr_t
)-1;
628 /* alternative file name (from #line or #include directives) */
631 incl_files
[incl_index
-1] = str
;
639 /* we try symtab symbols (no line number info) */
640 p
= rt_elfsym(rc
, wanted_pc
, &func_addr
);
642 pstrcpy(func_name
, sizeof func_name
, p
);
650 str
= incl_files
[--i
];
651 if (skip
[0] && strstr(str
, skip
))
653 rt_printf("%s:%d: ", str
, last_line_num
);
655 rt_printf("%08llx : ", (long long)wanted_pc
);
656 rt_printf("%s %s", msg
, func_name
[0] ? func_name
: "???");
659 rt_printf(" (included from ");
661 rt_printf("%s", incl_files
[i
]);
672 /* ------------------------------------------------------------- */
673 /* rt_printline - dwarf version */
675 #define MAX_128 ((8 * sizeof (long long) + 6) / 7)
677 #define DIR_TABLE_SIZE (64)
678 #define FILE_TABLE_SIZE (512)
680 #define dwarf_read_1(ln,end) \
681 ((ln) < (end) ? *(ln)++ : 0)
682 #define dwarf_read_2(ln,end) \
683 ((ln) + 2 < (end) ? (ln) += 2, read16le((ln) - 2) : 0)
684 #define dwarf_read_4(ln,end) \
685 ((ln) + 4 < (end) ? (ln) += 4, read32le((ln) - 4) : 0)
686 #define dwarf_read_8(ln,end) \
687 ((ln) + 8 < (end) ? (ln) += 8, read64le((ln) - 8) : 0)
688 #define dwarf_ignore_type(ln, end) /* timestamp/size/md5/... */ \
689 switch (entry_format[j].form) { \
690 case DW_FORM_data1: (ln) += 1; break; \
691 case DW_FORM_data2: (ln) += 2; break; \
692 case DW_FORM_data4: (ln) += 3; break; \
693 case DW_FORM_data8: (ln) += 8; break; \
694 case DW_FORM_data16: (ln) += 16; break; \
695 case DW_FORM_udata: dwarf_read_uleb128(&(ln), (end)); break; \
696 default: goto next_line; \
699 static unsigned long long
700 dwarf_read_uleb128(unsigned char **ln
, unsigned char *end
)
702 unsigned char *cp
= *ln
;
703 unsigned long long retval
= 0;
706 for (i
= 0; i
< MAX_128
; i
++) {
707 unsigned long long byte
= dwarf_read_1(cp
, end
);
709 retval
|= (byte
& 0x7f) << (i
* 7);
710 if ((byte
& 0x80) == 0)
718 dwarf_read_sleb128(unsigned char **ln
, unsigned char *end
)
720 unsigned char *cp
= *ln
;
721 long long retval
= 0;
724 for (i
= 0; i
< MAX_128
; i
++) {
725 unsigned long long byte
= dwarf_read_1(cp
, end
);
727 retval
|= (byte
& 0x7f) << (i
* 7);
728 if ((byte
& 0x80) == 0) {
729 if ((byte
& 0x40) && (i
+ 1) * 7 < 64)
730 retval
|= -1LL << ((i
+ 1) * 7);
738 static addr_t
rt_printline_dwarf (rt_context
*rc
, addr_t wanted_pc
,
739 const char *msg
, const char *skip
)
744 unsigned char *opcode_length
;
745 unsigned long long size
;
747 unsigned char version
;
748 unsigned int min_insn_length
;
749 unsigned int max_ops_per_insn
;
751 unsigned int line_range
;
752 unsigned int opcode_base
;
753 unsigned int opindex
;
758 unsigned long long value
;
763 unsigned int dir_size
;
765 char *dirs
[DIR_TABLE_SIZE
];
767 unsigned int filename_size
;
768 struct dwarf_filename_struct
{
769 unsigned int dir_entry
;
771 } filename_table
[FILE_TABLE_SIZE
];
781 while (ln
< rc
->dwarf_line_end
) {
791 size
= dwarf_read_4(ln
, rc
->dwarf_line_end
);
792 if (size
== 0xffffffffu
) // dwarf 64
793 length
= 8, size
= dwarf_read_8(ln
, rc
->dwarf_line_end
);
795 if (end
< ln
|| end
> rc
->dwarf_line_end
)
797 version
= dwarf_read_2(ln
, end
);
799 ln
+= length
+ 2; // address size, segment selector, prologue Length
801 ln
+= length
; // prologue Length
802 min_insn_length
= dwarf_read_1(ln
, end
);
804 max_ops_per_insn
= dwarf_read_1(ln
, end
);
806 max_ops_per_insn
= 1;
807 ln
++; // Initial value of 'is_stmt'
808 line_base
= dwarf_read_1(ln
, end
);
809 line_base
|= line_base
>= 0x80 ? ~0xff : 0;
810 line_range
= dwarf_read_1(ln
, end
);
811 opcode_base
= dwarf_read_1(ln
, end
);
813 ln
+= opcode_base
- 1;
816 col
= dwarf_read_1(ln
, end
);
817 for (i
= 0; i
< col
; i
++) {
818 entry_format
[i
].type
= dwarf_read_uleb128(&ln
, end
);
819 entry_format
[i
].form
= dwarf_read_uleb128(&ln
, end
);
821 dir_size
= dwarf_read_uleb128(&ln
, end
);
822 for (i
= 0; i
< dir_size
; i
++) {
823 for (j
= 0; j
< col
; j
++) {
824 if (entry_format
[j
].type
== DW_LNCT_path
) {
825 if (entry_format
[j
].form
!= DW_FORM_line_strp
)
828 value
= length
== 4 ? dwarf_read_4(ln
, end
)
829 : dwarf_read_8(ln
, end
);
830 if (i
< DIR_TABLE_SIZE
)
831 dirs
[i
] = (char *)rc
->dwarf_line_str
+ value
;
833 length
== 4 ? dwarf_read_4(ln
, end
)
834 : dwarf_read_8(ln
, end
);
838 dwarf_ignore_type(ln
, end
);
841 col
= dwarf_read_1(ln
, end
);
842 for (i
= 0; i
< col
; i
++) {
843 entry_format
[i
].type
= dwarf_read_uleb128(&ln
, end
);
844 entry_format
[i
].form
= dwarf_read_uleb128(&ln
, end
);
846 filename_size
= dwarf_read_uleb128(&ln
, end
);
847 for (i
= 0; i
< filename_size
; i
++)
848 for (j
= 0; j
< col
; j
++) {
849 if (entry_format
[j
].type
== DW_LNCT_path
) {
850 if (entry_format
[j
].form
!= DW_FORM_line_strp
)
852 value
= length
== 4 ? dwarf_read_4(ln
, end
)
853 : dwarf_read_8(ln
, end
);
854 if (i
< FILE_TABLE_SIZE
)
855 filename_table
[i
].name
=
856 (char *)rc
->dwarf_line_str
+ value
;
858 else if (entry_format
[j
].type
== DW_LNCT_directory_index
) {
859 switch (entry_format
[j
].form
) {
860 case DW_FORM_data1
: value
= dwarf_read_1(ln
, end
); break;
861 case DW_FORM_data2
: value
= dwarf_read_2(ln
, end
); break;
862 case DW_FORM_data4
: value
= dwarf_read_4(ln
, end
); break;
863 case DW_FORM_udata
: value
= dwarf_read_uleb128(&ln
, end
); break;
864 default: goto next_line
;
866 if (i
< FILE_TABLE_SIZE
)
867 filename_table
[i
].dir_entry
= value
;
870 dwarf_ignore_type(ln
, end
);
874 while ((dwarf_read_1(ln
, end
))) {
876 if (++dir_size
< DIR_TABLE_SIZE
)
877 dirs
[dir_size
- 1] = (char *)ln
- 1;
879 while (dwarf_read_1(ln
, end
)) {}
881 while ((dwarf_read_1(ln
, end
))) {
882 if (++filename_size
< FILE_TABLE_SIZE
) {
883 filename_table
[filename_size
- 1].name
= (char *)ln
- 1;
884 while (dwarf_read_1(ln
, end
)) {}
885 filename_table
[filename_size
- 1].dir_entry
=
886 dwarf_read_uleb128(&ln
, end
);
889 while (dwarf_read_1(ln
, end
)) {}
890 dwarf_read_uleb128(&ln
, end
);
892 dwarf_read_uleb128(&ln
, end
); // time
893 dwarf_read_uleb128(&ln
, end
); // size
896 if (filename_size
>= 1)
897 filename
= filename_table
[0].name
;
900 i
= dwarf_read_1(ln
, end
);
901 if (i
>= opcode_base
) {
902 if (max_ops_per_insn
== 1)
903 pc
+= ((i
- opcode_base
) / line_range
) * min_insn_length
;
905 pc
+= (opindex
+ (i
- opcode_base
) / line_range
) /
906 max_ops_per_insn
* min_insn_length
;
907 opindex
= (opindex
+ (i
- opcode_base
) / line_range
) %
910 i
= (int)((i
- opcode_base
) % line_range
) + line_base
;
912 if (pc
>= wanted_pc
&& wanted_pc
>= last_pc
)
919 len
= dwarf_read_uleb128(&ln
, end
);
924 switch (dwarf_read_1(cp
, end
)) {
925 case DW_LNE_end_sequence
:
927 case DW_LNE_set_address
:
929 pc
= dwarf_read_4(cp
, end
);
931 pc
= dwarf_read_8(cp
, end
);
933 #if defined TCC_TARGET_MACHO
934 if (rc
->prog_base
!= (addr_t
) -1)
939 case DW_LNE_define_file
: /* deprecated */
940 if (++filename_size
< FILE_TABLE_SIZE
) {
941 filename_table
[filename_size
- 1].name
= (char *)ln
- 1;
942 while (dwarf_read_1(ln
, end
)) {}
943 filename_table
[filename_size
- 1].dir_entry
=
944 dwarf_read_uleb128(&ln
, end
);
947 while (dwarf_read_1(ln
, end
)) {}
948 dwarf_read_uleb128(&ln
, end
);
950 dwarf_read_uleb128(&ln
, end
); // time
951 dwarf_read_uleb128(&ln
, end
); // size
953 case DW_LNE_hi_user
- 1:
954 function
= (char *)cp
;
961 case DW_LNS_advance_pc
:
962 if (max_ops_per_insn
== 1)
963 pc
+= dwarf_read_uleb128(&ln
, end
) * min_insn_length
;
965 unsigned long long off
= dwarf_read_uleb128(&ln
, end
);
967 pc
+= (opindex
+ off
) / max_ops_per_insn
*
969 opindex
= (opindex
+ off
) % max_ops_per_insn
;
973 case DW_LNS_advance_line
:
974 line
+= dwarf_read_sleb128(&ln
, end
);
976 case DW_LNS_set_file
:
977 i
= dwarf_read_uleb128(&ln
, end
);
978 if (i
< FILE_TABLE_SIZE
&& i
< filename_size
)
979 filename
= filename_table
[i
].name
;
981 case DW_LNS_const_add_pc
:
982 if (max_ops_per_insn
== 1)
983 pc
+= ((255 - opcode_base
) / line_range
) * min_insn_length
;
985 unsigned int off
= (255 - opcode_base
) / line_range
;
987 pc
+= ((opindex
+ off
) / max_ops_per_insn
) *
989 opindex
= (opindex
+ off
) % max_ops_per_insn
;
993 case DW_LNS_fixed_advance_pc
:
994 i
= dwarf_read_2(ln
, end
);
1000 for (j
= 0; j
< opcode_length
[i
- 1]; j
++)
1001 dwarf_read_uleb128 (&ln
, end
);
1012 /* we try symtab symbols (no line number info) */
1013 function
= rt_elfsym(rc
, wanted_pc
, &func_addr
);
1016 if ((rc
= rc
->next
))
1020 if (skip
[0] && strstr(filename
, skip
))
1022 rt_printf("%s:%d: ", filename
, line
);
1025 rt_printf("0x%08llx : ", (long long)wanted_pc
);
1026 rt_printf("%s %s", msg
, function
? function
: "???");
1027 return (addr_t
)func_addr
;
1029 /* ------------------------------------------------------------- */
1031 static int rt_get_caller_pc(addr_t
*paddr
, rt_context
*rc
, int level
);
1033 static int _rt_error(void *fp
, void *ip
, const char *fmt
, va_list ap
)
1035 rt_context
*rc
= &g_rtctxt
;
1038 int i
, level
, ret
, n
;
1039 const char *a
, *b
, *msg
;
1042 /* we're called from tcc_backtrace. */
1043 rc
->fp
= (addr_t
)fp
;
1044 rc
->ip
= (addr_t
)ip
;
1047 /* we're called from signal/exception handler */
1048 msg
= "RUNTIME ERROR: ";
1052 /* If fmt is like "^file.c^..." then skip calls from 'file.c' */
1053 if (fmt
[0] == '^' && (b
= strchr(a
= fmt
+ 1, fmt
[0]))) {
1054 memcpy(skip
, a
, b
- a
), skip
[b
- a
] = 0;
1058 n
= rc
->num_callers
? rc
->num_callers
: 6;
1059 for (i
= level
= 0; level
< n
; i
++) {
1060 ret
= rt_get_caller_pc(&pc
, rc
, i
);
1064 pc
= rt_printline_dwarf(rc
, pc
, level
? "by" : "at", skip
);
1066 pc
= rt_printline(rc
, pc
, level
? "by" : "at", skip
);
1067 if (pc
== (addr_t
)-1)
1073 rt_vprintf(fmt
, ap
);
1074 } else if (ret
== -1)
1077 if (ret
== -1 || (pc
== (addr_t
)rc
->top_func
&& pc
))
1082 rc
->ip
= rc
->fp
= 0;
1086 /* emit a run time error at position 'pc' */
1087 static int rt_error(const char *fmt
, ...)
1092 ret
= _rt_error(0, 0, fmt
, ap
);
1097 static void rt_exit(int code
)
1099 rt_context
*rc
= &g_rtctxt
;
1101 longjmp(rc
->jmp_buf, code
? code
: 256);
1105 /* ------------------------------------------------------------- */
1108 # include <signal.h>
1109 # ifndef __OpenBSD__
1110 # include <sys/ucontext.h>
1113 # define ucontext_t CONTEXT
1116 /* translate from ucontext_t* to internal rt_context * */
1117 static void rt_getcontext(ucontext_t
*uc
, rt_context
*rc
)
1123 #elif defined _WIN32
1127 #elif defined __i386__
1128 # if defined(__APPLE__)
1129 rc
->ip
= uc
->uc_mcontext
->__ss
.__eip
;
1130 rc
->fp
= uc
->uc_mcontext
->__ss
.__ebp
;
1131 # elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
1132 rc
->ip
= uc
->uc_mcontext
.mc_eip
;
1133 rc
->fp
= uc
->uc_mcontext
.mc_ebp
;
1134 # elif defined(__dietlibc__)
1135 rc
->ip
= uc
->uc_mcontext
.eip
;
1136 rc
->fp
= uc
->uc_mcontext
.ebp
;
1137 # elif defined(__NetBSD__)
1138 rc
->ip
= uc
->uc_mcontext
.__gregs
[_REG_EIP
];
1139 rc
->fp
= uc
->uc_mcontext
.__gregs
[_REG_EBP
];
1140 # elif defined(__OpenBSD__)
1141 rc
->ip
= uc
->sc_eip
;
1142 rc
->fp
= uc
->sc_ebp
;
1143 # elif !defined REG_EIP && defined EIP /* fix for glibc 2.1 */
1144 rc
->ip
= uc
->uc_mcontext
.gregs
[EIP
];
1145 rc
->fp
= uc
->uc_mcontext
.gregs
[EBP
];
1147 rc
->ip
= uc
->uc_mcontext
.gregs
[REG_EIP
];
1148 rc
->fp
= uc
->uc_mcontext
.gregs
[REG_EBP
];
1150 #elif defined(__x86_64__)
1151 # if defined(__APPLE__)
1152 rc
->ip
= uc
->uc_mcontext
->__ss
.__rip
;
1153 rc
->fp
= uc
->uc_mcontext
->__ss
.__rbp
;
1154 # elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
1155 rc
->ip
= uc
->uc_mcontext
.mc_rip
;
1156 rc
->fp
= uc
->uc_mcontext
.mc_rbp
;
1157 # elif defined(__NetBSD__)
1158 rc
->ip
= uc
->uc_mcontext
.__gregs
[_REG_RIP
];
1159 rc
->fp
= uc
->uc_mcontext
.__gregs
[_REG_RBP
];
1160 # elif defined(__OpenBSD__)
1161 rc
->ip
= uc
->sc_rip
;
1162 rc
->fp
= uc
->sc_rbp
;
1164 rc
->ip
= uc
->uc_mcontext
.gregs
[REG_RIP
];
1165 rc
->fp
= uc
->uc_mcontext
.gregs
[REG_RBP
];
1167 #elif defined(__arm__) && defined(__NetBSD__)
1168 rc
->ip
= uc
->uc_mcontext
.__gregs
[_REG_PC
];
1169 rc
->fp
= uc
->uc_mcontext
.__gregs
[_REG_FP
];
1170 #elif defined(__arm__) && defined(__OpenBSD__)
1172 rc
->fp
= uc
->sc_r11
;
1173 #elif defined(__arm__) && defined(__FreeBSD__)
1174 rc
->ip
= uc
->uc_mcontext
.__gregs
[_REG_PC
];
1175 rc
->fp
= uc
->uc_mcontext
.__gregs
[_REG_FP
];
1176 #elif defined(__arm__)
1177 rc
->ip
= uc
->uc_mcontext
.arm_pc
;
1178 rc
->fp
= uc
->uc_mcontext
.arm_fp
;
1179 #elif defined(__aarch64__) && defined(__APPLE__)
1181 // /Library/Developer/CommandLineTools/SDKs/MacOSX11.1.sdk/usr/include/mach/arm/_structs.h
1182 rc
->ip
= uc
->uc_mcontext
->__ss
.__pc
;
1183 rc
->fp
= uc
->uc_mcontext
->__ss
.__fp
;
1184 #elif defined(__aarch64__) && defined(__FreeBSD__)
1185 rc
->ip
= uc
->uc_mcontext
.mc_gpregs
.gp_elr
; /* aka REG_PC */
1186 rc
->fp
= uc
->uc_mcontext
.mc_gpregs
.gp_x
[29];
1187 #elif defined(__aarch64__) && defined(__NetBSD__)
1188 rc
->ip
= uc
->uc_mcontext
.__gregs
[_REG_PC
];
1189 rc
->fp
= uc
->uc_mcontext
.__gregs
[_REG_FP
];
1190 #elif defined(__aarch64__) && defined(__OpenBSD__)
1191 rc
->ip
= uc
->sc_elr
;
1192 rc
->fp
= uc
->sc_x
[29];
1193 #elif defined(__aarch64__)
1194 rc
->ip
= uc
->uc_mcontext
.pc
;
1195 rc
->fp
= uc
->uc_mcontext
.regs
[29];
1196 #elif defined(__riscv) && defined(__OpenBSD__)
1197 rc
->ip
= uc
->sc_sepc
;
1198 rc
->fp
= uc
->sc_s
[0];
1199 #elif defined(__riscv)
1200 rc
->ip
= uc
->uc_mcontext
.__gregs
[REG_PC
];
1201 rc
->fp
= uc
->uc_mcontext
.__gregs
[REG_S0
];
1205 /* ------------------------------------------------------------- */
1207 /* signal handler for fatal errors */
1208 static void sig_error(int signum
, siginfo_t
*siginf
, void *puc
)
1210 rt_context
*rc
= &g_rtctxt
;
1211 rt_getcontext(puc
, rc
);
1215 switch(siginf
->si_code
) {
1218 rt_error("division by zero");
1221 rt_error("floating point exception");
1227 rt_error("invalid memory access");
1230 rt_error("illegal instruction");
1233 rt_error("abort() called");
1236 rt_error("caught signal %d", signum
);
1243 # define SA_SIGINFO 0x00000004u
1246 /* Generate a stack backtrace when a CPU exception occurs. */
1247 static void set_exception_handler(void)
1249 struct sigaction sigact
;
1250 /* install TCC signal handlers to print debug info on fatal
1252 sigemptyset (&sigact
.sa_mask
);
1253 sigact
.sa_flags
= SA_SIGINFO
| SA_RESETHAND
;
1254 #if 0//def SIGSTKSZ // this causes signals not to work at all on some (older) linuxes
1255 sigact
.sa_flags
|= SA_ONSTACK
;
1257 sigact
.sa_sigaction
= sig_error
;
1258 sigemptyset(&sigact
.sa_mask
);
1259 sigaction(SIGFPE
, &sigact
, NULL
);
1260 sigaction(SIGILL
, &sigact
, NULL
);
1261 sigaction(SIGSEGV
, &sigact
, NULL
);
1262 sigaction(SIGBUS
, &sigact
, NULL
);
1263 sigaction(SIGABRT
, &sigact
, NULL
);
1265 /* This allows stack overflow to be reported instead of a SEGV */
1268 static unsigned char stack
[SIGSTKSZ
] __attribute__((aligned(16)));
1271 ss
.ss_size
= SIGSTKSZ
;
1273 sigaltstack(&ss
, NULL
);
1280 /* signal handler for fatal errors */
1281 static long __stdcall
cpu_exception_handler(EXCEPTION_POINTERS
*ex_info
)
1283 rt_context
*rc
= &g_rtctxt
;
1285 rt_getcontext(ex_info
->ContextRecord
, rc
);
1287 switch (code
= ex_info
->ExceptionRecord
->ExceptionCode
) {
1288 case EXCEPTION_ACCESS_VIOLATION
:
1289 rt_error("invalid memory access");
1291 case EXCEPTION_STACK_OVERFLOW
:
1292 rt_error("stack overflow");
1294 case EXCEPTION_INT_DIVIDE_BY_ZERO
:
1295 rt_error("division by zero");
1297 case EXCEPTION_BREAKPOINT
:
1298 case EXCEPTION_SINGLE_STEP
:
1299 rc
->ip
= *(addr_t
*)rc
->sp
;
1300 rt_error("breakpoint/single-step exception:");
1301 return EXCEPTION_CONTINUE_SEARCH
;
1303 rt_error("caught exception %08x", code
);
1308 return EXCEPTION_EXECUTE_HANDLER
;
1311 /* Generate a stack backtrace when a CPU exception occurs. */
1312 static void set_exception_handler(void)
1314 SetUnhandledExceptionFilter(cpu_exception_handler
);
1319 /* ------------------------------------------------------------- */
1320 /* return the PC at frame level 'level'. Return negative if not found */
1321 #if defined(__i386__) || defined(__x86_64__)
1322 static int rt_get_caller_pc(addr_t
*paddr
, rt_context
*rc
, int level
)
1331 /* XXX: check address validity with program info */
1334 fp
= ((addr_t
*)fp
)[0];
1337 ip
= ((addr_t
*)fp
)[1];
1345 #elif defined(__arm__)
1346 static int rt_get_caller_pc(addr_t
*paddr
, rt_context
*rc
, int level
)
1348 /* XXX: only supports linux/bsd */
1349 #if !defined(__linux__) && \
1350 !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__)
1358 fp
= ((addr_t
*)fp
)[0];
1359 *paddr
= ((addr_t
*)fp
)[2];
1365 #elif defined(__aarch64__)
1366 static int rt_get_caller_pc(addr_t
*paddr
, rt_context
*rc
, int level
)
1371 addr_t
*fp
= (addr_t
*)rc
->fp
;
1373 fp
= (addr_t
*)fp
[0];
1379 #elif defined(__riscv)
1380 static int rt_get_caller_pc(addr_t
*paddr
, rt_context
*rc
, int level
)
1385 addr_t
*fp
= (addr_t
*)rc
->fp
;
1386 while (--level
&& fp
>= (addr_t
*)0x1000)
1387 fp
= (addr_t
*)fp
[-2];
1388 if (fp
< (addr_t
*)0x1000)
1396 #warning add arch specific rt_get_caller_pc()
1397 static int rt_get_caller_pc(addr_t
*paddr
, rt_context
*rc
, int level
)
1403 #endif /* CONFIG_TCC_BACKTRACE */
1404 /* ------------------------------------------------------------- */
1405 #ifdef CONFIG_TCC_STATIC
1407 /* dummy function for profiling */
1408 ST_FUNC
void *dlopen(const char *filename
, int flag
)
1413 ST_FUNC
void dlclose(void *p
)
1417 ST_FUNC
const char *dlerror(void)
1422 typedef struct TCCSyms
{
1428 /* add the symbol you want here if no dynamic linking is done */
1429 static TCCSyms tcc_syms
[] = {
1430 #if !defined(CONFIG_TCCBOOT)
1431 #define TCCSYM(a) { #a, &a, },
1441 ST_FUNC
void *dlsym(void *handle
, const char *symbol
)
1445 while (p
->str
!= NULL
) {
1446 if (!strcmp(p
->str
, symbol
))
1453 #endif /* CONFIG_TCC_STATIC */
1454 #endif /* TCC_IS_NATIVE */
1455 /* ------------------------------------------------------------- */