fix uninitialized warnings with 'type.ref'
[tinycc.git] / libtcc.c
blob5b11396322f63cf0f3656abc7e9cbb47b8253e69
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
61 /* bound check related sections */
62 static Section *bounds_section; /* contains global data bound description */
63 static Section *lbounds_section; /* contains local data bound description */
64 /* symbol sections */
65 static Section *symtab_section, *strtab_section;
67 /* debug sections */
68 static Section *stab_section, *stabstr_section;
70 /* loc : local variable index
71 ind : output code index
72 rsym: return symbol
73 anon_sym: anonymous symbol index
75 static int rsym, anon_sym, ind, loc;
76 /* expression generation modifiers */
77 static int const_wanted; /* true if constant wanted */
78 static int nocode_wanted; /* true if no code generation wanted for an expression */
79 static int global_expr; /* true if compound literals must be allocated
80 globally (used during initializers parsing */
81 static CType func_vt; /* current function return type (used by return
82 instruction) */
83 static int func_vc;
84 static int last_line_num, last_ind, func_ind; /* debug last line number and pc */
85 static int tok_ident;
86 static TokenSym **table_ident;
87 static TokenSym *hash_ident[TOK_HASH_SIZE];
88 static char token_buf[STRING_MAX_SIZE + 1];
89 static char *funcname;
90 static Sym *global_stack, *local_stack;
91 static Sym *define_stack;
92 static Sym *global_label_stack, *local_label_stack;
93 /* symbol allocator */
94 #define SYM_POOL_NB (8192 / sizeof(Sym))
95 static Sym *sym_free_first;
96 static void **sym_pools;
97 static int nb_sym_pools;
99 static SValue vstack[VSTACK_SIZE], *vtop;
100 /* some predefined types */
101 static CType char_pointer_type, func_old_type, int_type;
103 /* use GNU C extensions */
104 static int gnu_ext = 1;
106 /* use Tiny C extensions */
107 static int tcc_ext = 1;
109 /* max number of callers shown if error */
110 #ifdef CONFIG_TCC_BACKTRACE
111 int num_callers = 6;
112 const char **rt_bound_error_msg;
113 unsigned long rt_prog_main;
114 #endif
116 /* XXX: get rid of this ASAP */
117 static struct TCCState *tcc_state;
119 /********************************************************/
120 /* function prototypes */
122 /* tccpp.c */
123 static void next(void);
124 char *get_tok_str(int v, CValue *cv);
126 /* tccgen.c */
127 static void parse_expr_type(CType *type);
128 static void expr_type(CType *type);
129 static void unary_type(CType *type);
130 static void block(int *bsym, int *csym, int *case_sym, int *def_sym,
131 int case_reg, int is_expr);
132 static int expr_const(void);
133 static void expr_eq(void);
134 static void gexpr(void);
135 static void gen_inline_functions(void);
136 static void decl(int l);
137 static void decl_initializer(CType *type, Section *sec, unsigned long c,
138 int first, int size_only);
139 static void decl_initializer_alloc(CType *type, AttributeDef *ad, int r,
140 int has_init, int v, int scope);
141 int gv(int rc);
142 void gv2(int rc1, int rc2);
143 void move_reg(int r, int s);
144 void save_regs(int n);
145 void save_reg(int r);
146 void vpop(void);
147 void vswap(void);
148 void vdup(void);
149 int get_reg(int rc);
150 int get_reg_ex(int rc,int rc2);
152 void gen_op(int op);
153 void force_charshort_cast(int t);
154 static void gen_cast(CType *type);
155 void vstore(void);
156 static Sym *sym_find(int v);
157 static Sym *sym_push(int v, CType *type, int r, int c);
159 /* type handling */
160 static int type_size(CType *type, int *a);
161 static inline CType *pointed_type(CType *type);
162 static int pointed_size(CType *type);
163 static int lvalue_type(int t);
164 static int parse_btype(CType *type, AttributeDef *ad);
165 static void type_decl(CType *type, AttributeDef *ad, int *v, int td);
166 static int compare_types(CType *type1, CType *type2, int unqualified);
167 static int is_compatible_types(CType *type1, CType *type2);
168 static int is_compatible_parameter_types(CType *type1, CType *type2);
170 int ieee_finite(double d);
171 void vpushi(int v);
172 void vpushll(long long v);
173 void vrott(int n);
174 void vnrott(int n);
175 void lexpand_nr(void);
176 static void vpush_global_sym(CType *type, int v);
177 void vset(CType *type, int r, int v);
178 void type_to_str(char *buf, int buf_size,
179 CType *type, const char *varstr);
180 static Sym *get_sym_ref(CType *type, Section *sec,
181 unsigned long offset, unsigned long size);
182 static Sym *external_global_sym(int v, CType *type, int r);
184 /* section generation */
185 static void section_realloc(Section *sec, unsigned long new_size);
186 static void *section_ptr_add(Section *sec, unsigned long size);
187 static void put_extern_sym(Sym *sym, Section *section,
188 unsigned long value, unsigned long size);
189 static void greloc(Section *s, Sym *sym, unsigned long addr, int type);
190 static int put_elf_str(Section *s, const char *sym);
191 static int put_elf_sym(Section *s,
192 unsigned long value, unsigned long size,
193 int info, int other, int shndx, const char *name);
194 static int add_elf_sym(Section *s, uplong value, unsigned long size,
195 int info, int other, int sh_num, const char *name);
196 static void put_elf_reloc(Section *symtab, Section *s, unsigned long offset,
197 int type, int symbol);
198 static void put_stabs(const char *str, int type, int other, int desc,
199 unsigned long value);
200 static void put_stabs_r(const char *str, int type, int other, int desc,
201 unsigned long value, Section *sec, int sym_index);
202 static void put_stabn(int type, int other, int desc, int value);
203 static void put_stabd(int type, int other, int desc);
204 static int tcc_add_dll(TCCState *s, const char *filename, int flags);
206 #define AFF_PRINT_ERROR 0x0001 /* print error if file not found */
207 #define AFF_REFERENCED_DLL 0x0002 /* load a referenced dll from another dll */
208 #define AFF_PREPROCESS 0x0004 /* preprocess file */
209 static int tcc_add_file_internal(TCCState *s, const char *filename, int flags);
211 /* tcccoff.c */
212 int tcc_output_coff(TCCState *s1, FILE *f);
214 /* tccpe.c */
215 int pe_load_file(struct TCCState *s1, const char *filename, int fd);
216 int pe_output_file(struct TCCState *s1, const char *filename);
217 int pe_dllimport(int r, SValue *sv, void (*fn)(int r, SValue *sv));
219 /* tccasm.c */
220 #ifdef CONFIG_TCC_ASM
221 static void asm_expr(TCCState *s1, ExprValue *pe);
222 static int asm_int_expr(TCCState *s1);
223 static int find_constraint(ASMOperand *operands, int nb_operands,
224 const char *name, const char **pp);
226 static int tcc_assemble(TCCState *s1, int do_preprocess);
227 #endif
229 static void asm_instr(void);
230 static void asm_global_instr(void);
232 /********************************************************/
233 /* libtcc.c */
235 static Sym *__sym_malloc(void);
236 static inline Sym *sym_malloc(void);
237 static inline void sym_free(Sym *sym);
238 Section *new_section(TCCState *s1, const char *name, int sh_type, int sh_flags);
239 static void free_section(Section *s);
240 static void section_realloc(Section *sec, unsigned long new_size);
241 static void *section_ptr_add(Section *sec, unsigned long size);
242 Section *find_section(TCCState *s1, const char *name);
243 static void put_extern_sym2(
244 Sym *sym, Section *section,
245 unsigned long value, unsigned long size, int can_add_underscore);
246 static void put_extern_sym(
247 Sym *sym, Section *section,
248 unsigned long value, unsigned long size);
249 static void greloc(Section *s, Sym *sym, unsigned long offset, int type);
251 static void strcat_vprintf(char *buf, int buf_size, const char *fmt, va_list ap);
252 static void strcat_printf(char *buf, int buf_size, const char *fmt, ...);
254 /* CString handling */
255 static void cstr_realloc(CString *cstr, int new_size);
256 static inline void cstr_ccat(CString *cstr, int ch);
257 static void cstr_cat(CString *cstr, const char *str);
258 static void cstr_wccat(CString *cstr, int ch);
259 static void cstr_new(CString *cstr);
260 static void cstr_free(CString *cstr);
261 #define cstr_reset(cstr) cstr_free(cstr)
262 static void add_char(CString *cstr, int c);
264 static Sym *sym_push2(Sym **ps, int v, int t, long c);
265 static Sym *sym_find2(Sym *s, int v);
266 static inline Sym *struct_find(int v);
267 static inline Sym *sym_find(int v);
268 static Sym *sym_push(int v, CType *type, int r, int c);
269 static Sym *global_identifier_push(int v, int t, int c);
270 static void sym_pop(Sym **ptop, Sym *b);
272 BufferedFile *tcc_open(TCCState *s1, const char *filename);
273 void tcc_close(BufferedFile *bf);
274 static int tcc_compile(TCCState *s1);
276 void expect(const char *msg);
277 void skip(int c);
278 static void test_lvalue(void);
279 void *resolve_sym(TCCState *s1, const char *sym);
281 static inline int isid(int c)
283 return (c >= 'a' && c <= 'z')
284 || (c >= 'A' && c <= 'Z')
285 || c == '_';
288 static inline int isnum(int c)
290 return c >= '0' && c <= '9';
293 static inline int isoct(int c)
295 return c >= '0' && c <= '7';
298 static inline int toup(int c)
300 if (c >= 'a' && c <= 'z')
301 return c - 'a' + 'A';
302 else
303 return c;
306 /********************************************************/
308 #ifdef TCC_TARGET_I386
309 #include "i386-gen.c"
310 #endif
312 #ifdef TCC_TARGET_ARM
313 #include "arm-gen.c"
314 #endif
316 #ifdef TCC_TARGET_C67
317 #include "c67-gen.c"
318 #endif
320 #ifdef TCC_TARGET_X86_64
321 #include "x86_64-gen.c"
322 #endif
324 #include "tccpp.c"
325 #include "tccgen.c"
327 #ifdef CONFIG_TCC_ASM
329 #if defined TCC_TARGET_I386 || defined TCC_TARGET_X86_64
330 #include "i386-asm.c"
331 #endif
333 #include "tccasm.c"
334 #else
335 static void asm_instr(void)
337 error("inline asm() not supported");
339 static void asm_global_instr(void)
341 error("inline asm() not supported");
343 #endif
345 #include "tccelf.c"
347 #ifdef TCC_TARGET_COFF
348 #include "tcccoff.c"
349 #endif
351 #ifdef TCC_TARGET_PE
352 #include "tccpe.c"
353 #endif
355 /********************************************************/
356 #ifdef _WIN32
357 char *normalize_slashes(char *path)
359 char *p;
360 for (p = path; *p; ++p)
361 if (*p == '\\')
362 *p = '/';
363 return path;
366 HMODULE tcc_module;
368 /* on win32, we suppose the lib and includes are at the location of 'tcc.exe' */
369 void tcc_set_lib_path_w32(TCCState *s)
371 char path[1024], *p;
372 GetModuleFileNameA(tcc_module, path, sizeof path);
373 p = tcc_basename(normalize_slashes(strlwr(path)));
374 if (p - 5 > path && 0 == strncmp(p - 5, "/bin/", 5))
375 p -= 5;
376 else if (p > path)
377 p--;
378 *p = 0;
379 tcc_set_lib_path(s, path);
382 #ifdef LIBTCC_AS_DLL
383 BOOL WINAPI DllMain (HANDLE hDll, DWORD dwReason, LPVOID lpReserved)
385 if (DLL_PROCESS_ATTACH == dwReason)
386 tcc_module = hDll;
387 return TRUE;
389 #endif
390 #endif
392 /********************************************************/
393 #ifdef CONFIG_TCC_STATIC
395 #define RTLD_LAZY 0x001
396 #define RTLD_NOW 0x002
397 #define RTLD_GLOBAL 0x100
398 #define RTLD_DEFAULT NULL
400 /* dummy function for profiling */
401 void *dlopen(const char *filename, int flag)
403 return NULL;
406 void dlclose(void *p)
410 const char *dlerror(void)
412 return "error";
415 typedef struct TCCSyms {
416 char *str;
417 void *ptr;
418 } TCCSyms;
420 #define TCCSYM(a) { #a, &a, },
422 /* add the symbol you want here if no dynamic linking is done */
423 static TCCSyms tcc_syms[] = {
424 #if !defined(CONFIG_TCCBOOT)
425 TCCSYM(printf)
426 TCCSYM(fprintf)
427 TCCSYM(fopen)
428 TCCSYM(fclose)
429 #endif
430 { NULL, NULL },
433 void *resolve_sym(TCCState *s1, const char *symbol)
435 TCCSyms *p;
436 p = tcc_syms;
437 while (p->str != NULL) {
438 if (!strcmp(p->str, symbol))
439 return p->ptr;
440 p++;
442 return NULL;
445 #elif defined(_WIN32)
446 #define dlclose FreeLibrary
448 #else
449 #include <dlfcn.h>
451 void *resolve_sym(TCCState *s1, const char *sym)
453 return dlsym(RTLD_DEFAULT, sym);
456 #endif
458 /********************************************************/
460 /* we use our own 'finite' function to avoid potential problems with
461 non standard math libs */
462 /* XXX: endianness dependent */
463 int ieee_finite(double d)
465 int *p = (int *)&d;
466 return ((unsigned)((p[1] | 0x800fffff) + 1)) >> 31;
469 /* copy a string and truncate it. */
470 char *pstrcpy(char *buf, int buf_size, const char *s)
472 char *q, *q_end;
473 int c;
475 if (buf_size > 0) {
476 q = buf;
477 q_end = buf + buf_size - 1;
478 while (q < q_end) {
479 c = *s++;
480 if (c == '\0')
481 break;
482 *q++ = c;
484 *q = '\0';
486 return buf;
489 /* strcat and truncate. */
490 char *pstrcat(char *buf, int buf_size, const char *s)
492 int len;
493 len = strlen(buf);
494 if (len < buf_size)
495 pstrcpy(buf + len, buf_size - len, s);
496 return buf;
499 /* extract the basename of a file */
500 char *tcc_basename(const char *name)
502 char *p = strchr(name, 0);
503 while (p > name && !IS_PATHSEP(p[-1]))
504 --p;
505 return p;
508 char *tcc_fileextension (const char *name)
510 char *b = tcc_basename(name);
511 char *e = strrchr(b, '.');
512 return e ? e : strchr(b, 0);
515 void set_pages_executable(void *ptr, unsigned long length)
517 #ifdef _WIN32
518 unsigned long old_protect;
519 VirtualProtect(ptr, length, PAGE_EXECUTE_READWRITE, &old_protect);
520 #else
521 unsigned long start, end;
522 start = (unsigned long)ptr & ~(PAGESIZE - 1);
523 end = (unsigned long)ptr + length;
524 end = (end + PAGESIZE - 1) & ~(PAGESIZE - 1);
525 mprotect((void *)start, end - start, PROT_READ | PROT_WRITE | PROT_EXEC);
526 #endif
529 /* memory management */
530 #ifdef MEM_DEBUG
531 int mem_cur_size;
532 int mem_max_size;
533 unsigned malloc_usable_size(void*);
534 #endif
536 void tcc_free(void *ptr)
538 #ifdef MEM_DEBUG
539 mem_cur_size -= malloc_usable_size(ptr);
540 #endif
541 free(ptr);
544 void *tcc_malloc(unsigned long size)
546 void *ptr;
547 ptr = malloc(size);
548 if (!ptr && size)
549 error("memory full");
550 #ifdef MEM_DEBUG
551 mem_cur_size += malloc_usable_size(ptr);
552 if (mem_cur_size > mem_max_size)
553 mem_max_size = mem_cur_size;
554 #endif
555 return ptr;
558 void *tcc_mallocz(unsigned long size)
560 void *ptr;
561 ptr = tcc_malloc(size);
562 memset(ptr, 0, size);
563 return ptr;
566 void *tcc_realloc(void *ptr, unsigned long size)
568 void *ptr1;
569 #ifdef MEM_DEBUG
570 mem_cur_size -= malloc_usable_size(ptr);
571 #endif
572 ptr1 = realloc(ptr, size);
573 #ifdef MEM_DEBUG
574 /* NOTE: count not correct if alloc error, but not critical */
575 mem_cur_size += malloc_usable_size(ptr1);
576 if (mem_cur_size > mem_max_size)
577 mem_max_size = mem_cur_size;
578 #endif
579 return ptr1;
582 char *tcc_strdup(const char *str)
584 char *ptr;
585 ptr = tcc_malloc(strlen(str) + 1);
586 strcpy(ptr, str);
587 return ptr;
590 #define free(p) use_tcc_free(p)
591 #define malloc(s) use_tcc_malloc(s)
592 #define realloc(p, s) use_tcc_realloc(p, s)
594 void dynarray_add(void ***ptab, int *nb_ptr, void *data)
596 int nb, nb_alloc;
597 void **pp;
599 nb = *nb_ptr;
600 pp = *ptab;
601 /* every power of two we double array size */
602 if ((nb & (nb - 1)) == 0) {
603 if (!nb)
604 nb_alloc = 1;
605 else
606 nb_alloc = nb * 2;
607 pp = tcc_realloc(pp, nb_alloc * sizeof(void *));
608 if (!pp)
609 error("memory full");
610 *ptab = pp;
612 pp[nb++] = data;
613 *nb_ptr = nb;
616 void dynarray_reset(void *pp, int *n)
618 void **p;
619 for (p = *(void***)pp; *n; ++p, --*n)
620 if (*p)
621 tcc_free(*p);
622 tcc_free(*(void**)pp);
623 *(void**)pp = NULL;
626 /* symbol allocator */
627 static Sym *__sym_malloc(void)
629 Sym *sym_pool, *sym, *last_sym;
630 int i;
632 sym_pool = tcc_malloc(SYM_POOL_NB * sizeof(Sym));
633 dynarray_add(&sym_pools, &nb_sym_pools, sym_pool);
635 last_sym = sym_free_first;
636 sym = sym_pool;
637 for(i = 0; i < SYM_POOL_NB; i++) {
638 sym->next = last_sym;
639 last_sym = sym;
640 sym++;
642 sym_free_first = last_sym;
643 return last_sym;
646 static inline Sym *sym_malloc(void)
648 Sym *sym;
649 sym = sym_free_first;
650 if (!sym)
651 sym = __sym_malloc();
652 sym_free_first = sym->next;
653 return sym;
656 static inline void sym_free(Sym *sym)
658 sym->next = sym_free_first;
659 sym_free_first = sym;
662 Section *new_section(TCCState *s1, const char *name, int sh_type, int sh_flags)
664 Section *sec;
666 sec = tcc_mallocz(sizeof(Section) + strlen(name));
667 strcpy(sec->name, name);
668 sec->sh_type = sh_type;
669 sec->sh_flags = sh_flags;
670 switch(sh_type) {
671 case SHT_HASH:
672 case SHT_REL:
673 case SHT_RELA:
674 case SHT_DYNSYM:
675 case SHT_SYMTAB:
676 case SHT_DYNAMIC:
677 sec->sh_addralign = 4;
678 break;
679 case SHT_STRTAB:
680 sec->sh_addralign = 1;
681 break;
682 default:
683 sec->sh_addralign = 32; /* default conservative alignment */
684 break;
687 if (sh_flags & SHF_PRIVATE) {
688 dynarray_add((void ***)&s1->priv_sections, &s1->nb_priv_sections, sec);
689 } else {
690 sec->sh_num = s1->nb_sections;
691 dynarray_add((void ***)&s1->sections, &s1->nb_sections, sec);
694 return sec;
697 static void free_section(Section *s)
699 tcc_free(s->data);
702 /* realloc section and set its content to zero */
703 static void section_realloc(Section *sec, unsigned long new_size)
705 unsigned long size;
706 unsigned char *data;
708 size = sec->data_allocated;
709 if (size == 0)
710 size = 1;
711 while (size < new_size)
712 size = size * 2;
713 data = tcc_realloc(sec->data, size);
714 if (!data)
715 error("memory full");
716 memset(data + sec->data_allocated, 0, size - sec->data_allocated);
717 sec->data = data;
718 sec->data_allocated = size;
721 /* reserve at least 'size' bytes in section 'sec' from
722 sec->data_offset. */
723 static void *section_ptr_add(Section *sec, unsigned long size)
725 unsigned long offset, offset1;
727 offset = sec->data_offset;
728 offset1 = offset + size;
729 if (offset1 > sec->data_allocated)
730 section_realloc(sec, offset1);
731 sec->data_offset = offset1;
732 return sec->data + offset;
735 /* return a reference to a section, and create it if it does not
736 exists */
737 Section *find_section(TCCState *s1, const char *name)
739 Section *sec;
740 int i;
741 for(i = 1; i < s1->nb_sections; i++) {
742 sec = s1->sections[i];
743 if (!strcmp(name, sec->name))
744 return sec;
746 /* sections are created as PROGBITS */
747 return new_section(s1, name, SHT_PROGBITS, SHF_ALLOC);
750 /* update sym->c so that it points to an external symbol in section
751 'section' with value 'value' */
752 static void put_extern_sym2(Sym *sym, Section *section,
753 unsigned long value, unsigned long size,
754 int can_add_underscore)
756 int sym_type, sym_bind, sh_num, info, other, attr;
757 ElfW(Sym) *esym;
758 const char *name;
759 char buf1[256];
761 if (section == NULL)
762 sh_num = SHN_UNDEF;
763 else if (section == SECTION_ABS)
764 sh_num = SHN_ABS;
765 else
766 sh_num = section->sh_num;
768 other = attr = 0;
770 if ((sym->type.t & VT_BTYPE) == VT_FUNC) {
771 sym_type = STT_FUNC;
772 #ifdef TCC_TARGET_PE
773 if (sym->type.ref)
774 attr = sym->type.ref->r;
775 if (FUNC_EXPORT(attr))
776 other |= 1;
777 if (FUNC_CALL(attr) == FUNC_STDCALL)
778 other |= 2;
779 #endif
780 } else if ((sym->type.t & VT_BTYPE) == VT_VOID) {
781 sym_type = STT_NOTYPE;
782 } else {
783 sym_type = STT_OBJECT;
784 #ifdef TCC_TARGET_PE
785 if (sym->type.t & VT_EXPORT)
786 other |= 1;
787 #endif
790 if (sym->type.t & VT_STATIC)
791 sym_bind = STB_LOCAL;
792 else
793 sym_bind = STB_GLOBAL;
795 if (!sym->c) {
796 name = get_tok_str(sym->v, NULL);
797 #ifdef CONFIG_TCC_BCHECK
798 if (tcc_state->do_bounds_check) {
799 char buf[32];
801 /* XXX: avoid doing that for statics ? */
802 /* if bound checking is activated, we change some function
803 names by adding the "__bound" prefix */
804 switch(sym->v) {
805 #if 0
806 /* XXX: we rely only on malloc hooks */
807 case TOK_malloc:
808 case TOK_free:
809 case TOK_realloc:
810 case TOK_memalign:
811 case TOK_calloc:
812 #endif
813 case TOK_memcpy:
814 case TOK_memmove:
815 case TOK_memset:
816 case TOK_strlen:
817 case TOK_strcpy:
818 case TOK_alloca:
819 strcpy(buf, "__bound_");
820 strcat(buf, name);
821 name = buf;
822 break;
825 #endif
827 #ifdef TCC_TARGET_PE
828 if ((other & 2) && can_add_underscore) {
829 sprintf(buf1, "_%s@%d", name, FUNC_ARGS(attr));
830 name = buf1;
831 } else
832 #endif
833 if (tcc_state->leading_underscore && can_add_underscore) {
834 buf1[0] = '_';
835 pstrcpy(buf1 + 1, sizeof(buf1) - 1, name);
836 name = buf1;
838 info = ELFW(ST_INFO)(sym_bind, sym_type);
839 sym->c = add_elf_sym(symtab_section, value, size, info, other, sh_num, name);
840 } else {
841 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
842 esym->st_value = value;
843 esym->st_size = size;
844 esym->st_shndx = sh_num;
845 esym->st_other |= other;
849 static void put_extern_sym(Sym *sym, Section *section,
850 unsigned long value, unsigned long size)
852 put_extern_sym2(sym, section, value, size, 1);
855 /* add a new relocation entry to symbol 'sym' in section 's' */
856 static void greloc(Section *s, Sym *sym, unsigned long offset, int type)
858 int c = 0;
859 if (sym) {
860 if (0 == sym->c)
861 put_extern_sym(sym, NULL, 0, 0);
862 c = sym->c;
864 /* now we can add ELF relocation info */
865 put_elf_reloc(symtab_section, s, offset, type, c);
868 static void strcat_vprintf(char *buf, int buf_size, const char *fmt, va_list ap)
870 int len;
871 len = strlen(buf);
872 vsnprintf(buf + len, buf_size - len, fmt, ap);
875 static void strcat_printf(char *buf, int buf_size, const char *fmt, ...)
877 va_list ap;
878 va_start(ap, fmt);
879 strcat_vprintf(buf, buf_size, fmt, ap);
880 va_end(ap);
883 void error1(TCCState *s1, int is_warning, const char *fmt, va_list ap)
885 char buf[2048];
886 BufferedFile **f;
888 buf[0] = '\0';
889 if (file) {
890 for(f = s1->include_stack; f < s1->include_stack_ptr; f++)
891 strcat_printf(buf, sizeof(buf), "In file included from %s:%d:\n",
892 (*f)->filename, (*f)->line_num);
893 if (file->line_num > 0) {
894 strcat_printf(buf, sizeof(buf),
895 "%s:%d: ", file->filename, file->line_num);
896 } else {
897 strcat_printf(buf, sizeof(buf),
898 "%s: ", file->filename);
900 } else {
901 strcat_printf(buf, sizeof(buf),
902 "tcc: ");
904 if (is_warning)
905 strcat_printf(buf, sizeof(buf), "warning: ");
906 else
907 strcat_printf(buf, sizeof(buf), "error: ");
908 strcat_vprintf(buf, sizeof(buf), fmt, ap);
910 if (!s1->error_func) {
911 /* default case: stderr */
912 fprintf(stderr, "%s\n", buf);
913 } else {
914 s1->error_func(s1->error_opaque, buf);
916 if (!is_warning || s1->warn_error)
917 s1->nb_errors++;
920 void tcc_set_error_func(TCCState *s, void *error_opaque,
921 void (*error_func)(void *opaque, const char *msg))
923 s->error_opaque = error_opaque;
924 s->error_func = error_func;
927 /* error without aborting current compilation */
928 void error_noabort(const char *fmt, ...)
930 TCCState *s1 = tcc_state;
931 va_list ap;
933 va_start(ap, fmt);
934 error1(s1, 0, fmt, ap);
935 va_end(ap);
938 void error(const char *fmt, ...)
940 TCCState *s1 = tcc_state;
941 va_list ap;
943 va_start(ap, fmt);
944 error1(s1, 0, fmt, ap);
945 va_end(ap);
946 /* better than nothing: in some cases, we accept to handle errors */
947 if (s1->error_set_jmp_enabled) {
948 longjmp(s1->error_jmp_buf, 1);
949 } else {
950 /* XXX: eliminate this someday */
951 exit(1);
955 void expect(const char *msg)
957 error("%s expected", msg);
960 void warning(const char *fmt, ...)
962 TCCState *s1 = tcc_state;
963 va_list ap;
965 if (s1->warn_none)
966 return;
968 va_start(ap, fmt);
969 error1(s1, 1, fmt, ap);
970 va_end(ap);
973 void skip(int c)
975 if (tok != c)
976 error("'%c' expected", c);
977 next();
980 static void test_lvalue(void)
982 if (!(vtop->r & VT_LVAL))
983 expect("lvalue");
986 /* CString handling */
988 static void cstr_realloc(CString *cstr, int new_size)
990 int size;
991 void *data;
993 size = cstr->size_allocated;
994 if (size == 0)
995 size = 8; /* no need to allocate a too small first string */
996 while (size < new_size)
997 size = size * 2;
998 data = tcc_realloc(cstr->data_allocated, size);
999 if (!data)
1000 error("memory full");
1001 cstr->data_allocated = data;
1002 cstr->size_allocated = size;
1003 cstr->data = data;
1006 /* add a byte */
1007 static inline void cstr_ccat(CString *cstr, int ch)
1009 int size;
1010 size = cstr->size + 1;
1011 if (size > cstr->size_allocated)
1012 cstr_realloc(cstr, size);
1013 ((unsigned char *)cstr->data)[size - 1] = ch;
1014 cstr->size = size;
1017 static void cstr_cat(CString *cstr, const char *str)
1019 int c;
1020 for(;;) {
1021 c = *str;
1022 if (c == '\0')
1023 break;
1024 cstr_ccat(cstr, c);
1025 str++;
1029 /* add a wide char */
1030 static void cstr_wccat(CString *cstr, int ch)
1032 int size;
1033 size = cstr->size + sizeof(nwchar_t);
1034 if (size > cstr->size_allocated)
1035 cstr_realloc(cstr, size);
1036 *(nwchar_t *)(((unsigned char *)cstr->data) + size - sizeof(nwchar_t)) = ch;
1037 cstr->size = size;
1040 static void cstr_new(CString *cstr)
1042 memset(cstr, 0, sizeof(CString));
1045 /* free string and reset it to NULL */
1046 static void cstr_free(CString *cstr)
1048 tcc_free(cstr->data_allocated);
1049 cstr_new(cstr);
1052 #define cstr_reset(cstr) cstr_free(cstr)
1054 /* XXX: unicode ? */
1055 static void add_char(CString *cstr, int c)
1057 if (c == '\'' || c == '\"' || c == '\\') {
1058 /* XXX: could be more precise if char or string */
1059 cstr_ccat(cstr, '\\');
1061 if (c >= 32 && c <= 126) {
1062 cstr_ccat(cstr, c);
1063 } else {
1064 cstr_ccat(cstr, '\\');
1065 if (c == '\n') {
1066 cstr_ccat(cstr, 'n');
1067 } else {
1068 cstr_ccat(cstr, '0' + ((c >> 6) & 7));
1069 cstr_ccat(cstr, '0' + ((c >> 3) & 7));
1070 cstr_ccat(cstr, '0' + (c & 7));
1075 /* push, without hashing */
1076 static Sym *sym_push2(Sym **ps, int v, int t, long c)
1078 Sym *s;
1079 s = sym_malloc();
1080 s->v = v;
1081 s->type.t = t;
1082 s->type.ref = NULL;
1083 #ifdef _WIN64
1084 s->d = NULL;
1085 #endif
1086 s->c = c;
1087 s->next = NULL;
1088 /* add in stack */
1089 s->prev = *ps;
1090 *ps = s;
1091 return s;
1094 /* find a symbol and return its associated structure. 's' is the top
1095 of the symbol stack */
1096 static Sym *sym_find2(Sym *s, int v)
1098 while (s) {
1099 if (s->v == v)
1100 return s;
1101 s = s->prev;
1103 return NULL;
1106 /* structure lookup */
1107 static inline Sym *struct_find(int v)
1109 v -= TOK_IDENT;
1110 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1111 return NULL;
1112 return table_ident[v]->sym_struct;
1115 /* find an identifier */
1116 static inline Sym *sym_find(int v)
1118 v -= TOK_IDENT;
1119 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1120 return NULL;
1121 return table_ident[v]->sym_identifier;
1124 /* push a given symbol on the symbol stack */
1125 static Sym *sym_push(int v, CType *type, int r, int c)
1127 Sym *s, **ps;
1128 TokenSym *ts;
1130 if (local_stack)
1131 ps = &local_stack;
1132 else
1133 ps = &global_stack;
1134 s = sym_push2(ps, v, type->t, c);
1135 s->type.ref = type->ref;
1136 s->r = r;
1137 /* don't record fields or anonymous symbols */
1138 /* XXX: simplify */
1139 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
1140 /* record symbol in token array */
1141 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
1142 if (v & SYM_STRUCT)
1143 ps = &ts->sym_struct;
1144 else
1145 ps = &ts->sym_identifier;
1146 s->prev_tok = *ps;
1147 *ps = s;
1149 return s;
1152 /* push a global identifier */
1153 static Sym *global_identifier_push(int v, int t, int c)
1155 Sym *s, **ps;
1156 s = sym_push2(&global_stack, v, t, c);
1157 /* don't record anonymous symbol */
1158 if (v < SYM_FIRST_ANOM) {
1159 ps = &table_ident[v - TOK_IDENT]->sym_identifier;
1160 /* modify the top most local identifier, so that
1161 sym_identifier will point to 's' when popped */
1162 while (*ps != NULL)
1163 ps = &(*ps)->prev_tok;
1164 s->prev_tok = NULL;
1165 *ps = s;
1167 return s;
1170 /* pop symbols until top reaches 'b' */
1171 static void sym_pop(Sym **ptop, Sym *b)
1173 Sym *s, *ss, **ps;
1174 TokenSym *ts;
1175 int v;
1177 s = *ptop;
1178 while(s != b) {
1179 ss = s->prev;
1180 v = s->v;
1181 /* remove symbol in token array */
1182 /* XXX: simplify */
1183 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
1184 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
1185 if (v & SYM_STRUCT)
1186 ps = &ts->sym_struct;
1187 else
1188 ps = &ts->sym_identifier;
1189 *ps = s->prev_tok;
1191 sym_free(s);
1192 s = ss;
1194 *ptop = b;
1197 /* I/O layer */
1199 BufferedFile *tcc_open(TCCState *s1, const char *filename)
1201 int fd;
1202 BufferedFile *bf;
1204 if (strcmp(filename, "-") == 0)
1205 fd = 0, filename = "stdin";
1206 else
1207 fd = open(filename, O_RDONLY | O_BINARY);
1208 if ((s1->verbose == 2 && fd >= 0) || s1->verbose == 3)
1209 printf("%s %*s%s\n", fd < 0 ? "nf":"->",
1210 (int)(s1->include_stack_ptr - s1->include_stack), "", filename);
1211 if (fd < 0)
1212 return NULL;
1213 bf = tcc_malloc(sizeof(BufferedFile));
1214 bf->fd = fd;
1215 bf->buf_ptr = bf->buffer;
1216 bf->buf_end = bf->buffer;
1217 bf->buffer[0] = CH_EOB; /* put eob symbol */
1218 pstrcpy(bf->filename, sizeof(bf->filename), filename);
1219 #ifdef _WIN32
1220 normalize_slashes(bf->filename);
1221 #endif
1222 bf->line_num = 1;
1223 bf->ifndef_macro = 0;
1224 bf->ifdef_stack_ptr = s1->ifdef_stack_ptr;
1225 // printf("opening '%s'\n", filename);
1226 return bf;
1229 void tcc_close(BufferedFile *bf)
1231 total_lines += bf->line_num;
1232 close(bf->fd);
1233 tcc_free(bf);
1236 /* compile the C file opened in 'file'. Return non zero if errors. */
1237 static int tcc_compile(TCCState *s1)
1239 Sym *define_start;
1240 char buf[512];
1241 volatile int section_sym;
1243 #ifdef INC_DEBUG
1244 printf("%s: **** new file\n", file->filename);
1245 #endif
1246 preprocess_init(s1);
1248 cur_text_section = NULL;
1249 funcname = "";
1250 anon_sym = SYM_FIRST_ANOM;
1252 /* file info: full path + filename */
1253 section_sym = 0; /* avoid warning */
1254 if (s1->do_debug) {
1255 section_sym = put_elf_sym(symtab_section, 0, 0,
1256 ELFW(ST_INFO)(STB_LOCAL, STT_SECTION), 0,
1257 text_section->sh_num, NULL);
1258 getcwd(buf, sizeof(buf));
1259 #ifdef _WIN32
1260 normalize_slashes(buf);
1261 #endif
1262 pstrcat(buf, sizeof(buf), "/");
1263 put_stabs_r(buf, N_SO, 0, 0,
1264 text_section->data_offset, text_section, section_sym);
1265 put_stabs_r(file->filename, N_SO, 0, 0,
1266 text_section->data_offset, text_section, section_sym);
1268 /* an elf symbol of type STT_FILE must be put so that STB_LOCAL
1269 symbols can be safely used */
1270 put_elf_sym(symtab_section, 0, 0,
1271 ELFW(ST_INFO)(STB_LOCAL, STT_FILE), 0,
1272 SHN_ABS, file->filename);
1274 /* define some often used types */
1275 int_type.t = VT_INT;
1277 char_pointer_type.t = VT_BYTE;
1278 mk_pointer(&char_pointer_type);
1280 func_old_type.t = VT_FUNC;
1281 func_old_type.ref = sym_push(SYM_FIELD, &int_type, FUNC_CDECL, FUNC_OLD);
1283 #if defined(TCC_ARM_EABI) && defined(TCC_ARM_VFP)
1284 float_type.t = VT_FLOAT;
1285 double_type.t = VT_DOUBLE;
1287 func_float_type.t = VT_FUNC;
1288 func_float_type.ref = sym_push(SYM_FIELD, &float_type, FUNC_CDECL, FUNC_OLD);
1289 func_double_type.t = VT_FUNC;
1290 func_double_type.ref = sym_push(SYM_FIELD, &double_type, FUNC_CDECL, FUNC_OLD);
1291 #endif
1293 #if 0
1294 /* define 'void *alloca(unsigned int)' builtin function */
1296 Sym *s1;
1298 p = anon_sym++;
1299 sym = sym_push(p, mk_pointer(VT_VOID), FUNC_CDECL, FUNC_NEW);
1300 s1 = sym_push(SYM_FIELD, VT_UNSIGNED | VT_INT, 0, 0);
1301 s1->next = NULL;
1302 sym->next = s1;
1303 sym_push(TOK_alloca, VT_FUNC | (p << VT_STRUCT_SHIFT), VT_CONST, 0);
1305 #endif
1307 define_start = define_stack;
1308 nocode_wanted = 1;
1310 if (setjmp(s1->error_jmp_buf) == 0) {
1311 s1->nb_errors = 0;
1312 s1->error_set_jmp_enabled = 1;
1314 ch = file->buf_ptr[0];
1315 tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
1316 parse_flags = PARSE_FLAG_PREPROCESS | PARSE_FLAG_TOK_NUM;
1317 next();
1318 decl(VT_CONST);
1319 if (tok != TOK_EOF)
1320 expect("declaration");
1322 /* end of translation unit info */
1323 if (s1->do_debug) {
1324 put_stabs_r(NULL, N_SO, 0, 0,
1325 text_section->data_offset, text_section, section_sym);
1328 s1->error_set_jmp_enabled = 0;
1330 /* reset define stack, but leave -Dsymbols (may be incorrect if
1331 they are undefined) */
1332 free_defines(define_start);
1334 gen_inline_functions();
1336 sym_pop(&global_stack, NULL);
1337 sym_pop(&local_stack, NULL);
1339 return s1->nb_errors != 0 ? -1 : 0;
1342 int tcc_compile_string(TCCState *s, const char *str)
1344 BufferedFile bf1, *bf = &bf1;
1345 int ret, len;
1346 char *buf;
1348 /* init file structure */
1349 bf->fd = -1;
1350 /* XXX: avoid copying */
1351 len = strlen(str);
1352 buf = tcc_malloc(len + 1);
1353 if (!buf)
1354 return -1;
1355 memcpy(buf, str, len);
1356 buf[len] = CH_EOB;
1357 bf->buf_ptr = buf;
1358 bf->buf_end = buf + len;
1359 pstrcpy(bf->filename, sizeof(bf->filename), "<string>");
1360 bf->line_num = 1;
1361 file = bf;
1362 ret = tcc_compile(s);
1363 file = NULL;
1364 tcc_free(buf);
1366 /* currently, no need to close */
1367 return ret;
1370 /* define a preprocessor symbol. A value can also be provided with the '=' operator */
1371 void tcc_define_symbol(TCCState *s1, const char *sym, const char *value)
1373 BufferedFile bf1, *bf = &bf1;
1375 pstrcpy(bf->buffer, IO_BUF_SIZE, sym);
1376 pstrcat(bf->buffer, IO_BUF_SIZE, " ");
1377 /* default value */
1378 if (!value)
1379 value = "1";
1380 pstrcat(bf->buffer, IO_BUF_SIZE, value);
1382 /* init file structure */
1383 bf->fd = -1;
1384 bf->buf_ptr = bf->buffer;
1385 bf->buf_end = bf->buffer + strlen(bf->buffer);
1386 *bf->buf_end = CH_EOB;
1387 bf->filename[0] = '\0';
1388 bf->line_num = 1;
1389 file = bf;
1391 s1->include_stack_ptr = s1->include_stack;
1393 /* parse with define parser */
1394 ch = file->buf_ptr[0];
1395 next_nomacro();
1396 parse_define();
1397 file = NULL;
1400 /* undefine a preprocessor symbol */
1401 void tcc_undefine_symbol(TCCState *s1, const char *sym)
1403 TokenSym *ts;
1404 Sym *s;
1405 ts = tok_alloc(sym, strlen(sym));
1406 s = define_find(ts->tok);
1407 /* undefine symbol by putting an invalid name */
1408 if (s)
1409 define_undef(s);
1413 #ifdef CONFIG_TCC_BACKTRACE
1414 /* print the position in the source file of PC value 'pc' by reading
1415 the stabs debug information */
1416 static unsigned long rt_printline(unsigned long wanted_pc)
1418 Stab_Sym *sym, *sym_end;
1419 char func_name[128], last_func_name[128];
1420 unsigned long func_addr, last_pc, pc;
1421 const char *incl_files[INCLUDE_STACK_SIZE];
1422 int incl_index, len, last_line_num, i;
1423 const char *str, *p;
1425 fprintf(stderr, "0x%08lx:", wanted_pc);
1427 func_name[0] = '\0';
1428 func_addr = 0;
1429 incl_index = 0;
1430 last_func_name[0] = '\0';
1431 last_pc = 0xffffffff;
1432 last_line_num = 1;
1433 sym = (Stab_Sym *)stab_section->data + 1;
1434 sym_end = (Stab_Sym *)(stab_section->data + stab_section->data_offset);
1435 while (sym < sym_end) {
1436 switch(sym->n_type) {
1437 /* function start or end */
1438 case N_FUN:
1439 if (sym->n_strx == 0) {
1440 /* we test if between last line and end of function */
1441 pc = sym->n_value + func_addr;
1442 if (wanted_pc >= last_pc && wanted_pc < pc)
1443 goto found;
1444 func_name[0] = '\0';
1445 func_addr = 0;
1446 } else {
1447 str = stabstr_section->data + sym->n_strx;
1448 p = strchr(str, ':');
1449 if (!p) {
1450 pstrcpy(func_name, sizeof(func_name), str);
1451 } else {
1452 len = p - str;
1453 if (len > sizeof(func_name) - 1)
1454 len = sizeof(func_name) - 1;
1455 memcpy(func_name, str, len);
1456 func_name[len] = '\0';
1458 func_addr = sym->n_value;
1460 break;
1461 /* line number info */
1462 case N_SLINE:
1463 pc = sym->n_value + func_addr;
1464 if (wanted_pc >= last_pc && wanted_pc < pc)
1465 goto found;
1466 last_pc = pc;
1467 last_line_num = sym->n_desc;
1468 /* XXX: slow! */
1469 strcpy(last_func_name, func_name);
1470 break;
1471 /* include files */
1472 case N_BINCL:
1473 str = stabstr_section->data + sym->n_strx;
1474 add_incl:
1475 if (incl_index < INCLUDE_STACK_SIZE) {
1476 incl_files[incl_index++] = str;
1478 break;
1479 case N_EINCL:
1480 if (incl_index > 1)
1481 incl_index--;
1482 break;
1483 case N_SO:
1484 if (sym->n_strx == 0) {
1485 incl_index = 0; /* end of translation unit */
1486 } else {
1487 str = stabstr_section->data + sym->n_strx;
1488 /* do not add path */
1489 len = strlen(str);
1490 if (len > 0 && str[len - 1] != '/')
1491 goto add_incl;
1493 break;
1495 sym++;
1498 /* second pass: we try symtab symbols (no line number info) */
1499 incl_index = 0;
1501 ElfW(Sym) *sym, *sym_end;
1502 int type;
1504 sym_end = (ElfW(Sym) *)(symtab_section->data + symtab_section->data_offset);
1505 for(sym = (ElfW(Sym) *)symtab_section->data + 1;
1506 sym < sym_end;
1507 sym++) {
1508 type = ELFW(ST_TYPE)(sym->st_info);
1509 if (type == STT_FUNC) {
1510 if (wanted_pc >= sym->st_value &&
1511 wanted_pc < sym->st_value + sym->st_size) {
1512 pstrcpy(last_func_name, sizeof(last_func_name),
1513 strtab_section->data + sym->st_name);
1514 func_addr = sym->st_value;
1515 goto found;
1520 /* did not find any info: */
1521 fprintf(stderr, " ???\n");
1522 return 0;
1523 found:
1524 if (last_func_name[0] != '\0') {
1525 fprintf(stderr, " %s()", last_func_name);
1527 if (incl_index > 0) {
1528 fprintf(stderr, " (%s:%d",
1529 incl_files[incl_index - 1], last_line_num);
1530 for(i = incl_index - 2; i >= 0; i--)
1531 fprintf(stderr, ", included from %s", incl_files[i]);
1532 fprintf(stderr, ")");
1534 fprintf(stderr, "\n");
1535 return func_addr;
1538 #ifdef __i386__
1539 /* fix for glibc 2.1 */
1540 #ifndef REG_EIP
1541 #define REG_EIP EIP
1542 #define REG_EBP EBP
1543 #endif
1545 /* return the PC at frame level 'level'. Return non zero if not found */
1546 static int rt_get_caller_pc(unsigned long *paddr,
1547 ucontext_t *uc, int level)
1549 unsigned long fp;
1550 int i;
1552 if (level == 0) {
1553 #if defined(__FreeBSD__)
1554 *paddr = uc->uc_mcontext.mc_eip;
1555 #elif defined(__dietlibc__)
1556 *paddr = uc->uc_mcontext.eip;
1557 #else
1558 *paddr = uc->uc_mcontext.gregs[REG_EIP];
1559 #endif
1560 return 0;
1561 } else {
1562 #if defined(__FreeBSD__)
1563 fp = uc->uc_mcontext.mc_ebp;
1564 #elif defined(__dietlibc__)
1565 fp = uc->uc_mcontext.ebp;
1566 #else
1567 fp = uc->uc_mcontext.gregs[REG_EBP];
1568 #endif
1569 for(i=1;i<level;i++) {
1570 /* XXX: check address validity with program info */
1571 if (fp <= 0x1000 || fp >= 0xc0000000)
1572 return -1;
1573 fp = ((unsigned long *)fp)[0];
1575 *paddr = ((unsigned long *)fp)[1];
1576 return 0;
1579 #elif defined(__x86_64__)
1580 /* return the PC at frame level 'level'. Return non zero if not found */
1581 static int rt_get_caller_pc(unsigned long *paddr,
1582 ucontext_t *uc, int level)
1584 unsigned long fp;
1585 int i;
1587 if (level == 0) {
1588 /* XXX: only support linux */
1589 #if defined(__FreeBSD__)
1590 *paddr = uc->uc_mcontext.mc_rip;
1591 #else
1592 *paddr = uc->uc_mcontext.gregs[REG_RIP];
1593 #endif
1594 return 0;
1595 } else {
1596 #if defined(__FreeBSD__)
1597 fp = uc->uc_mcontext.mc_rbp;
1598 #else
1599 fp = uc->uc_mcontext.gregs[REG_RBP];
1600 #endif
1601 for(i=1;i<level;i++) {
1602 /* XXX: check address validity with program info */
1603 if (fp <= 0x1000)
1604 return -1;
1605 fp = ((unsigned long *)fp)[0];
1607 *paddr = ((unsigned long *)fp)[1];
1608 return 0;
1611 #else
1612 #warning add arch specific rt_get_caller_pc()
1613 static int rt_get_caller_pc(unsigned long *paddr,
1614 ucontext_t *uc, int level)
1616 return -1;
1618 #endif
1620 /* emit a run time error at position 'pc' */
1621 void rt_error(ucontext_t *uc, const char *fmt, ...)
1623 va_list ap;
1624 unsigned long pc;
1625 int i;
1627 va_start(ap, fmt);
1628 fprintf(stderr, "Runtime error: ");
1629 vfprintf(stderr, fmt, ap);
1630 fprintf(stderr, "\n");
1631 for(i=0;i<num_callers;i++) {
1632 if (rt_get_caller_pc(&pc, uc, i) < 0)
1633 break;
1634 if (i == 0)
1635 fprintf(stderr, "at ");
1636 else
1637 fprintf(stderr, "by ");
1638 pc = rt_printline(pc);
1639 if (pc == rt_prog_main && pc)
1640 break;
1642 exit(255);
1643 va_end(ap);
1646 /* signal handler for fatal errors */
1647 static void sig_error(int signum, siginfo_t *siginf, void *puc)
1649 ucontext_t *uc = puc;
1651 switch(signum) {
1652 case SIGFPE:
1653 switch(siginf->si_code) {
1654 case FPE_INTDIV:
1655 case FPE_FLTDIV:
1656 rt_error(uc, "division by zero");
1657 break;
1658 default:
1659 rt_error(uc, "floating point exception");
1660 break;
1662 break;
1663 case SIGBUS:
1664 case SIGSEGV:
1665 if (rt_bound_error_msg && *rt_bound_error_msg)
1666 rt_error(uc, *rt_bound_error_msg);
1667 else
1668 rt_error(uc, "dereferencing invalid pointer");
1669 break;
1670 case SIGILL:
1671 rt_error(uc, "illegal instruction");
1672 break;
1673 case SIGABRT:
1674 rt_error(uc, "abort() called");
1675 break;
1676 default:
1677 rt_error(uc, "caught signal %d", signum);
1678 break;
1680 exit(255);
1683 #endif
1685 /* copy code into memory passed in by the caller and do all relocations
1686 (needed before using tcc_get_symbol()).
1687 returns -1 on error and required size if ptr is NULL */
1688 int tcc_relocate(TCCState *s1, void *ptr)
1690 Section *s;
1691 unsigned long offset, length;
1692 uplong mem;
1693 int i;
1695 if (0 == s1->runtime_added) {
1696 s1->runtime_added = 1;
1697 s1->nb_errors = 0;
1698 #ifdef TCC_TARGET_PE
1699 pe_output_file(s1, NULL);
1700 #else
1701 tcc_add_runtime(s1);
1702 relocate_common_syms();
1703 tcc_add_linker_symbols(s1);
1704 build_got_entries(s1);
1705 #endif
1706 if (s1->nb_errors)
1707 return -1;
1710 offset = 0, mem = (uplong)ptr;
1711 for(i = 1; i < s1->nb_sections; i++) {
1712 s = s1->sections[i];
1713 if (0 == (s->sh_flags & SHF_ALLOC))
1714 continue;
1715 length = s->data_offset;
1716 s->sh_addr = mem ? (mem + offset + 15) & ~15 : 0;
1717 offset = (offset + length + 15) & ~15;
1720 /* relocate symbols */
1721 relocate_syms(s1, 1);
1722 if (s1->nb_errors)
1723 return -1;
1725 #ifndef TCC_TARGET_PE
1726 #ifdef TCC_TARGET_X86_64
1727 s1->runtime_plt_and_got_offset = 0;
1728 s1->runtime_plt_and_got = (char *)(mem + offset);
1729 /* double the size of the buffer for got and plt entries
1730 XXX: calculate exact size for them? */
1731 offset *= 2;
1732 #endif
1733 #endif
1735 if (0 == mem)
1736 return offset + 15;
1738 /* relocate each section */
1739 for(i = 1; i < s1->nb_sections; i++) {
1740 s = s1->sections[i];
1741 if (s->reloc)
1742 relocate_section(s1, s);
1745 for(i = 1; i < s1->nb_sections; i++) {
1746 s = s1->sections[i];
1747 if (0 == (s->sh_flags & SHF_ALLOC))
1748 continue;
1749 length = s->data_offset;
1750 // printf("%-12s %08x %04x\n", s->name, s->sh_addr, length);
1751 ptr = (void*)(uplong)s->sh_addr;
1752 if (NULL == s->data || s->sh_type == SHT_NOBITS)
1753 memset(ptr, 0, length);
1754 else
1755 memcpy(ptr, s->data, length);
1756 /* mark executable sections as executable in memory */
1757 if (s->sh_flags & SHF_EXECINSTR)
1758 set_pages_executable(ptr, length);
1760 #ifndef TCC_TARGET_PE
1761 #ifdef TCC_TARGET_X86_64
1762 set_pages_executable(s1->runtime_plt_and_got,
1763 s1->runtime_plt_and_got_offset);
1764 #endif
1765 #endif
1766 return 0;
1769 /* launch the compiled program with the given arguments */
1770 int tcc_run(TCCState *s1, int argc, char **argv)
1772 int (*prog_main)(int, char **);
1773 void *ptr;
1774 int ret;
1776 ret = tcc_relocate(s1, NULL);
1777 if (ret < 0)
1778 return -1;
1779 ptr = tcc_malloc(ret);
1780 tcc_relocate(s1, ptr);
1782 prog_main = tcc_get_symbol_err(s1, "main");
1784 if (s1->do_debug) {
1785 #ifdef CONFIG_TCC_BACKTRACE
1786 struct sigaction sigact;
1787 /* install TCC signal handlers to print debug info on fatal
1788 runtime errors */
1789 sigact.sa_flags = SA_SIGINFO | SA_RESETHAND;
1790 sigact.sa_sigaction = sig_error;
1791 sigemptyset(&sigact.sa_mask);
1792 sigaction(SIGFPE, &sigact, NULL);
1793 sigaction(SIGILL, &sigact, NULL);
1794 sigaction(SIGSEGV, &sigact, NULL);
1795 sigaction(SIGBUS, &sigact, NULL);
1796 sigaction(SIGABRT, &sigact, NULL);
1797 #else
1798 error("debug mode not available");
1799 #endif
1802 #ifdef CONFIG_TCC_BCHECK
1803 if (s1->do_bounds_check) {
1804 void (*bound_init)(void);
1805 void (*bound_exit)(void);
1806 /* set error function */
1807 rt_bound_error_msg = tcc_get_symbol_err(s1, "__bound_error_msg");
1808 rt_prog_main = (unsigned long)prog_main;
1809 /* XXX: use .init section so that it also work in binary ? */
1810 bound_init = tcc_get_symbol_err(s1, "__bound_init");
1811 bound_exit = tcc_get_symbol_err(s1, "__bound_exit");
1812 bound_init();
1813 ret = (*prog_main)(argc, argv);
1814 bound_exit();
1815 } else
1816 #endif
1817 ret = (*prog_main)(argc, argv);
1818 tcc_free(ptr);
1819 return ret;
1822 void tcc_memstats(void)
1824 #ifdef MEM_DEBUG
1825 printf("memory in use: %d\n", mem_cur_size);
1826 #endif
1829 static void tcc_cleanup(void)
1831 int i, n;
1833 if (NULL == tcc_state)
1834 return;
1835 tcc_state = NULL;
1837 /* free -D defines */
1838 free_defines(NULL);
1840 /* free tokens */
1841 n = tok_ident - TOK_IDENT;
1842 for(i = 0; i < n; i++)
1843 tcc_free(table_ident[i]);
1844 tcc_free(table_ident);
1846 /* free sym_pools */
1847 dynarray_reset(&sym_pools, &nb_sym_pools);
1848 /* string buffer */
1849 cstr_free(&tokcstr);
1850 /* reset symbol stack */
1851 sym_free_first = NULL;
1852 /* cleanup from error/setjmp */
1853 macro_ptr = NULL;
1856 TCCState *tcc_new(void)
1858 TCCState *s;
1859 char buffer[100];
1860 int a,b,c;
1862 tcc_cleanup();
1864 s = tcc_mallocz(sizeof(TCCState));
1865 if (!s)
1866 return NULL;
1867 tcc_state = s;
1868 #ifdef _WIN32
1869 tcc_set_lib_path_w32(s);
1870 #else
1871 tcc_set_lib_path(s, CONFIG_TCCDIR);
1872 #endif
1873 s->output_type = TCC_OUTPUT_MEMORY;
1874 preprocess_new();
1876 /* we add dummy defines for some special macros to speed up tests
1877 and to have working defined() */
1878 define_push(TOK___LINE__, MACRO_OBJ, NULL, NULL);
1879 define_push(TOK___FILE__, MACRO_OBJ, NULL, NULL);
1880 define_push(TOK___DATE__, MACRO_OBJ, NULL, NULL);
1881 define_push(TOK___TIME__, MACRO_OBJ, NULL, NULL);
1883 /* standard defines */
1884 tcc_define_symbol(s, "__STDC__", NULL);
1885 tcc_define_symbol(s, "__STDC_VERSION__", "199901L");
1886 #if defined(TCC_TARGET_I386)
1887 tcc_define_symbol(s, "__i386__", "1");
1888 tcc_define_symbol(s, "__i386", "1");
1889 tcc_define_symbol(s, "i386", "1");
1890 #endif
1891 #if defined(TCC_TARGET_X86_64)
1892 tcc_define_symbol(s, "__x86_64__", NULL);
1893 #endif
1894 #if defined(TCC_TARGET_ARM)
1895 tcc_define_symbol(s, "__ARM_ARCH_4__", NULL);
1896 tcc_define_symbol(s, "__arm_elf__", NULL);
1897 tcc_define_symbol(s, "__arm_elf", NULL);
1898 tcc_define_symbol(s, "arm_elf", NULL);
1899 tcc_define_symbol(s, "__arm__", NULL);
1900 tcc_define_symbol(s, "__arm", NULL);
1901 tcc_define_symbol(s, "arm", NULL);
1902 tcc_define_symbol(s, "__APCS_32__", NULL);
1903 #endif
1904 #ifdef TCC_TARGET_PE
1905 tcc_define_symbol(s, "_WIN32", NULL);
1906 #ifdef TCC_TARGET_X86_64
1907 tcc_define_symbol(s, "_WIN64", NULL);
1908 #endif
1909 #else
1910 tcc_define_symbol(s, "__unix__", "1");
1911 tcc_define_symbol(s, "__unix", "1");
1912 tcc_define_symbol(s, "unix", "1");
1913 #if defined(__FreeBSD__)
1914 #define str(s) #s
1915 tcc_define_symbol(s, "__FreeBSD__", str( __FreeBSD__));
1916 tcc_define_symbol(s, "__INTEL_COMPILER", "1");
1917 #undef str
1918 #endif
1919 #if defined(__linux)
1920 tcc_define_symbol(s, "__linux__", NULL);
1921 tcc_define_symbol(s, "__linux", NULL);
1922 #endif
1923 #endif
1924 /* tiny C specific defines */
1925 sscanf(TCC_VERSION, "%d.%d.%d", &a, &b, &c);
1926 sprintf(buffer, "%d", a*10000 + b*100 + c);
1927 tcc_define_symbol(s, "__TINYC__", buffer);
1929 /* tiny C & gcc defines */
1930 tcc_define_symbol(s, "__SIZE_TYPE__", "unsigned long");
1931 tcc_define_symbol(s, "__PTRDIFF_TYPE__", "long");
1932 #ifdef TCC_TARGET_PE
1933 tcc_define_symbol(s, "__WCHAR_TYPE__", "unsigned short");
1934 #else
1935 tcc_define_symbol(s, "__WCHAR_TYPE__", "int");
1936 #endif
1938 #ifndef TCC_TARGET_PE
1939 /* default library paths */
1940 tcc_add_library_path(s, CONFIG_SYSROOT "/usr/local/lib");
1941 tcc_add_library_path(s, CONFIG_SYSROOT "/usr/lib");
1942 tcc_add_library_path(s, CONFIG_SYSROOT "/lib");
1943 #endif
1945 /* no section zero */
1946 dynarray_add((void ***)&s->sections, &s->nb_sections, NULL);
1948 /* create standard sections */
1949 text_section = new_section(s, ".text", SHT_PROGBITS, SHF_ALLOC | SHF_EXECINSTR);
1950 data_section = new_section(s, ".data", SHT_PROGBITS, SHF_ALLOC | SHF_WRITE);
1951 bss_section = new_section(s, ".bss", SHT_NOBITS, SHF_ALLOC | SHF_WRITE);
1953 /* symbols are always generated for linking stage */
1954 symtab_section = new_symtab(s, ".symtab", SHT_SYMTAB, 0,
1955 ".strtab",
1956 ".hashtab", SHF_PRIVATE);
1957 strtab_section = symtab_section->link;
1959 /* private symbol table for dynamic symbols */
1960 s->dynsymtab_section = new_symtab(s, ".dynsymtab", SHT_SYMTAB, SHF_PRIVATE,
1961 ".dynstrtab",
1962 ".dynhashtab", SHF_PRIVATE);
1963 s->alacarte_link = 1;
1965 #ifdef CHAR_IS_UNSIGNED
1966 s->char_is_unsigned = 1;
1967 #endif
1968 #if defined(TCC_TARGET_PE) && 0
1969 /* XXX: currently the PE linker is not ready to support that */
1970 s->leading_underscore = 1;
1971 #endif
1973 if (s->section_align == 0)
1974 s->section_align = ELF_PAGE_SIZE;
1976 #ifdef TCC_TARGET_I386
1977 s->seg_size = 32;
1978 #endif
1979 return s;
1982 void tcc_delete(TCCState *s1)
1984 int i;
1986 tcc_cleanup();
1988 /* free all sections */
1989 for(i = 1; i < s1->nb_sections; i++)
1990 free_section(s1->sections[i]);
1991 dynarray_reset(&s1->sections, &s1->nb_sections);
1993 for(i = 0; i < s1->nb_priv_sections; i++)
1994 free_section(s1->priv_sections[i]);
1995 dynarray_reset(&s1->priv_sections, &s1->nb_priv_sections);
1997 /* free any loaded DLLs */
1998 for ( i = 0; i < s1->nb_loaded_dlls; i++) {
1999 DLLReference *ref = s1->loaded_dlls[i];
2000 if ( ref->handle )
2001 dlclose(ref->handle);
2004 /* free loaded dlls array */
2005 dynarray_reset(&s1->loaded_dlls, &s1->nb_loaded_dlls);
2007 /* free library paths */
2008 dynarray_reset(&s1->library_paths, &s1->nb_library_paths);
2010 /* free include paths */
2011 dynarray_reset(&s1->cached_includes, &s1->nb_cached_includes);
2012 dynarray_reset(&s1->include_paths, &s1->nb_include_paths);
2013 dynarray_reset(&s1->sysinclude_paths, &s1->nb_sysinclude_paths);
2015 tcc_free(s1->tcc_lib_path);
2016 tcc_free(s1);
2019 int tcc_add_include_path(TCCState *s1, const char *pathname)
2021 char *pathname1;
2023 pathname1 = tcc_strdup(pathname);
2024 dynarray_add((void ***)&s1->include_paths, &s1->nb_include_paths, pathname1);
2025 return 0;
2028 int tcc_add_sysinclude_path(TCCState *s1, const char *pathname)
2030 char *pathname1;
2032 pathname1 = tcc_strdup(pathname);
2033 dynarray_add((void ***)&s1->sysinclude_paths, &s1->nb_sysinclude_paths, pathname1);
2034 return 0;
2037 static int tcc_add_file_internal(TCCState *s1, const char *filename, int flags)
2039 const char *ext;
2040 ElfW(Ehdr) ehdr;
2041 int fd, ret, size;
2042 BufferedFile *saved_file;
2044 ret = -1;
2046 /* find source file type with extension */
2047 ext = tcc_fileextension(filename);
2048 if (ext[0])
2049 ext++;
2051 /* open the file */
2052 saved_file = file;
2053 file = tcc_open(s1, filename);
2054 if (!file) {
2055 if (flags & AFF_PRINT_ERROR)
2056 error_noabort("file '%s' not found", filename);
2057 goto the_end;
2060 if (flags & AFF_PREPROCESS) {
2061 ret = tcc_preprocess(s1);
2062 goto the_end;
2065 if (!ext[0] || !PATHCMP(ext, "c")) {
2066 /* C file assumed */
2067 ret = tcc_compile(s1);
2068 goto the_end;
2071 #ifdef CONFIG_TCC_ASM
2072 if (!strcmp(ext, "S")) {
2073 /* preprocessed assembler */
2074 ret = tcc_assemble(s1, 1);
2075 goto the_end;
2078 if (!strcmp(ext, "s")) {
2079 /* non preprocessed assembler */
2080 ret = tcc_assemble(s1, 0);
2081 goto the_end;
2083 #endif
2085 fd = file->fd;
2086 /* assume executable format: auto guess file type */
2087 size = read(fd, &ehdr, sizeof(ehdr));
2088 lseek(fd, 0, SEEK_SET);
2089 if (size <= 0) {
2090 error_noabort("could not read header");
2091 goto the_end;
2094 if (size == sizeof(ehdr) &&
2095 ehdr.e_ident[0] == ELFMAG0 &&
2096 ehdr.e_ident[1] == ELFMAG1 &&
2097 ehdr.e_ident[2] == ELFMAG2 &&
2098 ehdr.e_ident[3] == ELFMAG3) {
2100 /* do not display line number if error */
2101 file->line_num = 0;
2102 if (ehdr.e_type == ET_REL) {
2103 ret = tcc_load_object_file(s1, fd, 0);
2104 goto the_end;
2107 #ifndef TCC_TARGET_PE
2108 if (ehdr.e_type == ET_DYN) {
2109 if (s1->output_type == TCC_OUTPUT_MEMORY) {
2110 void *h;
2111 h = dlopen(filename, RTLD_GLOBAL | RTLD_LAZY);
2112 if (h)
2113 ret = 0;
2114 } else {
2115 ret = tcc_load_dll(s1, fd, filename,
2116 (flags & AFF_REFERENCED_DLL) != 0);
2118 goto the_end;
2120 #endif
2121 error_noabort("unrecognized ELF file");
2122 goto the_end;
2125 if (memcmp((char *)&ehdr, ARMAG, 8) == 0) {
2126 file->line_num = 0; /* do not display line number if error */
2127 ret = tcc_load_archive(s1, fd);
2128 goto the_end;
2131 #ifdef TCC_TARGET_COFF
2132 if (*(uint16_t *)(&ehdr) == COFF_C67_MAGIC) {
2133 ret = tcc_load_coff(s1, fd);
2134 goto the_end;
2136 #endif
2138 #ifdef TCC_TARGET_PE
2139 ret = pe_load_file(s1, filename, fd);
2140 #else
2141 /* as GNU ld, consider it is an ld script if not recognized */
2142 ret = tcc_load_ldscript(s1);
2143 #endif
2144 if (ret < 0)
2145 error_noabort("unrecognized file type");
2147 the_end:
2148 if (file)
2149 tcc_close(file);
2150 file = saved_file;
2151 return ret;
2154 int tcc_add_file(TCCState *s, const char *filename)
2156 if (s->output_type == TCC_OUTPUT_PREPROCESS)
2157 return tcc_add_file_internal(s, filename, AFF_PRINT_ERROR | AFF_PREPROCESS);
2158 else
2159 return tcc_add_file_internal(s, filename, AFF_PRINT_ERROR);
2162 int tcc_add_library_path(TCCState *s, const char *pathname)
2164 char *pathname1;
2166 pathname1 = tcc_strdup(pathname);
2167 dynarray_add((void ***)&s->library_paths, &s->nb_library_paths, pathname1);
2168 return 0;
2171 /* find and load a dll. Return non zero if not found */
2172 /* XXX: add '-rpath' option support ? */
2173 static int tcc_add_dll(TCCState *s, const char *filename, int flags)
2175 char buf[1024];
2176 int i;
2178 for(i = 0; i < s->nb_library_paths; i++) {
2179 snprintf(buf, sizeof(buf), "%s/%s",
2180 s->library_paths[i], filename);
2181 if (tcc_add_file_internal(s, buf, flags) == 0)
2182 return 0;
2184 return -1;
2187 /* the library name is the same as the argument of the '-l' option */
2188 int tcc_add_library(TCCState *s, const char *libraryname)
2190 char buf[1024];
2191 int i;
2193 /* first we look for the dynamic library if not static linking */
2194 if (!s->static_link) {
2195 #ifdef TCC_TARGET_PE
2196 if (pe_add_dll(s, libraryname) == 0)
2197 return 0;
2198 #else
2199 snprintf(buf, sizeof(buf), "lib%s.so", libraryname);
2200 if (tcc_add_dll(s, buf, 0) == 0)
2201 return 0;
2202 #endif
2204 /* then we look for the static library */
2205 for(i = 0; i < s->nb_library_paths; i++) {
2206 snprintf(buf, sizeof(buf), "%s/lib%s.a",
2207 s->library_paths[i], libraryname);
2208 if (tcc_add_file_internal(s, buf, 0) == 0)
2209 return 0;
2211 return -1;
2214 int tcc_add_symbol(TCCState *s, const char *name, void *val)
2216 add_elf_sym(symtab_section, (uplong)val, 0,
2217 ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE), 0,
2218 SHN_ABS, name);
2219 return 0;
2222 int tcc_set_output_type(TCCState *s, int output_type)
2224 char buf[1024];
2226 s->output_type = output_type;
2228 if (!s->nostdinc) {
2229 /* default include paths */
2230 /* XXX: reverse order needed if -isystem support */
2231 #ifndef TCC_TARGET_PE
2232 tcc_add_sysinclude_path(s, CONFIG_SYSROOT "/usr/local/include");
2233 tcc_add_sysinclude_path(s, CONFIG_SYSROOT "/usr/include");
2234 #endif
2235 snprintf(buf, sizeof(buf), "%s/include", s->tcc_lib_path);
2236 tcc_add_sysinclude_path(s, buf);
2237 #ifdef TCC_TARGET_PE
2238 snprintf(buf, sizeof(buf), "%s/include/winapi", s->tcc_lib_path);
2239 tcc_add_sysinclude_path(s, buf);
2240 #endif
2243 /* if bound checking, then add corresponding sections */
2244 #ifdef CONFIG_TCC_BCHECK
2245 if (s->do_bounds_check) {
2246 /* define symbol */
2247 tcc_define_symbol(s, "__BOUNDS_CHECKING_ON", NULL);
2248 /* create bounds sections */
2249 bounds_section = new_section(s, ".bounds",
2250 SHT_PROGBITS, SHF_ALLOC);
2251 lbounds_section = new_section(s, ".lbounds",
2252 SHT_PROGBITS, SHF_ALLOC);
2254 #endif
2256 if (s->char_is_unsigned) {
2257 tcc_define_symbol(s, "__CHAR_UNSIGNED__", NULL);
2260 /* add debug sections */
2261 if (s->do_debug) {
2262 /* stab symbols */
2263 stab_section = new_section(s, ".stab", SHT_PROGBITS, 0);
2264 stab_section->sh_entsize = sizeof(Stab_Sym);
2265 stabstr_section = new_section(s, ".stabstr", SHT_STRTAB, 0);
2266 put_elf_str(stabstr_section, "");
2267 stab_section->link = stabstr_section;
2268 /* put first entry */
2269 put_stabs("", 0, 0, 0, 0);
2272 /* add libc crt1/crti objects */
2273 #ifndef TCC_TARGET_PE
2274 if ((output_type == TCC_OUTPUT_EXE || output_type == TCC_OUTPUT_DLL) &&
2275 !s->nostdlib) {
2276 if (output_type != TCC_OUTPUT_DLL)
2277 tcc_add_file(s, CONFIG_TCC_CRT_PREFIX "/crt1.o");
2278 tcc_add_file(s, CONFIG_TCC_CRT_PREFIX "/crti.o");
2280 #endif
2282 #ifdef TCC_TARGET_PE
2283 snprintf(buf, sizeof(buf), "%s/lib", s->tcc_lib_path);
2284 tcc_add_library_path(s, buf);
2285 #ifdef _WIN32
2286 if (GetSystemDirectory(buf, sizeof buf))
2287 tcc_add_library_path(s, buf);
2288 #endif
2289 #endif
2291 return 0;
2294 #define WD_ALL 0x0001 /* warning is activated when using -Wall */
2295 #define FD_INVERT 0x0002 /* invert value before storing */
2297 typedef struct FlagDef {
2298 uint16_t offset;
2299 uint16_t flags;
2300 const char *name;
2301 } FlagDef;
2303 static const FlagDef warning_defs[] = {
2304 { offsetof(TCCState, warn_unsupported), 0, "unsupported" },
2305 { offsetof(TCCState, warn_write_strings), 0, "write-strings" },
2306 { offsetof(TCCState, warn_error), 0, "error" },
2307 { offsetof(TCCState, warn_implicit_function_declaration), WD_ALL,
2308 "implicit-function-declaration" },
2311 static int set_flag(TCCState *s, const FlagDef *flags, int nb_flags,
2312 const char *name, int value)
2314 int i;
2315 const FlagDef *p;
2316 const char *r;
2318 r = name;
2319 if (r[0] == 'n' && r[1] == 'o' && r[2] == '-') {
2320 r += 3;
2321 value = !value;
2323 for(i = 0, p = flags; i < nb_flags; i++, p++) {
2324 if (!strcmp(r, p->name))
2325 goto found;
2327 return -1;
2328 found:
2329 if (p->flags & FD_INVERT)
2330 value = !value;
2331 *(int *)((uint8_t *)s + p->offset) = value;
2332 return 0;
2336 /* set/reset a warning */
2337 int tcc_set_warning(TCCState *s, const char *warning_name, int value)
2339 int i;
2340 const FlagDef *p;
2342 if (!strcmp(warning_name, "all")) {
2343 for(i = 0, p = warning_defs; i < countof(warning_defs); i++, p++) {
2344 if (p->flags & WD_ALL)
2345 *(int *)((uint8_t *)s + p->offset) = 1;
2347 return 0;
2348 } else {
2349 return set_flag(s, warning_defs, countof(warning_defs),
2350 warning_name, value);
2354 static const FlagDef flag_defs[] = {
2355 { offsetof(TCCState, char_is_unsigned), 0, "unsigned-char" },
2356 { offsetof(TCCState, char_is_unsigned), FD_INVERT, "signed-char" },
2357 { offsetof(TCCState, nocommon), FD_INVERT, "common" },
2358 { offsetof(TCCState, leading_underscore), 0, "leading-underscore" },
2361 /* set/reset a flag */
2362 int tcc_set_flag(TCCState *s, const char *flag_name, int value)
2364 return set_flag(s, flag_defs, countof(flag_defs),
2365 flag_name, value);
2368 /* set CONFIG_TCCDIR at runtime */
2369 void tcc_set_lib_path(TCCState *s, const char *path)
2371 tcc_free(s->tcc_lib_path);
2372 s->tcc_lib_path = tcc_strdup(path);
2375 void tcc_print_stats(TCCState *s, int64_t total_time)
2377 double tt;
2378 tt = (double)total_time / 1000000.0;
2379 if (tt < 0.001)
2380 tt = 0.001;
2381 if (total_bytes < 1)
2382 total_bytes = 1;
2383 printf("%d idents, %d lines, %d bytes, %0.3f s, %d lines/s, %0.1f MB/s\n",
2384 tok_ident - TOK_IDENT, total_lines, total_bytes,
2385 tt, (int)(total_lines / tt),
2386 total_bytes / tt / 1000000.0);