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
];
774 #if defined TCC_TARGET_MACHO
784 while (ln
< rc
->dwarf_line_end
) {
794 size
= dwarf_read_4(ln
, rc
->dwarf_line_end
);
795 if (size
== 0xffffffffu
) // dwarf 64
796 length
= 8, size
= dwarf_read_8(ln
, rc
->dwarf_line_end
);
798 if (end
< ln
|| end
> rc
->dwarf_line_end
)
800 version
= dwarf_read_2(ln
, end
);
802 ln
+= length
+ 2; // address size, segment selector, prologue Length
804 ln
+= length
; // prologue Length
805 min_insn_length
= dwarf_read_1(ln
, end
);
807 max_ops_per_insn
= dwarf_read_1(ln
, end
);
809 max_ops_per_insn
= 1;
810 ln
++; // Initial value of 'is_stmt'
811 line_base
= dwarf_read_1(ln
, end
);
812 line_base
|= line_base
>= 0x80 ? ~0xff : 0;
813 line_range
= dwarf_read_1(ln
, end
);
814 opcode_base
= dwarf_read_1(ln
, end
);
816 ln
+= opcode_base
- 1;
819 col
= dwarf_read_1(ln
, end
);
820 for (i
= 0; i
< col
; i
++) {
821 entry_format
[i
].type
= dwarf_read_uleb128(&ln
, end
);
822 entry_format
[i
].form
= dwarf_read_uleb128(&ln
, end
);
824 dir_size
= dwarf_read_uleb128(&ln
, end
);
825 for (i
= 0; i
< dir_size
; i
++) {
826 for (j
= 0; j
< col
; j
++) {
827 if (entry_format
[j
].type
== DW_LNCT_path
) {
828 if (entry_format
[j
].form
!= DW_FORM_line_strp
)
831 value
= length
== 4 ? dwarf_read_4(ln
, end
)
832 : dwarf_read_8(ln
, end
);
833 if (i
< DIR_TABLE_SIZE
)
834 dirs
[i
] = (char *)rc
->dwarf_line_str
+ value
;
836 length
== 4 ? dwarf_read_4(ln
, end
)
837 : dwarf_read_8(ln
, end
);
841 dwarf_ignore_type(ln
, end
);
844 col
= dwarf_read_1(ln
, end
);
845 for (i
= 0; i
< col
; i
++) {
846 entry_format
[i
].type
= dwarf_read_uleb128(&ln
, end
);
847 entry_format
[i
].form
= dwarf_read_uleb128(&ln
, end
);
849 filename_size
= dwarf_read_uleb128(&ln
, end
);
850 for (i
= 0; i
< filename_size
; i
++)
851 for (j
= 0; j
< col
; j
++) {
852 if (entry_format
[j
].type
== DW_LNCT_path
) {
853 if (entry_format
[j
].form
!= DW_FORM_line_strp
)
855 value
= length
== 4 ? dwarf_read_4(ln
, end
)
856 : dwarf_read_8(ln
, end
);
857 if (i
< FILE_TABLE_SIZE
)
858 filename_table
[i
].name
=
859 (char *)rc
->dwarf_line_str
+ value
;
861 else if (entry_format
[j
].type
== DW_LNCT_directory_index
) {
862 switch (entry_format
[j
].form
) {
863 case DW_FORM_data1
: value
= dwarf_read_1(ln
, end
); break;
864 case DW_FORM_data2
: value
= dwarf_read_2(ln
, end
); break;
865 case DW_FORM_data4
: value
= dwarf_read_4(ln
, end
); break;
866 case DW_FORM_udata
: value
= dwarf_read_uleb128(&ln
, end
); break;
867 default: goto next_line
;
869 if (i
< FILE_TABLE_SIZE
)
870 filename_table
[i
].dir_entry
= value
;
873 dwarf_ignore_type(ln
, end
);
877 while ((dwarf_read_1(ln
, end
))) {
879 if (++dir_size
< DIR_TABLE_SIZE
)
880 dirs
[dir_size
- 1] = (char *)ln
- 1;
882 while (dwarf_read_1(ln
, end
)) {}
884 while ((dwarf_read_1(ln
, end
))) {
885 if (++filename_size
< FILE_TABLE_SIZE
) {
886 filename_table
[filename_size
- 1].name
= (char *)ln
- 1;
887 while (dwarf_read_1(ln
, end
)) {}
888 filename_table
[filename_size
- 1].dir_entry
=
889 dwarf_read_uleb128(&ln
, end
);
892 while (dwarf_read_1(ln
, end
)) {}
893 dwarf_read_uleb128(&ln
, end
);
895 dwarf_read_uleb128(&ln
, end
); // time
896 dwarf_read_uleb128(&ln
, end
); // size
899 if (filename_size
>= 1)
900 filename
= filename_table
[0].name
;
903 i
= dwarf_read_1(ln
, end
);
904 if (i
>= opcode_base
) {
905 if (max_ops_per_insn
== 1)
906 pc
+= ((i
- opcode_base
) / line_range
) * min_insn_length
;
908 pc
+= (opindex
+ (i
- opcode_base
) / line_range
) /
909 max_ops_per_insn
* min_insn_length
;
910 opindex
= (opindex
+ (i
- opcode_base
) / line_range
) %
913 i
= (int)((i
- opcode_base
) % line_range
) + line_base
;
915 if (pc
>= wanted_pc
&& wanted_pc
>= last_pc
)
922 len
= dwarf_read_uleb128(&ln
, end
);
927 switch (dwarf_read_1(cp
, end
)) {
928 case DW_LNE_end_sequence
:
930 case DW_LNE_set_address
:
932 pc
= dwarf_read_4(cp
, end
);
934 pc
= dwarf_read_8(cp
, end
);
936 #if defined TCC_TARGET_MACHO
937 if (first_pc
== 0 && rc
->prog_base
!= (addr_t
) -1)
938 first_pc
+= rc
->prog_base
- ((uint64_t)1 << 32);
943 case DW_LNE_define_file
: /* deprecated */
944 if (++filename_size
< FILE_TABLE_SIZE
) {
945 filename_table
[filename_size
- 1].name
= (char *)ln
- 1;
946 while (dwarf_read_1(ln
, end
)) {}
947 filename_table
[filename_size
- 1].dir_entry
=
948 dwarf_read_uleb128(&ln
, end
);
951 while (dwarf_read_1(ln
, end
)) {}
952 dwarf_read_uleb128(&ln
, end
);
954 dwarf_read_uleb128(&ln
, end
); // time
955 dwarf_read_uleb128(&ln
, end
); // size
957 case DW_LNE_hi_user
- 1:
958 function
= (char *)cp
;
965 case DW_LNS_advance_pc
:
966 if (max_ops_per_insn
== 1)
967 pc
+= dwarf_read_uleb128(&ln
, end
) * min_insn_length
;
969 unsigned long long off
= dwarf_read_uleb128(&ln
, end
);
971 pc
+= (opindex
+ off
) / max_ops_per_insn
*
973 opindex
= (opindex
+ off
) % max_ops_per_insn
;
977 case DW_LNS_advance_line
:
978 line
+= dwarf_read_sleb128(&ln
, end
);
980 case DW_LNS_set_file
:
981 i
= dwarf_read_uleb128(&ln
, end
);
982 if (i
< FILE_TABLE_SIZE
&& i
< filename_size
)
983 filename
= filename_table
[i
].name
;
985 case DW_LNS_const_add_pc
:
986 if (max_ops_per_insn
== 1)
987 pc
+= ((255 - opcode_base
) / line_range
) * min_insn_length
;
989 unsigned int off
= (255 - opcode_base
) / line_range
;
991 pc
+= ((opindex
+ off
) / max_ops_per_insn
) *
993 opindex
= (opindex
+ off
) % max_ops_per_insn
;
997 case DW_LNS_fixed_advance_pc
:
998 i
= dwarf_read_2(ln
, end
);
1004 for (j
= 0; j
< opcode_length
[i
- 1]; j
++)
1005 dwarf_read_uleb128 (&ln
, end
);
1016 /* we try symtab symbols (no line number info) */
1017 function
= rt_elfsym(rc
, wanted_pc
, &func_addr
);
1020 if ((rc
= rc
->next
))
1024 if (skip
[0] && strstr(filename
, skip
))
1026 rt_printf("%s:%d: ", filename
, line
);
1029 rt_printf("0x%08llx : ", (long long)wanted_pc
);
1030 rt_printf("%s %s", msg
, function
? function
: "???");
1031 return (addr_t
)func_addr
;
1033 /* ------------------------------------------------------------- */
1035 static int rt_get_caller_pc(addr_t
*paddr
, rt_context
*rc
, int level
);
1037 static int _rt_error(void *fp
, void *ip
, const char *fmt
, va_list ap
)
1039 rt_context
*rc
= &g_rtctxt
;
1042 int i
, level
, ret
, n
;
1043 const char *a
, *b
, *msg
;
1046 /* we're called from tcc_backtrace. */
1047 rc
->fp
= (addr_t
)fp
;
1048 rc
->ip
= (addr_t
)ip
;
1051 /* we're called from signal/exception handler */
1052 msg
= "RUNTIME ERROR: ";
1056 /* If fmt is like "^file.c^..." then skip calls from 'file.c' */
1057 if (fmt
[0] == '^' && (b
= strchr(a
= fmt
+ 1, fmt
[0]))) {
1058 memcpy(skip
, a
, b
- a
), skip
[b
- a
] = 0;
1062 n
= rc
->num_callers
? rc
->num_callers
: 6;
1063 for (i
= level
= 0; level
< n
; i
++) {
1064 ret
= rt_get_caller_pc(&pc
, rc
, i
);
1068 pc
= rt_printline_dwarf(rc
, pc
, level
? "by" : "at", skip
);
1070 pc
= rt_printline(rc
, pc
, level
? "by" : "at", skip
);
1071 if (pc
== (addr_t
)-1)
1077 rt_vprintf(fmt
, ap
);
1078 } else if (ret
== -1)
1081 if (ret
== -1 || (pc
== (addr_t
)rc
->top_func
&& pc
))
1086 rc
->ip
= rc
->fp
= 0;
1090 /* emit a run time error at position 'pc' */
1091 static int rt_error(const char *fmt
, ...)
1096 ret
= _rt_error(0, 0, fmt
, ap
);
1101 static void rt_exit(int code
)
1103 rt_context
*rc
= &g_rtctxt
;
1105 longjmp(rc
->jmp_buf, code
? code
: 256);
1109 /* ------------------------------------------------------------- */
1112 # include <signal.h>
1113 # ifndef __OpenBSD__
1114 # include <sys/ucontext.h>
1117 # define ucontext_t CONTEXT
1120 /* translate from ucontext_t* to internal rt_context * */
1121 static void rt_getcontext(ucontext_t
*uc
, rt_context
*rc
)
1127 #elif defined _WIN32
1131 #elif defined __i386__
1132 # if defined(__APPLE__)
1133 rc
->ip
= uc
->uc_mcontext
->__ss
.__eip
;
1134 rc
->fp
= uc
->uc_mcontext
->__ss
.__ebp
;
1135 # elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
1136 rc
->ip
= uc
->uc_mcontext
.mc_eip
;
1137 rc
->fp
= uc
->uc_mcontext
.mc_ebp
;
1138 # elif defined(__dietlibc__)
1139 rc
->ip
= uc
->uc_mcontext
.eip
;
1140 rc
->fp
= uc
->uc_mcontext
.ebp
;
1141 # elif defined(__NetBSD__)
1142 rc
->ip
= uc
->uc_mcontext
.__gregs
[_REG_EIP
];
1143 rc
->fp
= uc
->uc_mcontext
.__gregs
[_REG_EBP
];
1144 # elif defined(__OpenBSD__)
1145 rc
->ip
= uc
->sc_eip
;
1146 rc
->fp
= uc
->sc_ebp
;
1147 # elif !defined REG_EIP && defined EIP /* fix for glibc 2.1 */
1148 rc
->ip
= uc
->uc_mcontext
.gregs
[EIP
];
1149 rc
->fp
= uc
->uc_mcontext
.gregs
[EBP
];
1151 rc
->ip
= uc
->uc_mcontext
.gregs
[REG_EIP
];
1152 rc
->fp
= uc
->uc_mcontext
.gregs
[REG_EBP
];
1154 #elif defined(__x86_64__)
1155 # if defined(__APPLE__)
1156 rc
->ip
= uc
->uc_mcontext
->__ss
.__rip
;
1157 rc
->fp
= uc
->uc_mcontext
->__ss
.__rbp
;
1158 # elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
1159 rc
->ip
= uc
->uc_mcontext
.mc_rip
;
1160 rc
->fp
= uc
->uc_mcontext
.mc_rbp
;
1161 # elif defined(__NetBSD__)
1162 rc
->ip
= uc
->uc_mcontext
.__gregs
[_REG_RIP
];
1163 rc
->fp
= uc
->uc_mcontext
.__gregs
[_REG_RBP
];
1164 # elif defined(__OpenBSD__)
1165 rc
->ip
= uc
->sc_rip
;
1166 rc
->fp
= uc
->sc_rbp
;
1168 rc
->ip
= uc
->uc_mcontext
.gregs
[REG_RIP
];
1169 rc
->fp
= uc
->uc_mcontext
.gregs
[REG_RBP
];
1171 #elif defined(__arm__) && defined(__NetBSD__)
1172 rc
->ip
= uc
->uc_mcontext
.__gregs
[_REG_PC
];
1173 rc
->fp
= uc
->uc_mcontext
.__gregs
[_REG_FP
];
1174 #elif defined(__arm__) && defined(__OpenBSD__)
1176 rc
->fp
= uc
->sc_r11
;
1177 #elif defined(__arm__) && defined(__FreeBSD__)
1178 rc
->ip
= uc
->uc_mcontext
.__gregs
[_REG_PC
];
1179 rc
->fp
= uc
->uc_mcontext
.__gregs
[_REG_FP
];
1180 #elif defined(__arm__)
1181 rc
->ip
= uc
->uc_mcontext
.arm_pc
;
1182 rc
->fp
= uc
->uc_mcontext
.arm_fp
;
1183 #elif defined(__aarch64__) && defined(__APPLE__)
1185 // /Library/Developer/CommandLineTools/SDKs/MacOSX11.1.sdk/usr/include/mach/arm/_structs.h
1186 rc
->ip
= uc
->uc_mcontext
->__ss
.__pc
;
1187 rc
->fp
= uc
->uc_mcontext
->__ss
.__fp
;
1188 #elif defined(__aarch64__) && defined(__FreeBSD__)
1189 rc
->ip
= uc
->uc_mcontext
.mc_gpregs
.gp_elr
; /* aka REG_PC */
1190 rc
->fp
= uc
->uc_mcontext
.mc_gpregs
.gp_x
[29];
1191 #elif defined(__aarch64__) && defined(__NetBSD__)
1192 rc
->ip
= uc
->uc_mcontext
.__gregs
[_REG_PC
];
1193 rc
->fp
= uc
->uc_mcontext
.__gregs
[_REG_FP
];
1194 #elif defined(__aarch64__) && defined(__OpenBSD__)
1195 rc
->ip
= uc
->sc_elr
;
1196 rc
->fp
= uc
->sc_x
[29];
1197 #elif defined(__aarch64__)
1198 rc
->ip
= uc
->uc_mcontext
.pc
;
1199 rc
->fp
= uc
->uc_mcontext
.regs
[29];
1200 #elif defined(__riscv) && defined(__OpenBSD__)
1201 rc
->ip
= uc
->sc_sepc
;
1202 rc
->fp
= uc
->sc_s
[0];
1203 #elif defined(__riscv)
1204 rc
->ip
= uc
->uc_mcontext
.__gregs
[REG_PC
];
1205 rc
->fp
= uc
->uc_mcontext
.__gregs
[REG_S0
];
1209 /* ------------------------------------------------------------- */
1211 /* signal handler for fatal errors */
1212 static void sig_error(int signum
, siginfo_t
*siginf
, void *puc
)
1214 rt_context
*rc
= &g_rtctxt
;
1215 rt_getcontext(puc
, rc
);
1219 switch(siginf
->si_code
) {
1222 rt_error("division by zero");
1225 rt_error("floating point exception");
1231 rt_error("invalid memory access");
1234 rt_error("illegal instruction");
1237 rt_error("abort() called");
1240 rt_error("caught signal %d", signum
);
1247 # define SA_SIGINFO 0x00000004u
1250 /* Generate a stack backtrace when a CPU exception occurs. */
1251 static void set_exception_handler(void)
1253 struct sigaction sigact
;
1254 /* install TCC signal handlers to print debug info on fatal
1256 sigemptyset (&sigact
.sa_mask
);
1257 sigact
.sa_flags
= SA_SIGINFO
| SA_RESETHAND
;
1258 #if 0//def SIGSTKSZ // this causes signals not to work at all on some (older) linuxes
1259 sigact
.sa_flags
|= SA_ONSTACK
;
1261 sigact
.sa_sigaction
= sig_error
;
1262 sigemptyset(&sigact
.sa_mask
);
1263 sigaction(SIGFPE
, &sigact
, NULL
);
1264 sigaction(SIGILL
, &sigact
, NULL
);
1265 sigaction(SIGSEGV
, &sigact
, NULL
);
1266 sigaction(SIGBUS
, &sigact
, NULL
);
1267 sigaction(SIGABRT
, &sigact
, NULL
);
1269 /* This allows stack overflow to be reported instead of a SEGV */
1272 static unsigned char stack
[SIGSTKSZ
] __attribute__((aligned(16)));
1275 ss
.ss_size
= SIGSTKSZ
;
1277 sigaltstack(&ss
, NULL
);
1284 /* signal handler for fatal errors */
1285 static long __stdcall
cpu_exception_handler(EXCEPTION_POINTERS
*ex_info
)
1287 rt_context
*rc
= &g_rtctxt
;
1289 rt_getcontext(ex_info
->ContextRecord
, rc
);
1291 switch (code
= ex_info
->ExceptionRecord
->ExceptionCode
) {
1292 case EXCEPTION_ACCESS_VIOLATION
:
1293 rt_error("invalid memory access");
1295 case EXCEPTION_STACK_OVERFLOW
:
1296 rt_error("stack overflow");
1298 case EXCEPTION_INT_DIVIDE_BY_ZERO
:
1299 rt_error("division by zero");
1301 case EXCEPTION_BREAKPOINT
:
1302 case EXCEPTION_SINGLE_STEP
:
1303 rc
->ip
= *(addr_t
*)rc
->sp
;
1304 rt_error("breakpoint/single-step exception:");
1305 return EXCEPTION_CONTINUE_SEARCH
;
1307 rt_error("caught exception %08x", code
);
1312 return EXCEPTION_EXECUTE_HANDLER
;
1315 /* Generate a stack backtrace when a CPU exception occurs. */
1316 static void set_exception_handler(void)
1318 SetUnhandledExceptionFilter(cpu_exception_handler
);
1323 /* ------------------------------------------------------------- */
1324 /* return the PC at frame level 'level'. Return negative if not found */
1325 #if defined(__i386__) || defined(__x86_64__)
1326 static int rt_get_caller_pc(addr_t
*paddr
, rt_context
*rc
, int level
)
1335 /* XXX: check address validity with program info */
1338 fp
= ((addr_t
*)fp
)[0];
1341 ip
= ((addr_t
*)fp
)[1];
1349 #elif defined(__arm__)
1350 static int rt_get_caller_pc(addr_t
*paddr
, rt_context
*rc
, int level
)
1352 /* XXX: only supports linux/bsd */
1353 #if !defined(__linux__) && \
1354 !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__)
1362 fp
= ((addr_t
*)fp
)[0];
1363 *paddr
= ((addr_t
*)fp
)[2];
1369 #elif defined(__aarch64__)
1370 static int rt_get_caller_pc(addr_t
*paddr
, rt_context
*rc
, int level
)
1375 addr_t
*fp
= (addr_t
*)rc
->fp
;
1377 fp
= (addr_t
*)fp
[0];
1383 #elif defined(__riscv)
1384 static int rt_get_caller_pc(addr_t
*paddr
, rt_context
*rc
, int level
)
1389 addr_t
*fp
= (addr_t
*)rc
->fp
;
1390 while (--level
&& fp
>= (addr_t
*)0x1000)
1391 fp
= (addr_t
*)fp
[-2];
1392 if (fp
< (addr_t
*)0x1000)
1400 #warning add arch specific rt_get_caller_pc()
1401 static int rt_get_caller_pc(addr_t
*paddr
, rt_context
*rc
, int level
)
1407 #endif /* CONFIG_TCC_BACKTRACE */
1408 /* ------------------------------------------------------------- */
1409 #ifdef CONFIG_TCC_STATIC
1411 /* dummy function for profiling */
1412 ST_FUNC
void *dlopen(const char *filename
, int flag
)
1417 ST_FUNC
void dlclose(void *p
)
1421 ST_FUNC
const char *dlerror(void)
1426 typedef struct TCCSyms
{
1432 /* add the symbol you want here if no dynamic linking is done */
1433 static TCCSyms tcc_syms
[] = {
1434 #if !defined(CONFIG_TCCBOOT)
1435 #define TCCSYM(a) { #a, &a, },
1445 ST_FUNC
void *dlsym(void *handle
, const char *symbol
)
1449 while (p
->str
!= NULL
) {
1450 if (!strcmp(p
->str
, symbol
))
1457 #endif /* CONFIG_TCC_STATIC */
1458 #endif /* TCC_IS_NATIVE */
1459 /* ------------------------------------------------------------- */