integrate x86_64-asm.c into i386-asm.c
[tinycc.git] / libtcc.c
blob823078e8e5d437c310c141dced926bc8b9a8f41b
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 #if defined TCC_TARGET_I386 || defined TCC_TARGET_X86_64
329 #include "i386-asm.c"
330 #endif
332 #include "tccasm.c"
333 #else
334 static void asm_instr(void)
336 error("inline asm() not supported");
338 static void asm_global_instr(void)
340 error("inline asm() not supported");
342 #endif
344 #include "tccelf.c"
346 #ifdef TCC_TARGET_COFF
347 #include "tcccoff.c"
348 #endif
350 #ifdef TCC_TARGET_PE
351 #include "tccpe.c"
352 #endif
354 /********************************************************/
355 #ifdef _WIN32
356 char *normalize_slashes(char *path)
358 char *p;
359 for (p = path; *p; ++p)
360 if (*p == '\\')
361 *p = '/';
362 return path;
365 HMODULE tcc_module;
367 /* on win32, we suppose the lib and includes are at the location of 'tcc.exe' */
368 void tcc_set_lib_path_w32(TCCState *s)
370 char path[1024], *p;
371 GetModuleFileNameA(tcc_module, path, sizeof path);
372 p = tcc_basename(normalize_slashes(strlwr(path)));
373 if (p - 5 > path && 0 == strncmp(p - 5, "/bin/", 5))
374 p -= 5;
375 else if (p > path)
376 p--;
377 *p = 0;
378 tcc_set_lib_path(s, path);
381 #ifdef LIBTCC_AS_DLL
382 BOOL WINAPI DllMain (HANDLE hDll, DWORD dwReason, LPVOID lpReserved)
384 if (DLL_PROCESS_ATTACH == dwReason)
385 tcc_module = hDll;
386 return TRUE;
388 #endif
389 #endif
391 /********************************************************/
392 #ifdef CONFIG_TCC_STATIC
394 #define RTLD_LAZY 0x001
395 #define RTLD_NOW 0x002
396 #define RTLD_GLOBAL 0x100
397 #define RTLD_DEFAULT NULL
399 /* dummy function for profiling */
400 void *dlopen(const char *filename, int flag)
402 return NULL;
405 void dlclose(void *p)
409 const char *dlerror(void)
411 return "error";
414 typedef struct TCCSyms {
415 char *str;
416 void *ptr;
417 } TCCSyms;
419 #define TCCSYM(a) { #a, &a, },
421 /* add the symbol you want here if no dynamic linking is done */
422 static TCCSyms tcc_syms[] = {
423 #if !defined(CONFIG_TCCBOOT)
424 TCCSYM(printf)
425 TCCSYM(fprintf)
426 TCCSYM(fopen)
427 TCCSYM(fclose)
428 #endif
429 { NULL, NULL },
432 void *resolve_sym(TCCState *s1, const char *symbol)
434 TCCSyms *p;
435 p = tcc_syms;
436 while (p->str != NULL) {
437 if (!strcmp(p->str, symbol))
438 return p->ptr;
439 p++;
441 return NULL;
444 #elif defined(_WIN32)
445 #define dlclose FreeLibrary
447 #else
448 #include <dlfcn.h>
450 void *resolve_sym(TCCState *s1, const char *sym)
452 return dlsym(RTLD_DEFAULT, sym);
455 #endif
457 /********************************************************/
459 /* we use our own 'finite' function to avoid potential problems with
460 non standard math libs */
461 /* XXX: endianness dependent */
462 int ieee_finite(double d)
464 int *p = (int *)&d;
465 return ((unsigned)((p[1] | 0x800fffff) + 1)) >> 31;
468 /* copy a string and truncate it. */
469 char *pstrcpy(char *buf, int buf_size, const char *s)
471 char *q, *q_end;
472 int c;
474 if (buf_size > 0) {
475 q = buf;
476 q_end = buf + buf_size - 1;
477 while (q < q_end) {
478 c = *s++;
479 if (c == '\0')
480 break;
481 *q++ = c;
483 *q = '\0';
485 return buf;
488 /* strcat and truncate. */
489 char *pstrcat(char *buf, int buf_size, const char *s)
491 int len;
492 len = strlen(buf);
493 if (len < buf_size)
494 pstrcpy(buf + len, buf_size - len, s);
495 return buf;
498 /* extract the basename of a file */
499 char *tcc_basename(const char *name)
501 char *p = strchr(name, 0);
502 while (p > name && !IS_PATHSEP(p[-1]))
503 --p;
504 return p;
507 char *tcc_fileextension (const char *name)
509 char *b = tcc_basename(name);
510 char *e = strrchr(b, '.');
511 return e ? e : strchr(b, 0);
514 void set_pages_executable(void *ptr, unsigned long length)
516 #ifdef _WIN32
517 unsigned long old_protect;
518 VirtualProtect(ptr, length, PAGE_EXECUTE_READWRITE, &old_protect);
519 #else
520 unsigned long start, end;
521 start = (unsigned long)ptr & ~(PAGESIZE - 1);
522 end = (unsigned long)ptr + length;
523 end = (end + PAGESIZE - 1) & ~(PAGESIZE - 1);
524 mprotect((void *)start, end - start, PROT_READ | PROT_WRITE | PROT_EXEC);
525 #endif
528 /* memory management */
529 #ifdef MEM_DEBUG
530 int mem_cur_size;
531 int mem_max_size;
532 unsigned malloc_usable_size(void*);
533 #endif
535 void tcc_free(void *ptr)
537 #ifdef MEM_DEBUG
538 mem_cur_size -= malloc_usable_size(ptr);
539 #endif
540 free(ptr);
543 void *tcc_malloc(unsigned long size)
545 void *ptr;
546 ptr = malloc(size);
547 if (!ptr && size)
548 error("memory full");
549 #ifdef MEM_DEBUG
550 mem_cur_size += malloc_usable_size(ptr);
551 if (mem_cur_size > mem_max_size)
552 mem_max_size = mem_cur_size;
553 #endif
554 return ptr;
557 void *tcc_mallocz(unsigned long size)
559 void *ptr;
560 ptr = tcc_malloc(size);
561 memset(ptr, 0, size);
562 return ptr;
565 void *tcc_realloc(void *ptr, unsigned long size)
567 void *ptr1;
568 #ifdef MEM_DEBUG
569 mem_cur_size -= malloc_usable_size(ptr);
570 #endif
571 ptr1 = realloc(ptr, size);
572 #ifdef MEM_DEBUG
573 /* NOTE: count not correct if alloc error, but not critical */
574 mem_cur_size += malloc_usable_size(ptr1);
575 if (mem_cur_size > mem_max_size)
576 mem_max_size = mem_cur_size;
577 #endif
578 return ptr1;
581 char *tcc_strdup(const char *str)
583 char *ptr;
584 ptr = tcc_malloc(strlen(str) + 1);
585 strcpy(ptr, str);
586 return ptr;
589 #define free(p) use_tcc_free(p)
590 #define malloc(s) use_tcc_malloc(s)
591 #define realloc(p, s) use_tcc_realloc(p, s)
593 void dynarray_add(void ***ptab, int *nb_ptr, void *data)
595 int nb, nb_alloc;
596 void **pp;
598 nb = *nb_ptr;
599 pp = *ptab;
600 /* every power of two we double array size */
601 if ((nb & (nb - 1)) == 0) {
602 if (!nb)
603 nb_alloc = 1;
604 else
605 nb_alloc = nb * 2;
606 pp = tcc_realloc(pp, nb_alloc * sizeof(void *));
607 if (!pp)
608 error("memory full");
609 *ptab = pp;
611 pp[nb++] = data;
612 *nb_ptr = nb;
615 void dynarray_reset(void *pp, int *n)
617 void **p;
618 for (p = *(void***)pp; *n; ++p, --*n)
619 if (*p)
620 tcc_free(*p);
621 tcc_free(*(void**)pp);
622 *(void**)pp = NULL;
625 /* symbol allocator */
626 static Sym *__sym_malloc(void)
628 Sym *sym_pool, *sym, *last_sym;
629 int i;
631 sym_pool = tcc_malloc(SYM_POOL_NB * sizeof(Sym));
632 dynarray_add(&sym_pools, &nb_sym_pools, sym_pool);
634 last_sym = sym_free_first;
635 sym = sym_pool;
636 for(i = 0; i < SYM_POOL_NB; i++) {
637 sym->next = last_sym;
638 last_sym = sym;
639 sym++;
641 sym_free_first = last_sym;
642 return last_sym;
645 static inline Sym *sym_malloc(void)
647 Sym *sym;
648 sym = sym_free_first;
649 if (!sym)
650 sym = __sym_malloc();
651 sym_free_first = sym->next;
652 return sym;
655 static inline void sym_free(Sym *sym)
657 sym->next = sym_free_first;
658 sym_free_first = sym;
661 Section *new_section(TCCState *s1, const char *name, int sh_type, int sh_flags)
663 Section *sec;
665 sec = tcc_mallocz(sizeof(Section) + strlen(name));
666 strcpy(sec->name, name);
667 sec->sh_type = sh_type;
668 sec->sh_flags = sh_flags;
669 switch(sh_type) {
670 case SHT_HASH:
671 case SHT_REL:
672 case SHT_RELA:
673 case SHT_DYNSYM:
674 case SHT_SYMTAB:
675 case SHT_DYNAMIC:
676 sec->sh_addralign = 4;
677 break;
678 case SHT_STRTAB:
679 sec->sh_addralign = 1;
680 break;
681 default:
682 sec->sh_addralign = 32; /* default conservative alignment */
683 break;
686 if (sh_flags & SHF_PRIVATE) {
687 dynarray_add((void ***)&s1->priv_sections, &s1->nb_priv_sections, sec);
688 } else {
689 sec->sh_num = s1->nb_sections;
690 dynarray_add((void ***)&s1->sections, &s1->nb_sections, sec);
693 return sec;
696 static void free_section(Section *s)
698 tcc_free(s->data);
701 /* realloc section and set its content to zero */
702 static void section_realloc(Section *sec, unsigned long new_size)
704 unsigned long size;
705 unsigned char *data;
707 size = sec->data_allocated;
708 if (size == 0)
709 size = 1;
710 while (size < new_size)
711 size = size * 2;
712 data = tcc_realloc(sec->data, size);
713 if (!data)
714 error("memory full");
715 memset(data + sec->data_allocated, 0, size - sec->data_allocated);
716 sec->data = data;
717 sec->data_allocated = size;
720 /* reserve at least 'size' bytes in section 'sec' from
721 sec->data_offset. */
722 static void *section_ptr_add(Section *sec, unsigned long size)
724 unsigned long offset, offset1;
726 offset = sec->data_offset;
727 offset1 = offset + size;
728 if (offset1 > sec->data_allocated)
729 section_realloc(sec, offset1);
730 sec->data_offset = offset1;
731 return sec->data + offset;
734 /* return a reference to a section, and create it if it does not
735 exists */
736 Section *find_section(TCCState *s1, const char *name)
738 Section *sec;
739 int i;
740 for(i = 1; i < s1->nb_sections; i++) {
741 sec = s1->sections[i];
742 if (!strcmp(name, sec->name))
743 return sec;
745 /* sections are created as PROGBITS */
746 return new_section(s1, name, SHT_PROGBITS, SHF_ALLOC);
749 /* update sym->c so that it points to an external symbol in section
750 'section' with value 'value' */
751 static void put_extern_sym2(Sym *sym, Section *section,
752 unsigned long value, unsigned long size,
753 int can_add_underscore)
755 int sym_type, sym_bind, sh_num, info, other, attr;
756 ElfW(Sym) *esym;
757 const char *name;
758 char buf1[256];
760 if (section == NULL)
761 sh_num = SHN_UNDEF;
762 else if (section == SECTION_ABS)
763 sh_num = SHN_ABS;
764 else
765 sh_num = section->sh_num;
767 other = attr = 0;
769 if ((sym->type.t & VT_BTYPE) == VT_FUNC) {
770 sym_type = STT_FUNC;
771 #ifdef TCC_TARGET_PE
772 if (sym->type.ref)
773 attr = sym->type.ref->r;
774 if (FUNC_EXPORT(attr))
775 other |= 1;
776 if (FUNC_CALL(attr) == FUNC_STDCALL)
777 other |= 2;
778 #endif
779 } else if ((sym->type.t & VT_BTYPE) == VT_VOID) {
780 sym_type = STT_NOTYPE;
781 } else {
782 sym_type = STT_OBJECT;
785 if (sym->type.t & VT_STATIC)
786 sym_bind = STB_LOCAL;
787 else
788 sym_bind = STB_GLOBAL;
790 if (!sym->c) {
791 name = get_tok_str(sym->v, NULL);
792 #ifdef CONFIG_TCC_BCHECK
793 if (tcc_state->do_bounds_check) {
794 char buf[32];
796 /* XXX: avoid doing that for statics ? */
797 /* if bound checking is activated, we change some function
798 names by adding the "__bound" prefix */
799 switch(sym->v) {
800 #if 0
801 /* XXX: we rely only on malloc hooks */
802 case TOK_malloc:
803 case TOK_free:
804 case TOK_realloc:
805 case TOK_memalign:
806 case TOK_calloc:
807 #endif
808 case TOK_memcpy:
809 case TOK_memmove:
810 case TOK_memset:
811 case TOK_strlen:
812 case TOK_strcpy:
813 case TOK_alloca:
814 strcpy(buf, "__bound_");
815 strcat(buf, name);
816 name = buf;
817 break;
820 #endif
822 #ifdef TCC_TARGET_PE
823 if ((other & 2) && can_add_underscore) {
824 sprintf(buf1, "_%s@%d", name, FUNC_ARGS(attr));
825 name = buf1;
826 } else
827 #endif
828 if (tcc_state->leading_underscore && can_add_underscore) {
829 buf1[0] = '_';
830 pstrcpy(buf1 + 1, sizeof(buf1) - 1, name);
831 name = buf1;
833 info = ELFW(ST_INFO)(sym_bind, sym_type);
834 sym->c = add_elf_sym(symtab_section, value, size, info, other, sh_num, name);
835 } else {
836 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
837 esym->st_value = value;
838 esym->st_size = size;
839 esym->st_shndx = sh_num;
840 esym->st_other |= other;
844 static void put_extern_sym(Sym *sym, Section *section,
845 unsigned long value, unsigned long size)
847 put_extern_sym2(sym, section, value, size, 1);
850 /* add a new relocation entry to symbol 'sym' in section 's' */
851 static void greloc(Section *s, Sym *sym, unsigned long offset, int type)
853 int c = 0;
854 if (sym) {
855 if (0 == sym->c)
856 put_extern_sym(sym, NULL, 0, 0);
857 c = sym->c;
859 /* now we can add ELF relocation info */
860 put_elf_reloc(symtab_section, s, offset, type, c);
863 static void strcat_vprintf(char *buf, int buf_size, const char *fmt, va_list ap)
865 int len;
866 len = strlen(buf);
867 vsnprintf(buf + len, buf_size - len, fmt, ap);
870 static void strcat_printf(char *buf, int buf_size, const char *fmt, ...)
872 va_list ap;
873 va_start(ap, fmt);
874 strcat_vprintf(buf, buf_size, fmt, ap);
875 va_end(ap);
878 void error1(TCCState *s1, int is_warning, const char *fmt, va_list ap)
880 char buf[2048];
881 BufferedFile **f;
883 buf[0] = '\0';
884 if (file) {
885 for(f = s1->include_stack; f < s1->include_stack_ptr; f++)
886 strcat_printf(buf, sizeof(buf), "In file included from %s:%d:\n",
887 (*f)->filename, (*f)->line_num);
888 if (file->line_num > 0) {
889 strcat_printf(buf, sizeof(buf),
890 "%s:%d: ", file->filename, file->line_num);
891 } else {
892 strcat_printf(buf, sizeof(buf),
893 "%s: ", file->filename);
895 } else {
896 strcat_printf(buf, sizeof(buf),
897 "tcc: ");
899 if (is_warning)
900 strcat_printf(buf, sizeof(buf), "warning: ");
901 else
902 strcat_printf(buf, sizeof(buf), "error: ");
903 strcat_vprintf(buf, sizeof(buf), fmt, ap);
905 if (!s1->error_func) {
906 /* default case: stderr */
907 fprintf(stderr, "%s\n", buf);
908 } else {
909 s1->error_func(s1->error_opaque, buf);
911 if (!is_warning || s1->warn_error)
912 s1->nb_errors++;
915 void tcc_set_error_func(TCCState *s, void *error_opaque,
916 void (*error_func)(void *opaque, const char *msg))
918 s->error_opaque = error_opaque;
919 s->error_func = error_func;
922 /* error without aborting current compilation */
923 void error_noabort(const char *fmt, ...)
925 TCCState *s1 = tcc_state;
926 va_list ap;
928 va_start(ap, fmt);
929 error1(s1, 0, fmt, ap);
930 va_end(ap);
933 void error(const char *fmt, ...)
935 TCCState *s1 = tcc_state;
936 va_list ap;
938 va_start(ap, fmt);
939 error1(s1, 0, fmt, ap);
940 va_end(ap);
941 /* better than nothing: in some cases, we accept to handle errors */
942 if (s1->error_set_jmp_enabled) {
943 longjmp(s1->error_jmp_buf, 1);
944 } else {
945 /* XXX: eliminate this someday */
946 exit(1);
950 void expect(const char *msg)
952 error("%s expected", msg);
955 void warning(const char *fmt, ...)
957 TCCState *s1 = tcc_state;
958 va_list ap;
960 if (s1->warn_none)
961 return;
963 va_start(ap, fmt);
964 error1(s1, 1, fmt, ap);
965 va_end(ap);
968 void skip(int c)
970 if (tok != c)
971 error("'%c' expected", c);
972 next();
975 static void test_lvalue(void)
977 if (!(vtop->r & VT_LVAL))
978 expect("lvalue");
981 /* CString handling */
983 static void cstr_realloc(CString *cstr, int new_size)
985 int size;
986 void *data;
988 size = cstr->size_allocated;
989 if (size == 0)
990 size = 8; /* no need to allocate a too small first string */
991 while (size < new_size)
992 size = size * 2;
993 data = tcc_realloc(cstr->data_allocated, size);
994 if (!data)
995 error("memory full");
996 cstr->data_allocated = data;
997 cstr->size_allocated = size;
998 cstr->data = data;
1001 /* add a byte */
1002 static inline void cstr_ccat(CString *cstr, int ch)
1004 int size;
1005 size = cstr->size + 1;
1006 if (size > cstr->size_allocated)
1007 cstr_realloc(cstr, size);
1008 ((unsigned char *)cstr->data)[size - 1] = ch;
1009 cstr->size = size;
1012 static void cstr_cat(CString *cstr, const char *str)
1014 int c;
1015 for(;;) {
1016 c = *str;
1017 if (c == '\0')
1018 break;
1019 cstr_ccat(cstr, c);
1020 str++;
1024 /* add a wide char */
1025 static void cstr_wccat(CString *cstr, int ch)
1027 int size;
1028 size = cstr->size + sizeof(nwchar_t);
1029 if (size > cstr->size_allocated)
1030 cstr_realloc(cstr, size);
1031 *(nwchar_t *)(((unsigned char *)cstr->data) + size - sizeof(nwchar_t)) = ch;
1032 cstr->size = size;
1035 static void cstr_new(CString *cstr)
1037 memset(cstr, 0, sizeof(CString));
1040 /* free string and reset it to NULL */
1041 static void cstr_free(CString *cstr)
1043 tcc_free(cstr->data_allocated);
1044 cstr_new(cstr);
1047 #define cstr_reset(cstr) cstr_free(cstr)
1049 /* XXX: unicode ? */
1050 static void add_char(CString *cstr, int c)
1052 if (c == '\'' || c == '\"' || c == '\\') {
1053 /* XXX: could be more precise if char or string */
1054 cstr_ccat(cstr, '\\');
1056 if (c >= 32 && c <= 126) {
1057 cstr_ccat(cstr, c);
1058 } else {
1059 cstr_ccat(cstr, '\\');
1060 if (c == '\n') {
1061 cstr_ccat(cstr, 'n');
1062 } else {
1063 cstr_ccat(cstr, '0' + ((c >> 6) & 7));
1064 cstr_ccat(cstr, '0' + ((c >> 3) & 7));
1065 cstr_ccat(cstr, '0' + (c & 7));
1070 /* push, without hashing */
1071 static Sym *sym_push2(Sym **ps, int v, int t, long c)
1073 Sym *s;
1074 s = sym_malloc();
1075 s->v = v;
1076 s->type.t = t;
1077 s->type.ref = NULL;
1078 #ifdef _WIN64
1079 s->d = NULL;
1080 #endif
1081 s->c = c;
1082 s->next = NULL;
1083 /* add in stack */
1084 s->prev = *ps;
1085 *ps = s;
1086 return s;
1089 /* find a symbol and return its associated structure. 's' is the top
1090 of the symbol stack */
1091 static Sym *sym_find2(Sym *s, int v)
1093 while (s) {
1094 if (s->v == v)
1095 return s;
1096 s = s->prev;
1098 return NULL;
1101 /* structure lookup */
1102 static inline Sym *struct_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_struct;
1110 /* find an identifier */
1111 static inline Sym *sym_find(int v)
1113 v -= TOK_IDENT;
1114 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1115 return NULL;
1116 return table_ident[v]->sym_identifier;
1119 /* push a given symbol on the symbol stack */
1120 static Sym *sym_push(int v, CType *type, int r, int c)
1122 Sym *s, **ps;
1123 TokenSym *ts;
1125 if (local_stack)
1126 ps = &local_stack;
1127 else
1128 ps = &global_stack;
1129 s = sym_push2(ps, v, type->t, c);
1130 s->type.ref = type->ref;
1131 s->r = r;
1132 /* don't record fields or anonymous symbols */
1133 /* XXX: simplify */
1134 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
1135 /* record symbol in token array */
1136 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
1137 if (v & SYM_STRUCT)
1138 ps = &ts->sym_struct;
1139 else
1140 ps = &ts->sym_identifier;
1141 s->prev_tok = *ps;
1142 *ps = s;
1144 return s;
1147 /* push a global identifier */
1148 static Sym *global_identifier_push(int v, int t, int c)
1150 Sym *s, **ps;
1151 s = sym_push2(&global_stack, v, t, c);
1152 /* don't record anonymous symbol */
1153 if (v < SYM_FIRST_ANOM) {
1154 ps = &table_ident[v - TOK_IDENT]->sym_identifier;
1155 /* modify the top most local identifier, so that
1156 sym_identifier will point to 's' when popped */
1157 while (*ps != NULL)
1158 ps = &(*ps)->prev_tok;
1159 s->prev_tok = NULL;
1160 *ps = s;
1162 return s;
1165 /* pop symbols until top reaches 'b' */
1166 static void sym_pop(Sym **ptop, Sym *b)
1168 Sym *s, *ss, **ps;
1169 TokenSym *ts;
1170 int v;
1172 s = *ptop;
1173 while(s != b) {
1174 ss = s->prev;
1175 v = s->v;
1176 /* remove symbol in token array */
1177 /* XXX: simplify */
1178 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
1179 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
1180 if (v & SYM_STRUCT)
1181 ps = &ts->sym_struct;
1182 else
1183 ps = &ts->sym_identifier;
1184 *ps = s->prev_tok;
1186 sym_free(s);
1187 s = ss;
1189 *ptop = b;
1192 /* I/O layer */
1194 BufferedFile *tcc_open(TCCState *s1, const char *filename)
1196 int fd;
1197 BufferedFile *bf;
1199 if (strcmp(filename, "-") == 0)
1200 fd = 0, filename = "stdin";
1201 else
1202 fd = open(filename, O_RDONLY | O_BINARY);
1203 if ((s1->verbose == 2 && fd >= 0) || s1->verbose == 3)
1204 printf("%s %*s%s\n", fd < 0 ? "nf":"->",
1205 (int)(s1->include_stack_ptr - s1->include_stack), "", filename);
1206 if (fd < 0)
1207 return NULL;
1208 bf = tcc_malloc(sizeof(BufferedFile));
1209 bf->fd = fd;
1210 bf->buf_ptr = bf->buffer;
1211 bf->buf_end = bf->buffer;
1212 bf->buffer[0] = CH_EOB; /* put eob symbol */
1213 pstrcpy(bf->filename, sizeof(bf->filename), filename);
1214 #ifdef _WIN32
1215 normalize_slashes(bf->filename);
1216 #endif
1217 bf->line_num = 1;
1218 bf->ifndef_macro = 0;
1219 bf->ifdef_stack_ptr = s1->ifdef_stack_ptr;
1220 // printf("opening '%s'\n", filename);
1221 return bf;
1224 void tcc_close(BufferedFile *bf)
1226 total_lines += bf->line_num;
1227 close(bf->fd);
1228 tcc_free(bf);
1231 /* compile the C file opened in 'file'. Return non zero if errors. */
1232 static int tcc_compile(TCCState *s1)
1234 Sym *define_start;
1235 char buf[512];
1236 volatile int section_sym;
1238 #ifdef INC_DEBUG
1239 printf("%s: **** new file\n", file->filename);
1240 #endif
1241 preprocess_init(s1);
1243 cur_text_section = NULL;
1244 funcname = "";
1245 anon_sym = SYM_FIRST_ANOM;
1247 /* file info: full path + filename */
1248 section_sym = 0; /* avoid warning */
1249 if (s1->do_debug) {
1250 section_sym = put_elf_sym(symtab_section, 0, 0,
1251 ELFW(ST_INFO)(STB_LOCAL, STT_SECTION), 0,
1252 text_section->sh_num, NULL);
1253 getcwd(buf, sizeof(buf));
1254 #ifdef _WIN32
1255 normalize_slashes(buf);
1256 #endif
1257 pstrcat(buf, sizeof(buf), "/");
1258 put_stabs_r(buf, N_SO, 0, 0,
1259 text_section->data_offset, text_section, section_sym);
1260 put_stabs_r(file->filename, N_SO, 0, 0,
1261 text_section->data_offset, text_section, section_sym);
1263 /* an elf symbol of type STT_FILE must be put so that STB_LOCAL
1264 symbols can be safely used */
1265 put_elf_sym(symtab_section, 0, 0,
1266 ELFW(ST_INFO)(STB_LOCAL, STT_FILE), 0,
1267 SHN_ABS, file->filename);
1269 /* define some often used types */
1270 int_type.t = VT_INT;
1272 char_pointer_type.t = VT_BYTE;
1273 mk_pointer(&char_pointer_type);
1275 func_old_type.t = VT_FUNC;
1276 func_old_type.ref = sym_push(SYM_FIELD, &int_type, FUNC_CDECL, FUNC_OLD);
1278 #if defined(TCC_ARM_EABI) && defined(TCC_ARM_VFP)
1279 float_type.t = VT_FLOAT;
1280 double_type.t = VT_DOUBLE;
1282 func_float_type.t = VT_FUNC;
1283 func_float_type.ref = sym_push(SYM_FIELD, &float_type, FUNC_CDECL, FUNC_OLD);
1284 func_double_type.t = VT_FUNC;
1285 func_double_type.ref = sym_push(SYM_FIELD, &double_type, FUNC_CDECL, FUNC_OLD);
1286 #endif
1288 #if 0
1289 /* define 'void *alloca(unsigned int)' builtin function */
1291 Sym *s1;
1293 p = anon_sym++;
1294 sym = sym_push(p, mk_pointer(VT_VOID), FUNC_CDECL, FUNC_NEW);
1295 s1 = sym_push(SYM_FIELD, VT_UNSIGNED | VT_INT, 0, 0);
1296 s1->next = NULL;
1297 sym->next = s1;
1298 sym_push(TOK_alloca, VT_FUNC | (p << VT_STRUCT_SHIFT), VT_CONST, 0);
1300 #endif
1302 define_start = define_stack;
1303 nocode_wanted = 1;
1305 if (setjmp(s1->error_jmp_buf) == 0) {
1306 s1->nb_errors = 0;
1307 s1->error_set_jmp_enabled = 1;
1309 ch = file->buf_ptr[0];
1310 tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
1311 parse_flags = PARSE_FLAG_PREPROCESS | PARSE_FLAG_TOK_NUM;
1312 next();
1313 decl(VT_CONST);
1314 if (tok != TOK_EOF)
1315 expect("declaration");
1317 /* end of translation unit info */
1318 if (s1->do_debug) {
1319 put_stabs_r(NULL, N_SO, 0, 0,
1320 text_section->data_offset, text_section, section_sym);
1323 s1->error_set_jmp_enabled = 0;
1325 /* reset define stack, but leave -Dsymbols (may be incorrect if
1326 they are undefined) */
1327 free_defines(define_start);
1329 gen_inline_functions();
1331 sym_pop(&global_stack, NULL);
1332 sym_pop(&local_stack, NULL);
1334 return s1->nb_errors != 0 ? -1 : 0;
1337 int tcc_compile_string(TCCState *s, const char *str)
1339 BufferedFile bf1, *bf = &bf1;
1340 int ret, len;
1341 char *buf;
1343 /* init file structure */
1344 bf->fd = -1;
1345 /* XXX: avoid copying */
1346 len = strlen(str);
1347 buf = tcc_malloc(len + 1);
1348 if (!buf)
1349 return -1;
1350 memcpy(buf, str, len);
1351 buf[len] = CH_EOB;
1352 bf->buf_ptr = buf;
1353 bf->buf_end = buf + len;
1354 pstrcpy(bf->filename, sizeof(bf->filename), "<string>");
1355 bf->line_num = 1;
1356 file = bf;
1357 ret = tcc_compile(s);
1358 file = NULL;
1359 tcc_free(buf);
1361 /* currently, no need to close */
1362 return ret;
1365 /* define a preprocessor symbol. A value can also be provided with the '=' operator */
1366 void tcc_define_symbol(TCCState *s1, const char *sym, const char *value)
1368 BufferedFile bf1, *bf = &bf1;
1370 pstrcpy(bf->buffer, IO_BUF_SIZE, sym);
1371 pstrcat(bf->buffer, IO_BUF_SIZE, " ");
1372 /* default value */
1373 if (!value)
1374 value = "1";
1375 pstrcat(bf->buffer, IO_BUF_SIZE, value);
1377 /* init file structure */
1378 bf->fd = -1;
1379 bf->buf_ptr = bf->buffer;
1380 bf->buf_end = bf->buffer + strlen(bf->buffer);
1381 *bf->buf_end = CH_EOB;
1382 bf->filename[0] = '\0';
1383 bf->line_num = 1;
1384 file = bf;
1386 s1->include_stack_ptr = s1->include_stack;
1388 /* parse with define parser */
1389 ch = file->buf_ptr[0];
1390 next_nomacro();
1391 parse_define();
1392 file = NULL;
1395 /* undefine a preprocessor symbol */
1396 void tcc_undefine_symbol(TCCState *s1, const char *sym)
1398 TokenSym *ts;
1399 Sym *s;
1400 ts = tok_alloc(sym, strlen(sym));
1401 s = define_find(ts->tok);
1402 /* undefine symbol by putting an invalid name */
1403 if (s)
1404 define_undef(s);
1408 #ifdef CONFIG_TCC_BACKTRACE
1409 /* print the position in the source file of PC value 'pc' by reading
1410 the stabs debug information */
1411 static unsigned long rt_printline(unsigned long wanted_pc)
1413 Stab_Sym *sym, *sym_end;
1414 char func_name[128], last_func_name[128];
1415 unsigned long func_addr, last_pc, pc;
1416 const char *incl_files[INCLUDE_STACK_SIZE];
1417 int incl_index, len, last_line_num, i;
1418 const char *str, *p;
1420 fprintf(stderr, "0x%08lx:", wanted_pc);
1422 func_name[0] = '\0';
1423 func_addr = 0;
1424 incl_index = 0;
1425 last_func_name[0] = '\0';
1426 last_pc = 0xffffffff;
1427 last_line_num = 1;
1428 sym = (Stab_Sym *)stab_section->data + 1;
1429 sym_end = (Stab_Sym *)(stab_section->data + stab_section->data_offset);
1430 while (sym < sym_end) {
1431 switch(sym->n_type) {
1432 /* function start or end */
1433 case N_FUN:
1434 if (sym->n_strx == 0) {
1435 /* we test if between last line and end of function */
1436 pc = sym->n_value + func_addr;
1437 if (wanted_pc >= last_pc && wanted_pc < pc)
1438 goto found;
1439 func_name[0] = '\0';
1440 func_addr = 0;
1441 } else {
1442 str = stabstr_section->data + sym->n_strx;
1443 p = strchr(str, ':');
1444 if (!p) {
1445 pstrcpy(func_name, sizeof(func_name), str);
1446 } else {
1447 len = p - str;
1448 if (len > sizeof(func_name) - 1)
1449 len = sizeof(func_name) - 1;
1450 memcpy(func_name, str, len);
1451 func_name[len] = '\0';
1453 func_addr = sym->n_value;
1455 break;
1456 /* line number info */
1457 case N_SLINE:
1458 pc = sym->n_value + func_addr;
1459 if (wanted_pc >= last_pc && wanted_pc < pc)
1460 goto found;
1461 last_pc = pc;
1462 last_line_num = sym->n_desc;
1463 /* XXX: slow! */
1464 strcpy(last_func_name, func_name);
1465 break;
1466 /* include files */
1467 case N_BINCL:
1468 str = stabstr_section->data + sym->n_strx;
1469 add_incl:
1470 if (incl_index < INCLUDE_STACK_SIZE) {
1471 incl_files[incl_index++] = str;
1473 break;
1474 case N_EINCL:
1475 if (incl_index > 1)
1476 incl_index--;
1477 break;
1478 case N_SO:
1479 if (sym->n_strx == 0) {
1480 incl_index = 0; /* end of translation unit */
1481 } else {
1482 str = stabstr_section->data + sym->n_strx;
1483 /* do not add path */
1484 len = strlen(str);
1485 if (len > 0 && str[len - 1] != '/')
1486 goto add_incl;
1488 break;
1490 sym++;
1493 /* second pass: we try symtab symbols (no line number info) */
1494 incl_index = 0;
1496 ElfW(Sym) *sym, *sym_end;
1497 int type;
1499 sym_end = (ElfW(Sym) *)(symtab_section->data + symtab_section->data_offset);
1500 for(sym = (ElfW(Sym) *)symtab_section->data + 1;
1501 sym < sym_end;
1502 sym++) {
1503 type = ELFW(ST_TYPE)(sym->st_info);
1504 if (type == STT_FUNC) {
1505 if (wanted_pc >= sym->st_value &&
1506 wanted_pc < sym->st_value + sym->st_size) {
1507 pstrcpy(last_func_name, sizeof(last_func_name),
1508 strtab_section->data + sym->st_name);
1509 func_addr = sym->st_value;
1510 goto found;
1515 /* did not find any info: */
1516 fprintf(stderr, " ???\n");
1517 return 0;
1518 found:
1519 if (last_func_name[0] != '\0') {
1520 fprintf(stderr, " %s()", last_func_name);
1522 if (incl_index > 0) {
1523 fprintf(stderr, " (%s:%d",
1524 incl_files[incl_index - 1], last_line_num);
1525 for(i = incl_index - 2; i >= 0; i--)
1526 fprintf(stderr, ", included from %s", incl_files[i]);
1527 fprintf(stderr, ")");
1529 fprintf(stderr, "\n");
1530 return func_addr;
1533 #ifdef __i386__
1534 /* fix for glibc 2.1 */
1535 #ifndef REG_EIP
1536 #define REG_EIP EIP
1537 #define REG_EBP EBP
1538 #endif
1540 /* return the PC at frame level 'level'. Return non zero if not found */
1541 static int rt_get_caller_pc(unsigned long *paddr,
1542 ucontext_t *uc, int level)
1544 unsigned long fp;
1545 int i;
1547 if (level == 0) {
1548 #if defined(__FreeBSD__)
1549 *paddr = uc->uc_mcontext.mc_eip;
1550 #elif defined(__dietlibc__)
1551 *paddr = uc->uc_mcontext.eip;
1552 #else
1553 *paddr = uc->uc_mcontext.gregs[REG_EIP];
1554 #endif
1555 return 0;
1556 } else {
1557 #if defined(__FreeBSD__)
1558 fp = uc->uc_mcontext.mc_ebp;
1559 #elif defined(__dietlibc__)
1560 fp = uc->uc_mcontext.ebp;
1561 #else
1562 fp = uc->uc_mcontext.gregs[REG_EBP];
1563 #endif
1564 for(i=1;i<level;i++) {
1565 /* XXX: check address validity with program info */
1566 if (fp <= 0x1000 || fp >= 0xc0000000)
1567 return -1;
1568 fp = ((unsigned long *)fp)[0];
1570 *paddr = ((unsigned long *)fp)[1];
1571 return 0;
1574 #elif defined(__x86_64__)
1575 /* return the PC at frame level 'level'. Return non zero if not found */
1576 static int rt_get_caller_pc(unsigned long *paddr,
1577 ucontext_t *uc, int level)
1579 unsigned long fp;
1580 int i;
1582 if (level == 0) {
1583 /* XXX: only support linux */
1584 #if defined(__FreeBSD__)
1585 *paddr = uc->uc_mcontext.mc_rip;
1586 #else
1587 *paddr = uc->uc_mcontext.gregs[REG_RIP];
1588 #endif
1589 return 0;
1590 } else {
1591 #if defined(__FreeBSD__)
1592 fp = uc->uc_mcontext.mc_rbp;
1593 #else
1594 fp = uc->uc_mcontext.gregs[REG_RBP];
1595 #endif
1596 for(i=1;i<level;i++) {
1597 /* XXX: check address validity with program info */
1598 if (fp <= 0x1000)
1599 return -1;
1600 fp = ((unsigned long *)fp)[0];
1602 *paddr = ((unsigned long *)fp)[1];
1603 return 0;
1606 #else
1607 #warning add arch specific rt_get_caller_pc()
1608 static int rt_get_caller_pc(unsigned long *paddr,
1609 ucontext_t *uc, int level)
1611 return -1;
1613 #endif
1615 /* emit a run time error at position 'pc' */
1616 void rt_error(ucontext_t *uc, const char *fmt, ...)
1618 va_list ap;
1619 unsigned long pc;
1620 int i;
1622 va_start(ap, fmt);
1623 fprintf(stderr, "Runtime error: ");
1624 vfprintf(stderr, fmt, ap);
1625 fprintf(stderr, "\n");
1626 for(i=0;i<num_callers;i++) {
1627 if (rt_get_caller_pc(&pc, uc, i) < 0)
1628 break;
1629 if (i == 0)
1630 fprintf(stderr, "at ");
1631 else
1632 fprintf(stderr, "by ");
1633 pc = rt_printline(pc);
1634 if (pc == rt_prog_main && pc)
1635 break;
1637 exit(255);
1638 va_end(ap);
1641 /* signal handler for fatal errors */
1642 static void sig_error(int signum, siginfo_t *siginf, void *puc)
1644 ucontext_t *uc = puc;
1646 switch(signum) {
1647 case SIGFPE:
1648 switch(siginf->si_code) {
1649 case FPE_INTDIV:
1650 case FPE_FLTDIV:
1651 rt_error(uc, "division by zero");
1652 break;
1653 default:
1654 rt_error(uc, "floating point exception");
1655 break;
1657 break;
1658 case SIGBUS:
1659 case SIGSEGV:
1660 if (rt_bound_error_msg && *rt_bound_error_msg)
1661 rt_error(uc, *rt_bound_error_msg);
1662 else
1663 rt_error(uc, "dereferencing invalid pointer");
1664 break;
1665 case SIGILL:
1666 rt_error(uc, "illegal instruction");
1667 break;
1668 case SIGABRT:
1669 rt_error(uc, "abort() called");
1670 break;
1671 default:
1672 rt_error(uc, "caught signal %d", signum);
1673 break;
1675 exit(255);
1678 #endif
1680 /* copy code into memory passed in by the caller and do all relocations
1681 (needed before using tcc_get_symbol()).
1682 returns -1 on error and required size if ptr is NULL */
1683 int tcc_relocate(TCCState *s1, void *ptr)
1685 Section *s;
1686 unsigned long offset, length;
1687 uplong mem;
1688 int i;
1690 if (0 == s1->runtime_added) {
1691 s1->runtime_added = 1;
1692 s1->nb_errors = 0;
1693 #ifdef TCC_TARGET_PE
1694 pe_output_file(s1, NULL);
1695 #else
1696 tcc_add_runtime(s1);
1697 relocate_common_syms();
1698 tcc_add_linker_symbols(s1);
1699 build_got_entries(s1);
1700 #endif
1701 if (s1->nb_errors)
1702 return -1;
1705 offset = 0, mem = (uplong)ptr;
1706 for(i = 1; i < s1->nb_sections; i++) {
1707 s = s1->sections[i];
1708 if (0 == (s->sh_flags & SHF_ALLOC))
1709 continue;
1710 length = s->data_offset;
1711 s->sh_addr = mem ? (mem + offset + 15) & ~15 : 0;
1712 offset = (offset + length + 15) & ~15;
1715 /* relocate symbols */
1716 relocate_syms(s1, 1);
1717 if (s1->nb_errors)
1718 return -1;
1720 #ifndef TCC_TARGET_PE
1721 #ifdef TCC_TARGET_X86_64
1722 s1->runtime_plt_and_got_offset = 0;
1723 s1->runtime_plt_and_got = (char *)(mem + offset);
1724 /* double the size of the buffer for got and plt entries
1725 XXX: calculate exact size for them? */
1726 offset *= 2;
1727 #endif
1728 #endif
1730 if (0 == mem)
1731 return offset + 15;
1733 /* relocate each section */
1734 for(i = 1; i < s1->nb_sections; i++) {
1735 s = s1->sections[i];
1736 if (s->reloc)
1737 relocate_section(s1, s);
1740 for(i = 1; i < s1->nb_sections; i++) {
1741 s = s1->sections[i];
1742 if (0 == (s->sh_flags & SHF_ALLOC))
1743 continue;
1744 length = s->data_offset;
1745 // printf("%-12s %08x %04x\n", s->name, s->sh_addr, length);
1746 ptr = (void*)(uplong)s->sh_addr;
1747 if (NULL == s->data || s->sh_type == SHT_NOBITS)
1748 memset(ptr, 0, length);
1749 else
1750 memcpy(ptr, s->data, length);
1751 /* mark executable sections as executable in memory */
1752 if (s->sh_flags & SHF_EXECINSTR)
1753 set_pages_executable(ptr, length);
1755 #ifndef TCC_TARGET_PE
1756 #ifdef TCC_TARGET_X86_64
1757 set_pages_executable(s1->runtime_plt_and_got,
1758 s1->runtime_plt_and_got_offset);
1759 #endif
1760 #endif
1761 return 0;
1764 /* launch the compiled program with the given arguments */
1765 int tcc_run(TCCState *s1, int argc, char **argv)
1767 int (*prog_main)(int, char **);
1768 void *ptr;
1769 int ret;
1771 ret = tcc_relocate(s1, NULL);
1772 if (ret < 0)
1773 return -1;
1774 ptr = tcc_malloc(ret);
1775 tcc_relocate(s1, ptr);
1777 prog_main = tcc_get_symbol_err(s1, "main");
1779 if (s1->do_debug) {
1780 #ifdef CONFIG_TCC_BACKTRACE
1781 struct sigaction sigact;
1782 /* install TCC signal handlers to print debug info on fatal
1783 runtime errors */
1784 sigact.sa_flags = SA_SIGINFO | SA_RESETHAND;
1785 sigact.sa_sigaction = sig_error;
1786 sigemptyset(&sigact.sa_mask);
1787 sigaction(SIGFPE, &sigact, NULL);
1788 sigaction(SIGILL, &sigact, NULL);
1789 sigaction(SIGSEGV, &sigact, NULL);
1790 sigaction(SIGBUS, &sigact, NULL);
1791 sigaction(SIGABRT, &sigact, NULL);
1792 #else
1793 error("debug mode not available");
1794 #endif
1797 #ifdef CONFIG_TCC_BCHECK
1798 if (s1->do_bounds_check) {
1799 void (*bound_init)(void);
1800 void (*bound_exit)(void);
1801 /* set error function */
1802 rt_bound_error_msg = tcc_get_symbol_err(s1, "__bound_error_msg");
1803 rt_prog_main = (unsigned long)prog_main;
1804 /* XXX: use .init section so that it also work in binary ? */
1805 bound_init = tcc_get_symbol_err(s1, "__bound_init");
1806 bound_exit = tcc_get_symbol_err(s1, "__bound_exit");
1807 bound_init();
1808 ret = (*prog_main)(argc, argv);
1809 bound_exit();
1810 } else
1811 #endif
1812 ret = (*prog_main)(argc, argv);
1813 tcc_free(ptr);
1814 return ret;
1817 void tcc_memstats(void)
1819 #ifdef MEM_DEBUG
1820 printf("memory in use: %d\n", mem_cur_size);
1821 #endif
1824 static void tcc_cleanup(void)
1826 int i, n;
1828 if (NULL == tcc_state)
1829 return;
1830 tcc_state = NULL;
1832 /* free -D defines */
1833 free_defines(NULL);
1835 /* free tokens */
1836 n = tok_ident - TOK_IDENT;
1837 for(i = 0; i < n; i++)
1838 tcc_free(table_ident[i]);
1839 tcc_free(table_ident);
1841 /* free sym_pools */
1842 dynarray_reset(&sym_pools, &nb_sym_pools);
1843 /* string buffer */
1844 cstr_free(&tokcstr);
1845 /* reset symbol stack */
1846 sym_free_first = NULL;
1847 /* cleanup from error/setjmp */
1848 macro_ptr = NULL;
1851 TCCState *tcc_new(void)
1853 TCCState *s;
1854 char buffer[100];
1855 int a,b,c;
1857 tcc_cleanup();
1859 s = tcc_mallocz(sizeof(TCCState));
1860 if (!s)
1861 return NULL;
1862 tcc_state = s;
1863 #ifdef _WIN32
1864 tcc_set_lib_path_w32(s);
1865 #else
1866 tcc_set_lib_path(s, CONFIG_TCCDIR);
1867 #endif
1868 s->output_type = TCC_OUTPUT_MEMORY;
1869 preprocess_new();
1871 /* we add dummy defines for some special macros to speed up tests
1872 and to have working defined() */
1873 define_push(TOK___LINE__, MACRO_OBJ, NULL, NULL);
1874 define_push(TOK___FILE__, MACRO_OBJ, NULL, NULL);
1875 define_push(TOK___DATE__, MACRO_OBJ, NULL, NULL);
1876 define_push(TOK___TIME__, MACRO_OBJ, NULL, NULL);
1878 /* standard defines */
1879 tcc_define_symbol(s, "__STDC__", NULL);
1880 tcc_define_symbol(s, "__STDC_VERSION__", "199901L");
1881 #if defined(TCC_TARGET_I386)
1882 tcc_define_symbol(s, "__i386__", "1");
1883 tcc_define_symbol(s, "__i386", "1");
1884 tcc_define_symbol(s, "i386", "1");
1885 #endif
1886 #if defined(TCC_TARGET_X86_64)
1887 tcc_define_symbol(s, "__x86_64__", NULL);
1888 #endif
1889 #if defined(TCC_TARGET_ARM)
1890 tcc_define_symbol(s, "__ARM_ARCH_4__", NULL);
1891 tcc_define_symbol(s, "__arm_elf__", NULL);
1892 tcc_define_symbol(s, "__arm_elf", NULL);
1893 tcc_define_symbol(s, "arm_elf", NULL);
1894 tcc_define_symbol(s, "__arm__", NULL);
1895 tcc_define_symbol(s, "__arm", NULL);
1896 tcc_define_symbol(s, "arm", NULL);
1897 tcc_define_symbol(s, "__APCS_32__", NULL);
1898 #endif
1899 #ifdef TCC_TARGET_PE
1900 tcc_define_symbol(s, "_WIN32", NULL);
1901 #ifdef TCC_TARGET_X86_64
1902 tcc_define_symbol(s, "_WIN64", NULL);
1903 #endif
1904 #else
1905 tcc_define_symbol(s, "__unix__", "1");
1906 tcc_define_symbol(s, "__unix", "1");
1907 tcc_define_symbol(s, "unix", "1");
1908 #if defined(__FreeBSD__)
1909 #define str(s) #s
1910 tcc_define_symbol(s, "__FreeBSD__", str( __FreeBSD__));
1911 tcc_define_symbol(s, "__INTEL_COMPILER", "1");
1912 #undef str
1913 #endif
1914 #if defined(__linux)
1915 tcc_define_symbol(s, "__linux__", NULL);
1916 tcc_define_symbol(s, "__linux", NULL);
1917 #endif
1918 #endif
1919 /* tiny C specific defines */
1920 sscanf(TCC_VERSION, "%d.%d.%d", &a, &b, &c);
1921 sprintf(buffer, "%d", a*10000 + b*100 + c);
1922 tcc_define_symbol(s, "__TINYC__", buffer);
1924 /* tiny C & gcc defines */
1925 tcc_define_symbol(s, "__SIZE_TYPE__", "unsigned long");
1926 tcc_define_symbol(s, "__PTRDIFF_TYPE__", "long");
1927 #ifdef TCC_TARGET_PE
1928 tcc_define_symbol(s, "__WCHAR_TYPE__", "unsigned short");
1929 #else
1930 tcc_define_symbol(s, "__WCHAR_TYPE__", "int");
1931 #endif
1933 #ifndef TCC_TARGET_PE
1934 /* default library paths */
1935 tcc_add_library_path(s, CONFIG_SYSROOT "/usr/local/lib");
1936 tcc_add_library_path(s, CONFIG_SYSROOT "/usr/lib");
1937 tcc_add_library_path(s, CONFIG_SYSROOT "/lib");
1938 #endif
1940 /* no section zero */
1941 dynarray_add((void ***)&s->sections, &s->nb_sections, NULL);
1943 /* create standard sections */
1944 text_section = new_section(s, ".text", SHT_PROGBITS, SHF_ALLOC | SHF_EXECINSTR);
1945 data_section = new_section(s, ".data", SHT_PROGBITS, SHF_ALLOC | SHF_WRITE);
1946 bss_section = new_section(s, ".bss", SHT_NOBITS, SHF_ALLOC | SHF_WRITE);
1948 /* symbols are always generated for linking stage */
1949 symtab_section = new_symtab(s, ".symtab", SHT_SYMTAB, 0,
1950 ".strtab",
1951 ".hashtab", SHF_PRIVATE);
1952 strtab_section = symtab_section->link;
1954 /* private symbol table for dynamic symbols */
1955 s->dynsymtab_section = new_symtab(s, ".dynsymtab", SHT_SYMTAB, SHF_PRIVATE,
1956 ".dynstrtab",
1957 ".dynhashtab", SHF_PRIVATE);
1958 s->alacarte_link = 1;
1960 #ifdef CHAR_IS_UNSIGNED
1961 s->char_is_unsigned = 1;
1962 #endif
1963 #if defined(TCC_TARGET_PE) && 0
1964 /* XXX: currently the PE linker is not ready to support that */
1965 s->leading_underscore = 1;
1966 #endif
1968 if (s->section_align == 0)
1969 s->section_align = ELF_PAGE_SIZE;
1971 #ifdef TCC_TARGET_I386
1972 s->seg_size = 32;
1973 #endif
1974 return s;
1977 void tcc_delete(TCCState *s1)
1979 int i;
1981 tcc_cleanup();
1983 /* free all sections */
1984 for(i = 1; i < s1->nb_sections; i++)
1985 free_section(s1->sections[i]);
1986 dynarray_reset(&s1->sections, &s1->nb_sections);
1988 for(i = 0; i < s1->nb_priv_sections; i++)
1989 free_section(s1->priv_sections[i]);
1990 dynarray_reset(&s1->priv_sections, &s1->nb_priv_sections);
1992 /* free any loaded DLLs */
1993 for ( i = 0; i < s1->nb_loaded_dlls; i++) {
1994 DLLReference *ref = s1->loaded_dlls[i];
1995 if ( ref->handle )
1996 dlclose(ref->handle);
1999 /* free loaded dlls array */
2000 dynarray_reset(&s1->loaded_dlls, &s1->nb_loaded_dlls);
2002 /* free library paths */
2003 dynarray_reset(&s1->library_paths, &s1->nb_library_paths);
2005 /* free include paths */
2006 dynarray_reset(&s1->cached_includes, &s1->nb_cached_includes);
2007 dynarray_reset(&s1->include_paths, &s1->nb_include_paths);
2008 dynarray_reset(&s1->sysinclude_paths, &s1->nb_sysinclude_paths);
2010 tcc_free(s1->tcc_lib_path);
2011 tcc_free(s1);
2014 int tcc_add_include_path(TCCState *s1, const char *pathname)
2016 char *pathname1;
2018 pathname1 = tcc_strdup(pathname);
2019 dynarray_add((void ***)&s1->include_paths, &s1->nb_include_paths, pathname1);
2020 return 0;
2023 int tcc_add_sysinclude_path(TCCState *s1, const char *pathname)
2025 char *pathname1;
2027 pathname1 = tcc_strdup(pathname);
2028 dynarray_add((void ***)&s1->sysinclude_paths, &s1->nb_sysinclude_paths, pathname1);
2029 return 0;
2032 static int tcc_add_file_internal(TCCState *s1, const char *filename, int flags)
2034 const char *ext;
2035 ElfW(Ehdr) ehdr;
2036 int fd, ret, size;
2037 BufferedFile *saved_file;
2039 ret = -1;
2041 /* find source file type with extension */
2042 ext = tcc_fileextension(filename);
2043 if (ext[0])
2044 ext++;
2046 /* open the file */
2047 saved_file = file;
2048 file = tcc_open(s1, filename);
2049 if (!file) {
2050 if (flags & AFF_PRINT_ERROR)
2051 error_noabort("file '%s' not found", filename);
2052 goto the_end;
2055 if (flags & AFF_PREPROCESS) {
2056 ret = tcc_preprocess(s1);
2057 goto the_end;
2060 if (!ext[0] || !PATHCMP(ext, "c")) {
2061 /* C file assumed */
2062 ret = tcc_compile(s1);
2063 goto the_end;
2066 #ifdef CONFIG_TCC_ASM
2067 if (!strcmp(ext, "S")) {
2068 /* preprocessed assembler */
2069 ret = tcc_assemble(s1, 1);
2070 goto the_end;
2073 if (!strcmp(ext, "s")) {
2074 /* non preprocessed assembler */
2075 ret = tcc_assemble(s1, 0);
2076 goto the_end;
2078 #endif
2080 fd = file->fd;
2081 /* assume executable format: auto guess file type */
2082 size = read(fd, &ehdr, sizeof(ehdr));
2083 lseek(fd, 0, SEEK_SET);
2084 if (size <= 0) {
2085 error_noabort("could not read header");
2086 goto the_end;
2089 if (size == sizeof(ehdr) &&
2090 ehdr.e_ident[0] == ELFMAG0 &&
2091 ehdr.e_ident[1] == ELFMAG1 &&
2092 ehdr.e_ident[2] == ELFMAG2 &&
2093 ehdr.e_ident[3] == ELFMAG3) {
2095 /* do not display line number if error */
2096 file->line_num = 0;
2097 if (ehdr.e_type == ET_REL) {
2098 ret = tcc_load_object_file(s1, fd, 0);
2099 goto the_end;
2102 #ifndef TCC_TARGET_PE
2103 if (ehdr.e_type == ET_DYN) {
2104 if (s1->output_type == TCC_OUTPUT_MEMORY) {
2105 void *h;
2106 h = dlopen(filename, RTLD_GLOBAL | RTLD_LAZY);
2107 if (h)
2108 ret = 0;
2109 } else {
2110 ret = tcc_load_dll(s1, fd, filename,
2111 (flags & AFF_REFERENCED_DLL) != 0);
2113 goto the_end;
2115 #endif
2116 error_noabort("unrecognized ELF file");
2117 goto the_end;
2120 if (memcmp((char *)&ehdr, ARMAG, 8) == 0) {
2121 file->line_num = 0; /* do not display line number if error */
2122 ret = tcc_load_archive(s1, fd);
2123 goto the_end;
2126 #ifdef TCC_TARGET_COFF
2127 if (*(uint16_t *)(&ehdr) == COFF_C67_MAGIC) {
2128 ret = tcc_load_coff(s1, fd);
2129 goto the_end;
2131 #endif
2133 #ifdef TCC_TARGET_PE
2134 ret = pe_load_file(s1, filename, fd);
2135 #else
2136 /* as GNU ld, consider it is an ld script if not recognized */
2137 ret = tcc_load_ldscript(s1);
2138 #endif
2139 if (ret < 0)
2140 error_noabort("unrecognized file type");
2142 the_end:
2143 if (file)
2144 tcc_close(file);
2145 file = saved_file;
2146 return ret;
2149 int tcc_add_file(TCCState *s, const char *filename)
2151 if (s->output_type == TCC_OUTPUT_PREPROCESS)
2152 return tcc_add_file_internal(s, filename, AFF_PRINT_ERROR | AFF_PREPROCESS);
2153 else
2154 return tcc_add_file_internal(s, filename, AFF_PRINT_ERROR);
2157 int tcc_add_library_path(TCCState *s, const char *pathname)
2159 char *pathname1;
2161 pathname1 = tcc_strdup(pathname);
2162 dynarray_add((void ***)&s->library_paths, &s->nb_library_paths, pathname1);
2163 return 0;
2166 /* find and load a dll. Return non zero if not found */
2167 /* XXX: add '-rpath' option support ? */
2168 static int tcc_add_dll(TCCState *s, const char *filename, int flags)
2170 char buf[1024];
2171 int i;
2173 for(i = 0; i < s->nb_library_paths; i++) {
2174 snprintf(buf, sizeof(buf), "%s/%s",
2175 s->library_paths[i], filename);
2176 if (tcc_add_file_internal(s, buf, flags) == 0)
2177 return 0;
2179 return -1;
2182 /* the library name is the same as the argument of the '-l' option */
2183 int tcc_add_library(TCCState *s, const char *libraryname)
2185 char buf[1024];
2186 int i;
2188 /* first we look for the dynamic library if not static linking */
2189 if (!s->static_link) {
2190 #ifdef TCC_TARGET_PE
2191 if (pe_add_dll(s, libraryname) == 0)
2192 return 0;
2193 #else
2194 snprintf(buf, sizeof(buf), "lib%s.so", libraryname);
2195 if (tcc_add_dll(s, buf, 0) == 0)
2196 return 0;
2197 #endif
2199 /* then we look for the static library */
2200 for(i = 0; i < s->nb_library_paths; i++) {
2201 snprintf(buf, sizeof(buf), "%s/lib%s.a",
2202 s->library_paths[i], libraryname);
2203 if (tcc_add_file_internal(s, buf, 0) == 0)
2204 return 0;
2206 return -1;
2209 int tcc_add_symbol(TCCState *s, const char *name, void *val)
2211 add_elf_sym(symtab_section, (uplong)val, 0,
2212 ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE), 0,
2213 SHN_ABS, name);
2214 return 0;
2217 int tcc_set_output_type(TCCState *s, int output_type)
2219 char buf[1024];
2221 s->output_type = output_type;
2223 if (!s->nostdinc) {
2224 /* default include paths */
2225 /* XXX: reverse order needed if -isystem support */
2226 #ifndef TCC_TARGET_PE
2227 tcc_add_sysinclude_path(s, CONFIG_SYSROOT "/usr/local/include");
2228 tcc_add_sysinclude_path(s, CONFIG_SYSROOT "/usr/include");
2229 #endif
2230 snprintf(buf, sizeof(buf), "%s/include", s->tcc_lib_path);
2231 tcc_add_sysinclude_path(s, buf);
2232 #ifdef TCC_TARGET_PE
2233 snprintf(buf, sizeof(buf), "%s/include/winapi", s->tcc_lib_path);
2234 tcc_add_sysinclude_path(s, buf);
2235 #endif
2238 /* if bound checking, then add corresponding sections */
2239 #ifdef CONFIG_TCC_BCHECK
2240 if (s->do_bounds_check) {
2241 /* define symbol */
2242 tcc_define_symbol(s, "__BOUNDS_CHECKING_ON", NULL);
2243 /* create bounds sections */
2244 bounds_section = new_section(s, ".bounds",
2245 SHT_PROGBITS, SHF_ALLOC);
2246 lbounds_section = new_section(s, ".lbounds",
2247 SHT_PROGBITS, SHF_ALLOC);
2249 #endif
2251 if (s->char_is_unsigned) {
2252 tcc_define_symbol(s, "__CHAR_UNSIGNED__", NULL);
2255 /* add debug sections */
2256 if (s->do_debug) {
2257 /* stab symbols */
2258 stab_section = new_section(s, ".stab", SHT_PROGBITS, 0);
2259 stab_section->sh_entsize = sizeof(Stab_Sym);
2260 stabstr_section = new_section(s, ".stabstr", SHT_STRTAB, 0);
2261 put_elf_str(stabstr_section, "");
2262 stab_section->link = stabstr_section;
2263 /* put first entry */
2264 put_stabs("", 0, 0, 0, 0);
2267 /* add libc crt1/crti objects */
2268 #ifndef TCC_TARGET_PE
2269 if ((output_type == TCC_OUTPUT_EXE || output_type == TCC_OUTPUT_DLL) &&
2270 !s->nostdlib) {
2271 if (output_type != TCC_OUTPUT_DLL)
2272 tcc_add_file(s, CONFIG_TCC_CRT_PREFIX "/crt1.o");
2273 tcc_add_file(s, CONFIG_TCC_CRT_PREFIX "/crti.o");
2275 #endif
2277 #ifdef TCC_TARGET_PE
2278 snprintf(buf, sizeof(buf), "%s/lib", s->tcc_lib_path);
2279 tcc_add_library_path(s, buf);
2280 #ifdef _WIN32
2281 if (GetSystemDirectory(buf, sizeof buf))
2282 tcc_add_library_path(s, buf);
2283 #endif
2284 #endif
2286 return 0;
2289 #define WD_ALL 0x0001 /* warning is activated when using -Wall */
2290 #define FD_INVERT 0x0002 /* invert value before storing */
2292 typedef struct FlagDef {
2293 uint16_t offset;
2294 uint16_t flags;
2295 const char *name;
2296 } FlagDef;
2298 static const FlagDef warning_defs[] = {
2299 { offsetof(TCCState, warn_unsupported), 0, "unsupported" },
2300 { offsetof(TCCState, warn_write_strings), 0, "write-strings" },
2301 { offsetof(TCCState, warn_error), 0, "error" },
2302 { offsetof(TCCState, warn_implicit_function_declaration), WD_ALL,
2303 "implicit-function-declaration" },
2306 static int set_flag(TCCState *s, const FlagDef *flags, int nb_flags,
2307 const char *name, int value)
2309 int i;
2310 const FlagDef *p;
2311 const char *r;
2313 r = name;
2314 if (r[0] == 'n' && r[1] == 'o' && r[2] == '-') {
2315 r += 3;
2316 value = !value;
2318 for(i = 0, p = flags; i < nb_flags; i++, p++) {
2319 if (!strcmp(r, p->name))
2320 goto found;
2322 return -1;
2323 found:
2324 if (p->flags & FD_INVERT)
2325 value = !value;
2326 *(int *)((uint8_t *)s + p->offset) = value;
2327 return 0;
2331 /* set/reset a warning */
2332 int tcc_set_warning(TCCState *s, const char *warning_name, int value)
2334 int i;
2335 const FlagDef *p;
2337 if (!strcmp(warning_name, "all")) {
2338 for(i = 0, p = warning_defs; i < countof(warning_defs); i++, p++) {
2339 if (p->flags & WD_ALL)
2340 *(int *)((uint8_t *)s + p->offset) = 1;
2342 return 0;
2343 } else {
2344 return set_flag(s, warning_defs, countof(warning_defs),
2345 warning_name, value);
2349 static const FlagDef flag_defs[] = {
2350 { offsetof(TCCState, char_is_unsigned), 0, "unsigned-char" },
2351 { offsetof(TCCState, char_is_unsigned), FD_INVERT, "signed-char" },
2352 { offsetof(TCCState, nocommon), FD_INVERT, "common" },
2353 { offsetof(TCCState, leading_underscore), 0, "leading-underscore" },
2356 /* set/reset a flag */
2357 int tcc_set_flag(TCCState *s, const char *flag_name, int value)
2359 return set_flag(s, flag_defs, countof(flag_defs),
2360 flag_name, value);
2363 /* set CONFIG_TCCDIR at runtime */
2364 void tcc_set_lib_path(TCCState *s, const char *path)
2366 tcc_free(s->tcc_lib_path);
2367 s->tcc_lib_path = tcc_strdup(path);
2370 void tcc_print_stats(TCCState *s, int64_t total_time)
2372 double tt;
2373 tt = (double)total_time / 1000000.0;
2374 if (tt < 0.001)
2375 tt = 0.001;
2376 if (total_bytes < 1)
2377 total_bytes = 1;
2378 printf("%d idents, %d lines, %d bytes, %0.3f s, %d lines/s, %0.1f MB/s\n",
2379 tok_ident - TOK_IDENT, total_lines, total_bytes,
2380 tt, (int)(total_lines / tt),
2381 total_bytes / tt / 1000000.0);