Fixed compilation error in i386-asm.c
[tinycc/kirr.git] / libtcc.c
blobdfb000a22cceac6fa664a2540dd8e1375371741f
1 /*
2 * TCC - Tiny C Compiler
3 *
4 * Copyright (c) 2001-2004 Fabrice Bellard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 #include "tcc.h"
23 /********************************************************/
24 /* global variables */
26 /* display benchmark infos */
27 int total_lines;
28 int total_bytes;
30 /* parser */
31 static struct BufferedFile *file;
32 static int ch, tok;
33 static CValue tokc;
34 static CString tokcstr; /* current parsed string, if any */
35 /* additional informations about token */
36 static int tok_flags;
37 #define TOK_FLAG_BOL 0x0001 /* beginning of line before */
38 #define TOK_FLAG_BOF 0x0002 /* beginning of file before */
39 #define TOK_FLAG_ENDIF 0x0004 /* a endif was found matching starting #ifdef */
40 #define TOK_FLAG_EOF 0x0008 /* end of file */
42 static int *macro_ptr, *macro_ptr_allocated;
43 static int *unget_saved_macro_ptr;
44 static int unget_saved_buffer[TOK_MAX_SIZE + 1];
45 static int unget_buffer_enabled;
46 static int parse_flags;
47 #define PARSE_FLAG_PREPROCESS 0x0001 /* activate preprocessing */
48 #define PARSE_FLAG_TOK_NUM 0x0002 /* return numbers instead of TOK_PPNUM */
49 #define PARSE_FLAG_LINEFEED 0x0004 /* line feed is returned as a
50 token. line feed is also
51 returned at eof */
52 #define PARSE_FLAG_ASM_COMMENTS 0x0008 /* '#' can be used for line comment */
53 #define PARSE_FLAG_SPACES 0x0010 /* next() returns space tokens (for -E) */
55 static Section *text_section, *data_section, *bss_section; /* predefined sections */
56 static Section *cur_text_section; /* current section where function code is
57 generated */
58 #ifdef CONFIG_TCC_ASM
59 static Section *last_text_section; /* to handle .previous asm directive */
60 #endif
61 /* bound check related sections */
62 static Section *bounds_section; /* contains global data bound description */
63 static Section *lbounds_section; /* contains local data bound description */
64 /* symbol sections */
65 static Section *symtab_section, *strtab_section;
67 /* debug sections */
68 static Section *stab_section, *stabstr_section;
70 /* loc : local variable index
71 ind : output code index
72 rsym: return symbol
73 anon_sym: anonymous symbol index
75 static int rsym, anon_sym, ind, loc;
76 /* expression generation modifiers */
77 static int const_wanted; /* true if constant wanted */
78 static int nocode_wanted; /* true if no code generation wanted for an expression */
79 static int global_expr; /* true if compound literals must be allocated
80 globally (used during initializers parsing */
81 static CType func_vt; /* current function return type (used by return
82 instruction) */
83 static int func_vc;
84 static int last_line_num, last_ind, func_ind; /* debug last line number and pc */
85 static int tok_ident;
86 static TokenSym **table_ident;
87 static TokenSym *hash_ident[TOK_HASH_SIZE];
88 static char token_buf[STRING_MAX_SIZE + 1];
89 static char *funcname;
90 static Sym *global_stack, *local_stack;
91 static Sym *define_stack;
92 static Sym *global_label_stack, *local_label_stack;
93 /* symbol allocator */
94 #define SYM_POOL_NB (8192 / sizeof(Sym))
95 static Sym *sym_free_first;
96 static void **sym_pools;
97 static int nb_sym_pools;
99 static SValue vstack[VSTACK_SIZE], *vtop;
100 /* some predefined types */
101 static CType char_pointer_type, func_old_type, int_type;
103 /* use GNU C extensions */
104 static int gnu_ext = 1;
106 /* use Tiny C extensions */
107 static int tcc_ext = 1;
109 /* max number of callers shown if error */
110 #ifdef CONFIG_TCC_BACKTRACE
111 int num_callers = 6;
112 const char **rt_bound_error_msg;
113 unsigned long rt_prog_main;
114 #endif
116 /* XXX: get rid of this ASAP */
117 static struct TCCState *tcc_state;
119 /********************************************************/
120 /* function prototypes */
122 /* tccpp.c */
123 static void next(void);
124 char *get_tok_str(int v, CValue *cv);
126 /* tccgen.c */
127 static void parse_expr_type(CType *type);
128 static void expr_type(CType *type);
129 static void unary_type(CType *type);
130 static void block(int *bsym, int *csym, int *case_sym, int *def_sym,
131 int case_reg, int is_expr);
132 static int expr_const(void);
133 static void expr_eq(void);
134 static void gexpr(void);
135 static void gen_inline_functions(void);
136 static void decl(int l);
137 static void decl_initializer(CType *type, Section *sec, unsigned long c,
138 int first, int size_only);
139 static void decl_initializer_alloc(CType *type, AttributeDef *ad, int r,
140 int has_init, int v, int scope);
141 int gv(int rc);
142 void gv2(int rc1, int rc2);
143 void move_reg(int r, int s);
144 void save_regs(int n);
145 void save_reg(int r);
146 void vpop(void);
147 void vswap(void);
148 void vdup(void);
149 int get_reg(int rc);
150 int get_reg_ex(int rc,int rc2);
152 void gen_op(int op);
153 void force_charshort_cast(int t);
154 static void gen_cast(CType *type);
155 void vstore(void);
156 static Sym *sym_find(int v);
157 static Sym *sym_push(int v, CType *type, int r, int c);
159 /* type handling */
160 static int type_size(CType *type, int *a);
161 static inline CType *pointed_type(CType *type);
162 static int pointed_size(CType *type);
163 static int lvalue_type(int t);
164 static int parse_btype(CType *type, AttributeDef *ad);
165 static void type_decl(CType *type, AttributeDef *ad, int *v, int td);
166 static int compare_types(CType *type1, CType *type2, int unqualified);
167 static int is_compatible_types(CType *type1, CType *type2);
168 static int is_compatible_parameter_types(CType *type1, CType *type2);
170 int ieee_finite(double d);
171 void vpushi(int v);
172 void vpushll(long long v);
173 void vrott(int n);
174 void vnrott(int n);
175 void lexpand_nr(void);
176 static void vpush_global_sym(CType *type, int v);
177 void vset(CType *type, int r, int v);
178 void type_to_str(char *buf, int buf_size,
179 CType *type, const char *varstr);
180 static Sym *get_sym_ref(CType *type, Section *sec,
181 unsigned long offset, unsigned long size);
182 static Sym *external_global_sym(int v, CType *type, int r);
184 /* section generation */
185 static void section_realloc(Section *sec, unsigned long new_size);
186 static void *section_ptr_add(Section *sec, unsigned long size);
187 static void put_extern_sym(Sym *sym, Section *section,
188 unsigned long value, unsigned long size);
189 static void greloc(Section *s, Sym *sym, unsigned long addr, int type);
190 static int put_elf_str(Section *s, const char *sym);
191 static int put_elf_sym(Section *s,
192 unsigned long value, unsigned long size,
193 int info, int other, int shndx, const char *name);
194 static int add_elf_sym(Section *s, uplong value, unsigned long size,
195 int info, int other, int sh_num, const char *name);
196 static void put_elf_reloc(Section *symtab, Section *s, unsigned long offset,
197 int type, int symbol);
198 static void put_stabs(const char *str, int type, int other, int desc,
199 unsigned long value);
200 static void put_stabs_r(const char *str, int type, int other, int desc,
201 unsigned long value, Section *sec, int sym_index);
202 static void put_stabn(int type, int other, int desc, int value);
203 static void put_stabd(int type, int other, int desc);
204 static int tcc_add_dll(TCCState *s, const char *filename, int flags);
206 #define AFF_PRINT_ERROR 0x0001 /* print error if file not found */
207 #define AFF_REFERENCED_DLL 0x0002 /* load a referenced dll from another dll */
208 #define AFF_PREPROCESS 0x0004 /* preprocess file */
209 static int tcc_add_file_internal(TCCState *s, const char *filename, int flags);
211 /* tcccoff.c */
212 int tcc_output_coff(TCCState *s1, FILE *f);
214 /* tccpe.c */
215 int pe_load_file(struct TCCState *s1, const char *filename, int fd);
216 int pe_output_file(struct TCCState *s1, const char *filename);
218 /* tccasm.c */
219 #ifdef CONFIG_TCC_ASM
220 static void asm_expr(TCCState *s1, ExprValue *pe);
221 static int asm_int_expr(TCCState *s1);
222 static int find_constraint(ASMOperand *operands, int nb_operands,
223 const char *name, const char **pp);
225 static int tcc_assemble(TCCState *s1, int do_preprocess);
226 #endif
228 static void asm_instr(void);
229 static void asm_global_instr(void);
231 /********************************************************/
232 /* libtcc.c */
234 static Sym *__sym_malloc(void);
235 static inline Sym *sym_malloc(void);
236 static inline void sym_free(Sym *sym);
237 Section *new_section(TCCState *s1, const char *name, int sh_type, int sh_flags);
238 static void free_section(Section *s);
239 static void section_realloc(Section *sec, unsigned long new_size);
240 static void *section_ptr_add(Section *sec, unsigned long size);
241 Section *find_section(TCCState *s1, const char *name);
242 static void put_extern_sym2(
243 Sym *sym, Section *section,
244 unsigned long value, unsigned long size, int can_add_underscore);
245 static void put_extern_sym(
246 Sym *sym, Section *section,
247 unsigned long value, unsigned long size);
248 static void greloc(Section *s, Sym *sym, unsigned long offset, int type);
250 static void strcat_vprintf(char *buf, int buf_size, const char *fmt, va_list ap);
251 static void strcat_printf(char *buf, int buf_size, const char *fmt, ...);
253 /* CString handling */
254 static void cstr_realloc(CString *cstr, int new_size);
255 static inline void cstr_ccat(CString *cstr, int ch);
256 static void cstr_cat(CString *cstr, const char *str);
257 static void cstr_wccat(CString *cstr, int ch);
258 static void cstr_new(CString *cstr);
259 static void cstr_free(CString *cstr);
260 #define cstr_reset(cstr) cstr_free(cstr)
261 static void add_char(CString *cstr, int c);
263 static Sym *sym_push2(Sym **ps, int v, int t, long c);
264 static Sym *sym_find2(Sym *s, int v);
265 static inline Sym *struct_find(int v);
266 static inline Sym *sym_find(int v);
267 static Sym *sym_push(int v, CType *type, int r, int c);
268 static Sym *global_identifier_push(int v, int t, int c);
269 static void sym_pop(Sym **ptop, Sym *b);
271 BufferedFile *tcc_open(TCCState *s1, const char *filename);
272 void tcc_close(BufferedFile *bf);
273 static int tcc_compile(TCCState *s1);
275 void expect(const char *msg);
276 void skip(int c);
277 static void test_lvalue(void);
278 void *resolve_sym(TCCState *s1, const char *sym);
280 static inline int isid(int c)
282 return (c >= 'a' && c <= 'z')
283 || (c >= 'A' && c <= 'Z')
284 || c == '_';
287 static inline int isnum(int c)
289 return c >= '0' && c <= '9';
292 static inline int isoct(int c)
294 return c >= '0' && c <= '7';
297 static inline int toup(int c)
299 if (c >= 'a' && c <= 'z')
300 return c - 'a' + 'A';
301 else
302 return c;
305 /********************************************************/
307 #ifdef TCC_TARGET_I386
308 #include "i386-gen.c"
309 #endif
311 #ifdef TCC_TARGET_ARM
312 #include "arm-gen.c"
313 #endif
315 #ifdef TCC_TARGET_C67
316 #include "c67-gen.c"
317 #endif
319 #ifdef TCC_TARGET_X86_64
320 #include "x86_64-gen.c"
321 #endif
323 #include "tccpp.c"
324 #include "tccgen.c"
326 #ifdef CONFIG_TCC_ASM
328 #ifdef TCC_TARGET_I386
329 #include "i386-asm.c"
330 #endif
332 #ifdef TCC_TARGET_X86_64
333 #include "x86_64-asm.c"
334 #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 _WIN32
360 char *normalize_slashes(char *path)
362 char *p;
363 for (p = path; *p; ++p)
364 if (*p == '\\')
365 *p = '/';
366 return path;
369 HMODULE tcc_module;
371 /* on win32, we suppose the lib and includes are at the location of 'tcc.exe' */
372 void tcc_set_lib_path_w32(TCCState *s)
374 char path[1024], *p;
375 GetModuleFileNameA(tcc_module, path, sizeof path);
376 p = tcc_basename(normalize_slashes(strlwr(path)));
377 if (p - 5 > path && 0 == strncmp(p - 5, "/bin/", 5))
378 p -= 5;
379 else if (p > path)
380 p--;
381 *p = 0;
382 tcc_set_lib_path(s, path);
385 #ifdef LIBTCC_AS_DLL
386 BOOL WINAPI DllMain (HANDLE hDll, DWORD dwReason, LPVOID lpReserved)
388 if (DLL_PROCESS_ATTACH == dwReason)
389 tcc_module = hDll;
390 return TRUE;
392 #endif
393 #endif
395 /********************************************************/
396 #ifdef CONFIG_TCC_STATIC
398 #define RTLD_LAZY 0x001
399 #define RTLD_NOW 0x002
400 #define RTLD_GLOBAL 0x100
401 #define RTLD_DEFAULT NULL
403 /* dummy function for profiling */
404 void *dlopen(const char *filename, int flag)
406 return NULL;
409 void dlclose(void *p)
413 const char *dlerror(void)
415 return "error";
418 typedef struct TCCSyms {
419 char *str;
420 void *ptr;
421 } TCCSyms;
423 #define TCCSYM(a) { #a, &a, },
425 /* add the symbol you want here if no dynamic linking is done */
426 static TCCSyms tcc_syms[] = {
427 #if !defined(CONFIG_TCCBOOT)
428 TCCSYM(printf)
429 TCCSYM(fprintf)
430 TCCSYM(fopen)
431 TCCSYM(fclose)
432 #endif
433 { NULL, NULL },
436 void *resolve_sym(TCCState *s1, const char *symbol)
438 TCCSyms *p;
439 p = tcc_syms;
440 while (p->str != NULL) {
441 if (!strcmp(p->str, symbol))
442 return p->ptr;
443 p++;
445 return NULL;
448 #elif defined(_WIN32)
449 #define dlclose FreeLibrary
451 #else
452 #include <dlfcn.h>
454 void *resolve_sym(TCCState *s1, const char *sym)
456 return dlsym(RTLD_DEFAULT, sym);
459 #endif
461 /********************************************************/
463 /* we use our own 'finite' function to avoid potential problems with
464 non standard math libs */
465 /* XXX: endianness dependent */
466 int ieee_finite(double d)
468 int *p = (int *)&d;
469 return ((unsigned)((p[1] | 0x800fffff) + 1)) >> 31;
472 /* copy a string and truncate it. */
473 char *pstrcpy(char *buf, int buf_size, const char *s)
475 char *q, *q_end;
476 int c;
478 if (buf_size > 0) {
479 q = buf;
480 q_end = buf + buf_size - 1;
481 while (q < q_end) {
482 c = *s++;
483 if (c == '\0')
484 break;
485 *q++ = c;
487 *q = '\0';
489 return buf;
492 /* strcat and truncate. */
493 char *pstrcat(char *buf, int buf_size, const char *s)
495 int len;
496 len = strlen(buf);
497 if (len < buf_size)
498 pstrcpy(buf + len, buf_size - len, s);
499 return buf;
502 /* extract the basename of a file */
503 char *tcc_basename(const char *name)
505 char *p = strchr(name, 0);
506 while (p > name && !IS_PATHSEP(p[-1]))
507 --p;
508 return p;
511 char *tcc_fileextension (const char *name)
513 char *b = tcc_basename(name);
514 char *e = strrchr(b, '.');
515 return e ? e : strchr(b, 0);
518 void set_pages_executable(void *ptr, unsigned long length)
520 #ifdef _WIN32
521 unsigned long old_protect;
522 VirtualProtect(ptr, length, PAGE_EXECUTE_READWRITE, &old_protect);
523 #else
524 unsigned long start, end;
525 start = (unsigned long)ptr & ~(PAGESIZE - 1);
526 end = (unsigned long)ptr + length;
527 end = (end + PAGESIZE - 1) & ~(PAGESIZE - 1);
528 mprotect((void *)start, end - start, PROT_READ | PROT_WRITE | PROT_EXEC);
529 #endif
532 /* memory management */
533 #ifdef MEM_DEBUG
534 int mem_cur_size;
535 int mem_max_size;
536 unsigned malloc_usable_size(void*);
537 #endif
539 void tcc_free(void *ptr)
541 #ifdef MEM_DEBUG
542 mem_cur_size -= malloc_usable_size(ptr);
543 #endif
544 free(ptr);
547 void *tcc_malloc(unsigned long size)
549 void *ptr;
550 ptr = malloc(size);
551 if (!ptr && size)
552 error("memory full");
553 #ifdef MEM_DEBUG
554 mem_cur_size += malloc_usable_size(ptr);
555 if (mem_cur_size > mem_max_size)
556 mem_max_size = mem_cur_size;
557 #endif
558 return ptr;
561 void *tcc_mallocz(unsigned long size)
563 void *ptr;
564 ptr = tcc_malloc(size);
565 memset(ptr, 0, size);
566 return ptr;
569 void *tcc_realloc(void *ptr, unsigned long size)
571 void *ptr1;
572 #ifdef MEM_DEBUG
573 mem_cur_size -= malloc_usable_size(ptr);
574 #endif
575 ptr1 = realloc(ptr, size);
576 #ifdef MEM_DEBUG
577 /* NOTE: count not correct if alloc error, but not critical */
578 mem_cur_size += malloc_usable_size(ptr1);
579 if (mem_cur_size > mem_max_size)
580 mem_max_size = mem_cur_size;
581 #endif
582 return ptr1;
585 char *tcc_strdup(const char *str)
587 char *ptr;
588 ptr = tcc_malloc(strlen(str) + 1);
589 strcpy(ptr, str);
590 return ptr;
593 #define free(p) use_tcc_free(p)
594 #define malloc(s) use_tcc_malloc(s)
595 #define realloc(p, s) use_tcc_realloc(p, s)
597 void dynarray_add(void ***ptab, int *nb_ptr, void *data)
599 int nb, nb_alloc;
600 void **pp;
602 nb = *nb_ptr;
603 pp = *ptab;
604 /* every power of two we double array size */
605 if ((nb & (nb - 1)) == 0) {
606 if (!nb)
607 nb_alloc = 1;
608 else
609 nb_alloc = nb * 2;
610 pp = tcc_realloc(pp, nb_alloc * sizeof(void *));
611 if (!pp)
612 error("memory full");
613 *ptab = pp;
615 pp[nb++] = data;
616 *nb_ptr = nb;
619 void dynarray_reset(void *pp, int *n)
621 void **p;
622 for (p = *(void***)pp; *n; ++p, --*n)
623 if (*p)
624 tcc_free(*p);
625 tcc_free(*(void**)pp);
626 *(void**)pp = NULL;
629 /* symbol allocator */
630 static Sym *__sym_malloc(void)
632 Sym *sym_pool, *sym, *last_sym;
633 int i;
635 sym_pool = tcc_malloc(SYM_POOL_NB * sizeof(Sym));
636 dynarray_add(&sym_pools, &nb_sym_pools, sym_pool);
638 last_sym = sym_free_first;
639 sym = sym_pool;
640 for(i = 0; i < SYM_POOL_NB; i++) {
641 sym->next = last_sym;
642 last_sym = sym;
643 sym++;
645 sym_free_first = last_sym;
646 return last_sym;
649 static inline Sym *sym_malloc(void)
651 Sym *sym;
652 sym = sym_free_first;
653 if (!sym)
654 sym = __sym_malloc();
655 sym_free_first = sym->next;
656 return sym;
659 static inline void sym_free(Sym *sym)
661 sym->next = sym_free_first;
662 sym_free_first = sym;
665 Section *new_section(TCCState *s1, const char *name, int sh_type, int sh_flags)
667 Section *sec;
669 sec = tcc_mallocz(sizeof(Section) + strlen(name));
670 strcpy(sec->name, name);
671 sec->sh_type = sh_type;
672 sec->sh_flags = sh_flags;
673 switch(sh_type) {
674 case SHT_HASH:
675 case SHT_REL:
676 case SHT_RELA:
677 case SHT_DYNSYM:
678 case SHT_SYMTAB:
679 case SHT_DYNAMIC:
680 sec->sh_addralign = 4;
681 break;
682 case SHT_STRTAB:
683 sec->sh_addralign = 1;
684 break;
685 default:
686 sec->sh_addralign = 32; /* default conservative alignment */
687 break;
690 if (sh_flags & SHF_PRIVATE) {
691 dynarray_add((void ***)&s1->priv_sections, &s1->nb_priv_sections, sec);
692 } else {
693 sec->sh_num = s1->nb_sections;
694 dynarray_add((void ***)&s1->sections, &s1->nb_sections, sec);
697 return sec;
700 static void free_section(Section *s)
702 tcc_free(s->data);
705 /* realloc section and set its content to zero */
706 static void section_realloc(Section *sec, unsigned long new_size)
708 unsigned long size;
709 unsigned char *data;
711 size = sec->data_allocated;
712 if (size == 0)
713 size = 1;
714 while (size < new_size)
715 size = size * 2;
716 data = tcc_realloc(sec->data, size);
717 if (!data)
718 error("memory full");
719 memset(data + sec->data_allocated, 0, size - sec->data_allocated);
720 sec->data = data;
721 sec->data_allocated = size;
724 /* reserve at least 'size' bytes in section 'sec' from
725 sec->data_offset. */
726 static void *section_ptr_add(Section *sec, unsigned long size)
728 unsigned long offset, offset1;
730 offset = sec->data_offset;
731 offset1 = offset + size;
732 if (offset1 > sec->data_allocated)
733 section_realloc(sec, offset1);
734 sec->data_offset = offset1;
735 return sec->data + offset;
738 /* return a reference to a section, and create it if it does not
739 exists */
740 Section *find_section(TCCState *s1, const char *name)
742 Section *sec;
743 int i;
744 for(i = 1; i < s1->nb_sections; i++) {
745 sec = s1->sections[i];
746 if (!strcmp(name, sec->name))
747 return sec;
749 /* sections are created as PROGBITS */
750 return new_section(s1, name, SHT_PROGBITS, SHF_ALLOC);
753 /* update sym->c so that it points to an external symbol in section
754 'section' with value 'value' */
755 static void put_extern_sym2(Sym *sym, Section *section,
756 unsigned long value, unsigned long size,
757 int can_add_underscore)
759 int sym_type, sym_bind, sh_num, info, other, attr;
760 ElfW(Sym) *esym;
761 const char *name;
762 char buf1[256];
764 if (section == NULL)
765 sh_num = SHN_UNDEF;
766 else if (section == SECTION_ABS)
767 sh_num = SHN_ABS;
768 else
769 sh_num = section->sh_num;
771 other = attr = 0;
773 if ((sym->type.t & VT_BTYPE) == VT_FUNC) {
774 sym_type = STT_FUNC;
775 #ifdef TCC_TARGET_PE
776 if (sym->type.ref)
777 attr = sym->type.ref->r;
778 if (FUNC_EXPORT(attr))
779 other |= 1;
780 if (FUNC_CALL(attr) == FUNC_STDCALL)
781 other |= 2;
782 #endif
783 } else {
784 sym_type = STT_OBJECT;
787 if (sym->type.t & VT_STATIC)
788 sym_bind = STB_LOCAL;
789 else
790 sym_bind = STB_GLOBAL;
792 if (!sym->c) {
793 name = get_tok_str(sym->v, NULL);
794 #ifdef CONFIG_TCC_BCHECK
795 if (tcc_state->do_bounds_check) {
796 char buf[32];
798 /* XXX: avoid doing that for statics ? */
799 /* if bound checking is activated, we change some function
800 names by adding the "__bound" prefix */
801 switch(sym->v) {
802 #if 0
803 /* XXX: we rely only on malloc hooks */
804 case TOK_malloc:
805 case TOK_free:
806 case TOK_realloc:
807 case TOK_memalign:
808 case TOK_calloc:
809 #endif
810 case TOK_memcpy:
811 case TOK_memmove:
812 case TOK_memset:
813 case TOK_strlen:
814 case TOK_strcpy:
815 case TOK_alloca:
816 strcpy(buf, "__bound_");
817 strcat(buf, name);
818 name = buf;
819 break;
822 #endif
824 #ifdef TCC_TARGET_PE
825 if ((other & 2) && can_add_underscore) {
826 sprintf(buf1, "_%s@%d", name, FUNC_ARGS(attr));
827 name = buf1;
828 } else
829 #endif
830 if (tcc_state->leading_underscore && can_add_underscore) {
831 buf1[0] = '_';
832 pstrcpy(buf1 + 1, sizeof(buf1) - 1, name);
833 name = buf1;
835 info = ELFW(ST_INFO)(sym_bind, sym_type);
836 sym->c = add_elf_sym(symtab_section, value, size, info, other, sh_num, name);
837 } else {
838 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
839 esym->st_value = value;
840 esym->st_size = size;
841 esym->st_shndx = sh_num;
842 esym->st_other |= other;
846 static void put_extern_sym(Sym *sym, Section *section,
847 unsigned long value, unsigned long size)
849 put_extern_sym2(sym, section, value, size, 1);
852 /* add a new relocation entry to symbol 'sym' in section 's' */
853 static void greloc(Section *s, Sym *sym, unsigned long offset, int type)
855 if (!sym->c)
856 put_extern_sym(sym, NULL, 0, 0);
857 /* now we can add ELF relocation info */
858 put_elf_reloc(symtab_section, s, offset, type, sym->c);
861 static void strcat_vprintf(char *buf, int buf_size, const char *fmt, va_list ap)
863 int len;
864 len = strlen(buf);
865 vsnprintf(buf + len, buf_size - len, fmt, ap);
868 static void strcat_printf(char *buf, int buf_size, const char *fmt, ...)
870 va_list ap;
871 va_start(ap, fmt);
872 strcat_vprintf(buf, buf_size, fmt, ap);
873 va_end(ap);
876 void error1(TCCState *s1, int is_warning, const char *fmt, va_list ap)
878 char buf[2048];
879 BufferedFile **f;
881 buf[0] = '\0';
882 if (file) {
883 for(f = s1->include_stack; f < s1->include_stack_ptr; f++)
884 strcat_printf(buf, sizeof(buf), "In file included from %s:%d:\n",
885 (*f)->filename, (*f)->line_num);
886 if (file->line_num > 0) {
887 strcat_printf(buf, sizeof(buf),
888 "%s:%d: ", file->filename, file->line_num);
889 } else {
890 strcat_printf(buf, sizeof(buf),
891 "%s: ", file->filename);
893 } else {
894 strcat_printf(buf, sizeof(buf),
895 "tcc: ");
897 if (is_warning)
898 strcat_printf(buf, sizeof(buf), "warning: ");
899 else
900 strcat_printf(buf, sizeof(buf), "error: ");
901 strcat_vprintf(buf, sizeof(buf), fmt, ap);
903 if (!s1->error_func) {
904 /* default case: stderr */
905 fprintf(stderr, "%s\n", buf);
906 } else {
907 s1->error_func(s1->error_opaque, buf);
909 if (!is_warning || s1->warn_error)
910 s1->nb_errors++;
913 void tcc_set_error_func(TCCState *s, void *error_opaque,
914 void (*error_func)(void *opaque, const char *msg))
916 s->error_opaque = error_opaque;
917 s->error_func = error_func;
920 /* error without aborting current compilation */
921 void error_noabort(const char *fmt, ...)
923 TCCState *s1 = tcc_state;
924 va_list ap;
926 va_start(ap, fmt);
927 error1(s1, 0, fmt, ap);
928 va_end(ap);
931 void error(const char *fmt, ...)
933 TCCState *s1 = tcc_state;
934 va_list ap;
936 va_start(ap, fmt);
937 error1(s1, 0, fmt, ap);
938 va_end(ap);
939 /* better than nothing: in some cases, we accept to handle errors */
940 if (s1->error_set_jmp_enabled) {
941 longjmp(s1->error_jmp_buf, 1);
942 } else {
943 /* XXX: eliminate this someday */
944 exit(1);
948 void expect(const char *msg)
950 error("%s expected", msg);
953 void warning(const char *fmt, ...)
955 TCCState *s1 = tcc_state;
956 va_list ap;
958 if (s1->warn_none)
959 return;
961 va_start(ap, fmt);
962 error1(s1, 1, fmt, ap);
963 va_end(ap);
966 void skip(int c)
968 if (tok != c)
969 error("'%c' expected", c);
970 next();
973 static void test_lvalue(void)
975 if (!(vtop->r & VT_LVAL))
976 expect("lvalue");
979 /* CString handling */
981 static void cstr_realloc(CString *cstr, int new_size)
983 int size;
984 void *data;
986 size = cstr->size_allocated;
987 if (size == 0)
988 size = 8; /* no need to allocate a too small first string */
989 while (size < new_size)
990 size = size * 2;
991 data = tcc_realloc(cstr->data_allocated, size);
992 if (!data)
993 error("memory full");
994 cstr->data_allocated = data;
995 cstr->size_allocated = size;
996 cstr->data = data;
999 /* add a byte */
1000 static inline void cstr_ccat(CString *cstr, int ch)
1002 int size;
1003 size = cstr->size + 1;
1004 if (size > cstr->size_allocated)
1005 cstr_realloc(cstr, size);
1006 ((unsigned char *)cstr->data)[size - 1] = ch;
1007 cstr->size = size;
1010 static void cstr_cat(CString *cstr, const char *str)
1012 int c;
1013 for(;;) {
1014 c = *str;
1015 if (c == '\0')
1016 break;
1017 cstr_ccat(cstr, c);
1018 str++;
1022 /* add a wide char */
1023 static void cstr_wccat(CString *cstr, int ch)
1025 int size;
1026 size = cstr->size + sizeof(nwchar_t);
1027 if (size > cstr->size_allocated)
1028 cstr_realloc(cstr, size);
1029 *(nwchar_t *)(((unsigned char *)cstr->data) + size - sizeof(nwchar_t)) = ch;
1030 cstr->size = size;
1033 static void cstr_new(CString *cstr)
1035 memset(cstr, 0, sizeof(CString));
1038 /* free string and reset it to NULL */
1039 static void cstr_free(CString *cstr)
1041 tcc_free(cstr->data_allocated);
1042 cstr_new(cstr);
1045 #define cstr_reset(cstr) cstr_free(cstr)
1047 /* XXX: unicode ? */
1048 static void add_char(CString *cstr, int c)
1050 if (c == '\'' || c == '\"' || c == '\\') {
1051 /* XXX: could be more precise if char or string */
1052 cstr_ccat(cstr, '\\');
1054 if (c >= 32 && c <= 126) {
1055 cstr_ccat(cstr, c);
1056 } else {
1057 cstr_ccat(cstr, '\\');
1058 if (c == '\n') {
1059 cstr_ccat(cstr, 'n');
1060 } else {
1061 cstr_ccat(cstr, '0' + ((c >> 6) & 7));
1062 cstr_ccat(cstr, '0' + ((c >> 3) & 7));
1063 cstr_ccat(cstr, '0' + (c & 7));
1068 /* push, without hashing */
1069 static Sym *sym_push2(Sym **ps, int v, int t, long c)
1071 Sym *s;
1072 s = sym_malloc();
1073 s->v = v;
1074 s->type.t = t;
1075 #ifdef _WIN64
1076 s->d = NULL;
1077 #endif
1078 s->c = c;
1079 s->next = NULL;
1080 /* add in stack */
1081 s->prev = *ps;
1082 *ps = s;
1083 return s;
1086 /* find a symbol and return its associated structure. 's' is the top
1087 of the symbol stack */
1088 static Sym *sym_find2(Sym *s, int v)
1090 while (s) {
1091 if (s->v == v)
1092 return s;
1093 s = s->prev;
1095 return NULL;
1098 /* structure lookup */
1099 static inline Sym *struct_find(int v)
1101 v -= TOK_IDENT;
1102 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1103 return NULL;
1104 return table_ident[v]->sym_struct;
1107 /* find an identifier */
1108 static inline Sym *sym_find(int v)
1110 v -= TOK_IDENT;
1111 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1112 return NULL;
1113 return table_ident[v]->sym_identifier;
1116 /* push a given symbol on the symbol stack */
1117 static Sym *sym_push(int v, CType *type, int r, int c)
1119 Sym *s, **ps;
1120 TokenSym *ts;
1122 if (local_stack)
1123 ps = &local_stack;
1124 else
1125 ps = &global_stack;
1126 s = sym_push2(ps, v, type->t, c);
1127 s->type.ref = type->ref;
1128 s->r = r;
1129 /* don't record fields or anonymous symbols */
1130 /* XXX: simplify */
1131 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
1132 /* record symbol in token array */
1133 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
1134 if (v & SYM_STRUCT)
1135 ps = &ts->sym_struct;
1136 else
1137 ps = &ts->sym_identifier;
1138 s->prev_tok = *ps;
1139 *ps = s;
1141 return s;
1144 /* push a global identifier */
1145 static Sym *global_identifier_push(int v, int t, int c)
1147 Sym *s, **ps;
1148 s = sym_push2(&global_stack, v, t, c);
1149 /* don't record anonymous symbol */
1150 if (v < SYM_FIRST_ANOM) {
1151 ps = &table_ident[v - TOK_IDENT]->sym_identifier;
1152 /* modify the top most local identifier, so that
1153 sym_identifier will point to 's' when popped */
1154 while (*ps != NULL)
1155 ps = &(*ps)->prev_tok;
1156 s->prev_tok = NULL;
1157 *ps = s;
1159 return s;
1162 /* pop symbols until top reaches 'b' */
1163 static void sym_pop(Sym **ptop, Sym *b)
1165 Sym *s, *ss, **ps;
1166 TokenSym *ts;
1167 int v;
1169 s = *ptop;
1170 while(s != b) {
1171 ss = s->prev;
1172 v = s->v;
1173 /* remove symbol in token array */
1174 /* XXX: simplify */
1175 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
1176 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
1177 if (v & SYM_STRUCT)
1178 ps = &ts->sym_struct;
1179 else
1180 ps = &ts->sym_identifier;
1181 *ps = s->prev_tok;
1183 sym_free(s);
1184 s = ss;
1186 *ptop = b;
1189 /* I/O layer */
1191 BufferedFile *tcc_open(TCCState *s1, const char *filename)
1193 int fd;
1194 BufferedFile *bf;
1196 if (strcmp(filename, "-") == 0)
1197 fd = 0, filename = "stdin";
1198 else
1199 fd = open(filename, O_RDONLY | O_BINARY);
1200 if ((s1->verbose == 2 && fd >= 0) || s1->verbose == 3)
1201 printf("%s %*s%s\n", fd < 0 ? "nf":"->",
1202 (int)(s1->include_stack_ptr - s1->include_stack), "", filename);
1203 if (fd < 0)
1204 return NULL;
1205 bf = tcc_malloc(sizeof(BufferedFile));
1206 bf->fd = fd;
1207 bf->buf_ptr = bf->buffer;
1208 bf->buf_end = bf->buffer;
1209 bf->buffer[0] = CH_EOB; /* put eob symbol */
1210 pstrcpy(bf->filename, sizeof(bf->filename), filename);
1211 #ifdef _WIN32
1212 normalize_slashes(bf->filename);
1213 #endif
1214 bf->line_num = 1;
1215 bf->ifndef_macro = 0;
1216 bf->ifdef_stack_ptr = s1->ifdef_stack_ptr;
1217 // printf("opening '%s'\n", filename);
1218 return bf;
1221 void tcc_close(BufferedFile *bf)
1223 total_lines += bf->line_num;
1224 close(bf->fd);
1225 tcc_free(bf);
1228 /* compile the C file opened in 'file'. Return non zero if errors. */
1229 static int tcc_compile(TCCState *s1)
1231 Sym *define_start;
1232 char buf[512];
1233 volatile int section_sym;
1235 #ifdef INC_DEBUG
1236 printf("%s: **** new file\n", file->filename);
1237 #endif
1238 preprocess_init(s1);
1240 cur_text_section = NULL;
1241 funcname = "";
1242 anon_sym = SYM_FIRST_ANOM;
1244 /* file info: full path + filename */
1245 section_sym = 0; /* avoid warning */
1246 if (s1->do_debug) {
1247 section_sym = put_elf_sym(symtab_section, 0, 0,
1248 ELFW(ST_INFO)(STB_LOCAL, STT_SECTION), 0,
1249 text_section->sh_num, NULL);
1250 getcwd(buf, sizeof(buf));
1251 #ifdef _WIN32
1252 normalize_slashes(buf);
1253 #endif
1254 pstrcat(buf, sizeof(buf), "/");
1255 put_stabs_r(buf, N_SO, 0, 0,
1256 text_section->data_offset, text_section, section_sym);
1257 put_stabs_r(file->filename, N_SO, 0, 0,
1258 text_section->data_offset, text_section, section_sym);
1260 /* an elf symbol of type STT_FILE must be put so that STB_LOCAL
1261 symbols can be safely used */
1262 put_elf_sym(symtab_section, 0, 0,
1263 ELFW(ST_INFO)(STB_LOCAL, STT_FILE), 0,
1264 SHN_ABS, file->filename);
1266 /* define some often used types */
1267 int_type.t = VT_INT;
1269 char_pointer_type.t = VT_BYTE;
1270 mk_pointer(&char_pointer_type);
1272 func_old_type.t = VT_FUNC;
1273 func_old_type.ref = sym_push(SYM_FIELD, &int_type, FUNC_CDECL, FUNC_OLD);
1275 #if defined(TCC_ARM_EABI) && defined(TCC_ARM_VFP)
1276 float_type.t = VT_FLOAT;
1277 double_type.t = VT_DOUBLE;
1279 func_float_type.t = VT_FUNC;
1280 func_float_type.ref = sym_push(SYM_FIELD, &float_type, FUNC_CDECL, FUNC_OLD);
1281 func_double_type.t = VT_FUNC;
1282 func_double_type.ref = sym_push(SYM_FIELD, &double_type, FUNC_CDECL, FUNC_OLD);
1283 #endif
1285 #if 0
1286 /* define 'void *alloca(unsigned int)' builtin function */
1288 Sym *s1;
1290 p = anon_sym++;
1291 sym = sym_push(p, mk_pointer(VT_VOID), FUNC_CDECL, FUNC_NEW);
1292 s1 = sym_push(SYM_FIELD, VT_UNSIGNED | VT_INT, 0, 0);
1293 s1->next = NULL;
1294 sym->next = s1;
1295 sym_push(TOK_alloca, VT_FUNC | (p << VT_STRUCT_SHIFT), VT_CONST, 0);
1297 #endif
1299 define_start = define_stack;
1300 nocode_wanted = 1;
1302 if (setjmp(s1->error_jmp_buf) == 0) {
1303 s1->nb_errors = 0;
1304 s1->error_set_jmp_enabled = 1;
1306 ch = file->buf_ptr[0];
1307 tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
1308 parse_flags = PARSE_FLAG_PREPROCESS | PARSE_FLAG_TOK_NUM;
1309 next();
1310 decl(VT_CONST);
1311 if (tok != TOK_EOF)
1312 expect("declaration");
1314 /* end of translation unit info */
1315 if (s1->do_debug) {
1316 put_stabs_r(NULL, N_SO, 0, 0,
1317 text_section->data_offset, text_section, section_sym);
1320 s1->error_set_jmp_enabled = 0;
1322 /* reset define stack, but leave -Dsymbols (may be incorrect if
1323 they are undefined) */
1324 free_defines(define_start);
1326 gen_inline_functions();
1328 sym_pop(&global_stack, NULL);
1329 sym_pop(&local_stack, NULL);
1331 return s1->nb_errors != 0 ? -1 : 0;
1334 int tcc_compile_string(TCCState *s, const char *str)
1336 BufferedFile bf1, *bf = &bf1;
1337 int ret, len;
1338 char *buf;
1340 /* init file structure */
1341 bf->fd = -1;
1342 /* XXX: avoid copying */
1343 len = strlen(str);
1344 buf = tcc_malloc(len + 1);
1345 if (!buf)
1346 return -1;
1347 memcpy(buf, str, len);
1348 buf[len] = CH_EOB;
1349 bf->buf_ptr = buf;
1350 bf->buf_end = buf + len;
1351 pstrcpy(bf->filename, sizeof(bf->filename), "<string>");
1352 bf->line_num = 1;
1353 file = bf;
1354 ret = tcc_compile(s);
1355 file = NULL;
1356 tcc_free(buf);
1358 /* currently, no need to close */
1359 return ret;
1362 /* define a preprocessor symbol. A value can also be provided with the '=' operator */
1363 void tcc_define_symbol(TCCState *s1, const char *sym, const char *value)
1365 BufferedFile bf1, *bf = &bf1;
1367 pstrcpy(bf->buffer, IO_BUF_SIZE, sym);
1368 pstrcat(bf->buffer, IO_BUF_SIZE, " ");
1369 /* default value */
1370 if (!value)
1371 value = "1";
1372 pstrcat(bf->buffer, IO_BUF_SIZE, value);
1374 /* init file structure */
1375 bf->fd = -1;
1376 bf->buf_ptr = bf->buffer;
1377 bf->buf_end = bf->buffer + strlen(bf->buffer);
1378 *bf->buf_end = CH_EOB;
1379 bf->filename[0] = '\0';
1380 bf->line_num = 1;
1381 file = bf;
1383 s1->include_stack_ptr = s1->include_stack;
1385 /* parse with define parser */
1386 ch = file->buf_ptr[0];
1387 next_nomacro();
1388 parse_define();
1389 file = NULL;
1392 /* undefine a preprocessor symbol */
1393 void tcc_undefine_symbol(TCCState *s1, const char *sym)
1395 TokenSym *ts;
1396 Sym *s;
1397 ts = tok_alloc(sym, strlen(sym));
1398 s = define_find(ts->tok);
1399 /* undefine symbol by putting an invalid name */
1400 if (s)
1401 define_undef(s);
1405 #ifdef CONFIG_TCC_BACKTRACE
1406 /* print the position in the source file of PC value 'pc' by reading
1407 the stabs debug information */
1408 static unsigned long rt_printline(unsigned long wanted_pc)
1410 Stab_Sym *sym, *sym_end;
1411 char func_name[128], last_func_name[128];
1412 unsigned long func_addr, last_pc, pc;
1413 const char *incl_files[INCLUDE_STACK_SIZE];
1414 int incl_index, len, last_line_num, i;
1415 const char *str, *p;
1417 fprintf(stderr, "0x%08lx:", wanted_pc);
1419 func_name[0] = '\0';
1420 func_addr = 0;
1421 incl_index = 0;
1422 last_func_name[0] = '\0';
1423 last_pc = 0xffffffff;
1424 last_line_num = 1;
1425 sym = (Stab_Sym *)stab_section->data + 1;
1426 sym_end = (Stab_Sym *)(stab_section->data + stab_section->data_offset);
1427 while (sym < sym_end) {
1428 switch(sym->n_type) {
1429 /* function start or end */
1430 case N_FUN:
1431 if (sym->n_strx == 0) {
1432 /* we test if between last line and end of function */
1433 pc = sym->n_value + func_addr;
1434 if (wanted_pc >= last_pc && wanted_pc < pc)
1435 goto found;
1436 func_name[0] = '\0';
1437 func_addr = 0;
1438 } else {
1439 str = stabstr_section->data + sym->n_strx;
1440 p = strchr(str, ':');
1441 if (!p) {
1442 pstrcpy(func_name, sizeof(func_name), str);
1443 } else {
1444 len = p - str;
1445 if (len > sizeof(func_name) - 1)
1446 len = sizeof(func_name) - 1;
1447 memcpy(func_name, str, len);
1448 func_name[len] = '\0';
1450 func_addr = sym->n_value;
1452 break;
1453 /* line number info */
1454 case N_SLINE:
1455 pc = sym->n_value + func_addr;
1456 if (wanted_pc >= last_pc && wanted_pc < pc)
1457 goto found;
1458 last_pc = pc;
1459 last_line_num = sym->n_desc;
1460 /* XXX: slow! */
1461 strcpy(last_func_name, func_name);
1462 break;
1463 /* include files */
1464 case N_BINCL:
1465 str = stabstr_section->data + sym->n_strx;
1466 add_incl:
1467 if (incl_index < INCLUDE_STACK_SIZE) {
1468 incl_files[incl_index++] = str;
1470 break;
1471 case N_EINCL:
1472 if (incl_index > 1)
1473 incl_index--;
1474 break;
1475 case N_SO:
1476 if (sym->n_strx == 0) {
1477 incl_index = 0; /* end of translation unit */
1478 } else {
1479 str = stabstr_section->data + sym->n_strx;
1480 /* do not add path */
1481 len = strlen(str);
1482 if (len > 0 && str[len - 1] != '/')
1483 goto add_incl;
1485 break;
1487 sym++;
1490 /* second pass: we try symtab symbols (no line number info) */
1491 incl_index = 0;
1493 ElfW(Sym) *sym, *sym_end;
1494 int type;
1496 sym_end = (ElfW(Sym) *)(symtab_section->data + symtab_section->data_offset);
1497 for(sym = (ElfW(Sym) *)symtab_section->data + 1;
1498 sym < sym_end;
1499 sym++) {
1500 type = ELFW(ST_TYPE)(sym->st_info);
1501 if (type == STT_FUNC) {
1502 if (wanted_pc >= sym->st_value &&
1503 wanted_pc < sym->st_value + sym->st_size) {
1504 pstrcpy(last_func_name, sizeof(last_func_name),
1505 strtab_section->data + sym->st_name);
1506 func_addr = sym->st_value;
1507 goto found;
1512 /* did not find any info: */
1513 fprintf(stderr, " ???\n");
1514 return 0;
1515 found:
1516 if (last_func_name[0] != '\0') {
1517 fprintf(stderr, " %s()", last_func_name);
1519 if (incl_index > 0) {
1520 fprintf(stderr, " (%s:%d",
1521 incl_files[incl_index - 1], last_line_num);
1522 for(i = incl_index - 2; i >= 0; i--)
1523 fprintf(stderr, ", included from %s", incl_files[i]);
1524 fprintf(stderr, ")");
1526 fprintf(stderr, "\n");
1527 return func_addr;
1530 #ifdef __i386__
1531 /* fix for glibc 2.1 */
1532 #ifndef REG_EIP
1533 #define REG_EIP EIP
1534 #define REG_EBP EBP
1535 #endif
1537 /* return the PC at frame level 'level'. Return non zero if not found */
1538 static int rt_get_caller_pc(unsigned long *paddr,
1539 ucontext_t *uc, int level)
1541 unsigned long fp;
1542 int i;
1544 if (level == 0) {
1545 #if defined(__FreeBSD__)
1546 *paddr = uc->uc_mcontext.mc_eip;
1547 #elif defined(__dietlibc__)
1548 *paddr = uc->uc_mcontext.eip;
1549 #else
1550 *paddr = uc->uc_mcontext.gregs[REG_EIP];
1551 #endif
1552 return 0;
1553 } else {
1554 #if defined(__FreeBSD__)
1555 fp = uc->uc_mcontext.mc_ebp;
1556 #elif defined(__dietlibc__)
1557 fp = uc->uc_mcontext.ebp;
1558 #else
1559 fp = uc->uc_mcontext.gregs[REG_EBP];
1560 #endif
1561 for(i=1;i<level;i++) {
1562 /* XXX: check address validity with program info */
1563 if (fp <= 0x1000 || fp >= 0xc0000000)
1564 return -1;
1565 fp = ((unsigned long *)fp)[0];
1567 *paddr = ((unsigned long *)fp)[1];
1568 return 0;
1571 #elif defined(__x86_64__)
1572 /* return the PC at frame level 'level'. Return non zero if not found */
1573 static int rt_get_caller_pc(unsigned long *paddr,
1574 ucontext_t *uc, int level)
1576 unsigned long fp;
1577 int i;
1579 if (level == 0) {
1580 /* XXX: only support linux */
1581 *paddr = uc->uc_mcontext.gregs[REG_RIP];
1582 return 0;
1583 } else {
1584 fp = uc->uc_mcontext.gregs[REG_RBP];
1585 for(i=1;i<level;i++) {
1586 /* XXX: check address validity with program info */
1587 if (fp <= 0x1000)
1588 return -1;
1589 fp = ((unsigned long *)fp)[0];
1591 *paddr = ((unsigned long *)fp)[1];
1592 return 0;
1595 #else
1596 #warning add arch specific rt_get_caller_pc()
1597 static int rt_get_caller_pc(unsigned long *paddr,
1598 ucontext_t *uc, int level)
1600 return -1;
1602 #endif
1604 /* emit a run time error at position 'pc' */
1605 void rt_error(ucontext_t *uc, const char *fmt, ...)
1607 va_list ap;
1608 unsigned long pc;
1609 int i;
1611 va_start(ap, fmt);
1612 fprintf(stderr, "Runtime error: ");
1613 vfprintf(stderr, fmt, ap);
1614 fprintf(stderr, "\n");
1615 for(i=0;i<num_callers;i++) {
1616 if (rt_get_caller_pc(&pc, uc, i) < 0)
1617 break;
1618 if (i == 0)
1619 fprintf(stderr, "at ");
1620 else
1621 fprintf(stderr, "by ");
1622 pc = rt_printline(pc);
1623 if (pc == rt_prog_main && pc)
1624 break;
1626 exit(255);
1627 va_end(ap);
1630 /* signal handler for fatal errors */
1631 static void sig_error(int signum, siginfo_t *siginf, void *puc)
1633 ucontext_t *uc = puc;
1635 switch(signum) {
1636 case SIGFPE:
1637 switch(siginf->si_code) {
1638 case FPE_INTDIV:
1639 case FPE_FLTDIV:
1640 rt_error(uc, "division by zero");
1641 break;
1642 default:
1643 rt_error(uc, "floating point exception");
1644 break;
1646 break;
1647 case SIGBUS:
1648 case SIGSEGV:
1649 if (rt_bound_error_msg && *rt_bound_error_msg)
1650 rt_error(uc, *rt_bound_error_msg);
1651 else
1652 rt_error(uc, "dereferencing invalid pointer");
1653 break;
1654 case SIGILL:
1655 rt_error(uc, "illegal instruction");
1656 break;
1657 case SIGABRT:
1658 rt_error(uc, "abort() called");
1659 break;
1660 default:
1661 rt_error(uc, "caught signal %d", signum);
1662 break;
1664 exit(255);
1667 #endif
1669 /* copy code into memory passed in by the caller and do all relocations
1670 (needed before using tcc_get_symbol()).
1671 returns -1 on error and required size if ptr is NULL */
1672 int tcc_relocate(TCCState *s1, void *ptr)
1674 Section *s;
1675 unsigned long offset, length;
1676 uplong mem;
1677 int i;
1679 if (0 == s1->runtime_added) {
1680 s1->runtime_added = 1;
1681 s1->nb_errors = 0;
1682 #ifdef TCC_TARGET_PE
1683 pe_output_file(s1, NULL);
1684 #else
1685 tcc_add_runtime(s1);
1686 relocate_common_syms();
1687 tcc_add_linker_symbols(s1);
1688 build_got_entries(s1);
1689 #endif
1690 if (s1->nb_errors)
1691 return -1;
1694 offset = 0, mem = (uplong)ptr;
1695 for(i = 1; i < s1->nb_sections; i++) {
1696 s = s1->sections[i];
1697 if (0 == (s->sh_flags & SHF_ALLOC))
1698 continue;
1699 length = s->data_offset;
1700 s->sh_addr = mem ? (mem + offset + 15) & ~15 : 0;
1701 offset = (offset + length + 15) & ~15;
1704 /* relocate symbols */
1705 relocate_syms(s1, 1);
1706 if (s1->nb_errors)
1707 return -1;
1709 #ifndef TCC_TARGET_PE
1710 #ifdef TCC_TARGET_X86_64
1711 s1->runtime_plt_and_got_offset = 0;
1712 s1->runtime_plt_and_got = (char *)(mem + offset);
1713 /* double the size of the buffer for got and plt entries
1714 XXX: calculate exact size for them? */
1715 offset *= 2;
1716 #endif
1717 #endif
1719 if (0 == mem)
1720 return offset + 15;
1722 /* relocate each section */
1723 for(i = 1; i < s1->nb_sections; i++) {
1724 s = s1->sections[i];
1725 if (s->reloc)
1726 relocate_section(s1, s);
1729 for(i = 1; i < s1->nb_sections; i++) {
1730 s = s1->sections[i];
1731 if (0 == (s->sh_flags & SHF_ALLOC))
1732 continue;
1733 length = s->data_offset;
1734 // printf("%-12s %08x %04x\n", s->name, s->sh_addr, length);
1735 ptr = (void*)(uplong)s->sh_addr;
1736 if (NULL == s->data || s->sh_type == SHT_NOBITS)
1737 memset(ptr, 0, length);
1738 else
1739 memcpy(ptr, s->data, length);
1740 /* mark executable sections as executable in memory */
1741 if (s->sh_flags & SHF_EXECINSTR)
1742 set_pages_executable(ptr, length);
1744 #ifndef TCC_TARGET_PE
1745 #ifdef TCC_TARGET_X86_64
1746 set_pages_executable(s1->runtime_plt_and_got,
1747 s1->runtime_plt_and_got_offset);
1748 #endif
1749 #endif
1750 return 0;
1753 /* launch the compiled program with the given arguments */
1754 int tcc_run(TCCState *s1, int argc, char **argv)
1756 int (*prog_main)(int, char **);
1757 void *ptr;
1758 int ret;
1760 ret = tcc_relocate(s1, NULL);
1761 if (ret < 0)
1762 return -1;
1763 ptr = tcc_malloc(ret);
1764 tcc_relocate(s1, ptr);
1766 prog_main = tcc_get_symbol_err(s1, "main");
1768 if (s1->do_debug) {
1769 #ifdef CONFIG_TCC_BACKTRACE
1770 struct sigaction sigact;
1771 /* install TCC signal handlers to print debug info on fatal
1772 runtime errors */
1773 sigact.sa_flags = SA_SIGINFO | SA_RESETHAND;
1774 sigact.sa_sigaction = sig_error;
1775 sigemptyset(&sigact.sa_mask);
1776 sigaction(SIGFPE, &sigact, NULL);
1777 sigaction(SIGILL, &sigact, NULL);
1778 sigaction(SIGSEGV, &sigact, NULL);
1779 sigaction(SIGBUS, &sigact, NULL);
1780 sigaction(SIGABRT, &sigact, NULL);
1781 #else
1782 error("debug mode not available");
1783 #endif
1786 #ifdef CONFIG_TCC_BCHECK
1787 if (s1->do_bounds_check) {
1788 void (*bound_init)(void);
1789 void (*bound_exit)(void);
1790 /* set error function */
1791 rt_bound_error_msg = tcc_get_symbol_err(s1, "__bound_error_msg");
1792 rt_prog_main = (unsigned long)prog_main;
1793 /* XXX: use .init section so that it also work in binary ? */
1794 bound_init = tcc_get_symbol_err(s1, "__bound_init");
1795 bound_exit = tcc_get_symbol_err(s1, "__bound_exit");
1796 bound_init();
1797 ret = (*prog_main)(argc, argv);
1798 bound_exit();
1799 } else
1800 #endif
1801 ret = (*prog_main)(argc, argv);
1802 tcc_free(ptr);
1803 return ret;
1806 void tcc_memstats(void)
1808 #ifdef MEM_DEBUG
1809 printf("memory in use: %d\n", mem_cur_size);
1810 #endif
1813 static void tcc_cleanup(void)
1815 int i, n;
1817 if (NULL == tcc_state)
1818 return;
1819 tcc_state = NULL;
1821 /* free -D defines */
1822 free_defines(NULL);
1824 /* free tokens */
1825 n = tok_ident - TOK_IDENT;
1826 for(i = 0; i < n; i++)
1827 tcc_free(table_ident[i]);
1828 tcc_free(table_ident);
1830 /* free sym_pools */
1831 dynarray_reset(&sym_pools, &nb_sym_pools);
1832 /* string buffer */
1833 cstr_free(&tokcstr);
1834 /* reset symbol stack */
1835 sym_free_first = NULL;
1836 /* cleanup from error/setjmp */
1837 macro_ptr = NULL;
1840 TCCState *tcc_new(void)
1842 TCCState *s;
1843 char buffer[100];
1844 int a,b,c;
1846 tcc_cleanup();
1848 s = tcc_mallocz(sizeof(TCCState));
1849 if (!s)
1850 return NULL;
1851 tcc_state = s;
1852 #ifdef _WIN32
1853 tcc_set_lib_path_w32(s);
1854 #else
1855 tcc_set_lib_path(s, CONFIG_TCCDIR);
1856 #endif
1857 s->output_type = TCC_OUTPUT_MEMORY;
1858 preprocess_new();
1860 /* we add dummy defines for some special macros to speed up tests
1861 and to have working defined() */
1862 define_push(TOK___LINE__, MACRO_OBJ, NULL, NULL);
1863 define_push(TOK___FILE__, MACRO_OBJ, NULL, NULL);
1864 define_push(TOK___DATE__, MACRO_OBJ, NULL, NULL);
1865 define_push(TOK___TIME__, MACRO_OBJ, NULL, NULL);
1867 /* standard defines */
1868 tcc_define_symbol(s, "__STDC__", NULL);
1869 tcc_define_symbol(s, "__STDC_VERSION__", "199901L");
1870 #if defined(TCC_TARGET_I386)
1871 tcc_define_symbol(s, "__i386__", NULL);
1872 #endif
1873 #if defined(TCC_TARGET_X86_64)
1874 tcc_define_symbol(s, "__x86_64__", NULL);
1875 #endif
1876 #if defined(TCC_TARGET_ARM)
1877 tcc_define_symbol(s, "__ARM_ARCH_4__", NULL);
1878 tcc_define_symbol(s, "__arm_elf__", NULL);
1879 tcc_define_symbol(s, "__arm_elf", NULL);
1880 tcc_define_symbol(s, "arm_elf", NULL);
1881 tcc_define_symbol(s, "__arm__", NULL);
1882 tcc_define_symbol(s, "__arm", NULL);
1883 tcc_define_symbol(s, "arm", NULL);
1884 tcc_define_symbol(s, "__APCS_32__", NULL);
1885 #endif
1886 #ifdef TCC_TARGET_PE
1887 tcc_define_symbol(s, "_WIN32", NULL);
1888 #ifdef TCC_TARGET_X86_64
1889 tcc_define_symbol(s, "_WIN64", NULL);
1890 #endif
1891 #else
1892 tcc_define_symbol(s, "__unix__", NULL);
1893 tcc_define_symbol(s, "__unix", NULL);
1894 #if defined(__linux)
1895 tcc_define_symbol(s, "__linux__", NULL);
1896 tcc_define_symbol(s, "__linux", NULL);
1897 #endif
1898 #endif
1899 /* tiny C specific defines */
1900 sscanf(TCC_VERSION, "%d.%d.%d", &a, &b, &c);
1901 sprintf(buffer, "%d", a*10000 + b*100 + c);
1902 tcc_define_symbol(s, "__TINYC__", buffer);
1904 /* tiny C & gcc defines */
1905 tcc_define_symbol(s, "__SIZE_TYPE__", "unsigned long");
1906 tcc_define_symbol(s, "__PTRDIFF_TYPE__", "long");
1907 #ifdef TCC_TARGET_PE
1908 tcc_define_symbol(s, "__WCHAR_TYPE__", "unsigned short");
1909 #else
1910 tcc_define_symbol(s, "__WCHAR_TYPE__", "int");
1911 #endif
1913 #ifndef TCC_TARGET_PE
1914 /* default library paths */
1915 tcc_add_library_path(s, CONFIG_SYSROOT "/usr/local/lib");
1916 tcc_add_library_path(s, CONFIG_SYSROOT "/usr/lib");
1917 tcc_add_library_path(s, CONFIG_SYSROOT "/lib");
1918 #endif
1920 /* no section zero */
1921 dynarray_add((void ***)&s->sections, &s->nb_sections, NULL);
1923 /* create standard sections */
1924 text_section = new_section(s, ".text", SHT_PROGBITS, SHF_ALLOC | SHF_EXECINSTR);
1925 data_section = new_section(s, ".data", SHT_PROGBITS, SHF_ALLOC | SHF_WRITE);
1926 bss_section = new_section(s, ".bss", SHT_NOBITS, SHF_ALLOC | SHF_WRITE);
1928 /* symbols are always generated for linking stage */
1929 symtab_section = new_symtab(s, ".symtab", SHT_SYMTAB, 0,
1930 ".strtab",
1931 ".hashtab", SHF_PRIVATE);
1932 strtab_section = symtab_section->link;
1934 /* private symbol table for dynamic symbols */
1935 s->dynsymtab_section = new_symtab(s, ".dynsymtab", SHT_SYMTAB, SHF_PRIVATE,
1936 ".dynstrtab",
1937 ".dynhashtab", SHF_PRIVATE);
1938 s->alacarte_link = 1;
1940 #ifdef CHAR_IS_UNSIGNED
1941 s->char_is_unsigned = 1;
1942 #endif
1943 #if defined(TCC_TARGET_PE) && 0
1944 /* XXX: currently the PE linker is not ready to support that */
1945 s->leading_underscore = 1;
1946 #endif
1948 if (s->section_align == 0)
1949 s->section_align = ELF_PAGE_SIZE;
1951 #ifdef TCC_TARGET_I386
1952 s->seg_size = 32;
1953 #endif
1954 return s;
1957 void tcc_delete(TCCState *s1)
1959 int i;
1961 tcc_cleanup();
1963 /* free all sections */
1964 for(i = 1; i < s1->nb_sections; i++)
1965 free_section(s1->sections[i]);
1966 dynarray_reset(&s1->sections, &s1->nb_sections);
1968 for(i = 0; i < s1->nb_priv_sections; i++)
1969 free_section(s1->priv_sections[i]);
1970 dynarray_reset(&s1->priv_sections, &s1->nb_priv_sections);
1972 /* free any loaded DLLs */
1973 for ( i = 0; i < s1->nb_loaded_dlls; i++) {
1974 DLLReference *ref = s1->loaded_dlls[i];
1975 if ( ref->handle )
1976 dlclose(ref->handle);
1979 /* free loaded dlls array */
1980 dynarray_reset(&s1->loaded_dlls, &s1->nb_loaded_dlls);
1982 /* free library paths */
1983 dynarray_reset(&s1->library_paths, &s1->nb_library_paths);
1985 /* free include paths */
1986 dynarray_reset(&s1->cached_includes, &s1->nb_cached_includes);
1987 dynarray_reset(&s1->include_paths, &s1->nb_include_paths);
1988 dynarray_reset(&s1->sysinclude_paths, &s1->nb_sysinclude_paths);
1990 tcc_free(s1->tcc_lib_path);
1991 tcc_free(s1);
1994 int tcc_add_include_path(TCCState *s1, const char *pathname)
1996 char *pathname1;
1998 pathname1 = tcc_strdup(pathname);
1999 dynarray_add((void ***)&s1->include_paths, &s1->nb_include_paths, pathname1);
2000 return 0;
2003 int tcc_add_sysinclude_path(TCCState *s1, const char *pathname)
2005 char *pathname1;
2007 pathname1 = tcc_strdup(pathname);
2008 dynarray_add((void ***)&s1->sysinclude_paths, &s1->nb_sysinclude_paths, pathname1);
2009 return 0;
2012 static int tcc_add_file_internal(TCCState *s1, const char *filename, int flags)
2014 const char *ext;
2015 ElfW(Ehdr) ehdr;
2016 int fd, ret, size;
2017 BufferedFile *saved_file;
2019 ret = -1;
2021 /* find source file type with extension */
2022 ext = tcc_fileextension(filename);
2023 if (ext[0])
2024 ext++;
2026 /* open the file */
2027 saved_file = file;
2028 file = tcc_open(s1, filename);
2029 if (!file) {
2030 if (flags & AFF_PRINT_ERROR)
2031 error_noabort("file '%s' not found", filename);
2032 goto the_end;
2035 if (flags & AFF_PREPROCESS) {
2036 ret = tcc_preprocess(s1);
2037 goto the_end;
2040 if (!ext[0] || !PATHCMP(ext, "c")) {
2041 /* C file assumed */
2042 ret = tcc_compile(s1);
2043 goto the_end;
2046 #ifdef CONFIG_TCC_ASM
2047 if (!strcmp(ext, "S")) {
2048 /* preprocessed assembler */
2049 ret = tcc_assemble(s1, 1);
2050 goto the_end;
2053 if (!strcmp(ext, "s")) {
2054 /* non preprocessed assembler */
2055 ret = tcc_assemble(s1, 0);
2056 goto the_end;
2058 #endif
2060 fd = file->fd;
2061 /* assume executable format: auto guess file type */
2062 size = read(fd, &ehdr, sizeof(ehdr));
2063 lseek(fd, 0, SEEK_SET);
2064 if (size <= 0) {
2065 error_noabort("could not read header");
2066 goto the_end;
2069 if (size == sizeof(ehdr) &&
2070 ehdr.e_ident[0] == ELFMAG0 &&
2071 ehdr.e_ident[1] == ELFMAG1 &&
2072 ehdr.e_ident[2] == ELFMAG2 &&
2073 ehdr.e_ident[3] == ELFMAG3) {
2075 /* do not display line number if error */
2076 file->line_num = 0;
2077 if (ehdr.e_type == ET_REL) {
2078 ret = tcc_load_object_file(s1, fd, 0);
2079 goto the_end;
2082 #ifndef TCC_TARGET_PE
2083 if (ehdr.e_type == ET_DYN) {
2084 if (s1->output_type == TCC_OUTPUT_MEMORY) {
2085 void *h;
2086 h = dlopen(filename, RTLD_GLOBAL | RTLD_LAZY);
2087 if (h)
2088 ret = 0;
2089 } else {
2090 ret = tcc_load_dll(s1, fd, filename,
2091 (flags & AFF_REFERENCED_DLL) != 0);
2093 goto the_end;
2095 #endif
2096 error_noabort("unrecognized ELF file");
2097 goto the_end;
2100 if (memcmp((char *)&ehdr, ARMAG, 8) == 0) {
2101 file->line_num = 0; /* do not display line number if error */
2102 ret = tcc_load_archive(s1, fd);
2103 goto the_end;
2106 #ifdef TCC_TARGET_COFF
2107 if (*(uint16_t *)(&ehdr) == COFF_C67_MAGIC) {
2108 ret = tcc_load_coff(s1, fd);
2109 goto the_end;
2111 #endif
2113 #ifdef TCC_TARGET_PE
2114 ret = pe_load_file(s1, filename, fd);
2115 #else
2116 /* as GNU ld, consider it is an ld script if not recognized */
2117 ret = tcc_load_ldscript(s1);
2118 #endif
2119 if (ret < 0)
2120 error_noabort("unrecognized file type");
2122 the_end:
2123 if (file)
2124 tcc_close(file);
2125 file = saved_file;
2126 return ret;
2129 int tcc_add_file(TCCState *s, const char *filename)
2131 if (s->output_type == TCC_OUTPUT_PREPROCESS)
2132 return tcc_add_file_internal(s, filename, AFF_PRINT_ERROR | AFF_PREPROCESS);
2133 else
2134 return tcc_add_file_internal(s, filename, AFF_PRINT_ERROR);
2137 int tcc_add_library_path(TCCState *s, const char *pathname)
2139 char *pathname1;
2141 pathname1 = tcc_strdup(pathname);
2142 dynarray_add((void ***)&s->library_paths, &s->nb_library_paths, pathname1);
2143 return 0;
2146 /* find and load a dll. Return non zero if not found */
2147 /* XXX: add '-rpath' option support ? */
2148 static int tcc_add_dll(TCCState *s, const char *filename, int flags)
2150 char buf[1024];
2151 int i;
2153 for(i = 0; i < s->nb_library_paths; i++) {
2154 snprintf(buf, sizeof(buf), "%s/%s",
2155 s->library_paths[i], filename);
2156 if (tcc_add_file_internal(s, buf, flags) == 0)
2157 return 0;
2159 return -1;
2162 /* the library name is the same as the argument of the '-l' option */
2163 int tcc_add_library(TCCState *s, const char *libraryname)
2165 char buf[1024];
2166 int i;
2168 /* first we look for the dynamic library if not static linking */
2169 if (!s->static_link) {
2170 #ifdef TCC_TARGET_PE
2171 if (pe_add_dll(s, libraryname) == 0)
2172 return 0;
2173 #else
2174 snprintf(buf, sizeof(buf), "lib%s.so", libraryname);
2175 if (tcc_add_dll(s, buf, 0) == 0)
2176 return 0;
2177 #endif
2179 /* then we look for the static library */
2180 for(i = 0; i < s->nb_library_paths; i++) {
2181 snprintf(buf, sizeof(buf), "%s/lib%s.a",
2182 s->library_paths[i], libraryname);
2183 if (tcc_add_file_internal(s, buf, 0) == 0)
2184 return 0;
2186 return -1;
2189 int tcc_add_symbol(TCCState *s, const char *name, void *val)
2191 add_elf_sym(symtab_section, (uplong)val, 0,
2192 ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE), 0,
2193 SHN_ABS, name);
2194 return 0;
2197 int tcc_set_output_type(TCCState *s, int output_type)
2199 char buf[1024];
2201 s->output_type = output_type;
2203 if (!s->nostdinc) {
2204 /* default include paths */
2205 /* XXX: reverse order needed if -isystem support */
2206 #ifndef TCC_TARGET_PE
2207 tcc_add_sysinclude_path(s, CONFIG_SYSROOT "/usr/local/include");
2208 tcc_add_sysinclude_path(s, CONFIG_SYSROOT "/usr/include");
2209 #endif
2210 snprintf(buf, sizeof(buf), "%s/include", s->tcc_lib_path);
2211 tcc_add_sysinclude_path(s, buf);
2212 #ifdef TCC_TARGET_PE
2213 snprintf(buf, sizeof(buf), "%s/include/winapi", s->tcc_lib_path);
2214 tcc_add_sysinclude_path(s, buf);
2215 #endif
2218 /* if bound checking, then add corresponding sections */
2219 #ifdef CONFIG_TCC_BCHECK
2220 if (s->do_bounds_check) {
2221 /* define symbol */
2222 tcc_define_symbol(s, "__BOUNDS_CHECKING_ON", NULL);
2223 /* create bounds sections */
2224 bounds_section = new_section(s, ".bounds",
2225 SHT_PROGBITS, SHF_ALLOC);
2226 lbounds_section = new_section(s, ".lbounds",
2227 SHT_PROGBITS, SHF_ALLOC);
2229 #endif
2231 if (s->char_is_unsigned) {
2232 tcc_define_symbol(s, "__CHAR_UNSIGNED__", NULL);
2235 /* add debug sections */
2236 if (s->do_debug) {
2237 /* stab symbols */
2238 stab_section = new_section(s, ".stab", SHT_PROGBITS, 0);
2239 stab_section->sh_entsize = sizeof(Stab_Sym);
2240 stabstr_section = new_section(s, ".stabstr", SHT_STRTAB, 0);
2241 put_elf_str(stabstr_section, "");
2242 stab_section->link = stabstr_section;
2243 /* put first entry */
2244 put_stabs("", 0, 0, 0, 0);
2247 /* add libc crt1/crti objects */
2248 #ifndef TCC_TARGET_PE
2249 if ((output_type == TCC_OUTPUT_EXE || output_type == TCC_OUTPUT_DLL) &&
2250 !s->nostdlib) {
2251 if (output_type != TCC_OUTPUT_DLL)
2252 tcc_add_file(s, CONFIG_TCC_CRT_PREFIX "/crt1.o");
2253 tcc_add_file(s, CONFIG_TCC_CRT_PREFIX "/crti.o");
2255 #endif
2257 #ifdef TCC_TARGET_PE
2258 snprintf(buf, sizeof(buf), "%s/lib", s->tcc_lib_path);
2259 tcc_add_library_path(s, buf);
2260 #ifdef _WIN32
2261 if (GetSystemDirectory(buf, sizeof buf))
2262 tcc_add_library_path(s, buf);
2263 #endif
2264 #endif
2266 return 0;
2269 #define WD_ALL 0x0001 /* warning is activated when using -Wall */
2270 #define FD_INVERT 0x0002 /* invert value before storing */
2272 typedef struct FlagDef {
2273 uint16_t offset;
2274 uint16_t flags;
2275 const char *name;
2276 } FlagDef;
2278 static const FlagDef warning_defs[] = {
2279 { offsetof(TCCState, warn_unsupported), 0, "unsupported" },
2280 { offsetof(TCCState, warn_write_strings), 0, "write-strings" },
2281 { offsetof(TCCState, warn_error), 0, "error" },
2282 { offsetof(TCCState, warn_implicit_function_declaration), WD_ALL,
2283 "implicit-function-declaration" },
2286 static int set_flag(TCCState *s, const FlagDef *flags, int nb_flags,
2287 const char *name, int value)
2289 int i;
2290 const FlagDef *p;
2291 const char *r;
2293 r = name;
2294 if (r[0] == 'n' && r[1] == 'o' && r[2] == '-') {
2295 r += 3;
2296 value = !value;
2298 for(i = 0, p = flags; i < nb_flags; i++, p++) {
2299 if (!strcmp(r, p->name))
2300 goto found;
2302 return -1;
2303 found:
2304 if (p->flags & FD_INVERT)
2305 value = !value;
2306 *(int *)((uint8_t *)s + p->offset) = value;
2307 return 0;
2311 /* set/reset a warning */
2312 int tcc_set_warning(TCCState *s, const char *warning_name, int value)
2314 int i;
2315 const FlagDef *p;
2317 if (!strcmp(warning_name, "all")) {
2318 for(i = 0, p = warning_defs; i < countof(warning_defs); i++, p++) {
2319 if (p->flags & WD_ALL)
2320 *(int *)((uint8_t *)s + p->offset) = 1;
2322 return 0;
2323 } else {
2324 return set_flag(s, warning_defs, countof(warning_defs),
2325 warning_name, value);
2329 static const FlagDef flag_defs[] = {
2330 { offsetof(TCCState, char_is_unsigned), 0, "unsigned-char" },
2331 { offsetof(TCCState, char_is_unsigned), FD_INVERT, "signed-char" },
2332 { offsetof(TCCState, nocommon), FD_INVERT, "common" },
2333 { offsetof(TCCState, leading_underscore), 0, "leading-underscore" },
2336 /* set/reset a flag */
2337 int tcc_set_flag(TCCState *s, const char *flag_name, int value)
2339 return set_flag(s, flag_defs, countof(flag_defs),
2340 flag_name, value);
2343 /* set CONFIG_TCCDIR at runtime */
2344 void tcc_set_lib_path(TCCState *s, const char *path)
2346 tcc_free(s->tcc_lib_path);
2347 s->tcc_lib_path = tcc_strdup(path);
2350 void tcc_print_stats(TCCState *s, int64_t total_time)
2352 double tt;
2353 tt = (double)total_time / 1000000.0;
2354 if (tt < 0.001)
2355 tt = 0.001;
2356 if (total_bytes < 1)
2357 total_bytes = 1;
2358 printf("%d idents, %d lines, %d bytes, %0.3f s, %d lines/s, %0.1f MB/s\n",
2359 tok_ident - TOK_IDENT, total_lines, total_bytes,
2360 tt, (int)(total_lines / tt),
2361 total_bytes / tt / 1000000.0);