added 16-bit x86 assembly support
[tinycc.git] / libtcc.c
blob513de90dee8120830c9a7f18e82ea584613608c0
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
327 #ifdef TCC_TARGET_I386
328 #include "i386-asm.c"
329 #endif
330 #include "tccasm.c"
331 #else
332 static void asm_instr(void)
334 error("inline asm() not supported");
336 static void asm_global_instr(void)
338 error("inline asm() not supported");
340 #endif
342 #include "tccelf.c"
344 #ifdef TCC_TARGET_COFF
345 #include "tcccoff.c"
346 #endif
348 #ifdef TCC_TARGET_PE
349 #include "tccpe.c"
350 #endif
352 /********************************************************/
353 #ifdef _WIN32
354 char *normalize_slashes(char *path)
356 char *p;
357 for (p = path; *p; ++p)
358 if (*p == '\\')
359 *p = '/';
360 return path;
363 HMODULE tcc_module;
365 /* on win32, we suppose the lib and includes are at the location of 'tcc.exe' */
366 void tcc_set_lib_path_w32(TCCState *s)
368 char path[1024], *p;
369 GetModuleFileNameA(tcc_module, path, sizeof path);
370 p = tcc_basename(normalize_slashes(strlwr(path)));
371 if (p - 5 > path && 0 == strncmp(p - 5, "/bin/", 5))
372 p -= 5;
373 else if (p > path)
374 p--;
375 *p = 0;
376 tcc_set_lib_path(s, path);
379 #ifdef LIBTCC_AS_DLL
380 BOOL WINAPI DllMain (HANDLE hDll, DWORD dwReason, LPVOID lpReserved)
382 if (DLL_PROCESS_ATTACH == dwReason)
383 tcc_module = hDll;
384 return TRUE;
386 #endif
387 #endif
389 /********************************************************/
390 #ifdef CONFIG_TCC_STATIC
392 #define RTLD_LAZY 0x001
393 #define RTLD_NOW 0x002
394 #define RTLD_GLOBAL 0x100
395 #define RTLD_DEFAULT NULL
397 /* dummy function for profiling */
398 void *dlopen(const char *filename, int flag)
400 return NULL;
403 void dlclose(void *p)
407 const char *dlerror(void)
409 return "error";
412 typedef struct TCCSyms {
413 char *str;
414 void *ptr;
415 } TCCSyms;
417 #define TCCSYM(a) { #a, &a, },
419 /* add the symbol you want here if no dynamic linking is done */
420 static TCCSyms tcc_syms[] = {
421 #if !defined(CONFIG_TCCBOOT)
422 TCCSYM(printf)
423 TCCSYM(fprintf)
424 TCCSYM(fopen)
425 TCCSYM(fclose)
426 #endif
427 { NULL, NULL },
430 void *resolve_sym(TCCState *s1, const char *symbol)
432 TCCSyms *p;
433 p = tcc_syms;
434 while (p->str != NULL) {
435 if (!strcmp(p->str, symbol))
436 return p->ptr;
437 p++;
439 return NULL;
442 #elif defined(_WIN32)
443 #define dlclose FreeLibrary
445 #else
446 #include <dlfcn.h>
448 void *resolve_sym(TCCState *s1, const char *sym)
450 return dlsym(RTLD_DEFAULT, sym);
453 #endif
455 /********************************************************/
457 /* we use our own 'finite' function to avoid potential problems with
458 non standard math libs */
459 /* XXX: endianness dependent */
460 int ieee_finite(double d)
462 int *p = (int *)&d;
463 return ((unsigned)((p[1] | 0x800fffff) + 1)) >> 31;
466 /* copy a string and truncate it. */
467 char *pstrcpy(char *buf, int buf_size, const char *s)
469 char *q, *q_end;
470 int c;
472 if (buf_size > 0) {
473 q = buf;
474 q_end = buf + buf_size - 1;
475 while (q < q_end) {
476 c = *s++;
477 if (c == '\0')
478 break;
479 *q++ = c;
481 *q = '\0';
483 return buf;
486 /* strcat and truncate. */
487 char *pstrcat(char *buf, int buf_size, const char *s)
489 int len;
490 len = strlen(buf);
491 if (len < buf_size)
492 pstrcpy(buf + len, buf_size - len, s);
493 return buf;
496 /* extract the basename of a file */
497 char *tcc_basename(const char *name)
499 char *p = strchr(name, 0);
500 while (p > name && !IS_PATHSEP(p[-1]))
501 --p;
502 return p;
505 char *tcc_fileextension (const char *name)
507 char *b = tcc_basename(name);
508 char *e = strrchr(b, '.');
509 return e ? e : strchr(b, 0);
512 void set_pages_executable(void *ptr, unsigned long length)
514 #ifdef _WIN32
515 unsigned long old_protect;
516 VirtualProtect(ptr, length, PAGE_EXECUTE_READWRITE, &old_protect);
517 #else
518 unsigned long start, end;
519 start = (unsigned long)ptr & ~(PAGESIZE - 1);
520 end = (unsigned long)ptr + length;
521 end = (end + PAGESIZE - 1) & ~(PAGESIZE - 1);
522 mprotect((void *)start, end - start, PROT_READ | PROT_WRITE | PROT_EXEC);
523 #endif
526 /* memory management */
527 #ifdef MEM_DEBUG
528 int mem_cur_size;
529 int mem_max_size;
530 unsigned malloc_usable_size(void*);
531 #endif
533 void tcc_free(void *ptr)
535 #ifdef MEM_DEBUG
536 mem_cur_size -= malloc_usable_size(ptr);
537 #endif
538 free(ptr);
541 void *tcc_malloc(unsigned long size)
543 void *ptr;
544 ptr = malloc(size);
545 if (!ptr && size)
546 error("memory full");
547 #ifdef MEM_DEBUG
548 mem_cur_size += malloc_usable_size(ptr);
549 if (mem_cur_size > mem_max_size)
550 mem_max_size = mem_cur_size;
551 #endif
552 return ptr;
555 void *tcc_mallocz(unsigned long size)
557 void *ptr;
558 ptr = tcc_malloc(size);
559 memset(ptr, 0, size);
560 return ptr;
563 void *tcc_realloc(void *ptr, unsigned long size)
565 void *ptr1;
566 #ifdef MEM_DEBUG
567 mem_cur_size -= malloc_usable_size(ptr);
568 #endif
569 ptr1 = realloc(ptr, size);
570 #ifdef MEM_DEBUG
571 /* NOTE: count not correct if alloc error, but not critical */
572 mem_cur_size += malloc_usable_size(ptr1);
573 if (mem_cur_size > mem_max_size)
574 mem_max_size = mem_cur_size;
575 #endif
576 return ptr1;
579 char *tcc_strdup(const char *str)
581 char *ptr;
582 ptr = tcc_malloc(strlen(str) + 1);
583 strcpy(ptr, str);
584 return ptr;
587 #define free(p) use_tcc_free(p)
588 #define malloc(s) use_tcc_malloc(s)
589 #define realloc(p, s) use_tcc_realloc(p, s)
591 void dynarray_add(void ***ptab, int *nb_ptr, void *data)
593 int nb, nb_alloc;
594 void **pp;
596 nb = *nb_ptr;
597 pp = *ptab;
598 /* every power of two we double array size */
599 if ((nb & (nb - 1)) == 0) {
600 if (!nb)
601 nb_alloc = 1;
602 else
603 nb_alloc = nb * 2;
604 pp = tcc_realloc(pp, nb_alloc * sizeof(void *));
605 if (!pp)
606 error("memory full");
607 *ptab = pp;
609 pp[nb++] = data;
610 *nb_ptr = nb;
613 void dynarray_reset(void *pp, int *n)
615 void **p;
616 for (p = *(void***)pp; *n; ++p, --*n)
617 if (*p)
618 tcc_free(*p);
619 tcc_free(*(void**)pp);
620 *(void**)pp = NULL;
623 /* symbol allocator */
624 static Sym *__sym_malloc(void)
626 Sym *sym_pool, *sym, *last_sym;
627 int i;
629 sym_pool = tcc_malloc(SYM_POOL_NB * sizeof(Sym));
630 dynarray_add(&sym_pools, &nb_sym_pools, sym_pool);
632 last_sym = sym_free_first;
633 sym = sym_pool;
634 for(i = 0; i < SYM_POOL_NB; i++) {
635 sym->next = last_sym;
636 last_sym = sym;
637 sym++;
639 sym_free_first = last_sym;
640 return last_sym;
643 static inline Sym *sym_malloc(void)
645 Sym *sym;
646 sym = sym_free_first;
647 if (!sym)
648 sym = __sym_malloc();
649 sym_free_first = sym->next;
650 return sym;
653 static inline void sym_free(Sym *sym)
655 sym->next = sym_free_first;
656 sym_free_first = sym;
659 Section *new_section(TCCState *s1, const char *name, int sh_type, int sh_flags)
661 Section *sec;
663 sec = tcc_mallocz(sizeof(Section) + strlen(name));
664 strcpy(sec->name, name);
665 sec->sh_type = sh_type;
666 sec->sh_flags = sh_flags;
667 switch(sh_type) {
668 case SHT_HASH:
669 case SHT_REL:
670 case SHT_RELA:
671 case SHT_DYNSYM:
672 case SHT_SYMTAB:
673 case SHT_DYNAMIC:
674 sec->sh_addralign = 4;
675 break;
676 case SHT_STRTAB:
677 sec->sh_addralign = 1;
678 break;
679 default:
680 sec->sh_addralign = 32; /* default conservative alignment */
681 break;
684 if (sh_flags & SHF_PRIVATE) {
685 dynarray_add((void ***)&s1->priv_sections, &s1->nb_priv_sections, sec);
686 } else {
687 sec->sh_num = s1->nb_sections;
688 dynarray_add((void ***)&s1->sections, &s1->nb_sections, sec);
691 return sec;
694 static void free_section(Section *s)
696 tcc_free(s->data);
699 /* realloc section and set its content to zero */
700 static void section_realloc(Section *sec, unsigned long new_size)
702 unsigned long size;
703 unsigned char *data;
705 size = sec->data_allocated;
706 if (size == 0)
707 size = 1;
708 while (size < new_size)
709 size = size * 2;
710 data = tcc_realloc(sec->data, size);
711 if (!data)
712 error("memory full");
713 memset(data + sec->data_allocated, 0, size - sec->data_allocated);
714 sec->data = data;
715 sec->data_allocated = size;
718 /* reserve at least 'size' bytes in section 'sec' from
719 sec->data_offset. */
720 static void *section_ptr_add(Section *sec, unsigned long size)
722 unsigned long offset, offset1;
724 offset = sec->data_offset;
725 offset1 = offset + size;
726 if (offset1 > sec->data_allocated)
727 section_realloc(sec, offset1);
728 sec->data_offset = offset1;
729 return sec->data + offset;
732 /* return a reference to a section, and create it if it does not
733 exists */
734 Section *find_section(TCCState *s1, const char *name)
736 Section *sec;
737 int i;
738 for(i = 1; i < s1->nb_sections; i++) {
739 sec = s1->sections[i];
740 if (!strcmp(name, sec->name))
741 return sec;
743 /* sections are created as PROGBITS */
744 return new_section(s1, name, SHT_PROGBITS, SHF_ALLOC);
747 /* update sym->c so that it points to an external symbol in section
748 'section' with value 'value' */
749 static void put_extern_sym2(Sym *sym, Section *section,
750 unsigned long value, unsigned long size,
751 int can_add_underscore)
753 int sym_type, sym_bind, sh_num, info, other, attr;
754 ElfW(Sym) *esym;
755 const char *name;
756 char buf1[256];
758 if (section == NULL)
759 sh_num = SHN_UNDEF;
760 else if (section == SECTION_ABS)
761 sh_num = SHN_ABS;
762 else
763 sh_num = section->sh_num;
765 other = attr = 0;
767 if ((sym->type.t & VT_BTYPE) == VT_FUNC) {
768 sym_type = STT_FUNC;
769 #ifdef TCC_TARGET_PE
770 if (sym->type.ref)
771 attr = sym->type.ref->r;
772 if (FUNC_EXPORT(attr))
773 other |= 1;
774 if (FUNC_CALL(attr) == FUNC_STDCALL)
775 other |= 2;
776 #endif
777 } else {
778 sym_type = STT_OBJECT;
781 if (sym->type.t & VT_STATIC)
782 sym_bind = STB_LOCAL;
783 else
784 sym_bind = STB_GLOBAL;
786 if (!sym->c) {
787 name = get_tok_str(sym->v, NULL);
788 #ifdef CONFIG_TCC_BCHECK
789 if (tcc_state->do_bounds_check) {
790 char buf[32];
792 /* XXX: avoid doing that for statics ? */
793 /* if bound checking is activated, we change some function
794 names by adding the "__bound" prefix */
795 switch(sym->v) {
796 #if 0
797 /* XXX: we rely only on malloc hooks */
798 case TOK_malloc:
799 case TOK_free:
800 case TOK_realloc:
801 case TOK_memalign:
802 case TOK_calloc:
803 #endif
804 case TOK_memcpy:
805 case TOK_memmove:
806 case TOK_memset:
807 case TOK_strlen:
808 case TOK_strcpy:
809 case TOK_alloca:
810 strcpy(buf, "__bound_");
811 strcat(buf, name);
812 name = buf;
813 break;
816 #endif
818 #ifdef TCC_TARGET_PE
819 if ((other & 2) && can_add_underscore) {
820 sprintf(buf1, "_%s@%d", name, FUNC_ARGS(attr));
821 name = buf1;
822 } else
823 #endif
824 if (tcc_state->leading_underscore && can_add_underscore) {
825 buf1[0] = '_';
826 pstrcpy(buf1 + 1, sizeof(buf1) - 1, name);
827 name = buf1;
829 info = ELFW(ST_INFO)(sym_bind, sym_type);
830 sym->c = add_elf_sym(symtab_section, value, size, info, other, sh_num, name);
831 } else {
832 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
833 esym->st_value = value;
834 esym->st_size = size;
835 esym->st_shndx = sh_num;
836 esym->st_other |= other;
840 static void put_extern_sym(Sym *sym, Section *section,
841 unsigned long value, unsigned long size)
843 put_extern_sym2(sym, section, value, size, 1);
846 /* add a new relocation entry to symbol 'sym' in section 's' */
847 static void greloc(Section *s, Sym *sym, unsigned long offset, int type)
849 if (!sym->c)
850 put_extern_sym(sym, NULL, 0, 0);
851 /* now we can add ELF relocation info */
852 put_elf_reloc(symtab_section, s, offset, type, sym->c);
855 static void strcat_vprintf(char *buf, int buf_size, const char *fmt, va_list ap)
857 int len;
858 len = strlen(buf);
859 vsnprintf(buf + len, buf_size - len, fmt, ap);
862 static void strcat_printf(char *buf, int buf_size, const char *fmt, ...)
864 va_list ap;
865 va_start(ap, fmt);
866 strcat_vprintf(buf, buf_size, fmt, ap);
867 va_end(ap);
870 void error1(TCCState *s1, int is_warning, const char *fmt, va_list ap)
872 char buf[2048];
873 BufferedFile **f;
875 buf[0] = '\0';
876 if (file) {
877 for(f = s1->include_stack; f < s1->include_stack_ptr; f++)
878 strcat_printf(buf, sizeof(buf), "In file included from %s:%d:\n",
879 (*f)->filename, (*f)->line_num);
880 if (file->line_num > 0) {
881 strcat_printf(buf, sizeof(buf),
882 "%s:%d: ", file->filename, file->line_num);
883 } else {
884 strcat_printf(buf, sizeof(buf),
885 "%s: ", file->filename);
887 } else {
888 strcat_printf(buf, sizeof(buf),
889 "tcc: ");
891 if (is_warning)
892 strcat_printf(buf, sizeof(buf), "warning: ");
893 else
894 strcat_printf(buf, sizeof(buf), "error: ");
895 strcat_vprintf(buf, sizeof(buf), fmt, ap);
897 if (!s1->error_func) {
898 /* default case: stderr */
899 fprintf(stderr, "%s\n", buf);
900 } else {
901 s1->error_func(s1->error_opaque, buf);
903 if (!is_warning || s1->warn_error)
904 s1->nb_errors++;
907 void tcc_set_error_func(TCCState *s, void *error_opaque,
908 void (*error_func)(void *opaque, const char *msg))
910 s->error_opaque = error_opaque;
911 s->error_func = error_func;
914 /* error without aborting current compilation */
915 void error_noabort(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);
925 void error(const char *fmt, ...)
927 TCCState *s1 = tcc_state;
928 va_list ap;
930 va_start(ap, fmt);
931 error1(s1, 0, fmt, ap);
932 va_end(ap);
933 /* better than nothing: in some cases, we accept to handle errors */
934 if (s1->error_set_jmp_enabled) {
935 longjmp(s1->error_jmp_buf, 1);
936 } else {
937 /* XXX: eliminate this someday */
938 exit(1);
942 void expect(const char *msg)
944 error("%s expected", msg);
947 void warning(const char *fmt, ...)
949 TCCState *s1 = tcc_state;
950 va_list ap;
952 if (s1->warn_none)
953 return;
955 va_start(ap, fmt);
956 error1(s1, 1, fmt, ap);
957 va_end(ap);
960 void skip(int c)
962 if (tok != c)
963 error("'%c' expected", c);
964 next();
967 static void test_lvalue(void)
969 if (!(vtop->r & VT_LVAL))
970 expect("lvalue");
973 /* CString handling */
975 static void cstr_realloc(CString *cstr, int new_size)
977 int size;
978 void *data;
980 size = cstr->size_allocated;
981 if (size == 0)
982 size = 8; /* no need to allocate a too small first string */
983 while (size < new_size)
984 size = size * 2;
985 data = tcc_realloc(cstr->data_allocated, size);
986 if (!data)
987 error("memory full");
988 cstr->data_allocated = data;
989 cstr->size_allocated = size;
990 cstr->data = data;
993 /* add a byte */
994 static inline void cstr_ccat(CString *cstr, int ch)
996 int size;
997 size = cstr->size + 1;
998 if (size > cstr->size_allocated)
999 cstr_realloc(cstr, size);
1000 ((unsigned char *)cstr->data)[size - 1] = ch;
1001 cstr->size = size;
1004 static void cstr_cat(CString *cstr, const char *str)
1006 int c;
1007 for(;;) {
1008 c = *str;
1009 if (c == '\0')
1010 break;
1011 cstr_ccat(cstr, c);
1012 str++;
1016 /* add a wide char */
1017 static void cstr_wccat(CString *cstr, int ch)
1019 int size;
1020 size = cstr->size + sizeof(nwchar_t);
1021 if (size > cstr->size_allocated)
1022 cstr_realloc(cstr, size);
1023 *(nwchar_t *)(((unsigned char *)cstr->data) + size - sizeof(nwchar_t)) = ch;
1024 cstr->size = size;
1027 static void cstr_new(CString *cstr)
1029 memset(cstr, 0, sizeof(CString));
1032 /* free string and reset it to NULL */
1033 static void cstr_free(CString *cstr)
1035 tcc_free(cstr->data_allocated);
1036 cstr_new(cstr);
1039 #define cstr_reset(cstr) cstr_free(cstr)
1041 /* XXX: unicode ? */
1042 static void add_char(CString *cstr, int c)
1044 if (c == '\'' || c == '\"' || c == '\\') {
1045 /* XXX: could be more precise if char or string */
1046 cstr_ccat(cstr, '\\');
1048 if (c >= 32 && c <= 126) {
1049 cstr_ccat(cstr, c);
1050 } else {
1051 cstr_ccat(cstr, '\\');
1052 if (c == '\n') {
1053 cstr_ccat(cstr, 'n');
1054 } else {
1055 cstr_ccat(cstr, '0' + ((c >> 6) & 7));
1056 cstr_ccat(cstr, '0' + ((c >> 3) & 7));
1057 cstr_ccat(cstr, '0' + (c & 7));
1062 /* push, without hashing */
1063 static Sym *sym_push2(Sym **ps, int v, int t, long c)
1065 Sym *s;
1066 s = sym_malloc();
1067 s->v = v;
1068 s->type.t = t;
1069 #ifdef _WIN64
1070 s->d = NULL;
1071 #endif
1072 s->c = c;
1073 s->next = NULL;
1074 /* add in stack */
1075 s->prev = *ps;
1076 *ps = s;
1077 return s;
1080 /* find a symbol and return its associated structure. 's' is the top
1081 of the symbol stack */
1082 static Sym *sym_find2(Sym *s, int v)
1084 while (s) {
1085 if (s->v == v)
1086 return s;
1087 s = s->prev;
1089 return NULL;
1092 /* structure lookup */
1093 static inline Sym *struct_find(int v)
1095 v -= TOK_IDENT;
1096 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1097 return NULL;
1098 return table_ident[v]->sym_struct;
1101 /* find an identifier */
1102 static inline Sym *sym_find(int v)
1104 v -= TOK_IDENT;
1105 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1106 return NULL;
1107 return table_ident[v]->sym_identifier;
1110 /* push a given symbol on the symbol stack */
1111 static Sym *sym_push(int v, CType *type, int r, int c)
1113 Sym *s, **ps;
1114 TokenSym *ts;
1116 if (local_stack)
1117 ps = &local_stack;
1118 else
1119 ps = &global_stack;
1120 s = sym_push2(ps, v, type->t, c);
1121 s->type.ref = type->ref;
1122 s->r = r;
1123 /* don't record fields or anonymous symbols */
1124 /* XXX: simplify */
1125 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
1126 /* record symbol in token array */
1127 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
1128 if (v & SYM_STRUCT)
1129 ps = &ts->sym_struct;
1130 else
1131 ps = &ts->sym_identifier;
1132 s->prev_tok = *ps;
1133 *ps = s;
1135 return s;
1138 /* push a global identifier */
1139 static Sym *global_identifier_push(int v, int t, int c)
1141 Sym *s, **ps;
1142 s = sym_push2(&global_stack, v, t, c);
1143 /* don't record anonymous symbol */
1144 if (v < SYM_FIRST_ANOM) {
1145 ps = &table_ident[v - TOK_IDENT]->sym_identifier;
1146 /* modify the top most local identifier, so that
1147 sym_identifier will point to 's' when popped */
1148 while (*ps != NULL)
1149 ps = &(*ps)->prev_tok;
1150 s->prev_tok = NULL;
1151 *ps = s;
1153 return s;
1156 /* pop symbols until top reaches 'b' */
1157 static void sym_pop(Sym **ptop, Sym *b)
1159 Sym *s, *ss, **ps;
1160 TokenSym *ts;
1161 int v;
1163 s = *ptop;
1164 while(s != b) {
1165 ss = s->prev;
1166 v = s->v;
1167 /* remove symbol in token array */
1168 /* XXX: simplify */
1169 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
1170 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
1171 if (v & SYM_STRUCT)
1172 ps = &ts->sym_struct;
1173 else
1174 ps = &ts->sym_identifier;
1175 *ps = s->prev_tok;
1177 sym_free(s);
1178 s = ss;
1180 *ptop = b;
1183 /* I/O layer */
1185 BufferedFile *tcc_open(TCCState *s1, const char *filename)
1187 int fd;
1188 BufferedFile *bf;
1190 if (strcmp(filename, "-") == 0)
1191 fd = 0, filename = "stdin";
1192 else
1193 fd = open(filename, O_RDONLY | O_BINARY);
1194 if ((s1->verbose == 2 && fd >= 0) || s1->verbose == 3)
1195 printf("%s %*s%s\n", fd < 0 ? "nf":"->",
1196 (int)(s1->include_stack_ptr - s1->include_stack), "", filename);
1197 if (fd < 0)
1198 return NULL;
1199 bf = tcc_malloc(sizeof(BufferedFile));
1200 bf->fd = fd;
1201 bf->buf_ptr = bf->buffer;
1202 bf->buf_end = bf->buffer;
1203 bf->buffer[0] = CH_EOB; /* put eob symbol */
1204 pstrcpy(bf->filename, sizeof(bf->filename), filename);
1205 #ifdef _WIN32
1206 normalize_slashes(bf->filename);
1207 #endif
1208 bf->line_num = 1;
1209 bf->ifndef_macro = 0;
1210 bf->ifdef_stack_ptr = s1->ifdef_stack_ptr;
1211 // printf("opening '%s'\n", filename);
1212 return bf;
1215 void tcc_close(BufferedFile *bf)
1217 total_lines += bf->line_num;
1218 close(bf->fd);
1219 tcc_free(bf);
1222 /* compile the C file opened in 'file'. Return non zero if errors. */
1223 static int tcc_compile(TCCState *s1)
1225 Sym *define_start;
1226 char buf[512];
1227 volatile int section_sym;
1229 #ifdef INC_DEBUG
1230 printf("%s: **** new file\n", file->filename);
1231 #endif
1232 preprocess_init(s1);
1234 cur_text_section = NULL;
1235 funcname = "";
1236 anon_sym = SYM_FIRST_ANOM;
1238 /* file info: full path + filename */
1239 section_sym = 0; /* avoid warning */
1240 if (s1->do_debug) {
1241 section_sym = put_elf_sym(symtab_section, 0, 0,
1242 ELFW(ST_INFO)(STB_LOCAL, STT_SECTION), 0,
1243 text_section->sh_num, NULL);
1244 getcwd(buf, sizeof(buf));
1245 #ifdef _WIN32
1246 normalize_slashes(buf);
1247 #endif
1248 pstrcat(buf, sizeof(buf), "/");
1249 put_stabs_r(buf, N_SO, 0, 0,
1250 text_section->data_offset, text_section, section_sym);
1251 put_stabs_r(file->filename, N_SO, 0, 0,
1252 text_section->data_offset, text_section, section_sym);
1254 /* an elf symbol of type STT_FILE must be put so that STB_LOCAL
1255 symbols can be safely used */
1256 put_elf_sym(symtab_section, 0, 0,
1257 ELFW(ST_INFO)(STB_LOCAL, STT_FILE), 0,
1258 SHN_ABS, file->filename);
1260 /* define some often used types */
1261 int_type.t = VT_INT;
1263 char_pointer_type.t = VT_BYTE;
1264 mk_pointer(&char_pointer_type);
1266 func_old_type.t = VT_FUNC;
1267 func_old_type.ref = sym_push(SYM_FIELD, &int_type, FUNC_CDECL, FUNC_OLD);
1269 #if defined(TCC_ARM_EABI) && defined(TCC_ARM_VFP)
1270 float_type.t = VT_FLOAT;
1271 double_type.t = VT_DOUBLE;
1273 func_float_type.t = VT_FUNC;
1274 func_float_type.ref = sym_push(SYM_FIELD, &float_type, FUNC_CDECL, FUNC_OLD);
1275 func_double_type.t = VT_FUNC;
1276 func_double_type.ref = sym_push(SYM_FIELD, &double_type, FUNC_CDECL, FUNC_OLD);
1277 #endif
1279 #if 0
1280 /* define 'void *alloca(unsigned int)' builtin function */
1282 Sym *s1;
1284 p = anon_sym++;
1285 sym = sym_push(p, mk_pointer(VT_VOID), FUNC_CDECL, FUNC_NEW);
1286 s1 = sym_push(SYM_FIELD, VT_UNSIGNED | VT_INT, 0, 0);
1287 s1->next = NULL;
1288 sym->next = s1;
1289 sym_push(TOK_alloca, VT_FUNC | (p << VT_STRUCT_SHIFT), VT_CONST, 0);
1291 #endif
1293 define_start = define_stack;
1294 nocode_wanted = 1;
1296 if (setjmp(s1->error_jmp_buf) == 0) {
1297 s1->nb_errors = 0;
1298 s1->error_set_jmp_enabled = 1;
1300 ch = file->buf_ptr[0];
1301 tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
1302 parse_flags = PARSE_FLAG_PREPROCESS | PARSE_FLAG_TOK_NUM;
1303 next();
1304 decl(VT_CONST);
1305 if (tok != TOK_EOF)
1306 expect("declaration");
1308 /* end of translation unit info */
1309 if (s1->do_debug) {
1310 put_stabs_r(NULL, N_SO, 0, 0,
1311 text_section->data_offset, text_section, section_sym);
1314 s1->error_set_jmp_enabled = 0;
1316 /* reset define stack, but leave -Dsymbols (may be incorrect if
1317 they are undefined) */
1318 free_defines(define_start);
1320 gen_inline_functions();
1322 sym_pop(&global_stack, NULL);
1323 sym_pop(&local_stack, NULL);
1325 return s1->nb_errors != 0 ? -1 : 0;
1328 int tcc_compile_string(TCCState *s, const char *str)
1330 BufferedFile bf1, *bf = &bf1;
1331 int ret, len;
1332 char *buf;
1334 /* init file structure */
1335 bf->fd = -1;
1336 /* XXX: avoid copying */
1337 len = strlen(str);
1338 buf = tcc_malloc(len + 1);
1339 if (!buf)
1340 return -1;
1341 memcpy(buf, str, len);
1342 buf[len] = CH_EOB;
1343 bf->buf_ptr = buf;
1344 bf->buf_end = buf + len;
1345 pstrcpy(bf->filename, sizeof(bf->filename), "<string>");
1346 bf->line_num = 1;
1347 file = bf;
1348 ret = tcc_compile(s);
1349 file = NULL;
1350 tcc_free(buf);
1352 /* currently, no need to close */
1353 return ret;
1356 /* define a preprocessor symbol. A value can also be provided with the '=' operator */
1357 void tcc_define_symbol(TCCState *s1, const char *sym, const char *value)
1359 BufferedFile bf1, *bf = &bf1;
1361 pstrcpy(bf->buffer, IO_BUF_SIZE, sym);
1362 pstrcat(bf->buffer, IO_BUF_SIZE, " ");
1363 /* default value */
1364 if (!value)
1365 value = "1";
1366 pstrcat(bf->buffer, IO_BUF_SIZE, value);
1368 /* init file structure */
1369 bf->fd = -1;
1370 bf->buf_ptr = bf->buffer;
1371 bf->buf_end = bf->buffer + strlen(bf->buffer);
1372 *bf->buf_end = CH_EOB;
1373 bf->filename[0] = '\0';
1374 bf->line_num = 1;
1375 file = bf;
1377 s1->include_stack_ptr = s1->include_stack;
1379 /* parse with define parser */
1380 ch = file->buf_ptr[0];
1381 next_nomacro();
1382 parse_define();
1383 file = NULL;
1386 /* undefine a preprocessor symbol */
1387 void tcc_undefine_symbol(TCCState *s1, const char *sym)
1389 TokenSym *ts;
1390 Sym *s;
1391 ts = tok_alloc(sym, strlen(sym));
1392 s = define_find(ts->tok);
1393 /* undefine symbol by putting an invalid name */
1394 if (s)
1395 define_undef(s);
1399 #ifdef CONFIG_TCC_BACKTRACE
1400 /* print the position in the source file of PC value 'pc' by reading
1401 the stabs debug information */
1402 static unsigned long rt_printline(unsigned long wanted_pc)
1404 Stab_Sym *sym, *sym_end;
1405 char func_name[128], last_func_name[128];
1406 unsigned long func_addr, last_pc, pc;
1407 const char *incl_files[INCLUDE_STACK_SIZE];
1408 int incl_index, len, last_line_num, i;
1409 const char *str, *p;
1411 fprintf(stderr, "0x%08lx:", wanted_pc);
1413 func_name[0] = '\0';
1414 func_addr = 0;
1415 incl_index = 0;
1416 last_func_name[0] = '\0';
1417 last_pc = 0xffffffff;
1418 last_line_num = 1;
1419 sym = (Stab_Sym *)stab_section->data + 1;
1420 sym_end = (Stab_Sym *)(stab_section->data + stab_section->data_offset);
1421 while (sym < sym_end) {
1422 switch(sym->n_type) {
1423 /* function start or end */
1424 case N_FUN:
1425 if (sym->n_strx == 0) {
1426 /* we test if between last line and end of function */
1427 pc = sym->n_value + func_addr;
1428 if (wanted_pc >= last_pc && wanted_pc < pc)
1429 goto found;
1430 func_name[0] = '\0';
1431 func_addr = 0;
1432 } else {
1433 str = stabstr_section->data + sym->n_strx;
1434 p = strchr(str, ':');
1435 if (!p) {
1436 pstrcpy(func_name, sizeof(func_name), str);
1437 } else {
1438 len = p - str;
1439 if (len > sizeof(func_name) - 1)
1440 len = sizeof(func_name) - 1;
1441 memcpy(func_name, str, len);
1442 func_name[len] = '\0';
1444 func_addr = sym->n_value;
1446 break;
1447 /* line number info */
1448 case N_SLINE:
1449 pc = sym->n_value + func_addr;
1450 if (wanted_pc >= last_pc && wanted_pc < pc)
1451 goto found;
1452 last_pc = pc;
1453 last_line_num = sym->n_desc;
1454 /* XXX: slow! */
1455 strcpy(last_func_name, func_name);
1456 break;
1457 /* include files */
1458 case N_BINCL:
1459 str = stabstr_section->data + sym->n_strx;
1460 add_incl:
1461 if (incl_index < INCLUDE_STACK_SIZE) {
1462 incl_files[incl_index++] = str;
1464 break;
1465 case N_EINCL:
1466 if (incl_index > 1)
1467 incl_index--;
1468 break;
1469 case N_SO:
1470 if (sym->n_strx == 0) {
1471 incl_index = 0; /* end of translation unit */
1472 } else {
1473 str = stabstr_section->data + sym->n_strx;
1474 /* do not add path */
1475 len = strlen(str);
1476 if (len > 0 && str[len - 1] != '/')
1477 goto add_incl;
1479 break;
1481 sym++;
1484 /* second pass: we try symtab symbols (no line number info) */
1485 incl_index = 0;
1487 ElfW(Sym) *sym, *sym_end;
1488 int type;
1490 sym_end = (ElfW(Sym) *)(symtab_section->data + symtab_section->data_offset);
1491 for(sym = (ElfW(Sym) *)symtab_section->data + 1;
1492 sym < sym_end;
1493 sym++) {
1494 type = ELFW(ST_TYPE)(sym->st_info);
1495 if (type == STT_FUNC) {
1496 if (wanted_pc >= sym->st_value &&
1497 wanted_pc < sym->st_value + sym->st_size) {
1498 pstrcpy(last_func_name, sizeof(last_func_name),
1499 strtab_section->data + sym->st_name);
1500 func_addr = sym->st_value;
1501 goto found;
1506 /* did not find any info: */
1507 fprintf(stderr, " ???\n");
1508 return 0;
1509 found:
1510 if (last_func_name[0] != '\0') {
1511 fprintf(stderr, " %s()", last_func_name);
1513 if (incl_index > 0) {
1514 fprintf(stderr, " (%s:%d",
1515 incl_files[incl_index - 1], last_line_num);
1516 for(i = incl_index - 2; i >= 0; i--)
1517 fprintf(stderr, ", included from %s", incl_files[i]);
1518 fprintf(stderr, ")");
1520 fprintf(stderr, "\n");
1521 return func_addr;
1524 #ifdef __i386__
1525 /* fix for glibc 2.1 */
1526 #ifndef REG_EIP
1527 #define REG_EIP EIP
1528 #define REG_EBP EBP
1529 #endif
1531 /* return the PC at frame level 'level'. Return non zero if not found */
1532 static int rt_get_caller_pc(unsigned long *paddr,
1533 ucontext_t *uc, int level)
1535 unsigned long fp;
1536 int i;
1538 if (level == 0) {
1539 #if defined(__FreeBSD__)
1540 *paddr = uc->uc_mcontext.mc_eip;
1541 #elif defined(__dietlibc__)
1542 *paddr = uc->uc_mcontext.eip;
1543 #else
1544 *paddr = uc->uc_mcontext.gregs[REG_EIP];
1545 #endif
1546 return 0;
1547 } else {
1548 #if defined(__FreeBSD__)
1549 fp = uc->uc_mcontext.mc_ebp;
1550 #elif defined(__dietlibc__)
1551 fp = uc->uc_mcontext.ebp;
1552 #else
1553 fp = uc->uc_mcontext.gregs[REG_EBP];
1554 #endif
1555 for(i=1;i<level;i++) {
1556 /* XXX: check address validity with program info */
1557 if (fp <= 0x1000 || fp >= 0xc0000000)
1558 return -1;
1559 fp = ((unsigned long *)fp)[0];
1561 *paddr = ((unsigned long *)fp)[1];
1562 return 0;
1565 #elif defined(__x86_64__)
1566 /* return the PC at frame level 'level'. Return non zero if not found */
1567 static int rt_get_caller_pc(unsigned long *paddr,
1568 ucontext_t *uc, int level)
1570 unsigned long fp;
1571 int i;
1573 if (level == 0) {
1574 /* XXX: only support linux */
1575 *paddr = uc->uc_mcontext.gregs[REG_RIP];
1576 return 0;
1577 } else {
1578 fp = uc->uc_mcontext.gregs[REG_RBP];
1579 for(i=1;i<level;i++) {
1580 /* XXX: check address validity with program info */
1581 if (fp <= 0x1000)
1582 return -1;
1583 fp = ((unsigned long *)fp)[0];
1585 *paddr = ((unsigned long *)fp)[1];
1586 return 0;
1589 #else
1590 #warning add arch specific rt_get_caller_pc()
1591 static int rt_get_caller_pc(unsigned long *paddr,
1592 ucontext_t *uc, int level)
1594 return -1;
1596 #endif
1598 /* emit a run time error at position 'pc' */
1599 void rt_error(ucontext_t *uc, const char *fmt, ...)
1601 va_list ap;
1602 unsigned long pc;
1603 int i;
1605 va_start(ap, fmt);
1606 fprintf(stderr, "Runtime error: ");
1607 vfprintf(stderr, fmt, ap);
1608 fprintf(stderr, "\n");
1609 for(i=0;i<num_callers;i++) {
1610 if (rt_get_caller_pc(&pc, uc, i) < 0)
1611 break;
1612 if (i == 0)
1613 fprintf(stderr, "at ");
1614 else
1615 fprintf(stderr, "by ");
1616 pc = rt_printline(pc);
1617 if (pc == rt_prog_main && pc)
1618 break;
1620 exit(255);
1621 va_end(ap);
1624 /* signal handler for fatal errors */
1625 static void sig_error(int signum, siginfo_t *siginf, void *puc)
1627 ucontext_t *uc = puc;
1629 switch(signum) {
1630 case SIGFPE:
1631 switch(siginf->si_code) {
1632 case FPE_INTDIV:
1633 case FPE_FLTDIV:
1634 rt_error(uc, "division by zero");
1635 break;
1636 default:
1637 rt_error(uc, "floating point exception");
1638 break;
1640 break;
1641 case SIGBUS:
1642 case SIGSEGV:
1643 if (rt_bound_error_msg && *rt_bound_error_msg)
1644 rt_error(uc, *rt_bound_error_msg);
1645 else
1646 rt_error(uc, "dereferencing invalid pointer");
1647 break;
1648 case SIGILL:
1649 rt_error(uc, "illegal instruction");
1650 break;
1651 case SIGABRT:
1652 rt_error(uc, "abort() called");
1653 break;
1654 default:
1655 rt_error(uc, "caught signal %d", signum);
1656 break;
1658 exit(255);
1661 #endif
1663 /* copy code into memory passed in by the caller and do all relocations
1664 (needed before using tcc_get_symbol()).
1665 returns -1 on error and required size if ptr is NULL */
1666 int tcc_relocate(TCCState *s1, void *ptr)
1668 Section *s;
1669 unsigned long offset, length;
1670 uplong mem;
1671 int i;
1673 if (0 == s1->runtime_added) {
1674 s1->runtime_added = 1;
1675 s1->nb_errors = 0;
1676 #ifdef TCC_TARGET_PE
1677 pe_output_file(s1, NULL);
1678 #else
1679 tcc_add_runtime(s1);
1680 relocate_common_syms();
1681 tcc_add_linker_symbols(s1);
1682 build_got_entries(s1);
1683 #endif
1684 if (s1->nb_errors)
1685 return -1;
1688 offset = 0, mem = (uplong)ptr;
1689 for(i = 1; i < s1->nb_sections; i++) {
1690 s = s1->sections[i];
1691 if (0 == (s->sh_flags & SHF_ALLOC))
1692 continue;
1693 length = s->data_offset;
1694 s->sh_addr = mem ? (mem + offset + 15) & ~15 : 0;
1695 offset = (offset + length + 15) & ~15;
1698 /* relocate symbols */
1699 relocate_syms(s1, 1);
1700 if (s1->nb_errors)
1701 return -1;
1703 #ifndef TCC_TARGET_PE
1704 #ifdef TCC_TARGET_X86_64
1705 s1->runtime_plt_and_got_offset = 0;
1706 s1->runtime_plt_and_got = (char *)(mem + offset);
1707 /* double the size of the buffer for got and plt entries
1708 XXX: calculate exact size for them? */
1709 offset *= 2;
1710 #endif
1711 #endif
1713 if (0 == mem)
1714 return offset + 15;
1716 /* relocate each section */
1717 for(i = 1; i < s1->nb_sections; i++) {
1718 s = s1->sections[i];
1719 if (s->reloc)
1720 relocate_section(s1, s);
1723 for(i = 1; i < s1->nb_sections; i++) {
1724 s = s1->sections[i];
1725 if (0 == (s->sh_flags & SHF_ALLOC))
1726 continue;
1727 length = s->data_offset;
1728 // printf("%-12s %08x %04x\n", s->name, s->sh_addr, length);
1729 ptr = (void*)(uplong)s->sh_addr;
1730 if (NULL == s->data || s->sh_type == SHT_NOBITS)
1731 memset(ptr, 0, length);
1732 else
1733 memcpy(ptr, s->data, length);
1734 /* mark executable sections as executable in memory */
1735 if (s->sh_flags & SHF_EXECINSTR)
1736 set_pages_executable(ptr, length);
1738 #ifndef TCC_TARGET_PE
1739 #ifdef TCC_TARGET_X86_64
1740 set_pages_executable(s1->runtime_plt_and_got,
1741 s1->runtime_plt_and_got_offset);
1742 #endif
1743 #endif
1744 return 0;
1747 /* launch the compiled program with the given arguments */
1748 int tcc_run(TCCState *s1, int argc, char **argv)
1750 int (*prog_main)(int, char **);
1751 void *ptr;
1752 int ret;
1754 ret = tcc_relocate(s1, NULL);
1755 if (ret < 0)
1756 return -1;
1757 ptr = tcc_malloc(ret);
1758 tcc_relocate(s1, ptr);
1760 prog_main = tcc_get_symbol_err(s1, "main");
1762 if (s1->do_debug) {
1763 #ifdef CONFIG_TCC_BACKTRACE
1764 struct sigaction sigact;
1765 /* install TCC signal handlers to print debug info on fatal
1766 runtime errors */
1767 sigact.sa_flags = SA_SIGINFO | SA_RESETHAND;
1768 sigact.sa_sigaction = sig_error;
1769 sigemptyset(&sigact.sa_mask);
1770 sigaction(SIGFPE, &sigact, NULL);
1771 sigaction(SIGILL, &sigact, NULL);
1772 sigaction(SIGSEGV, &sigact, NULL);
1773 sigaction(SIGBUS, &sigact, NULL);
1774 sigaction(SIGABRT, &sigact, NULL);
1775 #else
1776 error("debug mode not available");
1777 #endif
1780 #ifdef CONFIG_TCC_BCHECK
1781 if (s1->do_bounds_check) {
1782 void (*bound_init)(void);
1783 void (*bound_exit)(void);
1784 /* set error function */
1785 rt_bound_error_msg = tcc_get_symbol_err(s1, "__bound_error_msg");
1786 rt_prog_main = (unsigned long)prog_main;
1787 /* XXX: use .init section so that it also work in binary ? */
1788 bound_init = tcc_get_symbol_err(s1, "__bound_init");
1789 bound_exit = tcc_get_symbol_err(s1, "__bound_exit");
1790 bound_init();
1791 ret = (*prog_main)(argc, argv);
1792 bound_exit();
1793 } else
1794 #endif
1795 ret = (*prog_main)(argc, argv);
1796 tcc_free(ptr);
1797 return ret;
1800 void tcc_memstats(void)
1802 #ifdef MEM_DEBUG
1803 printf("memory in use: %d\n", mem_cur_size);
1804 #endif
1807 static void tcc_cleanup(void)
1809 int i, n;
1811 if (NULL == tcc_state)
1812 return;
1813 tcc_state = NULL;
1815 /* free -D defines */
1816 free_defines(NULL);
1818 /* free tokens */
1819 n = tok_ident - TOK_IDENT;
1820 for(i = 0; i < n; i++)
1821 tcc_free(table_ident[i]);
1822 tcc_free(table_ident);
1824 /* free sym_pools */
1825 dynarray_reset(&sym_pools, &nb_sym_pools);
1826 /* string buffer */
1827 cstr_free(&tokcstr);
1828 /* reset symbol stack */
1829 sym_free_first = NULL;
1830 /* cleanup from error/setjmp */
1831 macro_ptr = NULL;
1834 TCCState *tcc_new(void)
1836 TCCState *s;
1837 char buffer[100];
1838 int a,b,c;
1840 tcc_cleanup();
1842 s = tcc_mallocz(sizeof(TCCState));
1843 if (!s)
1844 return NULL;
1845 tcc_state = s;
1846 #ifdef _WIN32
1847 tcc_set_lib_path_w32(s);
1848 #else
1849 tcc_set_lib_path(s, CONFIG_TCCDIR);
1850 #endif
1851 s->output_type = TCC_OUTPUT_MEMORY;
1852 preprocess_new();
1854 /* we add dummy defines for some special macros to speed up tests
1855 and to have working defined() */
1856 define_push(TOK___LINE__, MACRO_OBJ, NULL, NULL);
1857 define_push(TOK___FILE__, MACRO_OBJ, NULL, NULL);
1858 define_push(TOK___DATE__, MACRO_OBJ, NULL, NULL);
1859 define_push(TOK___TIME__, MACRO_OBJ, NULL, NULL);
1861 /* standard defines */
1862 tcc_define_symbol(s, "__STDC__", NULL);
1863 tcc_define_symbol(s, "__STDC_VERSION__", "199901L");
1864 #if defined(TCC_TARGET_I386)
1865 tcc_define_symbol(s, "__i386__", NULL);
1866 #endif
1867 #if defined(TCC_TARGET_X86_64)
1868 tcc_define_symbol(s, "__x86_64__", NULL);
1869 #endif
1870 #if defined(TCC_TARGET_ARM)
1871 tcc_define_symbol(s, "__ARM_ARCH_4__", NULL);
1872 tcc_define_symbol(s, "__arm_elf__", NULL);
1873 tcc_define_symbol(s, "__arm_elf", NULL);
1874 tcc_define_symbol(s, "arm_elf", NULL);
1875 tcc_define_symbol(s, "__arm__", NULL);
1876 tcc_define_symbol(s, "__arm", NULL);
1877 tcc_define_symbol(s, "arm", NULL);
1878 tcc_define_symbol(s, "__APCS_32__", NULL);
1879 #endif
1880 #ifdef TCC_TARGET_PE
1881 tcc_define_symbol(s, "_WIN32", NULL);
1882 #ifdef TCC_TARGET_X86_64
1883 tcc_define_symbol(s, "_WIN64", NULL);
1884 #endif
1885 #else
1886 tcc_define_symbol(s, "__unix__", NULL);
1887 tcc_define_symbol(s, "__unix", NULL);
1888 #if defined(__linux)
1889 tcc_define_symbol(s, "__linux__", NULL);
1890 tcc_define_symbol(s, "__linux", NULL);
1891 #endif
1892 #endif
1893 /* tiny C specific defines */
1894 sscanf(TCC_VERSION, "%d.%d.%d", &a, &b, &c);
1895 sprintf(buffer, "%d", a*10000 + b*100 + c);
1896 tcc_define_symbol(s, "__TINYC__", buffer);
1898 /* tiny C & gcc defines */
1899 tcc_define_symbol(s, "__SIZE_TYPE__", "unsigned long");
1900 tcc_define_symbol(s, "__PTRDIFF_TYPE__", "long");
1901 #ifdef TCC_TARGET_PE
1902 tcc_define_symbol(s, "__WCHAR_TYPE__", "unsigned short");
1903 #else
1904 tcc_define_symbol(s, "__WCHAR_TYPE__", "int");
1905 #endif
1907 #ifndef TCC_TARGET_PE
1908 /* default library paths */
1909 tcc_add_library_path(s, CONFIG_SYSROOT "/usr/local/lib");
1910 tcc_add_library_path(s, CONFIG_SYSROOT "/usr/lib");
1911 tcc_add_library_path(s, CONFIG_SYSROOT "/lib");
1912 #endif
1914 /* no section zero */
1915 dynarray_add((void ***)&s->sections, &s->nb_sections, NULL);
1917 /* create standard sections */
1918 text_section = new_section(s, ".text", SHT_PROGBITS, SHF_ALLOC | SHF_EXECINSTR);
1919 data_section = new_section(s, ".data", SHT_PROGBITS, SHF_ALLOC | SHF_WRITE);
1920 bss_section = new_section(s, ".bss", SHT_NOBITS, SHF_ALLOC | SHF_WRITE);
1922 /* symbols are always generated for linking stage */
1923 symtab_section = new_symtab(s, ".symtab", SHT_SYMTAB, 0,
1924 ".strtab",
1925 ".hashtab", SHF_PRIVATE);
1926 strtab_section = symtab_section->link;
1928 /* private symbol table for dynamic symbols */
1929 s->dynsymtab_section = new_symtab(s, ".dynsymtab", SHT_SYMTAB, SHF_PRIVATE,
1930 ".dynstrtab",
1931 ".dynhashtab", SHF_PRIVATE);
1932 s->alacarte_link = 1;
1934 #ifdef CHAR_IS_UNSIGNED
1935 s->char_is_unsigned = 1;
1936 #endif
1937 #if defined(TCC_TARGET_PE) && 0
1938 /* XXX: currently the PE linker is not ready to support that */
1939 s->leading_underscore = 1;
1940 #endif
1941 #ifdef TCC_TARGET_I386
1942 s->seg_size = 32;
1943 #endif
1944 return s;
1947 void tcc_delete(TCCState *s1)
1949 int i;
1951 tcc_cleanup();
1953 /* free all sections */
1954 for(i = 1; i < s1->nb_sections; i++)
1955 free_section(s1->sections[i]);
1956 dynarray_reset(&s1->sections, &s1->nb_sections);
1958 for(i = 0; i < s1->nb_priv_sections; i++)
1959 free_section(s1->priv_sections[i]);
1960 dynarray_reset(&s1->priv_sections, &s1->nb_priv_sections);
1962 /* free any loaded DLLs */
1963 for ( i = 0; i < s1->nb_loaded_dlls; i++) {
1964 DLLReference *ref = s1->loaded_dlls[i];
1965 if ( ref->handle )
1966 dlclose(ref->handle);
1969 /* free loaded dlls array */
1970 dynarray_reset(&s1->loaded_dlls, &s1->nb_loaded_dlls);
1972 /* free library paths */
1973 dynarray_reset(&s1->library_paths, &s1->nb_library_paths);
1975 /* free include paths */
1976 dynarray_reset(&s1->cached_includes, &s1->nb_cached_includes);
1977 dynarray_reset(&s1->include_paths, &s1->nb_include_paths);
1978 dynarray_reset(&s1->sysinclude_paths, &s1->nb_sysinclude_paths);
1980 tcc_free(s1->tcc_lib_path);
1981 tcc_free(s1);
1984 int tcc_add_include_path(TCCState *s1, const char *pathname)
1986 char *pathname1;
1988 pathname1 = tcc_strdup(pathname);
1989 dynarray_add((void ***)&s1->include_paths, &s1->nb_include_paths, pathname1);
1990 return 0;
1993 int tcc_add_sysinclude_path(TCCState *s1, const char *pathname)
1995 char *pathname1;
1997 pathname1 = tcc_strdup(pathname);
1998 dynarray_add((void ***)&s1->sysinclude_paths, &s1->nb_sysinclude_paths, pathname1);
1999 return 0;
2002 static int tcc_add_file_internal(TCCState *s1, const char *filename, int flags)
2004 const char *ext;
2005 ElfW(Ehdr) ehdr;
2006 int fd, ret, size;
2007 BufferedFile *saved_file;
2009 ret = -1;
2011 /* find source file type with extension */
2012 ext = tcc_fileextension(filename);
2013 if (ext[0])
2014 ext++;
2016 /* open the file */
2017 saved_file = file;
2018 file = tcc_open(s1, filename);
2019 if (!file) {
2020 if (flags & AFF_PRINT_ERROR)
2021 error_noabort("file '%s' not found", filename);
2022 goto the_end;
2025 if (flags & AFF_PREPROCESS) {
2026 ret = tcc_preprocess(s1);
2027 goto the_end;
2030 if (!ext[0] || !PATHCMP(ext, "c")) {
2031 /* C file assumed */
2032 ret = tcc_compile(s1);
2033 goto the_end;
2036 #ifdef CONFIG_TCC_ASM
2037 if (!strcmp(ext, "S")) {
2038 /* preprocessed assembler */
2039 ret = tcc_assemble(s1, 1);
2040 goto the_end;
2043 if (!strcmp(ext, "s")) {
2044 /* non preprocessed assembler */
2045 ret = tcc_assemble(s1, 0);
2046 goto the_end;
2048 #endif
2050 fd = file->fd;
2051 /* assume executable format: auto guess file type */
2052 size = read(fd, &ehdr, sizeof(ehdr));
2053 lseek(fd, 0, SEEK_SET);
2054 if (size <= 0) {
2055 error_noabort("could not read header");
2056 goto the_end;
2059 if (size == sizeof(ehdr) &&
2060 ehdr.e_ident[0] == ELFMAG0 &&
2061 ehdr.e_ident[1] == ELFMAG1 &&
2062 ehdr.e_ident[2] == ELFMAG2 &&
2063 ehdr.e_ident[3] == ELFMAG3) {
2065 /* do not display line number if error */
2066 file->line_num = 0;
2067 if (ehdr.e_type == ET_REL) {
2068 ret = tcc_load_object_file(s1, fd, 0);
2069 goto the_end;
2072 #ifndef TCC_TARGET_PE
2073 if (ehdr.e_type == ET_DYN) {
2074 if (s1->output_type == TCC_OUTPUT_MEMORY) {
2075 void *h;
2076 h = dlopen(filename, RTLD_GLOBAL | RTLD_LAZY);
2077 if (h)
2078 ret = 0;
2079 } else {
2080 ret = tcc_load_dll(s1, fd, filename,
2081 (flags & AFF_REFERENCED_DLL) != 0);
2083 goto the_end;
2085 #endif
2086 error_noabort("unrecognized ELF file");
2087 goto the_end;
2090 if (memcmp((char *)&ehdr, ARMAG, 8) == 0) {
2091 file->line_num = 0; /* do not display line number if error */
2092 ret = tcc_load_archive(s1, fd);
2093 goto the_end;
2096 #ifdef TCC_TARGET_COFF
2097 if (*(uint16_t *)(&ehdr) == COFF_C67_MAGIC) {
2098 ret = tcc_load_coff(s1, fd);
2099 goto the_end;
2101 #endif
2103 #ifdef TCC_TARGET_PE
2104 ret = pe_load_file(s1, filename, fd);
2105 #else
2106 /* as GNU ld, consider it is an ld script if not recognized */
2107 ret = tcc_load_ldscript(s1);
2108 #endif
2109 if (ret < 0)
2110 error_noabort("unrecognized file type");
2112 the_end:
2113 if (file)
2114 tcc_close(file);
2115 file = saved_file;
2116 return ret;
2119 int tcc_add_file(TCCState *s, const char *filename)
2121 if (s->output_type == TCC_OUTPUT_PREPROCESS)
2122 return tcc_add_file_internal(s, filename, AFF_PRINT_ERROR | AFF_PREPROCESS);
2123 else
2124 return tcc_add_file_internal(s, filename, AFF_PRINT_ERROR);
2127 int tcc_add_library_path(TCCState *s, const char *pathname)
2129 char *pathname1;
2131 pathname1 = tcc_strdup(pathname);
2132 dynarray_add((void ***)&s->library_paths, &s->nb_library_paths, pathname1);
2133 return 0;
2136 /* find and load a dll. Return non zero if not found */
2137 /* XXX: add '-rpath' option support ? */
2138 static int tcc_add_dll(TCCState *s, const char *filename, int flags)
2140 char buf[1024];
2141 int i;
2143 for(i = 0; i < s->nb_library_paths; i++) {
2144 snprintf(buf, sizeof(buf), "%s/%s",
2145 s->library_paths[i], filename);
2146 if (tcc_add_file_internal(s, buf, flags) == 0)
2147 return 0;
2149 return -1;
2152 /* the library name is the same as the argument of the '-l' option */
2153 int tcc_add_library(TCCState *s, const char *libraryname)
2155 char buf[1024];
2156 int i;
2158 /* first we look for the dynamic library if not static linking */
2159 if (!s->static_link) {
2160 #ifdef TCC_TARGET_PE
2161 if (pe_add_dll(s, libraryname) == 0)
2162 return 0;
2163 #else
2164 snprintf(buf, sizeof(buf), "lib%s.so", libraryname);
2165 if (tcc_add_dll(s, buf, 0) == 0)
2166 return 0;
2167 #endif
2169 /* then we look for the static library */
2170 for(i = 0; i < s->nb_library_paths; i++) {
2171 snprintf(buf, sizeof(buf), "%s/lib%s.a",
2172 s->library_paths[i], libraryname);
2173 if (tcc_add_file_internal(s, buf, 0) == 0)
2174 return 0;
2176 return -1;
2179 int tcc_add_symbol(TCCState *s, const char *name, void *val)
2181 add_elf_sym(symtab_section, (uplong)val, 0,
2182 ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE), 0,
2183 SHN_ABS, name);
2184 return 0;
2187 int tcc_set_output_type(TCCState *s, int output_type)
2189 char buf[1024];
2191 s->output_type = output_type;
2193 if (!s->nostdinc) {
2194 /* default include paths */
2195 /* XXX: reverse order needed if -isystem support */
2196 #ifndef TCC_TARGET_PE
2197 tcc_add_sysinclude_path(s, CONFIG_SYSROOT "/usr/local/include");
2198 tcc_add_sysinclude_path(s, CONFIG_SYSROOT "/usr/include");
2199 #endif
2200 snprintf(buf, sizeof(buf), "%s/include", s->tcc_lib_path);
2201 tcc_add_sysinclude_path(s, buf);
2202 #ifdef TCC_TARGET_PE
2203 snprintf(buf, sizeof(buf), "%s/include/winapi", s->tcc_lib_path);
2204 tcc_add_sysinclude_path(s, buf);
2205 #endif
2208 /* if bound checking, then add corresponding sections */
2209 #ifdef CONFIG_TCC_BCHECK
2210 if (s->do_bounds_check) {
2211 /* define symbol */
2212 tcc_define_symbol(s, "__BOUNDS_CHECKING_ON", NULL);
2213 /* create bounds sections */
2214 bounds_section = new_section(s, ".bounds",
2215 SHT_PROGBITS, SHF_ALLOC);
2216 lbounds_section = new_section(s, ".lbounds",
2217 SHT_PROGBITS, SHF_ALLOC);
2219 #endif
2221 if (s->char_is_unsigned) {
2222 tcc_define_symbol(s, "__CHAR_UNSIGNED__", NULL);
2225 /* add debug sections */
2226 if (s->do_debug) {
2227 /* stab symbols */
2228 stab_section = new_section(s, ".stab", SHT_PROGBITS, 0);
2229 stab_section->sh_entsize = sizeof(Stab_Sym);
2230 stabstr_section = new_section(s, ".stabstr", SHT_STRTAB, 0);
2231 put_elf_str(stabstr_section, "");
2232 stab_section->link = stabstr_section;
2233 /* put first entry */
2234 put_stabs("", 0, 0, 0, 0);
2237 /* add libc crt1/crti objects */
2238 #ifndef TCC_TARGET_PE
2239 if ((output_type == TCC_OUTPUT_EXE || output_type == TCC_OUTPUT_DLL) &&
2240 !s->nostdlib) {
2241 if (output_type != TCC_OUTPUT_DLL)
2242 tcc_add_file(s, CONFIG_TCC_CRT_PREFIX "/crt1.o");
2243 tcc_add_file(s, CONFIG_TCC_CRT_PREFIX "/crti.o");
2245 #endif
2247 #ifdef TCC_TARGET_PE
2248 snprintf(buf, sizeof(buf), "%s/lib", s->tcc_lib_path);
2249 tcc_add_library_path(s, buf);
2250 #ifdef _WIN32
2251 if (GetSystemDirectory(buf, sizeof buf))
2252 tcc_add_library_path(s, buf);
2253 #endif
2254 #endif
2256 return 0;
2259 #define WD_ALL 0x0001 /* warning is activated when using -Wall */
2260 #define FD_INVERT 0x0002 /* invert value before storing */
2262 typedef struct FlagDef {
2263 uint16_t offset;
2264 uint16_t flags;
2265 const char *name;
2266 } FlagDef;
2268 static const FlagDef warning_defs[] = {
2269 { offsetof(TCCState, warn_unsupported), 0, "unsupported" },
2270 { offsetof(TCCState, warn_write_strings), 0, "write-strings" },
2271 { offsetof(TCCState, warn_error), 0, "error" },
2272 { offsetof(TCCState, warn_implicit_function_declaration), WD_ALL,
2273 "implicit-function-declaration" },
2276 static int set_flag(TCCState *s, const FlagDef *flags, int nb_flags,
2277 const char *name, int value)
2279 int i;
2280 const FlagDef *p;
2281 const char *r;
2283 r = name;
2284 if (r[0] == 'n' && r[1] == 'o' && r[2] == '-') {
2285 r += 3;
2286 value = !value;
2288 for(i = 0, p = flags; i < nb_flags; i++, p++) {
2289 if (!strcmp(r, p->name))
2290 goto found;
2292 return -1;
2293 found:
2294 if (p->flags & FD_INVERT)
2295 value = !value;
2296 *(int *)((uint8_t *)s + p->offset) = value;
2297 return 0;
2301 /* set/reset a warning */
2302 int tcc_set_warning(TCCState *s, const char *warning_name, int value)
2304 int i;
2305 const FlagDef *p;
2307 if (!strcmp(warning_name, "all")) {
2308 for(i = 0, p = warning_defs; i < countof(warning_defs); i++, p++) {
2309 if (p->flags & WD_ALL)
2310 *(int *)((uint8_t *)s + p->offset) = 1;
2312 return 0;
2313 } else {
2314 return set_flag(s, warning_defs, countof(warning_defs),
2315 warning_name, value);
2319 static const FlagDef flag_defs[] = {
2320 { offsetof(TCCState, char_is_unsigned), 0, "unsigned-char" },
2321 { offsetof(TCCState, char_is_unsigned), FD_INVERT, "signed-char" },
2322 { offsetof(TCCState, nocommon), FD_INVERT, "common" },
2323 { offsetof(TCCState, leading_underscore), 0, "leading-underscore" },
2326 /* set/reset a flag */
2327 int tcc_set_flag(TCCState *s, const char *flag_name, int value)
2329 return set_flag(s, flag_defs, countof(flag_defs),
2330 flag_name, value);
2333 /* set CONFIG_TCCDIR at runtime */
2334 void tcc_set_lib_path(TCCState *s, const char *path)
2336 tcc_free(s->tcc_lib_path);
2337 s->tcc_lib_path = tcc_strdup(path);
2340 void tcc_print_stats(TCCState *s, int64_t total_time)
2342 double tt;
2343 tt = (double)total_time / 1000000.0;
2344 if (tt < 0.001)
2345 tt = 0.001;
2346 if (total_bytes < 1)
2347 total_bytes = 1;
2348 printf("%d idents, %d lines, %d bytes, %0.3f s, %d lines/s, %0.1f MB/s\n",
2349 tok_ident - TOK_IDENT, total_lines, total_bytes,
2350 tt, (int)(total_lines / tt),
2351 total_bytes / tt / 1000000.0);