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
;
129 #ifdef TCC_TARGET_I386
130 #include "i386-gen.c"
133 #ifdef TCC_TARGET_ARM
137 #ifdef TCC_TARGET_C67
141 #ifdef TCC_TARGET_X86_64
142 #include "x86_64-gen.c"
145 #ifdef CONFIG_TCC_STATIC
147 #define RTLD_LAZY 0x001
148 #define RTLD_NOW 0x002
149 #define RTLD_GLOBAL 0x100
150 #define RTLD_DEFAULT NULL
152 /* dummy function for profiling */
153 void *dlopen(const char *filename
, int flag
)
158 void dlclose(void *p
)
162 const char *dlerror(void)
167 typedef struct TCCSyms
{
172 #define TCCSYM(a) { #a, &a, },
174 /* add the symbol you want here if no dynamic linking is done */
175 static TCCSyms tcc_syms
[] = {
176 #if !defined(CONFIG_TCCBOOT)
185 void *resolve_sym(TCCState
*s1
, const char *symbol
, int type
)
189 while (p
->str
!= NULL
) {
190 if (!strcmp(p
->str
, symbol
))
197 #elif !defined(_WIN32)
201 void *resolve_sym(TCCState
*s1
, const char *sym
, int type
)
203 return dlsym(RTLD_DEFAULT
, sym
);
208 /********************************************************/
210 /* we use our own 'finite' function to avoid potential problems with
211 non standard math libs */
212 /* XXX: endianness dependent */
213 int ieee_finite(double d
)
216 return ((unsigned)((p
[1] | 0x800fffff) + 1)) >> 31;
219 /* copy a string and truncate it. */
220 static char *pstrcpy(char *buf
, int buf_size
, const char *s
)
227 q_end
= buf
+ buf_size
- 1;
239 /* strcat and truncate. */
240 static char *pstrcat(char *buf
, int buf_size
, const char *s
)
245 pstrcpy(buf
+ len
, buf_size
- len
, s
);
249 /* extract the basename of a file */
250 static char *tcc_basename(const char *name
)
252 char *p
= strchr(name
, 0);
253 while (p
> name
&& !IS_PATHSEP(p
[-1]))
258 static char *tcc_fileextension (const char *name
)
260 char *b
= tcc_basename(name
);
261 char *e
= strrchr(b
, '.');
262 return e
? e
: strchr(b
, 0);
266 char *normalize_slashes(char *path
)
269 for (p
= path
; *p
; ++p
)
275 void tcc_set_lib_path_w32(TCCState
*s
)
277 /* on win32, we suppose the lib and includes are at the location
280 GetModuleFileNameA(NULL
, path
, sizeof path
);
281 p
= tcc_basename(normalize_slashes(strlwr(path
)));
282 if (p
- 5 > path
&& 0 == strncmp(p
- 5, "/bin/", 5))
287 tcc_set_lib_path(s
, path
);
291 void set_pages_executable(void *ptr
, unsigned long length
)
294 unsigned long old_protect
;
295 VirtualProtect(ptr
, length
, PAGE_EXECUTE_READWRITE
, &old_protect
);
297 unsigned long start
, end
;
298 start
= (unsigned long)ptr
& ~(PAGESIZE
- 1);
299 end
= (unsigned long)ptr
+ length
;
300 end
= (end
+ PAGESIZE
- 1) & ~(PAGESIZE
- 1);
301 mprotect((void *)start
, end
- start
, PROT_READ
| PROT_WRITE
| PROT_EXEC
);
305 /* memory management */
309 unsigned malloc_usable_size(void*);
312 static inline void tcc_free(void *ptr
)
315 mem_cur_size
-= malloc_usable_size(ptr
);
320 static void *tcc_malloc(unsigned long size
)
325 error("memory full");
327 mem_cur_size
+= malloc_usable_size(ptr
);
328 if (mem_cur_size
> mem_max_size
)
329 mem_max_size
= mem_cur_size
;
334 static void *tcc_mallocz(unsigned long size
)
337 ptr
= tcc_malloc(size
);
338 memset(ptr
, 0, size
);
342 static inline void *tcc_realloc(void *ptr
, unsigned long size
)
346 mem_cur_size
-= malloc_usable_size(ptr
);
348 ptr1
= realloc(ptr
, size
);
350 /* NOTE: count not correct if alloc error, but not critical */
351 mem_cur_size
+= malloc_usable_size(ptr1
);
352 if (mem_cur_size
> mem_max_size
)
353 mem_max_size
= mem_cur_size
;
358 static char *tcc_strdup(const char *str
)
361 ptr
= tcc_malloc(strlen(str
) + 1);
366 #define free(p) use_tcc_free(p)
367 #define malloc(s) use_tcc_malloc(s)
368 #define realloc(p, s) use_tcc_realloc(p, s)
370 static void dynarray_add(void ***ptab
, int *nb_ptr
, void *data
)
377 /* every power of two we double array size */
378 if ((nb
& (nb
- 1)) == 0) {
383 pp
= tcc_realloc(pp
, nb_alloc
* sizeof(void *));
385 error("memory full");
392 static void dynarray_reset(void *pp
, int *n
)
395 for (p
= *(void***)pp
; *n
; ++p
, --*n
)
398 tcc_free(*(void**)pp
);
402 /* symbol allocator */
403 static Sym
*__sym_malloc(void)
405 Sym
*sym_pool
, *sym
, *last_sym
;
408 sym_pool
= tcc_malloc(SYM_POOL_NB
* sizeof(Sym
));
409 dynarray_add(&sym_pools
, &nb_sym_pools
, sym_pool
);
411 last_sym
= sym_free_first
;
413 for(i
= 0; i
< SYM_POOL_NB
; i
++) {
414 sym
->next
= last_sym
;
418 sym_free_first
= last_sym
;
422 static inline Sym
*sym_malloc(void)
425 sym
= sym_free_first
;
427 sym
= __sym_malloc();
428 sym_free_first
= sym
->next
;
432 static inline void sym_free(Sym
*sym
)
434 sym
->next
= sym_free_first
;
435 sym_free_first
= sym
;
438 Section
*new_section(TCCState
*s1
, const char *name
, int sh_type
, int sh_flags
)
442 sec
= tcc_mallocz(sizeof(Section
) + strlen(name
));
443 strcpy(sec
->name
, name
);
444 sec
->sh_type
= sh_type
;
445 sec
->sh_flags
= sh_flags
;
453 sec
->sh_addralign
= 4;
456 sec
->sh_addralign
= 1;
459 sec
->sh_addralign
= 32; /* default conservative alignment */
463 if (sh_flags
& SHF_PRIVATE
) {
464 dynarray_add((void ***)&s1
->priv_sections
, &s1
->nb_priv_sections
, sec
);
466 sec
->sh_num
= s1
->nb_sections
;
467 dynarray_add((void ***)&s1
->sections
, &s1
->nb_sections
, sec
);
473 static void free_section(Section
*s
)
478 /* realloc section and set its content to zero */
479 static void section_realloc(Section
*sec
, unsigned long new_size
)
484 size
= sec
->data_allocated
;
487 while (size
< new_size
)
489 data
= tcc_realloc(sec
->data
, size
);
491 error("memory full");
492 memset(data
+ sec
->data_allocated
, 0, size
- sec
->data_allocated
);
494 sec
->data_allocated
= size
;
497 /* reserve at least 'size' bytes in section 'sec' from
499 static void *section_ptr_add(Section
*sec
, unsigned long size
)
501 unsigned long offset
, offset1
;
503 offset
= sec
->data_offset
;
504 offset1
= offset
+ size
;
505 if (offset1
> sec
->data_allocated
)
506 section_realloc(sec
, offset1
);
507 sec
->data_offset
= offset1
;
508 return sec
->data
+ offset
;
511 /* return a reference to a section, and create it if it does not
513 Section
*find_section(TCCState
*s1
, const char *name
)
517 for(i
= 1; i
< s1
->nb_sections
; i
++) {
518 sec
= s1
->sections
[i
];
519 if (!strcmp(name
, sec
->name
))
522 /* sections are created as PROGBITS */
523 return new_section(s1
, name
, SHT_PROGBITS
, SHF_ALLOC
);
526 /* update sym->c so that it points to an external symbol in section
527 'section' with value 'value' */
528 static void put_extern_sym2(Sym
*sym
, Section
*section
,
529 unsigned long value
, unsigned long size
,
530 int can_add_underscore
)
532 int sym_type
, sym_bind
, sh_num
, info
, other
, attr
;
539 else if (section
== SECTION_ABS
)
542 sh_num
= section
->sh_num
;
546 if ((sym
->type
.t
& VT_BTYPE
) == VT_FUNC
) {
550 attr
= sym
->type
.ref
->r
;
551 if (FUNC_EXPORT(attr
))
553 if (FUNC_CALL(attr
) == FUNC_STDCALL
)
557 sym_type
= STT_OBJECT
;
560 if (sym
->type
.t
& VT_STATIC
)
561 sym_bind
= STB_LOCAL
;
563 sym_bind
= STB_GLOBAL
;
566 name
= get_tok_str(sym
->v
, NULL
);
567 #ifdef CONFIG_TCC_BCHECK
568 if (do_bounds_check
) {
571 /* XXX: avoid doing that for statics ? */
572 /* if bound checking is activated, we change some function
573 names by adding the "__bound" prefix */
576 /* XXX: we rely only on malloc hooks */
589 strcpy(buf
, "__bound_");
598 if ((other
& 2) && can_add_underscore
) {
599 sprintf(buf1
, "_%s@%d", name
, FUNC_ARGS(attr
));
603 if (tcc_state
->leading_underscore
&& can_add_underscore
) {
605 pstrcpy(buf1
+ 1, sizeof(buf1
) - 1, name
);
608 info
= ELFW(ST_INFO
)(sym_bind
, sym_type
);
609 sym
->c
= add_elf_sym(symtab_section
, value
, size
, info
, other
, sh_num
, name
);
611 esym
= &((ElfW(Sym
) *)symtab_section
->data
)[sym
->c
];
612 esym
->st_value
= value
;
613 esym
->st_size
= size
;
614 esym
->st_shndx
= sh_num
;
615 esym
->st_other
|= other
;
619 static void put_extern_sym(Sym
*sym
, Section
*section
,
620 unsigned long value
, unsigned long size
)
622 put_extern_sym2(sym
, section
, value
, size
, 1);
625 /* add a new relocation entry to symbol 'sym' in section 's' */
626 static void greloc(Section
*s
, Sym
*sym
, unsigned long offset
, int type
)
629 put_extern_sym(sym
, NULL
, 0, 0);
630 /* now we can add ELF relocation info */
631 put_elf_reloc(symtab_section
, s
, offset
, type
, sym
->c
);
634 static inline int isid(int c
)
636 return (c
>= 'a' && c
<= 'z') ||
637 (c
>= 'A' && c
<= 'Z') ||
641 static inline int isnum(int c
)
643 return c
>= '0' && c
<= '9';
646 static inline int isoct(int c
)
648 return c
>= '0' && c
<= '7';
651 static inline int toup(int c
)
653 if (c
>= 'a' && c
<= 'z')
654 return c
- 'a' + 'A';
659 static void strcat_vprintf(char *buf
, int buf_size
, const char *fmt
, va_list ap
)
663 vsnprintf(buf
+ len
, buf_size
- len
, fmt
, ap
);
666 static void strcat_printf(char *buf
, int buf_size
, const char *fmt
, ...)
670 strcat_vprintf(buf
, buf_size
, fmt
, ap
);
674 void error1(TCCState
*s1
, int is_warning
, const char *fmt
, va_list ap
)
681 for(f
= s1
->include_stack
; f
< s1
->include_stack_ptr
; f
++)
682 strcat_printf(buf
, sizeof(buf
), "In file included from %s:%d:\n",
683 (*f
)->filename
, (*f
)->line_num
);
684 if (file
->line_num
> 0) {
685 strcat_printf(buf
, sizeof(buf
),
686 "%s:%d: ", file
->filename
, file
->line_num
);
688 strcat_printf(buf
, sizeof(buf
),
689 "%s: ", file
->filename
);
692 strcat_printf(buf
, sizeof(buf
),
696 strcat_printf(buf
, sizeof(buf
), "warning: ");
697 strcat_vprintf(buf
, sizeof(buf
), fmt
, ap
);
699 if (!s1
->error_func
) {
700 /* default case: stderr */
701 fprintf(stderr
, "%s\n", buf
);
703 s1
->error_func(s1
->error_opaque
, buf
);
705 if (!is_warning
|| s1
->warn_error
)
710 void tcc_set_error_func(TCCState
*s
, void *error_opaque
,
711 void (*error_func
)(void *opaque
, const char *msg
))
713 s
->error_opaque
= error_opaque
;
714 s
->error_func
= error_func
;
718 /* error without aborting current compilation */
719 void error_noabort(const char *fmt
, ...)
721 TCCState
*s1
= tcc_state
;
725 error1(s1
, 0, fmt
, ap
);
729 void error(const char *fmt
, ...)
731 TCCState
*s1
= tcc_state
;
735 error1(s1
, 0, fmt
, ap
);
737 /* better than nothing: in some cases, we accept to handle errors */
738 if (s1
->error_set_jmp_enabled
) {
739 longjmp(s1
->error_jmp_buf
, 1);
741 /* XXX: eliminate this someday */
746 void expect(const char *msg
)
748 error("%s expected", msg
);
751 void warning(const char *fmt
, ...)
753 TCCState
*s1
= tcc_state
;
760 error1(s1
, 1, fmt
, ap
);
767 error("'%c' expected", c
);
771 static void test_lvalue(void)
773 if (!(vtop
->r
& VT_LVAL
))
777 /* CString handling */
779 static void cstr_realloc(CString
*cstr
, int new_size
)
784 size
= cstr
->size_allocated
;
786 size
= 8; /* no need to allocate a too small first string */
787 while (size
< new_size
)
789 data
= tcc_realloc(cstr
->data_allocated
, size
);
791 error("memory full");
792 cstr
->data_allocated
= data
;
793 cstr
->size_allocated
= size
;
798 static inline void cstr_ccat(CString
*cstr
, int ch
)
801 size
= cstr
->size
+ 1;
802 if (size
> cstr
->size_allocated
)
803 cstr_realloc(cstr
, size
);
804 ((unsigned char *)cstr
->data
)[size
- 1] = ch
;
808 static void cstr_cat(CString
*cstr
, const char *str
)
820 /* add a wide char */
821 static void cstr_wccat(CString
*cstr
, int ch
)
824 size
= cstr
->size
+ sizeof(nwchar_t
);
825 if (size
> cstr
->size_allocated
)
826 cstr_realloc(cstr
, size
);
827 *(nwchar_t
*)(((unsigned char *)cstr
->data
) + size
- sizeof(nwchar_t
)) = ch
;
831 static void cstr_new(CString
*cstr
)
833 memset(cstr
, 0, sizeof(CString
));
836 /* free string and reset it to NULL */
837 static void cstr_free(CString
*cstr
)
839 tcc_free(cstr
->data_allocated
);
843 #define cstr_reset(cstr) cstr_free(cstr)
846 static void add_char(CString
*cstr
, int c
)
848 if (c
== '\'' || c
== '\"' || c
== '\\') {
849 /* XXX: could be more precise if char or string */
850 cstr_ccat(cstr
, '\\');
852 if (c
>= 32 && c
<= 126) {
855 cstr_ccat(cstr
, '\\');
857 cstr_ccat(cstr
, 'n');
859 cstr_ccat(cstr
, '0' + ((c
>> 6) & 7));
860 cstr_ccat(cstr
, '0' + ((c
>> 3) & 7));
861 cstr_ccat(cstr
, '0' + (c
& 7));
866 /* push, without hashing */
867 static Sym
*sym_push2(Sym
**ps
, int v
, int t
, long c
)
881 /* find a symbol and return its associated structure. 's' is the top
882 of the symbol stack */
883 static Sym
*sym_find2(Sym
*s
, int v
)
893 /* structure lookup */
894 static inline Sym
*struct_find(int v
)
897 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
899 return table_ident
[v
]->sym_struct
;
902 /* find an identifier */
903 static inline Sym
*sym_find(int v
)
906 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
908 return table_ident
[v
]->sym_identifier
;
911 /* push a given symbol on the symbol stack */
912 static Sym
*sym_push(int v
, CType
*type
, int r
, int c
)
921 s
= sym_push2(ps
, v
, type
->t
, c
);
922 s
->type
.ref
= type
->ref
;
924 /* don't record fields or anonymous symbols */
926 if (!(v
& SYM_FIELD
) && (v
& ~SYM_STRUCT
) < SYM_FIRST_ANOM
) {
927 /* record symbol in token array */
928 ts
= table_ident
[(v
& ~SYM_STRUCT
) - TOK_IDENT
];
930 ps
= &ts
->sym_struct
;
932 ps
= &ts
->sym_identifier
;
939 /* push a global identifier */
940 static Sym
*global_identifier_push(int v
, int t
, int c
)
943 s
= sym_push2(&global_stack
, v
, t
, c
);
944 /* don't record anonymous symbol */
945 if (v
< SYM_FIRST_ANOM
) {
946 ps
= &table_ident
[v
- TOK_IDENT
]->sym_identifier
;
947 /* modify the top most local identifier, so that
948 sym_identifier will point to 's' when popped */
950 ps
= &(*ps
)->prev_tok
;
957 /* pop symbols until top reaches 'b' */
958 static void sym_pop(Sym
**ptop
, Sym
*b
)
968 /* remove symbol in token array */
970 if (!(v
& SYM_FIELD
) && (v
& ~SYM_STRUCT
) < SYM_FIRST_ANOM
) {
971 ts
= table_ident
[(v
& ~SYM_STRUCT
) - TOK_IDENT
];
973 ps
= &ts
->sym_struct
;
975 ps
= &ts
->sym_identifier
;
986 BufferedFile
*tcc_open(TCCState
*s1
, const char *filename
)
991 if (strcmp(filename
, "-") == 0)
992 fd
= 0, filename
= "stdin";
994 fd
= open(filename
, O_RDONLY
| O_BINARY
);
995 if ((verbose
== 2 && fd
>= 0) || verbose
== 3)
996 printf("%s %*s%s\n", fd
< 0 ? "nf":"->",
997 (s1
->include_stack_ptr
- s1
->include_stack
), "", filename
);
1000 bf
= tcc_malloc(sizeof(BufferedFile
));
1002 bf
->buf_ptr
= bf
->buffer
;
1003 bf
->buf_end
= bf
->buffer
;
1004 bf
->buffer
[0] = CH_EOB
; /* put eob symbol */
1005 pstrcpy(bf
->filename
, sizeof(bf
->filename
), filename
);
1007 normalize_slashes(bf
->filename
);
1010 bf
->ifndef_macro
= 0;
1011 bf
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
1012 // printf("opening '%s'\n", filename);
1016 void tcc_close(BufferedFile
*bf
)
1018 total_lines
+= bf
->line_num
;
1027 /* compile the C file opened in 'file'. Return non zero if errors. */
1028 static int tcc_compile(TCCState
*s1
)
1032 volatile int section_sym
;
1035 printf("%s: **** new file\n", file
->filename
);
1037 preprocess_init(s1
);
1039 cur_text_section
= NULL
;
1041 anon_sym
= SYM_FIRST_ANOM
;
1043 /* file info: full path + filename */
1044 section_sym
= 0; /* avoid warning */
1046 section_sym
= put_elf_sym(symtab_section
, 0, 0,
1047 ELFW(ST_INFO
)(STB_LOCAL
, STT_SECTION
), 0,
1048 text_section
->sh_num
, NULL
);
1049 getcwd(buf
, sizeof(buf
));
1051 normalize_slashes(buf
);
1053 pstrcat(buf
, sizeof(buf
), "/");
1054 put_stabs_r(buf
, N_SO
, 0, 0,
1055 text_section
->data_offset
, text_section
, section_sym
);
1056 put_stabs_r(file
->filename
, N_SO
, 0, 0,
1057 text_section
->data_offset
, text_section
, section_sym
);
1059 /* an elf symbol of type STT_FILE must be put so that STB_LOCAL
1060 symbols can be safely used */
1061 put_elf_sym(symtab_section
, 0, 0,
1062 ELFW(ST_INFO
)(STB_LOCAL
, STT_FILE
), 0,
1063 SHN_ABS
, file
->filename
);
1065 /* define some often used types */
1066 int_type
.t
= VT_INT
;
1068 char_pointer_type
.t
= VT_BYTE
;
1069 mk_pointer(&char_pointer_type
);
1071 func_old_type
.t
= VT_FUNC
;
1072 func_old_type
.ref
= sym_push(SYM_FIELD
, &int_type
, FUNC_CDECL
, FUNC_OLD
);
1074 #if defined(TCC_ARM_EABI) && defined(TCC_ARM_VFP)
1075 float_type
.t
= VT_FLOAT
;
1076 double_type
.t
= VT_DOUBLE
;
1078 func_float_type
.t
= VT_FUNC
;
1079 func_float_type
.ref
= sym_push(SYM_FIELD
, &float_type
, FUNC_CDECL
, FUNC_OLD
);
1080 func_double_type
.t
= VT_FUNC
;
1081 func_double_type
.ref
= sym_push(SYM_FIELD
, &double_type
, FUNC_CDECL
, FUNC_OLD
);
1085 /* define 'void *alloca(unsigned int)' builtin function */
1090 sym
= sym_push(p
, mk_pointer(VT_VOID
), FUNC_CDECL
, FUNC_NEW
);
1091 s1
= sym_push(SYM_FIELD
, VT_UNSIGNED
| VT_INT
, 0, 0);
1094 sym_push(TOK_alloca
, VT_FUNC
| (p
<< VT_STRUCT_SHIFT
), VT_CONST
, 0);
1098 define_start
= define_stack
;
1101 if (setjmp(s1
->error_jmp_buf
) == 0) {
1103 s1
->error_set_jmp_enabled
= 1;
1105 ch
= file
->buf_ptr
[0];
1106 tok_flags
= TOK_FLAG_BOL
| TOK_FLAG_BOF
;
1107 parse_flags
= PARSE_FLAG_PREPROCESS
| PARSE_FLAG_TOK_NUM
;
1111 expect("declaration");
1113 /* end of translation unit info */
1115 put_stabs_r(NULL
, N_SO
, 0, 0,
1116 text_section
->data_offset
, text_section
, section_sym
);
1119 s1
->error_set_jmp_enabled
= 0;
1121 /* reset define stack, but leave -Dsymbols (may be incorrect if
1122 they are undefined) */
1123 free_defines(define_start
);
1125 gen_inline_functions();
1127 sym_pop(&global_stack
, NULL
);
1128 sym_pop(&local_stack
, NULL
);
1130 return s1
->nb_errors
!= 0 ? -1 : 0;
1134 int tcc_compile_string(TCCState
*s
, const char *str
)
1136 BufferedFile bf1
, *bf
= &bf1
;
1140 /* init file structure */
1142 /* XXX: avoid copying */
1144 buf
= tcc_malloc(len
+ 1);
1147 memcpy(buf
, str
, len
);
1150 bf
->buf_end
= buf
+ len
;
1151 pstrcpy(bf
->filename
, sizeof(bf
->filename
), "<string>");
1154 ret
= tcc_compile(s
);
1158 /* currently, no need to close */
1163 /* define a preprocessor symbol. A value can also be provided with the '=' operator */
1164 void tcc_define_symbol(TCCState
*s1
, const char *sym
, const char *value
)
1166 BufferedFile bf1
, *bf
= &bf1
;
1168 pstrcpy(bf
->buffer
, IO_BUF_SIZE
, sym
);
1169 pstrcat(bf
->buffer
, IO_BUF_SIZE
, " ");
1173 pstrcat(bf
->buffer
, IO_BUF_SIZE
, value
);
1175 /* init file structure */
1177 bf
->buf_ptr
= bf
->buffer
;
1178 bf
->buf_end
= bf
->buffer
+ strlen(bf
->buffer
);
1179 *bf
->buf_end
= CH_EOB
;
1180 bf
->filename
[0] = '\0';
1184 s1
->include_stack_ptr
= s1
->include_stack
;
1186 /* parse with define parser */
1187 ch
= file
->buf_ptr
[0];
1193 /* undefine a preprocessor symbol */
1194 void tcc_undefine_symbol(TCCState
*s1
, const char *sym
)
1198 ts
= tok_alloc(sym
, strlen(sym
));
1199 s
= define_find(ts
->tok
);
1200 /* undefine symbol by putting an invalid name */
1205 #ifdef CONFIG_TCC_ASM
1207 #ifdef TCC_TARGET_I386
1208 #include "i386-asm.c"
1213 static void asm_instr(void)
1215 error("inline asm() not supported");
1217 static void asm_global_instr(void)
1219 error("inline asm() not supported");
1225 #ifdef TCC_TARGET_COFF
1226 #include "tcccoff.c"
1229 #ifdef TCC_TARGET_PE
1233 #ifdef CONFIG_TCC_BACKTRACE
1234 /* print the position in the source file of PC value 'pc' by reading
1235 the stabs debug information */
1236 static void rt_printline(unsigned long wanted_pc
)
1238 Stab_Sym
*sym
, *sym_end
;
1239 char func_name
[128], last_func_name
[128];
1240 unsigned long func_addr
, last_pc
, pc
;
1241 const char *incl_files
[INCLUDE_STACK_SIZE
];
1242 int incl_index
, len
, last_line_num
, i
;
1243 const char *str
, *p
;
1245 fprintf(stderr
, "0x%08lx:", wanted_pc
);
1247 func_name
[0] = '\0';
1250 last_func_name
[0] = '\0';
1251 last_pc
= 0xffffffff;
1253 sym
= (Stab_Sym
*)stab_section
->data
+ 1;
1254 sym_end
= (Stab_Sym
*)(stab_section
->data
+ stab_section
->data_offset
);
1255 while (sym
< sym_end
) {
1256 switch(sym
->n_type
) {
1257 /* function start or end */
1259 if (sym
->n_strx
== 0) {
1260 /* we test if between last line and end of function */
1261 pc
= sym
->n_value
+ func_addr
;
1262 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
1264 func_name
[0] = '\0';
1267 str
= stabstr_section
->data
+ sym
->n_strx
;
1268 p
= strchr(str
, ':');
1270 pstrcpy(func_name
, sizeof(func_name
), str
);
1273 if (len
> sizeof(func_name
) - 1)
1274 len
= sizeof(func_name
) - 1;
1275 memcpy(func_name
, str
, len
);
1276 func_name
[len
] = '\0';
1278 func_addr
= sym
->n_value
;
1281 /* line number info */
1283 pc
= sym
->n_value
+ func_addr
;
1284 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
1287 last_line_num
= sym
->n_desc
;
1289 strcpy(last_func_name
, func_name
);
1293 str
= stabstr_section
->data
+ sym
->n_strx
;
1295 if (incl_index
< INCLUDE_STACK_SIZE
) {
1296 incl_files
[incl_index
++] = str
;
1304 if (sym
->n_strx
== 0) {
1305 incl_index
= 0; /* end of translation unit */
1307 str
= stabstr_section
->data
+ sym
->n_strx
;
1308 /* do not add path */
1310 if (len
> 0 && str
[len
- 1] != '/')
1318 /* second pass: we try symtab symbols (no line number info) */
1321 ElfW(Sym
) *sym
, *sym_end
;
1324 sym_end
= (ElfW(Sym
) *)(symtab_section
->data
+ symtab_section
->data_offset
);
1325 for(sym
= (ElfW(Sym
) *)symtab_section
->data
+ 1;
1328 type
= ELFW(ST_TYPE
)(sym
->st_info
);
1329 if (type
== STT_FUNC
) {
1330 if (wanted_pc
>= sym
->st_value
&&
1331 wanted_pc
< sym
->st_value
+ sym
->st_size
) {
1332 pstrcpy(last_func_name
, sizeof(last_func_name
),
1333 strtab_section
->data
+ sym
->st_name
);
1339 /* did not find any info: */
1340 fprintf(stderr
, " ???\n");
1343 if (last_func_name
[0] != '\0') {
1344 fprintf(stderr
, " %s()", last_func_name
);
1346 if (incl_index
> 0) {
1347 fprintf(stderr
, " (%s:%d",
1348 incl_files
[incl_index
- 1], last_line_num
);
1349 for(i
= incl_index
- 2; i
>= 0; i
--)
1350 fprintf(stderr
, ", included from %s", incl_files
[i
]);
1351 fprintf(stderr
, ")");
1353 fprintf(stderr
, "\n");
1357 /* fix for glibc 2.1 */
1363 /* return the PC at frame level 'level'. Return non zero if not found */
1364 static int rt_get_caller_pc(unsigned long *paddr
,
1365 ucontext_t
*uc
, int level
)
1371 #if defined(__FreeBSD__)
1372 *paddr
= uc
->uc_mcontext
.mc_eip
;
1373 #elif defined(__dietlibc__)
1374 *paddr
= uc
->uc_mcontext
.eip
;
1376 *paddr
= uc
->uc_mcontext
.gregs
[REG_EIP
];
1380 #if defined(__FreeBSD__)
1381 fp
= uc
->uc_mcontext
.mc_ebp
;
1382 #elif defined(__dietlibc__)
1383 fp
= uc
->uc_mcontext
.ebp
;
1385 fp
= uc
->uc_mcontext
.gregs
[REG_EBP
];
1387 for(i
=1;i
<level
;i
++) {
1388 /* XXX: check address validity with program info */
1389 if (fp
<= 0x1000 || fp
>= 0xc0000000)
1391 fp
= ((unsigned long *)fp
)[0];
1393 *paddr
= ((unsigned long *)fp
)[1];
1397 #elif defined(__x86_64__)
1398 /* return the PC at frame level 'level'. Return non zero if not found */
1399 static int rt_get_caller_pc(unsigned long *paddr
,
1400 ucontext_t
*uc
, int level
)
1406 /* XXX: only support linux */
1407 *paddr
= uc
->uc_mcontext
.gregs
[REG_RIP
];
1410 fp
= uc
->uc_mcontext
.gregs
[REG_RBP
];
1411 for(i
=1;i
<level
;i
++) {
1412 /* XXX: check address validity with program info */
1415 fp
= ((unsigned long *)fp
)[0];
1417 *paddr
= ((unsigned long *)fp
)[1];
1422 #warning add arch specific rt_get_caller_pc()
1423 static int rt_get_caller_pc(unsigned long *paddr
,
1424 ucontext_t
*uc
, int level
)
1430 /* emit a run time error at position 'pc' */
1431 void rt_error(ucontext_t
*uc
, const char *fmt
, ...)
1438 fprintf(stderr
, "Runtime error: ");
1439 vfprintf(stderr
, fmt
, ap
);
1440 fprintf(stderr
, "\n");
1441 for(i
=0;i
<num_callers
;i
++) {
1442 if (rt_get_caller_pc(&pc
, uc
, i
) < 0)
1445 fprintf(stderr
, "at ");
1447 fprintf(stderr
, "by ");
1454 /* signal handler for fatal errors */
1455 static void sig_error(int signum
, siginfo_t
*siginf
, void *puc
)
1457 ucontext_t
*uc
= puc
;
1461 switch(siginf
->si_code
) {
1464 rt_error(uc
, "division by zero");
1467 rt_error(uc
, "floating point exception");
1473 if (rt_bound_error_msg
&& *rt_bound_error_msg
)
1474 rt_error(uc
, *rt_bound_error_msg
);
1476 rt_error(uc
, "dereferencing invalid pointer");
1479 rt_error(uc
, "illegal instruction");
1482 rt_error(uc
, "abort() called");
1485 rt_error(uc
, "caught signal %d", signum
);
1493 /* copy code into memory passed in by the caller and do all relocations
1494 (needed before using tcc_get_symbol()).
1495 returns -1 on error and required size if ptr is NULL */
1496 int tcc_relocate(TCCState
*s1
, void *ptr
)
1499 unsigned long offset
, length
, mem
;
1502 if (0 == s1
->runtime_added
) {
1503 s1
->runtime_added
= 1;
1505 #ifdef TCC_TARGET_PE
1507 relocate_common_syms();
1508 tcc_add_linker_symbols(s1
);
1510 tcc_add_runtime(s1
);
1511 relocate_common_syms();
1512 tcc_add_linker_symbols(s1
);
1513 build_got_entries(s1
);
1517 offset
= 0, mem
= (unsigned long)ptr
;
1518 for(i
= 1; i
< s1
->nb_sections
; i
++) {
1519 s
= s1
->sections
[i
];
1520 if (0 == (s
->sh_flags
& SHF_ALLOC
))
1522 length
= s
->data_offset
;
1523 s
->sh_addr
= mem
? (mem
+ offset
+ 15) & ~15 : 0;
1524 offset
= (offset
+ length
+ 15) & ~15;
1527 /* relocate symbols */
1528 relocate_syms(s1
, 1);
1532 #ifdef TCC_TARGET_X86_64
1533 s1
->runtime_plt_and_got_offset
= 0;
1534 s1
->runtime_plt_and_got
= (char *)(mem
+ offset
);
1535 /* double the size of the buffer for got and plt entries
1536 XXX: calculate exact size for them? */
1543 /* relocate each section */
1544 for(i
= 1; i
< s1
->nb_sections
; i
++) {
1545 s
= s1
->sections
[i
];
1547 relocate_section(s1
, s
);
1550 for(i
= 1; i
< s1
->nb_sections
; i
++) {
1551 s
= s1
->sections
[i
];
1552 if (0 == (s
->sh_flags
& SHF_ALLOC
))
1554 length
= s
->data_offset
;
1555 // printf("%-12s %08x %04x\n", s->name, s->sh_addr, length);
1556 ptr
= (void*)s
->sh_addr
;
1557 if (NULL
== s
->data
|| s
->sh_type
== SHT_NOBITS
)
1558 memset(ptr
, 0, length
);
1560 memcpy(ptr
, s
->data
, length
);
1561 /* mark executable sections as executable in memory */
1562 if (s
->sh_flags
& SHF_EXECINSTR
)
1563 set_pages_executable(ptr
, length
);
1565 #ifdef TCC_TARGET_X86_64
1566 set_pages_executable(s1
->runtime_plt_and_got
,
1567 s1
->runtime_plt_and_got_offset
);
1572 /* launch the compiled program with the given arguments */
1573 int tcc_run(TCCState
*s1
, int argc
, char **argv
)
1575 int (*prog_main
)(int, char **);
1579 ret
= tcc_relocate(s1
, NULL
);
1582 ptr
= tcc_malloc(ret
);
1583 tcc_relocate(s1
, ptr
);
1585 prog_main
= tcc_get_symbol_err(s1
, "main");
1588 #ifdef CONFIG_TCC_BACKTRACE
1589 struct sigaction sigact
;
1590 /* install TCC signal handlers to print debug info on fatal
1592 sigact
.sa_flags
= SA_SIGINFO
| SA_RESETHAND
;
1593 sigact
.sa_sigaction
= sig_error
;
1594 sigemptyset(&sigact
.sa_mask
);
1595 sigaction(SIGFPE
, &sigact
, NULL
);
1596 sigaction(SIGILL
, &sigact
, NULL
);
1597 sigaction(SIGSEGV
, &sigact
, NULL
);
1598 sigaction(SIGBUS
, &sigact
, NULL
);
1599 sigaction(SIGABRT
, &sigact
, NULL
);
1601 error("debug mode not available");
1605 #ifdef CONFIG_TCC_BCHECK
1606 if (do_bounds_check
) {
1607 void (*bound_init
)(void);
1609 /* set error function */
1610 rt_bound_error_msg
= tcc_get_symbol_err(s1
, "__bound_error_msg");
1612 /* XXX: use .init section so that it also work in binary ? */
1613 bound_init
= (void *)tcc_get_symbol_err(s1
, "__bound_init");
1617 ret
= (*prog_main
)(argc
, argv
);
1622 void tcc_memstats(void)
1625 printf("memory in use: %d\n", mem_cur_size
);
1629 static void tcc_cleanup(void)
1633 if (NULL
== tcc_state
)
1637 /* free -D defines */
1641 n
= tok_ident
- TOK_IDENT
;
1642 for(i
= 0; i
< n
; i
++)
1643 tcc_free(table_ident
[i
]);
1644 tcc_free(table_ident
);
1646 /* free sym_pools */
1647 dynarray_reset(&sym_pools
, &nb_sym_pools
);
1649 cstr_free(&tokcstr
);
1650 /* reset symbol stack */
1651 sym_free_first
= NULL
;
1652 /* cleanup from error/setjmp */
1656 TCCState
*tcc_new(void)
1662 s
= tcc_mallocz(sizeof(TCCState
));
1666 s
->output_type
= TCC_OUTPUT_MEMORY
;
1670 /* we add dummy defines for some special macros to speed up tests
1671 and to have working defined() */
1672 define_push(TOK___LINE__
, MACRO_OBJ
, NULL
, NULL
);
1673 define_push(TOK___FILE__
, MACRO_OBJ
, NULL
, NULL
);
1674 define_push(TOK___DATE__
, MACRO_OBJ
, NULL
, NULL
);
1675 define_push(TOK___TIME__
, MACRO_OBJ
, NULL
, NULL
);
1677 /* standard defines */
1678 tcc_define_symbol(s
, "__STDC__", NULL
);
1679 tcc_define_symbol(s
, "__STDC_VERSION__", "199901L");
1680 #if defined(TCC_TARGET_I386)
1681 tcc_define_symbol(s
, "__i386__", NULL
);
1683 #if defined(TCC_TARGET_X86_64)
1684 tcc_define_symbol(s
, "__x86_64__", NULL
);
1686 #if defined(TCC_TARGET_ARM)
1687 tcc_define_symbol(s
, "__ARM_ARCH_4__", NULL
);
1688 tcc_define_symbol(s
, "__arm_elf__", NULL
);
1689 tcc_define_symbol(s
, "__arm_elf", NULL
);
1690 tcc_define_symbol(s
, "arm_elf", NULL
);
1691 tcc_define_symbol(s
, "__arm__", NULL
);
1692 tcc_define_symbol(s
, "__arm", NULL
);
1693 tcc_define_symbol(s
, "arm", NULL
);
1694 tcc_define_symbol(s
, "__APCS_32__", NULL
);
1696 #ifdef TCC_TARGET_PE
1697 tcc_define_symbol(s
, "_WIN32", NULL
);
1699 tcc_define_symbol(s
, "__unix__", NULL
);
1700 tcc_define_symbol(s
, "__unix", NULL
);
1701 #if defined(__linux)
1702 tcc_define_symbol(s
, "__linux__", NULL
);
1703 tcc_define_symbol(s
, "__linux", NULL
);
1706 /* tiny C specific defines */
1707 tcc_define_symbol(s
, "__TINYC__", NULL
);
1709 /* tiny C & gcc defines */
1710 tcc_define_symbol(s
, "__SIZE_TYPE__", "unsigned int");
1711 tcc_define_symbol(s
, "__PTRDIFF_TYPE__", "int");
1712 #ifdef TCC_TARGET_PE
1713 tcc_define_symbol(s
, "__WCHAR_TYPE__", "unsigned short");
1715 tcc_define_symbol(s
, "__WCHAR_TYPE__", "int");
1718 #ifndef TCC_TARGET_PE
1719 /* default library paths */
1720 tcc_add_library_path(s
, CONFIG_SYSROOT
"/usr/local/lib");
1721 tcc_add_library_path(s
, CONFIG_SYSROOT
"/usr/lib");
1722 tcc_add_library_path(s
, CONFIG_SYSROOT
"/lib");
1725 /* no section zero */
1726 dynarray_add((void ***)&s
->sections
, &s
->nb_sections
, NULL
);
1728 /* create standard sections */
1729 text_section
= new_section(s
, ".text", SHT_PROGBITS
, SHF_ALLOC
| SHF_EXECINSTR
);
1730 data_section
= new_section(s
, ".data", SHT_PROGBITS
, SHF_ALLOC
| SHF_WRITE
);
1731 bss_section
= new_section(s
, ".bss", SHT_NOBITS
, SHF_ALLOC
| SHF_WRITE
);
1733 /* symbols are always generated for linking stage */
1734 symtab_section
= new_symtab(s
, ".symtab", SHT_SYMTAB
, 0,
1736 ".hashtab", SHF_PRIVATE
);
1737 strtab_section
= symtab_section
->link
;
1739 /* private symbol table for dynamic symbols */
1740 s
->dynsymtab_section
= new_symtab(s
, ".dynsymtab", SHT_SYMTAB
, SHF_PRIVATE
,
1742 ".dynhashtab", SHF_PRIVATE
);
1743 s
->alacarte_link
= 1;
1745 #ifdef CHAR_IS_UNSIGNED
1746 s
->char_is_unsigned
= 1;
1748 #if defined(TCC_TARGET_PE) && 0
1749 /* XXX: currently the PE linker is not ready to support that */
1750 s
->leading_underscore
= 1;
1755 void tcc_delete(TCCState
*s1
)
1761 /* free all sections */
1762 for(i
= 1; i
< s1
->nb_sections
; i
++)
1763 free_section(s1
->sections
[i
]);
1764 dynarray_reset(&s1
->sections
, &s1
->nb_sections
);
1766 for(i
= 0; i
< s1
->nb_priv_sections
; i
++)
1767 free_section(s1
->priv_sections
[i
]);
1768 dynarray_reset(&s1
->priv_sections
, &s1
->nb_priv_sections
);
1770 /* free any loaded DLLs */
1771 for ( i
= 0; i
< s1
->nb_loaded_dlls
; i
++) {
1772 DLLReference
*ref
= s1
->loaded_dlls
[i
];
1774 dlclose(ref
->handle
);
1777 /* free loaded dlls array */
1778 dynarray_reset(&s1
->loaded_dlls
, &s1
->nb_loaded_dlls
);
1780 /* free library paths */
1781 dynarray_reset(&s1
->library_paths
, &s1
->nb_library_paths
);
1783 /* free include paths */
1784 dynarray_reset(&s1
->cached_includes
, &s1
->nb_cached_includes
);
1785 dynarray_reset(&s1
->include_paths
, &s1
->nb_include_paths
);
1786 dynarray_reset(&s1
->sysinclude_paths
, &s1
->nb_sysinclude_paths
);
1791 int tcc_add_include_path(TCCState
*s1
, const char *pathname
)
1795 pathname1
= tcc_strdup(pathname
);
1796 dynarray_add((void ***)&s1
->include_paths
, &s1
->nb_include_paths
, pathname1
);
1800 int tcc_add_sysinclude_path(TCCState
*s1
, const char *pathname
)
1804 pathname1
= tcc_strdup(pathname
);
1805 dynarray_add((void ***)&s1
->sysinclude_paths
, &s1
->nb_sysinclude_paths
, pathname1
);
1809 static int tcc_add_file_internal(TCCState
*s1
, const char *filename
, int flags
)
1814 BufferedFile
*saved_file
;
1816 /* find source file type with extension */
1817 ext
= tcc_fileextension(filename
);
1823 file
= tcc_open(s1
, filename
);
1825 if (flags
& AFF_PRINT_ERROR
) {
1826 error_noabort("file '%s' not found", filename
);
1832 if (flags
& AFF_PREPROCESS
) {
1833 ret
= tcc_preprocess(s1
);
1834 } else if (!ext
[0] || !PATHCMP(ext
, "c")) {
1835 /* C file assumed */
1836 ret
= tcc_compile(s1
);
1838 #ifdef CONFIG_TCC_ASM
1839 if (!strcmp(ext
, "S")) {
1840 /* preprocessed assembler */
1841 ret
= tcc_assemble(s1
, 1);
1842 } else if (!strcmp(ext
, "s")) {
1843 /* non preprocessed assembler */
1844 ret
= tcc_assemble(s1
, 0);
1847 #ifdef TCC_TARGET_PE
1848 if (!PATHCMP(ext
, "def")) {
1849 ret
= pe_load_def_file(s1
, file
->fd
);
1854 /* assume executable format: auto guess file type */
1855 ret
= read(fd
, &ehdr
, sizeof(ehdr
));
1856 lseek(fd
, 0, SEEK_SET
);
1858 error_noabort("could not read header");
1860 } else if (ret
!= sizeof(ehdr
)) {
1861 goto try_load_script
;
1864 if (ehdr
.e_ident
[0] == ELFMAG0
&&
1865 ehdr
.e_ident
[1] == ELFMAG1
&&
1866 ehdr
.e_ident
[2] == ELFMAG2
&&
1867 ehdr
.e_ident
[3] == ELFMAG3
) {
1868 file
->line_num
= 0; /* do not display line number if error */
1869 if (ehdr
.e_type
== ET_REL
) {
1870 ret
= tcc_load_object_file(s1
, fd
, 0);
1871 } else if (ehdr
.e_type
== ET_DYN
) {
1872 if (s1
->output_type
== TCC_OUTPUT_MEMORY
) {
1873 #ifdef TCC_TARGET_PE
1877 h
= dlopen(filename
, RTLD_GLOBAL
| RTLD_LAZY
);
1884 ret
= tcc_load_dll(s1
, fd
, filename
,
1885 (flags
& AFF_REFERENCED_DLL
) != 0);
1888 error_noabort("unrecognized ELF file");
1891 } else if (memcmp((char *)&ehdr
, ARMAG
, 8) == 0) {
1892 file
->line_num
= 0; /* do not display line number if error */
1893 ret
= tcc_load_archive(s1
, fd
);
1895 #ifdef TCC_TARGET_COFF
1896 if (*(uint16_t *)(&ehdr
) == COFF_C67_MAGIC
) {
1897 ret
= tcc_load_coff(s1
, fd
);
1900 #ifdef TCC_TARGET_PE
1901 if (pe_test_res_file(&ehdr
, ret
)) {
1902 ret
= pe_load_res_file(s1
, fd
);
1906 /* as GNU ld, consider it is an ld script if not recognized */
1908 ret
= tcc_load_ldscript(s1
);
1910 error_noabort("unrecognized file type");
1925 int tcc_add_file(TCCState
*s
, const char *filename
)
1927 return tcc_add_file_internal(s
, filename
, AFF_PRINT_ERROR
);
1930 int tcc_add_library_path(TCCState
*s
, const char *pathname
)
1934 pathname1
= tcc_strdup(pathname
);
1935 dynarray_add((void ***)&s
->library_paths
, &s
->nb_library_paths
, pathname1
);
1939 /* find and load a dll. Return non zero if not found */
1940 /* XXX: add '-rpath' option support ? */
1941 static int tcc_add_dll(TCCState
*s
, const char *filename
, int flags
)
1946 for(i
= 0; i
< s
->nb_library_paths
; i
++) {
1947 snprintf(buf
, sizeof(buf
), "%s/%s",
1948 s
->library_paths
[i
], filename
);
1949 if (tcc_add_file_internal(s
, buf
, flags
) == 0)
1955 /* the library name is the same as the argument of the '-l' option */
1956 int tcc_add_library(TCCState
*s
, const char *libraryname
)
1961 /* first we look for the dynamic library if not static linking */
1962 if (!s
->static_link
) {
1963 #ifdef TCC_TARGET_PE
1964 snprintf(buf
, sizeof(buf
), "%s.def", libraryname
);
1966 snprintf(buf
, sizeof(buf
), "lib%s.so", libraryname
);
1968 if (tcc_add_dll(s
, buf
, 0) == 0)
1972 /* then we look for the static library */
1973 for(i
= 0; i
< s
->nb_library_paths
; i
++) {
1974 snprintf(buf
, sizeof(buf
), "%s/lib%s.a",
1975 s
->library_paths
[i
], libraryname
);
1976 if (tcc_add_file_internal(s
, buf
, 0) == 0)
1982 int tcc_add_symbol(TCCState
*s
, const char *name
, void *val
)
1984 add_elf_sym(symtab_section
, (unsigned long)val
, 0,
1985 ELFW(ST_INFO
)(STB_GLOBAL
, STT_NOTYPE
), 0,
1990 int tcc_set_output_type(TCCState
*s
, int output_type
)
1994 s
->output_type
= output_type
;
1997 /* default include paths */
1998 /* XXX: reverse order needed if -isystem support */
1999 #ifndef TCC_TARGET_PE
2000 tcc_add_sysinclude_path(s
, CONFIG_SYSROOT
"/usr/local/include");
2001 tcc_add_sysinclude_path(s
, CONFIG_SYSROOT
"/usr/include");
2003 snprintf(buf
, sizeof(buf
), "%s/include", tcc_lib_path
);
2004 tcc_add_sysinclude_path(s
, buf
);
2005 #ifdef TCC_TARGET_PE
2006 snprintf(buf
, sizeof(buf
), "%s/include/winapi", tcc_lib_path
);
2007 tcc_add_sysinclude_path(s
, buf
);
2011 /* if bound checking, then add corresponding sections */
2012 #ifdef CONFIG_TCC_BCHECK
2013 if (do_bounds_check
) {
2015 tcc_define_symbol(s
, "__BOUNDS_CHECKING_ON", NULL
);
2016 /* create bounds sections */
2017 bounds_section
= new_section(s
, ".bounds",
2018 SHT_PROGBITS
, SHF_ALLOC
);
2019 lbounds_section
= new_section(s
, ".lbounds",
2020 SHT_PROGBITS
, SHF_ALLOC
);
2024 if (s
->char_is_unsigned
) {
2025 tcc_define_symbol(s
, "__CHAR_UNSIGNED__", NULL
);
2028 /* add debug sections */
2031 stab_section
= new_section(s
, ".stab", SHT_PROGBITS
, 0);
2032 stab_section
->sh_entsize
= sizeof(Stab_Sym
);
2033 stabstr_section
= new_section(s
, ".stabstr", SHT_STRTAB
, 0);
2034 put_elf_str(stabstr_section
, "");
2035 stab_section
->link
= stabstr_section
;
2036 /* put first entry */
2037 put_stabs("", 0, 0, 0, 0);
2040 /* add libc crt1/crti objects */
2041 #ifndef TCC_TARGET_PE
2042 if ((output_type
== TCC_OUTPUT_EXE
|| output_type
== TCC_OUTPUT_DLL
) &&
2044 if (output_type
!= TCC_OUTPUT_DLL
)
2045 tcc_add_file(s
, CONFIG_TCC_CRT_PREFIX
"/crt1.o");
2046 tcc_add_file(s
, CONFIG_TCC_CRT_PREFIX
"/crti.o");
2050 #ifdef TCC_TARGET_PE
2051 snprintf(buf
, sizeof(buf
), "%s/lib", tcc_lib_path
);
2052 tcc_add_library_path(s
, buf
);
2058 #define WD_ALL 0x0001 /* warning is activated when using -Wall */
2059 #define FD_INVERT 0x0002 /* invert value before storing */
2061 typedef struct FlagDef
{
2067 static const FlagDef warning_defs
[] = {
2068 { offsetof(TCCState
, warn_unsupported
), 0, "unsupported" },
2069 { offsetof(TCCState
, warn_write_strings
), 0, "write-strings" },
2070 { offsetof(TCCState
, warn_error
), 0, "error" },
2071 { offsetof(TCCState
, warn_implicit_function_declaration
), WD_ALL
,
2072 "implicit-function-declaration" },
2075 static int set_flag(TCCState
*s
, const FlagDef
*flags
, int nb_flags
,
2076 const char *name
, int value
)
2083 if (r
[0] == 'n' && r
[1] == 'o' && r
[2] == '-') {
2087 for(i
= 0, p
= flags
; i
< nb_flags
; i
++, p
++) {
2088 if (!strcmp(r
, p
->name
))
2093 if (p
->flags
& FD_INVERT
)
2095 *(int *)((uint8_t *)s
+ p
->offset
) = value
;
2100 /* set/reset a warning */
2101 int tcc_set_warning(TCCState
*s
, const char *warning_name
, int value
)
2106 if (!strcmp(warning_name
, "all")) {
2107 for(i
= 0, p
= warning_defs
; i
< countof(warning_defs
); i
++, p
++) {
2108 if (p
->flags
& WD_ALL
)
2109 *(int *)((uint8_t *)s
+ p
->offset
) = 1;
2113 return set_flag(s
, warning_defs
, countof(warning_defs
),
2114 warning_name
, value
);
2118 static const FlagDef flag_defs
[] = {
2119 { offsetof(TCCState
, char_is_unsigned
), 0, "unsigned-char" },
2120 { offsetof(TCCState
, char_is_unsigned
), FD_INVERT
, "signed-char" },
2121 { offsetof(TCCState
, nocommon
), FD_INVERT
, "common" },
2122 { offsetof(TCCState
, leading_underscore
), 0, "leading-underscore" },
2125 /* set/reset a flag */
2126 int tcc_set_flag(TCCState
*s
, const char *flag_name
, int value
)
2128 return set_flag(s
, flag_defs
, countof(flag_defs
),
2132 /* set CONFIG_TCCDIR at runtime */
2133 void tcc_set_lib_path(TCCState
*s
, const char *path
)
2135 tcc_lib_path
= tcc_strdup(path
);