error messages: print "error: ..."
[tinycc/kirr.git] / libtcc.c
blob865c1166026797302073951d720f1c29cfdd4a67
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 #endif
115 /* XXX: get rid of this ASAP */
116 static struct TCCState *tcc_state;
118 /********************************************************/
119 /* function prototypes */
121 /* tccpp.c */
122 static void next(void);
123 char *get_tok_str(int v, CValue *cv);
125 /* tccgen.c */
126 static void parse_expr_type(CType *type);
127 static void expr_type(CType *type);
128 static void unary_type(CType *type);
129 static void block(int *bsym, int *csym, int *case_sym, int *def_sym,
130 int case_reg, int is_expr);
131 static int expr_const(void);
132 static void expr_eq(void);
133 static void gexpr(void);
134 static void gen_inline_functions(void);
135 static void decl(int l);
136 static void decl_initializer(CType *type, Section *sec, unsigned long c,
137 int first, int size_only);
138 static void decl_initializer_alloc(CType *type, AttributeDef *ad, int r,
139 int has_init, int v, int scope);
140 int gv(int rc);
141 void gv2(int rc1, int rc2);
142 void move_reg(int r, int s);
143 void save_regs(int n);
144 void save_reg(int r);
145 void vpop(void);
146 void vswap(void);
147 void vdup(void);
148 int get_reg(int rc);
149 int get_reg_ex(int rc,int rc2);
151 void gen_op(int op);
152 void force_charshort_cast(int t);
153 static void gen_cast(CType *type);
154 void vstore(void);
155 static Sym *sym_find(int v);
156 static Sym *sym_push(int v, CType *type, int r, int c);
158 /* type handling */
159 static int type_size(CType *type, int *a);
160 static inline CType *pointed_type(CType *type);
161 static int pointed_size(CType *type);
162 static int lvalue_type(int t);
163 static int parse_btype(CType *type, AttributeDef *ad);
164 static void type_decl(CType *type, AttributeDef *ad, int *v, int td);
165 static int compare_types(CType *type1, CType *type2, int unqualified);
166 static int is_compatible_types(CType *type1, CType *type2);
167 static int is_compatible_parameter_types(CType *type1, CType *type2);
169 int ieee_finite(double d);
170 void vpushi(int v);
171 void vpushll(long long v);
172 void vrott(int n);
173 void vnrott(int n);
174 void lexpand_nr(void);
175 static void vpush_global_sym(CType *type, int v);
176 void vset(CType *type, int r, int v);
177 void type_to_str(char *buf, int buf_size,
178 CType *type, const char *varstr);
179 static Sym *get_sym_ref(CType *type, Section *sec,
180 unsigned long offset, unsigned long size);
181 static Sym *external_global_sym(int v, CType *type, int r);
183 /* section generation */
184 static void section_realloc(Section *sec, unsigned long new_size);
185 static void *section_ptr_add(Section *sec, unsigned long size);
186 static void put_extern_sym(Sym *sym, Section *section,
187 unsigned long value, unsigned long size);
188 static void greloc(Section *s, Sym *sym, unsigned long addr, int type);
189 static int put_elf_str(Section *s, const char *sym);
190 static int put_elf_sym(Section *s,
191 unsigned long value, unsigned long size,
192 int info, int other, int shndx, const char *name);
193 static int add_elf_sym(Section *s, unsigned long value, unsigned long size,
194 int info, int other, int sh_num, const char *name);
195 static void put_elf_reloc(Section *symtab, Section *s, unsigned long offset,
196 int type, int symbol);
197 static void put_stabs(const char *str, int type, int other, int desc,
198 unsigned long value);
199 static void put_stabs_r(const char *str, int type, int other, int desc,
200 unsigned long value, Section *sec, int sym_index);
201 static void put_stabn(int type, int other, int desc, int value);
202 static void put_stabd(int type, int other, int desc);
203 static int tcc_add_dll(TCCState *s, const char *filename, int flags);
205 #define AFF_PRINT_ERROR 0x0001 /* print error if file not found */
206 #define AFF_REFERENCED_DLL 0x0002 /* load a referenced dll from another dll */
207 #define AFF_PREPROCESS 0x0004 /* preprocess file */
208 static int tcc_add_file_internal(TCCState *s, const char *filename, int flags);
210 /* tcccoff.c */
211 int tcc_output_coff(TCCState *s1, FILE *f);
213 /* tccpe.c */
214 void *resolve_sym(TCCState *s1, const char *sym, int type);
215 int pe_load_def_file(struct TCCState *s1, int fd);
216 int pe_test_res_file(void *v, int size);
217 int pe_load_res_file(struct TCCState *s1, int fd);
218 void pe_add_runtime(struct TCCState *s1);
219 void pe_guess_outfile(char *objfilename, int output_type);
220 int pe_output_file(struct TCCState *s1, const char *filename);
222 /* tccasm.c */
223 #ifdef CONFIG_TCC_ASM
224 static void asm_expr(TCCState *s1, ExprValue *pe);
225 static int asm_int_expr(TCCState *s1);
226 static int find_constraint(ASMOperand *operands, int nb_operands,
227 const char *name, const char **pp);
229 static int tcc_assemble(TCCState *s1, int do_preprocess);
230 #endif
232 static void asm_instr(void);
233 static void asm_global_instr(void);
235 /********************************************************/
236 /* global variables */
238 #ifdef TCC_TARGET_I386
239 #include "i386-gen.c"
240 #endif
242 #ifdef TCC_TARGET_ARM
243 #include "arm-gen.c"
244 #endif
246 #ifdef TCC_TARGET_C67
247 #include "c67-gen.c"
248 #endif
250 #ifdef TCC_TARGET_X86_64
251 #include "x86_64-gen.c"
252 #endif
254 #ifdef CONFIG_TCC_STATIC
256 #define RTLD_LAZY 0x001
257 #define RTLD_NOW 0x002
258 #define RTLD_GLOBAL 0x100
259 #define RTLD_DEFAULT NULL
261 /* dummy function for profiling */
262 void *dlopen(const char *filename, int flag)
264 return NULL;
267 void dlclose(void *p)
271 const char *dlerror(void)
273 return "error";
276 typedef struct TCCSyms {
277 char *str;
278 void *ptr;
279 } TCCSyms;
281 #define TCCSYM(a) { #a, &a, },
283 /* add the symbol you want here if no dynamic linking is done */
284 static TCCSyms tcc_syms[] = {
285 #if !defined(CONFIG_TCCBOOT)
286 TCCSYM(printf)
287 TCCSYM(fprintf)
288 TCCSYM(fopen)
289 TCCSYM(fclose)
290 #endif
291 { NULL, NULL },
294 void *resolve_sym(TCCState *s1, const char *symbol, int type)
296 TCCSyms *p;
297 p = tcc_syms;
298 while (p->str != NULL) {
299 if (!strcmp(p->str, symbol))
300 return p->ptr;
301 p++;
303 return NULL;
306 #elif !defined(_WIN32)
308 #include <dlfcn.h>
310 void *resolve_sym(TCCState *s1, const char *sym, int type)
312 return dlsym(RTLD_DEFAULT, sym);
315 #endif
317 /********************************************************/
319 /* we use our own 'finite' function to avoid potential problems with
320 non standard math libs */
321 /* XXX: endianness dependent */
322 int ieee_finite(double d)
324 int *p = (int *)&d;
325 return ((unsigned)((p[1] | 0x800fffff) + 1)) >> 31;
328 /* copy a string and truncate it. */
329 char *pstrcpy(char *buf, int buf_size, const char *s)
331 char *q, *q_end;
332 int c;
334 if (buf_size > 0) {
335 q = buf;
336 q_end = buf + buf_size - 1;
337 while (q < q_end) {
338 c = *s++;
339 if (c == '\0')
340 break;
341 *q++ = c;
343 *q = '\0';
345 return buf;
348 /* strcat and truncate. */
349 char *pstrcat(char *buf, int buf_size, const char *s)
351 int len;
352 len = strlen(buf);
353 if (len < buf_size)
354 pstrcpy(buf + len, buf_size - len, s);
355 return buf;
358 /* extract the basename of a file */
359 char *tcc_basename(const char *name)
361 char *p = strchr(name, 0);
362 while (p > name && !IS_PATHSEP(p[-1]))
363 --p;
364 return p;
367 char *tcc_fileextension (const char *name)
369 char *b = tcc_basename(name);
370 char *e = strrchr(b, '.');
371 return e ? e : strchr(b, 0);
374 #ifdef _WIN32
375 char *normalize_slashes(char *path)
377 char *p;
378 for (p = path; *p; ++p)
379 if (*p == '\\')
380 *p = '/';
381 return path;
384 void tcc_set_lib_path_w32(TCCState *s)
386 /* on win32, we suppose the lib and includes are at the location
387 of 'tcc.exe' */
388 char path[1024], *p;
389 GetModuleFileNameA(NULL, path, sizeof path);
390 p = tcc_basename(normalize_slashes(strlwr(path)));
391 if (p - 5 > path && 0 == strncmp(p - 5, "/bin/", 5))
392 p -= 5;
393 else if (p > path)
394 p--;
395 *p = 0;
396 tcc_set_lib_path(s, path);
398 #endif
400 void set_pages_executable(void *ptr, unsigned long length)
402 #ifdef _WIN32
403 unsigned long old_protect;
404 VirtualProtect(ptr, length, PAGE_EXECUTE_READWRITE, &old_protect);
405 #else
406 unsigned long start, end;
407 start = (unsigned long)ptr & ~(PAGESIZE - 1);
408 end = (unsigned long)ptr + length;
409 end = (end + PAGESIZE - 1) & ~(PAGESIZE - 1);
410 mprotect((void *)start, end - start, PROT_READ | PROT_WRITE | PROT_EXEC);
411 #endif
414 /* memory management */
415 #ifdef MEM_DEBUG
416 int mem_cur_size;
417 int mem_max_size;
418 unsigned malloc_usable_size(void*);
419 #endif
421 void tcc_free(void *ptr)
423 #ifdef MEM_DEBUG
424 mem_cur_size -= malloc_usable_size(ptr);
425 #endif
426 free(ptr);
429 void *tcc_malloc(unsigned long size)
431 void *ptr;
432 ptr = malloc(size);
433 if (!ptr && size)
434 error("memory full");
435 #ifdef MEM_DEBUG
436 mem_cur_size += malloc_usable_size(ptr);
437 if (mem_cur_size > mem_max_size)
438 mem_max_size = mem_cur_size;
439 #endif
440 return ptr;
443 void *tcc_mallocz(unsigned long size)
445 void *ptr;
446 ptr = tcc_malloc(size);
447 memset(ptr, 0, size);
448 return ptr;
451 void *tcc_realloc(void *ptr, unsigned long size)
453 void *ptr1;
454 #ifdef MEM_DEBUG
455 mem_cur_size -= malloc_usable_size(ptr);
456 #endif
457 ptr1 = realloc(ptr, size);
458 #ifdef MEM_DEBUG
459 /* NOTE: count not correct if alloc error, but not critical */
460 mem_cur_size += malloc_usable_size(ptr1);
461 if (mem_cur_size > mem_max_size)
462 mem_max_size = mem_cur_size;
463 #endif
464 return ptr1;
467 char *tcc_strdup(const char *str)
469 char *ptr;
470 ptr = tcc_malloc(strlen(str) + 1);
471 strcpy(ptr, str);
472 return ptr;
475 #define free(p) use_tcc_free(p)
476 #define malloc(s) use_tcc_malloc(s)
477 #define realloc(p, s) use_tcc_realloc(p, s)
479 void dynarray_add(void ***ptab, int *nb_ptr, void *data)
481 int nb, nb_alloc;
482 void **pp;
484 nb = *nb_ptr;
485 pp = *ptab;
486 /* every power of two we double array size */
487 if ((nb & (nb - 1)) == 0) {
488 if (!nb)
489 nb_alloc = 1;
490 else
491 nb_alloc = nb * 2;
492 pp = tcc_realloc(pp, nb_alloc * sizeof(void *));
493 if (!pp)
494 error("memory full");
495 *ptab = pp;
497 pp[nb++] = data;
498 *nb_ptr = nb;
501 void dynarray_reset(void *pp, int *n)
503 void **p;
504 for (p = *(void***)pp; *n; ++p, --*n)
505 if (*p)
506 tcc_free(*p);
507 tcc_free(*(void**)pp);
508 *(void**)pp = NULL;
511 /* symbol allocator */
512 static Sym *__sym_malloc(void)
514 Sym *sym_pool, *sym, *last_sym;
515 int i;
517 sym_pool = tcc_malloc(SYM_POOL_NB * sizeof(Sym));
518 dynarray_add(&sym_pools, &nb_sym_pools, sym_pool);
520 last_sym = sym_free_first;
521 sym = sym_pool;
522 for(i = 0; i < SYM_POOL_NB; i++) {
523 sym->next = last_sym;
524 last_sym = sym;
525 sym++;
527 sym_free_first = last_sym;
528 return last_sym;
531 static inline Sym *sym_malloc(void)
533 Sym *sym;
534 sym = sym_free_first;
535 if (!sym)
536 sym = __sym_malloc();
537 sym_free_first = sym->next;
538 return sym;
541 static inline void sym_free(Sym *sym)
543 sym->next = sym_free_first;
544 sym_free_first = sym;
547 Section *new_section(TCCState *s1, const char *name, int sh_type, int sh_flags)
549 Section *sec;
551 sec = tcc_mallocz(sizeof(Section) + strlen(name));
552 strcpy(sec->name, name);
553 sec->sh_type = sh_type;
554 sec->sh_flags = sh_flags;
555 switch(sh_type) {
556 case SHT_HASH:
557 case SHT_REL:
558 case SHT_RELA:
559 case SHT_DYNSYM:
560 case SHT_SYMTAB:
561 case SHT_DYNAMIC:
562 sec->sh_addralign = 4;
563 break;
564 case SHT_STRTAB:
565 sec->sh_addralign = 1;
566 break;
567 default:
568 sec->sh_addralign = 32; /* default conservative alignment */
569 break;
572 if (sh_flags & SHF_PRIVATE) {
573 dynarray_add((void ***)&s1->priv_sections, &s1->nb_priv_sections, sec);
574 } else {
575 sec->sh_num = s1->nb_sections;
576 dynarray_add((void ***)&s1->sections, &s1->nb_sections, sec);
579 return sec;
582 static void free_section(Section *s)
584 tcc_free(s->data);
587 /* realloc section and set its content to zero */
588 static void section_realloc(Section *sec, unsigned long new_size)
590 unsigned long size;
591 unsigned char *data;
593 size = sec->data_allocated;
594 if (size == 0)
595 size = 1;
596 while (size < new_size)
597 size = size * 2;
598 data = tcc_realloc(sec->data, size);
599 if (!data)
600 error("memory full");
601 memset(data + sec->data_allocated, 0, size - sec->data_allocated);
602 sec->data = data;
603 sec->data_allocated = size;
606 /* reserve at least 'size' bytes in section 'sec' from
607 sec->data_offset. */
608 static void *section_ptr_add(Section *sec, unsigned long size)
610 unsigned long offset, offset1;
612 offset = sec->data_offset;
613 offset1 = offset + size;
614 if (offset1 > sec->data_allocated)
615 section_realloc(sec, offset1);
616 sec->data_offset = offset1;
617 return sec->data + offset;
620 /* return a reference to a section, and create it if it does not
621 exists */
622 Section *find_section(TCCState *s1, const char *name)
624 Section *sec;
625 int i;
626 for(i = 1; i < s1->nb_sections; i++) {
627 sec = s1->sections[i];
628 if (!strcmp(name, sec->name))
629 return sec;
631 /* sections are created as PROGBITS */
632 return new_section(s1, name, SHT_PROGBITS, SHF_ALLOC);
635 /* update sym->c so that it points to an external symbol in section
636 'section' with value 'value' */
637 static void put_extern_sym2(Sym *sym, Section *section,
638 unsigned long value, unsigned long size,
639 int can_add_underscore)
641 int sym_type, sym_bind, sh_num, info, other, attr;
642 ElfW(Sym) *esym;
643 const char *name;
644 char buf1[256];
646 if (section == NULL)
647 sh_num = SHN_UNDEF;
648 else if (section == SECTION_ABS)
649 sh_num = SHN_ABS;
650 else
651 sh_num = section->sh_num;
653 other = attr = 0;
655 if ((sym->type.t & VT_BTYPE) == VT_FUNC) {
656 sym_type = STT_FUNC;
657 #ifdef TCC_TARGET_PE
658 if (sym->type.ref)
659 attr = sym->type.ref->r;
660 if (FUNC_EXPORT(attr))
661 other |= 1;
662 if (FUNC_CALL(attr) == FUNC_STDCALL)
663 other |= 2;
664 #endif
665 } else {
666 sym_type = STT_OBJECT;
669 if (sym->type.t & VT_STATIC)
670 sym_bind = STB_LOCAL;
671 else
672 sym_bind = STB_GLOBAL;
674 if (!sym->c) {
675 name = get_tok_str(sym->v, NULL);
676 #ifdef CONFIG_TCC_BCHECK
677 if (tcc_state->do_bounds_check) {
678 char buf[32];
680 /* XXX: avoid doing that for statics ? */
681 /* if bound checking is activated, we change some function
682 names by adding the "__bound" prefix */
683 switch(sym->v) {
684 #if 0
685 /* XXX: we rely only on malloc hooks */
686 case TOK_malloc:
687 case TOK_free:
688 case TOK_realloc:
689 case TOK_memalign:
690 case TOK_calloc:
691 #endif
692 case TOK_memcpy:
693 case TOK_memmove:
694 case TOK_memset:
695 case TOK_strlen:
696 case TOK_strcpy:
697 case TOK_alloca:
698 strcpy(buf, "__bound_");
699 strcat(buf, name);
700 name = buf;
701 break;
704 #endif
706 #ifdef TCC_TARGET_PE
707 if ((other & 2) && can_add_underscore) {
708 sprintf(buf1, "_%s@%d", name, FUNC_ARGS(attr));
709 name = buf1;
710 } else
711 #endif
712 if (tcc_state->leading_underscore && can_add_underscore) {
713 buf1[0] = '_';
714 pstrcpy(buf1 + 1, sizeof(buf1) - 1, name);
715 name = buf1;
717 info = ELFW(ST_INFO)(sym_bind, sym_type);
718 sym->c = add_elf_sym(symtab_section, value, size, info, other, sh_num, name);
719 } else {
720 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
721 esym->st_value = value;
722 esym->st_size = size;
723 esym->st_shndx = sh_num;
724 esym->st_other |= other;
728 static void put_extern_sym(Sym *sym, Section *section,
729 unsigned long value, unsigned long size)
731 put_extern_sym2(sym, section, value, size, 1);
734 /* add a new relocation entry to symbol 'sym' in section 's' */
735 static void greloc(Section *s, Sym *sym, unsigned long offset, int type)
737 if (!sym->c)
738 put_extern_sym(sym, NULL, 0, 0);
739 /* now we can add ELF relocation info */
740 put_elf_reloc(symtab_section, s, offset, type, sym->c);
743 static inline int isid(int c)
745 return (c >= 'a' && c <= 'z') ||
746 (c >= 'A' && c <= 'Z') ||
747 c == '_';
750 static inline int isnum(int c)
752 return c >= '0' && c <= '9';
755 static inline int isoct(int c)
757 return c >= '0' && c <= '7';
760 static inline int toup(int c)
762 if (c >= 'a' && c <= 'z')
763 return c - 'a' + 'A';
764 else
765 return c;
768 static void strcat_vprintf(char *buf, int buf_size, const char *fmt, va_list ap)
770 int len;
771 len = strlen(buf);
772 vsnprintf(buf + len, buf_size - len, fmt, ap);
775 static void strcat_printf(char *buf, int buf_size, const char *fmt, ...)
777 va_list ap;
778 va_start(ap, fmt);
779 strcat_vprintf(buf, buf_size, fmt, ap);
780 va_end(ap);
783 void error1(TCCState *s1, int is_warning, const char *fmt, va_list ap)
785 char buf[2048];
786 BufferedFile **f;
788 buf[0] = '\0';
789 if (file) {
790 for(f = s1->include_stack; f < s1->include_stack_ptr; f++)
791 strcat_printf(buf, sizeof(buf), "In file included from %s:%d:\n",
792 (*f)->filename, (*f)->line_num);
793 if (file->line_num > 0) {
794 strcat_printf(buf, sizeof(buf),
795 "%s:%d: ", file->filename, file->line_num);
796 } else {
797 strcat_printf(buf, sizeof(buf),
798 "%s: ", file->filename);
800 } else {
801 strcat_printf(buf, sizeof(buf),
802 "tcc: ");
804 if (is_warning)
805 strcat_printf(buf, sizeof(buf), "warning: ");
806 else
807 strcat_printf(buf, sizeof(buf), "error: ");
808 strcat_vprintf(buf, sizeof(buf), fmt, ap);
810 if (!s1->error_func) {
811 /* default case: stderr */
812 fprintf(stderr, "%s\n", buf);
813 } else {
814 s1->error_func(s1->error_opaque, buf);
816 if (!is_warning || s1->warn_error)
817 s1->nb_errors++;
820 void tcc_set_error_func(TCCState *s, void *error_opaque,
821 void (*error_func)(void *opaque, const char *msg))
823 s->error_opaque = error_opaque;
824 s->error_func = error_func;
827 /* error without aborting current compilation */
828 void error_noabort(const char *fmt, ...)
830 TCCState *s1 = tcc_state;
831 va_list ap;
833 va_start(ap, fmt);
834 error1(s1, 0, fmt, ap);
835 va_end(ap);
838 void error(const char *fmt, ...)
840 TCCState *s1 = tcc_state;
841 va_list ap;
843 va_start(ap, fmt);
844 error1(s1, 0, fmt, ap);
845 va_end(ap);
846 /* better than nothing: in some cases, we accept to handle errors */
847 if (s1->error_set_jmp_enabled) {
848 longjmp(s1->error_jmp_buf, 1);
849 } else {
850 /* XXX: eliminate this someday */
851 exit(1);
855 void expect(const char *msg)
857 error("%s expected", msg);
860 void warning(const char *fmt, ...)
862 TCCState *s1 = tcc_state;
863 va_list ap;
865 if (s1->warn_none)
866 return;
868 va_start(ap, fmt);
869 error1(s1, 1, fmt, ap);
870 va_end(ap);
873 void skip(int c)
875 if (tok != c)
876 error("'%c' expected", c);
877 next();
880 static void test_lvalue(void)
882 if (!(vtop->r & VT_LVAL))
883 expect("lvalue");
886 /* CString handling */
888 static void cstr_realloc(CString *cstr, int new_size)
890 int size;
891 void *data;
893 size = cstr->size_allocated;
894 if (size == 0)
895 size = 8; /* no need to allocate a too small first string */
896 while (size < new_size)
897 size = size * 2;
898 data = tcc_realloc(cstr->data_allocated, size);
899 if (!data)
900 error("memory full");
901 cstr->data_allocated = data;
902 cstr->size_allocated = size;
903 cstr->data = data;
906 /* add a byte */
907 static inline void cstr_ccat(CString *cstr, int ch)
909 int size;
910 size = cstr->size + 1;
911 if (size > cstr->size_allocated)
912 cstr_realloc(cstr, size);
913 ((unsigned char *)cstr->data)[size - 1] = ch;
914 cstr->size = size;
917 static void cstr_cat(CString *cstr, const char *str)
919 int c;
920 for(;;) {
921 c = *str;
922 if (c == '\0')
923 break;
924 cstr_ccat(cstr, c);
925 str++;
929 /* add a wide char */
930 static void cstr_wccat(CString *cstr, int ch)
932 int size;
933 size = cstr->size + sizeof(nwchar_t);
934 if (size > cstr->size_allocated)
935 cstr_realloc(cstr, size);
936 *(nwchar_t *)(((unsigned char *)cstr->data) + size - sizeof(nwchar_t)) = ch;
937 cstr->size = size;
940 static void cstr_new(CString *cstr)
942 memset(cstr, 0, sizeof(CString));
945 /* free string and reset it to NULL */
946 static void cstr_free(CString *cstr)
948 tcc_free(cstr->data_allocated);
949 cstr_new(cstr);
952 #define cstr_reset(cstr) cstr_free(cstr)
954 /* XXX: unicode ? */
955 static void add_char(CString *cstr, int c)
957 if (c == '\'' || c == '\"' || c == '\\') {
958 /* XXX: could be more precise if char or string */
959 cstr_ccat(cstr, '\\');
961 if (c >= 32 && c <= 126) {
962 cstr_ccat(cstr, c);
963 } else {
964 cstr_ccat(cstr, '\\');
965 if (c == '\n') {
966 cstr_ccat(cstr, 'n');
967 } else {
968 cstr_ccat(cstr, '0' + ((c >> 6) & 7));
969 cstr_ccat(cstr, '0' + ((c >> 3) & 7));
970 cstr_ccat(cstr, '0' + (c & 7));
975 /* push, without hashing */
976 static Sym *sym_push2(Sym **ps, int v, int t, long c)
978 Sym *s;
979 s = sym_malloc();
980 s->v = v;
981 s->type.t = t;
982 s->c = c;
983 s->next = NULL;
984 /* add in stack */
985 s->prev = *ps;
986 *ps = s;
987 return s;
990 /* find a symbol and return its associated structure. 's' is the top
991 of the symbol stack */
992 static Sym *sym_find2(Sym *s, int v)
994 while (s) {
995 if (s->v == v)
996 return s;
997 s = s->prev;
999 return NULL;
1002 /* structure lookup */
1003 static inline Sym *struct_find(int v)
1005 v -= TOK_IDENT;
1006 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1007 return NULL;
1008 return table_ident[v]->sym_struct;
1011 /* find an identifier */
1012 static inline Sym *sym_find(int v)
1014 v -= TOK_IDENT;
1015 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1016 return NULL;
1017 return table_ident[v]->sym_identifier;
1020 /* push a given symbol on the symbol stack */
1021 static Sym *sym_push(int v, CType *type, int r, int c)
1023 Sym *s, **ps;
1024 TokenSym *ts;
1026 if (local_stack)
1027 ps = &local_stack;
1028 else
1029 ps = &global_stack;
1030 s = sym_push2(ps, v, type->t, c);
1031 s->type.ref = type->ref;
1032 s->r = r;
1033 /* don't record fields or anonymous symbols */
1034 /* XXX: simplify */
1035 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
1036 /* record symbol in token array */
1037 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
1038 if (v & SYM_STRUCT)
1039 ps = &ts->sym_struct;
1040 else
1041 ps = &ts->sym_identifier;
1042 s->prev_tok = *ps;
1043 *ps = s;
1045 return s;
1048 /* push a global identifier */
1049 static Sym *global_identifier_push(int v, int t, int c)
1051 Sym *s, **ps;
1052 s = sym_push2(&global_stack, v, t, c);
1053 /* don't record anonymous symbol */
1054 if (v < SYM_FIRST_ANOM) {
1055 ps = &table_ident[v - TOK_IDENT]->sym_identifier;
1056 /* modify the top most local identifier, so that
1057 sym_identifier will point to 's' when popped */
1058 while (*ps != NULL)
1059 ps = &(*ps)->prev_tok;
1060 s->prev_tok = NULL;
1061 *ps = s;
1063 return s;
1066 /* pop symbols until top reaches 'b' */
1067 static void sym_pop(Sym **ptop, Sym *b)
1069 Sym *s, *ss, **ps;
1070 TokenSym *ts;
1071 int v;
1073 s = *ptop;
1074 while(s != b) {
1075 ss = s->prev;
1076 v = s->v;
1077 /* remove symbol in token array */
1078 /* XXX: simplify */
1079 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
1080 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
1081 if (v & SYM_STRUCT)
1082 ps = &ts->sym_struct;
1083 else
1084 ps = &ts->sym_identifier;
1085 *ps = s->prev_tok;
1087 sym_free(s);
1088 s = ss;
1090 *ptop = b;
1093 /* I/O layer */
1095 BufferedFile *tcc_open(TCCState *s1, const char *filename)
1097 int fd;
1098 BufferedFile *bf;
1100 if (strcmp(filename, "-") == 0)
1101 fd = 0, filename = "stdin";
1102 else
1103 fd = open(filename, O_RDONLY | O_BINARY);
1104 if ((s1->verbose == 2 && fd >= 0) || s1->verbose == 3)
1105 printf("%s %*s%s\n", fd < 0 ? "nf":"->",
1106 (s1->include_stack_ptr - s1->include_stack), "", filename);
1107 if (fd < 0)
1108 return NULL;
1109 bf = tcc_malloc(sizeof(BufferedFile));
1110 bf->fd = fd;
1111 bf->buf_ptr = bf->buffer;
1112 bf->buf_end = bf->buffer;
1113 bf->buffer[0] = CH_EOB; /* put eob symbol */
1114 pstrcpy(bf->filename, sizeof(bf->filename), filename);
1115 #ifdef _WIN32
1116 normalize_slashes(bf->filename);
1117 #endif
1118 bf->line_num = 1;
1119 bf->ifndef_macro = 0;
1120 bf->ifdef_stack_ptr = s1->ifdef_stack_ptr;
1121 // printf("opening '%s'\n", filename);
1122 return bf;
1125 void tcc_close(BufferedFile *bf)
1127 total_lines += bf->line_num;
1128 close(bf->fd);
1129 tcc_free(bf);
1132 #include "tccpp.c"
1133 #include "tccgen.c"
1136 /* compile the C file opened in 'file'. Return non zero if errors. */
1137 static int tcc_compile(TCCState *s1)
1139 Sym *define_start;
1140 char buf[512];
1141 volatile int section_sym;
1143 #ifdef INC_DEBUG
1144 printf("%s: **** new file\n", file->filename);
1145 #endif
1146 preprocess_init(s1);
1148 cur_text_section = NULL;
1149 funcname = "";
1150 anon_sym = SYM_FIRST_ANOM;
1152 /* file info: full path + filename */
1153 section_sym = 0; /* avoid warning */
1154 if (s1->do_debug) {
1155 section_sym = put_elf_sym(symtab_section, 0, 0,
1156 ELFW(ST_INFO)(STB_LOCAL, STT_SECTION), 0,
1157 text_section->sh_num, NULL);
1158 getcwd(buf, sizeof(buf));
1159 #ifdef _WIN32
1160 normalize_slashes(buf);
1161 #endif
1162 pstrcat(buf, sizeof(buf), "/");
1163 put_stabs_r(buf, N_SO, 0, 0,
1164 text_section->data_offset, text_section, section_sym);
1165 put_stabs_r(file->filename, N_SO, 0, 0,
1166 text_section->data_offset, text_section, section_sym);
1168 /* an elf symbol of type STT_FILE must be put so that STB_LOCAL
1169 symbols can be safely used */
1170 put_elf_sym(symtab_section, 0, 0,
1171 ELFW(ST_INFO)(STB_LOCAL, STT_FILE), 0,
1172 SHN_ABS, file->filename);
1174 /* define some often used types */
1175 int_type.t = VT_INT;
1177 char_pointer_type.t = VT_BYTE;
1178 mk_pointer(&char_pointer_type);
1180 func_old_type.t = VT_FUNC;
1181 func_old_type.ref = sym_push(SYM_FIELD, &int_type, FUNC_CDECL, FUNC_OLD);
1183 #if defined(TCC_ARM_EABI) && defined(TCC_ARM_VFP)
1184 float_type.t = VT_FLOAT;
1185 double_type.t = VT_DOUBLE;
1187 func_float_type.t = VT_FUNC;
1188 func_float_type.ref = sym_push(SYM_FIELD, &float_type, FUNC_CDECL, FUNC_OLD);
1189 func_double_type.t = VT_FUNC;
1190 func_double_type.ref = sym_push(SYM_FIELD, &double_type, FUNC_CDECL, FUNC_OLD);
1191 #endif
1193 #if 0
1194 /* define 'void *alloca(unsigned int)' builtin function */
1196 Sym *s1;
1198 p = anon_sym++;
1199 sym = sym_push(p, mk_pointer(VT_VOID), FUNC_CDECL, FUNC_NEW);
1200 s1 = sym_push(SYM_FIELD, VT_UNSIGNED | VT_INT, 0, 0);
1201 s1->next = NULL;
1202 sym->next = s1;
1203 sym_push(TOK_alloca, VT_FUNC | (p << VT_STRUCT_SHIFT), VT_CONST, 0);
1205 #endif
1207 define_start = define_stack;
1208 nocode_wanted = 1;
1210 if (setjmp(s1->error_jmp_buf) == 0) {
1211 s1->nb_errors = 0;
1212 s1->error_set_jmp_enabled = 1;
1214 ch = file->buf_ptr[0];
1215 tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
1216 parse_flags = PARSE_FLAG_PREPROCESS | PARSE_FLAG_TOK_NUM;
1217 next();
1218 decl(VT_CONST);
1219 if (tok != TOK_EOF)
1220 expect("declaration");
1222 /* end of translation unit info */
1223 if (s1->do_debug) {
1224 put_stabs_r(NULL, N_SO, 0, 0,
1225 text_section->data_offset, text_section, section_sym);
1228 s1->error_set_jmp_enabled = 0;
1230 /* reset define stack, but leave -Dsymbols (may be incorrect if
1231 they are undefined) */
1232 free_defines(define_start);
1234 gen_inline_functions();
1236 sym_pop(&global_stack, NULL);
1237 sym_pop(&local_stack, NULL);
1239 return s1->nb_errors != 0 ? -1 : 0;
1242 int tcc_compile_string(TCCState *s, const char *str)
1244 BufferedFile bf1, *bf = &bf1;
1245 int ret, len;
1246 char *buf;
1248 /* init file structure */
1249 bf->fd = -1;
1250 /* XXX: avoid copying */
1251 len = strlen(str);
1252 buf = tcc_malloc(len + 1);
1253 if (!buf)
1254 return -1;
1255 memcpy(buf, str, len);
1256 buf[len] = CH_EOB;
1257 bf->buf_ptr = buf;
1258 bf->buf_end = buf + len;
1259 pstrcpy(bf->filename, sizeof(bf->filename), "<string>");
1260 bf->line_num = 1;
1261 file = bf;
1262 ret = tcc_compile(s);
1263 file = NULL;
1264 tcc_free(buf);
1266 /* currently, no need to close */
1267 return ret;
1270 /* define a preprocessor symbol. A value can also be provided with the '=' operator */
1271 void tcc_define_symbol(TCCState *s1, const char *sym, const char *value)
1273 BufferedFile bf1, *bf = &bf1;
1275 pstrcpy(bf->buffer, IO_BUF_SIZE, sym);
1276 pstrcat(bf->buffer, IO_BUF_SIZE, " ");
1277 /* default value */
1278 if (!value)
1279 value = "1";
1280 pstrcat(bf->buffer, IO_BUF_SIZE, value);
1282 /* init file structure */
1283 bf->fd = -1;
1284 bf->buf_ptr = bf->buffer;
1285 bf->buf_end = bf->buffer + strlen(bf->buffer);
1286 *bf->buf_end = CH_EOB;
1287 bf->filename[0] = '\0';
1288 bf->line_num = 1;
1289 file = bf;
1291 s1->include_stack_ptr = s1->include_stack;
1293 /* parse with define parser */
1294 ch = file->buf_ptr[0];
1295 next_nomacro();
1296 parse_define();
1297 file = NULL;
1300 /* undefine a preprocessor symbol */
1301 void tcc_undefine_symbol(TCCState *s1, const char *sym)
1303 TokenSym *ts;
1304 Sym *s;
1305 ts = tok_alloc(sym, strlen(sym));
1306 s = define_find(ts->tok);
1307 /* undefine symbol by putting an invalid name */
1308 if (s)
1309 define_undef(s);
1312 #ifdef CONFIG_TCC_ASM
1314 #ifdef TCC_TARGET_I386
1315 #include "i386-asm.c"
1316 #endif
1317 #include "tccasm.c"
1319 #else
1320 static void asm_instr(void)
1322 error("inline asm() not supported");
1324 static void asm_global_instr(void)
1326 error("inline asm() not supported");
1328 #endif
1330 #include "tccelf.c"
1332 #ifdef TCC_TARGET_COFF
1333 #include "tcccoff.c"
1334 #endif
1336 #ifdef TCC_TARGET_PE
1337 #include "tccpe.c"
1338 #endif
1340 #ifdef CONFIG_TCC_BACKTRACE
1341 /* print the position in the source file of PC value 'pc' by reading
1342 the stabs debug information */
1343 static void rt_printline(unsigned long wanted_pc)
1345 Stab_Sym *sym, *sym_end;
1346 char func_name[128], last_func_name[128];
1347 unsigned long func_addr, last_pc, pc;
1348 const char *incl_files[INCLUDE_STACK_SIZE];
1349 int incl_index, len, last_line_num, i;
1350 const char *str, *p;
1352 fprintf(stderr, "0x%08lx:", wanted_pc);
1354 func_name[0] = '\0';
1355 func_addr = 0;
1356 incl_index = 0;
1357 last_func_name[0] = '\0';
1358 last_pc = 0xffffffff;
1359 last_line_num = 1;
1360 sym = (Stab_Sym *)stab_section->data + 1;
1361 sym_end = (Stab_Sym *)(stab_section->data + stab_section->data_offset);
1362 while (sym < sym_end) {
1363 switch(sym->n_type) {
1364 /* function start or end */
1365 case N_FUN:
1366 if (sym->n_strx == 0) {
1367 /* we test if between last line and end of function */
1368 pc = sym->n_value + func_addr;
1369 if (wanted_pc >= last_pc && wanted_pc < pc)
1370 goto found;
1371 func_name[0] = '\0';
1372 func_addr = 0;
1373 } else {
1374 str = stabstr_section->data + sym->n_strx;
1375 p = strchr(str, ':');
1376 if (!p) {
1377 pstrcpy(func_name, sizeof(func_name), str);
1378 } else {
1379 len = p - str;
1380 if (len > sizeof(func_name) - 1)
1381 len = sizeof(func_name) - 1;
1382 memcpy(func_name, str, len);
1383 func_name[len] = '\0';
1385 func_addr = sym->n_value;
1387 break;
1388 /* line number info */
1389 case N_SLINE:
1390 pc = sym->n_value + func_addr;
1391 if (wanted_pc >= last_pc && wanted_pc < pc)
1392 goto found;
1393 last_pc = pc;
1394 last_line_num = sym->n_desc;
1395 /* XXX: slow! */
1396 strcpy(last_func_name, func_name);
1397 break;
1398 /* include files */
1399 case N_BINCL:
1400 str = stabstr_section->data + sym->n_strx;
1401 add_incl:
1402 if (incl_index < INCLUDE_STACK_SIZE) {
1403 incl_files[incl_index++] = str;
1405 break;
1406 case N_EINCL:
1407 if (incl_index > 1)
1408 incl_index--;
1409 break;
1410 case N_SO:
1411 if (sym->n_strx == 0) {
1412 incl_index = 0; /* end of translation unit */
1413 } else {
1414 str = stabstr_section->data + sym->n_strx;
1415 /* do not add path */
1416 len = strlen(str);
1417 if (len > 0 && str[len - 1] != '/')
1418 goto add_incl;
1420 break;
1422 sym++;
1425 /* second pass: we try symtab symbols (no line number info) */
1426 incl_index = 0;
1428 ElfW(Sym) *sym, *sym_end;
1429 int type;
1431 sym_end = (ElfW(Sym) *)(symtab_section->data + symtab_section->data_offset);
1432 for(sym = (ElfW(Sym) *)symtab_section->data + 1;
1433 sym < sym_end;
1434 sym++) {
1435 type = ELFW(ST_TYPE)(sym->st_info);
1436 if (type == STT_FUNC) {
1437 if (wanted_pc >= sym->st_value &&
1438 wanted_pc < sym->st_value + sym->st_size) {
1439 pstrcpy(last_func_name, sizeof(last_func_name),
1440 strtab_section->data + sym->st_name);
1441 goto found;
1446 /* did not find any info: */
1447 fprintf(stderr, " ???\n");
1448 return;
1449 found:
1450 if (last_func_name[0] != '\0') {
1451 fprintf(stderr, " %s()", last_func_name);
1453 if (incl_index > 0) {
1454 fprintf(stderr, " (%s:%d",
1455 incl_files[incl_index - 1], last_line_num);
1456 for(i = incl_index - 2; i >= 0; i--)
1457 fprintf(stderr, ", included from %s", incl_files[i]);
1458 fprintf(stderr, ")");
1460 fprintf(stderr, "\n");
1463 #ifdef __i386__
1464 /* fix for glibc 2.1 */
1465 #ifndef REG_EIP
1466 #define REG_EIP EIP
1467 #define REG_EBP EBP
1468 #endif
1470 /* return the PC at frame level 'level'. Return non zero if not found */
1471 static int rt_get_caller_pc(unsigned long *paddr,
1472 ucontext_t *uc, int level)
1474 unsigned long fp;
1475 int i;
1477 if (level == 0) {
1478 #if defined(__FreeBSD__)
1479 *paddr = uc->uc_mcontext.mc_eip;
1480 #elif defined(__dietlibc__)
1481 *paddr = uc->uc_mcontext.eip;
1482 #else
1483 *paddr = uc->uc_mcontext.gregs[REG_EIP];
1484 #endif
1485 return 0;
1486 } else {
1487 #if defined(__FreeBSD__)
1488 fp = uc->uc_mcontext.mc_ebp;
1489 #elif defined(__dietlibc__)
1490 fp = uc->uc_mcontext.ebp;
1491 #else
1492 fp = uc->uc_mcontext.gregs[REG_EBP];
1493 #endif
1494 for(i=1;i<level;i++) {
1495 /* XXX: check address validity with program info */
1496 if (fp <= 0x1000 || fp >= 0xc0000000)
1497 return -1;
1498 fp = ((unsigned long *)fp)[0];
1500 *paddr = ((unsigned long *)fp)[1];
1501 return 0;
1504 #elif defined(__x86_64__)
1505 /* return the PC at frame level 'level'. Return non zero if not found */
1506 static int rt_get_caller_pc(unsigned long *paddr,
1507 ucontext_t *uc, int level)
1509 unsigned long fp;
1510 int i;
1512 if (level == 0) {
1513 /* XXX: only support linux */
1514 *paddr = uc->uc_mcontext.gregs[REG_RIP];
1515 return 0;
1516 } else {
1517 fp = uc->uc_mcontext.gregs[REG_RBP];
1518 for(i=1;i<level;i++) {
1519 /* XXX: check address validity with program info */
1520 if (fp <= 0x1000)
1521 return -1;
1522 fp = ((unsigned long *)fp)[0];
1524 *paddr = ((unsigned long *)fp)[1];
1525 return 0;
1528 #else
1529 #warning add arch specific rt_get_caller_pc()
1530 static int rt_get_caller_pc(unsigned long *paddr,
1531 ucontext_t *uc, int level)
1533 return -1;
1535 #endif
1537 /* emit a run time error at position 'pc' */
1538 void rt_error(ucontext_t *uc, const char *fmt, ...)
1540 va_list ap;
1541 unsigned long pc;
1542 int i;
1544 va_start(ap, fmt);
1545 fprintf(stderr, "Runtime error: ");
1546 vfprintf(stderr, fmt, ap);
1547 fprintf(stderr, "\n");
1548 for(i=0;i<num_callers;i++) {
1549 if (rt_get_caller_pc(&pc, uc, i) < 0)
1550 break;
1551 if (i == 0)
1552 fprintf(stderr, "at ");
1553 else
1554 fprintf(stderr, "by ");
1555 rt_printline(pc);
1557 exit(255);
1558 va_end(ap);
1561 /* signal handler for fatal errors */
1562 static void sig_error(int signum, siginfo_t *siginf, void *puc)
1564 ucontext_t *uc = puc;
1566 switch(signum) {
1567 case SIGFPE:
1568 switch(siginf->si_code) {
1569 case FPE_INTDIV:
1570 case FPE_FLTDIV:
1571 rt_error(uc, "division by zero");
1572 break;
1573 default:
1574 rt_error(uc, "floating point exception");
1575 break;
1577 break;
1578 case SIGBUS:
1579 case SIGSEGV:
1580 if (rt_bound_error_msg && *rt_bound_error_msg)
1581 rt_error(uc, *rt_bound_error_msg);
1582 else
1583 rt_error(uc, "dereferencing invalid pointer");
1584 break;
1585 case SIGILL:
1586 rt_error(uc, "illegal instruction");
1587 break;
1588 case SIGABRT:
1589 rt_error(uc, "abort() called");
1590 break;
1591 default:
1592 rt_error(uc, "caught signal %d", signum);
1593 break;
1595 exit(255);
1598 #endif
1600 /* copy code into memory passed in by the caller and do all relocations
1601 (needed before using tcc_get_symbol()).
1602 returns -1 on error and required size if ptr is NULL */
1603 int tcc_relocate(TCCState *s1, void *ptr)
1605 Section *s;
1606 unsigned long offset, length, mem;
1607 int i;
1609 if (0 == s1->runtime_added) {
1610 s1->runtime_added = 1;
1611 s1->nb_errors = 0;
1612 #ifdef TCC_TARGET_PE
1613 pe_add_runtime(s1);
1614 relocate_common_syms();
1615 tcc_add_linker_symbols(s1);
1616 #else
1617 tcc_add_runtime(s1);
1618 relocate_common_syms();
1619 tcc_add_linker_symbols(s1);
1620 build_got_entries(s1);
1621 #endif
1624 offset = 0, mem = (unsigned long)ptr;
1625 for(i = 1; i < s1->nb_sections; i++) {
1626 s = s1->sections[i];
1627 if (0 == (s->sh_flags & SHF_ALLOC))
1628 continue;
1629 length = s->data_offset;
1630 s->sh_addr = mem ? (mem + offset + 15) & ~15 : 0;
1631 offset = (offset + length + 15) & ~15;
1634 /* relocate symbols */
1635 relocate_syms(s1, 1);
1636 if (s1->nb_errors)
1637 return -1;
1639 #ifdef TCC_TARGET_X86_64
1640 s1->runtime_plt_and_got_offset = 0;
1641 s1->runtime_plt_and_got = (char *)(mem + offset);
1642 /* double the size of the buffer for got and plt entries
1643 XXX: calculate exact size for them? */
1644 offset *= 2;
1645 #endif
1647 if (0 == mem)
1648 return offset + 15;
1650 /* relocate each section */
1651 for(i = 1; i < s1->nb_sections; i++) {
1652 s = s1->sections[i];
1653 if (s->reloc)
1654 relocate_section(s1, s);
1657 for(i = 1; i < s1->nb_sections; i++) {
1658 s = s1->sections[i];
1659 if (0 == (s->sh_flags & SHF_ALLOC))
1660 continue;
1661 length = s->data_offset;
1662 // printf("%-12s %08x %04x\n", s->name, s->sh_addr, length);
1663 ptr = (void*)s->sh_addr;
1664 if (NULL == s->data || s->sh_type == SHT_NOBITS)
1665 memset(ptr, 0, length);
1666 else
1667 memcpy(ptr, s->data, length);
1668 /* mark executable sections as executable in memory */
1669 if (s->sh_flags & SHF_EXECINSTR)
1670 set_pages_executable(ptr, length);
1672 #ifdef TCC_TARGET_X86_64
1673 set_pages_executable(s1->runtime_plt_and_got,
1674 s1->runtime_plt_and_got_offset);
1675 #endif
1676 return 0;
1679 /* launch the compiled program with the given arguments */
1680 int tcc_run(TCCState *s1, int argc, char **argv)
1682 int (*prog_main)(int, char **);
1683 void *ptr;
1684 int ret;
1686 ret = tcc_relocate(s1, NULL);
1687 if (ret < 0)
1688 return -1;
1689 ptr = tcc_malloc(ret);
1690 tcc_relocate(s1, ptr);
1692 prog_main = tcc_get_symbol_err(s1, "main");
1694 if (s1->do_debug) {
1695 #ifdef CONFIG_TCC_BACKTRACE
1696 struct sigaction sigact;
1697 /* install TCC signal handlers to print debug info on fatal
1698 runtime errors */
1699 sigact.sa_flags = SA_SIGINFO | SA_RESETHAND;
1700 sigact.sa_sigaction = sig_error;
1701 sigemptyset(&sigact.sa_mask);
1702 sigaction(SIGFPE, &sigact, NULL);
1703 sigaction(SIGILL, &sigact, NULL);
1704 sigaction(SIGSEGV, &sigact, NULL);
1705 sigaction(SIGBUS, &sigact, NULL);
1706 sigaction(SIGABRT, &sigact, NULL);
1707 #else
1708 error("debug mode not available");
1709 #endif
1712 #ifdef CONFIG_TCC_BCHECK
1713 if (s1->do_bounds_check) {
1714 void (*bound_init)(void);
1716 /* set error function */
1717 rt_bound_error_msg = tcc_get_symbol_err(s1, "__bound_error_msg");
1719 /* XXX: use .init section so that it also work in binary ? */
1720 bound_init = (void *)tcc_get_symbol_err(s1, "__bound_init");
1721 bound_init();
1723 #endif
1724 ret = (*prog_main)(argc, argv);
1725 tcc_free(ptr);
1726 return ret;
1729 void tcc_memstats(void)
1731 #ifdef MEM_DEBUG
1732 printf("memory in use: %d\n", mem_cur_size);
1733 #endif
1736 static void tcc_cleanup(void)
1738 int i, n;
1740 if (NULL == tcc_state)
1741 return;
1742 tcc_state = NULL;
1744 /* free -D defines */
1745 free_defines(NULL);
1747 /* free tokens */
1748 n = tok_ident - TOK_IDENT;
1749 for(i = 0; i < n; i++)
1750 tcc_free(table_ident[i]);
1751 tcc_free(table_ident);
1753 /* free sym_pools */
1754 dynarray_reset(&sym_pools, &nb_sym_pools);
1755 /* string buffer */
1756 cstr_free(&tokcstr);
1757 /* reset symbol stack */
1758 sym_free_first = NULL;
1759 /* cleanup from error/setjmp */
1760 macro_ptr = NULL;
1763 TCCState *tcc_new(void)
1765 TCCState *s;
1767 tcc_cleanup();
1769 s = tcc_mallocz(sizeof(TCCState));
1770 if (!s)
1771 return NULL;
1772 tcc_state = s;
1773 s->output_type = TCC_OUTPUT_MEMORY;
1774 s->tcc_lib_path = CONFIG_TCCDIR;
1776 preprocess_new();
1778 /* we add dummy defines for some special macros to speed up tests
1779 and to have working defined() */
1780 define_push(TOK___LINE__, MACRO_OBJ, NULL, NULL);
1781 define_push(TOK___FILE__, MACRO_OBJ, NULL, NULL);
1782 define_push(TOK___DATE__, MACRO_OBJ, NULL, NULL);
1783 define_push(TOK___TIME__, MACRO_OBJ, NULL, NULL);
1785 /* standard defines */
1786 tcc_define_symbol(s, "__STDC__", NULL);
1787 tcc_define_symbol(s, "__STDC_VERSION__", "199901L");
1788 #if defined(TCC_TARGET_I386)
1789 tcc_define_symbol(s, "__i386__", NULL);
1790 #endif
1791 #if defined(TCC_TARGET_X86_64)
1792 tcc_define_symbol(s, "__x86_64__", NULL);
1793 #endif
1794 #if defined(TCC_TARGET_ARM)
1795 tcc_define_symbol(s, "__ARM_ARCH_4__", NULL);
1796 tcc_define_symbol(s, "__arm_elf__", NULL);
1797 tcc_define_symbol(s, "__arm_elf", NULL);
1798 tcc_define_symbol(s, "arm_elf", NULL);
1799 tcc_define_symbol(s, "__arm__", NULL);
1800 tcc_define_symbol(s, "__arm", NULL);
1801 tcc_define_symbol(s, "arm", NULL);
1802 tcc_define_symbol(s, "__APCS_32__", NULL);
1803 #endif
1804 #ifdef TCC_TARGET_PE
1805 tcc_define_symbol(s, "_WIN32", NULL);
1806 #else
1807 tcc_define_symbol(s, "__unix__", NULL);
1808 tcc_define_symbol(s, "__unix", NULL);
1809 #if defined(__linux)
1810 tcc_define_symbol(s, "__linux__", NULL);
1811 tcc_define_symbol(s, "__linux", NULL);
1812 #endif
1813 #endif
1814 /* tiny C specific defines */
1815 tcc_define_symbol(s, "__TINYC__", NULL);
1817 /* tiny C & gcc defines */
1818 tcc_define_symbol(s, "__SIZE_TYPE__", "unsigned int");
1819 tcc_define_symbol(s, "__PTRDIFF_TYPE__", "int");
1820 #ifdef TCC_TARGET_PE
1821 tcc_define_symbol(s, "__WCHAR_TYPE__", "unsigned short");
1822 #else
1823 tcc_define_symbol(s, "__WCHAR_TYPE__", "int");
1824 #endif
1826 #ifndef TCC_TARGET_PE
1827 /* default library paths */
1828 tcc_add_library_path(s, CONFIG_SYSROOT "/usr/local/lib");
1829 tcc_add_library_path(s, CONFIG_SYSROOT "/usr/lib");
1830 tcc_add_library_path(s, CONFIG_SYSROOT "/lib");
1831 #endif
1833 /* no section zero */
1834 dynarray_add((void ***)&s->sections, &s->nb_sections, NULL);
1836 /* create standard sections */
1837 text_section = new_section(s, ".text", SHT_PROGBITS, SHF_ALLOC | SHF_EXECINSTR);
1838 data_section = new_section(s, ".data", SHT_PROGBITS, SHF_ALLOC | SHF_WRITE);
1839 bss_section = new_section(s, ".bss", SHT_NOBITS, SHF_ALLOC | SHF_WRITE);
1841 /* symbols are always generated for linking stage */
1842 symtab_section = new_symtab(s, ".symtab", SHT_SYMTAB, 0,
1843 ".strtab",
1844 ".hashtab", SHF_PRIVATE);
1845 strtab_section = symtab_section->link;
1847 /* private symbol table for dynamic symbols */
1848 s->dynsymtab_section = new_symtab(s, ".dynsymtab", SHT_SYMTAB, SHF_PRIVATE,
1849 ".dynstrtab",
1850 ".dynhashtab", SHF_PRIVATE);
1851 s->alacarte_link = 1;
1853 #ifdef CHAR_IS_UNSIGNED
1854 s->char_is_unsigned = 1;
1855 #endif
1856 #if defined(TCC_TARGET_PE) && 0
1857 /* XXX: currently the PE linker is not ready to support that */
1858 s->leading_underscore = 1;
1859 #endif
1860 return s;
1863 void tcc_delete(TCCState *s1)
1865 int i;
1867 tcc_cleanup();
1869 /* free all sections */
1870 for(i = 1; i < s1->nb_sections; i++)
1871 free_section(s1->sections[i]);
1872 dynarray_reset(&s1->sections, &s1->nb_sections);
1874 for(i = 0; i < s1->nb_priv_sections; i++)
1875 free_section(s1->priv_sections[i]);
1876 dynarray_reset(&s1->priv_sections, &s1->nb_priv_sections);
1878 /* free any loaded DLLs */
1879 for ( i = 0; i < s1->nb_loaded_dlls; i++) {
1880 DLLReference *ref = s1->loaded_dlls[i];
1881 if ( ref->handle )
1882 dlclose(ref->handle);
1885 /* free loaded dlls array */
1886 dynarray_reset(&s1->loaded_dlls, &s1->nb_loaded_dlls);
1888 /* free library paths */
1889 dynarray_reset(&s1->library_paths, &s1->nb_library_paths);
1891 /* free include paths */
1892 dynarray_reset(&s1->cached_includes, &s1->nb_cached_includes);
1893 dynarray_reset(&s1->include_paths, &s1->nb_include_paths);
1894 dynarray_reset(&s1->sysinclude_paths, &s1->nb_sysinclude_paths);
1896 tcc_free(s1);
1899 int tcc_add_include_path(TCCState *s1, const char *pathname)
1901 char *pathname1;
1903 pathname1 = tcc_strdup(pathname);
1904 dynarray_add((void ***)&s1->include_paths, &s1->nb_include_paths, pathname1);
1905 return 0;
1908 int tcc_add_sysinclude_path(TCCState *s1, const char *pathname)
1910 char *pathname1;
1912 pathname1 = tcc_strdup(pathname);
1913 dynarray_add((void ***)&s1->sysinclude_paths, &s1->nb_sysinclude_paths, pathname1);
1914 return 0;
1917 static int tcc_add_file_internal(TCCState *s1, const char *filename, int flags)
1919 const char *ext;
1920 ElfW(Ehdr) ehdr;
1921 int fd, ret;
1922 BufferedFile *saved_file;
1924 /* find source file type with extension */
1925 ext = tcc_fileextension(filename);
1926 if (ext[0])
1927 ext++;
1929 /* open the file */
1930 saved_file = file;
1931 file = tcc_open(s1, filename);
1932 if (!file) {
1933 if (flags & AFF_PRINT_ERROR) {
1934 error_noabort("file '%s' not found", filename);
1936 ret = -1;
1937 goto fail1;
1940 if (flags & AFF_PREPROCESS) {
1941 ret = tcc_preprocess(s1);
1942 } else if (!ext[0] || !PATHCMP(ext, "c")) {
1943 /* C file assumed */
1944 ret = tcc_compile(s1);
1945 } else
1946 #ifdef CONFIG_TCC_ASM
1947 if (!strcmp(ext, "S")) {
1948 /* preprocessed assembler */
1949 ret = tcc_assemble(s1, 1);
1950 } else if (!strcmp(ext, "s")) {
1951 /* non preprocessed assembler */
1952 ret = tcc_assemble(s1, 0);
1953 } else
1954 #endif
1955 #ifdef TCC_TARGET_PE
1956 if (!PATHCMP(ext, "def")) {
1957 ret = pe_load_def_file(s1, file->fd);
1958 } else
1959 #endif
1961 fd = file->fd;
1962 /* assume executable format: auto guess file type */
1963 ret = read(fd, &ehdr, sizeof(ehdr));
1964 lseek(fd, 0, SEEK_SET);
1965 if (ret <= 0) {
1966 error_noabort("could not read header");
1967 goto fail;
1968 } else if (ret != sizeof(ehdr)) {
1969 goto try_load_script;
1972 if (ehdr.e_ident[0] == ELFMAG0 &&
1973 ehdr.e_ident[1] == ELFMAG1 &&
1974 ehdr.e_ident[2] == ELFMAG2 &&
1975 ehdr.e_ident[3] == ELFMAG3) {
1976 file->line_num = 0; /* do not display line number if error */
1977 if (ehdr.e_type == ET_REL) {
1978 ret = tcc_load_object_file(s1, fd, 0);
1979 } else if (ehdr.e_type == ET_DYN) {
1980 if (s1->output_type == TCC_OUTPUT_MEMORY) {
1981 #ifdef TCC_TARGET_PE
1982 ret = -1;
1983 #else
1984 void *h;
1985 h = dlopen(filename, RTLD_GLOBAL | RTLD_LAZY);
1986 if (h)
1987 ret = 0;
1988 else
1989 ret = -1;
1990 #endif
1991 } else {
1992 ret = tcc_load_dll(s1, fd, filename,
1993 (flags & AFF_REFERENCED_DLL) != 0);
1995 } else {
1996 error_noabort("unrecognized ELF file");
1997 goto fail;
1999 } else if (memcmp((char *)&ehdr, ARMAG, 8) == 0) {
2000 file->line_num = 0; /* do not display line number if error */
2001 ret = tcc_load_archive(s1, fd);
2002 } else
2003 #ifdef TCC_TARGET_COFF
2004 if (*(uint16_t *)(&ehdr) == COFF_C67_MAGIC) {
2005 ret = tcc_load_coff(s1, fd);
2006 } else
2007 #endif
2008 #ifdef TCC_TARGET_PE
2009 if (pe_test_res_file(&ehdr, ret)) {
2010 ret = pe_load_res_file(s1, fd);
2011 } else
2012 #endif
2014 /* as GNU ld, consider it is an ld script if not recognized */
2015 try_load_script:
2016 ret = tcc_load_ldscript(s1);
2017 if (ret < 0) {
2018 error_noabort("unrecognized file type");
2019 goto fail;
2023 the_end:
2024 tcc_close(file);
2025 fail1:
2026 file = saved_file;
2027 return ret;
2028 fail:
2029 ret = -1;
2030 goto the_end;
2033 int tcc_add_file(TCCState *s, const char *filename)
2035 if (s->output_type == TCC_OUTPUT_PREPROCESS)
2036 return tcc_add_file_internal(s, filename, AFF_PRINT_ERROR | AFF_PREPROCESS);
2037 else
2038 return tcc_add_file_internal(s, filename, AFF_PRINT_ERROR);
2041 int tcc_add_library_path(TCCState *s, const char *pathname)
2043 char *pathname1;
2045 pathname1 = tcc_strdup(pathname);
2046 dynarray_add((void ***)&s->library_paths, &s->nb_library_paths, pathname1);
2047 return 0;
2050 /* find and load a dll. Return non zero if not found */
2051 /* XXX: add '-rpath' option support ? */
2052 static int tcc_add_dll(TCCState *s, const char *filename, int flags)
2054 char buf[1024];
2055 int i;
2057 for(i = 0; i < s->nb_library_paths; i++) {
2058 snprintf(buf, sizeof(buf), "%s/%s",
2059 s->library_paths[i], filename);
2060 if (tcc_add_file_internal(s, buf, flags) == 0)
2061 return 0;
2063 return -1;
2066 /* the library name is the same as the argument of the '-l' option */
2067 int tcc_add_library(TCCState *s, const char *libraryname)
2069 char buf[1024];
2070 int i;
2072 /* first we look for the dynamic library if not static linking */
2073 if (!s->static_link) {
2074 #ifdef TCC_TARGET_PE
2075 snprintf(buf, sizeof(buf), "%s.def", libraryname);
2076 #else
2077 snprintf(buf, sizeof(buf), "lib%s.so", libraryname);
2078 #endif
2079 if (tcc_add_dll(s, buf, 0) == 0)
2080 return 0;
2083 /* then we look for the static library */
2084 for(i = 0; i < s->nb_library_paths; i++) {
2085 snprintf(buf, sizeof(buf), "%s/lib%s.a",
2086 s->library_paths[i], libraryname);
2087 if (tcc_add_file_internal(s, buf, 0) == 0)
2088 return 0;
2090 return -1;
2093 int tcc_add_symbol(TCCState *s, const char *name, void *val)
2095 add_elf_sym(symtab_section, (unsigned long)val, 0,
2096 ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE), 0,
2097 SHN_ABS, name);
2098 return 0;
2101 int tcc_set_output_type(TCCState *s, int output_type)
2103 char buf[1024];
2105 s->output_type = output_type;
2107 if (!s->nostdinc) {
2108 /* default include paths */
2109 /* XXX: reverse order needed if -isystem support */
2110 #ifndef TCC_TARGET_PE
2111 tcc_add_sysinclude_path(s, CONFIG_SYSROOT "/usr/local/include");
2112 tcc_add_sysinclude_path(s, CONFIG_SYSROOT "/usr/include");
2113 #endif
2114 snprintf(buf, sizeof(buf), "%s/include", s->tcc_lib_path);
2115 tcc_add_sysinclude_path(s, buf);
2116 #ifdef TCC_TARGET_PE
2117 snprintf(buf, sizeof(buf), "%s/include/winapi", s->tcc_lib_path);
2118 tcc_add_sysinclude_path(s, buf);
2119 #endif
2122 /* if bound checking, then add corresponding sections */
2123 #ifdef CONFIG_TCC_BCHECK
2124 if (s->do_bounds_check) {
2125 /* define symbol */
2126 tcc_define_symbol(s, "__BOUNDS_CHECKING_ON", NULL);
2127 /* create bounds sections */
2128 bounds_section = new_section(s, ".bounds",
2129 SHT_PROGBITS, SHF_ALLOC);
2130 lbounds_section = new_section(s, ".lbounds",
2131 SHT_PROGBITS, SHF_ALLOC);
2133 #endif
2135 if (s->char_is_unsigned) {
2136 tcc_define_symbol(s, "__CHAR_UNSIGNED__", NULL);
2139 /* add debug sections */
2140 if (s->do_debug) {
2141 /* stab symbols */
2142 stab_section = new_section(s, ".stab", SHT_PROGBITS, 0);
2143 stab_section->sh_entsize = sizeof(Stab_Sym);
2144 stabstr_section = new_section(s, ".stabstr", SHT_STRTAB, 0);
2145 put_elf_str(stabstr_section, "");
2146 stab_section->link = stabstr_section;
2147 /* put first entry */
2148 put_stabs("", 0, 0, 0, 0);
2151 /* add libc crt1/crti objects */
2152 #ifndef TCC_TARGET_PE
2153 if ((output_type == TCC_OUTPUT_EXE || output_type == TCC_OUTPUT_DLL) &&
2154 !s->nostdlib) {
2155 if (output_type != TCC_OUTPUT_DLL)
2156 tcc_add_file(s, CONFIG_TCC_CRT_PREFIX "/crt1.o");
2157 tcc_add_file(s, CONFIG_TCC_CRT_PREFIX "/crti.o");
2159 #endif
2161 #ifdef TCC_TARGET_PE
2162 snprintf(buf, sizeof(buf), "%s/lib", s->tcc_lib_path);
2163 tcc_add_library_path(s, buf);
2164 #endif
2166 return 0;
2169 #define WD_ALL 0x0001 /* warning is activated when using -Wall */
2170 #define FD_INVERT 0x0002 /* invert value before storing */
2172 typedef struct FlagDef {
2173 uint16_t offset;
2174 uint16_t flags;
2175 const char *name;
2176 } FlagDef;
2178 static const FlagDef warning_defs[] = {
2179 { offsetof(TCCState, warn_unsupported), 0, "unsupported" },
2180 { offsetof(TCCState, warn_write_strings), 0, "write-strings" },
2181 { offsetof(TCCState, warn_error), 0, "error" },
2182 { offsetof(TCCState, warn_implicit_function_declaration), WD_ALL,
2183 "implicit-function-declaration" },
2186 static int set_flag(TCCState *s, const FlagDef *flags, int nb_flags,
2187 const char *name, int value)
2189 int i;
2190 const FlagDef *p;
2191 const char *r;
2193 r = name;
2194 if (r[0] == 'n' && r[1] == 'o' && r[2] == '-') {
2195 r += 3;
2196 value = !value;
2198 for(i = 0, p = flags; i < nb_flags; i++, p++) {
2199 if (!strcmp(r, p->name))
2200 goto found;
2202 return -1;
2203 found:
2204 if (p->flags & FD_INVERT)
2205 value = !value;
2206 *(int *)((uint8_t *)s + p->offset) = value;
2207 return 0;
2211 /* set/reset a warning */
2212 int tcc_set_warning(TCCState *s, const char *warning_name, int value)
2214 int i;
2215 const FlagDef *p;
2217 if (!strcmp(warning_name, "all")) {
2218 for(i = 0, p = warning_defs; i < countof(warning_defs); i++, p++) {
2219 if (p->flags & WD_ALL)
2220 *(int *)((uint8_t *)s + p->offset) = 1;
2222 return 0;
2223 } else {
2224 return set_flag(s, warning_defs, countof(warning_defs),
2225 warning_name, value);
2229 static const FlagDef flag_defs[] = {
2230 { offsetof(TCCState, char_is_unsigned), 0, "unsigned-char" },
2231 { offsetof(TCCState, char_is_unsigned), FD_INVERT, "signed-char" },
2232 { offsetof(TCCState, nocommon), FD_INVERT, "common" },
2233 { offsetof(TCCState, leading_underscore), 0, "leading-underscore" },
2236 /* set/reset a flag */
2237 int tcc_set_flag(TCCState *s, const char *flag_name, int value)
2239 return set_flag(s, flag_defs, countof(flag_defs),
2240 flag_name, value);
2243 /* set CONFIG_TCCDIR at runtime */
2244 void tcc_set_lib_path(TCCState *s, const char *path)
2246 s->tcc_lib_path = tcc_strdup(path);
2249 void tcc_print_stats(TCCState *s, int64_t total_time)
2251 double tt;
2252 tt = (double)total_time / 1000000.0;
2253 if (tt < 0.001)
2254 tt = 0.001;
2255 if (total_bytes < 1)
2256 total_bytes = 1;
2257 printf("%d idents, %d lines, %d bytes, %0.3f s, %d lines/s, %0.1f MB/s\n",
2258 tok_ident - TOK_IDENT, total_lines, total_bytes,
2259 tt, (int)(total_lines / tt),
2260 total_bytes / tt / 1000000.0);