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 int 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);
104 if (ptr
== MAP_FAILED
|| prx
== MAP_FAILED
)
105 return tcc_error_noabort("tccrun: could not map memory");
106 ptr_diff
= (char*)prx
- (char*)ptr
;
107 //printf("map %p %p %p\n", ptr, prx, (void*)ptr_diff);
110 ptr
= tcc_malloc(size
);
112 if (tcc_relocate_ex(s1
, ptr
, ptr_diff
))
114 dynarray_add(&s1
->runtime_mem
, &s1
->nb_runtime_mem
, (void*)(addr_t
)size
);
115 dynarray_add(&s1
->runtime_mem
, &s1
->nb_runtime_mem
, ptr
);
119 ST_FUNC
void tcc_run_free(TCCState
*s1
)
123 for (i
= 0; i
< s1
->nb_runtime_mem
; i
+= 2) {
124 unsigned size
= (unsigned)(addr_t
)s1
->runtime_mem
[i
];
125 void *ptr
= s1
->runtime_mem
[i
+1];
127 munmap(ptr
, size
* 2);
129 /* unprotect memory to make it usable for malloc again */
130 set_pages_executable(s1
, 2, ptr
, size
);
132 win64_del_function_table(*(void**)ptr
);
137 tcc_free(s1
->runtime_mem
);
140 static void run_cdtors(TCCState
*s1
, const char *start
, const char *end
,
141 int argc
, char **argv
, char **envp
)
143 void **a
= (void **)get_sym_addr(s1
, start
, 0, 0);
144 void **b
= (void **)get_sym_addr(s1
, end
, 0, 0);
146 ((void(*)(int, char **, char **))*a
++)(argc
, argv
, envp
);
149 #define NR_AT_EXIT 32
151 static struct exit_context
{
154 void (*exitfunc
[NR_AT_EXIT
])(int, void *);
155 void *exitarg
[NR_AT_EXIT
];
156 #ifndef CONFIG_TCC_BACKTRACE
161 static void init_exit(void)
163 struct exit_context
*e
= &g_exit_context
;
169 static void call_exit(int ret
)
171 struct exit_context
*e
= &g_exit_context
;
175 e
->exitfunc
[e
->nr_exit
](ret
, e
->exitarg
[e
->nr_exit
]);
179 static int rt_atexit(void (*function
)(void))
181 struct exit_context
*e
= &g_exit_context
;
183 if (e
->nr_exit
< NR_AT_EXIT
) {
184 e
->exitfunc
[e
->nr_exit
] = (void (*)(int, void *))function
;
185 e
->exitarg
[e
->nr_exit
++] = NULL
;
191 static int rt_on_exit(void (*function
)(int, void *), void *arg
)
193 struct exit_context
*e
= &g_exit_context
;
195 if (e
->nr_exit
< NR_AT_EXIT
) {
196 e
->exitfunc
[e
->nr_exit
] = function
;
197 e
->exitarg
[e
->nr_exit
++] = arg
;
203 static void run_exit(int code
)
205 struct exit_context
*e
= &g_exit_context
;
208 #ifdef CONFIG_TCC_BACKTRACE
209 longjmp((&g_rtctxt
)->jmp_buf, code
? code
: 256);
211 longjmp(e
->run_jmp_buf
, code
? code
: 256);
215 /* launch the compiled program with the given arguments */
216 LIBTCCAPI
int tcc_run(TCCState
*s1
, int argc
, char **argv
)
218 int (*prog_main
)(int, char **, char **), ret
;
219 #ifdef CONFIG_TCC_BACKTRACE
220 rt_context
*rc
= &g_rtctxt
;
223 #if defined(__APPLE__) || defined(__FreeBSD__)
225 #elif defined(__OpenBSD__) || defined(__NetBSD__)
226 extern char **environ
;
227 char **envp
= environ
;
229 char **envp
= environ
;
232 s1
->runtime_main
= s1
->nostdlib
? "_start" : "main";
233 if ((s1
->dflag
& 16) && (addr_t
)-1 == get_sym_addr(s1
, s1
->runtime_main
, 0, 1))
235 tcc_add_symbol(s1
, "exit", run_exit
);
236 tcc_add_symbol(s1
, "atexit", rt_atexit
);
237 tcc_add_symbol(s1
, "on_exit", rt_on_exit
);
238 if (tcc_relocate(s1
, TCC_RELOCATE_AUTO
) < 0)
240 prog_main
= (void*)get_sym_addr(s1
, s1
->runtime_main
, 1, 1);
241 if ((addr_t
)-1 == (addr_t
)prog_main
)
244 #ifdef CONFIG_TCC_BACKTRACE
245 memset(rc
, 0, sizeof *rc
);
249 rc
->dwarf_line
= dwarf_line_section
->data
;
250 rc
->dwarf_line_end
= dwarf_line_section
->data
+ dwarf_line_section
->data_offset
;
251 if (dwarf_line_str_section
)
252 rc
->dwarf_line_str
= dwarf_line_str_section
->data
;
256 rc
->stab_sym
= (Stab_Sym
*)stab_section
->data
;
257 rc
->stab_sym_end
= (Stab_Sym
*)(stab_section
->data
+ stab_section
->data_offset
);
258 rc
->stab_str
= (char *)stab_section
->link
->data
;
260 rc
->dwarf
= s1
->dwarf
;
261 rc
->esym_start
= (ElfW(Sym
) *)(symtab_section
->data
);
262 rc
->esym_end
= (ElfW(Sym
) *)(symtab_section
->data
+ symtab_section
->data_offset
);
263 rc
->elf_str
= (char *)symtab_section
->link
->data
;
265 rc
->prog_base
= text_section
->sh_addr
& 0xffffffff00000000ULL
;
266 #if defined TCC_TARGET_MACHO
268 rc
->prog_base
= (addr_t
) -1;
272 rc
->top_func
= tcc_get_symbol(s1
, "main");
273 rc
->num_callers
= s1
->rt_num_callers
;
275 if ((p
= tcc_get_symbol(s1
, "__rt_error")))
276 *(void**)p
= _rt_error
;
277 #ifdef CONFIG_TCC_BCHECK
278 if (s1
->do_bounds_check
) {
279 rc
->bounds_start
= (void*)bounds_section
->sh_addr
;
280 if ((p
= tcc_get_symbol(s1
, "__bound_init")))
281 ((void(*)(void*,int))p
)(rc
->bounds_start
, 1);
284 set_exception_handler();
288 errno
= 0; /* clean errno value */
292 /* These aren't C symbols, so don't need leading underscore handling. */
293 run_cdtors(s1
, "__init_array_start", "__init_array_end", argc
, argv
, envp
);
294 #ifdef CONFIG_TCC_BACKTRACE
295 if (!(ret
= setjmp(rc
->jmp_buf)))
297 if (!(ret
= setjmp((&g_exit_context
)->run_jmp_buf
)))
300 ret
= prog_main(argc
, argv
, envp
);
302 run_cdtors(s1
, "__fini_array_start", "__fini_array_end", 0, NULL
, NULL
);
304 if ((s1
->dflag
& 16) && ret
)
305 fprintf(s1
->ppfp
, "[returns %d]\n", ret
), fflush(s1
->ppfp
);
306 if ((s1
->dflag
& 16) == 0 && (&g_exit_context
)->exit_called
)
311 #define DEBUG_RUNMEN 0
313 /* enable rx/ro/rw permissions */
314 #define CONFIG_RUNMEM_RO 1
317 # define PAGE_ALIGN PAGESIZE
318 #elif defined TCC_TARGET_I386 || defined TCC_TARGET_X86_64
319 /* To avoid that x86 processors would reload cached instructions
320 each time when data is written in the near, we need to make
321 sure that code and data do not share the same 64 byte unit */
322 # define PAGE_ALIGN 64
324 # define PAGE_ALIGN 1
327 /* relocate code. Return -1 on error, required size if ptr is NULL,
328 otherwise copy code into buffer passed by the caller */
329 static int tcc_relocate_ex(TCCState
*s1
, void *ptr
, addr_t ptr_diff
)
332 unsigned offset
, length
, align
, max_align
, i
, k
, f
;
339 pe_output_file(s1
, NULL
);
342 resolve_common_syms(s1
);
343 build_got_entries(s1
, 0);
349 offset
= max_align
= 0, mem
= (addr_t
)ptr
;
351 offset
+= sizeof (void*); /* space for function_table pointer */
355 for (k
= 0; k
< 3; ++k
) { /* 0:rx, 1:ro, 2:rw sections */
357 for(i
= 1; i
< s1
->nb_sections
; i
++) {
358 static const char shf
[] = {
359 SHF_ALLOC
|SHF_EXECINSTR
, SHF_ALLOC
, SHF_ALLOC
|SHF_WRITE
362 if (shf
[k
] != (s
->sh_flags
& (SHF_ALLOC
|SHF_WRITE
|SHF_EXECINSTR
)))
364 length
= s
->data_offset
;
368 n
= (s
->sh_addr
- addr
) + length
;
369 ptr
= (void*)s
->sh_addr
;
371 ptr
= (void*)(s
->sh_addr
- ptr_diff
);
372 if (NULL
== s
->data
|| s
->sh_type
== SHT_NOBITS
)
373 memset(ptr
, 0, length
);
375 memcpy(ptr
, s
->data
, length
);
377 if (s
== s1
->uw_pdata
)
378 *(void**)mem
= win64_add_function_table(s1
);
383 s
->data_allocated
= 0;
388 align
= s
->sh_addralign
- 1;
389 if (++n
== 1 && align
< (PAGE_ALIGN
- 1))
390 align
= (PAGE_ALIGN
- 1);
391 if (max_align
< align
)
393 addr
= k
? mem
: mem
+ ptr_diff
;
394 offset
+= -(addr
+ offset
) & align
;
395 s
->sh_addr
= mem
? addr
+ offset
: 0;
399 printf("%d: %-16s %p len %04x align %04x\n",
400 k
, s
->name
, (void*)s
->sh_addr
, length
, align
+ 1);
403 if (copy
) { /* set permissions */
404 if (k
== 0 && ptr_diff
)
405 continue; /* not with HAVE_SELINUX */
407 #if !CONFIG_RUNMEM_RO
410 f
= 3; /* change only SHF_EXECINSTR to rwx */
413 printf("protect %d %p %04x\n", f
, (void*)addr
, n
);
416 if (set_pages_executable(s1
, f
, (void*)addr
, n
))
425 /* relocate symbols */
426 relocate_syms(s1
, s1
->symtab
, !(s1
->nostdlib
));
430 return offset
+ max_align
;
433 s1
->pe_imagebase
= mem
;
436 /* relocate sections */
437 #ifndef TCC_TARGET_PE
440 relocate_sections(s1
);
445 /* ------------------------------------------------------------- */
446 /* allow to run code in memory */
448 static int set_pages_executable(TCCState
*s1
, int mode
, void *ptr
, unsigned long length
)
451 static const unsigned char protect
[] = {
455 PAGE_EXECUTE_READWRITE
458 if (!VirtualProtect(ptr
, length
, protect
[mode
], &old
))
462 static const unsigned char protect
[] = {
463 PROT_READ
| PROT_EXEC
,
465 PROT_READ
| PROT_WRITE
,
466 PROT_READ
| PROT_WRITE
| PROT_EXEC
469 start
= (addr_t
)ptr
& ~(PAGESIZE
- 1);
470 end
= (addr_t
)ptr
+ length
;
471 end
= (end
+ PAGESIZE
- 1) & ~(PAGESIZE
- 1);
472 if (mprotect((void *)start
, end
- start
, protect
[mode
]))
473 return tcc_error_noabort("mprotect failed: did you mean to configure --with-selinux?");
474 /* XXX: BSD sometimes dump core with bad system call */
475 # if (defined TCC_TARGET_ARM && !TARGETOS_BSD) || defined TCC_TARGET_ARM64
476 if (mode
== 0 || mode
== 3) {
477 void __clear_cache(void *beginning
, void *end
);
478 __clear_cache(ptr
, (char *)ptr
+ length
);
486 static void *win64_add_function_table(TCCState
*s1
)
490 p
= (void*)s1
->uw_pdata
->sh_addr
;
492 (RUNTIME_FUNCTION
*)p
,
493 s1
->uw_pdata
->data_offset
/ sizeof (RUNTIME_FUNCTION
),
501 static void win64_del_function_table(void *p
)
504 RtlDeleteFunctionTable((RUNTIME_FUNCTION
*)p
);
508 #endif //ndef CONFIG_TCC_BACKTRACE_ONLY
509 /* ------------------------------------------------------------- */
510 #ifdef CONFIG_TCC_BACKTRACE
512 static int rt_vprintf(const char *fmt
, va_list ap
)
514 int ret
= vfprintf(stderr
, fmt
, ap
);
519 static int rt_printf(const char *fmt
, ...)
524 r
= rt_vprintf(fmt
, ap
);
529 static char *rt_elfsym(rt_context
*rc
, addr_t wanted_pc
, addr_t
*func_addr
)
532 for (esym
= rc
->esym_start
+ 1; esym
< rc
->esym_end
; ++esym
) {
533 int type
= ELFW(ST_TYPE
)(esym
->st_info
);
534 if ((type
== STT_FUNC
|| type
== STT_GNU_IFUNC
)
535 && wanted_pc
>= esym
->st_value
536 && wanted_pc
< esym
->st_value
+ esym
->st_size
) {
537 *func_addr
= esym
->st_value
;
538 return rc
->elf_str
+ esym
->st_name
;
545 /* print the position in the source file of PC value 'pc' by reading
546 the stabs debug information */
547 static addr_t
rt_printline (rt_context
*rc
, addr_t wanted_pc
,
548 const char *msg
, const char *skip
)
551 addr_t func_addr
, last_pc
, pc
;
552 const char *incl_files
[INCLUDE_STACK_SIZE
];
553 int incl_index
, last_incl_index
, len
, last_line_num
, i
;
561 last_pc
= (addr_t
)-1;
565 for (sym
= rc
->stab_sym
+ 1; sym
< rc
->stab_sym_end
; ++sym
) {
566 str
= rc
->stab_str
+ sym
->n_strx
;
569 switch(sym
->n_type
) {
577 if (sym
->n_strx
== 0) /* end of function */
581 /* Stab_Sym.n_value is only 32bits */
588 if (pc
>= wanted_pc
&& wanted_pc
>= last_pc
)
593 switch(sym
->n_type
) {
594 /* function start or end */
596 if (sym
->n_strx
== 0)
598 p
= strchr(str
, ':');
599 if (0 == p
|| (len
= p
- str
+ 1, len
> sizeof func_name
))
600 len
= sizeof func_name
;
601 pstrcpy(func_name
, len
, str
);
604 /* line number info */
607 last_line_num
= sym
->n_desc
;
608 last_incl_index
= incl_index
;
612 if (incl_index
< INCLUDE_STACK_SIZE
)
613 incl_files
[incl_index
++] = str
;
619 /* start/end of translation unit */
623 /* do not add path */
625 if (len
> 0 && str
[len
- 1] != '/')
626 incl_files
[incl_index
++] = str
;
631 last_pc
= (addr_t
)-1;
633 /* alternative file name (from #line or #include directives) */
636 incl_files
[incl_index
-1] = str
;
644 /* we try symtab symbols (no line number info) */
645 p
= rt_elfsym(rc
, wanted_pc
, &func_addr
);
647 pstrcpy(func_name
, sizeof func_name
, p
);
655 str
= incl_files
[--i
];
656 if (skip
[0] && strstr(str
, skip
))
658 rt_printf("%s:%d: ", str
, last_line_num
);
660 rt_printf("%08llx : ", (long long)wanted_pc
);
661 rt_printf("%s %s", msg
, func_name
[0] ? func_name
: "???");
664 rt_printf(" (included from ");
666 rt_printf("%s", incl_files
[i
]);
677 /* ------------------------------------------------------------- */
678 /* rt_printline - dwarf version */
680 #define MAX_128 ((8 * sizeof (long long) + 6) / 7)
682 #define DIR_TABLE_SIZE (64)
683 #define FILE_TABLE_SIZE (512)
685 #define dwarf_read_1(ln,end) \
686 ((ln) < (end) ? *(ln)++ : 0)
687 #define dwarf_read_2(ln,end) \
688 ((ln) + 2 < (end) ? (ln) += 2, read16le((ln) - 2) : 0)
689 #define dwarf_read_4(ln,end) \
690 ((ln) + 4 < (end) ? (ln) += 4, read32le((ln) - 4) : 0)
691 #define dwarf_read_8(ln,end) \
692 ((ln) + 8 < (end) ? (ln) += 8, read64le((ln) - 8) : 0)
693 #define dwarf_ignore_type(ln, end) /* timestamp/size/md5/... */ \
694 switch (entry_format[j].form) { \
695 case DW_FORM_data1: (ln) += 1; break; \
696 case DW_FORM_data2: (ln) += 2; break; \
697 case DW_FORM_data4: (ln) += 3; break; \
698 case DW_FORM_data8: (ln) += 8; break; \
699 case DW_FORM_data16: (ln) += 16; break; \
700 case DW_FORM_udata: dwarf_read_uleb128(&(ln), (end)); break; \
701 default: goto next_line; \
704 static unsigned long long
705 dwarf_read_uleb128(unsigned char **ln
, unsigned char *end
)
707 unsigned char *cp
= *ln
;
708 unsigned long long retval
= 0;
711 for (i
= 0; i
< MAX_128
; i
++) {
712 unsigned long long byte
= dwarf_read_1(cp
, end
);
714 retval
|= (byte
& 0x7f) << (i
* 7);
715 if ((byte
& 0x80) == 0)
723 dwarf_read_sleb128(unsigned char **ln
, unsigned char *end
)
725 unsigned char *cp
= *ln
;
726 long long retval
= 0;
729 for (i
= 0; i
< MAX_128
; i
++) {
730 unsigned long long byte
= dwarf_read_1(cp
, end
);
732 retval
|= (byte
& 0x7f) << (i
* 7);
733 if ((byte
& 0x80) == 0) {
734 if ((byte
& 0x40) && (i
+ 1) * 7 < 64)
735 retval
|= -1LL << ((i
+ 1) * 7);
743 static addr_t
rt_printline_dwarf (rt_context
*rc
, addr_t wanted_pc
,
744 const char *msg
, const char *skip
)
749 unsigned char *opcode_length
;
750 unsigned long long size
;
752 unsigned char version
;
753 unsigned int min_insn_length
;
754 unsigned int max_ops_per_insn
;
756 unsigned int line_range
;
757 unsigned int opcode_base
;
758 unsigned int opindex
;
763 unsigned long long value
;
768 unsigned int dir_size
;
770 char *dirs
[DIR_TABLE_SIZE
];
772 unsigned int filename_size
;
773 struct dwarf_filename_struct
{
774 unsigned int dir_entry
;
776 } filename_table
[FILE_TABLE_SIZE
];
786 while (ln
< rc
->dwarf_line_end
) {
796 size
= dwarf_read_4(ln
, rc
->dwarf_line_end
);
797 if (size
== 0xffffffffu
) // dwarf 64
798 length
= 8, size
= dwarf_read_8(ln
, rc
->dwarf_line_end
);
800 if (end
< ln
|| end
> rc
->dwarf_line_end
)
802 version
= dwarf_read_2(ln
, end
);
804 ln
+= length
+ 2; // address size, segment selector, prologue Length
806 ln
+= length
; // prologue Length
807 min_insn_length
= dwarf_read_1(ln
, end
);
809 max_ops_per_insn
= dwarf_read_1(ln
, end
);
811 max_ops_per_insn
= 1;
812 ln
++; // Initial value of 'is_stmt'
813 line_base
= dwarf_read_1(ln
, end
);
814 line_base
|= line_base
>= 0x80 ? ~0xff : 0;
815 line_range
= dwarf_read_1(ln
, end
);
816 opcode_base
= dwarf_read_1(ln
, end
);
818 ln
+= opcode_base
- 1;
821 col
= dwarf_read_1(ln
, end
);
822 for (i
= 0; i
< col
; i
++) {
823 entry_format
[i
].type
= dwarf_read_uleb128(&ln
, end
);
824 entry_format
[i
].form
= dwarf_read_uleb128(&ln
, end
);
826 dir_size
= dwarf_read_uleb128(&ln
, end
);
827 for (i
= 0; i
< dir_size
; i
++) {
828 for (j
= 0; j
< col
; j
++) {
829 if (entry_format
[j
].type
== DW_LNCT_path
) {
830 if (entry_format
[j
].form
!= DW_FORM_line_strp
)
833 value
= length
== 4 ? dwarf_read_4(ln
, end
)
834 : dwarf_read_8(ln
, end
);
835 if (i
< DIR_TABLE_SIZE
)
836 dirs
[i
] = (char *)rc
->dwarf_line_str
+ value
;
838 length
== 4 ? dwarf_read_4(ln
, end
)
839 : dwarf_read_8(ln
, end
);
843 dwarf_ignore_type(ln
, end
);
846 col
= dwarf_read_1(ln
, end
);
847 for (i
= 0; i
< col
; i
++) {
848 entry_format
[i
].type
= dwarf_read_uleb128(&ln
, end
);
849 entry_format
[i
].form
= dwarf_read_uleb128(&ln
, end
);
851 filename_size
= dwarf_read_uleb128(&ln
, end
);
852 for (i
= 0; i
< filename_size
; i
++)
853 for (j
= 0; j
< col
; j
++) {
854 if (entry_format
[j
].type
== DW_LNCT_path
) {
855 if (entry_format
[j
].form
!= DW_FORM_line_strp
)
857 value
= length
== 4 ? dwarf_read_4(ln
, end
)
858 : dwarf_read_8(ln
, end
);
859 if (i
< FILE_TABLE_SIZE
)
860 filename_table
[i
].name
=
861 (char *)rc
->dwarf_line_str
+ value
;
863 else if (entry_format
[j
].type
== DW_LNCT_directory_index
) {
864 switch (entry_format
[j
].form
) {
865 case DW_FORM_data1
: value
= dwarf_read_1(ln
, end
); break;
866 case DW_FORM_data2
: value
= dwarf_read_2(ln
, end
); break;
867 case DW_FORM_data4
: value
= dwarf_read_4(ln
, end
); break;
868 case DW_FORM_udata
: value
= dwarf_read_uleb128(&ln
, end
); break;
869 default: goto next_line
;
871 if (i
< FILE_TABLE_SIZE
)
872 filename_table
[i
].dir_entry
= value
;
875 dwarf_ignore_type(ln
, end
);
879 while ((dwarf_read_1(ln
, end
))) {
881 if (++dir_size
< DIR_TABLE_SIZE
)
882 dirs
[dir_size
- 1] = (char *)ln
- 1;
884 while (dwarf_read_1(ln
, end
)) {}
886 while ((dwarf_read_1(ln
, end
))) {
887 if (++filename_size
< FILE_TABLE_SIZE
) {
888 filename_table
[filename_size
- 1].name
= (char *)ln
- 1;
889 while (dwarf_read_1(ln
, end
)) {}
890 filename_table
[filename_size
- 1].dir_entry
=
891 dwarf_read_uleb128(&ln
, end
);
894 while (dwarf_read_1(ln
, end
)) {}
895 dwarf_read_uleb128(&ln
, end
);
897 dwarf_read_uleb128(&ln
, end
); // time
898 dwarf_read_uleb128(&ln
, end
); // size
901 if (filename_size
>= 1)
902 filename
= filename_table
[0].name
;
905 i
= dwarf_read_1(ln
, end
);
906 if (i
>= opcode_base
) {
907 if (max_ops_per_insn
== 1)
908 pc
+= ((i
- opcode_base
) / line_range
) * min_insn_length
;
910 pc
+= (opindex
+ (i
- opcode_base
) / line_range
) /
911 max_ops_per_insn
* min_insn_length
;
912 opindex
= (opindex
+ (i
- opcode_base
) / line_range
) %
915 i
= (int)((i
- opcode_base
) % line_range
) + line_base
;
917 if (pc
>= wanted_pc
&& wanted_pc
>= last_pc
)
924 len
= dwarf_read_uleb128(&ln
, end
);
929 switch (dwarf_read_1(cp
, end
)) {
930 case DW_LNE_end_sequence
:
932 case DW_LNE_set_address
:
934 pc
= dwarf_read_4(cp
, end
);
936 pc
= dwarf_read_8(cp
, end
);
938 #if defined TCC_TARGET_MACHO
939 if (rc
->prog_base
!= (addr_t
) -1)
944 case DW_LNE_define_file
: /* deprecated */
945 if (++filename_size
< FILE_TABLE_SIZE
) {
946 filename_table
[filename_size
- 1].name
= (char *)ln
- 1;
947 while (dwarf_read_1(ln
, end
)) {}
948 filename_table
[filename_size
- 1].dir_entry
=
949 dwarf_read_uleb128(&ln
, end
);
952 while (dwarf_read_1(ln
, end
)) {}
953 dwarf_read_uleb128(&ln
, end
);
955 dwarf_read_uleb128(&ln
, end
); // time
956 dwarf_read_uleb128(&ln
, end
); // size
958 case DW_LNE_hi_user
- 1:
959 function
= (char *)cp
;
966 case DW_LNS_advance_pc
:
967 if (max_ops_per_insn
== 1)
968 pc
+= dwarf_read_uleb128(&ln
, end
) * min_insn_length
;
970 unsigned long long off
= dwarf_read_uleb128(&ln
, end
);
972 pc
+= (opindex
+ off
) / max_ops_per_insn
*
974 opindex
= (opindex
+ off
) % max_ops_per_insn
;
978 case DW_LNS_advance_line
:
979 line
+= dwarf_read_sleb128(&ln
, end
);
981 case DW_LNS_set_file
:
982 i
= dwarf_read_uleb128(&ln
, end
);
983 i
-= i
> 0 && version
< 5;
984 if (i
< FILE_TABLE_SIZE
&& i
< filename_size
)
985 filename
= filename_table
[i
].name
;
987 case DW_LNS_const_add_pc
:
988 if (max_ops_per_insn
== 1)
989 pc
+= ((255 - opcode_base
) / line_range
) * min_insn_length
;
991 unsigned int off
= (255 - opcode_base
) / line_range
;
993 pc
+= ((opindex
+ off
) / max_ops_per_insn
) *
995 opindex
= (opindex
+ off
) % max_ops_per_insn
;
999 case DW_LNS_fixed_advance_pc
:
1000 i
= dwarf_read_2(ln
, end
);
1006 for (j
= 0; j
< opcode_length
[i
- 1]; j
++)
1007 dwarf_read_uleb128 (&ln
, end
);
1018 /* we try symtab symbols (no line number info) */
1019 function
= rt_elfsym(rc
, wanted_pc
, &func_addr
);
1022 if ((rc
= rc
->next
))
1026 if (skip
[0] && strstr(filename
, skip
))
1028 rt_printf("%s:%d: ", filename
, line
);
1031 rt_printf("0x%08llx : ", (long long)wanted_pc
);
1032 rt_printf("%s %s", msg
, function
? function
: "???");
1033 return (addr_t
)func_addr
;
1035 /* ------------------------------------------------------------- */
1037 static int rt_get_caller_pc(addr_t
*paddr
, rt_context
*rc
, int level
);
1039 static int _rt_error(void *fp
, void *ip
, const char *fmt
, va_list ap
)
1041 rt_context
*rc
= &g_rtctxt
;
1044 int i
, level
, ret
, n
;
1045 const char *a
, *b
, *msg
;
1048 /* we're called from tcc_backtrace. */
1049 rc
->fp
= (addr_t
)fp
;
1050 rc
->ip
= (addr_t
)ip
;
1053 /* we're called from signal/exception handler */
1054 msg
= "RUNTIME ERROR: ";
1058 /* If fmt is like "^file.c^..." then skip calls from 'file.c' */
1059 if (fmt
[0] == '^' && (b
= strchr(a
= fmt
+ 1, fmt
[0]))) {
1060 memcpy(skip
, a
, b
- a
), skip
[b
- a
] = 0;
1064 n
= rc
->num_callers
? rc
->num_callers
: 6;
1065 for (i
= level
= 0; level
< n
; i
++) {
1066 ret
= rt_get_caller_pc(&pc
, rc
, i
);
1070 pc
= rt_printline_dwarf(rc
, pc
, level
? "by" : "at", skip
);
1072 pc
= rt_printline(rc
, pc
, level
? "by" : "at", skip
);
1073 if (pc
== (addr_t
)-1)
1079 rt_vprintf(fmt
, ap
);
1080 } else if (ret
== -1)
1083 if (ret
== -1 || (pc
== (addr_t
)rc
->top_func
&& pc
))
1088 rc
->ip
= rc
->fp
= 0;
1092 /* emit a run time error at position 'pc' */
1093 static int rt_error(const char *fmt
, ...)
1098 ret
= _rt_error(0, 0, fmt
, ap
);
1103 static void rt_exit(int code
)
1105 rt_context
*rc
= &g_rtctxt
;
1107 longjmp(rc
->jmp_buf, code
? code
: 256);
1111 /* ------------------------------------------------------------- */
1114 # include <signal.h>
1115 # ifndef __OpenBSD__
1116 # include <sys/ucontext.h>
1119 # define ucontext_t CONTEXT
1122 /* translate from ucontext_t* to internal rt_context * */
1123 static void rt_getcontext(ucontext_t
*uc
, rt_context
*rc
)
1129 #elif defined _WIN32
1133 #elif defined __i386__
1134 # if defined(__APPLE__)
1135 rc
->ip
= uc
->uc_mcontext
->__ss
.__eip
;
1136 rc
->fp
= uc
->uc_mcontext
->__ss
.__ebp
;
1137 # elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
1138 rc
->ip
= uc
->uc_mcontext
.mc_eip
;
1139 rc
->fp
= uc
->uc_mcontext
.mc_ebp
;
1140 # elif defined(__dietlibc__)
1141 rc
->ip
= uc
->uc_mcontext
.eip
;
1142 rc
->fp
= uc
->uc_mcontext
.ebp
;
1143 # elif defined(__NetBSD__)
1144 rc
->ip
= uc
->uc_mcontext
.__gregs
[_REG_EIP
];
1145 rc
->fp
= uc
->uc_mcontext
.__gregs
[_REG_EBP
];
1146 # elif defined(__OpenBSD__)
1147 rc
->ip
= uc
->sc_eip
;
1148 rc
->fp
= uc
->sc_ebp
;
1149 # elif !defined REG_EIP && defined EIP /* fix for glibc 2.1 */
1150 rc
->ip
= uc
->uc_mcontext
.gregs
[EIP
];
1151 rc
->fp
= uc
->uc_mcontext
.gregs
[EBP
];
1153 rc
->ip
= uc
->uc_mcontext
.gregs
[REG_EIP
];
1154 rc
->fp
= uc
->uc_mcontext
.gregs
[REG_EBP
];
1156 #elif defined(__x86_64__)
1157 # if defined(__APPLE__)
1158 rc
->ip
= uc
->uc_mcontext
->__ss
.__rip
;
1159 rc
->fp
= uc
->uc_mcontext
->__ss
.__rbp
;
1160 # elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
1161 rc
->ip
= uc
->uc_mcontext
.mc_rip
;
1162 rc
->fp
= uc
->uc_mcontext
.mc_rbp
;
1163 # elif defined(__NetBSD__)
1164 rc
->ip
= uc
->uc_mcontext
.__gregs
[_REG_RIP
];
1165 rc
->fp
= uc
->uc_mcontext
.__gregs
[_REG_RBP
];
1166 # elif defined(__OpenBSD__)
1167 rc
->ip
= uc
->sc_rip
;
1168 rc
->fp
= uc
->sc_rbp
;
1170 rc
->ip
= uc
->uc_mcontext
.gregs
[REG_RIP
];
1171 rc
->fp
= uc
->uc_mcontext
.gregs
[REG_RBP
];
1173 #elif defined(__arm__) && defined(__NetBSD__)
1174 rc
->ip
= uc
->uc_mcontext
.__gregs
[_REG_PC
];
1175 rc
->fp
= uc
->uc_mcontext
.__gregs
[_REG_FP
];
1176 #elif defined(__arm__) && defined(__OpenBSD__)
1178 rc
->fp
= uc
->sc_r11
;
1179 #elif defined(__arm__) && defined(__FreeBSD__)
1180 rc
->ip
= uc
->uc_mcontext
.__gregs
[_REG_PC
];
1181 rc
->fp
= uc
->uc_mcontext
.__gregs
[_REG_FP
];
1182 #elif defined(__arm__)
1183 rc
->ip
= uc
->uc_mcontext
.arm_pc
;
1184 rc
->fp
= uc
->uc_mcontext
.arm_fp
;
1185 #elif defined(__aarch64__) && defined(__APPLE__)
1187 // /Library/Developer/CommandLineTools/SDKs/MacOSX11.1.sdk/usr/include/mach/arm/_structs.h
1188 rc
->ip
= uc
->uc_mcontext
->__ss
.__pc
;
1189 rc
->fp
= uc
->uc_mcontext
->__ss
.__fp
;
1190 #elif defined(__aarch64__) && defined(__FreeBSD__)
1191 rc
->ip
= uc
->uc_mcontext
.mc_gpregs
.gp_elr
; /* aka REG_PC */
1192 rc
->fp
= uc
->uc_mcontext
.mc_gpregs
.gp_x
[29];
1193 #elif defined(__aarch64__) && defined(__NetBSD__)
1194 rc
->ip
= uc
->uc_mcontext
.__gregs
[_REG_PC
];
1195 rc
->fp
= uc
->uc_mcontext
.__gregs
[_REG_FP
];
1196 #elif defined(__aarch64__) && defined(__OpenBSD__)
1197 rc
->ip
= uc
->sc_elr
;
1198 rc
->fp
= uc
->sc_x
[29];
1199 #elif defined(__aarch64__)
1200 rc
->ip
= uc
->uc_mcontext
.pc
;
1201 rc
->fp
= uc
->uc_mcontext
.regs
[29];
1202 #elif defined(__riscv) && defined(__OpenBSD__)
1203 rc
->ip
= uc
->sc_sepc
;
1204 rc
->fp
= uc
->sc_s
[0];
1205 #elif defined(__riscv)
1206 rc
->ip
= uc
->uc_mcontext
.__gregs
[REG_PC
];
1207 rc
->fp
= uc
->uc_mcontext
.__gregs
[REG_S0
];
1211 /* ------------------------------------------------------------- */
1213 /* signal handler for fatal errors */
1214 static void sig_error(int signum
, siginfo_t
*siginf
, void *puc
)
1216 rt_context
*rc
= &g_rtctxt
;
1217 rt_getcontext(puc
, rc
);
1221 switch(siginf
->si_code
) {
1224 rt_error("division by zero");
1227 rt_error("floating point exception");
1233 rt_error("invalid memory access");
1236 rt_error("illegal instruction");
1239 rt_error("abort() called");
1242 rt_error("caught signal %d", signum
);
1249 # define SA_SIGINFO 0x00000004u
1252 /* Generate a stack backtrace when a CPU exception occurs. */
1253 static void set_exception_handler(void)
1255 struct sigaction sigact
;
1256 /* install TCC signal handlers to print debug info on fatal
1258 sigemptyset (&sigact
.sa_mask
);
1259 sigact
.sa_flags
= SA_SIGINFO
| SA_RESETHAND
;
1260 #if 0//def SIGSTKSZ // this causes signals not to work at all on some (older) linuxes
1261 sigact
.sa_flags
|= SA_ONSTACK
;
1263 sigact
.sa_sigaction
= sig_error
;
1264 sigemptyset(&sigact
.sa_mask
);
1265 sigaction(SIGFPE
, &sigact
, NULL
);
1266 sigaction(SIGILL
, &sigact
, NULL
);
1267 sigaction(SIGSEGV
, &sigact
, NULL
);
1268 sigaction(SIGBUS
, &sigact
, NULL
);
1269 sigaction(SIGABRT
, &sigact
, NULL
);
1271 /* This allows stack overflow to be reported instead of a SEGV */
1274 static unsigned char stack
[SIGSTKSZ
] __attribute__((aligned(16)));
1277 ss
.ss_size
= SIGSTKSZ
;
1279 sigaltstack(&ss
, NULL
);
1286 /* signal handler for fatal errors */
1287 static long __stdcall
cpu_exception_handler(EXCEPTION_POINTERS
*ex_info
)
1289 rt_context
*rc
= &g_rtctxt
;
1291 rt_getcontext(ex_info
->ContextRecord
, rc
);
1293 switch (code
= ex_info
->ExceptionRecord
->ExceptionCode
) {
1294 case EXCEPTION_ACCESS_VIOLATION
:
1295 rt_error("invalid memory access");
1297 case EXCEPTION_STACK_OVERFLOW
:
1298 rt_error("stack overflow");
1300 case EXCEPTION_INT_DIVIDE_BY_ZERO
:
1301 rt_error("division by zero");
1303 case EXCEPTION_BREAKPOINT
:
1304 case EXCEPTION_SINGLE_STEP
:
1305 rc
->ip
= *(addr_t
*)rc
->sp
;
1306 rt_error("breakpoint/single-step exception:");
1307 return EXCEPTION_CONTINUE_SEARCH
;
1309 rt_error("caught exception %08x", code
);
1314 return EXCEPTION_EXECUTE_HANDLER
;
1317 /* Generate a stack backtrace when a CPU exception occurs. */
1318 static void set_exception_handler(void)
1320 SetUnhandledExceptionFilter(cpu_exception_handler
);
1325 /* ------------------------------------------------------------- */
1326 /* return the PC at frame level 'level'. Return negative if not found */
1327 #if defined(__i386__) || defined(__x86_64__)
1328 static int rt_get_caller_pc(addr_t
*paddr
, rt_context
*rc
, int level
)
1337 /* XXX: check address validity with program info */
1340 fp
= ((addr_t
*)fp
)[0];
1343 ip
= ((addr_t
*)fp
)[1];
1351 #elif defined(__arm__)
1352 static int rt_get_caller_pc(addr_t
*paddr
, rt_context
*rc
, int level
)
1354 /* XXX: only supports linux/bsd */
1355 #if !defined(__linux__) && \
1356 !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__)
1364 fp
= ((addr_t
*)fp
)[0];
1365 *paddr
= ((addr_t
*)fp
)[2];
1371 #elif defined(__aarch64__)
1372 static int rt_get_caller_pc(addr_t
*paddr
, rt_context
*rc
, int level
)
1377 addr_t
*fp
= (addr_t
*)rc
->fp
;
1379 fp
= (addr_t
*)fp
[0];
1385 #elif defined(__riscv)
1386 static int rt_get_caller_pc(addr_t
*paddr
, rt_context
*rc
, int level
)
1391 addr_t
*fp
= (addr_t
*)rc
->fp
;
1392 while (--level
&& fp
>= (addr_t
*)0x1000)
1393 fp
= (addr_t
*)fp
[-2];
1394 if (fp
< (addr_t
*)0x1000)
1402 #warning add arch specific rt_get_caller_pc()
1403 static int rt_get_caller_pc(addr_t
*paddr
, rt_context
*rc
, int level
)
1409 #endif /* CONFIG_TCC_BACKTRACE */
1410 /* ------------------------------------------------------------- */
1411 #ifdef CONFIG_TCC_STATIC
1413 /* dummy function for profiling */
1414 ST_FUNC
void *dlopen(const char *filename
, int flag
)
1419 ST_FUNC
void dlclose(void *p
)
1423 ST_FUNC
const char *dlerror(void)
1428 typedef struct TCCSyms
{
1434 /* add the symbol you want here if no dynamic linking is done */
1435 static TCCSyms tcc_syms
[] = {
1436 #if !defined(CONFIG_TCCBOOT)
1437 #define TCCSYM(a) { #a, &a, },
1447 ST_FUNC
void *dlsym(void *handle
, const char *symbol
)
1451 while (p
->str
!= NULL
) {
1452 if (!strcmp(p
->str
, symbol
))
1459 #endif /* CONFIG_TCC_STATIC */
1460 #endif /* TCC_IS_NATIVE */
1461 /* ------------------------------------------------------------- */