2 * TCC - Tiny C Compiler
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 /********************************************************/
24 /* global variables */
26 /* display benchmark infos */
31 static struct BufferedFile
*file
;
34 static CString tokcstr
; /* current parsed string, if any */
35 /* additional informations about token */
37 #define TOK_FLAG_BOL 0x0001 /* beginning of line before */
38 #define TOK_FLAG_BOF 0x0002 /* beginning of file before */
39 #define TOK_FLAG_ENDIF 0x0004 /* a endif was found matching starting #ifdef */
40 #define TOK_FLAG_EOF 0x0008 /* end of file */
42 static int *macro_ptr
, *macro_ptr_allocated
;
43 static int *unget_saved_macro_ptr
;
44 static int unget_saved_buffer
[TOK_MAX_SIZE
+ 1];
45 static int unget_buffer_enabled
;
46 static int parse_flags
;
47 #define PARSE_FLAG_PREPROCESS 0x0001 /* activate preprocessing */
48 #define PARSE_FLAG_TOK_NUM 0x0002 /* return numbers instead of TOK_PPNUM */
49 #define PARSE_FLAG_LINEFEED 0x0004 /* line feed is returned as a
50 token. line feed is also
52 #define PARSE_FLAG_ASM_COMMENTS 0x0008 /* '#' can be used for line comment */
53 #define PARSE_FLAG_SPACES 0x0010 /* next() returns space tokens (for -E) */
55 static Section
*text_section
, *data_section
, *bss_section
; /* predefined sections */
56 static Section
*cur_text_section
; /* current section where function code is
59 static Section
*last_text_section
; /* to handle .previous asm directive */
61 /* bound check related sections */
62 static Section
*bounds_section
; /* contains global data bound description */
63 static Section
*lbounds_section
; /* contains local data bound description */
65 static Section
*symtab_section
, *strtab_section
;
68 static Section
*stab_section
, *stabstr_section
;
70 /* loc : local variable index
71 ind : output code index
73 anon_sym: anonymous symbol index
75 static int rsym
, anon_sym
, ind
, loc
;
76 /* expression generation modifiers */
77 static int const_wanted
; /* true if constant wanted */
78 static int nocode_wanted
; /* true if no code generation wanted for an expression */
79 static int global_expr
; /* true if compound literals must be allocated
80 globally (used during initializers parsing */
81 static CType func_vt
; /* current function return type (used by return
84 static int last_line_num
, last_ind
, func_ind
; /* debug last line number and pc */
86 static TokenSym
**table_ident
;
87 static TokenSym
*hash_ident
[TOK_HASH_SIZE
];
88 static char token_buf
[STRING_MAX_SIZE
+ 1];
89 static char *funcname
;
90 static Sym
*global_stack
, *local_stack
;
91 static Sym
*define_stack
;
92 static Sym
*global_label_stack
, *local_label_stack
;
93 /* symbol allocator */
94 #define SYM_POOL_NB (8192 / sizeof(Sym))
95 static Sym
*sym_free_first
;
96 static void **sym_pools
;
97 static int nb_sym_pools
;
99 static SValue vstack
[VSTACK_SIZE
], *vtop
;
100 /* some predefined types */
101 static CType char_pointer_type
, func_old_type
, int_type
;
103 /* use GNU C extensions */
104 static int gnu_ext
= 1;
106 /* use Tiny C extensions */
107 static int tcc_ext
= 1;
109 /* max number of callers shown if error */
110 #ifdef CONFIG_TCC_BACKTRACE
112 const char **rt_bound_error_msg
;
113 unsigned long rt_prog_main
;
116 /* XXX: get rid of this ASAP */
117 static struct TCCState
*tcc_state
;
119 /********************************************************/
120 /* function prototypes */
123 static void next(void);
124 char *get_tok_str(int v
, CValue
*cv
);
127 static void parse_expr_type(CType
*type
);
128 static void expr_type(CType
*type
);
129 static void unary_type(CType
*type
);
130 static void block(int *bsym
, int *csym
, int *case_sym
, int *def_sym
,
131 int case_reg
, int is_expr
);
132 static int expr_const(void);
133 static void expr_eq(void);
134 static void gexpr(void);
135 static void gen_inline_functions(void);
136 static void decl(int l
);
137 static void decl_initializer(CType
*type
, Section
*sec
, unsigned long c
,
138 int first
, int size_only
);
139 static void decl_initializer_alloc(CType
*type
, AttributeDef
*ad
, int r
,
140 int has_init
, int v
, int scope
);
142 void gv2(int rc1
, int rc2
);
143 void move_reg(int r
, int s
);
144 void save_regs(int n
);
145 void save_reg(int r
);
150 int get_reg_ex(int rc
,int rc2
);
153 void force_charshort_cast(int t
);
154 static void gen_cast(CType
*type
);
156 static Sym
*sym_find(int v
);
157 static Sym
*sym_push(int v
, CType
*type
, int r
, int c
);
160 static int type_size(CType
*type
, int *a
);
161 static inline CType
*pointed_type(CType
*type
);
162 static int pointed_size(CType
*type
);
163 static int lvalue_type(int t
);
164 static int parse_btype(CType
*type
, AttributeDef
*ad
);
165 static void type_decl(CType
*type
, AttributeDef
*ad
, int *v
, int td
);
166 static int compare_types(CType
*type1
, CType
*type2
, int unqualified
);
167 static int is_compatible_types(CType
*type1
, CType
*type2
);
168 static int is_compatible_parameter_types(CType
*type1
, CType
*type2
);
170 int ieee_finite(double d
);
172 void vpushll(long long v
);
175 void lexpand_nr(void);
176 static void vpush_global_sym(CType
*type
, int v
);
177 void vset(CType
*type
, int r
, int v
);
178 void type_to_str(char *buf
, int buf_size
,
179 CType
*type
, const char *varstr
);
180 static Sym
*get_sym_ref(CType
*type
, Section
*sec
,
181 unsigned long offset
, unsigned long size
);
182 static Sym
*external_global_sym(int v
, CType
*type
, int r
);
184 /* section generation */
185 static void section_realloc(Section
*sec
, unsigned long new_size
);
186 static void *section_ptr_add(Section
*sec
, unsigned long size
);
187 static void put_extern_sym(Sym
*sym
, Section
*section
,
188 unsigned long value
, unsigned long size
);
189 static void greloc(Section
*s
, Sym
*sym
, unsigned long addr
, int type
);
190 static int put_elf_str(Section
*s
, const char *sym
);
191 static int put_elf_sym(Section
*s
,
192 unsigned long value
, unsigned long size
,
193 int info
, int other
, int shndx
, const char *name
);
194 static int add_elf_sym(Section
*s
, uplong value
, unsigned long size
,
195 int info
, int other
, int sh_num
, const char *name
);
196 static void put_elf_reloc(Section
*symtab
, Section
*s
, unsigned long offset
,
197 int type
, int symbol
);
198 static void put_stabs(const char *str
, int type
, int other
, int desc
,
199 unsigned long value
);
200 static void put_stabs_r(const char *str
, int type
, int other
, int desc
,
201 unsigned long value
, Section
*sec
, int sym_index
);
202 static void put_stabn(int type
, int other
, int desc
, int value
);
203 static void put_stabd(int type
, int other
, int desc
);
204 static int tcc_add_dll(TCCState
*s
, const char *filename
, int flags
);
206 #define AFF_PRINT_ERROR 0x0001 /* print error if file not found */
207 #define AFF_REFERENCED_DLL 0x0002 /* load a referenced dll from another dll */
208 #define AFF_PREPROCESS 0x0004 /* preprocess file */
209 static int tcc_add_file_internal(TCCState
*s
, const char *filename
, int flags
);
212 int tcc_output_coff(TCCState
*s1
, FILE *f
);
215 int pe_load_file(struct TCCState
*s1
, const char *filename
, int fd
);
216 int pe_output_file(struct TCCState
*s1
, const char *filename
);
219 #ifdef CONFIG_TCC_ASM
220 static void asm_expr(TCCState
*s1
, ExprValue
*pe
);
221 static int asm_int_expr(TCCState
*s1
);
222 static int find_constraint(ASMOperand
*operands
, int nb_operands
,
223 const char *name
, const char **pp
);
225 static int tcc_assemble(TCCState
*s1
, int do_preprocess
);
228 static void asm_instr(void);
229 static void asm_global_instr(void);
231 /********************************************************/
234 static Sym
*__sym_malloc(void);
235 static inline Sym
*sym_malloc(void);
236 static inline void sym_free(Sym
*sym
);
237 Section
*new_section(TCCState
*s1
, const char *name
, int sh_type
, int sh_flags
);
238 static void free_section(Section
*s
);
239 static void section_realloc(Section
*sec
, unsigned long new_size
);
240 static void *section_ptr_add(Section
*sec
, unsigned long size
);
241 Section
*find_section(TCCState
*s1
, const char *name
);
242 static void put_extern_sym2(
243 Sym
*sym
, Section
*section
,
244 unsigned long value
, unsigned long size
, int can_add_underscore
);
245 static void put_extern_sym(
246 Sym
*sym
, Section
*section
,
247 unsigned long value
, unsigned long size
);
248 static void greloc(Section
*s
, Sym
*sym
, unsigned long offset
, int type
);
250 static void strcat_vprintf(char *buf
, int buf_size
, const char *fmt
, va_list ap
);
251 static void strcat_printf(char *buf
, int buf_size
, const char *fmt
, ...);
253 /* CString handling */
254 static void cstr_realloc(CString
*cstr
, int new_size
);
255 static inline void cstr_ccat(CString
*cstr
, int ch
);
256 static void cstr_cat(CString
*cstr
, const char *str
);
257 static void cstr_wccat(CString
*cstr
, int ch
);
258 static void cstr_new(CString
*cstr
);
259 static void cstr_free(CString
*cstr
);
260 #define cstr_reset(cstr) cstr_free(cstr)
261 static void add_char(CString
*cstr
, int c
);
263 static Sym
*sym_push2(Sym
**ps
, int v
, int t
, long c
);
264 static Sym
*sym_find2(Sym
*s
, int v
);
265 static inline Sym
*struct_find(int v
);
266 static inline Sym
*sym_find(int v
);
267 static Sym
*sym_push(int v
, CType
*type
, int r
, int c
);
268 static Sym
*global_identifier_push(int v
, int t
, int c
);
269 static void sym_pop(Sym
**ptop
, Sym
*b
);
271 BufferedFile
*tcc_open(TCCState
*s1
, const char *filename
);
272 void tcc_close(BufferedFile
*bf
);
273 static int tcc_compile(TCCState
*s1
);
275 void expect(const char *msg
);
277 static void test_lvalue(void);
278 void *resolve_sym(TCCState
*s1
, const char *sym
);
280 static inline int isid(int c
)
282 return (c
>= 'a' && c
<= 'z')
283 || (c
>= 'A' && c
<= 'Z')
287 static inline int isnum(int c
)
289 return c
>= '0' && c
<= '9';
292 static inline int isoct(int c
)
294 return c
>= '0' && c
<= '7';
297 static inline int toup(int c
)
299 if (c
>= 'a' && c
<= 'z')
300 return c
- 'a' + 'A';
305 /********************************************************/
307 #ifdef TCC_TARGET_I386
308 #include "i386-gen.c"
311 #ifdef TCC_TARGET_ARM
315 #ifdef TCC_TARGET_C67
319 #ifdef TCC_TARGET_X86_64
320 #include "x86_64-gen.c"
326 #ifdef CONFIG_TCC_ASM
328 #ifdef TCC_TARGET_I386
329 #include "i386-asm.c"
332 #ifdef TCC_TARGET_X86_64
333 #include "x86_64-asm.c"
338 static void asm_instr(void)
340 error("inline asm() not supported");
342 static void asm_global_instr(void)
344 error("inline asm() not supported");
350 #ifdef TCC_TARGET_COFF
358 /********************************************************/
360 char *normalize_slashes(char *path
)
363 for (p
= path
; *p
; ++p
)
371 /* on win32, we suppose the lib and includes are at the location of 'tcc.exe' */
372 void tcc_set_lib_path_w32(TCCState
*s
)
375 GetModuleFileNameA(tcc_module
, path
, sizeof path
);
376 p
= tcc_basename(normalize_slashes(strlwr(path
)));
377 if (p
- 5 > path
&& 0 == strncmp(p
- 5, "/bin/", 5))
382 tcc_set_lib_path(s
, path
);
386 BOOL WINAPI
DllMain (HANDLE hDll
, DWORD dwReason
, LPVOID lpReserved
)
388 if (DLL_PROCESS_ATTACH
== dwReason
)
395 /********************************************************/
396 #ifdef CONFIG_TCC_STATIC
398 #define RTLD_LAZY 0x001
399 #define RTLD_NOW 0x002
400 #define RTLD_GLOBAL 0x100
401 #define RTLD_DEFAULT NULL
403 /* dummy function for profiling */
404 void *dlopen(const char *filename
, int flag
)
409 void dlclose(void *p
)
413 const char *dlerror(void)
418 typedef struct TCCSyms
{
423 #define TCCSYM(a) { #a, &a, },
425 /* add the symbol you want here if no dynamic linking is done */
426 static TCCSyms tcc_syms
[] = {
427 #if !defined(CONFIG_TCCBOOT)
436 void *resolve_sym(TCCState
*s1
, const char *symbol
)
440 while (p
->str
!= NULL
) {
441 if (!strcmp(p
->str
, symbol
))
448 #elif defined(_WIN32)
449 #define dlclose FreeLibrary
454 void *resolve_sym(TCCState
*s1
, const char *sym
)
456 return dlsym(RTLD_DEFAULT
, sym
);
461 /********************************************************/
463 /* we use our own 'finite' function to avoid potential problems with
464 non standard math libs */
465 /* XXX: endianness dependent */
466 int ieee_finite(double d
)
469 return ((unsigned)((p
[1] | 0x800fffff) + 1)) >> 31;
472 /* copy a string and truncate it. */
473 char *pstrcpy(char *buf
, int buf_size
, const char *s
)
480 q_end
= buf
+ buf_size
- 1;
492 /* strcat and truncate. */
493 char *pstrcat(char *buf
, int buf_size
, const char *s
)
498 pstrcpy(buf
+ len
, buf_size
- len
, s
);
502 /* extract the basename of a file */
503 char *tcc_basename(const char *name
)
505 char *p
= strchr(name
, 0);
506 while (p
> name
&& !IS_PATHSEP(p
[-1]))
511 char *tcc_fileextension (const char *name
)
513 char *b
= tcc_basename(name
);
514 char *e
= strrchr(b
, '.');
515 return e
? e
: strchr(b
, 0);
518 void set_pages_executable(void *ptr
, unsigned long length
)
521 unsigned long old_protect
;
522 VirtualProtect(ptr
, length
, PAGE_EXECUTE_READWRITE
, &old_protect
);
524 unsigned long start
, end
;
525 start
= (unsigned long)ptr
& ~(PAGESIZE
- 1);
526 end
= (unsigned long)ptr
+ length
;
527 end
= (end
+ PAGESIZE
- 1) & ~(PAGESIZE
- 1);
528 mprotect((void *)start
, end
- start
, PROT_READ
| PROT_WRITE
| PROT_EXEC
);
532 /* memory management */
536 unsigned malloc_usable_size(void*);
539 void tcc_free(void *ptr
)
542 mem_cur_size
-= malloc_usable_size(ptr
);
547 void *tcc_malloc(unsigned long size
)
552 error("memory full");
554 mem_cur_size
+= malloc_usable_size(ptr
);
555 if (mem_cur_size
> mem_max_size
)
556 mem_max_size
= mem_cur_size
;
561 void *tcc_mallocz(unsigned long size
)
564 ptr
= tcc_malloc(size
);
565 memset(ptr
, 0, size
);
569 void *tcc_realloc(void *ptr
, unsigned long size
)
573 mem_cur_size
-= malloc_usable_size(ptr
);
575 ptr1
= realloc(ptr
, size
);
577 /* NOTE: count not correct if alloc error, but not critical */
578 mem_cur_size
+= malloc_usable_size(ptr1
);
579 if (mem_cur_size
> mem_max_size
)
580 mem_max_size
= mem_cur_size
;
585 char *tcc_strdup(const char *str
)
588 ptr
= tcc_malloc(strlen(str
) + 1);
593 #define free(p) use_tcc_free(p)
594 #define malloc(s) use_tcc_malloc(s)
595 #define realloc(p, s) use_tcc_realloc(p, s)
597 void dynarray_add(void ***ptab
, int *nb_ptr
, void *data
)
604 /* every power of two we double array size */
605 if ((nb
& (nb
- 1)) == 0) {
610 pp
= tcc_realloc(pp
, nb_alloc
* sizeof(void *));
612 error("memory full");
619 void dynarray_reset(void *pp
, int *n
)
622 for (p
= *(void***)pp
; *n
; ++p
, --*n
)
625 tcc_free(*(void**)pp
);
629 /* symbol allocator */
630 static Sym
*__sym_malloc(void)
632 Sym
*sym_pool
, *sym
, *last_sym
;
635 sym_pool
= tcc_malloc(SYM_POOL_NB
* sizeof(Sym
));
636 dynarray_add(&sym_pools
, &nb_sym_pools
, sym_pool
);
638 last_sym
= sym_free_first
;
640 for(i
= 0; i
< SYM_POOL_NB
; i
++) {
641 sym
->next
= last_sym
;
645 sym_free_first
= last_sym
;
649 static inline Sym
*sym_malloc(void)
652 sym
= sym_free_first
;
654 sym
= __sym_malloc();
655 sym_free_first
= sym
->next
;
659 static inline void sym_free(Sym
*sym
)
661 sym
->next
= sym_free_first
;
662 sym_free_first
= sym
;
665 Section
*new_section(TCCState
*s1
, const char *name
, int sh_type
, int sh_flags
)
669 sec
= tcc_mallocz(sizeof(Section
) + strlen(name
));
670 strcpy(sec
->name
, name
);
671 sec
->sh_type
= sh_type
;
672 sec
->sh_flags
= sh_flags
;
680 sec
->sh_addralign
= 4;
683 sec
->sh_addralign
= 1;
686 sec
->sh_addralign
= 32; /* default conservative alignment */
690 if (sh_flags
& SHF_PRIVATE
) {
691 dynarray_add((void ***)&s1
->priv_sections
, &s1
->nb_priv_sections
, sec
);
693 sec
->sh_num
= s1
->nb_sections
;
694 dynarray_add((void ***)&s1
->sections
, &s1
->nb_sections
, sec
);
700 static void free_section(Section
*s
)
705 /* realloc section and set its content to zero */
706 static void section_realloc(Section
*sec
, unsigned long new_size
)
711 size
= sec
->data_allocated
;
714 while (size
< new_size
)
716 data
= tcc_realloc(sec
->data
, size
);
718 error("memory full");
719 memset(data
+ sec
->data_allocated
, 0, size
- sec
->data_allocated
);
721 sec
->data_allocated
= size
;
724 /* reserve at least 'size' bytes in section 'sec' from
726 static void *section_ptr_add(Section
*sec
, unsigned long size
)
728 unsigned long offset
, offset1
;
730 offset
= sec
->data_offset
;
731 offset1
= offset
+ size
;
732 if (offset1
> sec
->data_allocated
)
733 section_realloc(sec
, offset1
);
734 sec
->data_offset
= offset1
;
735 return sec
->data
+ offset
;
738 /* return a reference to a section, and create it if it does not
740 Section
*find_section(TCCState
*s1
, const char *name
)
744 for(i
= 1; i
< s1
->nb_sections
; i
++) {
745 sec
= s1
->sections
[i
];
746 if (!strcmp(name
, sec
->name
))
749 /* sections are created as PROGBITS */
750 return new_section(s1
, name
, SHT_PROGBITS
, SHF_ALLOC
);
753 /* update sym->c so that it points to an external symbol in section
754 'section' with value 'value' */
755 static void put_extern_sym2(Sym
*sym
, Section
*section
,
756 unsigned long value
, unsigned long size
,
757 int can_add_underscore
)
759 int sym_type
, sym_bind
, sh_num
, info
, other
, attr
;
766 else if (section
== SECTION_ABS
)
769 sh_num
= section
->sh_num
;
773 if ((sym
->type
.t
& VT_BTYPE
) == VT_FUNC
) {
777 attr
= sym
->type
.ref
->r
;
778 if (FUNC_EXPORT(attr
))
780 if (FUNC_CALL(attr
) == FUNC_STDCALL
)
784 sym_type
= STT_OBJECT
;
787 if (sym
->type
.t
& VT_STATIC
)
788 sym_bind
= STB_LOCAL
;
790 sym_bind
= STB_GLOBAL
;
793 name
= get_tok_str(sym
->v
, NULL
);
794 #ifdef CONFIG_TCC_BCHECK
795 if (tcc_state
->do_bounds_check
) {
798 /* XXX: avoid doing that for statics ? */
799 /* if bound checking is activated, we change some function
800 names by adding the "__bound" prefix */
803 /* XXX: we rely only on malloc hooks */
816 strcpy(buf
, "__bound_");
825 if ((other
& 2) && can_add_underscore
) {
826 sprintf(buf1
, "_%s@%d", name
, FUNC_ARGS(attr
));
830 if (tcc_state
->leading_underscore
&& can_add_underscore
) {
832 pstrcpy(buf1
+ 1, sizeof(buf1
) - 1, name
);
835 info
= ELFW(ST_INFO
)(sym_bind
, sym_type
);
836 sym
->c
= add_elf_sym(symtab_section
, value
, size
, info
, other
, sh_num
, name
);
838 esym
= &((ElfW(Sym
) *)symtab_section
->data
)[sym
->c
];
839 esym
->st_value
= value
;
840 esym
->st_size
= size
;
841 esym
->st_shndx
= sh_num
;
842 esym
->st_other
|= other
;
846 static void put_extern_sym(Sym
*sym
, Section
*section
,
847 unsigned long value
, unsigned long size
)
849 put_extern_sym2(sym
, section
, value
, size
, 1);
852 /* add a new relocation entry to symbol 'sym' in section 's' */
853 static void greloc(Section
*s
, Sym
*sym
, unsigned long offset
, int type
)
856 put_extern_sym(sym
, NULL
, 0, 0);
857 /* now we can add ELF relocation info */
858 put_elf_reloc(symtab_section
, s
, offset
, type
, sym
->c
);
861 static void strcat_vprintf(char *buf
, int buf_size
, const char *fmt
, va_list ap
)
865 vsnprintf(buf
+ len
, buf_size
- len
, fmt
, ap
);
868 static void strcat_printf(char *buf
, int buf_size
, const char *fmt
, ...)
872 strcat_vprintf(buf
, buf_size
, fmt
, ap
);
876 void error1(TCCState
*s1
, int is_warning
, const char *fmt
, va_list ap
)
883 for(f
= s1
->include_stack
; f
< s1
->include_stack_ptr
; f
++)
884 strcat_printf(buf
, sizeof(buf
), "In file included from %s:%d:\n",
885 (*f
)->filename
, (*f
)->line_num
);
886 if (file
->line_num
> 0) {
887 strcat_printf(buf
, sizeof(buf
),
888 "%s:%d: ", file
->filename
, file
->line_num
);
890 strcat_printf(buf
, sizeof(buf
),
891 "%s: ", file
->filename
);
894 strcat_printf(buf
, sizeof(buf
),
898 strcat_printf(buf
, sizeof(buf
), "warning: ");
900 strcat_printf(buf
, sizeof(buf
), "error: ");
901 strcat_vprintf(buf
, sizeof(buf
), fmt
, ap
);
903 if (!s1
->error_func
) {
904 /* default case: stderr */
905 fprintf(stderr
, "%s\n", buf
);
907 s1
->error_func(s1
->error_opaque
, buf
);
909 if (!is_warning
|| s1
->warn_error
)
913 void tcc_set_error_func(TCCState
*s
, void *error_opaque
,
914 void (*error_func
)(void *opaque
, const char *msg
))
916 s
->error_opaque
= error_opaque
;
917 s
->error_func
= error_func
;
920 /* error without aborting current compilation */
921 void error_noabort(const char *fmt
, ...)
923 TCCState
*s1
= tcc_state
;
927 error1(s1
, 0, fmt
, ap
);
931 void error(const char *fmt
, ...)
933 TCCState
*s1
= tcc_state
;
937 error1(s1
, 0, fmt
, ap
);
939 /* better than nothing: in some cases, we accept to handle errors */
940 if (s1
->error_set_jmp_enabled
) {
941 longjmp(s1
->error_jmp_buf
, 1);
943 /* XXX: eliminate this someday */
948 void expect(const char *msg
)
950 error("%s expected", msg
);
953 void warning(const char *fmt
, ...)
955 TCCState
*s1
= tcc_state
;
962 error1(s1
, 1, fmt
, ap
);
969 error("'%c' expected", c
);
973 static void test_lvalue(void)
975 if (!(vtop
->r
& VT_LVAL
))
979 /* CString handling */
981 static void cstr_realloc(CString
*cstr
, int new_size
)
986 size
= cstr
->size_allocated
;
988 size
= 8; /* no need to allocate a too small first string */
989 while (size
< new_size
)
991 data
= tcc_realloc(cstr
->data_allocated
, size
);
993 error("memory full");
994 cstr
->data_allocated
= data
;
995 cstr
->size_allocated
= size
;
1000 static inline void cstr_ccat(CString
*cstr
, int ch
)
1003 size
= cstr
->size
+ 1;
1004 if (size
> cstr
->size_allocated
)
1005 cstr_realloc(cstr
, size
);
1006 ((unsigned char *)cstr
->data
)[size
- 1] = ch
;
1010 static void cstr_cat(CString
*cstr
, const char *str
)
1022 /* add a wide char */
1023 static void cstr_wccat(CString
*cstr
, int ch
)
1026 size
= cstr
->size
+ sizeof(nwchar_t
);
1027 if (size
> cstr
->size_allocated
)
1028 cstr_realloc(cstr
, size
);
1029 *(nwchar_t
*)(((unsigned char *)cstr
->data
) + size
- sizeof(nwchar_t
)) = ch
;
1033 static void cstr_new(CString
*cstr
)
1035 memset(cstr
, 0, sizeof(CString
));
1038 /* free string and reset it to NULL */
1039 static void cstr_free(CString
*cstr
)
1041 tcc_free(cstr
->data_allocated
);
1045 #define cstr_reset(cstr) cstr_free(cstr)
1047 /* XXX: unicode ? */
1048 static void add_char(CString
*cstr
, int c
)
1050 if (c
== '\'' || c
== '\"' || c
== '\\') {
1051 /* XXX: could be more precise if char or string */
1052 cstr_ccat(cstr
, '\\');
1054 if (c
>= 32 && c
<= 126) {
1057 cstr_ccat(cstr
, '\\');
1059 cstr_ccat(cstr
, 'n');
1061 cstr_ccat(cstr
, '0' + ((c
>> 6) & 7));
1062 cstr_ccat(cstr
, '0' + ((c
>> 3) & 7));
1063 cstr_ccat(cstr
, '0' + (c
& 7));
1068 /* push, without hashing */
1069 static Sym
*sym_push2(Sym
**ps
, int v
, int t
, long c
)
1086 /* find a symbol and return its associated structure. 's' is the top
1087 of the symbol stack */
1088 static Sym
*sym_find2(Sym
*s
, int v
)
1098 /* structure lookup */
1099 static inline Sym
*struct_find(int v
)
1102 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1104 return table_ident
[v
]->sym_struct
;
1107 /* find an identifier */
1108 static inline Sym
*sym_find(int v
)
1111 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1113 return table_ident
[v
]->sym_identifier
;
1116 /* push a given symbol on the symbol stack */
1117 static Sym
*sym_push(int v
, CType
*type
, int r
, int c
)
1126 s
= sym_push2(ps
, v
, type
->t
, c
);
1127 s
->type
.ref
= type
->ref
;
1129 /* don't record fields or anonymous symbols */
1131 if (!(v
& SYM_FIELD
) && (v
& ~SYM_STRUCT
) < SYM_FIRST_ANOM
) {
1132 /* record symbol in token array */
1133 ts
= table_ident
[(v
& ~SYM_STRUCT
) - TOK_IDENT
];
1135 ps
= &ts
->sym_struct
;
1137 ps
= &ts
->sym_identifier
;
1144 /* push a global identifier */
1145 static Sym
*global_identifier_push(int v
, int t
, int c
)
1148 s
= sym_push2(&global_stack
, v
, t
, c
);
1149 /* don't record anonymous symbol */
1150 if (v
< SYM_FIRST_ANOM
) {
1151 ps
= &table_ident
[v
- TOK_IDENT
]->sym_identifier
;
1152 /* modify the top most local identifier, so that
1153 sym_identifier will point to 's' when popped */
1155 ps
= &(*ps
)->prev_tok
;
1162 /* pop symbols until top reaches 'b' */
1163 static void sym_pop(Sym
**ptop
, Sym
*b
)
1173 /* remove symbol in token array */
1175 if (!(v
& SYM_FIELD
) && (v
& ~SYM_STRUCT
) < SYM_FIRST_ANOM
) {
1176 ts
= table_ident
[(v
& ~SYM_STRUCT
) - TOK_IDENT
];
1178 ps
= &ts
->sym_struct
;
1180 ps
= &ts
->sym_identifier
;
1191 BufferedFile
*tcc_open(TCCState
*s1
, const char *filename
)
1196 if (strcmp(filename
, "-") == 0)
1197 fd
= 0, filename
= "stdin";
1199 fd
= open(filename
, O_RDONLY
| O_BINARY
);
1200 if ((s1
->verbose
== 2 && fd
>= 0) || s1
->verbose
== 3)
1201 printf("%s %*s%s\n", fd
< 0 ? "nf":"->",
1202 (int)(s1
->include_stack_ptr
- s1
->include_stack
), "", filename
);
1205 bf
= tcc_malloc(sizeof(BufferedFile
));
1207 bf
->buf_ptr
= bf
->buffer
;
1208 bf
->buf_end
= bf
->buffer
;
1209 bf
->buffer
[0] = CH_EOB
; /* put eob symbol */
1210 pstrcpy(bf
->filename
, sizeof(bf
->filename
), filename
);
1212 normalize_slashes(bf
->filename
);
1215 bf
->ifndef_macro
= 0;
1216 bf
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
1217 // printf("opening '%s'\n", filename);
1221 void tcc_close(BufferedFile
*bf
)
1223 total_lines
+= bf
->line_num
;
1228 /* compile the C file opened in 'file'. Return non zero if errors. */
1229 static int tcc_compile(TCCState
*s1
)
1233 volatile int section_sym
;
1236 printf("%s: **** new file\n", file
->filename
);
1238 preprocess_init(s1
);
1240 cur_text_section
= NULL
;
1242 anon_sym
= SYM_FIRST_ANOM
;
1244 /* file info: full path + filename */
1245 section_sym
= 0; /* avoid warning */
1247 section_sym
= put_elf_sym(symtab_section
, 0, 0,
1248 ELFW(ST_INFO
)(STB_LOCAL
, STT_SECTION
), 0,
1249 text_section
->sh_num
, NULL
);
1250 getcwd(buf
, sizeof(buf
));
1252 normalize_slashes(buf
);
1254 pstrcat(buf
, sizeof(buf
), "/");
1255 put_stabs_r(buf
, N_SO
, 0, 0,
1256 text_section
->data_offset
, text_section
, section_sym
);
1257 put_stabs_r(file
->filename
, N_SO
, 0, 0,
1258 text_section
->data_offset
, text_section
, section_sym
);
1260 /* an elf symbol of type STT_FILE must be put so that STB_LOCAL
1261 symbols can be safely used */
1262 put_elf_sym(symtab_section
, 0, 0,
1263 ELFW(ST_INFO
)(STB_LOCAL
, STT_FILE
), 0,
1264 SHN_ABS
, file
->filename
);
1266 /* define some often used types */
1267 int_type
.t
= VT_INT
;
1269 char_pointer_type
.t
= VT_BYTE
;
1270 mk_pointer(&char_pointer_type
);
1272 func_old_type
.t
= VT_FUNC
;
1273 func_old_type
.ref
= sym_push(SYM_FIELD
, &int_type
, FUNC_CDECL
, FUNC_OLD
);
1275 #if defined(TCC_ARM_EABI) && defined(TCC_ARM_VFP)
1276 float_type
.t
= VT_FLOAT
;
1277 double_type
.t
= VT_DOUBLE
;
1279 func_float_type
.t
= VT_FUNC
;
1280 func_float_type
.ref
= sym_push(SYM_FIELD
, &float_type
, FUNC_CDECL
, FUNC_OLD
);
1281 func_double_type
.t
= VT_FUNC
;
1282 func_double_type
.ref
= sym_push(SYM_FIELD
, &double_type
, FUNC_CDECL
, FUNC_OLD
);
1286 /* define 'void *alloca(unsigned int)' builtin function */
1291 sym
= sym_push(p
, mk_pointer(VT_VOID
), FUNC_CDECL
, FUNC_NEW
);
1292 s1
= sym_push(SYM_FIELD
, VT_UNSIGNED
| VT_INT
, 0, 0);
1295 sym_push(TOK_alloca
, VT_FUNC
| (p
<< VT_STRUCT_SHIFT
), VT_CONST
, 0);
1299 define_start
= define_stack
;
1302 if (setjmp(s1
->error_jmp_buf
) == 0) {
1304 s1
->error_set_jmp_enabled
= 1;
1306 ch
= file
->buf_ptr
[0];
1307 tok_flags
= TOK_FLAG_BOL
| TOK_FLAG_BOF
;
1308 parse_flags
= PARSE_FLAG_PREPROCESS
| PARSE_FLAG_TOK_NUM
;
1312 expect("declaration");
1314 /* end of translation unit info */
1316 put_stabs_r(NULL
, N_SO
, 0, 0,
1317 text_section
->data_offset
, text_section
, section_sym
);
1320 s1
->error_set_jmp_enabled
= 0;
1322 /* reset define stack, but leave -Dsymbols (may be incorrect if
1323 they are undefined) */
1324 free_defines(define_start
);
1326 gen_inline_functions();
1328 sym_pop(&global_stack
, NULL
);
1329 sym_pop(&local_stack
, NULL
);
1331 return s1
->nb_errors
!= 0 ? -1 : 0;
1334 int tcc_compile_string(TCCState
*s
, const char *str
)
1336 BufferedFile bf1
, *bf
= &bf1
;
1340 /* init file structure */
1342 /* XXX: avoid copying */
1344 buf
= tcc_malloc(len
+ 1);
1347 memcpy(buf
, str
, len
);
1350 bf
->buf_end
= buf
+ len
;
1351 pstrcpy(bf
->filename
, sizeof(bf
->filename
), "<string>");
1354 ret
= tcc_compile(s
);
1358 /* currently, no need to close */
1362 /* define a preprocessor symbol. A value can also be provided with the '=' operator */
1363 void tcc_define_symbol(TCCState
*s1
, const char *sym
, const char *value
)
1365 BufferedFile bf1
, *bf
= &bf1
;
1367 pstrcpy(bf
->buffer
, IO_BUF_SIZE
, sym
);
1368 pstrcat(bf
->buffer
, IO_BUF_SIZE
, " ");
1372 pstrcat(bf
->buffer
, IO_BUF_SIZE
, value
);
1374 /* init file structure */
1376 bf
->buf_ptr
= bf
->buffer
;
1377 bf
->buf_end
= bf
->buffer
+ strlen(bf
->buffer
);
1378 *bf
->buf_end
= CH_EOB
;
1379 bf
->filename
[0] = '\0';
1383 s1
->include_stack_ptr
= s1
->include_stack
;
1385 /* parse with define parser */
1386 ch
= file
->buf_ptr
[0];
1392 /* undefine a preprocessor symbol */
1393 void tcc_undefine_symbol(TCCState
*s1
, const char *sym
)
1397 ts
= tok_alloc(sym
, strlen(sym
));
1398 s
= define_find(ts
->tok
);
1399 /* undefine symbol by putting an invalid name */
1405 #ifdef CONFIG_TCC_BACKTRACE
1406 /* print the position in the source file of PC value 'pc' by reading
1407 the stabs debug information */
1408 static unsigned long rt_printline(unsigned long wanted_pc
)
1410 Stab_Sym
*sym
, *sym_end
;
1411 char func_name
[128], last_func_name
[128];
1412 unsigned long func_addr
, last_pc
, pc
;
1413 const char *incl_files
[INCLUDE_STACK_SIZE
];
1414 int incl_index
, len
, last_line_num
, i
;
1415 const char *str
, *p
;
1417 fprintf(stderr
, "0x%08lx:", wanted_pc
);
1419 func_name
[0] = '\0';
1422 last_func_name
[0] = '\0';
1423 last_pc
= 0xffffffff;
1425 sym
= (Stab_Sym
*)stab_section
->data
+ 1;
1426 sym_end
= (Stab_Sym
*)(stab_section
->data
+ stab_section
->data_offset
);
1427 while (sym
< sym_end
) {
1428 switch(sym
->n_type
) {
1429 /* function start or end */
1431 if (sym
->n_strx
== 0) {
1432 /* we test if between last line and end of function */
1433 pc
= sym
->n_value
+ func_addr
;
1434 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
1436 func_name
[0] = '\0';
1439 str
= stabstr_section
->data
+ sym
->n_strx
;
1440 p
= strchr(str
, ':');
1442 pstrcpy(func_name
, sizeof(func_name
), str
);
1445 if (len
> sizeof(func_name
) - 1)
1446 len
= sizeof(func_name
) - 1;
1447 memcpy(func_name
, str
, len
);
1448 func_name
[len
] = '\0';
1450 func_addr
= sym
->n_value
;
1453 /* line number info */
1455 pc
= sym
->n_value
+ func_addr
;
1456 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
1459 last_line_num
= sym
->n_desc
;
1461 strcpy(last_func_name
, func_name
);
1465 str
= stabstr_section
->data
+ sym
->n_strx
;
1467 if (incl_index
< INCLUDE_STACK_SIZE
) {
1468 incl_files
[incl_index
++] = str
;
1476 if (sym
->n_strx
== 0) {
1477 incl_index
= 0; /* end of translation unit */
1479 str
= stabstr_section
->data
+ sym
->n_strx
;
1480 /* do not add path */
1482 if (len
> 0 && str
[len
- 1] != '/')
1490 /* second pass: we try symtab symbols (no line number info) */
1493 ElfW(Sym
) *sym
, *sym_end
;
1496 sym_end
= (ElfW(Sym
) *)(symtab_section
->data
+ symtab_section
->data_offset
);
1497 for(sym
= (ElfW(Sym
) *)symtab_section
->data
+ 1;
1500 type
= ELFW(ST_TYPE
)(sym
->st_info
);
1501 if (type
== STT_FUNC
) {
1502 if (wanted_pc
>= sym
->st_value
&&
1503 wanted_pc
< sym
->st_value
+ sym
->st_size
) {
1504 pstrcpy(last_func_name
, sizeof(last_func_name
),
1505 strtab_section
->data
+ sym
->st_name
);
1506 func_addr
= sym
->st_value
;
1512 /* did not find any info: */
1513 fprintf(stderr
, " ???\n");
1516 if (last_func_name
[0] != '\0') {
1517 fprintf(stderr
, " %s()", last_func_name
);
1519 if (incl_index
> 0) {
1520 fprintf(stderr
, " (%s:%d",
1521 incl_files
[incl_index
- 1], last_line_num
);
1522 for(i
= incl_index
- 2; i
>= 0; i
--)
1523 fprintf(stderr
, ", included from %s", incl_files
[i
]);
1524 fprintf(stderr
, ")");
1526 fprintf(stderr
, "\n");
1531 /* fix for glibc 2.1 */
1537 /* return the PC at frame level 'level'. Return non zero if not found */
1538 static int rt_get_caller_pc(unsigned long *paddr
,
1539 ucontext_t
*uc
, int level
)
1545 #if defined(__FreeBSD__)
1546 *paddr
= uc
->uc_mcontext
.mc_eip
;
1547 #elif defined(__dietlibc__)
1548 *paddr
= uc
->uc_mcontext
.eip
;
1550 *paddr
= uc
->uc_mcontext
.gregs
[REG_EIP
];
1554 #if defined(__FreeBSD__)
1555 fp
= uc
->uc_mcontext
.mc_ebp
;
1556 #elif defined(__dietlibc__)
1557 fp
= uc
->uc_mcontext
.ebp
;
1559 fp
= uc
->uc_mcontext
.gregs
[REG_EBP
];
1561 for(i
=1;i
<level
;i
++) {
1562 /* XXX: check address validity with program info */
1563 if (fp
<= 0x1000 || fp
>= 0xc0000000)
1565 fp
= ((unsigned long *)fp
)[0];
1567 *paddr
= ((unsigned long *)fp
)[1];
1571 #elif defined(__x86_64__)
1572 /* return the PC at frame level 'level'. Return non zero if not found */
1573 static int rt_get_caller_pc(unsigned long *paddr
,
1574 ucontext_t
*uc
, int level
)
1580 /* XXX: only support linux */
1581 #if defined(__FreeBSD__)
1582 *paddr
= uc
->uc_mcontext
.mc_rip
;
1584 *paddr
= uc
->uc_mcontext
.gregs
[REG_RIP
];
1588 #if defined(__FreeBSD__)
1589 fp
= uc
->uc_mcontext
.mc_rbp
;
1591 fp
= uc
->uc_mcontext
.gregs
[REG_RBP
];
1593 for(i
=1;i
<level
;i
++) {
1594 /* XXX: check address validity with program info */
1597 fp
= ((unsigned long *)fp
)[0];
1599 *paddr
= ((unsigned long *)fp
)[1];
1604 #warning add arch specific rt_get_caller_pc()
1605 static int rt_get_caller_pc(unsigned long *paddr
,
1606 ucontext_t
*uc
, int level
)
1612 /* emit a run time error at position 'pc' */
1613 void rt_error(ucontext_t
*uc
, const char *fmt
, ...)
1620 fprintf(stderr
, "Runtime error: ");
1621 vfprintf(stderr
, fmt
, ap
);
1622 fprintf(stderr
, "\n");
1623 for(i
=0;i
<num_callers
;i
++) {
1624 if (rt_get_caller_pc(&pc
, uc
, i
) < 0)
1627 fprintf(stderr
, "at ");
1629 fprintf(stderr
, "by ");
1630 pc
= rt_printline(pc
);
1631 if (pc
== rt_prog_main
&& pc
)
1638 /* signal handler for fatal errors */
1639 static void sig_error(int signum
, siginfo_t
*siginf
, void *puc
)
1641 ucontext_t
*uc
= puc
;
1645 switch(siginf
->si_code
) {
1648 rt_error(uc
, "division by zero");
1651 rt_error(uc
, "floating point exception");
1657 if (rt_bound_error_msg
&& *rt_bound_error_msg
)
1658 rt_error(uc
, *rt_bound_error_msg
);
1660 rt_error(uc
, "dereferencing invalid pointer");
1663 rt_error(uc
, "illegal instruction");
1666 rt_error(uc
, "abort() called");
1669 rt_error(uc
, "caught signal %d", signum
);
1677 /* copy code into memory passed in by the caller and do all relocations
1678 (needed before using tcc_get_symbol()).
1679 returns -1 on error and required size if ptr is NULL */
1680 int tcc_relocate(TCCState
*s1
, void *ptr
)
1683 unsigned long offset
, length
;
1687 if (0 == s1
->runtime_added
) {
1688 s1
->runtime_added
= 1;
1690 #ifdef TCC_TARGET_PE
1691 pe_output_file(s1
, NULL
);
1693 tcc_add_runtime(s1
);
1694 relocate_common_syms();
1695 tcc_add_linker_symbols(s1
);
1696 build_got_entries(s1
);
1702 offset
= 0, mem
= (uplong
)ptr
;
1703 for(i
= 1; i
< s1
->nb_sections
; i
++) {
1704 s
= s1
->sections
[i
];
1705 if (0 == (s
->sh_flags
& SHF_ALLOC
))
1707 length
= s
->data_offset
;
1708 s
->sh_addr
= mem
? (mem
+ offset
+ 15) & ~15 : 0;
1709 offset
= (offset
+ length
+ 15) & ~15;
1712 /* relocate symbols */
1713 relocate_syms(s1
, 1);
1717 #ifndef TCC_TARGET_PE
1718 #ifdef TCC_TARGET_X86_64
1719 s1
->runtime_plt_and_got_offset
= 0;
1720 s1
->runtime_plt_and_got
= (char *)(mem
+ offset
);
1721 /* double the size of the buffer for got and plt entries
1722 XXX: calculate exact size for them? */
1730 /* relocate each section */
1731 for(i
= 1; i
< s1
->nb_sections
; i
++) {
1732 s
= s1
->sections
[i
];
1734 relocate_section(s1
, s
);
1737 for(i
= 1; i
< s1
->nb_sections
; i
++) {
1738 s
= s1
->sections
[i
];
1739 if (0 == (s
->sh_flags
& SHF_ALLOC
))
1741 length
= s
->data_offset
;
1742 // printf("%-12s %08x %04x\n", s->name, s->sh_addr, length);
1743 ptr
= (void*)(uplong
)s
->sh_addr
;
1744 if (NULL
== s
->data
|| s
->sh_type
== SHT_NOBITS
)
1745 memset(ptr
, 0, length
);
1747 memcpy(ptr
, s
->data
, length
);
1748 /* mark executable sections as executable in memory */
1749 if (s
->sh_flags
& SHF_EXECINSTR
)
1750 set_pages_executable(ptr
, length
);
1752 #ifndef TCC_TARGET_PE
1753 #ifdef TCC_TARGET_X86_64
1754 set_pages_executable(s1
->runtime_plt_and_got
,
1755 s1
->runtime_plt_and_got_offset
);
1761 /* launch the compiled program with the given arguments */
1762 int tcc_run(TCCState
*s1
, int argc
, char **argv
)
1764 int (*prog_main
)(int, char **);
1768 ret
= tcc_relocate(s1
, NULL
);
1771 ptr
= tcc_malloc(ret
);
1772 tcc_relocate(s1
, ptr
);
1774 prog_main
= tcc_get_symbol_err(s1
, "main");
1777 #ifdef CONFIG_TCC_BACKTRACE
1778 struct sigaction sigact
;
1779 /* install TCC signal handlers to print debug info on fatal
1781 sigact
.sa_flags
= SA_SIGINFO
| SA_RESETHAND
;
1782 sigact
.sa_sigaction
= sig_error
;
1783 sigemptyset(&sigact
.sa_mask
);
1784 sigaction(SIGFPE
, &sigact
, NULL
);
1785 sigaction(SIGILL
, &sigact
, NULL
);
1786 sigaction(SIGSEGV
, &sigact
, NULL
);
1787 sigaction(SIGBUS
, &sigact
, NULL
);
1788 sigaction(SIGABRT
, &sigact
, NULL
);
1790 error("debug mode not available");
1794 #ifdef CONFIG_TCC_BCHECK
1795 if (s1
->do_bounds_check
) {
1796 void (*bound_init
)(void);
1797 void (*bound_exit
)(void);
1798 /* set error function */
1799 rt_bound_error_msg
= tcc_get_symbol_err(s1
, "__bound_error_msg");
1800 rt_prog_main
= (unsigned long)prog_main
;
1801 /* XXX: use .init section so that it also work in binary ? */
1802 bound_init
= tcc_get_symbol_err(s1
, "__bound_init");
1803 bound_exit
= tcc_get_symbol_err(s1
, "__bound_exit");
1805 ret
= (*prog_main
)(argc
, argv
);
1809 ret
= (*prog_main
)(argc
, argv
);
1814 void tcc_memstats(void)
1817 printf("memory in use: %d\n", mem_cur_size
);
1821 static void tcc_cleanup(void)
1825 if (NULL
== tcc_state
)
1829 /* free -D defines */
1833 n
= tok_ident
- TOK_IDENT
;
1834 for(i
= 0; i
< n
; i
++)
1835 tcc_free(table_ident
[i
]);
1836 tcc_free(table_ident
);
1838 /* free sym_pools */
1839 dynarray_reset(&sym_pools
, &nb_sym_pools
);
1841 cstr_free(&tokcstr
);
1842 /* reset symbol stack */
1843 sym_free_first
= NULL
;
1844 /* cleanup from error/setjmp */
1848 TCCState
*tcc_new(void)
1856 s
= tcc_mallocz(sizeof(TCCState
));
1861 tcc_set_lib_path_w32(s
);
1863 tcc_set_lib_path(s
, CONFIG_TCCDIR
);
1865 s
->output_type
= TCC_OUTPUT_MEMORY
;
1868 /* we add dummy defines for some special macros to speed up tests
1869 and to have working defined() */
1870 define_push(TOK___LINE__
, MACRO_OBJ
, NULL
, NULL
);
1871 define_push(TOK___FILE__
, MACRO_OBJ
, NULL
, NULL
);
1872 define_push(TOK___DATE__
, MACRO_OBJ
, NULL
, NULL
);
1873 define_push(TOK___TIME__
, MACRO_OBJ
, NULL
, NULL
);
1875 /* standard defines */
1876 tcc_define_symbol(s
, "__STDC__", NULL
);
1877 tcc_define_symbol(s
, "__STDC_VERSION__", "199901L");
1878 #if defined(TCC_TARGET_I386)
1879 tcc_define_symbol(s
, "__i386__", "1");
1880 tcc_define_symbol(s
, "__i386", "1");
1881 tcc_define_symbol(s
, "i386", "1");
1883 #if defined(TCC_TARGET_X86_64)
1884 tcc_define_symbol(s
, "__x86_64__", NULL
);
1886 #if defined(TCC_TARGET_ARM)
1887 tcc_define_symbol(s
, "__ARM_ARCH_4__", NULL
);
1888 tcc_define_symbol(s
, "__arm_elf__", NULL
);
1889 tcc_define_symbol(s
, "__arm_elf", NULL
);
1890 tcc_define_symbol(s
, "arm_elf", NULL
);
1891 tcc_define_symbol(s
, "__arm__", NULL
);
1892 tcc_define_symbol(s
, "__arm", NULL
);
1893 tcc_define_symbol(s
, "arm", NULL
);
1894 tcc_define_symbol(s
, "__APCS_32__", NULL
);
1896 #ifdef TCC_TARGET_PE
1897 tcc_define_symbol(s
, "_WIN32", NULL
);
1898 #ifdef TCC_TARGET_X86_64
1899 tcc_define_symbol(s
, "_WIN64", NULL
);
1902 tcc_define_symbol(s
, "__unix__", "1");
1903 tcc_define_symbol(s
, "__unix", "1");
1904 tcc_define_symbol(s
, "unix", "1");
1905 #if defined(__FreeBSD__)
1907 tcc_define_symbol(s
, "__FreeBSD__", str( __FreeBSD__
));
1908 tcc_define_symbol(s
, "__INTEL_COMPILER", "1");
1911 #if defined(__linux)
1912 tcc_define_symbol(s
, "__linux__", NULL
);
1913 tcc_define_symbol(s
, "__linux", NULL
);
1916 /* tiny C specific defines */
1917 sscanf(TCC_VERSION
, "%d.%d.%d", &a
, &b
, &c
);
1918 sprintf(buffer
, "%d", a
*10000 + b
*100 + c
);
1919 tcc_define_symbol(s
, "__TINYC__", buffer
);
1921 /* tiny C & gcc defines */
1922 tcc_define_symbol(s
, "__SIZE_TYPE__", "unsigned long");
1923 tcc_define_symbol(s
, "__PTRDIFF_TYPE__", "long");
1924 #ifdef TCC_TARGET_PE
1925 tcc_define_symbol(s
, "__WCHAR_TYPE__", "unsigned short");
1927 tcc_define_symbol(s
, "__WCHAR_TYPE__", "int");
1930 #ifndef TCC_TARGET_PE
1931 /* default library paths */
1932 tcc_add_library_path(s
, CONFIG_SYSROOT
"/usr/local/lib");
1933 tcc_add_library_path(s
, CONFIG_SYSROOT
"/usr/lib");
1934 tcc_add_library_path(s
, CONFIG_SYSROOT
"/lib");
1937 /* no section zero */
1938 dynarray_add((void ***)&s
->sections
, &s
->nb_sections
, NULL
);
1940 /* create standard sections */
1941 text_section
= new_section(s
, ".text", SHT_PROGBITS
, SHF_ALLOC
| SHF_EXECINSTR
);
1942 data_section
= new_section(s
, ".data", SHT_PROGBITS
, SHF_ALLOC
| SHF_WRITE
);
1943 bss_section
= new_section(s
, ".bss", SHT_NOBITS
, SHF_ALLOC
| SHF_WRITE
);
1945 /* symbols are always generated for linking stage */
1946 symtab_section
= new_symtab(s
, ".symtab", SHT_SYMTAB
, 0,
1948 ".hashtab", SHF_PRIVATE
);
1949 strtab_section
= symtab_section
->link
;
1951 /* private symbol table for dynamic symbols */
1952 s
->dynsymtab_section
= new_symtab(s
, ".dynsymtab", SHT_SYMTAB
, SHF_PRIVATE
,
1954 ".dynhashtab", SHF_PRIVATE
);
1955 s
->alacarte_link
= 1;
1957 #ifdef CHAR_IS_UNSIGNED
1958 s
->char_is_unsigned
= 1;
1960 #if defined(TCC_TARGET_PE) && 0
1961 /* XXX: currently the PE linker is not ready to support that */
1962 s
->leading_underscore
= 1;
1965 if (s
->section_align
== 0)
1966 s
->section_align
= ELF_PAGE_SIZE
;
1968 #ifdef TCC_TARGET_I386
1974 void tcc_delete(TCCState
*s1
)
1980 /* free all sections */
1981 for(i
= 1; i
< s1
->nb_sections
; i
++)
1982 free_section(s1
->sections
[i
]);
1983 dynarray_reset(&s1
->sections
, &s1
->nb_sections
);
1985 for(i
= 0; i
< s1
->nb_priv_sections
; i
++)
1986 free_section(s1
->priv_sections
[i
]);
1987 dynarray_reset(&s1
->priv_sections
, &s1
->nb_priv_sections
);
1989 /* free any loaded DLLs */
1990 for ( i
= 0; i
< s1
->nb_loaded_dlls
; i
++) {
1991 DLLReference
*ref
= s1
->loaded_dlls
[i
];
1993 dlclose(ref
->handle
);
1996 /* free loaded dlls array */
1997 dynarray_reset(&s1
->loaded_dlls
, &s1
->nb_loaded_dlls
);
1999 /* free library paths */
2000 dynarray_reset(&s1
->library_paths
, &s1
->nb_library_paths
);
2002 /* free include paths */
2003 dynarray_reset(&s1
->cached_includes
, &s1
->nb_cached_includes
);
2004 dynarray_reset(&s1
->include_paths
, &s1
->nb_include_paths
);
2005 dynarray_reset(&s1
->sysinclude_paths
, &s1
->nb_sysinclude_paths
);
2007 tcc_free(s1
->tcc_lib_path
);
2011 int tcc_add_include_path(TCCState
*s1
, const char *pathname
)
2015 pathname1
= tcc_strdup(pathname
);
2016 dynarray_add((void ***)&s1
->include_paths
, &s1
->nb_include_paths
, pathname1
);
2020 int tcc_add_sysinclude_path(TCCState
*s1
, const char *pathname
)
2024 pathname1
= tcc_strdup(pathname
);
2025 dynarray_add((void ***)&s1
->sysinclude_paths
, &s1
->nb_sysinclude_paths
, pathname1
);
2029 static int tcc_add_file_internal(TCCState
*s1
, const char *filename
, int flags
)
2034 BufferedFile
*saved_file
;
2038 /* find source file type with extension */
2039 ext
= tcc_fileextension(filename
);
2045 file
= tcc_open(s1
, filename
);
2047 if (flags
& AFF_PRINT_ERROR
)
2048 error_noabort("file '%s' not found", filename
);
2052 if (flags
& AFF_PREPROCESS
) {
2053 ret
= tcc_preprocess(s1
);
2057 if (!ext
[0] || !PATHCMP(ext
, "c")) {
2058 /* C file assumed */
2059 ret
= tcc_compile(s1
);
2063 #ifdef CONFIG_TCC_ASM
2064 if (!strcmp(ext
, "S")) {
2065 /* preprocessed assembler */
2066 ret
= tcc_assemble(s1
, 1);
2070 if (!strcmp(ext
, "s")) {
2071 /* non preprocessed assembler */
2072 ret
= tcc_assemble(s1
, 0);
2078 /* assume executable format: auto guess file type */
2079 size
= read(fd
, &ehdr
, sizeof(ehdr
));
2080 lseek(fd
, 0, SEEK_SET
);
2082 error_noabort("could not read header");
2086 if (size
== sizeof(ehdr
) &&
2087 ehdr
.e_ident
[0] == ELFMAG0
&&
2088 ehdr
.e_ident
[1] == ELFMAG1
&&
2089 ehdr
.e_ident
[2] == ELFMAG2
&&
2090 ehdr
.e_ident
[3] == ELFMAG3
) {
2092 /* do not display line number if error */
2094 if (ehdr
.e_type
== ET_REL
) {
2095 ret
= tcc_load_object_file(s1
, fd
, 0);
2099 #ifndef TCC_TARGET_PE
2100 if (ehdr
.e_type
== ET_DYN
) {
2101 if (s1
->output_type
== TCC_OUTPUT_MEMORY
) {
2103 h
= dlopen(filename
, RTLD_GLOBAL
| RTLD_LAZY
);
2107 ret
= tcc_load_dll(s1
, fd
, filename
,
2108 (flags
& AFF_REFERENCED_DLL
) != 0);
2113 error_noabort("unrecognized ELF file");
2117 if (memcmp((char *)&ehdr
, ARMAG
, 8) == 0) {
2118 file
->line_num
= 0; /* do not display line number if error */
2119 ret
= tcc_load_archive(s1
, fd
);
2123 #ifdef TCC_TARGET_COFF
2124 if (*(uint16_t *)(&ehdr
) == COFF_C67_MAGIC
) {
2125 ret
= tcc_load_coff(s1
, fd
);
2130 #ifdef TCC_TARGET_PE
2131 ret
= pe_load_file(s1
, filename
, fd
);
2133 /* as GNU ld, consider it is an ld script if not recognized */
2134 ret
= tcc_load_ldscript(s1
);
2137 error_noabort("unrecognized file type");
2146 int tcc_add_file(TCCState
*s
, const char *filename
)
2148 if (s
->output_type
== TCC_OUTPUT_PREPROCESS
)
2149 return tcc_add_file_internal(s
, filename
, AFF_PRINT_ERROR
| AFF_PREPROCESS
);
2151 return tcc_add_file_internal(s
, filename
, AFF_PRINT_ERROR
);
2154 int tcc_add_library_path(TCCState
*s
, const char *pathname
)
2158 pathname1
= tcc_strdup(pathname
);
2159 dynarray_add((void ***)&s
->library_paths
, &s
->nb_library_paths
, pathname1
);
2163 /* find and load a dll. Return non zero if not found */
2164 /* XXX: add '-rpath' option support ? */
2165 static int tcc_add_dll(TCCState
*s
, const char *filename
, int flags
)
2170 for(i
= 0; i
< s
->nb_library_paths
; i
++) {
2171 snprintf(buf
, sizeof(buf
), "%s/%s",
2172 s
->library_paths
[i
], filename
);
2173 if (tcc_add_file_internal(s
, buf
, flags
) == 0)
2179 /* the library name is the same as the argument of the '-l' option */
2180 int tcc_add_library(TCCState
*s
, const char *libraryname
)
2185 /* first we look for the dynamic library if not static linking */
2186 if (!s
->static_link
) {
2187 #ifdef TCC_TARGET_PE
2188 if (pe_add_dll(s
, libraryname
) == 0)
2191 snprintf(buf
, sizeof(buf
), "lib%s.so", libraryname
);
2192 if (tcc_add_dll(s
, buf
, 0) == 0)
2196 /* then we look for the static library */
2197 for(i
= 0; i
< s
->nb_library_paths
; i
++) {
2198 snprintf(buf
, sizeof(buf
), "%s/lib%s.a",
2199 s
->library_paths
[i
], libraryname
);
2200 if (tcc_add_file_internal(s
, buf
, 0) == 0)
2206 int tcc_add_symbol(TCCState
*s
, const char *name
, void *val
)
2208 add_elf_sym(symtab_section
, (uplong
)val
, 0,
2209 ELFW(ST_INFO
)(STB_GLOBAL
, STT_NOTYPE
), 0,
2214 int tcc_set_output_type(TCCState
*s
, int output_type
)
2218 s
->output_type
= output_type
;
2221 /* default include paths */
2222 /* XXX: reverse order needed if -isystem support */
2223 #ifndef TCC_TARGET_PE
2224 tcc_add_sysinclude_path(s
, CONFIG_SYSROOT
"/usr/local/include");
2225 tcc_add_sysinclude_path(s
, CONFIG_SYSROOT
"/usr/include");
2227 snprintf(buf
, sizeof(buf
), "%s/include", s
->tcc_lib_path
);
2228 tcc_add_sysinclude_path(s
, buf
);
2229 #ifdef TCC_TARGET_PE
2230 snprintf(buf
, sizeof(buf
), "%s/include/winapi", s
->tcc_lib_path
);
2231 tcc_add_sysinclude_path(s
, buf
);
2235 /* if bound checking, then add corresponding sections */
2236 #ifdef CONFIG_TCC_BCHECK
2237 if (s
->do_bounds_check
) {
2239 tcc_define_symbol(s
, "__BOUNDS_CHECKING_ON", NULL
);
2240 /* create bounds sections */
2241 bounds_section
= new_section(s
, ".bounds",
2242 SHT_PROGBITS
, SHF_ALLOC
);
2243 lbounds_section
= new_section(s
, ".lbounds",
2244 SHT_PROGBITS
, SHF_ALLOC
);
2248 if (s
->char_is_unsigned
) {
2249 tcc_define_symbol(s
, "__CHAR_UNSIGNED__", NULL
);
2252 /* add debug sections */
2255 stab_section
= new_section(s
, ".stab", SHT_PROGBITS
, 0);
2256 stab_section
->sh_entsize
= sizeof(Stab_Sym
);
2257 stabstr_section
= new_section(s
, ".stabstr", SHT_STRTAB
, 0);
2258 put_elf_str(stabstr_section
, "");
2259 stab_section
->link
= stabstr_section
;
2260 /* put first entry */
2261 put_stabs("", 0, 0, 0, 0);
2264 /* add libc crt1/crti objects */
2265 #ifndef TCC_TARGET_PE
2266 if ((output_type
== TCC_OUTPUT_EXE
|| output_type
== TCC_OUTPUT_DLL
) &&
2268 if (output_type
!= TCC_OUTPUT_DLL
)
2269 tcc_add_file(s
, CONFIG_TCC_CRT_PREFIX
"/crt1.o");
2270 tcc_add_file(s
, CONFIG_TCC_CRT_PREFIX
"/crti.o");
2274 #ifdef TCC_TARGET_PE
2275 snprintf(buf
, sizeof(buf
), "%s/lib", s
->tcc_lib_path
);
2276 tcc_add_library_path(s
, buf
);
2278 if (GetSystemDirectory(buf
, sizeof buf
))
2279 tcc_add_library_path(s
, buf
);
2286 #define WD_ALL 0x0001 /* warning is activated when using -Wall */
2287 #define FD_INVERT 0x0002 /* invert value before storing */
2289 typedef struct FlagDef
{
2295 static const FlagDef warning_defs
[] = {
2296 { offsetof(TCCState
, warn_unsupported
), 0, "unsupported" },
2297 { offsetof(TCCState
, warn_write_strings
), 0, "write-strings" },
2298 { offsetof(TCCState
, warn_error
), 0, "error" },
2299 { offsetof(TCCState
, warn_implicit_function_declaration
), WD_ALL
,
2300 "implicit-function-declaration" },
2303 static int set_flag(TCCState
*s
, const FlagDef
*flags
, int nb_flags
,
2304 const char *name
, int value
)
2311 if (r
[0] == 'n' && r
[1] == 'o' && r
[2] == '-') {
2315 for(i
= 0, p
= flags
; i
< nb_flags
; i
++, p
++) {
2316 if (!strcmp(r
, p
->name
))
2321 if (p
->flags
& FD_INVERT
)
2323 *(int *)((uint8_t *)s
+ p
->offset
) = value
;
2328 /* set/reset a warning */
2329 int tcc_set_warning(TCCState
*s
, const char *warning_name
, int value
)
2334 if (!strcmp(warning_name
, "all")) {
2335 for(i
= 0, p
= warning_defs
; i
< countof(warning_defs
); i
++, p
++) {
2336 if (p
->flags
& WD_ALL
)
2337 *(int *)((uint8_t *)s
+ p
->offset
) = 1;
2341 return set_flag(s
, warning_defs
, countof(warning_defs
),
2342 warning_name
, value
);
2346 static const FlagDef flag_defs
[] = {
2347 { offsetof(TCCState
, char_is_unsigned
), 0, "unsigned-char" },
2348 { offsetof(TCCState
, char_is_unsigned
), FD_INVERT
, "signed-char" },
2349 { offsetof(TCCState
, nocommon
), FD_INVERT
, "common" },
2350 { offsetof(TCCState
, leading_underscore
), 0, "leading-underscore" },
2353 /* set/reset a flag */
2354 int tcc_set_flag(TCCState
*s
, const char *flag_name
, int value
)
2356 return set_flag(s
, flag_defs
, countof(flag_defs
),
2360 /* set CONFIG_TCCDIR at runtime */
2361 void tcc_set_lib_path(TCCState
*s
, const char *path
)
2363 tcc_free(s
->tcc_lib_path
);
2364 s
->tcc_lib_path
= tcc_strdup(path
);
2367 void tcc_print_stats(TCCState
*s
, int64_t total_time
)
2370 tt
= (double)total_time
/ 1000000.0;
2373 if (total_bytes
< 1)
2375 printf("%d idents, %d lines, %d bytes, %0.3f s, %d lines/s, %0.1f MB/s\n",
2376 tok_ident
- TOK_IDENT
, total_lines
, total_bytes
,
2377 tt
, (int)(total_lines
/ tt
),
2378 total_bytes
/ tt
/ 1000000.0);