win64: use new headers from mingw
[tinycc/k1w1.git] / libtcc.c
blobbfa683964bcd71aa9b54b14caffefc0c36c9b27a
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_def_file(struct TCCState *s1, int fd);
216 int pe_test_res_file(void *v, int size);
217 int pe_load_res_file(struct TCCState *s1, int fd);
218 int pe_output_file(struct TCCState *s1, const char *filename);
220 /* tccasm.c */
221 #ifdef CONFIG_TCC_ASM
222 static void asm_expr(TCCState *s1, ExprValue *pe);
223 static int asm_int_expr(TCCState *s1);
224 static int find_constraint(ASMOperand *operands, int nb_operands,
225 const char *name, const char **pp);
227 static int tcc_assemble(TCCState *s1, int do_preprocess);
228 #endif
230 static void asm_instr(void);
231 static void asm_global_instr(void);
233 /********************************************************/
234 /* libtcc.c */
236 static Sym *__sym_malloc(void);
237 static inline Sym *sym_malloc(void);
238 static inline void sym_free(Sym *sym);
239 Section *new_section(TCCState *s1, const char *name, int sh_type, int sh_flags);
240 static void free_section(Section *s);
241 static void section_realloc(Section *sec, unsigned long new_size);
242 static void *section_ptr_add(Section *sec, unsigned long size);
243 Section *find_section(TCCState *s1, const char *name);
244 static void put_extern_sym2(
245 Sym *sym, Section *section,
246 unsigned long value, unsigned long size, int can_add_underscore);
247 static void put_extern_sym(
248 Sym *sym, Section *section,
249 unsigned long value, unsigned long size);
250 static void greloc(Section *s, Sym *sym, unsigned long offset, int type);
252 static void strcat_vprintf(char *buf, int buf_size, const char *fmt, va_list ap);
253 static void strcat_printf(char *buf, int buf_size, const char *fmt, ...);
255 /* CString handling */
256 static void cstr_realloc(CString *cstr, int new_size);
257 static inline void cstr_ccat(CString *cstr, int ch);
258 static void cstr_cat(CString *cstr, const char *str);
259 static void cstr_wccat(CString *cstr, int ch);
260 static void cstr_new(CString *cstr);
261 static void cstr_free(CString *cstr);
262 #define cstr_reset(cstr) cstr_free(cstr)
263 static void add_char(CString *cstr, int c);
265 static Sym *sym_push2(Sym **ps, int v, int t, long c);
266 static Sym *sym_find2(Sym *s, int v);
267 static inline Sym *struct_find(int v);
268 static inline Sym *sym_find(int v);
269 static Sym *sym_push(int v, CType *type, int r, int c);
270 static Sym *global_identifier_push(int v, int t, int c);
271 static void sym_pop(Sym **ptop, Sym *b);
273 BufferedFile *tcc_open(TCCState *s1, const char *filename);
274 void tcc_close(BufferedFile *bf);
275 static int tcc_compile(TCCState *s1);
277 void expect(const char *msg);
278 void skip(int c);
279 static void test_lvalue(void);
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 void *resolve_sym(TCCState *s1, const char *sym);
308 /********************************************************/
310 #ifdef TCC_TARGET_I386
311 #include "i386-gen.c"
312 #endif
314 #ifdef TCC_TARGET_ARM
315 #include "arm-gen.c"
316 #endif
318 #ifdef TCC_TARGET_C67
319 #include "c67-gen.c"
320 #endif
322 #ifdef TCC_TARGET_X86_64
323 #include "x86_64-gen.c"
324 #endif
326 #include "tccpp.c"
327 #include "tccgen.c"
329 #ifdef CONFIG_TCC_ASM
330 #ifdef TCC_TARGET_I386
331 #include "i386-asm.c"
332 #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 CONFIG_TCC_STATIC
358 #define RTLD_LAZY 0x001
359 #define RTLD_NOW 0x002
360 #define RTLD_GLOBAL 0x100
361 #define RTLD_DEFAULT NULL
363 /* dummy function for profiling */
364 void *dlopen(const char *filename, int flag)
366 return NULL;
369 void dlclose(void *p)
373 const char *dlerror(void)
375 return "error";
378 typedef struct TCCSyms {
379 char *str;
380 void *ptr;
381 } TCCSyms;
383 #define TCCSYM(a) { #a, &a, },
385 /* add the symbol you want here if no dynamic linking is done */
386 static TCCSyms tcc_syms[] = {
387 #if !defined(CONFIG_TCCBOOT)
388 TCCSYM(printf)
389 TCCSYM(fprintf)
390 TCCSYM(fopen)
391 TCCSYM(fclose)
392 #endif
393 { NULL, NULL },
396 void *resolve_sym(TCCState *s1, const char *symbol, int type)
398 TCCSyms *p;
399 p = tcc_syms;
400 while (p->str != NULL) {
401 if (!strcmp(p->str, symbol))
402 return p->ptr;
403 p++;
405 return NULL;
408 #elif !defined(_WIN32)
410 #include <dlfcn.h>
412 void *resolve_sym(TCCState *s1, const char *sym)
414 return dlsym(RTLD_DEFAULT, sym);
417 #endif
419 /********************************************************/
421 /* we use our own 'finite' function to avoid potential problems with
422 non standard math libs */
423 /* XXX: endianness dependent */
424 int ieee_finite(double d)
426 int *p = (int *)&d;
427 return ((unsigned)((p[1] | 0x800fffff) + 1)) >> 31;
430 /* copy a string and truncate it. */
431 char *pstrcpy(char *buf, int buf_size, const char *s)
433 char *q, *q_end;
434 int c;
436 if (buf_size > 0) {
437 q = buf;
438 q_end = buf + buf_size - 1;
439 while (q < q_end) {
440 c = *s++;
441 if (c == '\0')
442 break;
443 *q++ = c;
445 *q = '\0';
447 return buf;
450 /* strcat and truncate. */
451 char *pstrcat(char *buf, int buf_size, const char *s)
453 int len;
454 len = strlen(buf);
455 if (len < buf_size)
456 pstrcpy(buf + len, buf_size - len, s);
457 return buf;
460 /* extract the basename of a file */
461 char *tcc_basename(const char *name)
463 char *p = strchr(name, 0);
464 while (p > name && !IS_PATHSEP(p[-1]))
465 --p;
466 return p;
469 char *tcc_fileextension (const char *name)
471 char *b = tcc_basename(name);
472 char *e = strrchr(b, '.');
473 return e ? e : strchr(b, 0);
476 #ifdef _WIN32
477 char *normalize_slashes(char *path)
479 char *p;
480 for (p = path; *p; ++p)
481 if (*p == '\\')
482 *p = '/';
483 return path;
486 void tcc_set_lib_path_w32(TCCState *s)
488 /* on win32, we suppose the lib and includes are at the location
489 of 'tcc.exe' */
490 char path[1024], *p;
491 GetModuleFileNameA(NULL, path, sizeof path);
492 p = tcc_basename(normalize_slashes(strlwr(path)));
493 if (p - 5 > path && 0 == strncmp(p - 5, "/bin/", 5))
494 p -= 5;
495 else if (p > path)
496 p--;
497 *p = 0;
498 tcc_set_lib_path(s, path);
500 #endif
502 void set_pages_executable(void *ptr, unsigned long length)
504 #ifdef _WIN32
505 unsigned long old_protect;
506 VirtualProtect(ptr, length, PAGE_EXECUTE_READWRITE, &old_protect);
507 #else
508 unsigned long start, end;
509 start = (unsigned long)ptr & ~(PAGESIZE - 1);
510 end = (unsigned long)ptr + length;
511 end = (end + PAGESIZE - 1) & ~(PAGESIZE - 1);
512 mprotect((void *)start, end - start, PROT_READ | PROT_WRITE | PROT_EXEC);
513 #endif
516 /* memory management */
517 #ifdef MEM_DEBUG
518 int mem_cur_size;
519 int mem_max_size;
520 unsigned malloc_usable_size(void*);
521 #endif
523 void tcc_free(void *ptr)
525 #ifdef MEM_DEBUG
526 mem_cur_size -= malloc_usable_size(ptr);
527 #endif
528 free(ptr);
531 void *tcc_malloc(unsigned long size)
533 void *ptr;
534 ptr = malloc(size);
535 if (!ptr && size)
536 error("memory full");
537 #ifdef MEM_DEBUG
538 mem_cur_size += malloc_usable_size(ptr);
539 if (mem_cur_size > mem_max_size)
540 mem_max_size = mem_cur_size;
541 #endif
542 return ptr;
545 void *tcc_mallocz(unsigned long size)
547 void *ptr;
548 ptr = tcc_malloc(size);
549 memset(ptr, 0, size);
550 return ptr;
553 void *tcc_realloc(void *ptr, unsigned long size)
555 void *ptr1;
556 #ifdef MEM_DEBUG
557 mem_cur_size -= malloc_usable_size(ptr);
558 #endif
559 ptr1 = realloc(ptr, size);
560 #ifdef MEM_DEBUG
561 /* NOTE: count not correct if alloc error, but not critical */
562 mem_cur_size += malloc_usable_size(ptr1);
563 if (mem_cur_size > mem_max_size)
564 mem_max_size = mem_cur_size;
565 #endif
566 return ptr1;
569 char *tcc_strdup(const char *str)
571 char *ptr;
572 ptr = tcc_malloc(strlen(str) + 1);
573 strcpy(ptr, str);
574 return ptr;
577 #define free(p) use_tcc_free(p)
578 #define malloc(s) use_tcc_malloc(s)
579 #define realloc(p, s) use_tcc_realloc(p, s)
581 void dynarray_add(void ***ptab, int *nb_ptr, void *data)
583 int nb, nb_alloc;
584 void **pp;
586 nb = *nb_ptr;
587 pp = *ptab;
588 /* every power of two we double array size */
589 if ((nb & (nb - 1)) == 0) {
590 if (!nb)
591 nb_alloc = 1;
592 else
593 nb_alloc = nb * 2;
594 pp = tcc_realloc(pp, nb_alloc * sizeof(void *));
595 if (!pp)
596 error("memory full");
597 *ptab = pp;
599 pp[nb++] = data;
600 *nb_ptr = nb;
603 void dynarray_reset(void *pp, int *n)
605 void **p;
606 for (p = *(void***)pp; *n; ++p, --*n)
607 if (*p)
608 tcc_free(*p);
609 tcc_free(*(void**)pp);
610 *(void**)pp = NULL;
613 /* symbol allocator */
614 static Sym *__sym_malloc(void)
616 Sym *sym_pool, *sym, *last_sym;
617 int i;
619 sym_pool = tcc_malloc(SYM_POOL_NB * sizeof(Sym));
620 dynarray_add(&sym_pools, &nb_sym_pools, sym_pool);
622 last_sym = sym_free_first;
623 sym = sym_pool;
624 for(i = 0; i < SYM_POOL_NB; i++) {
625 sym->next = last_sym;
626 last_sym = sym;
627 sym++;
629 sym_free_first = last_sym;
630 return last_sym;
633 static inline Sym *sym_malloc(void)
635 Sym *sym;
636 sym = sym_free_first;
637 if (!sym)
638 sym = __sym_malloc();
639 sym_free_first = sym->next;
640 return sym;
643 static inline void sym_free(Sym *sym)
645 sym->next = sym_free_first;
646 sym_free_first = sym;
649 Section *new_section(TCCState *s1, const char *name, int sh_type, int sh_flags)
651 Section *sec;
653 sec = tcc_mallocz(sizeof(Section) + strlen(name));
654 strcpy(sec->name, name);
655 sec->sh_type = sh_type;
656 sec->sh_flags = sh_flags;
657 switch(sh_type) {
658 case SHT_HASH:
659 case SHT_REL:
660 case SHT_RELA:
661 case SHT_DYNSYM:
662 case SHT_SYMTAB:
663 case SHT_DYNAMIC:
664 sec->sh_addralign = 4;
665 break;
666 case SHT_STRTAB:
667 sec->sh_addralign = 1;
668 break;
669 default:
670 sec->sh_addralign = 32; /* default conservative alignment */
671 break;
674 if (sh_flags & SHF_PRIVATE) {
675 dynarray_add((void ***)&s1->priv_sections, &s1->nb_priv_sections, sec);
676 } else {
677 sec->sh_num = s1->nb_sections;
678 dynarray_add((void ***)&s1->sections, &s1->nb_sections, sec);
681 return sec;
684 static void free_section(Section *s)
686 tcc_free(s->data);
689 /* realloc section and set its content to zero */
690 static void section_realloc(Section *sec, unsigned long new_size)
692 unsigned long size;
693 unsigned char *data;
695 size = sec->data_allocated;
696 if (size == 0)
697 size = 1;
698 while (size < new_size)
699 size = size * 2;
700 data = tcc_realloc(sec->data, size);
701 if (!data)
702 error("memory full");
703 memset(data + sec->data_allocated, 0, size - sec->data_allocated);
704 sec->data = data;
705 sec->data_allocated = size;
708 /* reserve at least 'size' bytes in section 'sec' from
709 sec->data_offset. */
710 static void *section_ptr_add(Section *sec, unsigned long size)
712 unsigned long offset, offset1;
714 offset = sec->data_offset;
715 offset1 = offset + size;
716 if (offset1 > sec->data_allocated)
717 section_realloc(sec, offset1);
718 sec->data_offset = offset1;
719 return sec->data + offset;
722 /* return a reference to a section, and create it if it does not
723 exists */
724 Section *find_section(TCCState *s1, const char *name)
726 Section *sec;
727 int i;
728 for(i = 1; i < s1->nb_sections; i++) {
729 sec = s1->sections[i];
730 if (!strcmp(name, sec->name))
731 return sec;
733 /* sections are created as PROGBITS */
734 return new_section(s1, name, SHT_PROGBITS, SHF_ALLOC);
737 /* update sym->c so that it points to an external symbol in section
738 'section' with value 'value' */
739 static void put_extern_sym2(Sym *sym, Section *section,
740 unsigned long value, unsigned long size,
741 int can_add_underscore)
743 int sym_type, sym_bind, sh_num, info, other, attr;
744 ElfW(Sym) *esym;
745 const char *name;
746 char buf1[256];
748 if (section == NULL)
749 sh_num = SHN_UNDEF;
750 else if (section == SECTION_ABS)
751 sh_num = SHN_ABS;
752 else
753 sh_num = section->sh_num;
755 other = attr = 0;
757 if ((sym->type.t & VT_BTYPE) == VT_FUNC) {
758 sym_type = STT_FUNC;
759 #ifdef TCC_TARGET_PE
760 if (sym->type.ref)
761 attr = sym->type.ref->r;
762 if (FUNC_EXPORT(attr))
763 other |= 1;
764 if (FUNC_CALL(attr) == FUNC_STDCALL)
765 other |= 2;
766 #endif
767 } else {
768 sym_type = STT_OBJECT;
771 if (sym->type.t & VT_STATIC)
772 sym_bind = STB_LOCAL;
773 else
774 sym_bind = STB_GLOBAL;
776 if (!sym->c) {
777 name = get_tok_str(sym->v, NULL);
778 #ifdef CONFIG_TCC_BCHECK
779 if (tcc_state->do_bounds_check) {
780 char buf[32];
782 /* XXX: avoid doing that for statics ? */
783 /* if bound checking is activated, we change some function
784 names by adding the "__bound" prefix */
785 switch(sym->v) {
786 #if 0
787 /* XXX: we rely only on malloc hooks */
788 case TOK_malloc:
789 case TOK_free:
790 case TOK_realloc:
791 case TOK_memalign:
792 case TOK_calloc:
793 #endif
794 case TOK_memcpy:
795 case TOK_memmove:
796 case TOK_memset:
797 case TOK_strlen:
798 case TOK_strcpy:
799 case TOK_alloca:
800 strcpy(buf, "__bound_");
801 strcat(buf, name);
802 name = buf;
803 break;
806 #endif
808 #ifdef TCC_TARGET_PE
809 if ((other & 2) && can_add_underscore) {
810 sprintf(buf1, "_%s@%d", name, FUNC_ARGS(attr));
811 name = buf1;
812 } else
813 #endif
814 if (tcc_state->leading_underscore && can_add_underscore) {
815 buf1[0] = '_';
816 pstrcpy(buf1 + 1, sizeof(buf1) - 1, name);
817 name = buf1;
819 info = ELFW(ST_INFO)(sym_bind, sym_type);
820 sym->c = add_elf_sym(symtab_section, value, size, info, other, sh_num, name);
821 } else {
822 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
823 esym->st_value = value;
824 esym->st_size = size;
825 esym->st_shndx = sh_num;
826 esym->st_other |= other;
830 static void put_extern_sym(Sym *sym, Section *section,
831 unsigned long value, unsigned long size)
833 put_extern_sym2(sym, section, value, size, 1);
836 /* add a new relocation entry to symbol 'sym' in section 's' */
837 static void greloc(Section *s, Sym *sym, unsigned long offset, int type)
839 if (!sym->c)
840 put_extern_sym(sym, NULL, 0, 0);
841 /* now we can add ELF relocation info */
842 put_elf_reloc(symtab_section, s, offset, type, sym->c);
845 static void strcat_vprintf(char *buf, int buf_size, const char *fmt, va_list ap)
847 int len;
848 len = strlen(buf);
849 vsnprintf(buf + len, buf_size - len, fmt, ap);
852 static void strcat_printf(char *buf, int buf_size, const char *fmt, ...)
854 va_list ap;
855 va_start(ap, fmt);
856 strcat_vprintf(buf, buf_size, fmt, ap);
857 va_end(ap);
860 void error1(TCCState *s1, int is_warning, const char *fmt, va_list ap)
862 char buf[2048];
863 BufferedFile **f;
865 buf[0] = '\0';
866 if (file) {
867 for(f = s1->include_stack; f < s1->include_stack_ptr; f++)
868 strcat_printf(buf, sizeof(buf), "In file included from %s:%d:\n",
869 (*f)->filename, (*f)->line_num);
870 if (file->line_num > 0) {
871 strcat_printf(buf, sizeof(buf),
872 "%s:%d: ", file->filename, file->line_num);
873 } else {
874 strcat_printf(buf, sizeof(buf),
875 "%s: ", file->filename);
877 } else {
878 strcat_printf(buf, sizeof(buf),
879 "tcc: ");
881 if (is_warning)
882 strcat_printf(buf, sizeof(buf), "warning: ");
883 else
884 strcat_printf(buf, sizeof(buf), "error: ");
885 strcat_vprintf(buf, sizeof(buf), fmt, ap);
887 if (!s1->error_func) {
888 /* default case: stderr */
889 fprintf(stderr, "%s\n", buf);
890 } else {
891 s1->error_func(s1->error_opaque, buf);
893 if (!is_warning || s1->warn_error)
894 s1->nb_errors++;
897 void tcc_set_error_func(TCCState *s, void *error_opaque,
898 void (*error_func)(void *opaque, const char *msg))
900 s->error_opaque = error_opaque;
901 s->error_func = error_func;
904 /* error without aborting current compilation */
905 void error_noabort(const char *fmt, ...)
907 TCCState *s1 = tcc_state;
908 va_list ap;
910 va_start(ap, fmt);
911 error1(s1, 0, fmt, ap);
912 va_end(ap);
915 void error(const char *fmt, ...)
917 TCCState *s1 = tcc_state;
918 va_list ap;
920 va_start(ap, fmt);
921 error1(s1, 0, fmt, ap);
922 va_end(ap);
923 /* better than nothing: in some cases, we accept to handle errors */
924 if (s1->error_set_jmp_enabled) {
925 longjmp(s1->error_jmp_buf, 1);
926 } else {
927 /* XXX: eliminate this someday */
928 exit(1);
932 void expect(const char *msg)
934 error("%s expected", msg);
937 void warning(const char *fmt, ...)
939 TCCState *s1 = tcc_state;
940 va_list ap;
942 if (s1->warn_none)
943 return;
945 va_start(ap, fmt);
946 error1(s1, 1, fmt, ap);
947 va_end(ap);
950 void skip(int c)
952 if (tok != c)
953 error("'%c' expected", c);
954 next();
957 static void test_lvalue(void)
959 if (!(vtop->r & VT_LVAL))
960 expect("lvalue");
963 /* CString handling */
965 static void cstr_realloc(CString *cstr, int new_size)
967 int size;
968 void *data;
970 size = cstr->size_allocated;
971 if (size == 0)
972 size = 8; /* no need to allocate a too small first string */
973 while (size < new_size)
974 size = size * 2;
975 data = tcc_realloc(cstr->data_allocated, size);
976 if (!data)
977 error("memory full");
978 cstr->data_allocated = data;
979 cstr->size_allocated = size;
980 cstr->data = data;
983 /* add a byte */
984 static inline void cstr_ccat(CString *cstr, int ch)
986 int size;
987 size = cstr->size + 1;
988 if (size > cstr->size_allocated)
989 cstr_realloc(cstr, size);
990 ((unsigned char *)cstr->data)[size - 1] = ch;
991 cstr->size = size;
994 static void cstr_cat(CString *cstr, const char *str)
996 int c;
997 for(;;) {
998 c = *str;
999 if (c == '\0')
1000 break;
1001 cstr_ccat(cstr, c);
1002 str++;
1006 /* add a wide char */
1007 static void cstr_wccat(CString *cstr, int ch)
1009 int size;
1010 size = cstr->size + sizeof(nwchar_t);
1011 if (size > cstr->size_allocated)
1012 cstr_realloc(cstr, size);
1013 *(nwchar_t *)(((unsigned char *)cstr->data) + size - sizeof(nwchar_t)) = ch;
1014 cstr->size = size;
1017 static void cstr_new(CString *cstr)
1019 memset(cstr, 0, sizeof(CString));
1022 /* free string and reset it to NULL */
1023 static void cstr_free(CString *cstr)
1025 tcc_free(cstr->data_allocated);
1026 cstr_new(cstr);
1029 #define cstr_reset(cstr) cstr_free(cstr)
1031 /* XXX: unicode ? */
1032 static void add_char(CString *cstr, int c)
1034 if (c == '\'' || c == '\"' || c == '\\') {
1035 /* XXX: could be more precise if char or string */
1036 cstr_ccat(cstr, '\\');
1038 if (c >= 32 && c <= 126) {
1039 cstr_ccat(cstr, c);
1040 } else {
1041 cstr_ccat(cstr, '\\');
1042 if (c == '\n') {
1043 cstr_ccat(cstr, 'n');
1044 } else {
1045 cstr_ccat(cstr, '0' + ((c >> 6) & 7));
1046 cstr_ccat(cstr, '0' + ((c >> 3) & 7));
1047 cstr_ccat(cstr, '0' + (c & 7));
1052 /* push, without hashing */
1053 static Sym *sym_push2(Sym **ps, int v, int t, long c)
1055 Sym *s;
1056 s = sym_malloc();
1057 s->v = v;
1058 s->type.t = t;
1059 #ifdef _WIN64
1060 s->d = NULL;
1061 #endif
1062 s->c = c;
1063 s->next = NULL;
1064 /* add in stack */
1065 s->prev = *ps;
1066 *ps = s;
1067 return s;
1070 /* find a symbol and return its associated structure. 's' is the top
1071 of the symbol stack */
1072 static Sym *sym_find2(Sym *s, int v)
1074 while (s) {
1075 if (s->v == v)
1076 return s;
1077 s = s->prev;
1079 return NULL;
1082 /* structure lookup */
1083 static inline Sym *struct_find(int v)
1085 v -= TOK_IDENT;
1086 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1087 return NULL;
1088 return table_ident[v]->sym_struct;
1091 /* find an identifier */
1092 static inline Sym *sym_find(int v)
1094 v -= TOK_IDENT;
1095 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1096 return NULL;
1097 return table_ident[v]->sym_identifier;
1100 /* push a given symbol on the symbol stack */
1101 static Sym *sym_push(int v, CType *type, int r, int c)
1103 Sym *s, **ps;
1104 TokenSym *ts;
1106 if (local_stack)
1107 ps = &local_stack;
1108 else
1109 ps = &global_stack;
1110 s = sym_push2(ps, v, type->t, c);
1111 s->type.ref = type->ref;
1112 s->r = r;
1113 /* don't record fields or anonymous symbols */
1114 /* XXX: simplify */
1115 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
1116 /* record symbol in token array */
1117 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
1118 if (v & SYM_STRUCT)
1119 ps = &ts->sym_struct;
1120 else
1121 ps = &ts->sym_identifier;
1122 s->prev_tok = *ps;
1123 *ps = s;
1125 return s;
1128 /* push a global identifier */
1129 static Sym *global_identifier_push(int v, int t, int c)
1131 Sym *s, **ps;
1132 s = sym_push2(&global_stack, v, t, c);
1133 /* don't record anonymous symbol */
1134 if (v < SYM_FIRST_ANOM) {
1135 ps = &table_ident[v - TOK_IDENT]->sym_identifier;
1136 /* modify the top most local identifier, so that
1137 sym_identifier will point to 's' when popped */
1138 while (*ps != NULL)
1139 ps = &(*ps)->prev_tok;
1140 s->prev_tok = NULL;
1141 *ps = s;
1143 return s;
1146 /* pop symbols until top reaches 'b' */
1147 static void sym_pop(Sym **ptop, Sym *b)
1149 Sym *s, *ss, **ps;
1150 TokenSym *ts;
1151 int v;
1153 s = *ptop;
1154 while(s != b) {
1155 ss = s->prev;
1156 v = s->v;
1157 /* remove symbol in token array */
1158 /* XXX: simplify */
1159 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
1160 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
1161 if (v & SYM_STRUCT)
1162 ps = &ts->sym_struct;
1163 else
1164 ps = &ts->sym_identifier;
1165 *ps = s->prev_tok;
1167 sym_free(s);
1168 s = ss;
1170 *ptop = b;
1173 /* I/O layer */
1175 BufferedFile *tcc_open(TCCState *s1, const char *filename)
1177 int fd;
1178 BufferedFile *bf;
1180 if (strcmp(filename, "-") == 0)
1181 fd = 0, filename = "stdin";
1182 else
1183 fd = open(filename, O_RDONLY | O_BINARY);
1184 if ((s1->verbose == 2 && fd >= 0) || s1->verbose == 3)
1185 printf("%s %*s%s\n", fd < 0 ? "nf":"->",
1186 (int)(s1->include_stack_ptr - s1->include_stack), "", filename);
1187 if (fd < 0)
1188 return NULL;
1189 bf = tcc_malloc(sizeof(BufferedFile));
1190 bf->fd = fd;
1191 bf->buf_ptr = bf->buffer;
1192 bf->buf_end = bf->buffer;
1193 bf->buffer[0] = CH_EOB; /* put eob symbol */
1194 pstrcpy(bf->filename, sizeof(bf->filename), filename);
1195 #ifdef _WIN32
1196 normalize_slashes(bf->filename);
1197 #endif
1198 bf->line_num = 1;
1199 bf->ifndef_macro = 0;
1200 bf->ifdef_stack_ptr = s1->ifdef_stack_ptr;
1201 // printf("opening '%s'\n", filename);
1202 return bf;
1205 void tcc_close(BufferedFile *bf)
1207 total_lines += bf->line_num;
1208 close(bf->fd);
1209 tcc_free(bf);
1212 /* compile the C file opened in 'file'. Return non zero if errors. */
1213 static int tcc_compile(TCCState *s1)
1215 Sym *define_start;
1216 char buf[512];
1217 volatile int section_sym;
1219 #ifdef INC_DEBUG
1220 printf("%s: **** new file\n", file->filename);
1221 #endif
1222 preprocess_init(s1);
1224 cur_text_section = NULL;
1225 funcname = "";
1226 anon_sym = SYM_FIRST_ANOM;
1228 /* file info: full path + filename */
1229 section_sym = 0; /* avoid warning */
1230 if (s1->do_debug) {
1231 section_sym = put_elf_sym(symtab_section, 0, 0,
1232 ELFW(ST_INFO)(STB_LOCAL, STT_SECTION), 0,
1233 text_section->sh_num, NULL);
1234 getcwd(buf, sizeof(buf));
1235 #ifdef _WIN32
1236 normalize_slashes(buf);
1237 #endif
1238 pstrcat(buf, sizeof(buf), "/");
1239 put_stabs_r(buf, N_SO, 0, 0,
1240 text_section->data_offset, text_section, section_sym);
1241 put_stabs_r(file->filename, N_SO, 0, 0,
1242 text_section->data_offset, text_section, section_sym);
1244 /* an elf symbol of type STT_FILE must be put so that STB_LOCAL
1245 symbols can be safely used */
1246 put_elf_sym(symtab_section, 0, 0,
1247 ELFW(ST_INFO)(STB_LOCAL, STT_FILE), 0,
1248 SHN_ABS, file->filename);
1250 /* define some often used types */
1251 int_type.t = VT_INT;
1253 char_pointer_type.t = VT_BYTE;
1254 mk_pointer(&char_pointer_type);
1256 func_old_type.t = VT_FUNC;
1257 func_old_type.ref = sym_push(SYM_FIELD, &int_type, FUNC_CDECL, FUNC_OLD);
1259 #if defined(TCC_ARM_EABI) && defined(TCC_ARM_VFP)
1260 float_type.t = VT_FLOAT;
1261 double_type.t = VT_DOUBLE;
1263 func_float_type.t = VT_FUNC;
1264 func_float_type.ref = sym_push(SYM_FIELD, &float_type, FUNC_CDECL, FUNC_OLD);
1265 func_double_type.t = VT_FUNC;
1266 func_double_type.ref = sym_push(SYM_FIELD, &double_type, FUNC_CDECL, FUNC_OLD);
1267 #endif
1269 #if 0
1270 /* define 'void *alloca(unsigned int)' builtin function */
1272 Sym *s1;
1274 p = anon_sym++;
1275 sym = sym_push(p, mk_pointer(VT_VOID), FUNC_CDECL, FUNC_NEW);
1276 s1 = sym_push(SYM_FIELD, VT_UNSIGNED | VT_INT, 0, 0);
1277 s1->next = NULL;
1278 sym->next = s1;
1279 sym_push(TOK_alloca, VT_FUNC | (p << VT_STRUCT_SHIFT), VT_CONST, 0);
1281 #endif
1283 define_start = define_stack;
1284 nocode_wanted = 1;
1286 if (setjmp(s1->error_jmp_buf) == 0) {
1287 s1->nb_errors = 0;
1288 s1->error_set_jmp_enabled = 1;
1290 ch = file->buf_ptr[0];
1291 tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
1292 parse_flags = PARSE_FLAG_PREPROCESS | PARSE_FLAG_TOK_NUM;
1293 next();
1294 decl(VT_CONST);
1295 if (tok != TOK_EOF)
1296 expect("declaration");
1298 /* end of translation unit info */
1299 if (s1->do_debug) {
1300 put_stabs_r(NULL, N_SO, 0, 0,
1301 text_section->data_offset, text_section, section_sym);
1304 s1->error_set_jmp_enabled = 0;
1306 /* reset define stack, but leave -Dsymbols (may be incorrect if
1307 they are undefined) */
1308 free_defines(define_start);
1310 gen_inline_functions();
1312 sym_pop(&global_stack, NULL);
1313 sym_pop(&local_stack, NULL);
1315 return s1->nb_errors != 0 ? -1 : 0;
1318 int tcc_compile_string(TCCState *s, const char *str)
1320 BufferedFile bf1, *bf = &bf1;
1321 int ret, len;
1322 char *buf;
1324 /* init file structure */
1325 bf->fd = -1;
1326 /* XXX: avoid copying */
1327 len = strlen(str);
1328 buf = tcc_malloc(len + 1);
1329 if (!buf)
1330 return -1;
1331 memcpy(buf, str, len);
1332 buf[len] = CH_EOB;
1333 bf->buf_ptr = buf;
1334 bf->buf_end = buf + len;
1335 pstrcpy(bf->filename, sizeof(bf->filename), "<string>");
1336 bf->line_num = 1;
1337 file = bf;
1338 ret = tcc_compile(s);
1339 file = NULL;
1340 tcc_free(buf);
1342 /* currently, no need to close */
1343 return ret;
1346 /* define a preprocessor symbol. A value can also be provided with the '=' operator */
1347 void tcc_define_symbol(TCCState *s1, const char *sym, const char *value)
1349 BufferedFile bf1, *bf = &bf1;
1351 pstrcpy(bf->buffer, IO_BUF_SIZE, sym);
1352 pstrcat(bf->buffer, IO_BUF_SIZE, " ");
1353 /* default value */
1354 if (!value)
1355 value = "1";
1356 pstrcat(bf->buffer, IO_BUF_SIZE, value);
1358 /* init file structure */
1359 bf->fd = -1;
1360 bf->buf_ptr = bf->buffer;
1361 bf->buf_end = bf->buffer + strlen(bf->buffer);
1362 *bf->buf_end = CH_EOB;
1363 bf->filename[0] = '\0';
1364 bf->line_num = 1;
1365 file = bf;
1367 s1->include_stack_ptr = s1->include_stack;
1369 /* parse with define parser */
1370 ch = file->buf_ptr[0];
1371 next_nomacro();
1372 parse_define();
1373 file = NULL;
1376 /* undefine a preprocessor symbol */
1377 void tcc_undefine_symbol(TCCState *s1, const char *sym)
1379 TokenSym *ts;
1380 Sym *s;
1381 ts = tok_alloc(sym, strlen(sym));
1382 s = define_find(ts->tok);
1383 /* undefine symbol by putting an invalid name */
1384 if (s)
1385 define_undef(s);
1389 #ifdef CONFIG_TCC_BACKTRACE
1390 /* print the position in the source file of PC value 'pc' by reading
1391 the stabs debug information */
1392 static unsigned long rt_printline(unsigned long wanted_pc)
1394 Stab_Sym *sym, *sym_end;
1395 char func_name[128], last_func_name[128];
1396 unsigned long func_addr, last_pc, pc;
1397 const char *incl_files[INCLUDE_STACK_SIZE];
1398 int incl_index, len, last_line_num, i;
1399 const char *str, *p;
1401 fprintf(stderr, "0x%08lx:", wanted_pc);
1403 func_name[0] = '\0';
1404 func_addr = 0;
1405 incl_index = 0;
1406 last_func_name[0] = '\0';
1407 last_pc = 0xffffffff;
1408 last_line_num = 1;
1409 sym = (Stab_Sym *)stab_section->data + 1;
1410 sym_end = (Stab_Sym *)(stab_section->data + stab_section->data_offset);
1411 while (sym < sym_end) {
1412 switch(sym->n_type) {
1413 /* function start or end */
1414 case N_FUN:
1415 if (sym->n_strx == 0) {
1416 /* we test if between last line and end of function */
1417 pc = sym->n_value + func_addr;
1418 if (wanted_pc >= last_pc && wanted_pc < pc)
1419 goto found;
1420 func_name[0] = '\0';
1421 func_addr = 0;
1422 } else {
1423 str = stabstr_section->data + sym->n_strx;
1424 p = strchr(str, ':');
1425 if (!p) {
1426 pstrcpy(func_name, sizeof(func_name), str);
1427 } else {
1428 len = p - str;
1429 if (len > sizeof(func_name) - 1)
1430 len = sizeof(func_name) - 1;
1431 memcpy(func_name, str, len);
1432 func_name[len] = '\0';
1434 func_addr = sym->n_value;
1436 break;
1437 /* line number info */
1438 case N_SLINE:
1439 pc = sym->n_value + func_addr;
1440 if (wanted_pc >= last_pc && wanted_pc < pc)
1441 goto found;
1442 last_pc = pc;
1443 last_line_num = sym->n_desc;
1444 /* XXX: slow! */
1445 strcpy(last_func_name, func_name);
1446 break;
1447 /* include files */
1448 case N_BINCL:
1449 str = stabstr_section->data + sym->n_strx;
1450 add_incl:
1451 if (incl_index < INCLUDE_STACK_SIZE) {
1452 incl_files[incl_index++] = str;
1454 break;
1455 case N_EINCL:
1456 if (incl_index > 1)
1457 incl_index--;
1458 break;
1459 case N_SO:
1460 if (sym->n_strx == 0) {
1461 incl_index = 0; /* end of translation unit */
1462 } else {
1463 str = stabstr_section->data + sym->n_strx;
1464 /* do not add path */
1465 len = strlen(str);
1466 if (len > 0 && str[len - 1] != '/')
1467 goto add_incl;
1469 break;
1471 sym++;
1474 /* second pass: we try symtab symbols (no line number info) */
1475 incl_index = 0;
1477 ElfW(Sym) *sym, *sym_end;
1478 int type;
1480 sym_end = (ElfW(Sym) *)(symtab_section->data + symtab_section->data_offset);
1481 for(sym = (ElfW(Sym) *)symtab_section->data + 1;
1482 sym < sym_end;
1483 sym++) {
1484 type = ELFW(ST_TYPE)(sym->st_info);
1485 if (type == STT_FUNC) {
1486 if (wanted_pc >= sym->st_value &&
1487 wanted_pc < sym->st_value + sym->st_size) {
1488 pstrcpy(last_func_name, sizeof(last_func_name),
1489 strtab_section->data + sym->st_name);
1490 func_addr = sym->st_value;
1491 goto found;
1496 /* did not find any info: */
1497 fprintf(stderr, " ???\n");
1498 return 0;
1499 found:
1500 if (last_func_name[0] != '\0') {
1501 fprintf(stderr, " %s()", last_func_name);
1503 if (incl_index > 0) {
1504 fprintf(stderr, " (%s:%d",
1505 incl_files[incl_index - 1], last_line_num);
1506 for(i = incl_index - 2; i >= 0; i--)
1507 fprintf(stderr, ", included from %s", incl_files[i]);
1508 fprintf(stderr, ")");
1510 fprintf(stderr, "\n");
1511 return func_addr;
1514 #ifdef __i386__
1515 /* fix for glibc 2.1 */
1516 #ifndef REG_EIP
1517 #define REG_EIP EIP
1518 #define REG_EBP EBP
1519 #endif
1521 /* return the PC at frame level 'level'. Return non zero if not found */
1522 static int rt_get_caller_pc(unsigned long *paddr,
1523 ucontext_t *uc, int level)
1525 unsigned long fp;
1526 int i;
1528 if (level == 0) {
1529 #if defined(__FreeBSD__)
1530 *paddr = uc->uc_mcontext.mc_eip;
1531 #elif defined(__dietlibc__)
1532 *paddr = uc->uc_mcontext.eip;
1533 #else
1534 *paddr = uc->uc_mcontext.gregs[REG_EIP];
1535 #endif
1536 return 0;
1537 } else {
1538 #if defined(__FreeBSD__)
1539 fp = uc->uc_mcontext.mc_ebp;
1540 #elif defined(__dietlibc__)
1541 fp = uc->uc_mcontext.ebp;
1542 #else
1543 fp = uc->uc_mcontext.gregs[REG_EBP];
1544 #endif
1545 for(i=1;i<level;i++) {
1546 /* XXX: check address validity with program info */
1547 if (fp <= 0x1000 || fp >= 0xc0000000)
1548 return -1;
1549 fp = ((unsigned long *)fp)[0];
1551 *paddr = ((unsigned long *)fp)[1];
1552 return 0;
1555 #elif defined(__x86_64__)
1556 /* return the PC at frame level 'level'. Return non zero if not found */
1557 static int rt_get_caller_pc(unsigned long *paddr,
1558 ucontext_t *uc, int level)
1560 unsigned long fp;
1561 int i;
1563 if (level == 0) {
1564 /* XXX: only support linux */
1565 *paddr = uc->uc_mcontext.gregs[REG_RIP];
1566 return 0;
1567 } else {
1568 fp = uc->uc_mcontext.gregs[REG_RBP];
1569 for(i=1;i<level;i++) {
1570 /* XXX: check address validity with program info */
1571 if (fp <= 0x1000)
1572 return -1;
1573 fp = ((unsigned long *)fp)[0];
1575 *paddr = ((unsigned long *)fp)[1];
1576 return 0;
1579 #else
1580 #warning add arch specific rt_get_caller_pc()
1581 static int rt_get_caller_pc(unsigned long *paddr,
1582 ucontext_t *uc, int level)
1584 return -1;
1586 #endif
1588 /* emit a run time error at position 'pc' */
1589 void rt_error(ucontext_t *uc, const char *fmt, ...)
1591 va_list ap;
1592 unsigned long pc;
1593 int i;
1595 va_start(ap, fmt);
1596 fprintf(stderr, "Runtime error: ");
1597 vfprintf(stderr, fmt, ap);
1598 fprintf(stderr, "\n");
1599 for(i=0;i<num_callers;i++) {
1600 if (rt_get_caller_pc(&pc, uc, i) < 0)
1601 break;
1602 if (i == 0)
1603 fprintf(stderr, "at ");
1604 else
1605 fprintf(stderr, "by ");
1606 pc = rt_printline(pc);
1607 if (pc == rt_prog_main && pc)
1608 break;
1610 exit(255);
1611 va_end(ap);
1614 /* signal handler for fatal errors */
1615 static void sig_error(int signum, siginfo_t *siginf, void *puc)
1617 ucontext_t *uc = puc;
1619 switch(signum) {
1620 case SIGFPE:
1621 switch(siginf->si_code) {
1622 case FPE_INTDIV:
1623 case FPE_FLTDIV:
1624 rt_error(uc, "division by zero");
1625 break;
1626 default:
1627 rt_error(uc, "floating point exception");
1628 break;
1630 break;
1631 case SIGBUS:
1632 case SIGSEGV:
1633 if (rt_bound_error_msg && *rt_bound_error_msg)
1634 rt_error(uc, *rt_bound_error_msg);
1635 else
1636 rt_error(uc, "dereferencing invalid pointer");
1637 break;
1638 case SIGILL:
1639 rt_error(uc, "illegal instruction");
1640 break;
1641 case SIGABRT:
1642 rt_error(uc, "abort() called");
1643 break;
1644 default:
1645 rt_error(uc, "caught signal %d", signum);
1646 break;
1648 exit(255);
1651 #endif
1653 /* copy code into memory passed in by the caller and do all relocations
1654 (needed before using tcc_get_symbol()).
1655 returns -1 on error and required size if ptr is NULL */
1656 int tcc_relocate(TCCState *s1, void *ptr)
1658 Section *s;
1659 unsigned long offset, length;
1660 uplong mem;
1661 int i;
1663 if (0 == s1->runtime_added) {
1664 s1->runtime_added = 1;
1665 s1->nb_errors = 0;
1666 #ifdef TCC_TARGET_PE
1667 pe_output_file(s1, NULL);
1668 #else
1669 tcc_add_runtime(s1);
1670 relocate_common_syms();
1671 tcc_add_linker_symbols(s1);
1672 build_got_entries(s1);
1673 #endif
1674 if (s1->nb_errors)
1675 return -1;
1678 offset = 0, mem = (uplong)ptr;
1679 for(i = 1; i < s1->nb_sections; i++) {
1680 s = s1->sections[i];
1681 if (0 == (s->sh_flags & SHF_ALLOC))
1682 continue;
1683 length = s->data_offset;
1684 s->sh_addr = mem ? (mem + offset + 15) & ~15 : 0;
1685 offset = (offset + length + 15) & ~15;
1688 /* relocate symbols */
1689 relocate_syms(s1, 1);
1690 if (s1->nb_errors)
1691 return -1;
1693 #ifndef TCC_TARGET_PE
1694 #ifdef TCC_TARGET_X86_64
1695 s1->runtime_plt_and_got_offset = 0;
1696 s1->runtime_plt_and_got = (char *)(mem + offset);
1697 /* double the size of the buffer for got and plt entries
1698 XXX: calculate exact size for them? */
1699 offset *= 2;
1700 #endif
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*)(uplong)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 #ifndef TCC_TARGET_PE
1729 #ifdef TCC_TARGET_X86_64
1730 set_pages_executable(s1->runtime_plt_and_got,
1731 s1->runtime_plt_and_got_offset);
1732 #endif
1733 #endif
1734 return 0;
1737 /* launch the compiled program with the given arguments */
1738 int tcc_run(TCCState *s1, int argc, char **argv)
1740 int (*prog_main)(int, char **);
1741 void *ptr;
1742 int ret;
1744 ret = tcc_relocate(s1, NULL);
1745 if (ret < 0)
1746 return -1;
1747 ptr = tcc_malloc(ret);
1748 tcc_relocate(s1, ptr);
1750 prog_main = tcc_get_symbol_err(s1, "main");
1752 if (s1->do_debug) {
1753 #ifdef CONFIG_TCC_BACKTRACE
1754 struct sigaction sigact;
1755 /* install TCC signal handlers to print debug info on fatal
1756 runtime errors */
1757 sigact.sa_flags = SA_SIGINFO | SA_RESETHAND;
1758 sigact.sa_sigaction = sig_error;
1759 sigemptyset(&sigact.sa_mask);
1760 sigaction(SIGFPE, &sigact, NULL);
1761 sigaction(SIGILL, &sigact, NULL);
1762 sigaction(SIGSEGV, &sigact, NULL);
1763 sigaction(SIGBUS, &sigact, NULL);
1764 sigaction(SIGABRT, &sigact, NULL);
1765 #else
1766 error("debug mode not available");
1767 #endif
1770 #ifdef CONFIG_TCC_BCHECK
1771 if (s1->do_bounds_check) {
1772 void (*bound_init)(void);
1773 void (*bound_exit)(void);
1774 /* set error function */
1775 rt_bound_error_msg = tcc_get_symbol_err(s1, "__bound_error_msg");
1776 rt_prog_main = (unsigned long)prog_main;
1777 /* XXX: use .init section so that it also work in binary ? */
1778 bound_init = tcc_get_symbol_err(s1, "__bound_init");
1779 bound_exit = tcc_get_symbol_err(s1, "__bound_exit");
1780 bound_init();
1781 ret = (*prog_main)(argc, argv);
1782 bound_exit();
1783 } else
1784 #endif
1785 ret = (*prog_main)(argc, argv);
1786 tcc_free(ptr);
1787 return ret;
1790 void tcc_memstats(void)
1792 #ifdef MEM_DEBUG
1793 printf("memory in use: %d\n", mem_cur_size);
1794 #endif
1797 static void tcc_cleanup(void)
1799 int i, n;
1801 if (NULL == tcc_state)
1802 return;
1803 tcc_state = NULL;
1805 /* free -D defines */
1806 free_defines(NULL);
1808 /* free tokens */
1809 n = tok_ident - TOK_IDENT;
1810 for(i = 0; i < n; i++)
1811 tcc_free(table_ident[i]);
1812 tcc_free(table_ident);
1814 /* free sym_pools */
1815 dynarray_reset(&sym_pools, &nb_sym_pools);
1816 /* string buffer */
1817 cstr_free(&tokcstr);
1818 /* reset symbol stack */
1819 sym_free_first = NULL;
1820 /* cleanup from error/setjmp */
1821 macro_ptr = NULL;
1824 TCCState *tcc_new(void)
1826 TCCState *s;
1828 tcc_cleanup();
1830 s = tcc_mallocz(sizeof(TCCState));
1831 if (!s)
1832 return NULL;
1833 tcc_state = s;
1834 s->output_type = TCC_OUTPUT_MEMORY;
1835 s->tcc_lib_path = CONFIG_TCCDIR;
1837 preprocess_new();
1839 /* we add dummy defines for some special macros to speed up tests
1840 and to have working defined() */
1841 define_push(TOK___LINE__, MACRO_OBJ, NULL, NULL);
1842 define_push(TOK___FILE__, MACRO_OBJ, NULL, NULL);
1843 define_push(TOK___DATE__, MACRO_OBJ, NULL, NULL);
1844 define_push(TOK___TIME__, MACRO_OBJ, NULL, NULL);
1846 /* standard defines */
1847 tcc_define_symbol(s, "__STDC__", NULL);
1848 tcc_define_symbol(s, "__STDC_VERSION__", "199901L");
1849 #if defined(TCC_TARGET_I386)
1850 tcc_define_symbol(s, "__i386__", NULL);
1851 #endif
1852 #if defined(TCC_TARGET_X86_64)
1853 tcc_define_symbol(s, "__x86_64__", NULL);
1854 #endif
1855 #if defined(TCC_TARGET_ARM)
1856 tcc_define_symbol(s, "__ARM_ARCH_4__", NULL);
1857 tcc_define_symbol(s, "__arm_elf__", NULL);
1858 tcc_define_symbol(s, "__arm_elf", NULL);
1859 tcc_define_symbol(s, "arm_elf", NULL);
1860 tcc_define_symbol(s, "__arm__", NULL);
1861 tcc_define_symbol(s, "__arm", NULL);
1862 tcc_define_symbol(s, "arm", NULL);
1863 tcc_define_symbol(s, "__APCS_32__", NULL);
1864 #endif
1865 #ifdef TCC_TARGET_PE
1866 tcc_define_symbol(s, "_WIN32", NULL);
1867 #ifdef TCC_TARGET_X86_64
1868 tcc_define_symbol(s, "_WIN64", NULL);
1869 #endif
1870 #else
1871 tcc_define_symbol(s, "__unix__", NULL);
1872 tcc_define_symbol(s, "__unix", NULL);
1873 #if defined(__linux)
1874 tcc_define_symbol(s, "__linux__", NULL);
1875 tcc_define_symbol(s, "__linux", NULL);
1876 #endif
1877 #endif
1878 /* tiny C specific defines */
1879 tcc_define_symbol(s, "__TINYC__", NULL);
1881 /* tiny C & gcc defines */
1882 tcc_define_symbol(s, "__SIZE_TYPE__", "unsigned int");
1883 tcc_define_symbol(s, "__PTRDIFF_TYPE__", "int");
1884 #ifdef TCC_TARGET_PE
1885 tcc_define_symbol(s, "__WCHAR_TYPE__", "unsigned short");
1886 #else
1887 tcc_define_symbol(s, "__WCHAR_TYPE__", "int");
1888 #endif
1890 #ifndef TCC_TARGET_PE
1891 /* default library paths */
1892 tcc_add_library_path(s, CONFIG_SYSROOT "/usr/local/lib");
1893 tcc_add_library_path(s, CONFIG_SYSROOT "/usr/lib");
1894 tcc_add_library_path(s, CONFIG_SYSROOT "/lib");
1895 #endif
1897 /* no section zero */
1898 dynarray_add((void ***)&s->sections, &s->nb_sections, NULL);
1900 /* create standard sections */
1901 text_section = new_section(s, ".text", SHT_PROGBITS, SHF_ALLOC | SHF_EXECINSTR);
1902 data_section = new_section(s, ".data", SHT_PROGBITS, SHF_ALLOC | SHF_WRITE);
1903 bss_section = new_section(s, ".bss", SHT_NOBITS, SHF_ALLOC | SHF_WRITE);
1905 /* symbols are always generated for linking stage */
1906 symtab_section = new_symtab(s, ".symtab", SHT_SYMTAB, 0,
1907 ".strtab",
1908 ".hashtab", SHF_PRIVATE);
1909 strtab_section = symtab_section->link;
1911 /* private symbol table for dynamic symbols */
1912 s->dynsymtab_section = new_symtab(s, ".dynsymtab", SHT_SYMTAB, SHF_PRIVATE,
1913 ".dynstrtab",
1914 ".dynhashtab", SHF_PRIVATE);
1915 s->alacarte_link = 1;
1917 #ifdef CHAR_IS_UNSIGNED
1918 s->char_is_unsigned = 1;
1919 #endif
1920 #if defined(TCC_TARGET_PE) && 0
1921 /* XXX: currently the PE linker is not ready to support that */
1922 s->leading_underscore = 1;
1923 #endif
1924 return s;
1927 void tcc_delete(TCCState *s1)
1929 int i;
1931 tcc_cleanup();
1933 /* free all sections */
1934 for(i = 1; i < s1->nb_sections; i++)
1935 free_section(s1->sections[i]);
1936 dynarray_reset(&s1->sections, &s1->nb_sections);
1938 for(i = 0; i < s1->nb_priv_sections; i++)
1939 free_section(s1->priv_sections[i]);
1940 dynarray_reset(&s1->priv_sections, &s1->nb_priv_sections);
1942 /* free any loaded DLLs */
1943 for ( i = 0; i < s1->nb_loaded_dlls; i++) {
1944 DLLReference *ref = s1->loaded_dlls[i];
1945 if ( ref->handle )
1946 dlclose(ref->handle);
1949 /* free loaded dlls array */
1950 dynarray_reset(&s1->loaded_dlls, &s1->nb_loaded_dlls);
1952 /* free library paths */
1953 dynarray_reset(&s1->library_paths, &s1->nb_library_paths);
1955 /* free include paths */
1956 dynarray_reset(&s1->cached_includes, &s1->nb_cached_includes);
1957 dynarray_reset(&s1->include_paths, &s1->nb_include_paths);
1958 dynarray_reset(&s1->sysinclude_paths, &s1->nb_sysinclude_paths);
1960 tcc_free(s1);
1963 int tcc_add_include_path(TCCState *s1, const char *pathname)
1965 char *pathname1;
1967 pathname1 = tcc_strdup(pathname);
1968 dynarray_add((void ***)&s1->include_paths, &s1->nb_include_paths, pathname1);
1969 return 0;
1972 int tcc_add_sysinclude_path(TCCState *s1, const char *pathname)
1974 char *pathname1;
1976 pathname1 = tcc_strdup(pathname);
1977 dynarray_add((void ***)&s1->sysinclude_paths, &s1->nb_sysinclude_paths, pathname1);
1978 return 0;
1981 static int tcc_add_file_internal(TCCState *s1, const char *filename, int flags)
1983 const char *ext;
1984 ElfW(Ehdr) ehdr;
1985 int fd, ret;
1986 BufferedFile *saved_file;
1988 /* find source file type with extension */
1989 ext = tcc_fileextension(filename);
1990 if (ext[0])
1991 ext++;
1993 /* open the file */
1994 saved_file = file;
1995 file = tcc_open(s1, filename);
1996 if (!file) {
1997 if (flags & AFF_PRINT_ERROR) {
1998 error_noabort("file '%s' not found", filename);
2000 ret = -1;
2001 goto fail1;
2004 if (flags & AFF_PREPROCESS) {
2005 ret = tcc_preprocess(s1);
2006 } else if (!ext[0] || !PATHCMP(ext, "c")) {
2007 /* C file assumed */
2008 ret = tcc_compile(s1);
2009 } else
2010 #ifdef CONFIG_TCC_ASM
2011 if (!strcmp(ext, "S")) {
2012 /* preprocessed assembler */
2013 ret = tcc_assemble(s1, 1);
2014 } else if (!strcmp(ext, "s")) {
2015 /* non preprocessed assembler */
2016 ret = tcc_assemble(s1, 0);
2017 } else
2018 #endif
2019 #ifdef TCC_TARGET_PE
2020 if (!PATHCMP(ext, "def")) {
2021 ret = pe_load_def_file(s1, file->fd);
2022 } else
2023 #endif
2025 fd = file->fd;
2026 /* assume executable format: auto guess file type */
2027 ret = read(fd, &ehdr, sizeof(ehdr));
2028 lseek(fd, 0, SEEK_SET);
2029 if (ret <= 0) {
2030 error_noabort("could not read header");
2031 goto fail;
2032 } else if (ret != sizeof(ehdr)) {
2033 goto try_load_script;
2036 if (ehdr.e_ident[0] == ELFMAG0 &&
2037 ehdr.e_ident[1] == ELFMAG1 &&
2038 ehdr.e_ident[2] == ELFMAG2 &&
2039 ehdr.e_ident[3] == ELFMAG3) {
2040 file->line_num = 0; /* do not display line number if error */
2041 if (ehdr.e_type == ET_REL) {
2042 ret = tcc_load_object_file(s1, fd, 0);
2043 } else if (ehdr.e_type == ET_DYN) {
2044 if (s1->output_type == TCC_OUTPUT_MEMORY) {
2045 #ifdef TCC_TARGET_PE
2046 ret = -1;
2047 #else
2048 void *h;
2049 h = dlopen(filename, RTLD_GLOBAL | RTLD_LAZY);
2050 if (h)
2051 ret = 0;
2052 else
2053 ret = -1;
2054 #endif
2055 } else {
2056 ret = tcc_load_dll(s1, fd, filename,
2057 (flags & AFF_REFERENCED_DLL) != 0);
2059 } else {
2060 error_noabort("unrecognized ELF file");
2061 goto fail;
2063 } else if (memcmp((char *)&ehdr, ARMAG, 8) == 0) {
2064 file->line_num = 0; /* do not display line number if error */
2065 ret = tcc_load_archive(s1, fd);
2066 } else
2067 #ifdef TCC_TARGET_COFF
2068 if (*(uint16_t *)(&ehdr) == COFF_C67_MAGIC) {
2069 ret = tcc_load_coff(s1, fd);
2070 } else
2071 #endif
2072 #ifdef TCC_TARGET_PE
2073 if (pe_test_res_file(&ehdr, ret)) {
2074 ret = pe_load_res_file(s1, fd);
2075 } else
2076 #endif
2078 /* as GNU ld, consider it is an ld script if not recognized */
2079 try_load_script:
2080 ret = tcc_load_ldscript(s1);
2081 if (ret < 0) {
2082 error_noabort("unrecognized file type");
2083 goto fail;
2087 the_end:
2088 tcc_close(file);
2089 fail1:
2090 file = saved_file;
2091 return ret;
2092 fail:
2093 ret = -1;
2094 goto the_end;
2097 int tcc_add_file(TCCState *s, const char *filename)
2099 if (s->output_type == TCC_OUTPUT_PREPROCESS)
2100 return tcc_add_file_internal(s, filename, AFF_PRINT_ERROR | AFF_PREPROCESS);
2101 else
2102 return tcc_add_file_internal(s, filename, AFF_PRINT_ERROR);
2105 int tcc_add_library_path(TCCState *s, const char *pathname)
2107 char *pathname1;
2109 pathname1 = tcc_strdup(pathname);
2110 dynarray_add((void ***)&s->library_paths, &s->nb_library_paths, pathname1);
2111 return 0;
2114 /* find and load a dll. Return non zero if not found */
2115 /* XXX: add '-rpath' option support ? */
2116 static int tcc_add_dll(TCCState *s, const char *filename, int flags)
2118 char buf[1024];
2119 int i;
2121 for(i = 0; i < s->nb_library_paths; i++) {
2122 snprintf(buf, sizeof(buf), "%s/%s",
2123 s->library_paths[i], filename);
2124 if (tcc_add_file_internal(s, buf, flags) == 0)
2125 return 0;
2127 return -1;
2130 /* the library name is the same as the argument of the '-l' option */
2131 int tcc_add_library(TCCState *s, const char *libraryname)
2133 char buf[1024];
2134 int i;
2136 /* first we look for the dynamic library if not static linking */
2137 if (!s->static_link) {
2138 #ifdef TCC_TARGET_PE
2139 snprintf(buf, sizeof(buf), "%s.def", libraryname);
2140 #else
2141 snprintf(buf, sizeof(buf), "lib%s.so", libraryname);
2142 #endif
2143 if (tcc_add_dll(s, buf, 0) == 0)
2144 return 0;
2147 /* then we look for the static library */
2148 for(i = 0; i < s->nb_library_paths; i++) {
2149 snprintf(buf, sizeof(buf), "%s/lib%s.a",
2150 s->library_paths[i], libraryname);
2151 if (tcc_add_file_internal(s, buf, 0) == 0)
2152 return 0;
2154 return -1;
2157 int tcc_add_symbol(TCCState *s, const char *name, void *val)
2159 add_elf_sym(symtab_section, (uplong)val, 0,
2160 ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE), 0,
2161 SHN_ABS, name);
2162 return 0;
2165 int tcc_set_output_type(TCCState *s, int output_type)
2167 char buf[1024];
2169 s->output_type = output_type;
2171 if (!s->nostdinc) {
2172 /* default include paths */
2173 /* XXX: reverse order needed if -isystem support */
2174 #ifndef TCC_TARGET_PE
2175 tcc_add_sysinclude_path(s, CONFIG_SYSROOT "/usr/local/include");
2176 tcc_add_sysinclude_path(s, CONFIG_SYSROOT "/usr/include");
2177 #endif
2178 snprintf(buf, sizeof(buf), "%s/include", s->tcc_lib_path);
2179 tcc_add_sysinclude_path(s, buf);
2180 #ifdef TCC_TARGET_PE
2181 snprintf(buf, sizeof(buf), "%s/include/winapi", s->tcc_lib_path);
2182 tcc_add_sysinclude_path(s, buf);
2183 #endif
2186 /* if bound checking, then add corresponding sections */
2187 #ifdef CONFIG_TCC_BCHECK
2188 if (s->do_bounds_check) {
2189 /* define symbol */
2190 tcc_define_symbol(s, "__BOUNDS_CHECKING_ON", NULL);
2191 /* create bounds sections */
2192 bounds_section = new_section(s, ".bounds",
2193 SHT_PROGBITS, SHF_ALLOC);
2194 lbounds_section = new_section(s, ".lbounds",
2195 SHT_PROGBITS, SHF_ALLOC);
2197 #endif
2199 if (s->char_is_unsigned) {
2200 tcc_define_symbol(s, "__CHAR_UNSIGNED__", NULL);
2203 /* add debug sections */
2204 if (s->do_debug) {
2205 /* stab symbols */
2206 stab_section = new_section(s, ".stab", SHT_PROGBITS, 0);
2207 stab_section->sh_entsize = sizeof(Stab_Sym);
2208 stabstr_section = new_section(s, ".stabstr", SHT_STRTAB, 0);
2209 put_elf_str(stabstr_section, "");
2210 stab_section->link = stabstr_section;
2211 /* put first entry */
2212 put_stabs("", 0, 0, 0, 0);
2215 /* add libc crt1/crti objects */
2216 #ifndef TCC_TARGET_PE
2217 if ((output_type == TCC_OUTPUT_EXE || output_type == TCC_OUTPUT_DLL) &&
2218 !s->nostdlib) {
2219 if (output_type != TCC_OUTPUT_DLL)
2220 tcc_add_file(s, CONFIG_TCC_CRT_PREFIX "/crt1.o");
2221 tcc_add_file(s, CONFIG_TCC_CRT_PREFIX "/crti.o");
2223 #endif
2225 #ifdef TCC_TARGET_PE
2226 snprintf(buf, sizeof(buf), "%s/lib", s->tcc_lib_path);
2227 tcc_add_library_path(s, buf);
2228 #endif
2230 return 0;
2233 #define WD_ALL 0x0001 /* warning is activated when using -Wall */
2234 #define FD_INVERT 0x0002 /* invert value before storing */
2236 typedef struct FlagDef {
2237 uint16_t offset;
2238 uint16_t flags;
2239 const char *name;
2240 } FlagDef;
2242 static const FlagDef warning_defs[] = {
2243 { offsetof(TCCState, warn_unsupported), 0, "unsupported" },
2244 { offsetof(TCCState, warn_write_strings), 0, "write-strings" },
2245 { offsetof(TCCState, warn_error), 0, "error" },
2246 { offsetof(TCCState, warn_implicit_function_declaration), WD_ALL,
2247 "implicit-function-declaration" },
2250 static int set_flag(TCCState *s, const FlagDef *flags, int nb_flags,
2251 const char *name, int value)
2253 int i;
2254 const FlagDef *p;
2255 const char *r;
2257 r = name;
2258 if (r[0] == 'n' && r[1] == 'o' && r[2] == '-') {
2259 r += 3;
2260 value = !value;
2262 for(i = 0, p = flags; i < nb_flags; i++, p++) {
2263 if (!strcmp(r, p->name))
2264 goto found;
2266 return -1;
2267 found:
2268 if (p->flags & FD_INVERT)
2269 value = !value;
2270 *(int *)((uint8_t *)s + p->offset) = value;
2271 return 0;
2275 /* set/reset a warning */
2276 int tcc_set_warning(TCCState *s, const char *warning_name, int value)
2278 int i;
2279 const FlagDef *p;
2281 if (!strcmp(warning_name, "all")) {
2282 for(i = 0, p = warning_defs; i < countof(warning_defs); i++, p++) {
2283 if (p->flags & WD_ALL)
2284 *(int *)((uint8_t *)s + p->offset) = 1;
2286 return 0;
2287 } else {
2288 return set_flag(s, warning_defs, countof(warning_defs),
2289 warning_name, value);
2293 static const FlagDef flag_defs[] = {
2294 { offsetof(TCCState, char_is_unsigned), 0, "unsigned-char" },
2295 { offsetof(TCCState, char_is_unsigned), FD_INVERT, "signed-char" },
2296 { offsetof(TCCState, nocommon), FD_INVERT, "common" },
2297 { offsetof(TCCState, leading_underscore), 0, "leading-underscore" },
2300 /* set/reset a flag */
2301 int tcc_set_flag(TCCState *s, const char *flag_name, int value)
2303 return set_flag(s, flag_defs, countof(flag_defs),
2304 flag_name, value);
2307 /* set CONFIG_TCCDIR at runtime */
2308 void tcc_set_lib_path(TCCState *s, const char *path)
2310 s->tcc_lib_path = tcc_strdup(path);
2313 void tcc_print_stats(TCCState *s, int64_t total_time)
2315 double tt;
2316 tt = (double)total_time / 1000000.0;
2317 if (tt < 0.001)
2318 tt = 0.001;
2319 if (total_bytes < 1)
2320 total_bytes = 1;
2321 printf("%d idents, %d lines, %d bytes, %0.3f s, %d lines/s, %0.1f MB/s\n",
2322 tok_ident - TOK_IDENT, total_lines, total_bytes,
2323 tt, (int)(total_lines / tt),
2324 total_bytes / tt / 1000000.0);