cleanup: stop abuse of sym->c for #define tokenstreams
[tinycc.git] / libtcc.c
blob43293e2d86f1609c0823076dd1820611dfda998d
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, unsigned long 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 void *resolve_sym(TCCState *s1, const char *sym, int type);
216 int pe_load_def_file(struct TCCState *s1, int fd);
217 int pe_test_res_file(void *v, int size);
218 int pe_load_res_file(struct TCCState *s1, int fd);
219 void pe_add_runtime(struct TCCState *s1);
220 void pe_guess_outfile(char *objfilename, int output_type);
221 int pe_output_file(struct TCCState *s1, const char *filename);
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);
284 static inline int isid(int c)
286 return (c >= 'a' && c <= 'z')
287 || (c >= 'A' && c <= 'Z')
288 || c == '_';
291 static inline int isnum(int c)
293 return c >= '0' && c <= '9';
296 static inline int isoct(int c)
298 return c >= '0' && c <= '7';
301 static inline int toup(int c)
303 if (c >= 'a' && c <= 'z')
304 return c - 'a' + 'A';
305 else
306 return c;
309 void *resolve_sym(TCCState *s1, const char *sym, int type);
311 /********************************************************/
313 #ifdef TCC_TARGET_I386
314 #include "i386-gen.c"
315 #endif
317 #ifdef TCC_TARGET_ARM
318 #include "arm-gen.c"
319 #endif
321 #ifdef TCC_TARGET_C67
322 #include "c67-gen.c"
323 #endif
325 #ifdef TCC_TARGET_X86_64
326 #include "x86_64-gen.c"
327 #endif
329 #include "tccpp.c"
330 #include "tccgen.c"
332 #ifdef CONFIG_TCC_ASM
333 #ifdef TCC_TARGET_I386
334 #include "i386-asm.c"
335 #endif
336 #include "tccasm.c"
337 #else
338 static void asm_instr(void)
340 error("inline asm() not supported");
342 static void asm_global_instr(void)
344 error("inline asm() not supported");
346 #endif
348 #include "tccelf.c"
350 #ifdef TCC_TARGET_COFF
351 #include "tcccoff.c"
352 #endif
354 #ifdef TCC_TARGET_PE
355 #include "tccpe.c"
356 #endif
358 /********************************************************/
359 #ifdef CONFIG_TCC_STATIC
361 #define RTLD_LAZY 0x001
362 #define RTLD_NOW 0x002
363 #define RTLD_GLOBAL 0x100
364 #define RTLD_DEFAULT NULL
366 /* dummy function for profiling */
367 void *dlopen(const char *filename, int flag)
369 return NULL;
372 void dlclose(void *p)
376 const char *dlerror(void)
378 return "error";
381 typedef struct TCCSyms {
382 char *str;
383 void *ptr;
384 } TCCSyms;
386 #define TCCSYM(a) { #a, &a, },
388 /* add the symbol you want here if no dynamic linking is done */
389 static TCCSyms tcc_syms[] = {
390 #if !defined(CONFIG_TCCBOOT)
391 TCCSYM(printf)
392 TCCSYM(fprintf)
393 TCCSYM(fopen)
394 TCCSYM(fclose)
395 #endif
396 { NULL, NULL },
399 void *resolve_sym(TCCState *s1, const char *symbol, int type)
401 TCCSyms *p;
402 p = tcc_syms;
403 while (p->str != NULL) {
404 if (!strcmp(p->str, symbol))
405 return p->ptr;
406 p++;
408 return NULL;
411 #elif !defined(_WIN32)
413 #include <dlfcn.h>
415 void *resolve_sym(TCCState *s1, const char *sym, int type)
417 return dlsym(RTLD_DEFAULT, sym);
420 #endif
422 /********************************************************/
424 /* we use our own 'finite' function to avoid potential problems with
425 non standard math libs */
426 /* XXX: endianness dependent */
427 int ieee_finite(double d)
429 int *p = (int *)&d;
430 return ((unsigned)((p[1] | 0x800fffff) + 1)) >> 31;
433 /* copy a string and truncate it. */
434 char *pstrcpy(char *buf, int buf_size, const char *s)
436 char *q, *q_end;
437 int c;
439 if (buf_size > 0) {
440 q = buf;
441 q_end = buf + buf_size - 1;
442 while (q < q_end) {
443 c = *s++;
444 if (c == '\0')
445 break;
446 *q++ = c;
448 *q = '\0';
450 return buf;
453 /* strcat and truncate. */
454 char *pstrcat(char *buf, int buf_size, const char *s)
456 int len;
457 len = strlen(buf);
458 if (len < buf_size)
459 pstrcpy(buf + len, buf_size - len, s);
460 return buf;
463 /* extract the basename of a file */
464 char *tcc_basename(const char *name)
466 char *p = strchr(name, 0);
467 while (p > name && !IS_PATHSEP(p[-1]))
468 --p;
469 return p;
472 char *tcc_fileextension (const char *name)
474 char *b = tcc_basename(name);
475 char *e = strrchr(b, '.');
476 return e ? e : strchr(b, 0);
479 #ifdef _WIN32
480 char *normalize_slashes(char *path)
482 char *p;
483 for (p = path; *p; ++p)
484 if (*p == '\\')
485 *p = '/';
486 return path;
489 void tcc_set_lib_path_w32(TCCState *s)
491 /* on win32, we suppose the lib and includes are at the location
492 of 'tcc.exe' */
493 char path[1024], *p;
494 GetModuleFileNameA(NULL, path, sizeof path);
495 p = tcc_basename(normalize_slashes(strlwr(path)));
496 if (p - 5 > path && 0 == strncmp(p - 5, "/bin/", 5))
497 p -= 5;
498 else if (p > path)
499 p--;
500 *p = 0;
501 tcc_set_lib_path(s, path);
503 #endif
505 void set_pages_executable(void *ptr, unsigned long length)
507 #ifdef _WIN32
508 unsigned long old_protect;
509 VirtualProtect(ptr, length, PAGE_EXECUTE_READWRITE, &old_protect);
510 #else
511 unsigned long start, end;
512 start = (unsigned long)ptr & ~(PAGESIZE - 1);
513 end = (unsigned long)ptr + length;
514 end = (end + PAGESIZE - 1) & ~(PAGESIZE - 1);
515 mprotect((void *)start, end - start, PROT_READ | PROT_WRITE | PROT_EXEC);
516 #endif
519 /* memory management */
520 #ifdef MEM_DEBUG
521 int mem_cur_size;
522 int mem_max_size;
523 unsigned malloc_usable_size(void*);
524 #endif
526 void tcc_free(void *ptr)
528 #ifdef MEM_DEBUG
529 mem_cur_size -= malloc_usable_size(ptr);
530 #endif
531 free(ptr);
534 void *tcc_malloc(unsigned long size)
536 void *ptr;
537 ptr = malloc(size);
538 if (!ptr && size)
539 error("memory full");
540 #ifdef MEM_DEBUG
541 mem_cur_size += malloc_usable_size(ptr);
542 if (mem_cur_size > mem_max_size)
543 mem_max_size = mem_cur_size;
544 #endif
545 return ptr;
548 void *tcc_mallocz(unsigned long size)
550 void *ptr;
551 ptr = tcc_malloc(size);
552 memset(ptr, 0, size);
553 return ptr;
556 void *tcc_realloc(void *ptr, unsigned long size)
558 void *ptr1;
559 #ifdef MEM_DEBUG
560 mem_cur_size -= malloc_usable_size(ptr);
561 #endif
562 ptr1 = realloc(ptr, size);
563 #ifdef MEM_DEBUG
564 /* NOTE: count not correct if alloc error, but not critical */
565 mem_cur_size += malloc_usable_size(ptr1);
566 if (mem_cur_size > mem_max_size)
567 mem_max_size = mem_cur_size;
568 #endif
569 return ptr1;
572 char *tcc_strdup(const char *str)
574 char *ptr;
575 ptr = tcc_malloc(strlen(str) + 1);
576 strcpy(ptr, str);
577 return ptr;
580 #define free(p) use_tcc_free(p)
581 #define malloc(s) use_tcc_malloc(s)
582 #define realloc(p, s) use_tcc_realloc(p, s)
584 void dynarray_add(void ***ptab, int *nb_ptr, void *data)
586 int nb, nb_alloc;
587 void **pp;
589 nb = *nb_ptr;
590 pp = *ptab;
591 /* every power of two we double array size */
592 if ((nb & (nb - 1)) == 0) {
593 if (!nb)
594 nb_alloc = 1;
595 else
596 nb_alloc = nb * 2;
597 pp = tcc_realloc(pp, nb_alloc * sizeof(void *));
598 if (!pp)
599 error("memory full");
600 *ptab = pp;
602 pp[nb++] = data;
603 *nb_ptr = nb;
606 void dynarray_reset(void *pp, int *n)
608 void **p;
609 for (p = *(void***)pp; *n; ++p, --*n)
610 if (*p)
611 tcc_free(*p);
612 tcc_free(*(void**)pp);
613 *(void**)pp = NULL;
616 /* symbol allocator */
617 static Sym *__sym_malloc(void)
619 Sym *sym_pool, *sym, *last_sym;
620 int i;
622 sym_pool = tcc_malloc(SYM_POOL_NB * sizeof(Sym));
623 dynarray_add(&sym_pools, &nb_sym_pools, sym_pool);
625 last_sym = sym_free_first;
626 sym = sym_pool;
627 for(i = 0; i < SYM_POOL_NB; i++) {
628 sym->next = last_sym;
629 last_sym = sym;
630 sym++;
632 sym_free_first = last_sym;
633 return last_sym;
636 static inline Sym *sym_malloc(void)
638 Sym *sym;
639 sym = sym_free_first;
640 if (!sym)
641 sym = __sym_malloc();
642 sym_free_first = sym->next;
643 return sym;
646 static inline void sym_free(Sym *sym)
648 sym->next = sym_free_first;
649 sym_free_first = sym;
652 Section *new_section(TCCState *s1, const char *name, int sh_type, int sh_flags)
654 Section *sec;
656 sec = tcc_mallocz(sizeof(Section) + strlen(name));
657 strcpy(sec->name, name);
658 sec->sh_type = sh_type;
659 sec->sh_flags = sh_flags;
660 switch(sh_type) {
661 case SHT_HASH:
662 case SHT_REL:
663 case SHT_RELA:
664 case SHT_DYNSYM:
665 case SHT_SYMTAB:
666 case SHT_DYNAMIC:
667 sec->sh_addralign = 4;
668 break;
669 case SHT_STRTAB:
670 sec->sh_addralign = 1;
671 break;
672 default:
673 sec->sh_addralign = 32; /* default conservative alignment */
674 break;
677 if (sh_flags & SHF_PRIVATE) {
678 dynarray_add((void ***)&s1->priv_sections, &s1->nb_priv_sections, sec);
679 } else {
680 sec->sh_num = s1->nb_sections;
681 dynarray_add((void ***)&s1->sections, &s1->nb_sections, sec);
684 return sec;
687 static void free_section(Section *s)
689 tcc_free(s->data);
692 /* realloc section and set its content to zero */
693 static void section_realloc(Section *sec, unsigned long new_size)
695 unsigned long size;
696 unsigned char *data;
698 size = sec->data_allocated;
699 if (size == 0)
700 size = 1;
701 while (size < new_size)
702 size = size * 2;
703 data = tcc_realloc(sec->data, size);
704 if (!data)
705 error("memory full");
706 memset(data + sec->data_allocated, 0, size - sec->data_allocated);
707 sec->data = data;
708 sec->data_allocated = size;
711 /* reserve at least 'size' bytes in section 'sec' from
712 sec->data_offset. */
713 static void *section_ptr_add(Section *sec, unsigned long size)
715 unsigned long offset, offset1;
717 offset = sec->data_offset;
718 offset1 = offset + size;
719 if (offset1 > sec->data_allocated)
720 section_realloc(sec, offset1);
721 sec->data_offset = offset1;
722 return sec->data + offset;
725 /* return a reference to a section, and create it if it does not
726 exists */
727 Section *find_section(TCCState *s1, const char *name)
729 Section *sec;
730 int i;
731 for(i = 1; i < s1->nb_sections; i++) {
732 sec = s1->sections[i];
733 if (!strcmp(name, sec->name))
734 return sec;
736 /* sections are created as PROGBITS */
737 return new_section(s1, name, SHT_PROGBITS, SHF_ALLOC);
740 /* update sym->c so that it points to an external symbol in section
741 'section' with value 'value' */
742 static void put_extern_sym2(Sym *sym, Section *section,
743 unsigned long value, unsigned long size,
744 int can_add_underscore)
746 int sym_type, sym_bind, sh_num, info, other, attr;
747 ElfW(Sym) *esym;
748 const char *name;
749 char buf1[256];
751 if (section == NULL)
752 sh_num = SHN_UNDEF;
753 else if (section == SECTION_ABS)
754 sh_num = SHN_ABS;
755 else
756 sh_num = section->sh_num;
758 other = attr = 0;
760 if ((sym->type.t & VT_BTYPE) == VT_FUNC) {
761 sym_type = STT_FUNC;
762 #ifdef TCC_TARGET_PE
763 if (sym->type.ref)
764 attr = sym->type.ref->r;
765 if (FUNC_EXPORT(attr))
766 other |= 1;
767 if (FUNC_CALL(attr) == FUNC_STDCALL)
768 other |= 2;
769 #endif
770 } else {
771 sym_type = STT_OBJECT;
774 if (sym->type.t & VT_STATIC)
775 sym_bind = STB_LOCAL;
776 else
777 sym_bind = STB_GLOBAL;
779 if (!sym->c) {
780 name = get_tok_str(sym->v, NULL);
781 #ifdef CONFIG_TCC_BCHECK
782 if (tcc_state->do_bounds_check) {
783 char buf[32];
785 /* XXX: avoid doing that for statics ? */
786 /* if bound checking is activated, we change some function
787 names by adding the "__bound" prefix */
788 switch(sym->v) {
789 #if 0
790 /* XXX: we rely only on malloc hooks */
791 case TOK_malloc:
792 case TOK_free:
793 case TOK_realloc:
794 case TOK_memalign:
795 case TOK_calloc:
796 #endif
797 case TOK_memcpy:
798 case TOK_memmove:
799 case TOK_memset:
800 case TOK_strlen:
801 case TOK_strcpy:
802 case TOK_alloca:
803 strcpy(buf, "__bound_");
804 strcat(buf, name);
805 name = buf;
806 break;
809 #endif
811 #ifdef TCC_TARGET_PE
812 if ((other & 2) && can_add_underscore) {
813 sprintf(buf1, "_%s@%d", name, FUNC_ARGS(attr));
814 name = buf1;
815 } else
816 #endif
817 if (tcc_state->leading_underscore && can_add_underscore) {
818 buf1[0] = '_';
819 pstrcpy(buf1 + 1, sizeof(buf1) - 1, name);
820 name = buf1;
822 info = ELFW(ST_INFO)(sym_bind, sym_type);
823 sym->c = add_elf_sym(symtab_section, value, size, info, other, sh_num, name);
824 } else {
825 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
826 esym->st_value = value;
827 esym->st_size = size;
828 esym->st_shndx = sh_num;
829 esym->st_other |= other;
833 static void put_extern_sym(Sym *sym, Section *section,
834 unsigned long value, unsigned long size)
836 put_extern_sym2(sym, section, value, size, 1);
839 /* add a new relocation entry to symbol 'sym' in section 's' */
840 static void greloc(Section *s, Sym *sym, unsigned long offset, int type)
842 if (!sym->c)
843 put_extern_sym(sym, NULL, 0, 0);
844 /* now we can add ELF relocation info */
845 put_elf_reloc(symtab_section, s, offset, type, sym->c);
848 static void strcat_vprintf(char *buf, int buf_size, const char *fmt, va_list ap)
850 int len;
851 len = strlen(buf);
852 vsnprintf(buf + len, buf_size - len, fmt, ap);
855 static void strcat_printf(char *buf, int buf_size, const char *fmt, ...)
857 va_list ap;
858 va_start(ap, fmt);
859 strcat_vprintf(buf, buf_size, fmt, ap);
860 va_end(ap);
863 void error1(TCCState *s1, int is_warning, const char *fmt, va_list ap)
865 char buf[2048];
866 BufferedFile **f;
868 buf[0] = '\0';
869 if (file) {
870 for(f = s1->include_stack; f < s1->include_stack_ptr; f++)
871 strcat_printf(buf, sizeof(buf), "In file included from %s:%d:\n",
872 (*f)->filename, (*f)->line_num);
873 if (file->line_num > 0) {
874 strcat_printf(buf, sizeof(buf),
875 "%s:%d: ", file->filename, file->line_num);
876 } else {
877 strcat_printf(buf, sizeof(buf),
878 "%s: ", file->filename);
880 } else {
881 strcat_printf(buf, sizeof(buf),
882 "tcc: ");
884 if (is_warning)
885 strcat_printf(buf, sizeof(buf), "warning: ");
886 else
887 strcat_printf(buf, sizeof(buf), "error: ");
888 strcat_vprintf(buf, sizeof(buf), fmt, ap);
890 if (!s1->error_func) {
891 /* default case: stderr */
892 fprintf(stderr, "%s\n", buf);
893 } else {
894 s1->error_func(s1->error_opaque, buf);
896 if (!is_warning || s1->warn_error)
897 s1->nb_errors++;
900 void tcc_set_error_func(TCCState *s, void *error_opaque,
901 void (*error_func)(void *opaque, const char *msg))
903 s->error_opaque = error_opaque;
904 s->error_func = error_func;
907 /* error without aborting current compilation */
908 void error_noabort(const char *fmt, ...)
910 TCCState *s1 = tcc_state;
911 va_list ap;
913 va_start(ap, fmt);
914 error1(s1, 0, fmt, ap);
915 va_end(ap);
918 void error(const char *fmt, ...)
920 TCCState *s1 = tcc_state;
921 va_list ap;
923 va_start(ap, fmt);
924 error1(s1, 0, fmt, ap);
925 va_end(ap);
926 /* better than nothing: in some cases, we accept to handle errors */
927 if (s1->error_set_jmp_enabled) {
928 longjmp(s1->error_jmp_buf, 1);
929 } else {
930 /* XXX: eliminate this someday */
931 exit(1);
935 void expect(const char *msg)
937 error("%s expected", msg);
940 void warning(const char *fmt, ...)
942 TCCState *s1 = tcc_state;
943 va_list ap;
945 if (s1->warn_none)
946 return;
948 va_start(ap, fmt);
949 error1(s1, 1, fmt, ap);
950 va_end(ap);
953 void skip(int c)
955 if (tok != c)
956 error("'%c' expected", c);
957 next();
960 static void test_lvalue(void)
962 if (!(vtop->r & VT_LVAL))
963 expect("lvalue");
966 /* CString handling */
968 static void cstr_realloc(CString *cstr, int new_size)
970 int size;
971 void *data;
973 size = cstr->size_allocated;
974 if (size == 0)
975 size = 8; /* no need to allocate a too small first string */
976 while (size < new_size)
977 size = size * 2;
978 data = tcc_realloc(cstr->data_allocated, size);
979 if (!data)
980 error("memory full");
981 cstr->data_allocated = data;
982 cstr->size_allocated = size;
983 cstr->data = data;
986 /* add a byte */
987 static inline void cstr_ccat(CString *cstr, int ch)
989 int size;
990 size = cstr->size + 1;
991 if (size > cstr->size_allocated)
992 cstr_realloc(cstr, size);
993 ((unsigned char *)cstr->data)[size - 1] = ch;
994 cstr->size = size;
997 static void cstr_cat(CString *cstr, const char *str)
999 int c;
1000 for(;;) {
1001 c = *str;
1002 if (c == '\0')
1003 break;
1004 cstr_ccat(cstr, c);
1005 str++;
1009 /* add a wide char */
1010 static void cstr_wccat(CString *cstr, int ch)
1012 int size;
1013 size = cstr->size + sizeof(nwchar_t);
1014 if (size > cstr->size_allocated)
1015 cstr_realloc(cstr, size);
1016 *(nwchar_t *)(((unsigned char *)cstr->data) + size - sizeof(nwchar_t)) = ch;
1017 cstr->size = size;
1020 static void cstr_new(CString *cstr)
1022 memset(cstr, 0, sizeof(CString));
1025 /* free string and reset it to NULL */
1026 static void cstr_free(CString *cstr)
1028 tcc_free(cstr->data_allocated);
1029 cstr_new(cstr);
1032 #define cstr_reset(cstr) cstr_free(cstr)
1034 /* XXX: unicode ? */
1035 static void add_char(CString *cstr, int c)
1037 if (c == '\'' || c == '\"' || c == '\\') {
1038 /* XXX: could be more precise if char or string */
1039 cstr_ccat(cstr, '\\');
1041 if (c >= 32 && c <= 126) {
1042 cstr_ccat(cstr, c);
1043 } else {
1044 cstr_ccat(cstr, '\\');
1045 if (c == '\n') {
1046 cstr_ccat(cstr, 'n');
1047 } else {
1048 cstr_ccat(cstr, '0' + ((c >> 6) & 7));
1049 cstr_ccat(cstr, '0' + ((c >> 3) & 7));
1050 cstr_ccat(cstr, '0' + (c & 7));
1055 /* push, without hashing */
1056 static Sym *sym_push2(Sym **ps, int v, int t, long c)
1058 Sym *s;
1059 s = sym_malloc();
1060 s->v = v;
1061 s->type.t = t;
1062 #ifdef _WIN64
1063 s->d = NULL;
1064 #endif
1065 s->c = c;
1066 s->next = NULL;
1067 /* add in stack */
1068 s->prev = *ps;
1069 *ps = s;
1070 return s;
1073 /* find a symbol and return its associated structure. 's' is the top
1074 of the symbol stack */
1075 static Sym *sym_find2(Sym *s, int v)
1077 while (s) {
1078 if (s->v == v)
1079 return s;
1080 s = s->prev;
1082 return NULL;
1085 /* structure lookup */
1086 static inline Sym *struct_find(int v)
1088 v -= TOK_IDENT;
1089 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1090 return NULL;
1091 return table_ident[v]->sym_struct;
1094 /* find an identifier */
1095 static inline Sym *sym_find(int v)
1097 v -= TOK_IDENT;
1098 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1099 return NULL;
1100 return table_ident[v]->sym_identifier;
1103 /* push a given symbol on the symbol stack */
1104 static Sym *sym_push(int v, CType *type, int r, int c)
1106 Sym *s, **ps;
1107 TokenSym *ts;
1109 if (local_stack)
1110 ps = &local_stack;
1111 else
1112 ps = &global_stack;
1113 s = sym_push2(ps, v, type->t, c);
1114 s->type.ref = type->ref;
1115 s->r = r;
1116 /* don't record fields or anonymous symbols */
1117 /* XXX: simplify */
1118 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
1119 /* record symbol in token array */
1120 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
1121 if (v & SYM_STRUCT)
1122 ps = &ts->sym_struct;
1123 else
1124 ps = &ts->sym_identifier;
1125 s->prev_tok = *ps;
1126 *ps = s;
1128 return s;
1131 /* push a global identifier */
1132 static Sym *global_identifier_push(int v, int t, int c)
1134 Sym *s, **ps;
1135 s = sym_push2(&global_stack, v, t, c);
1136 /* don't record anonymous symbol */
1137 if (v < SYM_FIRST_ANOM) {
1138 ps = &table_ident[v - TOK_IDENT]->sym_identifier;
1139 /* modify the top most local identifier, so that
1140 sym_identifier will point to 's' when popped */
1141 while (*ps != NULL)
1142 ps = &(*ps)->prev_tok;
1143 s->prev_tok = NULL;
1144 *ps = s;
1146 return s;
1149 /* pop symbols until top reaches 'b' */
1150 static void sym_pop(Sym **ptop, Sym *b)
1152 Sym *s, *ss, **ps;
1153 TokenSym *ts;
1154 int v;
1156 s = *ptop;
1157 while(s != b) {
1158 ss = s->prev;
1159 v = s->v;
1160 /* remove symbol in token array */
1161 /* XXX: simplify */
1162 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
1163 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
1164 if (v & SYM_STRUCT)
1165 ps = &ts->sym_struct;
1166 else
1167 ps = &ts->sym_identifier;
1168 *ps = s->prev_tok;
1170 sym_free(s);
1171 s = ss;
1173 *ptop = b;
1176 /* I/O layer */
1178 BufferedFile *tcc_open(TCCState *s1, const char *filename)
1180 int fd;
1181 BufferedFile *bf;
1183 if (strcmp(filename, "-") == 0)
1184 fd = 0, filename = "stdin";
1185 else
1186 fd = open(filename, O_RDONLY | O_BINARY);
1187 if ((s1->verbose == 2 && fd >= 0) || s1->verbose == 3)
1188 printf("%s %*s%s\n", fd < 0 ? "nf":"->",
1189 (s1->include_stack_ptr - s1->include_stack), "", filename);
1190 if (fd < 0)
1191 return NULL;
1192 bf = tcc_malloc(sizeof(BufferedFile));
1193 bf->fd = fd;
1194 bf->buf_ptr = bf->buffer;
1195 bf->buf_end = bf->buffer;
1196 bf->buffer[0] = CH_EOB; /* put eob symbol */
1197 pstrcpy(bf->filename, sizeof(bf->filename), filename);
1198 #ifdef _WIN32
1199 normalize_slashes(bf->filename);
1200 #endif
1201 bf->line_num = 1;
1202 bf->ifndef_macro = 0;
1203 bf->ifdef_stack_ptr = s1->ifdef_stack_ptr;
1204 // printf("opening '%s'\n", filename);
1205 return bf;
1208 void tcc_close(BufferedFile *bf)
1210 total_lines += bf->line_num;
1211 close(bf->fd);
1212 tcc_free(bf);
1215 /* compile the C file opened in 'file'. Return non zero if errors. */
1216 static int tcc_compile(TCCState *s1)
1218 Sym *define_start;
1219 char buf[512];
1220 volatile int section_sym;
1222 #ifdef INC_DEBUG
1223 printf("%s: **** new file\n", file->filename);
1224 #endif
1225 preprocess_init(s1);
1227 cur_text_section = NULL;
1228 funcname = "";
1229 anon_sym = SYM_FIRST_ANOM;
1231 /* file info: full path + filename */
1232 section_sym = 0; /* avoid warning */
1233 if (s1->do_debug) {
1234 section_sym = put_elf_sym(symtab_section, 0, 0,
1235 ELFW(ST_INFO)(STB_LOCAL, STT_SECTION), 0,
1236 text_section->sh_num, NULL);
1237 getcwd(buf, sizeof(buf));
1238 #ifdef _WIN32
1239 normalize_slashes(buf);
1240 #endif
1241 pstrcat(buf, sizeof(buf), "/");
1242 put_stabs_r(buf, N_SO, 0, 0,
1243 text_section->data_offset, text_section, section_sym);
1244 put_stabs_r(file->filename, N_SO, 0, 0,
1245 text_section->data_offset, text_section, section_sym);
1247 /* an elf symbol of type STT_FILE must be put so that STB_LOCAL
1248 symbols can be safely used */
1249 put_elf_sym(symtab_section, 0, 0,
1250 ELFW(ST_INFO)(STB_LOCAL, STT_FILE), 0,
1251 SHN_ABS, file->filename);
1253 /* define some often used types */
1254 int_type.t = VT_INT;
1256 char_pointer_type.t = VT_BYTE;
1257 mk_pointer(&char_pointer_type);
1259 func_old_type.t = VT_FUNC;
1260 func_old_type.ref = sym_push(SYM_FIELD, &int_type, FUNC_CDECL, FUNC_OLD);
1262 #if defined(TCC_ARM_EABI) && defined(TCC_ARM_VFP)
1263 float_type.t = VT_FLOAT;
1264 double_type.t = VT_DOUBLE;
1266 func_float_type.t = VT_FUNC;
1267 func_float_type.ref = sym_push(SYM_FIELD, &float_type, FUNC_CDECL, FUNC_OLD);
1268 func_double_type.t = VT_FUNC;
1269 func_double_type.ref = sym_push(SYM_FIELD, &double_type, FUNC_CDECL, FUNC_OLD);
1270 #endif
1272 #if 0
1273 /* define 'void *alloca(unsigned int)' builtin function */
1275 Sym *s1;
1277 p = anon_sym++;
1278 sym = sym_push(p, mk_pointer(VT_VOID), FUNC_CDECL, FUNC_NEW);
1279 s1 = sym_push(SYM_FIELD, VT_UNSIGNED | VT_INT, 0, 0);
1280 s1->next = NULL;
1281 sym->next = s1;
1282 sym_push(TOK_alloca, VT_FUNC | (p << VT_STRUCT_SHIFT), VT_CONST, 0);
1284 #endif
1286 define_start = define_stack;
1287 nocode_wanted = 1;
1289 if (setjmp(s1->error_jmp_buf) == 0) {
1290 s1->nb_errors = 0;
1291 s1->error_set_jmp_enabled = 1;
1293 ch = file->buf_ptr[0];
1294 tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
1295 parse_flags = PARSE_FLAG_PREPROCESS | PARSE_FLAG_TOK_NUM;
1296 next();
1297 decl(VT_CONST);
1298 if (tok != TOK_EOF)
1299 expect("declaration");
1301 /* end of translation unit info */
1302 if (s1->do_debug) {
1303 put_stabs_r(NULL, N_SO, 0, 0,
1304 text_section->data_offset, text_section, section_sym);
1307 s1->error_set_jmp_enabled = 0;
1309 /* reset define stack, but leave -Dsymbols (may be incorrect if
1310 they are undefined) */
1311 free_defines(define_start);
1313 gen_inline_functions();
1315 sym_pop(&global_stack, NULL);
1316 sym_pop(&local_stack, NULL);
1318 return s1->nb_errors != 0 ? -1 : 0;
1321 int tcc_compile_string(TCCState *s, const char *str)
1323 BufferedFile bf1, *bf = &bf1;
1324 int ret, len;
1325 char *buf;
1327 /* init file structure */
1328 bf->fd = -1;
1329 /* XXX: avoid copying */
1330 len = strlen(str);
1331 buf = tcc_malloc(len + 1);
1332 if (!buf)
1333 return -1;
1334 memcpy(buf, str, len);
1335 buf[len] = CH_EOB;
1336 bf->buf_ptr = buf;
1337 bf->buf_end = buf + len;
1338 pstrcpy(bf->filename, sizeof(bf->filename), "<string>");
1339 bf->line_num = 1;
1340 file = bf;
1341 ret = tcc_compile(s);
1342 file = NULL;
1343 tcc_free(buf);
1345 /* currently, no need to close */
1346 return ret;
1349 /* define a preprocessor symbol. A value can also be provided with the '=' operator */
1350 void tcc_define_symbol(TCCState *s1, const char *sym, const char *value)
1352 BufferedFile bf1, *bf = &bf1;
1354 pstrcpy(bf->buffer, IO_BUF_SIZE, sym);
1355 pstrcat(bf->buffer, IO_BUF_SIZE, " ");
1356 /* default value */
1357 if (!value)
1358 value = "1";
1359 pstrcat(bf->buffer, IO_BUF_SIZE, value);
1361 /* init file structure */
1362 bf->fd = -1;
1363 bf->buf_ptr = bf->buffer;
1364 bf->buf_end = bf->buffer + strlen(bf->buffer);
1365 *bf->buf_end = CH_EOB;
1366 bf->filename[0] = '\0';
1367 bf->line_num = 1;
1368 file = bf;
1370 s1->include_stack_ptr = s1->include_stack;
1372 /* parse with define parser */
1373 ch = file->buf_ptr[0];
1374 next_nomacro();
1375 parse_define();
1376 file = NULL;
1379 /* undefine a preprocessor symbol */
1380 void tcc_undefine_symbol(TCCState *s1, const char *sym)
1382 TokenSym *ts;
1383 Sym *s;
1384 ts = tok_alloc(sym, strlen(sym));
1385 s = define_find(ts->tok);
1386 /* undefine symbol by putting an invalid name */
1387 if (s)
1388 define_undef(s);
1392 #ifdef CONFIG_TCC_BACKTRACE
1393 /* print the position in the source file of PC value 'pc' by reading
1394 the stabs debug information */
1395 static unsigned long rt_printline(unsigned long wanted_pc)
1397 Stab_Sym *sym, *sym_end;
1398 char func_name[128], last_func_name[128];
1399 unsigned long func_addr, last_pc, pc;
1400 const char *incl_files[INCLUDE_STACK_SIZE];
1401 int incl_index, len, last_line_num, i;
1402 const char *str, *p;
1404 fprintf(stderr, "0x%08lx:", wanted_pc);
1406 func_name[0] = '\0';
1407 func_addr = 0;
1408 incl_index = 0;
1409 last_func_name[0] = '\0';
1410 last_pc = 0xffffffff;
1411 last_line_num = 1;
1412 sym = (Stab_Sym *)stab_section->data + 1;
1413 sym_end = (Stab_Sym *)(stab_section->data + stab_section->data_offset);
1414 while (sym < sym_end) {
1415 switch(sym->n_type) {
1416 /* function start or end */
1417 case N_FUN:
1418 if (sym->n_strx == 0) {
1419 /* we test if between last line and end of function */
1420 pc = sym->n_value + func_addr;
1421 if (wanted_pc >= last_pc && wanted_pc < pc)
1422 goto found;
1423 func_name[0] = '\0';
1424 func_addr = 0;
1425 } else {
1426 str = stabstr_section->data + sym->n_strx;
1427 p = strchr(str, ':');
1428 if (!p) {
1429 pstrcpy(func_name, sizeof(func_name), str);
1430 } else {
1431 len = p - str;
1432 if (len > sizeof(func_name) - 1)
1433 len = sizeof(func_name) - 1;
1434 memcpy(func_name, str, len);
1435 func_name[len] = '\0';
1437 func_addr = sym->n_value;
1439 break;
1440 /* line number info */
1441 case N_SLINE:
1442 pc = sym->n_value + func_addr;
1443 if (wanted_pc >= last_pc && wanted_pc < pc)
1444 goto found;
1445 last_pc = pc;
1446 last_line_num = sym->n_desc;
1447 /* XXX: slow! */
1448 strcpy(last_func_name, func_name);
1449 break;
1450 /* include files */
1451 case N_BINCL:
1452 str = stabstr_section->data + sym->n_strx;
1453 add_incl:
1454 if (incl_index < INCLUDE_STACK_SIZE) {
1455 incl_files[incl_index++] = str;
1457 break;
1458 case N_EINCL:
1459 if (incl_index > 1)
1460 incl_index--;
1461 break;
1462 case N_SO:
1463 if (sym->n_strx == 0) {
1464 incl_index = 0; /* end of translation unit */
1465 } else {
1466 str = stabstr_section->data + sym->n_strx;
1467 /* do not add path */
1468 len = strlen(str);
1469 if (len > 0 && str[len - 1] != '/')
1470 goto add_incl;
1472 break;
1474 sym++;
1477 /* second pass: we try symtab symbols (no line number info) */
1478 incl_index = 0;
1480 ElfW(Sym) *sym, *sym_end;
1481 int type;
1483 sym_end = (ElfW(Sym) *)(symtab_section->data + symtab_section->data_offset);
1484 for(sym = (ElfW(Sym) *)symtab_section->data + 1;
1485 sym < sym_end;
1486 sym++) {
1487 type = ELFW(ST_TYPE)(sym->st_info);
1488 if (type == STT_FUNC) {
1489 if (wanted_pc >= sym->st_value &&
1490 wanted_pc < sym->st_value + sym->st_size) {
1491 pstrcpy(last_func_name, sizeof(last_func_name),
1492 strtab_section->data + sym->st_name);
1493 func_addr = sym->st_value;
1494 goto found;
1499 /* did not find any info: */
1500 fprintf(stderr, " ???\n");
1501 return 0;
1502 found:
1503 if (last_func_name[0] != '\0') {
1504 fprintf(stderr, " %s()", last_func_name);
1506 if (incl_index > 0) {
1507 fprintf(stderr, " (%s:%d",
1508 incl_files[incl_index - 1], last_line_num);
1509 for(i = incl_index - 2; i >= 0; i--)
1510 fprintf(stderr, ", included from %s", incl_files[i]);
1511 fprintf(stderr, ")");
1513 fprintf(stderr, "\n");
1514 return func_addr;
1517 #ifdef __i386__
1518 /* fix for glibc 2.1 */
1519 #ifndef REG_EIP
1520 #define REG_EIP EIP
1521 #define REG_EBP EBP
1522 #endif
1524 /* return the PC at frame level 'level'. Return non zero if not found */
1525 static int rt_get_caller_pc(unsigned long *paddr,
1526 ucontext_t *uc, int level)
1528 unsigned long fp;
1529 int i;
1531 if (level == 0) {
1532 #if defined(__FreeBSD__)
1533 *paddr = uc->uc_mcontext.mc_eip;
1534 #elif defined(__dietlibc__)
1535 *paddr = uc->uc_mcontext.eip;
1536 #else
1537 *paddr = uc->uc_mcontext.gregs[REG_EIP];
1538 #endif
1539 return 0;
1540 } else {
1541 #if defined(__FreeBSD__)
1542 fp = uc->uc_mcontext.mc_ebp;
1543 #elif defined(__dietlibc__)
1544 fp = uc->uc_mcontext.ebp;
1545 #else
1546 fp = uc->uc_mcontext.gregs[REG_EBP];
1547 #endif
1548 for(i=1;i<level;i++) {
1549 /* XXX: check address validity with program info */
1550 if (fp <= 0x1000 || fp >= 0xc0000000)
1551 return -1;
1552 fp = ((unsigned long *)fp)[0];
1554 *paddr = ((unsigned long *)fp)[1];
1555 return 0;
1558 #elif defined(__x86_64__)
1559 /* return the PC at frame level 'level'. Return non zero if not found */
1560 static int rt_get_caller_pc(unsigned long *paddr,
1561 ucontext_t *uc, int level)
1563 unsigned long fp;
1564 int i;
1566 if (level == 0) {
1567 /* XXX: only support linux */
1568 *paddr = uc->uc_mcontext.gregs[REG_RIP];
1569 return 0;
1570 } else {
1571 fp = uc->uc_mcontext.gregs[REG_RBP];
1572 for(i=1;i<level;i++) {
1573 /* XXX: check address validity with program info */
1574 if (fp <= 0x1000)
1575 return -1;
1576 fp = ((unsigned long *)fp)[0];
1578 *paddr = ((unsigned long *)fp)[1];
1579 return 0;
1582 #else
1583 #warning add arch specific rt_get_caller_pc()
1584 static int rt_get_caller_pc(unsigned long *paddr,
1585 ucontext_t *uc, int level)
1587 return -1;
1589 #endif
1591 /* emit a run time error at position 'pc' */
1592 void rt_error(ucontext_t *uc, const char *fmt, ...)
1594 va_list ap;
1595 unsigned long pc;
1596 int i;
1598 va_start(ap, fmt);
1599 fprintf(stderr, "Runtime error: ");
1600 vfprintf(stderr, fmt, ap);
1601 fprintf(stderr, "\n");
1602 for(i=0;i<num_callers;i++) {
1603 if (rt_get_caller_pc(&pc, uc, i) < 0)
1604 break;
1605 if (i == 0)
1606 fprintf(stderr, "at ");
1607 else
1608 fprintf(stderr, "by ");
1609 pc = rt_printline(pc);
1610 if (pc == rt_prog_main && pc)
1611 break;
1613 exit(255);
1614 va_end(ap);
1617 /* signal handler for fatal errors */
1618 static void sig_error(int signum, siginfo_t *siginf, void *puc)
1620 ucontext_t *uc = puc;
1622 switch(signum) {
1623 case SIGFPE:
1624 switch(siginf->si_code) {
1625 case FPE_INTDIV:
1626 case FPE_FLTDIV:
1627 rt_error(uc, "division by zero");
1628 break;
1629 default:
1630 rt_error(uc, "floating point exception");
1631 break;
1633 break;
1634 case SIGBUS:
1635 case SIGSEGV:
1636 if (rt_bound_error_msg && *rt_bound_error_msg)
1637 rt_error(uc, *rt_bound_error_msg);
1638 else
1639 rt_error(uc, "dereferencing invalid pointer");
1640 break;
1641 case SIGILL:
1642 rt_error(uc, "illegal instruction");
1643 break;
1644 case SIGABRT:
1645 rt_error(uc, "abort() called");
1646 break;
1647 default:
1648 rt_error(uc, "caught signal %d", signum);
1649 break;
1651 exit(255);
1654 #endif
1656 /* copy code into memory passed in by the caller and do all relocations
1657 (needed before using tcc_get_symbol()).
1658 returns -1 on error and required size if ptr is NULL */
1659 int tcc_relocate(TCCState *s1, void *ptr)
1661 Section *s;
1662 unsigned long offset, length, mem;
1663 int i;
1665 if (0 == s1->runtime_added) {
1666 s1->runtime_added = 1;
1667 s1->nb_errors = 0;
1668 #ifdef TCC_TARGET_PE
1669 pe_add_runtime(s1);
1670 relocate_common_syms();
1671 tcc_add_linker_symbols(s1);
1672 #else
1673 tcc_add_runtime(s1);
1674 relocate_common_syms();
1675 tcc_add_linker_symbols(s1);
1676 build_got_entries(s1);
1677 #endif
1680 offset = 0, mem = (unsigned long)ptr;
1681 for(i = 1; i < s1->nb_sections; i++) {
1682 s = s1->sections[i];
1683 if (0 == (s->sh_flags & SHF_ALLOC))
1684 continue;
1685 length = s->data_offset;
1686 s->sh_addr = mem ? (mem + offset + 15) & ~15 : 0;
1687 offset = (offset + length + 15) & ~15;
1690 /* relocate symbols */
1691 relocate_syms(s1, 1);
1692 if (s1->nb_errors)
1693 return -1;
1695 #ifdef TCC_TARGET_X86_64
1696 s1->runtime_plt_and_got_offset = 0;
1697 s1->runtime_plt_and_got = (char *)(mem + offset);
1698 /* double the size of the buffer for got and plt entries
1699 XXX: calculate exact size for them? */
1700 offset *= 2;
1701 #endif
1703 if (0 == mem)
1704 return offset + 15;
1706 /* relocate each section */
1707 for(i = 1; i < s1->nb_sections; i++) {
1708 s = s1->sections[i];
1709 if (s->reloc)
1710 relocate_section(s1, s);
1713 for(i = 1; i < s1->nb_sections; i++) {
1714 s = s1->sections[i];
1715 if (0 == (s->sh_flags & SHF_ALLOC))
1716 continue;
1717 length = s->data_offset;
1718 // printf("%-12s %08x %04x\n", s->name, s->sh_addr, length);
1719 ptr = (void*)s->sh_addr;
1720 if (NULL == s->data || s->sh_type == SHT_NOBITS)
1721 memset(ptr, 0, length);
1722 else
1723 memcpy(ptr, s->data, length);
1724 /* mark executable sections as executable in memory */
1725 if (s->sh_flags & SHF_EXECINSTR)
1726 set_pages_executable(ptr, length);
1728 #ifdef TCC_TARGET_X86_64
1729 set_pages_executable(s1->runtime_plt_and_got,
1730 s1->runtime_plt_and_got_offset);
1731 #endif
1732 return 0;
1735 /* launch the compiled program with the given arguments */
1736 int tcc_run(TCCState *s1, int argc, char **argv)
1738 int (*prog_main)(int, char **);
1739 void *ptr;
1740 int ret;
1742 ret = tcc_relocate(s1, NULL);
1743 if (ret < 0)
1744 return -1;
1745 ptr = tcc_malloc(ret);
1746 tcc_relocate(s1, ptr);
1748 prog_main = tcc_get_symbol_err(s1, "main");
1750 if (s1->do_debug) {
1751 #ifdef CONFIG_TCC_BACKTRACE
1752 struct sigaction sigact;
1753 /* install TCC signal handlers to print debug info on fatal
1754 runtime errors */
1755 sigact.sa_flags = SA_SIGINFO | SA_RESETHAND;
1756 sigact.sa_sigaction = sig_error;
1757 sigemptyset(&sigact.sa_mask);
1758 sigaction(SIGFPE, &sigact, NULL);
1759 sigaction(SIGILL, &sigact, NULL);
1760 sigaction(SIGSEGV, &sigact, NULL);
1761 sigaction(SIGBUS, &sigact, NULL);
1762 sigaction(SIGABRT, &sigact, NULL);
1763 #else
1764 error("debug mode not available");
1765 #endif
1768 #ifdef CONFIG_TCC_BCHECK
1769 if (s1->do_bounds_check) {
1770 void (*bound_init)(void);
1771 void (*bound_exit)(void);
1772 /* set error function */
1773 rt_bound_error_msg = tcc_get_symbol_err(s1, "__bound_error_msg");
1774 rt_prog_main = (unsigned long)prog_main;
1775 /* XXX: use .init section so that it also work in binary ? */
1776 bound_init = tcc_get_symbol_err(s1, "__bound_init");
1777 bound_exit = tcc_get_symbol_err(s1, "__bound_exit");
1778 bound_init();
1779 ret = (*prog_main)(argc, argv);
1780 bound_exit();
1781 } else
1782 #endif
1783 ret = (*prog_main)(argc, argv);
1784 tcc_free(ptr);
1785 return ret;
1788 void tcc_memstats(void)
1790 #ifdef MEM_DEBUG
1791 printf("memory in use: %d\n", mem_cur_size);
1792 #endif
1795 static void tcc_cleanup(void)
1797 int i, n;
1799 if (NULL == tcc_state)
1800 return;
1801 tcc_state = NULL;
1803 /* free -D defines */
1804 free_defines(NULL);
1806 /* free tokens */
1807 n = tok_ident - TOK_IDENT;
1808 for(i = 0; i < n; i++)
1809 tcc_free(table_ident[i]);
1810 tcc_free(table_ident);
1812 /* free sym_pools */
1813 dynarray_reset(&sym_pools, &nb_sym_pools);
1814 /* string buffer */
1815 cstr_free(&tokcstr);
1816 /* reset symbol stack */
1817 sym_free_first = NULL;
1818 /* cleanup from error/setjmp */
1819 macro_ptr = NULL;
1822 TCCState *tcc_new(void)
1824 TCCState *s;
1826 tcc_cleanup();
1828 s = tcc_mallocz(sizeof(TCCState));
1829 if (!s)
1830 return NULL;
1831 tcc_state = s;
1832 s->output_type = TCC_OUTPUT_MEMORY;
1833 s->tcc_lib_path = CONFIG_TCCDIR;
1835 preprocess_new();
1837 /* we add dummy defines for some special macros to speed up tests
1838 and to have working defined() */
1839 define_push(TOK___LINE__, MACRO_OBJ, NULL, NULL);
1840 define_push(TOK___FILE__, MACRO_OBJ, NULL, NULL);
1841 define_push(TOK___DATE__, MACRO_OBJ, NULL, NULL);
1842 define_push(TOK___TIME__, MACRO_OBJ, NULL, NULL);
1844 /* standard defines */
1845 tcc_define_symbol(s, "__STDC__", NULL);
1846 tcc_define_symbol(s, "__STDC_VERSION__", "199901L");
1847 #if defined(TCC_TARGET_I386)
1848 tcc_define_symbol(s, "__i386__", NULL);
1849 #endif
1850 #if defined(TCC_TARGET_X86_64)
1851 tcc_define_symbol(s, "__x86_64__", NULL);
1852 #endif
1853 #if defined(TCC_TARGET_ARM)
1854 tcc_define_symbol(s, "__ARM_ARCH_4__", NULL);
1855 tcc_define_symbol(s, "__arm_elf__", NULL);
1856 tcc_define_symbol(s, "__arm_elf", NULL);
1857 tcc_define_symbol(s, "arm_elf", NULL);
1858 tcc_define_symbol(s, "__arm__", NULL);
1859 tcc_define_symbol(s, "__arm", NULL);
1860 tcc_define_symbol(s, "arm", NULL);
1861 tcc_define_symbol(s, "__APCS_32__", NULL);
1862 #endif
1863 #ifdef TCC_TARGET_PE
1864 tcc_define_symbol(s, "_WIN32", NULL);
1865 #else
1866 tcc_define_symbol(s, "__unix__", NULL);
1867 tcc_define_symbol(s, "__unix", NULL);
1868 #if defined(__linux)
1869 tcc_define_symbol(s, "__linux__", NULL);
1870 tcc_define_symbol(s, "__linux", NULL);
1871 #endif
1872 #endif
1873 /* tiny C specific defines */
1874 tcc_define_symbol(s, "__TINYC__", NULL);
1876 /* tiny C & gcc defines */
1877 tcc_define_symbol(s, "__SIZE_TYPE__", "unsigned int");
1878 tcc_define_symbol(s, "__PTRDIFF_TYPE__", "int");
1879 #ifdef TCC_TARGET_PE
1880 tcc_define_symbol(s, "__WCHAR_TYPE__", "unsigned short");
1881 #else
1882 tcc_define_symbol(s, "__WCHAR_TYPE__", "int");
1883 #endif
1885 #ifndef TCC_TARGET_PE
1886 /* default library paths */
1887 tcc_add_library_path(s, CONFIG_SYSROOT "/usr/local/lib");
1888 tcc_add_library_path(s, CONFIG_SYSROOT "/usr/lib");
1889 tcc_add_library_path(s, CONFIG_SYSROOT "/lib");
1890 #endif
1892 /* no section zero */
1893 dynarray_add((void ***)&s->sections, &s->nb_sections, NULL);
1895 /* create standard sections */
1896 text_section = new_section(s, ".text", SHT_PROGBITS, SHF_ALLOC | SHF_EXECINSTR);
1897 data_section = new_section(s, ".data", SHT_PROGBITS, SHF_ALLOC | SHF_WRITE);
1898 bss_section = new_section(s, ".bss", SHT_NOBITS, SHF_ALLOC | SHF_WRITE);
1900 /* symbols are always generated for linking stage */
1901 symtab_section = new_symtab(s, ".symtab", SHT_SYMTAB, 0,
1902 ".strtab",
1903 ".hashtab", SHF_PRIVATE);
1904 strtab_section = symtab_section->link;
1906 /* private symbol table for dynamic symbols */
1907 s->dynsymtab_section = new_symtab(s, ".dynsymtab", SHT_SYMTAB, SHF_PRIVATE,
1908 ".dynstrtab",
1909 ".dynhashtab", SHF_PRIVATE);
1910 s->alacarte_link = 1;
1912 #ifdef CHAR_IS_UNSIGNED
1913 s->char_is_unsigned = 1;
1914 #endif
1915 #if defined(TCC_TARGET_PE) && 0
1916 /* XXX: currently the PE linker is not ready to support that */
1917 s->leading_underscore = 1;
1918 #endif
1919 return s;
1922 void tcc_delete(TCCState *s1)
1924 int i;
1926 tcc_cleanup();
1928 /* free all sections */
1929 for(i = 1; i < s1->nb_sections; i++)
1930 free_section(s1->sections[i]);
1931 dynarray_reset(&s1->sections, &s1->nb_sections);
1933 for(i = 0; i < s1->nb_priv_sections; i++)
1934 free_section(s1->priv_sections[i]);
1935 dynarray_reset(&s1->priv_sections, &s1->nb_priv_sections);
1937 /* free any loaded DLLs */
1938 for ( i = 0; i < s1->nb_loaded_dlls; i++) {
1939 DLLReference *ref = s1->loaded_dlls[i];
1940 if ( ref->handle )
1941 dlclose(ref->handle);
1944 /* free loaded dlls array */
1945 dynarray_reset(&s1->loaded_dlls, &s1->nb_loaded_dlls);
1947 /* free library paths */
1948 dynarray_reset(&s1->library_paths, &s1->nb_library_paths);
1950 /* free include paths */
1951 dynarray_reset(&s1->cached_includes, &s1->nb_cached_includes);
1952 dynarray_reset(&s1->include_paths, &s1->nb_include_paths);
1953 dynarray_reset(&s1->sysinclude_paths, &s1->nb_sysinclude_paths);
1955 tcc_free(s1);
1958 int tcc_add_include_path(TCCState *s1, const char *pathname)
1960 char *pathname1;
1962 pathname1 = tcc_strdup(pathname);
1963 dynarray_add((void ***)&s1->include_paths, &s1->nb_include_paths, pathname1);
1964 return 0;
1967 int tcc_add_sysinclude_path(TCCState *s1, const char *pathname)
1969 char *pathname1;
1971 pathname1 = tcc_strdup(pathname);
1972 dynarray_add((void ***)&s1->sysinclude_paths, &s1->nb_sysinclude_paths, pathname1);
1973 return 0;
1976 static int tcc_add_file_internal(TCCState *s1, const char *filename, int flags)
1978 const char *ext;
1979 ElfW(Ehdr) ehdr;
1980 int fd, ret;
1981 BufferedFile *saved_file;
1983 /* find source file type with extension */
1984 ext = tcc_fileextension(filename);
1985 if (ext[0])
1986 ext++;
1988 /* open the file */
1989 saved_file = file;
1990 file = tcc_open(s1, filename);
1991 if (!file) {
1992 if (flags & AFF_PRINT_ERROR) {
1993 error_noabort("file '%s' not found", filename);
1995 ret = -1;
1996 goto fail1;
1999 if (flags & AFF_PREPROCESS) {
2000 ret = tcc_preprocess(s1);
2001 } else if (!ext[0] || !PATHCMP(ext, "c")) {
2002 /* C file assumed */
2003 ret = tcc_compile(s1);
2004 } else
2005 #ifdef CONFIG_TCC_ASM
2006 if (!strcmp(ext, "S")) {
2007 /* preprocessed assembler */
2008 ret = tcc_assemble(s1, 1);
2009 } else if (!strcmp(ext, "s")) {
2010 /* non preprocessed assembler */
2011 ret = tcc_assemble(s1, 0);
2012 } else
2013 #endif
2014 #ifdef TCC_TARGET_PE
2015 if (!PATHCMP(ext, "def")) {
2016 ret = pe_load_def_file(s1, file->fd);
2017 } else
2018 #endif
2020 fd = file->fd;
2021 /* assume executable format: auto guess file type */
2022 ret = read(fd, &ehdr, sizeof(ehdr));
2023 lseek(fd, 0, SEEK_SET);
2024 if (ret <= 0) {
2025 error_noabort("could not read header");
2026 goto fail;
2027 } else if (ret != sizeof(ehdr)) {
2028 goto try_load_script;
2031 if (ehdr.e_ident[0] == ELFMAG0 &&
2032 ehdr.e_ident[1] == ELFMAG1 &&
2033 ehdr.e_ident[2] == ELFMAG2 &&
2034 ehdr.e_ident[3] == ELFMAG3) {
2035 file->line_num = 0; /* do not display line number if error */
2036 if (ehdr.e_type == ET_REL) {
2037 ret = tcc_load_object_file(s1, fd, 0);
2038 } else if (ehdr.e_type == ET_DYN) {
2039 if (s1->output_type == TCC_OUTPUT_MEMORY) {
2040 #ifdef TCC_TARGET_PE
2041 ret = -1;
2042 #else
2043 void *h;
2044 h = dlopen(filename, RTLD_GLOBAL | RTLD_LAZY);
2045 if (h)
2046 ret = 0;
2047 else
2048 ret = -1;
2049 #endif
2050 } else {
2051 ret = tcc_load_dll(s1, fd, filename,
2052 (flags & AFF_REFERENCED_DLL) != 0);
2054 } else {
2055 error_noabort("unrecognized ELF file");
2056 goto fail;
2058 } else if (memcmp((char *)&ehdr, ARMAG, 8) == 0) {
2059 file->line_num = 0; /* do not display line number if error */
2060 ret = tcc_load_archive(s1, fd);
2061 } else
2062 #ifdef TCC_TARGET_COFF
2063 if (*(uint16_t *)(&ehdr) == COFF_C67_MAGIC) {
2064 ret = tcc_load_coff(s1, fd);
2065 } else
2066 #endif
2067 #ifdef TCC_TARGET_PE
2068 if (pe_test_res_file(&ehdr, ret)) {
2069 ret = pe_load_res_file(s1, fd);
2070 } else
2071 #endif
2073 /* as GNU ld, consider it is an ld script if not recognized */
2074 try_load_script:
2075 ret = tcc_load_ldscript(s1);
2076 if (ret < 0) {
2077 error_noabort("unrecognized file type");
2078 goto fail;
2082 the_end:
2083 tcc_close(file);
2084 fail1:
2085 file = saved_file;
2086 return ret;
2087 fail:
2088 ret = -1;
2089 goto the_end;
2092 int tcc_add_file(TCCState *s, const char *filename)
2094 if (s->output_type == TCC_OUTPUT_PREPROCESS)
2095 return tcc_add_file_internal(s, filename, AFF_PRINT_ERROR | AFF_PREPROCESS);
2096 else
2097 return tcc_add_file_internal(s, filename, AFF_PRINT_ERROR);
2100 int tcc_add_library_path(TCCState *s, const char *pathname)
2102 char *pathname1;
2104 pathname1 = tcc_strdup(pathname);
2105 dynarray_add((void ***)&s->library_paths, &s->nb_library_paths, pathname1);
2106 return 0;
2109 /* find and load a dll. Return non zero if not found */
2110 /* XXX: add '-rpath' option support ? */
2111 static int tcc_add_dll(TCCState *s, const char *filename, int flags)
2113 char buf[1024];
2114 int i;
2116 for(i = 0; i < s->nb_library_paths; i++) {
2117 snprintf(buf, sizeof(buf), "%s/%s",
2118 s->library_paths[i], filename);
2119 if (tcc_add_file_internal(s, buf, flags) == 0)
2120 return 0;
2122 return -1;
2125 /* the library name is the same as the argument of the '-l' option */
2126 int tcc_add_library(TCCState *s, const char *libraryname)
2128 char buf[1024];
2129 int i;
2131 /* first we look for the dynamic library if not static linking */
2132 if (!s->static_link) {
2133 #ifdef TCC_TARGET_PE
2134 snprintf(buf, sizeof(buf), "%s.def", libraryname);
2135 #else
2136 snprintf(buf, sizeof(buf), "lib%s.so", libraryname);
2137 #endif
2138 if (tcc_add_dll(s, buf, 0) == 0)
2139 return 0;
2142 /* then we look for the static library */
2143 for(i = 0; i < s->nb_library_paths; i++) {
2144 snprintf(buf, sizeof(buf), "%s/lib%s.a",
2145 s->library_paths[i], libraryname);
2146 if (tcc_add_file_internal(s, buf, 0) == 0)
2147 return 0;
2149 return -1;
2152 int tcc_add_symbol(TCCState *s, const char *name, void *val)
2154 add_elf_sym(symtab_section, (unsigned long)val, 0,
2155 ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE), 0,
2156 SHN_ABS, name);
2157 return 0;
2160 int tcc_set_output_type(TCCState *s, int output_type)
2162 char buf[1024];
2164 s->output_type = output_type;
2166 if (!s->nostdinc) {
2167 /* default include paths */
2168 /* XXX: reverse order needed if -isystem support */
2169 #ifndef TCC_TARGET_PE
2170 tcc_add_sysinclude_path(s, CONFIG_SYSROOT "/usr/local/include");
2171 tcc_add_sysinclude_path(s, CONFIG_SYSROOT "/usr/include");
2172 #endif
2173 snprintf(buf, sizeof(buf), "%s/include", s->tcc_lib_path);
2174 tcc_add_sysinclude_path(s, buf);
2175 #ifdef TCC_TARGET_PE
2176 snprintf(buf, sizeof(buf), "%s/include/winapi", s->tcc_lib_path);
2177 tcc_add_sysinclude_path(s, buf);
2178 #endif
2181 /* if bound checking, then add corresponding sections */
2182 #ifdef CONFIG_TCC_BCHECK
2183 if (s->do_bounds_check) {
2184 /* define symbol */
2185 tcc_define_symbol(s, "__BOUNDS_CHECKING_ON", NULL);
2186 /* create bounds sections */
2187 bounds_section = new_section(s, ".bounds",
2188 SHT_PROGBITS, SHF_ALLOC);
2189 lbounds_section = new_section(s, ".lbounds",
2190 SHT_PROGBITS, SHF_ALLOC);
2192 #endif
2194 if (s->char_is_unsigned) {
2195 tcc_define_symbol(s, "__CHAR_UNSIGNED__", NULL);
2198 /* add debug sections */
2199 if (s->do_debug) {
2200 /* stab symbols */
2201 stab_section = new_section(s, ".stab", SHT_PROGBITS, 0);
2202 stab_section->sh_entsize = sizeof(Stab_Sym);
2203 stabstr_section = new_section(s, ".stabstr", SHT_STRTAB, 0);
2204 put_elf_str(stabstr_section, "");
2205 stab_section->link = stabstr_section;
2206 /* put first entry */
2207 put_stabs("", 0, 0, 0, 0);
2210 /* add libc crt1/crti objects */
2211 #ifndef TCC_TARGET_PE
2212 if ((output_type == TCC_OUTPUT_EXE || output_type == TCC_OUTPUT_DLL) &&
2213 !s->nostdlib) {
2214 if (output_type != TCC_OUTPUT_DLL)
2215 tcc_add_file(s, CONFIG_TCC_CRT_PREFIX "/crt1.o");
2216 tcc_add_file(s, CONFIG_TCC_CRT_PREFIX "/crti.o");
2218 #endif
2220 #ifdef TCC_TARGET_PE
2221 snprintf(buf, sizeof(buf), "%s/lib", s->tcc_lib_path);
2222 tcc_add_library_path(s, buf);
2223 #endif
2225 return 0;
2228 #define WD_ALL 0x0001 /* warning is activated when using -Wall */
2229 #define FD_INVERT 0x0002 /* invert value before storing */
2231 typedef struct FlagDef {
2232 uint16_t offset;
2233 uint16_t flags;
2234 const char *name;
2235 } FlagDef;
2237 static const FlagDef warning_defs[] = {
2238 { offsetof(TCCState, warn_unsupported), 0, "unsupported" },
2239 { offsetof(TCCState, warn_write_strings), 0, "write-strings" },
2240 { offsetof(TCCState, warn_error), 0, "error" },
2241 { offsetof(TCCState, warn_implicit_function_declaration), WD_ALL,
2242 "implicit-function-declaration" },
2245 static int set_flag(TCCState *s, const FlagDef *flags, int nb_flags,
2246 const char *name, int value)
2248 int i;
2249 const FlagDef *p;
2250 const char *r;
2252 r = name;
2253 if (r[0] == 'n' && r[1] == 'o' && r[2] == '-') {
2254 r += 3;
2255 value = !value;
2257 for(i = 0, p = flags; i < nb_flags; i++, p++) {
2258 if (!strcmp(r, p->name))
2259 goto found;
2261 return -1;
2262 found:
2263 if (p->flags & FD_INVERT)
2264 value = !value;
2265 *(int *)((uint8_t *)s + p->offset) = value;
2266 return 0;
2270 /* set/reset a warning */
2271 int tcc_set_warning(TCCState *s, const char *warning_name, int value)
2273 int i;
2274 const FlagDef *p;
2276 if (!strcmp(warning_name, "all")) {
2277 for(i = 0, p = warning_defs; i < countof(warning_defs); i++, p++) {
2278 if (p->flags & WD_ALL)
2279 *(int *)((uint8_t *)s + p->offset) = 1;
2281 return 0;
2282 } else {
2283 return set_flag(s, warning_defs, countof(warning_defs),
2284 warning_name, value);
2288 static const FlagDef flag_defs[] = {
2289 { offsetof(TCCState, char_is_unsigned), 0, "unsigned-char" },
2290 { offsetof(TCCState, char_is_unsigned), FD_INVERT, "signed-char" },
2291 { offsetof(TCCState, nocommon), FD_INVERT, "common" },
2292 { offsetof(TCCState, leading_underscore), 0, "leading-underscore" },
2295 /* set/reset a flag */
2296 int tcc_set_flag(TCCState *s, const char *flag_name, int value)
2298 return set_flag(s, flag_defs, countof(flag_defs),
2299 flag_name, value);
2302 /* set CONFIG_TCCDIR at runtime */
2303 void tcc_set_lib_path(TCCState *s, const char *path)
2305 s->tcc_lib_path = tcc_strdup(path);
2308 void tcc_print_stats(TCCState *s, int64_t total_time)
2310 double tt;
2311 tt = (double)total_time / 1000000.0;
2312 if (tt < 0.001)
2313 tt = 0.001;
2314 if (total_bytes < 1)
2315 total_bytes = 1;
2316 printf("%d idents, %d lines, %d bytes, %0.3f s, %d lines/s, %0.1f MB/s\n",
2317 tok_ident - TOK_IDENT, total_lines, total_bytes,
2318 tt, (int)(total_lines / tt),
2319 total_bytes / tt / 1000000.0);