win32: enable bounds checker & exception handler
[tinycc.git] / libtcc.c
blob7ef1f0b4365d287527cf5910f143020f74e319a2
1 /*
2 * TCC - Tiny C Compiler
3 *
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
21 #include "tcc.h"
23 /********************************************************/
24 /* global variables */
26 /* display benchmark infos */
27 int total_lines;
28 int total_bytes;
30 /* parser */
31 static struct BufferedFile *file;
32 static int ch, tok;
33 static CValue tokc;
34 static CString tokcstr; /* current parsed string, if any */
35 /* additional informations about token */
36 static int tok_flags;
37 #define TOK_FLAG_BOL 0x0001 /* beginning of line before */
38 #define TOK_FLAG_BOF 0x0002 /* beginning of file before */
39 #define TOK_FLAG_ENDIF 0x0004 /* a endif was found matching starting #ifdef */
40 #define TOK_FLAG_EOF 0x0008 /* end of file */
42 static int *macro_ptr, *macro_ptr_allocated;
43 static int *unget_saved_macro_ptr;
44 static int unget_saved_buffer[TOK_MAX_SIZE + 1];
45 static int unget_buffer_enabled;
46 static int parse_flags;
47 #define PARSE_FLAG_PREPROCESS 0x0001 /* activate preprocessing */
48 #define PARSE_FLAG_TOK_NUM 0x0002 /* return numbers instead of TOK_PPNUM */
49 #define PARSE_FLAG_LINEFEED 0x0004 /* line feed is returned as a
50 token. line feed is also
51 returned at eof */
52 #define PARSE_FLAG_ASM_COMMENTS 0x0008 /* '#' can be used for line comment */
53 #define PARSE_FLAG_SPACES 0x0010 /* next() returns space tokens (for -E) */
55 static Section *text_section, *data_section, *bss_section; /* predefined sections */
56 static Section *cur_text_section; /* current section where function code is
57 generated */
58 #ifdef CONFIG_TCC_ASM
59 static Section *last_text_section; /* to handle .previous asm directive */
60 #endif
62 #ifdef CONFIG_TCC_BCHECK
63 /* bound check related sections */
64 static Section *bounds_section; /* contains global data bound description */
65 static Section *lbounds_section; /* contains local data bound description */
66 #endif
68 /* symbol sections */
69 static Section *symtab_section, *strtab_section;
71 /* debug sections */
72 static Section *stab_section, *stabstr_section;
74 /* loc : local variable index
75 ind : output code index
76 rsym: return symbol
77 anon_sym: anonymous symbol index
79 static int rsym, anon_sym, ind, loc;
80 /* expression generation modifiers */
81 static int const_wanted; /* true if constant wanted */
82 static int nocode_wanted; /* true if no code generation wanted for an expression */
83 static int global_expr; /* true if compound literals must be allocated
84 globally (used during initializers parsing */
85 static CType func_vt; /* current function return type (used by return
86 instruction) */
87 static int func_vc;
88 static int last_line_num, last_ind, func_ind; /* debug last line number and pc */
89 static int tok_ident;
90 static TokenSym **table_ident;
91 static TokenSym *hash_ident[TOK_HASH_SIZE];
92 static char token_buf[STRING_MAX_SIZE + 1];
93 static char *funcname;
94 static Sym *global_stack, *local_stack;
95 static Sym *define_stack;
96 static Sym *global_label_stack, *local_label_stack;
97 /* symbol allocator */
98 #define SYM_POOL_NB (8192 / sizeof(Sym))
99 static Sym *sym_free_first;
100 static void **sym_pools;
101 static int nb_sym_pools;
103 static SValue vstack[VSTACK_SIZE], *vtop;
104 /* some predefined types */
105 static CType char_pointer_type, func_old_type, int_type;
107 /* use GNU C extensions */
108 static int gnu_ext = 1;
110 /* use Tiny C extensions */
111 static int tcc_ext = 1;
113 /* max number of callers shown if error */
114 #ifdef CONFIG_TCC_BACKTRACE
115 int num_callers = 6;
116 void *rt_prog_main;
117 const char **rt_bound_error_msg;
118 #endif
120 /* XXX: get rid of this ASAP */
121 static struct TCCState *tcc_state;
123 /********************************************************/
124 /* function prototypes */
126 /* tccpp.c */
127 static void next(void);
128 char *get_tok_str(int v, CValue *cv);
130 /* tccgen.c */
131 static void parse_expr_type(CType *type);
132 static void expr_type(CType *type);
133 static void unary_type(CType *type);
134 static void block(int *bsym, int *csym, int *case_sym, int *def_sym,
135 int case_reg, int is_expr);
136 static int expr_const(void);
137 static void expr_eq(void);
138 static void gexpr(void);
139 static void gen_inline_functions(void);
140 static void decl(int l);
141 static void decl_initializer(CType *type, Section *sec, unsigned long c,
142 int first, int size_only);
143 static void decl_initializer_alloc(CType *type, AttributeDef *ad, int r,
144 int has_init, int v, int scope);
145 int gv(int rc);
146 void gv2(int rc1, int rc2);
147 void move_reg(int r, int s);
148 void save_regs(int n);
149 void save_reg(int r);
150 void vpop(void);
151 void vswap(void);
152 void vdup(void);
153 int get_reg(int rc);
154 int get_reg_ex(int rc,int rc2);
156 void gen_op(int op);
157 void force_charshort_cast(int t);
158 static void gen_cast(CType *type);
159 void vstore(void);
160 static Sym *sym_find(int v);
161 static Sym *sym_push(int v, CType *type, int r, int c);
163 /* type handling */
164 static int type_size(CType *type, int *a);
165 static inline CType *pointed_type(CType *type);
166 static int pointed_size(CType *type);
167 static int lvalue_type(int t);
168 static int parse_btype(CType *type, AttributeDef *ad);
169 static void type_decl(CType *type, AttributeDef *ad, int *v, int td);
170 static int compare_types(CType *type1, CType *type2, int unqualified);
171 static int is_compatible_types(CType *type1, CType *type2);
172 static int is_compatible_parameter_types(CType *type1, CType *type2);
174 int ieee_finite(double d);
175 void vpushi(int v);
176 void vpushll(long long v);
177 void vrott(int n);
178 void vnrott(int n);
179 void lexpand_nr(void);
180 static void vpush_global_sym(CType *type, int v);
181 void vset(CType *type, int r, int v);
182 void type_to_str(char *buf, int buf_size,
183 CType *type, const char *varstr);
184 static Sym *get_sym_ref(CType *type, Section *sec,
185 unsigned long offset, unsigned long size);
186 static Sym *external_global_sym(int v, CType *type, int r);
188 /* section generation */
189 static void section_realloc(Section *sec, unsigned long new_size);
190 static void *section_ptr_add(Section *sec, unsigned long size);
191 static void put_extern_sym(Sym *sym, Section *section,
192 unsigned long value, unsigned long size);
193 static void greloc(Section *s, Sym *sym, unsigned long addr, int type);
194 static int put_elf_str(Section *s, const char *sym);
195 static int put_elf_sym(Section *s,
196 unsigned long value, unsigned long size,
197 int info, int other, int shndx, const char *name);
198 static int add_elf_sym(Section *s, uplong value, unsigned long size,
199 int info, int other, int sh_num, const char *name);
200 static void put_elf_reloc(Section *symtab, Section *s, unsigned long offset,
201 int type, int symbol);
202 static void put_stabs(const char *str, int type, int other, int desc,
203 unsigned long value);
204 static void put_stabs_r(const char *str, int type, int other, int desc,
205 unsigned long value, Section *sec, int sym_index);
206 static void put_stabn(int type, int other, int desc, int value);
207 static void put_stabd(int type, int other, int desc);
208 static int tcc_add_dll(TCCState *s, const char *filename, int flags);
210 #define AFF_PRINT_ERROR 0x0001 /* print error if file not found */
211 #define AFF_REFERENCED_DLL 0x0002 /* load a referenced dll from another dll */
212 #define AFF_PREPROCESS 0x0004 /* preprocess file */
213 static int tcc_add_file_internal(TCCState *s, const char *filename, int flags);
215 /* tcccoff.c */
216 int tcc_output_coff(TCCState *s1, FILE *f);
218 /* tccpe.c */
219 int pe_load_file(struct TCCState *s1, const char *filename, int fd);
220 int pe_output_file(struct TCCState *s1, const char *filename);
221 int pe_dllimport(int r, SValue *sv, void (*fn)(int r, SValue *sv));
223 /* tccasm.c */
224 #ifdef CONFIG_TCC_ASM
225 static void asm_expr(TCCState *s1, ExprValue *pe);
226 static int asm_int_expr(TCCState *s1);
227 static int find_constraint(ASMOperand *operands, int nb_operands,
228 const char *name, const char **pp);
230 static int tcc_assemble(TCCState *s1, int do_preprocess);
231 #endif
233 static void asm_instr(void);
234 static void asm_global_instr(void);
236 /********************************************************/
237 /* libtcc.c */
239 static Sym *__sym_malloc(void);
240 static inline Sym *sym_malloc(void);
241 static inline void sym_free(Sym *sym);
242 Section *new_section(TCCState *s1, const char *name, int sh_type, int sh_flags);
243 static void free_section(Section *s);
244 static void section_realloc(Section *sec, unsigned long new_size);
245 static void *section_ptr_add(Section *sec, unsigned long size);
246 Section *find_section(TCCState *s1, const char *name);
247 static void put_extern_sym2(
248 Sym *sym, Section *section,
249 unsigned long value, unsigned long size, int can_add_underscore);
250 static void put_extern_sym(
251 Sym *sym, Section *section,
252 unsigned long value, unsigned long size);
253 static void greloc(Section *s, Sym *sym, unsigned long offset, int type);
255 static void strcat_vprintf(char *buf, int buf_size, const char *fmt, va_list ap);
256 static void strcat_printf(char *buf, int buf_size, const char *fmt, ...);
258 /* CString handling */
259 static void cstr_realloc(CString *cstr, int new_size);
260 static inline void cstr_ccat(CString *cstr, int ch);
261 static void cstr_cat(CString *cstr, const char *str);
262 static void cstr_wccat(CString *cstr, int ch);
263 static void cstr_new(CString *cstr);
264 static void cstr_free(CString *cstr);
265 #define cstr_reset(cstr) cstr_free(cstr)
266 static void add_char(CString *cstr, int c);
268 static Sym *sym_push2(Sym **ps, int v, int t, long c);
269 static Sym *sym_find2(Sym *s, int v);
270 static inline Sym *struct_find(int v);
271 static inline Sym *sym_find(int v);
272 static Sym *sym_push(int v, CType *type, int r, int c);
273 static Sym *global_identifier_push(int v, int t, int c);
274 static void sym_pop(Sym **ptop, Sym *b);
276 BufferedFile *tcc_open(TCCState *s1, const char *filename);
277 void tcc_close(BufferedFile *bf);
278 static int tcc_compile(TCCState *s1);
280 void expect(const char *msg);
281 void skip(int c);
282 static void test_lvalue(void);
283 void *resolve_sym(TCCState *s1, const char *sym);
285 static inline int isid(int c)
287 return (c >= 'a' && c <= 'z')
288 || (c >= 'A' && c <= 'Z')
289 || c == '_';
292 static inline int isnum(int c)
294 return c >= '0' && c <= '9';
297 static inline int isoct(int c)
299 return c >= '0' && c <= '7';
302 static inline int toup(int c)
304 if (c >= 'a' && c <= 'z')
305 return c - 'a' + 'A';
306 else
307 return c;
310 /********************************************************/
312 #ifdef TCC_TARGET_I386
313 #include "i386-gen.c"
314 #endif
316 #ifdef TCC_TARGET_ARM
317 #include "arm-gen.c"
318 #endif
320 #ifdef TCC_TARGET_C67
321 #include "c67-gen.c"
322 #endif
324 #ifdef TCC_TARGET_X86_64
325 #include "x86_64-gen.c"
326 #endif
328 #include "tccpp.c"
329 #include "tccgen.c"
331 #ifdef CONFIG_TCC_ASM
333 #if defined TCC_TARGET_I386 || defined TCC_TARGET_X86_64
334 #include "i386-asm.c"
335 #endif
337 #include "tccasm.c"
338 #else
339 static void asm_instr(void)
341 error("inline asm() not supported");
343 static void asm_global_instr(void)
345 error("inline asm() not supported");
347 #endif
349 #include "tccelf.c"
351 #ifdef TCC_TARGET_COFF
352 #include "tcccoff.c"
353 #endif
355 #ifdef TCC_TARGET_PE
356 #include "tccpe.c"
357 #endif
359 #include "tccrun.c"
361 /********************************************************/
362 #ifdef _WIN32
363 char *normalize_slashes(char *path)
365 char *p;
366 for (p = path; *p; ++p)
367 if (*p == '\\')
368 *p = '/';
369 return path;
372 HMODULE tcc_module;
374 /* on win32, we suppose the lib and includes are at the location of 'tcc.exe' */
375 void tcc_set_lib_path_w32(TCCState *s)
377 char path[1024], *p;
378 GetModuleFileNameA(tcc_module, path, sizeof path);
379 p = tcc_basename(normalize_slashes(strlwr(path)));
380 if (p - 5 > path && 0 == strncmp(p - 5, "/bin/", 5))
381 p -= 5;
382 else if (p > path)
383 p--;
384 *p = 0;
385 tcc_set_lib_path(s, path);
388 #ifdef LIBTCC_AS_DLL
389 BOOL WINAPI DllMain (HANDLE hDll, DWORD dwReason, LPVOID lpReserved)
391 if (DLL_PROCESS_ATTACH == dwReason)
392 tcc_module = hDll;
393 return TRUE;
395 #endif
396 #endif
398 /********************************************************/
400 /* we use our own 'finite' function to avoid potential problems with
401 non standard math libs */
402 /* XXX: endianness dependent */
403 int ieee_finite(double d)
405 int *p = (int *)&d;
406 return ((unsigned)((p[1] | 0x800fffff) + 1)) >> 31;
409 /* copy a string and truncate it. */
410 char *pstrcpy(char *buf, int buf_size, const char *s)
412 char *q, *q_end;
413 int c;
415 if (buf_size > 0) {
416 q = buf;
417 q_end = buf + buf_size - 1;
418 while (q < q_end) {
419 c = *s++;
420 if (c == '\0')
421 break;
422 *q++ = c;
424 *q = '\0';
426 return buf;
429 /* strcat and truncate. */
430 char *pstrcat(char *buf, int buf_size, const char *s)
432 int len;
433 len = strlen(buf);
434 if (len < buf_size)
435 pstrcpy(buf + len, buf_size - len, s);
436 return buf;
439 /* extract the basename of a file */
440 char *tcc_basename(const char *name)
442 char *p = strchr(name, 0);
443 while (p > name && !IS_PATHSEP(p[-1]))
444 --p;
445 return p;
448 char *tcc_fileextension (const char *name)
450 char *b = tcc_basename(name);
451 char *e = strrchr(b, '.');
452 return e ? e : strchr(b, 0);
455 /* memory management */
456 #ifdef MEM_DEBUG
457 int mem_cur_size;
458 int mem_max_size;
459 unsigned malloc_usable_size(void*);
460 #endif
462 void tcc_free(void *ptr)
464 #ifdef MEM_DEBUG
465 mem_cur_size -= malloc_usable_size(ptr);
466 #endif
467 free(ptr);
470 void *tcc_malloc(unsigned long size)
472 void *ptr;
473 ptr = malloc(size);
474 if (!ptr && size)
475 error("memory full");
476 #ifdef MEM_DEBUG
477 mem_cur_size += malloc_usable_size(ptr);
478 if (mem_cur_size > mem_max_size)
479 mem_max_size = mem_cur_size;
480 #endif
481 return ptr;
484 void *tcc_mallocz(unsigned long size)
486 void *ptr;
487 ptr = tcc_malloc(size);
488 memset(ptr, 0, size);
489 return ptr;
492 void *tcc_realloc(void *ptr, unsigned long size)
494 void *ptr1;
495 #ifdef MEM_DEBUG
496 mem_cur_size -= malloc_usable_size(ptr);
497 #endif
498 ptr1 = realloc(ptr, size);
499 #ifdef MEM_DEBUG
500 /* NOTE: count not correct if alloc error, but not critical */
501 mem_cur_size += malloc_usable_size(ptr1);
502 if (mem_cur_size > mem_max_size)
503 mem_max_size = mem_cur_size;
504 #endif
505 return ptr1;
508 char *tcc_strdup(const char *str)
510 char *ptr;
511 ptr = tcc_malloc(strlen(str) + 1);
512 strcpy(ptr, str);
513 return ptr;
516 void tcc_memstats(void)
518 #ifdef MEM_DEBUG
519 printf("memory in use: %d\n", mem_cur_size);
520 #endif
523 #define free(p) use_tcc_free(p)
524 #define malloc(s) use_tcc_malloc(s)
525 #define realloc(p, s) use_tcc_realloc(p, s)
527 void dynarray_add(void ***ptab, int *nb_ptr, void *data)
529 int nb, nb_alloc;
530 void **pp;
532 nb = *nb_ptr;
533 pp = *ptab;
534 /* every power of two we double array size */
535 if ((nb & (nb - 1)) == 0) {
536 if (!nb)
537 nb_alloc = 1;
538 else
539 nb_alloc = nb * 2;
540 pp = tcc_realloc(pp, nb_alloc * sizeof(void *));
541 if (!pp)
542 error("memory full");
543 *ptab = pp;
545 pp[nb++] = data;
546 *nb_ptr = nb;
549 void dynarray_reset(void *pp, int *n)
551 void **p;
552 for (p = *(void***)pp; *n; ++p, --*n)
553 if (*p)
554 tcc_free(*p);
555 tcc_free(*(void**)pp);
556 *(void**)pp = NULL;
559 /* symbol allocator */
560 static Sym *__sym_malloc(void)
562 Sym *sym_pool, *sym, *last_sym;
563 int i;
565 sym_pool = tcc_malloc(SYM_POOL_NB * sizeof(Sym));
566 dynarray_add(&sym_pools, &nb_sym_pools, sym_pool);
568 last_sym = sym_free_first;
569 sym = sym_pool;
570 for(i = 0; i < SYM_POOL_NB; i++) {
571 sym->next = last_sym;
572 last_sym = sym;
573 sym++;
575 sym_free_first = last_sym;
576 return last_sym;
579 static inline Sym *sym_malloc(void)
581 Sym *sym;
582 sym = sym_free_first;
583 if (!sym)
584 sym = __sym_malloc();
585 sym_free_first = sym->next;
586 return sym;
589 static inline void sym_free(Sym *sym)
591 sym->next = sym_free_first;
592 sym_free_first = sym;
595 Section *new_section(TCCState *s1, const char *name, int sh_type, int sh_flags)
597 Section *sec;
599 sec = tcc_mallocz(sizeof(Section) + strlen(name));
600 strcpy(sec->name, name);
601 sec->sh_type = sh_type;
602 sec->sh_flags = sh_flags;
603 switch(sh_type) {
604 case SHT_HASH:
605 case SHT_REL:
606 case SHT_RELA:
607 case SHT_DYNSYM:
608 case SHT_SYMTAB:
609 case SHT_DYNAMIC:
610 sec->sh_addralign = 4;
611 break;
612 case SHT_STRTAB:
613 sec->sh_addralign = 1;
614 break;
615 default:
616 sec->sh_addralign = 32; /* default conservative alignment */
617 break;
620 if (sh_flags & SHF_PRIVATE) {
621 dynarray_add((void ***)&s1->priv_sections, &s1->nb_priv_sections, sec);
622 } else {
623 sec->sh_num = s1->nb_sections;
624 dynarray_add((void ***)&s1->sections, &s1->nb_sections, sec);
627 return sec;
630 static void free_section(Section *s)
632 tcc_free(s->data);
635 /* realloc section and set its content to zero */
636 static void section_realloc(Section *sec, unsigned long new_size)
638 unsigned long size;
639 unsigned char *data;
641 size = sec->data_allocated;
642 if (size == 0)
643 size = 1;
644 while (size < new_size)
645 size = size * 2;
646 data = tcc_realloc(sec->data, size);
647 if (!data)
648 error("memory full");
649 memset(data + sec->data_allocated, 0, size - sec->data_allocated);
650 sec->data = data;
651 sec->data_allocated = size;
654 /* reserve at least 'size' bytes in section 'sec' from
655 sec->data_offset. */
656 static void *section_ptr_add(Section *sec, unsigned long size)
658 unsigned long offset, offset1;
660 offset = sec->data_offset;
661 offset1 = offset + size;
662 if (offset1 > sec->data_allocated)
663 section_realloc(sec, offset1);
664 sec->data_offset = offset1;
665 return sec->data + offset;
668 /* return a reference to a section, and create it if it does not
669 exists */
670 Section *find_section(TCCState *s1, const char *name)
672 Section *sec;
673 int i;
674 for(i = 1; i < s1->nb_sections; i++) {
675 sec = s1->sections[i];
676 if (!strcmp(name, sec->name))
677 return sec;
679 /* sections are created as PROGBITS */
680 return new_section(s1, name, SHT_PROGBITS, SHF_ALLOC);
683 /* update sym->c so that it points to an external symbol in section
684 'section' with value 'value' */
685 static void put_extern_sym2(Sym *sym, Section *section,
686 unsigned long value, unsigned long size,
687 int can_add_underscore)
689 int sym_type, sym_bind, sh_num, info, other, attr;
690 ElfW(Sym) *esym;
691 const char *name;
692 char buf1[256];
694 if (section == NULL)
695 sh_num = SHN_UNDEF;
696 else if (section == SECTION_ABS)
697 sh_num = SHN_ABS;
698 else
699 sh_num = section->sh_num;
701 other = attr = 0;
703 if ((sym->type.t & VT_BTYPE) == VT_FUNC) {
704 sym_type = STT_FUNC;
705 #ifdef TCC_TARGET_PE
706 if (sym->type.ref)
707 attr = sym->type.ref->r;
708 if (FUNC_EXPORT(attr))
709 other |= 1;
710 if (FUNC_CALL(attr) == FUNC_STDCALL)
711 other |= 2;
712 #endif
713 } else if ((sym->type.t & VT_BTYPE) == VT_VOID) {
714 sym_type = STT_NOTYPE;
715 } else {
716 sym_type = STT_OBJECT;
717 #ifdef TCC_TARGET_PE
718 if (sym->type.t & VT_EXPORT)
719 other |= 1;
720 #endif
723 if (sym->type.t & VT_STATIC)
724 sym_bind = STB_LOCAL;
725 else
726 sym_bind = STB_GLOBAL;
728 if (!sym->c) {
729 name = get_tok_str(sym->v, NULL);
730 #ifdef CONFIG_TCC_BCHECK
731 if (tcc_state->do_bounds_check) {
732 char buf[32];
734 /* XXX: avoid doing that for statics ? */
735 /* if bound checking is activated, we change some function
736 names by adding the "__bound" prefix */
737 switch(sym->v) {
738 #ifdef TCC_TARGET_PE
739 /* XXX: we rely only on malloc hooks */
740 case TOK_malloc:
741 case TOK_free:
742 case TOK_realloc:
743 case TOK_memalign:
744 case TOK_calloc:
745 #endif
746 case TOK_memcpy:
747 case TOK_memmove:
748 case TOK_memset:
749 case TOK_strlen:
750 case TOK_strcpy:
751 case TOK_alloca:
752 strcpy(buf, "__bound_");
753 strcat(buf, name);
754 name = buf;
755 break;
758 #endif
760 #ifdef TCC_TARGET_PE
761 if ((other & 2) && can_add_underscore) {
762 sprintf(buf1, "_%s@%d", name, FUNC_ARGS(attr));
763 name = buf1;
764 } else
765 #endif
766 if (tcc_state->leading_underscore && can_add_underscore) {
767 buf1[0] = '_';
768 pstrcpy(buf1 + 1, sizeof(buf1) - 1, name);
769 name = buf1;
771 info = ELFW(ST_INFO)(sym_bind, sym_type);
772 sym->c = add_elf_sym(symtab_section, value, size, info, other, sh_num, name);
773 } else {
774 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
775 esym->st_value = value;
776 esym->st_size = size;
777 esym->st_shndx = sh_num;
778 esym->st_other |= other;
782 static void put_extern_sym(Sym *sym, Section *section,
783 unsigned long value, unsigned long size)
785 put_extern_sym2(sym, section, value, size, 1);
788 /* add a new relocation entry to symbol 'sym' in section 's' */
789 static void greloc(Section *s, Sym *sym, unsigned long offset, int type)
791 int c = 0;
792 if (sym) {
793 if (0 == sym->c)
794 put_extern_sym(sym, NULL, 0, 0);
795 c = sym->c;
797 /* now we can add ELF relocation info */
798 put_elf_reloc(symtab_section, s, offset, type, c);
801 static void strcat_vprintf(char *buf, int buf_size, const char *fmt, va_list ap)
803 int len;
804 len = strlen(buf);
805 vsnprintf(buf + len, buf_size - len, fmt, ap);
808 static void strcat_printf(char *buf, int buf_size, const char *fmt, ...)
810 va_list ap;
811 va_start(ap, fmt);
812 strcat_vprintf(buf, buf_size, fmt, ap);
813 va_end(ap);
816 void error1(TCCState *s1, int is_warning, const char *fmt, va_list ap)
818 char buf[2048];
819 BufferedFile **f;
821 buf[0] = '\0';
822 if (file) {
823 for(f = s1->include_stack; f < s1->include_stack_ptr; f++)
824 strcat_printf(buf, sizeof(buf), "In file included from %s:%d:\n",
825 (*f)->filename, (*f)->line_num);
826 if (file->line_num > 0) {
827 strcat_printf(buf, sizeof(buf),
828 "%s:%d: ", file->filename, file->line_num);
829 } else {
830 strcat_printf(buf, sizeof(buf),
831 "%s: ", file->filename);
833 } else {
834 strcat_printf(buf, sizeof(buf),
835 "tcc: ");
837 if (is_warning)
838 strcat_printf(buf, sizeof(buf), "warning: ");
839 else
840 strcat_printf(buf, sizeof(buf), "error: ");
841 strcat_vprintf(buf, sizeof(buf), fmt, ap);
843 if (!s1->error_func) {
844 /* default case: stderr */
845 fprintf(stderr, "%s\n", buf);
846 } else {
847 s1->error_func(s1->error_opaque, buf);
849 if (!is_warning || s1->warn_error)
850 s1->nb_errors++;
853 void tcc_set_error_func(TCCState *s, void *error_opaque,
854 void (*error_func)(void *opaque, const char *msg))
856 s->error_opaque = error_opaque;
857 s->error_func = error_func;
860 /* error without aborting current compilation */
861 void error_noabort(const char *fmt, ...)
863 TCCState *s1 = tcc_state;
864 va_list ap;
866 va_start(ap, fmt);
867 error1(s1, 0, fmt, ap);
868 va_end(ap);
871 void error(const char *fmt, ...)
873 TCCState *s1 = tcc_state;
874 va_list ap;
876 va_start(ap, fmt);
877 error1(s1, 0, fmt, ap);
878 va_end(ap);
879 /* better than nothing: in some cases, we accept to handle errors */
880 if (s1->error_set_jmp_enabled) {
881 longjmp(s1->error_jmp_buf, 1);
882 } else {
883 /* XXX: eliminate this someday */
884 exit(1);
888 void expect(const char *msg)
890 error("%s expected", msg);
893 void warning(const char *fmt, ...)
895 TCCState *s1 = tcc_state;
896 va_list ap;
898 if (s1->warn_none)
899 return;
901 va_start(ap, fmt);
902 error1(s1, 1, fmt, ap);
903 va_end(ap);
906 void skip(int c)
908 if (tok != c)
909 error("'%c' expected", c);
910 next();
913 static void test_lvalue(void)
915 if (!(vtop->r & VT_LVAL))
916 expect("lvalue");
919 /* CString handling */
921 static void cstr_realloc(CString *cstr, int new_size)
923 int size;
924 void *data;
926 size = cstr->size_allocated;
927 if (size == 0)
928 size = 8; /* no need to allocate a too small first string */
929 while (size < new_size)
930 size = size * 2;
931 data = tcc_realloc(cstr->data_allocated, size);
932 if (!data)
933 error("memory full");
934 cstr->data_allocated = data;
935 cstr->size_allocated = size;
936 cstr->data = data;
939 /* add a byte */
940 static inline void cstr_ccat(CString *cstr, int ch)
942 int size;
943 size = cstr->size + 1;
944 if (size > cstr->size_allocated)
945 cstr_realloc(cstr, size);
946 ((unsigned char *)cstr->data)[size - 1] = ch;
947 cstr->size = size;
950 static void cstr_cat(CString *cstr, const char *str)
952 int c;
953 for(;;) {
954 c = *str;
955 if (c == '\0')
956 break;
957 cstr_ccat(cstr, c);
958 str++;
962 /* add a wide char */
963 static void cstr_wccat(CString *cstr, int ch)
965 int size;
966 size = cstr->size + sizeof(nwchar_t);
967 if (size > cstr->size_allocated)
968 cstr_realloc(cstr, size);
969 *(nwchar_t *)(((unsigned char *)cstr->data) + size - sizeof(nwchar_t)) = ch;
970 cstr->size = size;
973 static void cstr_new(CString *cstr)
975 memset(cstr, 0, sizeof(CString));
978 /* free string and reset it to NULL */
979 static void cstr_free(CString *cstr)
981 tcc_free(cstr->data_allocated);
982 cstr_new(cstr);
985 #define cstr_reset(cstr) cstr_free(cstr)
987 /* XXX: unicode ? */
988 static void add_char(CString *cstr, int c)
990 if (c == '\'' || c == '\"' || c == '\\') {
991 /* XXX: could be more precise if char or string */
992 cstr_ccat(cstr, '\\');
994 if (c >= 32 && c <= 126) {
995 cstr_ccat(cstr, c);
996 } else {
997 cstr_ccat(cstr, '\\');
998 if (c == '\n') {
999 cstr_ccat(cstr, 'n');
1000 } else {
1001 cstr_ccat(cstr, '0' + ((c >> 6) & 7));
1002 cstr_ccat(cstr, '0' + ((c >> 3) & 7));
1003 cstr_ccat(cstr, '0' + (c & 7));
1008 /* push, without hashing */
1009 static Sym *sym_push2(Sym **ps, int v, int t, long c)
1011 Sym *s;
1012 s = sym_malloc();
1013 s->v = v;
1014 s->type.t = t;
1015 s->type.ref = NULL;
1016 #ifdef _WIN64
1017 s->d = NULL;
1018 #endif
1019 s->c = c;
1020 s->next = NULL;
1021 /* add in stack */
1022 s->prev = *ps;
1023 *ps = s;
1024 return s;
1027 /* find a symbol and return its associated structure. 's' is the top
1028 of the symbol stack */
1029 static Sym *sym_find2(Sym *s, int v)
1031 while (s) {
1032 if (s->v == v)
1033 return s;
1034 s = s->prev;
1036 return NULL;
1039 /* structure lookup */
1040 static inline Sym *struct_find(int v)
1042 v -= TOK_IDENT;
1043 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1044 return NULL;
1045 return table_ident[v]->sym_struct;
1048 /* find an identifier */
1049 static inline Sym *sym_find(int v)
1051 v -= TOK_IDENT;
1052 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1053 return NULL;
1054 return table_ident[v]->sym_identifier;
1057 /* push a given symbol on the symbol stack */
1058 static Sym *sym_push(int v, CType *type, int r, int c)
1060 Sym *s, **ps;
1061 TokenSym *ts;
1063 if (local_stack)
1064 ps = &local_stack;
1065 else
1066 ps = &global_stack;
1067 s = sym_push2(ps, v, type->t, c);
1068 s->type.ref = type->ref;
1069 s->r = r;
1070 /* don't record fields or anonymous symbols */
1071 /* XXX: simplify */
1072 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
1073 /* record symbol in token array */
1074 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
1075 if (v & SYM_STRUCT)
1076 ps = &ts->sym_struct;
1077 else
1078 ps = &ts->sym_identifier;
1079 s->prev_tok = *ps;
1080 *ps = s;
1082 return s;
1085 /* push a global identifier */
1086 static Sym *global_identifier_push(int v, int t, int c)
1088 Sym *s, **ps;
1089 s = sym_push2(&global_stack, v, t, c);
1090 /* don't record anonymous symbol */
1091 if (v < SYM_FIRST_ANOM) {
1092 ps = &table_ident[v - TOK_IDENT]->sym_identifier;
1093 /* modify the top most local identifier, so that
1094 sym_identifier will point to 's' when popped */
1095 while (*ps != NULL)
1096 ps = &(*ps)->prev_tok;
1097 s->prev_tok = NULL;
1098 *ps = s;
1100 return s;
1103 /* pop symbols until top reaches 'b' */
1104 static void sym_pop(Sym **ptop, Sym *b)
1106 Sym *s, *ss, **ps;
1107 TokenSym *ts;
1108 int v;
1110 s = *ptop;
1111 while(s != b) {
1112 ss = s->prev;
1113 v = s->v;
1114 /* remove symbol in token array */
1115 /* XXX: simplify */
1116 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
1117 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
1118 if (v & SYM_STRUCT)
1119 ps = &ts->sym_struct;
1120 else
1121 ps = &ts->sym_identifier;
1122 *ps = s->prev_tok;
1124 sym_free(s);
1125 s = ss;
1127 *ptop = b;
1130 /* I/O layer */
1132 BufferedFile *tcc_open(TCCState *s1, const char *filename)
1134 int fd;
1135 BufferedFile *bf;
1137 if (strcmp(filename, "-") == 0)
1138 fd = 0, filename = "stdin";
1139 else
1140 fd = open(filename, O_RDONLY | O_BINARY);
1141 if ((s1->verbose == 2 && fd >= 0) || s1->verbose == 3)
1142 printf("%s %*s%s\n", fd < 0 ? "nf":"->",
1143 (int)(s1->include_stack_ptr - s1->include_stack), "", filename);
1144 if (fd < 0)
1145 return NULL;
1146 bf = tcc_malloc(sizeof(BufferedFile));
1147 bf->fd = fd;
1148 bf->buf_ptr = bf->buffer;
1149 bf->buf_end = bf->buffer;
1150 bf->buffer[0] = CH_EOB; /* put eob symbol */
1151 pstrcpy(bf->filename, sizeof(bf->filename), filename);
1152 #ifdef _WIN32
1153 normalize_slashes(bf->filename);
1154 #endif
1155 bf->line_num = 1;
1156 bf->ifndef_macro = 0;
1157 bf->ifdef_stack_ptr = s1->ifdef_stack_ptr;
1158 // printf("opening '%s'\n", filename);
1159 return bf;
1162 void tcc_close(BufferedFile *bf)
1164 total_lines += bf->line_num;
1165 close(bf->fd);
1166 tcc_free(bf);
1169 /* compile the C file opened in 'file'. Return non zero if errors. */
1170 static int tcc_compile(TCCState *s1)
1172 Sym *define_start;
1173 char buf[512];
1174 volatile int section_sym;
1176 #ifdef INC_DEBUG
1177 printf("%s: **** new file\n", file->filename);
1178 #endif
1179 preprocess_init(s1);
1181 cur_text_section = NULL;
1182 funcname = "";
1183 anon_sym = SYM_FIRST_ANOM;
1185 /* file info: full path + filename */
1186 section_sym = 0; /* avoid warning */
1187 if (s1->do_debug) {
1188 section_sym = put_elf_sym(symtab_section, 0, 0,
1189 ELFW(ST_INFO)(STB_LOCAL, STT_SECTION), 0,
1190 text_section->sh_num, NULL);
1191 getcwd(buf, sizeof(buf));
1192 #ifdef _WIN32
1193 normalize_slashes(buf);
1194 #endif
1195 pstrcat(buf, sizeof(buf), "/");
1196 put_stabs_r(buf, N_SO, 0, 0,
1197 text_section->data_offset, text_section, section_sym);
1198 put_stabs_r(file->filename, N_SO, 0, 0,
1199 text_section->data_offset, text_section, section_sym);
1201 /* an elf symbol of type STT_FILE must be put so that STB_LOCAL
1202 symbols can be safely used */
1203 put_elf_sym(symtab_section, 0, 0,
1204 ELFW(ST_INFO)(STB_LOCAL, STT_FILE), 0,
1205 SHN_ABS, file->filename);
1207 /* define some often used types */
1208 int_type.t = VT_INT;
1210 char_pointer_type.t = VT_BYTE;
1211 mk_pointer(&char_pointer_type);
1213 func_old_type.t = VT_FUNC;
1214 func_old_type.ref = sym_push(SYM_FIELD, &int_type, FUNC_CDECL, FUNC_OLD);
1216 #if defined(TCC_ARM_EABI) && defined(TCC_ARM_VFP)
1217 float_type.t = VT_FLOAT;
1218 double_type.t = VT_DOUBLE;
1220 func_float_type.t = VT_FUNC;
1221 func_float_type.ref = sym_push(SYM_FIELD, &float_type, FUNC_CDECL, FUNC_OLD);
1222 func_double_type.t = VT_FUNC;
1223 func_double_type.ref = sym_push(SYM_FIELD, &double_type, FUNC_CDECL, FUNC_OLD);
1224 #endif
1226 #if 0
1227 /* define 'void *alloca(unsigned int)' builtin function */
1229 Sym *s1;
1231 p = anon_sym++;
1232 sym = sym_push(p, mk_pointer(VT_VOID), FUNC_CDECL, FUNC_NEW);
1233 s1 = sym_push(SYM_FIELD, VT_UNSIGNED | VT_INT, 0, 0);
1234 s1->next = NULL;
1235 sym->next = s1;
1236 sym_push(TOK_alloca, VT_FUNC | (p << VT_STRUCT_SHIFT), VT_CONST, 0);
1238 #endif
1240 define_start = define_stack;
1241 nocode_wanted = 1;
1243 if (setjmp(s1->error_jmp_buf) == 0) {
1244 s1->nb_errors = 0;
1245 s1->error_set_jmp_enabled = 1;
1247 ch = file->buf_ptr[0];
1248 tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
1249 parse_flags = PARSE_FLAG_PREPROCESS | PARSE_FLAG_TOK_NUM;
1250 next();
1251 decl(VT_CONST);
1252 if (tok != TOK_EOF)
1253 expect("declaration");
1255 /* end of translation unit info */
1256 if (s1->do_debug) {
1257 put_stabs_r(NULL, N_SO, 0, 0,
1258 text_section->data_offset, text_section, section_sym);
1261 s1->error_set_jmp_enabled = 0;
1263 /* reset define stack, but leave -Dsymbols (may be incorrect if
1264 they are undefined) */
1265 free_defines(define_start);
1267 gen_inline_functions();
1269 sym_pop(&global_stack, NULL);
1270 sym_pop(&local_stack, NULL);
1272 return s1->nb_errors != 0 ? -1 : 0;
1275 int tcc_compile_string(TCCState *s, const char *str)
1277 BufferedFile bf1, *bf = &bf1;
1278 int ret, len;
1279 char *buf;
1281 /* init file structure */
1282 bf->fd = -1;
1283 /* XXX: avoid copying */
1284 len = strlen(str);
1285 buf = tcc_malloc(len + 1);
1286 if (!buf)
1287 return -1;
1288 memcpy(buf, str, len);
1289 buf[len] = CH_EOB;
1290 bf->buf_ptr = buf;
1291 bf->buf_end = buf + len;
1292 pstrcpy(bf->filename, sizeof(bf->filename), "<string>");
1293 bf->line_num = 1;
1294 file = bf;
1295 ret = tcc_compile(s);
1296 file = NULL;
1297 tcc_free(buf);
1299 /* currently, no need to close */
1300 return ret;
1303 /* define a preprocessor symbol. A value can also be provided with the '=' operator */
1304 void tcc_define_symbol(TCCState *s1, const char *sym, const char *value)
1306 BufferedFile bf1, *bf = &bf1;
1308 pstrcpy(bf->buffer, IO_BUF_SIZE, sym);
1309 pstrcat(bf->buffer, IO_BUF_SIZE, " ");
1310 /* default value */
1311 if (!value)
1312 value = "1";
1313 pstrcat(bf->buffer, IO_BUF_SIZE, value);
1315 /* init file structure */
1316 bf->fd = -1;
1317 bf->buf_ptr = bf->buffer;
1318 bf->buf_end = bf->buffer + strlen(bf->buffer);
1319 *bf->buf_end = CH_EOB;
1320 bf->filename[0] = '\0';
1321 bf->line_num = 1;
1322 file = bf;
1324 s1->include_stack_ptr = s1->include_stack;
1326 /* parse with define parser */
1327 ch = file->buf_ptr[0];
1328 next_nomacro();
1329 parse_define();
1330 file = NULL;
1333 /* undefine a preprocessor symbol */
1334 void tcc_undefine_symbol(TCCState *s1, const char *sym)
1336 TokenSym *ts;
1337 Sym *s;
1338 ts = tok_alloc(sym, strlen(sym));
1339 s = define_find(ts->tok);
1340 /* undefine symbol by putting an invalid name */
1341 if (s)
1342 define_undef(s);
1345 static void tcc_cleanup(void)
1347 int i, n;
1349 if (NULL == tcc_state)
1350 return;
1351 tcc_state = NULL;
1353 /* free -D defines */
1354 free_defines(NULL);
1356 /* free tokens */
1357 n = tok_ident - TOK_IDENT;
1358 for(i = 0; i < n; i++)
1359 tcc_free(table_ident[i]);
1360 tcc_free(table_ident);
1362 /* free sym_pools */
1363 dynarray_reset(&sym_pools, &nb_sym_pools);
1364 /* string buffer */
1365 cstr_free(&tokcstr);
1366 /* reset symbol stack */
1367 sym_free_first = NULL;
1368 /* cleanup from error/setjmp */
1369 macro_ptr = NULL;
1372 TCCState *tcc_new(void)
1374 TCCState *s;
1375 char buffer[100];
1376 int a,b,c;
1378 tcc_cleanup();
1380 s = tcc_mallocz(sizeof(TCCState));
1381 if (!s)
1382 return NULL;
1383 tcc_state = s;
1384 #ifdef _WIN32
1385 tcc_set_lib_path_w32(s);
1386 #else
1387 tcc_set_lib_path(s, CONFIG_TCCDIR);
1388 #endif
1389 s->output_type = TCC_OUTPUT_MEMORY;
1390 preprocess_new();
1392 /* we add dummy defines for some special macros to speed up tests
1393 and to have working defined() */
1394 define_push(TOK___LINE__, MACRO_OBJ, NULL, NULL);
1395 define_push(TOK___FILE__, MACRO_OBJ, NULL, NULL);
1396 define_push(TOK___DATE__, MACRO_OBJ, NULL, NULL);
1397 define_push(TOK___TIME__, MACRO_OBJ, NULL, NULL);
1399 /* standard defines */
1400 tcc_define_symbol(s, "__STDC__", NULL);
1401 tcc_define_symbol(s, "__STDC_VERSION__", "199901L");
1402 #if defined(TCC_TARGET_I386)
1403 tcc_define_symbol(s, "__i386__", "1");
1404 tcc_define_symbol(s, "__i386", "1");
1405 tcc_define_symbol(s, "i386", "1");
1406 #endif
1407 #if defined(TCC_TARGET_X86_64)
1408 tcc_define_symbol(s, "__x86_64__", NULL);
1409 #endif
1410 #if defined(TCC_TARGET_ARM)
1411 tcc_define_symbol(s, "__ARM_ARCH_4__", NULL);
1412 tcc_define_symbol(s, "__arm_elf__", NULL);
1413 tcc_define_symbol(s, "__arm_elf", NULL);
1414 tcc_define_symbol(s, "arm_elf", NULL);
1415 tcc_define_symbol(s, "__arm__", NULL);
1416 tcc_define_symbol(s, "__arm", NULL);
1417 tcc_define_symbol(s, "arm", NULL);
1418 tcc_define_symbol(s, "__APCS_32__", NULL);
1419 #endif
1420 #ifdef TCC_TARGET_PE
1421 tcc_define_symbol(s, "_WIN32", NULL);
1422 #ifdef TCC_TARGET_X86_64
1423 tcc_define_symbol(s, "_WIN64", NULL);
1424 #endif
1425 #else
1426 tcc_define_symbol(s, "__unix__", "1");
1427 tcc_define_symbol(s, "__unix", "1");
1428 tcc_define_symbol(s, "unix", "1");
1429 #if defined(__FreeBSD__)
1430 #define str(s) #s
1431 tcc_define_symbol(s, "__FreeBSD__", str( __FreeBSD__));
1432 tcc_define_symbol(s, "__INTEL_COMPILER", "1");
1433 #undef str
1434 #endif
1435 #if defined(__linux)
1436 tcc_define_symbol(s, "__linux__", NULL);
1437 tcc_define_symbol(s, "__linux", NULL);
1438 #endif
1439 #endif
1440 /* tiny C specific defines */
1441 sscanf(TCC_VERSION, "%d.%d.%d", &a, &b, &c);
1442 sprintf(buffer, "%d", a*10000 + b*100 + c);
1443 tcc_define_symbol(s, "__TINYC__", buffer);
1445 /* tiny C & gcc defines */
1446 tcc_define_symbol(s, "__SIZE_TYPE__", "unsigned long");
1447 tcc_define_symbol(s, "__PTRDIFF_TYPE__", "long");
1448 #ifdef TCC_TARGET_PE
1449 tcc_define_symbol(s, "__WCHAR_TYPE__", "unsigned short");
1450 #else
1451 tcc_define_symbol(s, "__WCHAR_TYPE__", "int");
1452 #endif
1454 #ifndef TCC_TARGET_PE
1455 /* default library paths */
1456 tcc_add_library_path(s, CONFIG_SYSROOT "/usr/local/lib");
1457 tcc_add_library_path(s, CONFIG_SYSROOT "/usr/lib");
1458 tcc_add_library_path(s, CONFIG_SYSROOT "/lib");
1459 #endif
1461 /* no section zero */
1462 dynarray_add((void ***)&s->sections, &s->nb_sections, NULL);
1464 /* create standard sections */
1465 text_section = new_section(s, ".text", SHT_PROGBITS, SHF_ALLOC | SHF_EXECINSTR);
1466 data_section = new_section(s, ".data", SHT_PROGBITS, SHF_ALLOC | SHF_WRITE);
1467 bss_section = new_section(s, ".bss", SHT_NOBITS, SHF_ALLOC | SHF_WRITE);
1469 /* symbols are always generated for linking stage */
1470 symtab_section = new_symtab(s, ".symtab", SHT_SYMTAB, 0,
1471 ".strtab",
1472 ".hashtab", SHF_PRIVATE);
1473 strtab_section = symtab_section->link;
1475 /* private symbol table for dynamic symbols */
1476 s->dynsymtab_section = new_symtab(s, ".dynsymtab", SHT_SYMTAB, SHF_PRIVATE,
1477 ".dynstrtab",
1478 ".dynhashtab", SHF_PRIVATE);
1479 s->alacarte_link = 1;
1481 #ifdef CHAR_IS_UNSIGNED
1482 s->char_is_unsigned = 1;
1483 #endif
1484 #if defined(TCC_TARGET_PE) && 0
1485 /* XXX: currently the PE linker is not ready to support that */
1486 s->leading_underscore = 1;
1487 #endif
1489 if (s->section_align == 0)
1490 s->section_align = ELF_PAGE_SIZE;
1492 #ifdef TCC_TARGET_I386
1493 s->seg_size = 32;
1494 #endif
1495 return s;
1498 void tcc_delete(TCCState *s1)
1500 int i;
1502 tcc_cleanup();
1504 /* free all sections */
1505 for(i = 1; i < s1->nb_sections; i++)
1506 free_section(s1->sections[i]);
1507 dynarray_reset(&s1->sections, &s1->nb_sections);
1509 for(i = 0; i < s1->nb_priv_sections; i++)
1510 free_section(s1->priv_sections[i]);
1511 dynarray_reset(&s1->priv_sections, &s1->nb_priv_sections);
1513 /* free any loaded DLLs */
1514 for ( i = 0; i < s1->nb_loaded_dlls; i++) {
1515 DLLReference *ref = s1->loaded_dlls[i];
1516 if ( ref->handle )
1517 dlclose(ref->handle);
1520 /* free loaded dlls array */
1521 dynarray_reset(&s1->loaded_dlls, &s1->nb_loaded_dlls);
1523 /* free library paths */
1524 dynarray_reset(&s1->library_paths, &s1->nb_library_paths);
1526 /* free include paths */
1527 dynarray_reset(&s1->cached_includes, &s1->nb_cached_includes);
1528 dynarray_reset(&s1->include_paths, &s1->nb_include_paths);
1529 dynarray_reset(&s1->sysinclude_paths, &s1->nb_sysinclude_paths);
1531 tcc_free(s1->tcc_lib_path);
1532 tcc_free(s1->runtime_mem);
1533 tcc_free(s1);
1536 int tcc_add_include_path(TCCState *s1, const char *pathname)
1538 char *pathname1;
1540 pathname1 = tcc_strdup(pathname);
1541 dynarray_add((void ***)&s1->include_paths, &s1->nb_include_paths, pathname1);
1542 return 0;
1545 int tcc_add_sysinclude_path(TCCState *s1, const char *pathname)
1547 char *pathname1;
1549 pathname1 = tcc_strdup(pathname);
1550 dynarray_add((void ***)&s1->sysinclude_paths, &s1->nb_sysinclude_paths, pathname1);
1551 return 0;
1554 static int tcc_add_file_internal(TCCState *s1, const char *filename, int flags)
1556 const char *ext;
1557 ElfW(Ehdr) ehdr;
1558 int fd, ret, size;
1559 BufferedFile *saved_file;
1561 ret = -1;
1563 /* find source file type with extension */
1564 ext = tcc_fileextension(filename);
1565 if (ext[0])
1566 ext++;
1568 /* open the file */
1569 saved_file = file;
1570 file = tcc_open(s1, filename);
1571 if (!file) {
1572 if (flags & AFF_PRINT_ERROR)
1573 error_noabort("file '%s' not found", filename);
1574 goto the_end;
1577 if (flags & AFF_PREPROCESS) {
1578 ret = tcc_preprocess(s1);
1579 goto the_end;
1582 if (!ext[0] || !PATHCMP(ext, "c")) {
1583 /* C file assumed */
1584 ret = tcc_compile(s1);
1585 goto the_end;
1588 #ifdef CONFIG_TCC_ASM
1589 if (!strcmp(ext, "S")) {
1590 /* preprocessed assembler */
1591 ret = tcc_assemble(s1, 1);
1592 goto the_end;
1595 if (!strcmp(ext, "s")) {
1596 /* non preprocessed assembler */
1597 ret = tcc_assemble(s1, 0);
1598 goto the_end;
1600 #endif
1602 fd = file->fd;
1603 /* assume executable format: auto guess file type */
1604 size = read(fd, &ehdr, sizeof(ehdr));
1605 lseek(fd, 0, SEEK_SET);
1606 if (size <= 0) {
1607 error_noabort("could not read header");
1608 goto the_end;
1611 if (size == sizeof(ehdr) &&
1612 ehdr.e_ident[0] == ELFMAG0 &&
1613 ehdr.e_ident[1] == ELFMAG1 &&
1614 ehdr.e_ident[2] == ELFMAG2 &&
1615 ehdr.e_ident[3] == ELFMAG3) {
1617 /* do not display line number if error */
1618 file->line_num = 0;
1619 if (ehdr.e_type == ET_REL) {
1620 ret = tcc_load_object_file(s1, fd, 0);
1621 goto the_end;
1624 #ifndef TCC_TARGET_PE
1625 if (ehdr.e_type == ET_DYN) {
1626 if (s1->output_type == TCC_OUTPUT_MEMORY) {
1627 void *h;
1628 h = dlopen(filename, RTLD_GLOBAL | RTLD_LAZY);
1629 if (h)
1630 ret = 0;
1631 } else {
1632 ret = tcc_load_dll(s1, fd, filename,
1633 (flags & AFF_REFERENCED_DLL) != 0);
1635 goto the_end;
1637 #endif
1638 error_noabort("unrecognized ELF file");
1639 goto the_end;
1642 if (memcmp((char *)&ehdr, ARMAG, 8) == 0) {
1643 file->line_num = 0; /* do not display line number if error */
1644 ret = tcc_load_archive(s1, fd);
1645 goto the_end;
1648 #ifdef TCC_TARGET_COFF
1649 if (*(uint16_t *)(&ehdr) == COFF_C67_MAGIC) {
1650 ret = tcc_load_coff(s1, fd);
1651 goto the_end;
1653 #endif
1655 #ifdef TCC_TARGET_PE
1656 ret = pe_load_file(s1, filename, fd);
1657 #else
1658 /* as GNU ld, consider it is an ld script if not recognized */
1659 ret = tcc_load_ldscript(s1);
1660 #endif
1661 if (ret < 0)
1662 error_noabort("unrecognized file type");
1664 the_end:
1665 if (file)
1666 tcc_close(file);
1667 file = saved_file;
1668 return ret;
1671 int tcc_add_file(TCCState *s, const char *filename)
1673 if (s->output_type == TCC_OUTPUT_PREPROCESS)
1674 return tcc_add_file_internal(s, filename, AFF_PRINT_ERROR | AFF_PREPROCESS);
1675 else
1676 return tcc_add_file_internal(s, filename, AFF_PRINT_ERROR);
1679 int tcc_add_library_path(TCCState *s, const char *pathname)
1681 char *pathname1;
1683 pathname1 = tcc_strdup(pathname);
1684 dynarray_add((void ***)&s->library_paths, &s->nb_library_paths, pathname1);
1685 return 0;
1688 /* find and load a dll. Return non zero if not found */
1689 /* XXX: add '-rpath' option support ? */
1690 static int tcc_add_dll(TCCState *s, const char *filename, int flags)
1692 char buf[1024];
1693 int i;
1695 for(i = 0; i < s->nb_library_paths; i++) {
1696 snprintf(buf, sizeof(buf), "%s/%s",
1697 s->library_paths[i], filename);
1698 if (tcc_add_file_internal(s, buf, flags) == 0)
1699 return 0;
1701 return -1;
1704 /* the library name is the same as the argument of the '-l' option */
1705 int tcc_add_library(TCCState *s, const char *libraryname)
1707 char buf[1024];
1708 int i;
1710 /* first we look for the dynamic library if not static linking */
1711 if (!s->static_link) {
1712 #ifdef TCC_TARGET_PE
1713 if (pe_add_dll(s, libraryname) == 0)
1714 return 0;
1715 #else
1716 snprintf(buf, sizeof(buf), "lib%s.so", libraryname);
1717 if (tcc_add_dll(s, buf, 0) == 0)
1718 return 0;
1719 #endif
1721 /* then we look for the static library */
1722 for(i = 0; i < s->nb_library_paths; i++) {
1723 snprintf(buf, sizeof(buf), "%s/lib%s.a",
1724 s->library_paths[i], libraryname);
1725 if (tcc_add_file_internal(s, buf, 0) == 0)
1726 return 0;
1728 return -1;
1731 int tcc_add_symbol(TCCState *s, const char *name, void *val)
1733 add_elf_sym(symtab_section, (uplong)val, 0,
1734 ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE), 0,
1735 SHN_ABS, name);
1736 return 0;
1739 int tcc_set_output_type(TCCState *s, int output_type)
1741 char buf[1024];
1743 s->output_type = output_type;
1745 if (!s->nostdinc) {
1746 /* default include paths */
1747 /* XXX: reverse order needed if -isystem support */
1748 #ifndef TCC_TARGET_PE
1749 tcc_add_sysinclude_path(s, CONFIG_SYSROOT "/usr/local/include");
1750 tcc_add_sysinclude_path(s, CONFIG_SYSROOT "/usr/include");
1751 #endif
1752 snprintf(buf, sizeof(buf), "%s/include", s->tcc_lib_path);
1753 tcc_add_sysinclude_path(s, buf);
1754 #ifdef TCC_TARGET_PE
1755 snprintf(buf, sizeof(buf), "%s/include/winapi", s->tcc_lib_path);
1756 tcc_add_sysinclude_path(s, buf);
1757 #endif
1760 /* if bound checking, then add corresponding sections */
1761 #ifdef CONFIG_TCC_BCHECK
1762 if (s->do_bounds_check) {
1763 /* define symbol */
1764 tcc_define_symbol(s, "__BOUNDS_CHECKING_ON", NULL);
1765 /* create bounds sections */
1766 bounds_section = new_section(s, ".bounds",
1767 SHT_PROGBITS, SHF_ALLOC);
1768 lbounds_section = new_section(s, ".lbounds",
1769 SHT_PROGBITS, SHF_ALLOC);
1771 #endif
1773 if (s->char_is_unsigned) {
1774 tcc_define_symbol(s, "__CHAR_UNSIGNED__", NULL);
1777 /* add debug sections */
1778 if (s->do_debug) {
1779 /* stab symbols */
1780 stab_section = new_section(s, ".stab", SHT_PROGBITS, 0);
1781 stab_section->sh_entsize = sizeof(Stab_Sym);
1782 stabstr_section = new_section(s, ".stabstr", SHT_STRTAB, 0);
1783 put_elf_str(stabstr_section, "");
1784 stab_section->link = stabstr_section;
1785 /* put first entry */
1786 put_stabs("", 0, 0, 0, 0);
1789 /* add libc crt1/crti objects */
1790 #ifndef TCC_TARGET_PE
1791 if ((output_type == TCC_OUTPUT_EXE || output_type == TCC_OUTPUT_DLL) &&
1792 !s->nostdlib) {
1793 if (output_type != TCC_OUTPUT_DLL)
1794 tcc_add_file(s, CONFIG_TCC_CRT_PREFIX "/crt1.o");
1795 tcc_add_file(s, CONFIG_TCC_CRT_PREFIX "/crti.o");
1797 #endif
1799 #ifdef TCC_TARGET_PE
1800 snprintf(buf, sizeof(buf), "%s/lib", s->tcc_lib_path);
1801 tcc_add_library_path(s, buf);
1802 #ifdef _WIN32
1803 if (GetSystemDirectory(buf, sizeof buf))
1804 tcc_add_library_path(s, buf);
1805 #endif
1806 #endif
1808 return 0;
1811 #define WD_ALL 0x0001 /* warning is activated when using -Wall */
1812 #define FD_INVERT 0x0002 /* invert value before storing */
1814 typedef struct FlagDef {
1815 uint16_t offset;
1816 uint16_t flags;
1817 const char *name;
1818 } FlagDef;
1820 static const FlagDef warning_defs[] = {
1821 { offsetof(TCCState, warn_unsupported), 0, "unsupported" },
1822 { offsetof(TCCState, warn_write_strings), 0, "write-strings" },
1823 { offsetof(TCCState, warn_error), 0, "error" },
1824 { offsetof(TCCState, warn_implicit_function_declaration), WD_ALL,
1825 "implicit-function-declaration" },
1828 static int set_flag(TCCState *s, const FlagDef *flags, int nb_flags,
1829 const char *name, int value)
1831 int i;
1832 const FlagDef *p;
1833 const char *r;
1835 r = name;
1836 if (r[0] == 'n' && r[1] == 'o' && r[2] == '-') {
1837 r += 3;
1838 value = !value;
1840 for(i = 0, p = flags; i < nb_flags; i++, p++) {
1841 if (!strcmp(r, p->name))
1842 goto found;
1844 return -1;
1845 found:
1846 if (p->flags & FD_INVERT)
1847 value = !value;
1848 *(int *)((uint8_t *)s + p->offset) = value;
1849 return 0;
1853 /* set/reset a warning */
1854 int tcc_set_warning(TCCState *s, const char *warning_name, int value)
1856 int i;
1857 const FlagDef *p;
1859 if (!strcmp(warning_name, "all")) {
1860 for(i = 0, p = warning_defs; i < countof(warning_defs); i++, p++) {
1861 if (p->flags & WD_ALL)
1862 *(int *)((uint8_t *)s + p->offset) = 1;
1864 return 0;
1865 } else {
1866 return set_flag(s, warning_defs, countof(warning_defs),
1867 warning_name, value);
1871 static const FlagDef flag_defs[] = {
1872 { offsetof(TCCState, char_is_unsigned), 0, "unsigned-char" },
1873 { offsetof(TCCState, char_is_unsigned), FD_INVERT, "signed-char" },
1874 { offsetof(TCCState, nocommon), FD_INVERT, "common" },
1875 { offsetof(TCCState, leading_underscore), 0, "leading-underscore" },
1878 /* set/reset a flag */
1879 int tcc_set_flag(TCCState *s, const char *flag_name, int value)
1881 return set_flag(s, flag_defs, countof(flag_defs),
1882 flag_name, value);
1885 /* set CONFIG_TCCDIR at runtime */
1886 void tcc_set_lib_path(TCCState *s, const char *path)
1888 tcc_free(s->tcc_lib_path);
1889 s->tcc_lib_path = tcc_strdup(path);
1892 void tcc_print_stats(TCCState *s, int64_t total_time)
1894 double tt;
1895 tt = (double)total_time / 1000000.0;
1896 if (tt < 0.001)
1897 tt = 0.001;
1898 if (total_bytes < 1)
1899 total_bytes = 1;
1900 printf("%d idents, %d lines, %d bytes, %0.3f s, %d lines/s, %0.1f MB/s\n",
1901 tok_ident - TOK_IDENT, total_lines, total_bytes,
1902 tt, (int)(total_lines / tt),
1903 total_bytes / tt / 1000000.0);