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
24 static struct BufferedFile
*file
;
27 static CString tokcstr
; /* current parsed string, if any */
28 /* additional informations about token */
30 #define TOK_FLAG_BOL 0x0001 /* beginning of line before */
31 #define TOK_FLAG_BOF 0x0002 /* beginning of file before */
32 #define TOK_FLAG_ENDIF 0x0004 /* a endif was found matching starting #ifdef */
33 #define TOK_FLAG_EOF 0x0008 /* end of file */
35 static int *macro_ptr
, *macro_ptr_allocated
;
36 static int *unget_saved_macro_ptr
;
37 static int unget_saved_buffer
[TOK_MAX_SIZE
+ 1];
38 static int unget_buffer_enabled
;
39 static int parse_flags
;
40 #define PARSE_FLAG_PREPROCESS 0x0001 /* activate preprocessing */
41 #define PARSE_FLAG_TOK_NUM 0x0002 /* return numbers instead of TOK_PPNUM */
42 #define PARSE_FLAG_LINEFEED 0x0004 /* line feed is returned as a
43 token. line feed is also
45 #define PARSE_FLAG_ASM_COMMENTS 0x0008 /* '#' can be used for line comment */
46 #define PARSE_FLAG_SPACES 0x0010 /* next() returns space tokens (for -E) */
48 static Section
*text_section
, *data_section
, *bss_section
; /* predefined sections */
49 static Section
*cur_text_section
; /* current section where function code is
52 static Section
*last_text_section
; /* to handle .previous asm directive */
54 /* bound check related sections */
55 static Section
*bounds_section
; /* contains global data bound description */
56 static Section
*lbounds_section
; /* contains local data bound description */
58 static Section
*symtab_section
, *strtab_section
;
61 static Section
*stab_section
, *stabstr_section
;
63 /* loc : local variable index
64 ind : output code index
66 anon_sym: anonymous symbol index
68 static int rsym
, anon_sym
, ind
, loc
;
69 /* expression generation modifiers */
70 static int const_wanted
; /* true if constant wanted */
71 static int nocode_wanted
; /* true if no code generation wanted for an expression */
72 static int global_expr
; /* true if compound literals must be allocated
73 globally (used during initializers parsing */
74 static CType func_vt
; /* current function return type (used by return
77 static int last_line_num
, last_ind
, func_ind
; /* debug last line number and pc */
79 static TokenSym
**table_ident
;
80 static TokenSym
*hash_ident
[TOK_HASH_SIZE
];
81 static char token_buf
[STRING_MAX_SIZE
+ 1];
82 static char *funcname
;
83 static Sym
*global_stack
, *local_stack
;
84 static Sym
*define_stack
;
85 static Sym
*global_label_stack
, *local_label_stack
;
86 /* symbol allocator */
87 #define SYM_POOL_NB (8192 / sizeof(Sym))
88 static Sym
*sym_free_first
;
89 static void **sym_pools
;
90 static int nb_sym_pools
;
92 static SValue vstack
[VSTACK_SIZE
], *vtop
;
93 /* some predefined types */
94 static CType char_pointer_type
, func_old_type
, int_type
;
96 /* display some information during compilation */
97 static int verbose
= 0;
99 /* compile with debug symbol (and use them if error during execution) */
100 static int do_debug
= 0;
102 /* compile with built-in memory and bounds checker */
103 static int do_bounds_check
= 0;
105 /* display benchmark infos */
106 static int total_lines
;
107 static int total_bytes
;
109 /* use GNU C extensions */
110 static int gnu_ext
= 1;
112 /* use Tiny C extensions */
113 static int tcc_ext
= 1;
115 /* max number of callers shown if error */
116 #ifdef CONFIG_TCC_BACKTRACE
117 static int num_callers
= 6;
118 static const char **rt_bound_error_msg
;
121 /* XXX: get rid of this ASAP */
122 static struct TCCState
*tcc_state
;
124 /* give the path of the tcc libraries */
125 static const char *tcc_lib_path
= CONFIG_TCCDIR
;
128 #ifdef TCC_TARGET_I386
129 #include "i386-gen.c"
132 #ifdef TCC_TARGET_ARM
136 #ifdef TCC_TARGET_C67
140 #ifdef TCC_TARGET_X86_64
141 #include "x86_64-gen.c"
144 #ifdef CONFIG_TCC_STATIC
146 #define RTLD_LAZY 0x001
147 #define RTLD_NOW 0x002
148 #define RTLD_GLOBAL 0x100
149 #define RTLD_DEFAULT NULL
151 /* dummy function for profiling */
152 void *dlopen(const char *filename
, int flag
)
157 void dlclose(void *p
)
161 const char *dlerror(void)
166 typedef struct TCCSyms
{
171 #define TCCSYM(a) { #a, &a, },
173 /* add the symbol you want here if no dynamic linking is done */
174 static TCCSyms tcc_syms
[] = {
175 #if !defined(CONFIG_TCCBOOT)
184 void *resolve_sym(TCCState
*s1
, const char *symbol
, int type
)
188 while (p
->str
!= NULL
) {
189 if (!strcmp(p
->str
, symbol
))
196 #elif !defined(_WIN32)
200 void *resolve_sym(TCCState
*s1
, const char *sym
, int type
)
202 return dlsym(RTLD_DEFAULT
, sym
);
207 /********************************************************/
209 /* we use our own 'finite' function to avoid potential problems with
210 non standard math libs */
211 /* XXX: endianness dependent */
212 int ieee_finite(double d
)
215 return ((unsigned)((p
[1] | 0x800fffff) + 1)) >> 31;
218 /* copy a string and truncate it. */
219 static char *pstrcpy(char *buf
, int buf_size
, const char *s
)
226 q_end
= buf
+ buf_size
- 1;
238 /* strcat and truncate. */
239 static char *pstrcat(char *buf
, int buf_size
, const char *s
)
244 pstrcpy(buf
+ len
, buf_size
- len
, s
);
248 /* extract the basename of a file */
249 static char *tcc_basename(const char *name
)
251 char *p
= strchr(name
, 0);
252 while (p
> name
&& !IS_PATHSEP(p
[-1]))
257 static char *tcc_fileextension (const char *name
)
259 char *b
= tcc_basename(name
);
260 char *e
= strrchr(b
, '.');
261 return e
? e
: strchr(b
, 0);
265 char *normalize_slashes(char *path
)
268 for (p
= path
; *p
; ++p
)
274 void tcc_set_lib_path_w32(TCCState
*s
)
276 /* on win32, we suppose the lib and includes are at the location
279 GetModuleFileNameA(NULL
, path
, sizeof path
);
280 p
= tcc_basename(normalize_slashes(strlwr(path
)));
281 if (p
- 5 > path
&& 0 == strncmp(p
- 5, "/bin/", 5))
286 tcc_set_lib_path(s
, path
);
290 void set_pages_executable(void *ptr
, unsigned long length
)
293 unsigned long old_protect
;
294 VirtualProtect(ptr
, length
, PAGE_EXECUTE_READWRITE
, &old_protect
);
296 unsigned long start
, end
;
297 start
= (unsigned long)ptr
& ~(PAGESIZE
- 1);
298 end
= (unsigned long)ptr
+ length
;
299 end
= (end
+ PAGESIZE
- 1) & ~(PAGESIZE
- 1);
300 mprotect((void *)start
, end
- start
, PROT_READ
| PROT_WRITE
| PROT_EXEC
);
304 /* memory management */
308 unsigned malloc_usable_size(void*);
311 static inline void tcc_free(void *ptr
)
314 mem_cur_size
-= malloc_usable_size(ptr
);
319 static void *tcc_malloc(unsigned long size
)
324 error("memory full");
326 mem_cur_size
+= malloc_usable_size(ptr
);
327 if (mem_cur_size
> mem_max_size
)
328 mem_max_size
= mem_cur_size
;
333 static void *tcc_mallocz(unsigned long size
)
336 ptr
= tcc_malloc(size
);
337 memset(ptr
, 0, size
);
341 static inline void *tcc_realloc(void *ptr
, unsigned long size
)
345 mem_cur_size
-= malloc_usable_size(ptr
);
347 ptr1
= realloc(ptr
, size
);
349 /* NOTE: count not correct if alloc error, but not critical */
350 mem_cur_size
+= malloc_usable_size(ptr1
);
351 if (mem_cur_size
> mem_max_size
)
352 mem_max_size
= mem_cur_size
;
357 static char *tcc_strdup(const char *str
)
360 ptr
= tcc_malloc(strlen(str
) + 1);
365 #define free(p) use_tcc_free(p)
366 #define malloc(s) use_tcc_malloc(s)
367 #define realloc(p, s) use_tcc_realloc(p, s)
369 static void dynarray_add(void ***ptab
, int *nb_ptr
, void *data
)
376 /* every power of two we double array size */
377 if ((nb
& (nb
- 1)) == 0) {
382 pp
= tcc_realloc(pp
, nb_alloc
* sizeof(void *));
384 error("memory full");
391 static void dynarray_reset(void *pp
, int *n
)
394 for (p
= *(void***)pp
; *n
; ++p
, --*n
)
397 tcc_free(*(void**)pp
);
401 /* symbol allocator */
402 static Sym
*__sym_malloc(void)
404 Sym
*sym_pool
, *sym
, *last_sym
;
407 sym_pool
= tcc_malloc(SYM_POOL_NB
* sizeof(Sym
));
408 dynarray_add(&sym_pools
, &nb_sym_pools
, sym_pool
);
410 last_sym
= sym_free_first
;
412 for(i
= 0; i
< SYM_POOL_NB
; i
++) {
413 sym
->next
= last_sym
;
417 sym_free_first
= last_sym
;
421 static inline Sym
*sym_malloc(void)
424 sym
= sym_free_first
;
426 sym
= __sym_malloc();
427 sym_free_first
= sym
->next
;
431 static inline void sym_free(Sym
*sym
)
433 sym
->next
= sym_free_first
;
434 sym_free_first
= sym
;
437 Section
*new_section(TCCState
*s1
, const char *name
, int sh_type
, int sh_flags
)
441 sec
= tcc_mallocz(sizeof(Section
) + strlen(name
));
442 strcpy(sec
->name
, name
);
443 sec
->sh_type
= sh_type
;
444 sec
->sh_flags
= sh_flags
;
452 sec
->sh_addralign
= 4;
455 sec
->sh_addralign
= 1;
458 sec
->sh_addralign
= 32; /* default conservative alignment */
462 if (sh_flags
& SHF_PRIVATE
) {
463 dynarray_add((void ***)&s1
->priv_sections
, &s1
->nb_priv_sections
, sec
);
465 sec
->sh_num
= s1
->nb_sections
;
466 dynarray_add((void ***)&s1
->sections
, &s1
->nb_sections
, sec
);
472 static void free_section(Section
*s
)
477 /* realloc section and set its content to zero */
478 static void section_realloc(Section
*sec
, unsigned long new_size
)
483 size
= sec
->data_allocated
;
486 while (size
< new_size
)
488 data
= tcc_realloc(sec
->data
, size
);
490 error("memory full");
491 memset(data
+ sec
->data_allocated
, 0, size
- sec
->data_allocated
);
493 sec
->data_allocated
= size
;
496 /* reserve at least 'size' bytes in section 'sec' from
498 static void *section_ptr_add(Section
*sec
, unsigned long size
)
500 unsigned long offset
, offset1
;
502 offset
= sec
->data_offset
;
503 offset1
= offset
+ size
;
504 if (offset1
> sec
->data_allocated
)
505 section_realloc(sec
, offset1
);
506 sec
->data_offset
= offset1
;
507 return sec
->data
+ offset
;
510 /* return a reference to a section, and create it if it does not
512 Section
*find_section(TCCState
*s1
, const char *name
)
516 for(i
= 1; i
< s1
->nb_sections
; i
++) {
517 sec
= s1
->sections
[i
];
518 if (!strcmp(name
, sec
->name
))
521 /* sections are created as PROGBITS */
522 return new_section(s1
, name
, SHT_PROGBITS
, SHF_ALLOC
);
525 /* update sym->c so that it points to an external symbol in section
526 'section' with value 'value' */
527 static void put_extern_sym2(Sym
*sym
, Section
*section
,
528 unsigned long value
, unsigned long size
,
529 int can_add_underscore
)
531 int sym_type
, sym_bind
, sh_num
, info
, other
, attr
;
538 else if (section
== SECTION_ABS
)
541 sh_num
= section
->sh_num
;
545 if ((sym
->type
.t
& VT_BTYPE
) == VT_FUNC
) {
549 attr
= sym
->type
.ref
->r
;
550 if (FUNC_EXPORT(attr
))
552 if (FUNC_CALL(attr
) == FUNC_STDCALL
)
556 sym_type
= STT_OBJECT
;
559 if (sym
->type
.t
& VT_STATIC
)
560 sym_bind
= STB_LOCAL
;
562 sym_bind
= STB_GLOBAL
;
565 name
= get_tok_str(sym
->v
, NULL
);
566 #ifdef CONFIG_TCC_BCHECK
567 if (do_bounds_check
) {
570 /* XXX: avoid doing that for statics ? */
571 /* if bound checking is activated, we change some function
572 names by adding the "__bound" prefix */
575 /* XXX: we rely only on malloc hooks */
588 strcpy(buf
, "__bound_");
597 if ((other
& 2) && can_add_underscore
) {
598 sprintf(buf1
, "_%s@%d", name
, FUNC_ARGS(attr
));
602 if (tcc_state
->leading_underscore
&& can_add_underscore
) {
604 pstrcpy(buf1
+ 1, sizeof(buf1
) - 1, name
);
607 info
= ELFW(ST_INFO
)(sym_bind
, sym_type
);
608 sym
->c
= add_elf_sym(symtab_section
, value
, size
, info
, other
, sh_num
, name
);
610 esym
= &((ElfW(Sym
) *)symtab_section
->data
)[sym
->c
];
611 esym
->st_value
= value
;
612 esym
->st_size
= size
;
613 esym
->st_shndx
= sh_num
;
614 esym
->st_other
|= other
;
618 static void put_extern_sym(Sym
*sym
, Section
*section
,
619 unsigned long value
, unsigned long size
)
621 put_extern_sym2(sym
, section
, value
, size
, 1);
624 /* add a new relocation entry to symbol 'sym' in section 's' */
625 static void greloc(Section
*s
, Sym
*sym
, unsigned long offset
, int type
)
628 put_extern_sym(sym
, NULL
, 0, 0);
629 /* now we can add ELF relocation info */
630 put_elf_reloc(symtab_section
, s
, offset
, type
, sym
->c
);
633 static inline int isid(int c
)
635 return (c
>= 'a' && c
<= 'z') ||
636 (c
>= 'A' && c
<= 'Z') ||
640 static inline int isnum(int c
)
642 return c
>= '0' && c
<= '9';
645 static inline int isoct(int c
)
647 return c
>= '0' && c
<= '7';
650 static inline int toup(int c
)
652 if (c
>= 'a' && c
<= 'z')
653 return c
- 'a' + 'A';
658 static void strcat_vprintf(char *buf
, int buf_size
, const char *fmt
, va_list ap
)
662 vsnprintf(buf
+ len
, buf_size
- len
, fmt
, ap
);
665 static void strcat_printf(char *buf
, int buf_size
, const char *fmt
, ...)
669 strcat_vprintf(buf
, buf_size
, fmt
, ap
);
673 void error1(TCCState
*s1
, int is_warning
, const char *fmt
, va_list ap
)
680 for(f
= s1
->include_stack
; f
< s1
->include_stack_ptr
; f
++)
681 strcat_printf(buf
, sizeof(buf
), "In file included from %s:%d:\n",
682 (*f
)->filename
, (*f
)->line_num
);
683 if (file
->line_num
> 0) {
684 strcat_printf(buf
, sizeof(buf
),
685 "%s:%d: ", file
->filename
, file
->line_num
);
687 strcat_printf(buf
, sizeof(buf
),
688 "%s: ", file
->filename
);
691 strcat_printf(buf
, sizeof(buf
),
695 strcat_printf(buf
, sizeof(buf
), "warning: ");
696 strcat_vprintf(buf
, sizeof(buf
), fmt
, ap
);
698 if (!s1
->error_func
) {
699 /* default case: stderr */
700 fprintf(stderr
, "%s\n", buf
);
702 s1
->error_func(s1
->error_opaque
, buf
);
704 if (!is_warning
|| s1
->warn_error
)
708 void tcc_set_error_func(TCCState
*s
, void *error_opaque
,
709 void (*error_func
)(void *opaque
, const char *msg
))
711 s
->error_opaque
= error_opaque
;
712 s
->error_func
= error_func
;
715 /* error without aborting current compilation */
716 void error_noabort(const char *fmt
, ...)
718 TCCState
*s1
= tcc_state
;
722 error1(s1
, 0, fmt
, ap
);
726 void error(const char *fmt
, ...)
728 TCCState
*s1
= tcc_state
;
732 error1(s1
, 0, fmt
, ap
);
734 /* better than nothing: in some cases, we accept to handle errors */
735 if (s1
->error_set_jmp_enabled
) {
736 longjmp(s1
->error_jmp_buf
, 1);
738 /* XXX: eliminate this someday */
743 void expect(const char *msg
)
745 error("%s expected", msg
);
748 void warning(const char *fmt
, ...)
750 TCCState
*s1
= tcc_state
;
757 error1(s1
, 1, fmt
, ap
);
764 error("'%c' expected", c
);
768 static void test_lvalue(void)
770 if (!(vtop
->r
& VT_LVAL
))
774 /* CString handling */
776 static void cstr_realloc(CString
*cstr
, int new_size
)
781 size
= cstr
->size_allocated
;
783 size
= 8; /* no need to allocate a too small first string */
784 while (size
< new_size
)
786 data
= tcc_realloc(cstr
->data_allocated
, size
);
788 error("memory full");
789 cstr
->data_allocated
= data
;
790 cstr
->size_allocated
= size
;
795 static inline void cstr_ccat(CString
*cstr
, int ch
)
798 size
= cstr
->size
+ 1;
799 if (size
> cstr
->size_allocated
)
800 cstr_realloc(cstr
, size
);
801 ((unsigned char *)cstr
->data
)[size
- 1] = ch
;
805 static void cstr_cat(CString
*cstr
, const char *str
)
817 /* add a wide char */
818 static void cstr_wccat(CString
*cstr
, int ch
)
821 size
= cstr
->size
+ sizeof(nwchar_t
);
822 if (size
> cstr
->size_allocated
)
823 cstr_realloc(cstr
, size
);
824 *(nwchar_t
*)(((unsigned char *)cstr
->data
) + size
- sizeof(nwchar_t
)) = ch
;
828 static void cstr_new(CString
*cstr
)
830 memset(cstr
, 0, sizeof(CString
));
833 /* free string and reset it to NULL */
834 static void cstr_free(CString
*cstr
)
836 tcc_free(cstr
->data_allocated
);
840 #define cstr_reset(cstr) cstr_free(cstr)
843 static void add_char(CString
*cstr
, int c
)
845 if (c
== '\'' || c
== '\"' || c
== '\\') {
846 /* XXX: could be more precise if char or string */
847 cstr_ccat(cstr
, '\\');
849 if (c
>= 32 && c
<= 126) {
852 cstr_ccat(cstr
, '\\');
854 cstr_ccat(cstr
, 'n');
856 cstr_ccat(cstr
, '0' + ((c
>> 6) & 7));
857 cstr_ccat(cstr
, '0' + ((c
>> 3) & 7));
858 cstr_ccat(cstr
, '0' + (c
& 7));
863 /* push, without hashing */
864 static Sym
*sym_push2(Sym
**ps
, int v
, int t
, long c
)
878 /* find a symbol and return its associated structure. 's' is the top
879 of the symbol stack */
880 static Sym
*sym_find2(Sym
*s
, int v
)
890 /* structure lookup */
891 static inline Sym
*struct_find(int v
)
894 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
896 return table_ident
[v
]->sym_struct
;
899 /* find an identifier */
900 static inline Sym
*sym_find(int v
)
903 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
905 return table_ident
[v
]->sym_identifier
;
908 /* push a given symbol on the symbol stack */
909 static Sym
*sym_push(int v
, CType
*type
, int r
, int c
)
918 s
= sym_push2(ps
, v
, type
->t
, c
);
919 s
->type
.ref
= type
->ref
;
921 /* don't record fields or anonymous symbols */
923 if (!(v
& SYM_FIELD
) && (v
& ~SYM_STRUCT
) < SYM_FIRST_ANOM
) {
924 /* record symbol in token array */
925 ts
= table_ident
[(v
& ~SYM_STRUCT
) - TOK_IDENT
];
927 ps
= &ts
->sym_struct
;
929 ps
= &ts
->sym_identifier
;
936 /* push a global identifier */
937 static Sym
*global_identifier_push(int v
, int t
, int c
)
940 s
= sym_push2(&global_stack
, v
, t
, c
);
941 /* don't record anonymous symbol */
942 if (v
< SYM_FIRST_ANOM
) {
943 ps
= &table_ident
[v
- TOK_IDENT
]->sym_identifier
;
944 /* modify the top most local identifier, so that
945 sym_identifier will point to 's' when popped */
947 ps
= &(*ps
)->prev_tok
;
954 /* pop symbols until top reaches 'b' */
955 static void sym_pop(Sym
**ptop
, Sym
*b
)
965 /* remove symbol in token array */
967 if (!(v
& SYM_FIELD
) && (v
& ~SYM_STRUCT
) < SYM_FIRST_ANOM
) {
968 ts
= table_ident
[(v
& ~SYM_STRUCT
) - TOK_IDENT
];
970 ps
= &ts
->sym_struct
;
972 ps
= &ts
->sym_identifier
;
983 BufferedFile
*tcc_open(TCCState
*s1
, const char *filename
)
988 if (strcmp(filename
, "-") == 0)
989 fd
= 0, filename
= "stdin";
991 fd
= open(filename
, O_RDONLY
| O_BINARY
);
992 if ((verbose
== 2 && fd
>= 0) || verbose
== 3)
993 printf("%s %*s%s\n", fd
< 0 ? "nf":"->",
994 (s1
->include_stack_ptr
- s1
->include_stack
), "", filename
);
997 bf
= tcc_malloc(sizeof(BufferedFile
));
999 bf
->buf_ptr
= bf
->buffer
;
1000 bf
->buf_end
= bf
->buffer
;
1001 bf
->buffer
[0] = CH_EOB
; /* put eob symbol */
1002 pstrcpy(bf
->filename
, sizeof(bf
->filename
), filename
);
1004 normalize_slashes(bf
->filename
);
1007 bf
->ifndef_macro
= 0;
1008 bf
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
1009 // printf("opening '%s'\n", filename);
1013 void tcc_close(BufferedFile
*bf
)
1015 total_lines
+= bf
->line_num
;
1024 /* compile the C file opened in 'file'. Return non zero if errors. */
1025 static int tcc_compile(TCCState
*s1
)
1029 volatile int section_sym
;
1032 printf("%s: **** new file\n", file
->filename
);
1034 preprocess_init(s1
);
1036 cur_text_section
= NULL
;
1038 anon_sym
= SYM_FIRST_ANOM
;
1040 /* file info: full path + filename */
1041 section_sym
= 0; /* avoid warning */
1043 section_sym
= put_elf_sym(symtab_section
, 0, 0,
1044 ELFW(ST_INFO
)(STB_LOCAL
, STT_SECTION
), 0,
1045 text_section
->sh_num
, NULL
);
1046 getcwd(buf
, sizeof(buf
));
1048 normalize_slashes(buf
);
1050 pstrcat(buf
, sizeof(buf
), "/");
1051 put_stabs_r(buf
, N_SO
, 0, 0,
1052 text_section
->data_offset
, text_section
, section_sym
);
1053 put_stabs_r(file
->filename
, N_SO
, 0, 0,
1054 text_section
->data_offset
, text_section
, section_sym
);
1056 /* an elf symbol of type STT_FILE must be put so that STB_LOCAL
1057 symbols can be safely used */
1058 put_elf_sym(symtab_section
, 0, 0,
1059 ELFW(ST_INFO
)(STB_LOCAL
, STT_FILE
), 0,
1060 SHN_ABS
, file
->filename
);
1062 /* define some often used types */
1063 int_type
.t
= VT_INT
;
1065 char_pointer_type
.t
= VT_BYTE
;
1066 mk_pointer(&char_pointer_type
);
1068 func_old_type
.t
= VT_FUNC
;
1069 func_old_type
.ref
= sym_push(SYM_FIELD
, &int_type
, FUNC_CDECL
, FUNC_OLD
);
1071 #if defined(TCC_ARM_EABI) && defined(TCC_ARM_VFP)
1072 float_type
.t
= VT_FLOAT
;
1073 double_type
.t
= VT_DOUBLE
;
1075 func_float_type
.t
= VT_FUNC
;
1076 func_float_type
.ref
= sym_push(SYM_FIELD
, &float_type
, FUNC_CDECL
, FUNC_OLD
);
1077 func_double_type
.t
= VT_FUNC
;
1078 func_double_type
.ref
= sym_push(SYM_FIELD
, &double_type
, FUNC_CDECL
, FUNC_OLD
);
1082 /* define 'void *alloca(unsigned int)' builtin function */
1087 sym
= sym_push(p
, mk_pointer(VT_VOID
), FUNC_CDECL
, FUNC_NEW
);
1088 s1
= sym_push(SYM_FIELD
, VT_UNSIGNED
| VT_INT
, 0, 0);
1091 sym_push(TOK_alloca
, VT_FUNC
| (p
<< VT_STRUCT_SHIFT
), VT_CONST
, 0);
1095 define_start
= define_stack
;
1098 if (setjmp(s1
->error_jmp_buf
) == 0) {
1100 s1
->error_set_jmp_enabled
= 1;
1102 ch
= file
->buf_ptr
[0];
1103 tok_flags
= TOK_FLAG_BOL
| TOK_FLAG_BOF
;
1104 parse_flags
= PARSE_FLAG_PREPROCESS
| PARSE_FLAG_TOK_NUM
;
1108 expect("declaration");
1110 /* end of translation unit info */
1112 put_stabs_r(NULL
, N_SO
, 0, 0,
1113 text_section
->data_offset
, text_section
, section_sym
);
1116 s1
->error_set_jmp_enabled
= 0;
1118 /* reset define stack, but leave -Dsymbols (may be incorrect if
1119 they are undefined) */
1120 free_defines(define_start
);
1122 gen_inline_functions();
1124 sym_pop(&global_stack
, NULL
);
1125 sym_pop(&local_stack
, NULL
);
1127 return s1
->nb_errors
!= 0 ? -1 : 0;
1130 int tcc_compile_string(TCCState
*s
, const char *str
)
1132 BufferedFile bf1
, *bf
= &bf1
;
1136 /* init file structure */
1138 /* XXX: avoid copying */
1140 buf
= tcc_malloc(len
+ 1);
1143 memcpy(buf
, str
, len
);
1146 bf
->buf_end
= buf
+ len
;
1147 pstrcpy(bf
->filename
, sizeof(bf
->filename
), "<string>");
1150 ret
= tcc_compile(s
);
1154 /* currently, no need to close */
1158 /* define a preprocessor symbol. A value can also be provided with the '=' operator */
1159 void tcc_define_symbol(TCCState
*s1
, const char *sym
, const char *value
)
1161 BufferedFile bf1
, *bf
= &bf1
;
1163 pstrcpy(bf
->buffer
, IO_BUF_SIZE
, sym
);
1164 pstrcat(bf
->buffer
, IO_BUF_SIZE
, " ");
1168 pstrcat(bf
->buffer
, IO_BUF_SIZE
, value
);
1170 /* init file structure */
1172 bf
->buf_ptr
= bf
->buffer
;
1173 bf
->buf_end
= bf
->buffer
+ strlen(bf
->buffer
);
1174 *bf
->buf_end
= CH_EOB
;
1175 bf
->filename
[0] = '\0';
1179 s1
->include_stack_ptr
= s1
->include_stack
;
1181 /* parse with define parser */
1182 ch
= file
->buf_ptr
[0];
1188 /* undefine a preprocessor symbol */
1189 void tcc_undefine_symbol(TCCState
*s1
, const char *sym
)
1193 ts
= tok_alloc(sym
, strlen(sym
));
1194 s
= define_find(ts
->tok
);
1195 /* undefine symbol by putting an invalid name */
1200 #ifdef CONFIG_TCC_ASM
1202 #ifdef TCC_TARGET_I386
1203 #include "i386-asm.c"
1208 static void asm_instr(void)
1210 error("inline asm() not supported");
1212 static void asm_global_instr(void)
1214 error("inline asm() not supported");
1220 #ifdef TCC_TARGET_COFF
1221 #include "tcccoff.c"
1224 #ifdef TCC_TARGET_PE
1228 #ifdef CONFIG_TCC_BACKTRACE
1229 /* print the position in the source file of PC value 'pc' by reading
1230 the stabs debug information */
1231 static void rt_printline(unsigned long wanted_pc
)
1233 Stab_Sym
*sym
, *sym_end
;
1234 char func_name
[128], last_func_name
[128];
1235 unsigned long func_addr
, last_pc
, pc
;
1236 const char *incl_files
[INCLUDE_STACK_SIZE
];
1237 int incl_index
, len
, last_line_num
, i
;
1238 const char *str
, *p
;
1240 fprintf(stderr
, "0x%08lx:", wanted_pc
);
1242 func_name
[0] = '\0';
1245 last_func_name
[0] = '\0';
1246 last_pc
= 0xffffffff;
1248 sym
= (Stab_Sym
*)stab_section
->data
+ 1;
1249 sym_end
= (Stab_Sym
*)(stab_section
->data
+ stab_section
->data_offset
);
1250 while (sym
< sym_end
) {
1251 switch(sym
->n_type
) {
1252 /* function start or end */
1254 if (sym
->n_strx
== 0) {
1255 /* we test if between last line and end of function */
1256 pc
= sym
->n_value
+ func_addr
;
1257 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
1259 func_name
[0] = '\0';
1262 str
= stabstr_section
->data
+ sym
->n_strx
;
1263 p
= strchr(str
, ':');
1265 pstrcpy(func_name
, sizeof(func_name
), str
);
1268 if (len
> sizeof(func_name
) - 1)
1269 len
= sizeof(func_name
) - 1;
1270 memcpy(func_name
, str
, len
);
1271 func_name
[len
] = '\0';
1273 func_addr
= sym
->n_value
;
1276 /* line number info */
1278 pc
= sym
->n_value
+ func_addr
;
1279 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
1282 last_line_num
= sym
->n_desc
;
1284 strcpy(last_func_name
, func_name
);
1288 str
= stabstr_section
->data
+ sym
->n_strx
;
1290 if (incl_index
< INCLUDE_STACK_SIZE
) {
1291 incl_files
[incl_index
++] = str
;
1299 if (sym
->n_strx
== 0) {
1300 incl_index
= 0; /* end of translation unit */
1302 str
= stabstr_section
->data
+ sym
->n_strx
;
1303 /* do not add path */
1305 if (len
> 0 && str
[len
- 1] != '/')
1313 /* second pass: we try symtab symbols (no line number info) */
1316 ElfW(Sym
) *sym
, *sym_end
;
1319 sym_end
= (ElfW(Sym
) *)(symtab_section
->data
+ symtab_section
->data_offset
);
1320 for(sym
= (ElfW(Sym
) *)symtab_section
->data
+ 1;
1323 type
= ELFW(ST_TYPE
)(sym
->st_info
);
1324 if (type
== STT_FUNC
) {
1325 if (wanted_pc
>= sym
->st_value
&&
1326 wanted_pc
< sym
->st_value
+ sym
->st_size
) {
1327 pstrcpy(last_func_name
, sizeof(last_func_name
),
1328 strtab_section
->data
+ sym
->st_name
);
1334 /* did not find any info: */
1335 fprintf(stderr
, " ???\n");
1338 if (last_func_name
[0] != '\0') {
1339 fprintf(stderr
, " %s()", last_func_name
);
1341 if (incl_index
> 0) {
1342 fprintf(stderr
, " (%s:%d",
1343 incl_files
[incl_index
- 1], last_line_num
);
1344 for(i
= incl_index
- 2; i
>= 0; i
--)
1345 fprintf(stderr
, ", included from %s", incl_files
[i
]);
1346 fprintf(stderr
, ")");
1348 fprintf(stderr
, "\n");
1352 /* fix for glibc 2.1 */
1358 /* return the PC at frame level 'level'. Return non zero if not found */
1359 static int rt_get_caller_pc(unsigned long *paddr
,
1360 ucontext_t
*uc
, int level
)
1366 #if defined(__FreeBSD__)
1367 *paddr
= uc
->uc_mcontext
.mc_eip
;
1368 #elif defined(__dietlibc__)
1369 *paddr
= uc
->uc_mcontext
.eip
;
1371 *paddr
= uc
->uc_mcontext
.gregs
[REG_EIP
];
1375 #if defined(__FreeBSD__)
1376 fp
= uc
->uc_mcontext
.mc_ebp
;
1377 #elif defined(__dietlibc__)
1378 fp
= uc
->uc_mcontext
.ebp
;
1380 fp
= uc
->uc_mcontext
.gregs
[REG_EBP
];
1382 for(i
=1;i
<level
;i
++) {
1383 /* XXX: check address validity with program info */
1384 if (fp
<= 0x1000 || fp
>= 0xc0000000)
1386 fp
= ((unsigned long *)fp
)[0];
1388 *paddr
= ((unsigned long *)fp
)[1];
1392 #elif defined(__x86_64__)
1393 /* return the PC at frame level 'level'. Return non zero if not found */
1394 static int rt_get_caller_pc(unsigned long *paddr
,
1395 ucontext_t
*uc
, int level
)
1401 /* XXX: only support linux */
1402 *paddr
= uc
->uc_mcontext
.gregs
[REG_RIP
];
1405 fp
= uc
->uc_mcontext
.gregs
[REG_RBP
];
1406 for(i
=1;i
<level
;i
++) {
1407 /* XXX: check address validity with program info */
1410 fp
= ((unsigned long *)fp
)[0];
1412 *paddr
= ((unsigned long *)fp
)[1];
1417 #warning add arch specific rt_get_caller_pc()
1418 static int rt_get_caller_pc(unsigned long *paddr
,
1419 ucontext_t
*uc
, int level
)
1425 /* emit a run time error at position 'pc' */
1426 void rt_error(ucontext_t
*uc
, const char *fmt
, ...)
1433 fprintf(stderr
, "Runtime error: ");
1434 vfprintf(stderr
, fmt
, ap
);
1435 fprintf(stderr
, "\n");
1436 for(i
=0;i
<num_callers
;i
++) {
1437 if (rt_get_caller_pc(&pc
, uc
, i
) < 0)
1440 fprintf(stderr
, "at ");
1442 fprintf(stderr
, "by ");
1449 /* signal handler for fatal errors */
1450 static void sig_error(int signum
, siginfo_t
*siginf
, void *puc
)
1452 ucontext_t
*uc
= puc
;
1456 switch(siginf
->si_code
) {
1459 rt_error(uc
, "division by zero");
1462 rt_error(uc
, "floating point exception");
1468 if (rt_bound_error_msg
&& *rt_bound_error_msg
)
1469 rt_error(uc
, *rt_bound_error_msg
);
1471 rt_error(uc
, "dereferencing invalid pointer");
1474 rt_error(uc
, "illegal instruction");
1477 rt_error(uc
, "abort() called");
1480 rt_error(uc
, "caught signal %d", signum
);
1488 /* copy code into memory passed in by the caller and do all relocations
1489 (needed before using tcc_get_symbol()).
1490 returns -1 on error and required size if ptr is NULL */
1491 int tcc_relocate(TCCState
*s1
, void *ptr
)
1494 unsigned long offset
, length
, mem
;
1497 if (0 == s1
->runtime_added
) {
1498 s1
->runtime_added
= 1;
1500 #ifdef TCC_TARGET_PE
1502 relocate_common_syms();
1503 tcc_add_linker_symbols(s1
);
1505 tcc_add_runtime(s1
);
1506 relocate_common_syms();
1507 tcc_add_linker_symbols(s1
);
1508 build_got_entries(s1
);
1512 offset
= 0, mem
= (unsigned long)ptr
;
1513 for(i
= 1; i
< s1
->nb_sections
; i
++) {
1514 s
= s1
->sections
[i
];
1515 if (0 == (s
->sh_flags
& SHF_ALLOC
))
1517 length
= s
->data_offset
;
1518 s
->sh_addr
= mem
? (mem
+ offset
+ 15) & ~15 : 0;
1519 offset
= (offset
+ length
+ 15) & ~15;
1522 /* relocate symbols */
1523 relocate_syms(s1
, 1);
1527 #ifdef TCC_TARGET_X86_64
1528 s1
->runtime_plt_and_got_offset
= 0;
1529 s1
->runtime_plt_and_got
= (char *)(mem
+ offset
);
1530 /* double the size of the buffer for got and plt entries
1531 XXX: calculate exact size for them? */
1538 /* relocate each section */
1539 for(i
= 1; i
< s1
->nb_sections
; i
++) {
1540 s
= s1
->sections
[i
];
1542 relocate_section(s1
, s
);
1545 for(i
= 1; i
< s1
->nb_sections
; i
++) {
1546 s
= s1
->sections
[i
];
1547 if (0 == (s
->sh_flags
& SHF_ALLOC
))
1549 length
= s
->data_offset
;
1550 // printf("%-12s %08x %04x\n", s->name, s->sh_addr, length);
1551 ptr
= (void*)s
->sh_addr
;
1552 if (NULL
== s
->data
|| s
->sh_type
== SHT_NOBITS
)
1553 memset(ptr
, 0, length
);
1555 memcpy(ptr
, s
->data
, length
);
1556 /* mark executable sections as executable in memory */
1557 if (s
->sh_flags
& SHF_EXECINSTR
)
1558 set_pages_executable(ptr
, length
);
1560 #ifdef TCC_TARGET_X86_64
1561 set_pages_executable(s1
->runtime_plt_and_got
,
1562 s1
->runtime_plt_and_got_offset
);
1567 /* launch the compiled program with the given arguments */
1568 int tcc_run(TCCState
*s1
, int argc
, char **argv
)
1570 int (*prog_main
)(int, char **);
1574 ret
= tcc_relocate(s1
, NULL
);
1577 ptr
= tcc_malloc(ret
);
1578 tcc_relocate(s1
, ptr
);
1580 prog_main
= tcc_get_symbol_err(s1
, "main");
1583 #ifdef CONFIG_TCC_BACKTRACE
1584 struct sigaction sigact
;
1585 /* install TCC signal handlers to print debug info on fatal
1587 sigact
.sa_flags
= SA_SIGINFO
| SA_RESETHAND
;
1588 sigact
.sa_sigaction
= sig_error
;
1589 sigemptyset(&sigact
.sa_mask
);
1590 sigaction(SIGFPE
, &sigact
, NULL
);
1591 sigaction(SIGILL
, &sigact
, NULL
);
1592 sigaction(SIGSEGV
, &sigact
, NULL
);
1593 sigaction(SIGBUS
, &sigact
, NULL
);
1594 sigaction(SIGABRT
, &sigact
, NULL
);
1596 error("debug mode not available");
1600 #ifdef CONFIG_TCC_BCHECK
1601 if (do_bounds_check
) {
1602 void (*bound_init
)(void);
1604 /* set error function */
1605 rt_bound_error_msg
= tcc_get_symbol_err(s1
, "__bound_error_msg");
1607 /* XXX: use .init section so that it also work in binary ? */
1608 bound_init
= (void *)tcc_get_symbol_err(s1
, "__bound_init");
1612 ret
= (*prog_main
)(argc
, argv
);
1617 void tcc_memstats(void)
1620 printf("memory in use: %d\n", mem_cur_size
);
1624 static void tcc_cleanup(void)
1628 if (NULL
== tcc_state
)
1632 /* free -D defines */
1636 n
= tok_ident
- TOK_IDENT
;
1637 for(i
= 0; i
< n
; i
++)
1638 tcc_free(table_ident
[i
]);
1639 tcc_free(table_ident
);
1641 /* free sym_pools */
1642 dynarray_reset(&sym_pools
, &nb_sym_pools
);
1644 cstr_free(&tokcstr
);
1645 /* reset symbol stack */
1646 sym_free_first
= NULL
;
1647 /* cleanup from error/setjmp */
1651 TCCState
*tcc_new(void)
1657 s
= tcc_mallocz(sizeof(TCCState
));
1661 s
->output_type
= TCC_OUTPUT_MEMORY
;
1665 /* we add dummy defines for some special macros to speed up tests
1666 and to have working defined() */
1667 define_push(TOK___LINE__
, MACRO_OBJ
, NULL
, NULL
);
1668 define_push(TOK___FILE__
, MACRO_OBJ
, NULL
, NULL
);
1669 define_push(TOK___DATE__
, MACRO_OBJ
, NULL
, NULL
);
1670 define_push(TOK___TIME__
, MACRO_OBJ
, NULL
, NULL
);
1672 /* standard defines */
1673 tcc_define_symbol(s
, "__STDC__", NULL
);
1674 tcc_define_symbol(s
, "__STDC_VERSION__", "199901L");
1675 #if defined(TCC_TARGET_I386)
1676 tcc_define_symbol(s
, "__i386__", NULL
);
1678 #if defined(TCC_TARGET_X86_64)
1679 tcc_define_symbol(s
, "__x86_64__", NULL
);
1681 #if defined(TCC_TARGET_ARM)
1682 tcc_define_symbol(s
, "__ARM_ARCH_4__", NULL
);
1683 tcc_define_symbol(s
, "__arm_elf__", NULL
);
1684 tcc_define_symbol(s
, "__arm_elf", NULL
);
1685 tcc_define_symbol(s
, "arm_elf", NULL
);
1686 tcc_define_symbol(s
, "__arm__", NULL
);
1687 tcc_define_symbol(s
, "__arm", NULL
);
1688 tcc_define_symbol(s
, "arm", NULL
);
1689 tcc_define_symbol(s
, "__APCS_32__", NULL
);
1691 #ifdef TCC_TARGET_PE
1692 tcc_define_symbol(s
, "_WIN32", NULL
);
1694 tcc_define_symbol(s
, "__unix__", NULL
);
1695 tcc_define_symbol(s
, "__unix", NULL
);
1696 #if defined(__linux)
1697 tcc_define_symbol(s
, "__linux__", NULL
);
1698 tcc_define_symbol(s
, "__linux", NULL
);
1701 /* tiny C specific defines */
1702 tcc_define_symbol(s
, "__TINYC__", NULL
);
1704 /* tiny C & gcc defines */
1705 tcc_define_symbol(s
, "__SIZE_TYPE__", "unsigned int");
1706 tcc_define_symbol(s
, "__PTRDIFF_TYPE__", "int");
1707 #ifdef TCC_TARGET_PE
1708 tcc_define_symbol(s
, "__WCHAR_TYPE__", "unsigned short");
1710 tcc_define_symbol(s
, "__WCHAR_TYPE__", "int");
1713 #ifndef TCC_TARGET_PE
1714 /* default library paths */
1715 tcc_add_library_path(s
, CONFIG_SYSROOT
"/usr/local/lib");
1716 tcc_add_library_path(s
, CONFIG_SYSROOT
"/usr/lib");
1717 tcc_add_library_path(s
, CONFIG_SYSROOT
"/lib");
1720 /* no section zero */
1721 dynarray_add((void ***)&s
->sections
, &s
->nb_sections
, NULL
);
1723 /* create standard sections */
1724 text_section
= new_section(s
, ".text", SHT_PROGBITS
, SHF_ALLOC
| SHF_EXECINSTR
);
1725 data_section
= new_section(s
, ".data", SHT_PROGBITS
, SHF_ALLOC
| SHF_WRITE
);
1726 bss_section
= new_section(s
, ".bss", SHT_NOBITS
, SHF_ALLOC
| SHF_WRITE
);
1728 /* symbols are always generated for linking stage */
1729 symtab_section
= new_symtab(s
, ".symtab", SHT_SYMTAB
, 0,
1731 ".hashtab", SHF_PRIVATE
);
1732 strtab_section
= symtab_section
->link
;
1734 /* private symbol table for dynamic symbols */
1735 s
->dynsymtab_section
= new_symtab(s
, ".dynsymtab", SHT_SYMTAB
, SHF_PRIVATE
,
1737 ".dynhashtab", SHF_PRIVATE
);
1738 s
->alacarte_link
= 1;
1740 #ifdef CHAR_IS_UNSIGNED
1741 s
->char_is_unsigned
= 1;
1743 #if defined(TCC_TARGET_PE) && 0
1744 /* XXX: currently the PE linker is not ready to support that */
1745 s
->leading_underscore
= 1;
1750 void tcc_delete(TCCState
*s1
)
1756 /* free all sections */
1757 for(i
= 1; i
< s1
->nb_sections
; i
++)
1758 free_section(s1
->sections
[i
]);
1759 dynarray_reset(&s1
->sections
, &s1
->nb_sections
);
1761 for(i
= 0; i
< s1
->nb_priv_sections
; i
++)
1762 free_section(s1
->priv_sections
[i
]);
1763 dynarray_reset(&s1
->priv_sections
, &s1
->nb_priv_sections
);
1765 /* free any loaded DLLs */
1766 for ( i
= 0; i
< s1
->nb_loaded_dlls
; i
++) {
1767 DLLReference
*ref
= s1
->loaded_dlls
[i
];
1769 dlclose(ref
->handle
);
1772 /* free loaded dlls array */
1773 dynarray_reset(&s1
->loaded_dlls
, &s1
->nb_loaded_dlls
);
1775 /* free library paths */
1776 dynarray_reset(&s1
->library_paths
, &s1
->nb_library_paths
);
1778 /* free include paths */
1779 dynarray_reset(&s1
->cached_includes
, &s1
->nb_cached_includes
);
1780 dynarray_reset(&s1
->include_paths
, &s1
->nb_include_paths
);
1781 dynarray_reset(&s1
->sysinclude_paths
, &s1
->nb_sysinclude_paths
);
1786 int tcc_add_include_path(TCCState
*s1
, const char *pathname
)
1790 pathname1
= tcc_strdup(pathname
);
1791 dynarray_add((void ***)&s1
->include_paths
, &s1
->nb_include_paths
, pathname1
);
1795 int tcc_add_sysinclude_path(TCCState
*s1
, const char *pathname
)
1799 pathname1
= tcc_strdup(pathname
);
1800 dynarray_add((void ***)&s1
->sysinclude_paths
, &s1
->nb_sysinclude_paths
, pathname1
);
1804 static int tcc_add_file_internal(TCCState
*s1
, const char *filename
, int flags
)
1809 BufferedFile
*saved_file
;
1811 /* find source file type with extension */
1812 ext
= tcc_fileextension(filename
);
1818 file
= tcc_open(s1
, filename
);
1820 if (flags
& AFF_PRINT_ERROR
) {
1821 error_noabort("file '%s' not found", filename
);
1827 if (flags
& AFF_PREPROCESS
) {
1828 ret
= tcc_preprocess(s1
);
1829 } else if (!ext
[0] || !PATHCMP(ext
, "c")) {
1830 /* C file assumed */
1831 ret
= tcc_compile(s1
);
1833 #ifdef CONFIG_TCC_ASM
1834 if (!strcmp(ext
, "S")) {
1835 /* preprocessed assembler */
1836 ret
= tcc_assemble(s1
, 1);
1837 } else if (!strcmp(ext
, "s")) {
1838 /* non preprocessed assembler */
1839 ret
= tcc_assemble(s1
, 0);
1842 #ifdef TCC_TARGET_PE
1843 if (!PATHCMP(ext
, "def")) {
1844 ret
= pe_load_def_file(s1
, file
->fd
);
1849 /* assume executable format: auto guess file type */
1850 ret
= read(fd
, &ehdr
, sizeof(ehdr
));
1851 lseek(fd
, 0, SEEK_SET
);
1853 error_noabort("could not read header");
1855 } else if (ret
!= sizeof(ehdr
)) {
1856 goto try_load_script
;
1859 if (ehdr
.e_ident
[0] == ELFMAG0
&&
1860 ehdr
.e_ident
[1] == ELFMAG1
&&
1861 ehdr
.e_ident
[2] == ELFMAG2
&&
1862 ehdr
.e_ident
[3] == ELFMAG3
) {
1863 file
->line_num
= 0; /* do not display line number if error */
1864 if (ehdr
.e_type
== ET_REL
) {
1865 ret
= tcc_load_object_file(s1
, fd
, 0);
1866 } else if (ehdr
.e_type
== ET_DYN
) {
1867 if (s1
->output_type
== TCC_OUTPUT_MEMORY
) {
1868 #ifdef TCC_TARGET_PE
1872 h
= dlopen(filename
, RTLD_GLOBAL
| RTLD_LAZY
);
1879 ret
= tcc_load_dll(s1
, fd
, filename
,
1880 (flags
& AFF_REFERENCED_DLL
) != 0);
1883 error_noabort("unrecognized ELF file");
1886 } else if (memcmp((char *)&ehdr
, ARMAG
, 8) == 0) {
1887 file
->line_num
= 0; /* do not display line number if error */
1888 ret
= tcc_load_archive(s1
, fd
);
1890 #ifdef TCC_TARGET_COFF
1891 if (*(uint16_t *)(&ehdr
) == COFF_C67_MAGIC
) {
1892 ret
= tcc_load_coff(s1
, fd
);
1895 #ifdef TCC_TARGET_PE
1896 if (pe_test_res_file(&ehdr
, ret
)) {
1897 ret
= pe_load_res_file(s1
, fd
);
1901 /* as GNU ld, consider it is an ld script if not recognized */
1903 ret
= tcc_load_ldscript(s1
);
1905 error_noabort("unrecognized file type");
1920 int tcc_add_file(TCCState
*s
, const char *filename
)
1922 return tcc_add_file_internal(s
, filename
, AFF_PRINT_ERROR
);
1925 int tcc_add_library_path(TCCState
*s
, const char *pathname
)
1929 pathname1
= tcc_strdup(pathname
);
1930 dynarray_add((void ***)&s
->library_paths
, &s
->nb_library_paths
, pathname1
);
1934 /* find and load a dll. Return non zero if not found */
1935 /* XXX: add '-rpath' option support ? */
1936 static int tcc_add_dll(TCCState
*s
, const char *filename
, int flags
)
1941 for(i
= 0; i
< s
->nb_library_paths
; i
++) {
1942 snprintf(buf
, sizeof(buf
), "%s/%s",
1943 s
->library_paths
[i
], filename
);
1944 if (tcc_add_file_internal(s
, buf
, flags
) == 0)
1950 /* the library name is the same as the argument of the '-l' option */
1951 int tcc_add_library(TCCState
*s
, const char *libraryname
)
1956 /* first we look for the dynamic library if not static linking */
1957 if (!s
->static_link
) {
1958 #ifdef TCC_TARGET_PE
1959 snprintf(buf
, sizeof(buf
), "%s.def", libraryname
);
1961 snprintf(buf
, sizeof(buf
), "lib%s.so", libraryname
);
1963 if (tcc_add_dll(s
, buf
, 0) == 0)
1967 /* then we look for the static library */
1968 for(i
= 0; i
< s
->nb_library_paths
; i
++) {
1969 snprintf(buf
, sizeof(buf
), "%s/lib%s.a",
1970 s
->library_paths
[i
], libraryname
);
1971 if (tcc_add_file_internal(s
, buf
, 0) == 0)
1977 int tcc_add_symbol(TCCState
*s
, const char *name
, void *val
)
1979 add_elf_sym(symtab_section
, (unsigned long)val
, 0,
1980 ELFW(ST_INFO
)(STB_GLOBAL
, STT_NOTYPE
), 0,
1985 int tcc_set_output_type(TCCState
*s
, int output_type
)
1989 s
->output_type
= output_type
;
1992 /* default include paths */
1993 /* XXX: reverse order needed if -isystem support */
1994 #ifndef TCC_TARGET_PE
1995 tcc_add_sysinclude_path(s
, CONFIG_SYSROOT
"/usr/local/include");
1996 tcc_add_sysinclude_path(s
, CONFIG_SYSROOT
"/usr/include");
1998 snprintf(buf
, sizeof(buf
), "%s/include", tcc_lib_path
);
1999 tcc_add_sysinclude_path(s
, buf
);
2000 #ifdef TCC_TARGET_PE
2001 snprintf(buf
, sizeof(buf
), "%s/include/winapi", tcc_lib_path
);
2002 tcc_add_sysinclude_path(s
, buf
);
2006 /* if bound checking, then add corresponding sections */
2007 #ifdef CONFIG_TCC_BCHECK
2008 if (do_bounds_check
) {
2010 tcc_define_symbol(s
, "__BOUNDS_CHECKING_ON", NULL
);
2011 /* create bounds sections */
2012 bounds_section
= new_section(s
, ".bounds",
2013 SHT_PROGBITS
, SHF_ALLOC
);
2014 lbounds_section
= new_section(s
, ".lbounds",
2015 SHT_PROGBITS
, SHF_ALLOC
);
2019 if (s
->char_is_unsigned
) {
2020 tcc_define_symbol(s
, "__CHAR_UNSIGNED__", NULL
);
2023 /* add debug sections */
2026 stab_section
= new_section(s
, ".stab", SHT_PROGBITS
, 0);
2027 stab_section
->sh_entsize
= sizeof(Stab_Sym
);
2028 stabstr_section
= new_section(s
, ".stabstr", SHT_STRTAB
, 0);
2029 put_elf_str(stabstr_section
, "");
2030 stab_section
->link
= stabstr_section
;
2031 /* put first entry */
2032 put_stabs("", 0, 0, 0, 0);
2035 /* add libc crt1/crti objects */
2036 #ifndef TCC_TARGET_PE
2037 if ((output_type
== TCC_OUTPUT_EXE
|| output_type
== TCC_OUTPUT_DLL
) &&
2039 if (output_type
!= TCC_OUTPUT_DLL
)
2040 tcc_add_file(s
, CONFIG_TCC_CRT_PREFIX
"/crt1.o");
2041 tcc_add_file(s
, CONFIG_TCC_CRT_PREFIX
"/crti.o");
2045 #ifdef TCC_TARGET_PE
2046 snprintf(buf
, sizeof(buf
), "%s/lib", tcc_lib_path
);
2047 tcc_add_library_path(s
, buf
);
2053 #define WD_ALL 0x0001 /* warning is activated when using -Wall */
2054 #define FD_INVERT 0x0002 /* invert value before storing */
2056 typedef struct FlagDef
{
2062 static const FlagDef warning_defs
[] = {
2063 { offsetof(TCCState
, warn_unsupported
), 0, "unsupported" },
2064 { offsetof(TCCState
, warn_write_strings
), 0, "write-strings" },
2065 { offsetof(TCCState
, warn_error
), 0, "error" },
2066 { offsetof(TCCState
, warn_implicit_function_declaration
), WD_ALL
,
2067 "implicit-function-declaration" },
2070 static int set_flag(TCCState
*s
, const FlagDef
*flags
, int nb_flags
,
2071 const char *name
, int value
)
2078 if (r
[0] == 'n' && r
[1] == 'o' && r
[2] == '-') {
2082 for(i
= 0, p
= flags
; i
< nb_flags
; i
++, p
++) {
2083 if (!strcmp(r
, p
->name
))
2088 if (p
->flags
& FD_INVERT
)
2090 *(int *)((uint8_t *)s
+ p
->offset
) = value
;
2095 /* set/reset a warning */
2096 int tcc_set_warning(TCCState
*s
, const char *warning_name
, int value
)
2101 if (!strcmp(warning_name
, "all")) {
2102 for(i
= 0, p
= warning_defs
; i
< countof(warning_defs
); i
++, p
++) {
2103 if (p
->flags
& WD_ALL
)
2104 *(int *)((uint8_t *)s
+ p
->offset
) = 1;
2108 return set_flag(s
, warning_defs
, countof(warning_defs
),
2109 warning_name
, value
);
2113 static const FlagDef flag_defs
[] = {
2114 { offsetof(TCCState
, char_is_unsigned
), 0, "unsigned-char" },
2115 { offsetof(TCCState
, char_is_unsigned
), FD_INVERT
, "signed-char" },
2116 { offsetof(TCCState
, nocommon
), FD_INVERT
, "common" },
2117 { offsetof(TCCState
, leading_underscore
), 0, "leading-underscore" },
2120 /* set/reset a flag */
2121 int tcc_set_flag(TCCState
*s
, const char *flag_name
, int value
)
2123 return set_flag(s
, flag_defs
, countof(flag_defs
),
2127 /* set CONFIG_TCCDIR at runtime */
2128 void tcc_set_lib_path(TCCState
*s
, const char *path
)
2130 tcc_lib_path
= tcc_strdup(path
);