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 /* display benchmark infos */
28 static struct BufferedFile
*file
;
31 static CString tokcstr
; /* current parsed string, if any */
32 /* additional informations about token */
34 #define TOK_FLAG_BOL 0x0001 /* beginning of line before */
35 #define TOK_FLAG_BOF 0x0002 /* beginning of file before */
36 #define TOK_FLAG_ENDIF 0x0004 /* a endif was found matching starting #ifdef */
37 #define TOK_FLAG_EOF 0x0008 /* end of file */
39 static int *macro_ptr
, *macro_ptr_allocated
;
40 static int *unget_saved_macro_ptr
;
41 static int unget_saved_buffer
[TOK_MAX_SIZE
+ 1];
42 static int unget_buffer_enabled
;
43 static int parse_flags
;
44 #define PARSE_FLAG_PREPROCESS 0x0001 /* activate preprocessing */
45 #define PARSE_FLAG_TOK_NUM 0x0002 /* return numbers instead of TOK_PPNUM */
46 #define PARSE_FLAG_LINEFEED 0x0004 /* line feed is returned as a
47 token. line feed is also
49 #define PARSE_FLAG_ASM_COMMENTS 0x0008 /* '#' can be used for line comment */
50 #define PARSE_FLAG_SPACES 0x0010 /* next() returns space tokens (for -E) */
52 static Section
*text_section
, *data_section
, *bss_section
; /* predefined sections */
53 static Section
*cur_text_section
; /* current section where function code is
56 static Section
*last_text_section
; /* to handle .previous asm directive */
58 /* bound check related sections */
59 static Section
*bounds_section
; /* contains global data bound description */
60 static Section
*lbounds_section
; /* contains local data bound description */
62 static Section
*symtab_section
, *strtab_section
;
65 static Section
*stab_section
, *stabstr_section
;
67 /* loc : local variable index
68 ind : output code index
70 anon_sym: anonymous symbol index
72 static int rsym
, anon_sym
, ind
, loc
;
73 /* expression generation modifiers */
74 static int const_wanted
; /* true if constant wanted */
75 static int nocode_wanted
; /* true if no code generation wanted for an expression */
76 static int global_expr
; /* true if compound literals must be allocated
77 globally (used during initializers parsing */
78 static CType func_vt
; /* current function return type (used by return
81 static int last_line_num
, last_ind
, func_ind
; /* debug last line number and pc */
83 static TokenSym
**table_ident
;
84 static TokenSym
*hash_ident
[TOK_HASH_SIZE
];
85 static char token_buf
[STRING_MAX_SIZE
+ 1];
86 static char *funcname
;
87 static Sym
*global_stack
, *local_stack
;
88 static Sym
*define_stack
;
89 static Sym
*global_label_stack
, *local_label_stack
;
90 /* symbol allocator */
91 #define SYM_POOL_NB (8192 / sizeof(Sym))
92 static Sym
*sym_free_first
;
93 static void **sym_pools
;
94 static int nb_sym_pools
;
96 static SValue vstack
[VSTACK_SIZE
], *vtop
;
97 /* some predefined types */
98 static CType char_pointer_type
, func_old_type
, int_type
;
100 /* use GNU C extensions */
101 static int gnu_ext
= 1;
103 /* use Tiny C extensions */
104 static int tcc_ext
= 1;
106 /* max number of callers shown if error */
107 #ifdef CONFIG_TCC_BACKTRACE
109 const char **rt_bound_error_msg
;
112 /* XXX: get rid of this ASAP */
113 static struct TCCState
*tcc_state
;
115 #ifdef TCC_TARGET_I386
116 #include "i386-gen.c"
119 #ifdef TCC_TARGET_ARM
123 #ifdef TCC_TARGET_C67
127 #ifdef TCC_TARGET_X86_64
128 #include "x86_64-gen.c"
131 #ifdef CONFIG_TCC_STATIC
133 #define RTLD_LAZY 0x001
134 #define RTLD_NOW 0x002
135 #define RTLD_GLOBAL 0x100
136 #define RTLD_DEFAULT NULL
138 /* dummy function for profiling */
139 void *dlopen(const char *filename
, int flag
)
144 void dlclose(void *p
)
148 const char *dlerror(void)
153 typedef struct TCCSyms
{
158 #define TCCSYM(a) { #a, &a, },
160 /* add the symbol you want here if no dynamic linking is done */
161 static TCCSyms tcc_syms
[] = {
162 #if !defined(CONFIG_TCCBOOT)
171 void *resolve_sym(TCCState
*s1
, const char *symbol
, int type
)
175 while (p
->str
!= NULL
) {
176 if (!strcmp(p
->str
, symbol
))
183 #elif !defined(_WIN32)
187 void *resolve_sym(TCCState
*s1
, const char *sym
, int type
)
189 return dlsym(RTLD_DEFAULT
, sym
);
194 /********************************************************/
196 /* we use our own 'finite' function to avoid potential problems with
197 non standard math libs */
198 /* XXX: endianness dependent */
199 int ieee_finite(double d
)
202 return ((unsigned)((p
[1] | 0x800fffff) + 1)) >> 31;
205 /* copy a string and truncate it. */
206 static char *pstrcpy(char *buf
, int buf_size
, const char *s
)
213 q_end
= buf
+ buf_size
- 1;
225 /* strcat and truncate. */
226 static char *pstrcat(char *buf
, int buf_size
, const char *s
)
231 pstrcpy(buf
+ len
, buf_size
- len
, s
);
235 /* extract the basename of a file */
236 static char *tcc_basename(const char *name
)
238 char *p
= strchr(name
, 0);
239 while (p
> name
&& !IS_PATHSEP(p
[-1]))
244 static char *tcc_fileextension (const char *name
)
246 char *b
= tcc_basename(name
);
247 char *e
= strrchr(b
, '.');
248 return e
? e
: strchr(b
, 0);
252 char *normalize_slashes(char *path
)
255 for (p
= path
; *p
; ++p
)
261 void tcc_set_lib_path_w32(TCCState
*s
)
263 /* on win32, we suppose the lib and includes are at the location
266 GetModuleFileNameA(NULL
, path
, sizeof path
);
267 p
= tcc_basename(normalize_slashes(strlwr(path
)));
268 if (p
- 5 > path
&& 0 == strncmp(p
- 5, "/bin/", 5))
273 tcc_set_lib_path(s
, path
);
277 void set_pages_executable(void *ptr
, unsigned long length
)
280 unsigned long old_protect
;
281 VirtualProtect(ptr
, length
, PAGE_EXECUTE_READWRITE
, &old_protect
);
283 unsigned long start
, end
;
284 start
= (unsigned long)ptr
& ~(PAGESIZE
- 1);
285 end
= (unsigned long)ptr
+ length
;
286 end
= (end
+ PAGESIZE
- 1) & ~(PAGESIZE
- 1);
287 mprotect((void *)start
, end
- start
, PROT_READ
| PROT_WRITE
| PROT_EXEC
);
291 /* memory management */
295 unsigned malloc_usable_size(void*);
298 static inline void tcc_free(void *ptr
)
301 mem_cur_size
-= malloc_usable_size(ptr
);
306 static void *tcc_malloc(unsigned long size
)
311 error("memory full");
313 mem_cur_size
+= malloc_usable_size(ptr
);
314 if (mem_cur_size
> mem_max_size
)
315 mem_max_size
= mem_cur_size
;
320 static void *tcc_mallocz(unsigned long size
)
323 ptr
= tcc_malloc(size
);
324 memset(ptr
, 0, size
);
328 static inline void *tcc_realloc(void *ptr
, unsigned long size
)
332 mem_cur_size
-= malloc_usable_size(ptr
);
334 ptr1
= realloc(ptr
, size
);
336 /* NOTE: count not correct if alloc error, but not critical */
337 mem_cur_size
+= malloc_usable_size(ptr1
);
338 if (mem_cur_size
> mem_max_size
)
339 mem_max_size
= mem_cur_size
;
344 static char *tcc_strdup(const char *str
)
347 ptr
= tcc_malloc(strlen(str
) + 1);
352 #define free(p) use_tcc_free(p)
353 #define malloc(s) use_tcc_malloc(s)
354 #define realloc(p, s) use_tcc_realloc(p, s)
356 static void dynarray_add(void ***ptab
, int *nb_ptr
, void *data
)
363 /* every power of two we double array size */
364 if ((nb
& (nb
- 1)) == 0) {
369 pp
= tcc_realloc(pp
, nb_alloc
* sizeof(void *));
371 error("memory full");
378 static void dynarray_reset(void *pp
, int *n
)
381 for (p
= *(void***)pp
; *n
; ++p
, --*n
)
384 tcc_free(*(void**)pp
);
388 /* symbol allocator */
389 static Sym
*__sym_malloc(void)
391 Sym
*sym_pool
, *sym
, *last_sym
;
394 sym_pool
= tcc_malloc(SYM_POOL_NB
* sizeof(Sym
));
395 dynarray_add(&sym_pools
, &nb_sym_pools
, sym_pool
);
397 last_sym
= sym_free_first
;
399 for(i
= 0; i
< SYM_POOL_NB
; i
++) {
400 sym
->next
= last_sym
;
404 sym_free_first
= last_sym
;
408 static inline Sym
*sym_malloc(void)
411 sym
= sym_free_first
;
413 sym
= __sym_malloc();
414 sym_free_first
= sym
->next
;
418 static inline void sym_free(Sym
*sym
)
420 sym
->next
= sym_free_first
;
421 sym_free_first
= sym
;
424 Section
*new_section(TCCState
*s1
, const char *name
, int sh_type
, int sh_flags
)
428 sec
= tcc_mallocz(sizeof(Section
) + strlen(name
));
429 strcpy(sec
->name
, name
);
430 sec
->sh_type
= sh_type
;
431 sec
->sh_flags
= sh_flags
;
439 sec
->sh_addralign
= 4;
442 sec
->sh_addralign
= 1;
445 sec
->sh_addralign
= 32; /* default conservative alignment */
449 if (sh_flags
& SHF_PRIVATE
) {
450 dynarray_add((void ***)&s1
->priv_sections
, &s1
->nb_priv_sections
, sec
);
452 sec
->sh_num
= s1
->nb_sections
;
453 dynarray_add((void ***)&s1
->sections
, &s1
->nb_sections
, sec
);
459 static void free_section(Section
*s
)
464 /* realloc section and set its content to zero */
465 static void section_realloc(Section
*sec
, unsigned long new_size
)
470 size
= sec
->data_allocated
;
473 while (size
< new_size
)
475 data
= tcc_realloc(sec
->data
, size
);
477 error("memory full");
478 memset(data
+ sec
->data_allocated
, 0, size
- sec
->data_allocated
);
480 sec
->data_allocated
= size
;
483 /* reserve at least 'size' bytes in section 'sec' from
485 static void *section_ptr_add(Section
*sec
, unsigned long size
)
487 unsigned long offset
, offset1
;
489 offset
= sec
->data_offset
;
490 offset1
= offset
+ size
;
491 if (offset1
> sec
->data_allocated
)
492 section_realloc(sec
, offset1
);
493 sec
->data_offset
= offset1
;
494 return sec
->data
+ offset
;
497 /* return a reference to a section, and create it if it does not
499 Section
*find_section(TCCState
*s1
, const char *name
)
503 for(i
= 1; i
< s1
->nb_sections
; i
++) {
504 sec
= s1
->sections
[i
];
505 if (!strcmp(name
, sec
->name
))
508 /* sections are created as PROGBITS */
509 return new_section(s1
, name
, SHT_PROGBITS
, SHF_ALLOC
);
512 /* update sym->c so that it points to an external symbol in section
513 'section' with value 'value' */
514 static void put_extern_sym2(Sym
*sym
, Section
*section
,
515 unsigned long value
, unsigned long size
,
516 int can_add_underscore
)
518 int sym_type
, sym_bind
, sh_num
, info
, other
, attr
;
525 else if (section
== SECTION_ABS
)
528 sh_num
= section
->sh_num
;
532 if ((sym
->type
.t
& VT_BTYPE
) == VT_FUNC
) {
536 attr
= sym
->type
.ref
->r
;
537 if (FUNC_EXPORT(attr
))
539 if (FUNC_CALL(attr
) == FUNC_STDCALL
)
543 sym_type
= STT_OBJECT
;
546 if (sym
->type
.t
& VT_STATIC
)
547 sym_bind
= STB_LOCAL
;
549 sym_bind
= STB_GLOBAL
;
552 name
= get_tok_str(sym
->v
, NULL
);
553 #ifdef CONFIG_TCC_BCHECK
554 if (tcc_state
->do_bounds_check
) {
557 /* XXX: avoid doing that for statics ? */
558 /* if bound checking is activated, we change some function
559 names by adding the "__bound" prefix */
562 /* XXX: we rely only on malloc hooks */
575 strcpy(buf
, "__bound_");
584 if ((other
& 2) && can_add_underscore
) {
585 sprintf(buf1
, "_%s@%d", name
, FUNC_ARGS(attr
));
589 if (tcc_state
->leading_underscore
&& can_add_underscore
) {
591 pstrcpy(buf1
+ 1, sizeof(buf1
) - 1, name
);
594 info
= ELFW(ST_INFO
)(sym_bind
, sym_type
);
595 sym
->c
= add_elf_sym(symtab_section
, value
, size
, info
, other
, sh_num
, name
);
597 esym
= &((ElfW(Sym
) *)symtab_section
->data
)[sym
->c
];
598 esym
->st_value
= value
;
599 esym
->st_size
= size
;
600 esym
->st_shndx
= sh_num
;
601 esym
->st_other
|= other
;
605 static void put_extern_sym(Sym
*sym
, Section
*section
,
606 unsigned long value
, unsigned long size
)
608 put_extern_sym2(sym
, section
, value
, size
, 1);
611 /* add a new relocation entry to symbol 'sym' in section 's' */
612 static void greloc(Section
*s
, Sym
*sym
, unsigned long offset
, int type
)
615 put_extern_sym(sym
, NULL
, 0, 0);
616 /* now we can add ELF relocation info */
617 put_elf_reloc(symtab_section
, s
, offset
, type
, sym
->c
);
620 static inline int isid(int c
)
622 return (c
>= 'a' && c
<= 'z') ||
623 (c
>= 'A' && c
<= 'Z') ||
627 static inline int isnum(int c
)
629 return c
>= '0' && c
<= '9';
632 static inline int isoct(int c
)
634 return c
>= '0' && c
<= '7';
637 static inline int toup(int c
)
639 if (c
>= 'a' && c
<= 'z')
640 return c
- 'a' + 'A';
645 static void strcat_vprintf(char *buf
, int buf_size
, const char *fmt
, va_list ap
)
649 vsnprintf(buf
+ len
, buf_size
- len
, fmt
, ap
);
652 static void strcat_printf(char *buf
, int buf_size
, const char *fmt
, ...)
656 strcat_vprintf(buf
, buf_size
, fmt
, ap
);
660 void error1(TCCState
*s1
, int is_warning
, const char *fmt
, va_list ap
)
667 for(f
= s1
->include_stack
; f
< s1
->include_stack_ptr
; f
++)
668 strcat_printf(buf
, sizeof(buf
), "In file included from %s:%d:\n",
669 (*f
)->filename
, (*f
)->line_num
);
670 if (file
->line_num
> 0) {
671 strcat_printf(buf
, sizeof(buf
),
672 "%s:%d: ", file
->filename
, file
->line_num
);
674 strcat_printf(buf
, sizeof(buf
),
675 "%s: ", file
->filename
);
678 strcat_printf(buf
, sizeof(buf
),
682 strcat_printf(buf
, sizeof(buf
), "warning: ");
683 strcat_vprintf(buf
, sizeof(buf
), fmt
, ap
);
685 if (!s1
->error_func
) {
686 /* default case: stderr */
687 fprintf(stderr
, "%s\n", buf
);
689 s1
->error_func(s1
->error_opaque
, buf
);
691 if (!is_warning
|| s1
->warn_error
)
695 void tcc_set_error_func(TCCState
*s
, void *error_opaque
,
696 void (*error_func
)(void *opaque
, const char *msg
))
698 s
->error_opaque
= error_opaque
;
699 s
->error_func
= error_func
;
702 /* error without aborting current compilation */
703 void error_noabort(const char *fmt
, ...)
705 TCCState
*s1
= tcc_state
;
709 error1(s1
, 0, fmt
, ap
);
713 void error(const char *fmt
, ...)
715 TCCState
*s1
= tcc_state
;
719 error1(s1
, 0, fmt
, ap
);
721 /* better than nothing: in some cases, we accept to handle errors */
722 if (s1
->error_set_jmp_enabled
) {
723 longjmp(s1
->error_jmp_buf
, 1);
725 /* XXX: eliminate this someday */
730 void expect(const char *msg
)
732 error("%s expected", msg
);
735 void warning(const char *fmt
, ...)
737 TCCState
*s1
= tcc_state
;
744 error1(s1
, 1, fmt
, ap
);
751 error("'%c' expected", c
);
755 static void test_lvalue(void)
757 if (!(vtop
->r
& VT_LVAL
))
761 /* CString handling */
763 static void cstr_realloc(CString
*cstr
, int new_size
)
768 size
= cstr
->size_allocated
;
770 size
= 8; /* no need to allocate a too small first string */
771 while (size
< new_size
)
773 data
= tcc_realloc(cstr
->data_allocated
, size
);
775 error("memory full");
776 cstr
->data_allocated
= data
;
777 cstr
->size_allocated
= size
;
782 static inline void cstr_ccat(CString
*cstr
, int ch
)
785 size
= cstr
->size
+ 1;
786 if (size
> cstr
->size_allocated
)
787 cstr_realloc(cstr
, size
);
788 ((unsigned char *)cstr
->data
)[size
- 1] = ch
;
792 static void cstr_cat(CString
*cstr
, const char *str
)
804 /* add a wide char */
805 static void cstr_wccat(CString
*cstr
, int ch
)
808 size
= cstr
->size
+ sizeof(nwchar_t
);
809 if (size
> cstr
->size_allocated
)
810 cstr_realloc(cstr
, size
);
811 *(nwchar_t
*)(((unsigned char *)cstr
->data
) + size
- sizeof(nwchar_t
)) = ch
;
815 static void cstr_new(CString
*cstr
)
817 memset(cstr
, 0, sizeof(CString
));
820 /* free string and reset it to NULL */
821 static void cstr_free(CString
*cstr
)
823 tcc_free(cstr
->data_allocated
);
827 #define cstr_reset(cstr) cstr_free(cstr)
830 static void add_char(CString
*cstr
, int c
)
832 if (c
== '\'' || c
== '\"' || c
== '\\') {
833 /* XXX: could be more precise if char or string */
834 cstr_ccat(cstr
, '\\');
836 if (c
>= 32 && c
<= 126) {
839 cstr_ccat(cstr
, '\\');
841 cstr_ccat(cstr
, 'n');
843 cstr_ccat(cstr
, '0' + ((c
>> 6) & 7));
844 cstr_ccat(cstr
, '0' + ((c
>> 3) & 7));
845 cstr_ccat(cstr
, '0' + (c
& 7));
850 /* push, without hashing */
851 static Sym
*sym_push2(Sym
**ps
, int v
, int t
, long c
)
865 /* find a symbol and return its associated structure. 's' is the top
866 of the symbol stack */
867 static Sym
*sym_find2(Sym
*s
, int v
)
877 /* structure lookup */
878 static inline Sym
*struct_find(int v
)
881 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
883 return table_ident
[v
]->sym_struct
;
886 /* find an identifier */
887 static inline Sym
*sym_find(int v
)
890 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
892 return table_ident
[v
]->sym_identifier
;
895 /* push a given symbol on the symbol stack */
896 static Sym
*sym_push(int v
, CType
*type
, int r
, int c
)
905 s
= sym_push2(ps
, v
, type
->t
, c
);
906 s
->type
.ref
= type
->ref
;
908 /* don't record fields or anonymous symbols */
910 if (!(v
& SYM_FIELD
) && (v
& ~SYM_STRUCT
) < SYM_FIRST_ANOM
) {
911 /* record symbol in token array */
912 ts
= table_ident
[(v
& ~SYM_STRUCT
) - TOK_IDENT
];
914 ps
= &ts
->sym_struct
;
916 ps
= &ts
->sym_identifier
;
923 /* push a global identifier */
924 static Sym
*global_identifier_push(int v
, int t
, int c
)
927 s
= sym_push2(&global_stack
, v
, t
, c
);
928 /* don't record anonymous symbol */
929 if (v
< SYM_FIRST_ANOM
) {
930 ps
= &table_ident
[v
- TOK_IDENT
]->sym_identifier
;
931 /* modify the top most local identifier, so that
932 sym_identifier will point to 's' when popped */
934 ps
= &(*ps
)->prev_tok
;
941 /* pop symbols until top reaches 'b' */
942 static void sym_pop(Sym
**ptop
, Sym
*b
)
952 /* remove symbol in token array */
954 if (!(v
& SYM_FIELD
) && (v
& ~SYM_STRUCT
) < SYM_FIRST_ANOM
) {
955 ts
= table_ident
[(v
& ~SYM_STRUCT
) - TOK_IDENT
];
957 ps
= &ts
->sym_struct
;
959 ps
= &ts
->sym_identifier
;
970 BufferedFile
*tcc_open(TCCState
*s1
, const char *filename
)
975 if (strcmp(filename
, "-") == 0)
976 fd
= 0, filename
= "stdin";
978 fd
= open(filename
, O_RDONLY
| O_BINARY
);
979 if ((s1
->verbose
== 2 && fd
>= 0) || s1
->verbose
== 3)
980 printf("%s %*s%s\n", fd
< 0 ? "nf":"->",
981 (s1
->include_stack_ptr
- s1
->include_stack
), "", filename
);
984 bf
= tcc_malloc(sizeof(BufferedFile
));
986 bf
->buf_ptr
= bf
->buffer
;
987 bf
->buf_end
= bf
->buffer
;
988 bf
->buffer
[0] = CH_EOB
; /* put eob symbol */
989 pstrcpy(bf
->filename
, sizeof(bf
->filename
), filename
);
991 normalize_slashes(bf
->filename
);
994 bf
->ifndef_macro
= 0;
995 bf
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
996 // printf("opening '%s'\n", filename);
1000 void tcc_close(BufferedFile
*bf
)
1002 total_lines
+= bf
->line_num
;
1011 /* compile the C file opened in 'file'. Return non zero if errors. */
1012 static int tcc_compile(TCCState
*s1
)
1016 volatile int section_sym
;
1019 printf("%s: **** new file\n", file
->filename
);
1021 preprocess_init(s1
);
1023 cur_text_section
= NULL
;
1025 anon_sym
= SYM_FIRST_ANOM
;
1027 /* file info: full path + filename */
1028 section_sym
= 0; /* avoid warning */
1030 section_sym
= put_elf_sym(symtab_section
, 0, 0,
1031 ELFW(ST_INFO
)(STB_LOCAL
, STT_SECTION
), 0,
1032 text_section
->sh_num
, NULL
);
1033 getcwd(buf
, sizeof(buf
));
1035 normalize_slashes(buf
);
1037 pstrcat(buf
, sizeof(buf
), "/");
1038 put_stabs_r(buf
, N_SO
, 0, 0,
1039 text_section
->data_offset
, text_section
, section_sym
);
1040 put_stabs_r(file
->filename
, N_SO
, 0, 0,
1041 text_section
->data_offset
, text_section
, section_sym
);
1043 /* an elf symbol of type STT_FILE must be put so that STB_LOCAL
1044 symbols can be safely used */
1045 put_elf_sym(symtab_section
, 0, 0,
1046 ELFW(ST_INFO
)(STB_LOCAL
, STT_FILE
), 0,
1047 SHN_ABS
, file
->filename
);
1049 /* define some often used types */
1050 int_type
.t
= VT_INT
;
1052 char_pointer_type
.t
= VT_BYTE
;
1053 mk_pointer(&char_pointer_type
);
1055 func_old_type
.t
= VT_FUNC
;
1056 func_old_type
.ref
= sym_push(SYM_FIELD
, &int_type
, FUNC_CDECL
, FUNC_OLD
);
1058 #if defined(TCC_ARM_EABI) && defined(TCC_ARM_VFP)
1059 float_type
.t
= VT_FLOAT
;
1060 double_type
.t
= VT_DOUBLE
;
1062 func_float_type
.t
= VT_FUNC
;
1063 func_float_type
.ref
= sym_push(SYM_FIELD
, &float_type
, FUNC_CDECL
, FUNC_OLD
);
1064 func_double_type
.t
= VT_FUNC
;
1065 func_double_type
.ref
= sym_push(SYM_FIELD
, &double_type
, FUNC_CDECL
, FUNC_OLD
);
1069 /* define 'void *alloca(unsigned int)' builtin function */
1074 sym
= sym_push(p
, mk_pointer(VT_VOID
), FUNC_CDECL
, FUNC_NEW
);
1075 s1
= sym_push(SYM_FIELD
, VT_UNSIGNED
| VT_INT
, 0, 0);
1078 sym_push(TOK_alloca
, VT_FUNC
| (p
<< VT_STRUCT_SHIFT
), VT_CONST
, 0);
1082 define_start
= define_stack
;
1085 if (setjmp(s1
->error_jmp_buf
) == 0) {
1087 s1
->error_set_jmp_enabled
= 1;
1089 ch
= file
->buf_ptr
[0];
1090 tok_flags
= TOK_FLAG_BOL
| TOK_FLAG_BOF
;
1091 parse_flags
= PARSE_FLAG_PREPROCESS
| PARSE_FLAG_TOK_NUM
;
1095 expect("declaration");
1097 /* end of translation unit info */
1099 put_stabs_r(NULL
, N_SO
, 0, 0,
1100 text_section
->data_offset
, text_section
, section_sym
);
1103 s1
->error_set_jmp_enabled
= 0;
1105 /* reset define stack, but leave -Dsymbols (may be incorrect if
1106 they are undefined) */
1107 free_defines(define_start
);
1109 gen_inline_functions();
1111 sym_pop(&global_stack
, NULL
);
1112 sym_pop(&local_stack
, NULL
);
1114 return s1
->nb_errors
!= 0 ? -1 : 0;
1117 int tcc_compile_string(TCCState
*s
, const char *str
)
1119 BufferedFile bf1
, *bf
= &bf1
;
1123 /* init file structure */
1125 /* XXX: avoid copying */
1127 buf
= tcc_malloc(len
+ 1);
1130 memcpy(buf
, str
, len
);
1133 bf
->buf_end
= buf
+ len
;
1134 pstrcpy(bf
->filename
, sizeof(bf
->filename
), "<string>");
1137 ret
= tcc_compile(s
);
1141 /* currently, no need to close */
1145 /* define a preprocessor symbol. A value can also be provided with the '=' operator */
1146 void tcc_define_symbol(TCCState
*s1
, const char *sym
, const char *value
)
1148 BufferedFile bf1
, *bf
= &bf1
;
1150 pstrcpy(bf
->buffer
, IO_BUF_SIZE
, sym
);
1151 pstrcat(bf
->buffer
, IO_BUF_SIZE
, " ");
1155 pstrcat(bf
->buffer
, IO_BUF_SIZE
, value
);
1157 /* init file structure */
1159 bf
->buf_ptr
= bf
->buffer
;
1160 bf
->buf_end
= bf
->buffer
+ strlen(bf
->buffer
);
1161 *bf
->buf_end
= CH_EOB
;
1162 bf
->filename
[0] = '\0';
1166 s1
->include_stack_ptr
= s1
->include_stack
;
1168 /* parse with define parser */
1169 ch
= file
->buf_ptr
[0];
1175 /* undefine a preprocessor symbol */
1176 void tcc_undefine_symbol(TCCState
*s1
, const char *sym
)
1180 ts
= tok_alloc(sym
, strlen(sym
));
1181 s
= define_find(ts
->tok
);
1182 /* undefine symbol by putting an invalid name */
1187 #ifdef CONFIG_TCC_ASM
1189 #ifdef TCC_TARGET_I386
1190 #include "i386-asm.c"
1195 static void asm_instr(void)
1197 error("inline asm() not supported");
1199 static void asm_global_instr(void)
1201 error("inline asm() not supported");
1207 #ifdef TCC_TARGET_COFF
1208 #include "tcccoff.c"
1211 #ifdef TCC_TARGET_PE
1215 #ifdef CONFIG_TCC_BACKTRACE
1216 /* print the position in the source file of PC value 'pc' by reading
1217 the stabs debug information */
1218 static void rt_printline(unsigned long wanted_pc
)
1220 Stab_Sym
*sym
, *sym_end
;
1221 char func_name
[128], last_func_name
[128];
1222 unsigned long func_addr
, last_pc
, pc
;
1223 const char *incl_files
[INCLUDE_STACK_SIZE
];
1224 int incl_index
, len
, last_line_num
, i
;
1225 const char *str
, *p
;
1227 fprintf(stderr
, "0x%08lx:", wanted_pc
);
1229 func_name
[0] = '\0';
1232 last_func_name
[0] = '\0';
1233 last_pc
= 0xffffffff;
1235 sym
= (Stab_Sym
*)stab_section
->data
+ 1;
1236 sym_end
= (Stab_Sym
*)(stab_section
->data
+ stab_section
->data_offset
);
1237 while (sym
< sym_end
) {
1238 switch(sym
->n_type
) {
1239 /* function start or end */
1241 if (sym
->n_strx
== 0) {
1242 /* we test if between last line and end of function */
1243 pc
= sym
->n_value
+ func_addr
;
1244 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
1246 func_name
[0] = '\0';
1249 str
= stabstr_section
->data
+ sym
->n_strx
;
1250 p
= strchr(str
, ':');
1252 pstrcpy(func_name
, sizeof(func_name
), str
);
1255 if (len
> sizeof(func_name
) - 1)
1256 len
= sizeof(func_name
) - 1;
1257 memcpy(func_name
, str
, len
);
1258 func_name
[len
] = '\0';
1260 func_addr
= sym
->n_value
;
1263 /* line number info */
1265 pc
= sym
->n_value
+ func_addr
;
1266 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
1269 last_line_num
= sym
->n_desc
;
1271 strcpy(last_func_name
, func_name
);
1275 str
= stabstr_section
->data
+ sym
->n_strx
;
1277 if (incl_index
< INCLUDE_STACK_SIZE
) {
1278 incl_files
[incl_index
++] = str
;
1286 if (sym
->n_strx
== 0) {
1287 incl_index
= 0; /* end of translation unit */
1289 str
= stabstr_section
->data
+ sym
->n_strx
;
1290 /* do not add path */
1292 if (len
> 0 && str
[len
- 1] != '/')
1300 /* second pass: we try symtab symbols (no line number info) */
1303 ElfW(Sym
) *sym
, *sym_end
;
1306 sym_end
= (ElfW(Sym
) *)(symtab_section
->data
+ symtab_section
->data_offset
);
1307 for(sym
= (ElfW(Sym
) *)symtab_section
->data
+ 1;
1310 type
= ELFW(ST_TYPE
)(sym
->st_info
);
1311 if (type
== STT_FUNC
) {
1312 if (wanted_pc
>= sym
->st_value
&&
1313 wanted_pc
< sym
->st_value
+ sym
->st_size
) {
1314 pstrcpy(last_func_name
, sizeof(last_func_name
),
1315 strtab_section
->data
+ sym
->st_name
);
1321 /* did not find any info: */
1322 fprintf(stderr
, " ???\n");
1325 if (last_func_name
[0] != '\0') {
1326 fprintf(stderr
, " %s()", last_func_name
);
1328 if (incl_index
> 0) {
1329 fprintf(stderr
, " (%s:%d",
1330 incl_files
[incl_index
- 1], last_line_num
);
1331 for(i
= incl_index
- 2; i
>= 0; i
--)
1332 fprintf(stderr
, ", included from %s", incl_files
[i
]);
1333 fprintf(stderr
, ")");
1335 fprintf(stderr
, "\n");
1339 /* fix for glibc 2.1 */
1345 /* return the PC at frame level 'level'. Return non zero if not found */
1346 static int rt_get_caller_pc(unsigned long *paddr
,
1347 ucontext_t
*uc
, int level
)
1353 #if defined(__FreeBSD__)
1354 *paddr
= uc
->uc_mcontext
.mc_eip
;
1355 #elif defined(__dietlibc__)
1356 *paddr
= uc
->uc_mcontext
.eip
;
1358 *paddr
= uc
->uc_mcontext
.gregs
[REG_EIP
];
1362 #if defined(__FreeBSD__)
1363 fp
= uc
->uc_mcontext
.mc_ebp
;
1364 #elif defined(__dietlibc__)
1365 fp
= uc
->uc_mcontext
.ebp
;
1367 fp
= uc
->uc_mcontext
.gregs
[REG_EBP
];
1369 for(i
=1;i
<level
;i
++) {
1370 /* XXX: check address validity with program info */
1371 if (fp
<= 0x1000 || fp
>= 0xc0000000)
1373 fp
= ((unsigned long *)fp
)[0];
1375 *paddr
= ((unsigned long *)fp
)[1];
1379 #elif defined(__x86_64__)
1380 /* return the PC at frame level 'level'. Return non zero if not found */
1381 static int rt_get_caller_pc(unsigned long *paddr
,
1382 ucontext_t
*uc
, int level
)
1388 /* XXX: only support linux */
1389 *paddr
= uc
->uc_mcontext
.gregs
[REG_RIP
];
1392 fp
= uc
->uc_mcontext
.gregs
[REG_RBP
];
1393 for(i
=1;i
<level
;i
++) {
1394 /* XXX: check address validity with program info */
1397 fp
= ((unsigned long *)fp
)[0];
1399 *paddr
= ((unsigned long *)fp
)[1];
1404 #warning add arch specific rt_get_caller_pc()
1405 static int rt_get_caller_pc(unsigned long *paddr
,
1406 ucontext_t
*uc
, int level
)
1412 /* emit a run time error at position 'pc' */
1413 void rt_error(ucontext_t
*uc
, const char *fmt
, ...)
1420 fprintf(stderr
, "Runtime error: ");
1421 vfprintf(stderr
, fmt
, ap
);
1422 fprintf(stderr
, "\n");
1423 for(i
=0;i
<num_callers
;i
++) {
1424 if (rt_get_caller_pc(&pc
, uc
, i
) < 0)
1427 fprintf(stderr
, "at ");
1429 fprintf(stderr
, "by ");
1436 /* signal handler for fatal errors */
1437 static void sig_error(int signum
, siginfo_t
*siginf
, void *puc
)
1439 ucontext_t
*uc
= puc
;
1443 switch(siginf
->si_code
) {
1446 rt_error(uc
, "division by zero");
1449 rt_error(uc
, "floating point exception");
1455 if (rt_bound_error_msg
&& *rt_bound_error_msg
)
1456 rt_error(uc
, *rt_bound_error_msg
);
1458 rt_error(uc
, "dereferencing invalid pointer");
1461 rt_error(uc
, "illegal instruction");
1464 rt_error(uc
, "abort() called");
1467 rt_error(uc
, "caught signal %d", signum
);
1475 /* copy code into memory passed in by the caller and do all relocations
1476 (needed before using tcc_get_symbol()).
1477 returns -1 on error and required size if ptr is NULL */
1478 int tcc_relocate(TCCState
*s1
, void *ptr
)
1481 unsigned long offset
, length
, mem
;
1484 if (0 == s1
->runtime_added
) {
1485 s1
->runtime_added
= 1;
1487 #ifdef TCC_TARGET_PE
1489 relocate_common_syms();
1490 tcc_add_linker_symbols(s1
);
1492 tcc_add_runtime(s1
);
1493 relocate_common_syms();
1494 tcc_add_linker_symbols(s1
);
1495 build_got_entries(s1
);
1499 offset
= 0, mem
= (unsigned long)ptr
;
1500 for(i
= 1; i
< s1
->nb_sections
; i
++) {
1501 s
= s1
->sections
[i
];
1502 if (0 == (s
->sh_flags
& SHF_ALLOC
))
1504 length
= s
->data_offset
;
1505 s
->sh_addr
= mem
? (mem
+ offset
+ 15) & ~15 : 0;
1506 offset
= (offset
+ length
+ 15) & ~15;
1509 /* relocate symbols */
1510 relocate_syms(s1
, 1);
1514 #ifdef TCC_TARGET_X86_64
1515 s1
->runtime_plt_and_got_offset
= 0;
1516 s1
->runtime_plt_and_got
= (char *)(mem
+ offset
);
1517 /* double the size of the buffer for got and plt entries
1518 XXX: calculate exact size for them? */
1525 /* relocate each section */
1526 for(i
= 1; i
< s1
->nb_sections
; i
++) {
1527 s
= s1
->sections
[i
];
1529 relocate_section(s1
, s
);
1532 for(i
= 1; i
< s1
->nb_sections
; i
++) {
1533 s
= s1
->sections
[i
];
1534 if (0 == (s
->sh_flags
& SHF_ALLOC
))
1536 length
= s
->data_offset
;
1537 // printf("%-12s %08x %04x\n", s->name, s->sh_addr, length);
1538 ptr
= (void*)s
->sh_addr
;
1539 if (NULL
== s
->data
|| s
->sh_type
== SHT_NOBITS
)
1540 memset(ptr
, 0, length
);
1542 memcpy(ptr
, s
->data
, length
);
1543 /* mark executable sections as executable in memory */
1544 if (s
->sh_flags
& SHF_EXECINSTR
)
1545 set_pages_executable(ptr
, length
);
1547 #ifdef TCC_TARGET_X86_64
1548 set_pages_executable(s1
->runtime_plt_and_got
,
1549 s1
->runtime_plt_and_got_offset
);
1554 /* launch the compiled program with the given arguments */
1555 int tcc_run(TCCState
*s1
, int argc
, char **argv
)
1557 int (*prog_main
)(int, char **);
1561 ret
= tcc_relocate(s1
, NULL
);
1564 ptr
= tcc_malloc(ret
);
1565 tcc_relocate(s1
, ptr
);
1567 prog_main
= tcc_get_symbol_err(s1
, "main");
1570 #ifdef CONFIG_TCC_BACKTRACE
1571 struct sigaction sigact
;
1572 /* install TCC signal handlers to print debug info on fatal
1574 sigact
.sa_flags
= SA_SIGINFO
| SA_RESETHAND
;
1575 sigact
.sa_sigaction
= sig_error
;
1576 sigemptyset(&sigact
.sa_mask
);
1577 sigaction(SIGFPE
, &sigact
, NULL
);
1578 sigaction(SIGILL
, &sigact
, NULL
);
1579 sigaction(SIGSEGV
, &sigact
, NULL
);
1580 sigaction(SIGBUS
, &sigact
, NULL
);
1581 sigaction(SIGABRT
, &sigact
, NULL
);
1583 error("debug mode not available");
1587 #ifdef CONFIG_TCC_BCHECK
1588 if (s1
->do_bounds_check
) {
1589 void (*bound_init
)(void);
1591 /* set error function */
1592 rt_bound_error_msg
= tcc_get_symbol_err(s1
, "__bound_error_msg");
1594 /* XXX: use .init section so that it also work in binary ? */
1595 bound_init
= (void *)tcc_get_symbol_err(s1
, "__bound_init");
1599 ret
= (*prog_main
)(argc
, argv
);
1604 void tcc_memstats(void)
1607 printf("memory in use: %d\n", mem_cur_size
);
1611 static void tcc_cleanup(void)
1615 if (NULL
== tcc_state
)
1619 /* free -D defines */
1623 n
= tok_ident
- TOK_IDENT
;
1624 for(i
= 0; i
< n
; i
++)
1625 tcc_free(table_ident
[i
]);
1626 tcc_free(table_ident
);
1628 /* free sym_pools */
1629 dynarray_reset(&sym_pools
, &nb_sym_pools
);
1631 cstr_free(&tokcstr
);
1632 /* reset symbol stack */
1633 sym_free_first
= NULL
;
1634 /* cleanup from error/setjmp */
1638 TCCState
*tcc_new(void)
1644 s
= tcc_mallocz(sizeof(TCCState
));
1648 s
->output_type
= TCC_OUTPUT_MEMORY
;
1649 s
->tcc_lib_path
= CONFIG_TCCDIR
;
1653 /* we add dummy defines for some special macros to speed up tests
1654 and to have working defined() */
1655 define_push(TOK___LINE__
, MACRO_OBJ
, NULL
, NULL
);
1656 define_push(TOK___FILE__
, MACRO_OBJ
, NULL
, NULL
);
1657 define_push(TOK___DATE__
, MACRO_OBJ
, NULL
, NULL
);
1658 define_push(TOK___TIME__
, MACRO_OBJ
, NULL
, NULL
);
1660 /* standard defines */
1661 tcc_define_symbol(s
, "__STDC__", NULL
);
1662 tcc_define_symbol(s
, "__STDC_VERSION__", "199901L");
1663 #if defined(TCC_TARGET_I386)
1664 tcc_define_symbol(s
, "__i386__", NULL
);
1666 #if defined(TCC_TARGET_X86_64)
1667 tcc_define_symbol(s
, "__x86_64__", NULL
);
1669 #if defined(TCC_TARGET_ARM)
1670 tcc_define_symbol(s
, "__ARM_ARCH_4__", NULL
);
1671 tcc_define_symbol(s
, "__arm_elf__", NULL
);
1672 tcc_define_symbol(s
, "__arm_elf", NULL
);
1673 tcc_define_symbol(s
, "arm_elf", NULL
);
1674 tcc_define_symbol(s
, "__arm__", NULL
);
1675 tcc_define_symbol(s
, "__arm", NULL
);
1676 tcc_define_symbol(s
, "arm", NULL
);
1677 tcc_define_symbol(s
, "__APCS_32__", NULL
);
1679 #ifdef TCC_TARGET_PE
1680 tcc_define_symbol(s
, "_WIN32", NULL
);
1682 tcc_define_symbol(s
, "__unix__", NULL
);
1683 tcc_define_symbol(s
, "__unix", NULL
);
1684 #if defined(__linux)
1685 tcc_define_symbol(s
, "__linux__", NULL
);
1686 tcc_define_symbol(s
, "__linux", NULL
);
1689 /* tiny C specific defines */
1690 tcc_define_symbol(s
, "__TINYC__", NULL
);
1692 /* tiny C & gcc defines */
1693 tcc_define_symbol(s
, "__SIZE_TYPE__", "unsigned int");
1694 tcc_define_symbol(s
, "__PTRDIFF_TYPE__", "int");
1695 #ifdef TCC_TARGET_PE
1696 tcc_define_symbol(s
, "__WCHAR_TYPE__", "unsigned short");
1698 tcc_define_symbol(s
, "__WCHAR_TYPE__", "int");
1701 #ifndef TCC_TARGET_PE
1702 /* default library paths */
1703 tcc_add_library_path(s
, CONFIG_SYSROOT
"/usr/local/lib");
1704 tcc_add_library_path(s
, CONFIG_SYSROOT
"/usr/lib");
1705 tcc_add_library_path(s
, CONFIG_SYSROOT
"/lib");
1708 /* no section zero */
1709 dynarray_add((void ***)&s
->sections
, &s
->nb_sections
, NULL
);
1711 /* create standard sections */
1712 text_section
= new_section(s
, ".text", SHT_PROGBITS
, SHF_ALLOC
| SHF_EXECINSTR
);
1713 data_section
= new_section(s
, ".data", SHT_PROGBITS
, SHF_ALLOC
| SHF_WRITE
);
1714 bss_section
= new_section(s
, ".bss", SHT_NOBITS
, SHF_ALLOC
| SHF_WRITE
);
1716 /* symbols are always generated for linking stage */
1717 symtab_section
= new_symtab(s
, ".symtab", SHT_SYMTAB
, 0,
1719 ".hashtab", SHF_PRIVATE
);
1720 strtab_section
= symtab_section
->link
;
1722 /* private symbol table for dynamic symbols */
1723 s
->dynsymtab_section
= new_symtab(s
, ".dynsymtab", SHT_SYMTAB
, SHF_PRIVATE
,
1725 ".dynhashtab", SHF_PRIVATE
);
1726 s
->alacarte_link
= 1;
1728 #ifdef CHAR_IS_UNSIGNED
1729 s
->char_is_unsigned
= 1;
1731 #if defined(TCC_TARGET_PE) && 0
1732 /* XXX: currently the PE linker is not ready to support that */
1733 s
->leading_underscore
= 1;
1738 void tcc_delete(TCCState
*s1
)
1744 /* free all sections */
1745 for(i
= 1; i
< s1
->nb_sections
; i
++)
1746 free_section(s1
->sections
[i
]);
1747 dynarray_reset(&s1
->sections
, &s1
->nb_sections
);
1749 for(i
= 0; i
< s1
->nb_priv_sections
; i
++)
1750 free_section(s1
->priv_sections
[i
]);
1751 dynarray_reset(&s1
->priv_sections
, &s1
->nb_priv_sections
);
1753 /* free any loaded DLLs */
1754 for ( i
= 0; i
< s1
->nb_loaded_dlls
; i
++) {
1755 DLLReference
*ref
= s1
->loaded_dlls
[i
];
1757 dlclose(ref
->handle
);
1760 /* free loaded dlls array */
1761 dynarray_reset(&s1
->loaded_dlls
, &s1
->nb_loaded_dlls
);
1763 /* free library paths */
1764 dynarray_reset(&s1
->library_paths
, &s1
->nb_library_paths
);
1766 /* free include paths */
1767 dynarray_reset(&s1
->cached_includes
, &s1
->nb_cached_includes
);
1768 dynarray_reset(&s1
->include_paths
, &s1
->nb_include_paths
);
1769 dynarray_reset(&s1
->sysinclude_paths
, &s1
->nb_sysinclude_paths
);
1774 int tcc_add_include_path(TCCState
*s1
, const char *pathname
)
1778 pathname1
= tcc_strdup(pathname
);
1779 dynarray_add((void ***)&s1
->include_paths
, &s1
->nb_include_paths
, pathname1
);
1783 int tcc_add_sysinclude_path(TCCState
*s1
, const char *pathname
)
1787 pathname1
= tcc_strdup(pathname
);
1788 dynarray_add((void ***)&s1
->sysinclude_paths
, &s1
->nb_sysinclude_paths
, pathname1
);
1792 static int tcc_add_file_internal(TCCState
*s1
, const char *filename
, int flags
)
1797 BufferedFile
*saved_file
;
1799 /* find source file type with extension */
1800 ext
= tcc_fileextension(filename
);
1806 file
= tcc_open(s1
, filename
);
1808 if (flags
& AFF_PRINT_ERROR
) {
1809 error_noabort("file '%s' not found", filename
);
1815 if (flags
& AFF_PREPROCESS
) {
1816 ret
= tcc_preprocess(s1
);
1817 } else if (!ext
[0] || !PATHCMP(ext
, "c")) {
1818 /* C file assumed */
1819 ret
= tcc_compile(s1
);
1821 #ifdef CONFIG_TCC_ASM
1822 if (!strcmp(ext
, "S")) {
1823 /* preprocessed assembler */
1824 ret
= tcc_assemble(s1
, 1);
1825 } else if (!strcmp(ext
, "s")) {
1826 /* non preprocessed assembler */
1827 ret
= tcc_assemble(s1
, 0);
1830 #ifdef TCC_TARGET_PE
1831 if (!PATHCMP(ext
, "def")) {
1832 ret
= pe_load_def_file(s1
, file
->fd
);
1837 /* assume executable format: auto guess file type */
1838 ret
= read(fd
, &ehdr
, sizeof(ehdr
));
1839 lseek(fd
, 0, SEEK_SET
);
1841 error_noabort("could not read header");
1843 } else if (ret
!= sizeof(ehdr
)) {
1844 goto try_load_script
;
1847 if (ehdr
.e_ident
[0] == ELFMAG0
&&
1848 ehdr
.e_ident
[1] == ELFMAG1
&&
1849 ehdr
.e_ident
[2] == ELFMAG2
&&
1850 ehdr
.e_ident
[3] == ELFMAG3
) {
1851 file
->line_num
= 0; /* do not display line number if error */
1852 if (ehdr
.e_type
== ET_REL
) {
1853 ret
= tcc_load_object_file(s1
, fd
, 0);
1854 } else if (ehdr
.e_type
== ET_DYN
) {
1855 if (s1
->output_type
== TCC_OUTPUT_MEMORY
) {
1856 #ifdef TCC_TARGET_PE
1860 h
= dlopen(filename
, RTLD_GLOBAL
| RTLD_LAZY
);
1867 ret
= tcc_load_dll(s1
, fd
, filename
,
1868 (flags
& AFF_REFERENCED_DLL
) != 0);
1871 error_noabort("unrecognized ELF file");
1874 } else if (memcmp((char *)&ehdr
, ARMAG
, 8) == 0) {
1875 file
->line_num
= 0; /* do not display line number if error */
1876 ret
= tcc_load_archive(s1
, fd
);
1878 #ifdef TCC_TARGET_COFF
1879 if (*(uint16_t *)(&ehdr
) == COFF_C67_MAGIC
) {
1880 ret
= tcc_load_coff(s1
, fd
);
1883 #ifdef TCC_TARGET_PE
1884 if (pe_test_res_file(&ehdr
, ret
)) {
1885 ret
= pe_load_res_file(s1
, fd
);
1889 /* as GNU ld, consider it is an ld script if not recognized */
1891 ret
= tcc_load_ldscript(s1
);
1893 error_noabort("unrecognized file type");
1908 int tcc_add_file(TCCState
*s
, const char *filename
)
1910 return tcc_add_file_internal(s
, filename
, AFF_PRINT_ERROR
);
1913 int tcc_add_library_path(TCCState
*s
, const char *pathname
)
1917 pathname1
= tcc_strdup(pathname
);
1918 dynarray_add((void ***)&s
->library_paths
, &s
->nb_library_paths
, pathname1
);
1922 /* find and load a dll. Return non zero if not found */
1923 /* XXX: add '-rpath' option support ? */
1924 static int tcc_add_dll(TCCState
*s
, const char *filename
, int flags
)
1929 for(i
= 0; i
< s
->nb_library_paths
; i
++) {
1930 snprintf(buf
, sizeof(buf
), "%s/%s",
1931 s
->library_paths
[i
], filename
);
1932 if (tcc_add_file_internal(s
, buf
, flags
) == 0)
1938 /* the library name is the same as the argument of the '-l' option */
1939 int tcc_add_library(TCCState
*s
, const char *libraryname
)
1944 /* first we look for the dynamic library if not static linking */
1945 if (!s
->static_link
) {
1946 #ifdef TCC_TARGET_PE
1947 snprintf(buf
, sizeof(buf
), "%s.def", libraryname
);
1949 snprintf(buf
, sizeof(buf
), "lib%s.so", libraryname
);
1951 if (tcc_add_dll(s
, buf
, 0) == 0)
1955 /* then we look for the static library */
1956 for(i
= 0; i
< s
->nb_library_paths
; i
++) {
1957 snprintf(buf
, sizeof(buf
), "%s/lib%s.a",
1958 s
->library_paths
[i
], libraryname
);
1959 if (tcc_add_file_internal(s
, buf
, 0) == 0)
1965 int tcc_add_symbol(TCCState
*s
, const char *name
, void *val
)
1967 add_elf_sym(symtab_section
, (unsigned long)val
, 0,
1968 ELFW(ST_INFO
)(STB_GLOBAL
, STT_NOTYPE
), 0,
1973 int tcc_set_output_type(TCCState
*s
, int output_type
)
1977 s
->output_type
= output_type
;
1980 /* default include paths */
1981 /* XXX: reverse order needed if -isystem support */
1982 #ifndef TCC_TARGET_PE
1983 tcc_add_sysinclude_path(s
, CONFIG_SYSROOT
"/usr/local/include");
1984 tcc_add_sysinclude_path(s
, CONFIG_SYSROOT
"/usr/include");
1986 snprintf(buf
, sizeof(buf
), "%s/include", s
->tcc_lib_path
);
1987 tcc_add_sysinclude_path(s
, buf
);
1988 #ifdef TCC_TARGET_PE
1989 snprintf(buf
, sizeof(buf
), "%s/include/winapi", s
->tcc_lib_path
);
1990 tcc_add_sysinclude_path(s
, buf
);
1994 /* if bound checking, then add corresponding sections */
1995 #ifdef CONFIG_TCC_BCHECK
1996 if (s
->do_bounds_check
) {
1998 tcc_define_symbol(s
, "__BOUNDS_CHECKING_ON", NULL
);
1999 /* create bounds sections */
2000 bounds_section
= new_section(s
, ".bounds",
2001 SHT_PROGBITS
, SHF_ALLOC
);
2002 lbounds_section
= new_section(s
, ".lbounds",
2003 SHT_PROGBITS
, SHF_ALLOC
);
2007 if (s
->char_is_unsigned
) {
2008 tcc_define_symbol(s
, "__CHAR_UNSIGNED__", NULL
);
2011 /* add debug sections */
2014 stab_section
= new_section(s
, ".stab", SHT_PROGBITS
, 0);
2015 stab_section
->sh_entsize
= sizeof(Stab_Sym
);
2016 stabstr_section
= new_section(s
, ".stabstr", SHT_STRTAB
, 0);
2017 put_elf_str(stabstr_section
, "");
2018 stab_section
->link
= stabstr_section
;
2019 /* put first entry */
2020 put_stabs("", 0, 0, 0, 0);
2023 /* add libc crt1/crti objects */
2024 #ifndef TCC_TARGET_PE
2025 if ((output_type
== TCC_OUTPUT_EXE
|| output_type
== TCC_OUTPUT_DLL
) &&
2027 if (output_type
!= TCC_OUTPUT_DLL
)
2028 tcc_add_file(s
, CONFIG_TCC_CRT_PREFIX
"/crt1.o");
2029 tcc_add_file(s
, CONFIG_TCC_CRT_PREFIX
"/crti.o");
2033 #ifdef TCC_TARGET_PE
2034 snprintf(buf
, sizeof(buf
), "%s/lib", s
->tcc_lib_path
);
2035 tcc_add_library_path(s
, buf
);
2041 #define WD_ALL 0x0001 /* warning is activated when using -Wall */
2042 #define FD_INVERT 0x0002 /* invert value before storing */
2044 typedef struct FlagDef
{
2050 static const FlagDef warning_defs
[] = {
2051 { offsetof(TCCState
, warn_unsupported
), 0, "unsupported" },
2052 { offsetof(TCCState
, warn_write_strings
), 0, "write-strings" },
2053 { offsetof(TCCState
, warn_error
), 0, "error" },
2054 { offsetof(TCCState
, warn_implicit_function_declaration
), WD_ALL
,
2055 "implicit-function-declaration" },
2058 static int set_flag(TCCState
*s
, const FlagDef
*flags
, int nb_flags
,
2059 const char *name
, int value
)
2066 if (r
[0] == 'n' && r
[1] == 'o' && r
[2] == '-') {
2070 for(i
= 0, p
= flags
; i
< nb_flags
; i
++, p
++) {
2071 if (!strcmp(r
, p
->name
))
2076 if (p
->flags
& FD_INVERT
)
2078 *(int *)((uint8_t *)s
+ p
->offset
) = value
;
2083 /* set/reset a warning */
2084 int tcc_set_warning(TCCState
*s
, const char *warning_name
, int value
)
2089 if (!strcmp(warning_name
, "all")) {
2090 for(i
= 0, p
= warning_defs
; i
< countof(warning_defs
); i
++, p
++) {
2091 if (p
->flags
& WD_ALL
)
2092 *(int *)((uint8_t *)s
+ p
->offset
) = 1;
2096 return set_flag(s
, warning_defs
, countof(warning_defs
),
2097 warning_name
, value
);
2101 static const FlagDef flag_defs
[] = {
2102 { offsetof(TCCState
, char_is_unsigned
), 0, "unsigned-char" },
2103 { offsetof(TCCState
, char_is_unsigned
), FD_INVERT
, "signed-char" },
2104 { offsetof(TCCState
, nocommon
), FD_INVERT
, "common" },
2105 { offsetof(TCCState
, leading_underscore
), 0, "leading-underscore" },
2108 /* set/reset a flag */
2109 int tcc_set_flag(TCCState
*s
, const char *flag_name
, int value
)
2111 return set_flag(s
, flag_defs
, countof(flag_defs
),
2115 /* set CONFIG_TCCDIR at runtime */
2116 void tcc_set_lib_path(TCCState
*s
, const char *path
)
2118 s
->tcc_lib_path
= tcc_strdup(path
);
2121 LIBTCCAPI
void print_stats(TCCState
*s
, int64_t total_time
)
2124 tt
= (double)total_time
/ 1000000.0;
2127 if (total_bytes
< 1)
2129 printf("%d idents, %d lines, %d bytes, %0.3f s, %d lines/s, %0.1f MB/s\n",
2130 tok_ident
- TOK_IDENT
, total_lines
, total_bytes
,
2131 tt
, (int)(total_lines
/ tt
),
2132 total_bytes
/ tt
/ 1000000.0);