pp: return newline after directive
[tinycc/kirr.git] / libtcc.c
blobe1a10bf9b425b4c13b3140819ab5df324781e41d
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, unsigned long 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 void *resolve_sym(TCCState *s1, const char *sym, int type);
216 int pe_load_def_file(struct TCCState *s1, int fd);
217 int pe_test_res_file(void *v, int size);
218 int pe_load_res_file(struct TCCState *s1, int fd);
219 void pe_add_runtime(struct TCCState *s1);
220 void pe_guess_outfile(char *objfilename, int output_type);
221 int pe_output_file(struct TCCState *s1, const char *filename);
223 /* tccasm.c */
224 #ifdef CONFIG_TCC_ASM
225 static void asm_expr(TCCState *s1, ExprValue *pe);
226 static int asm_int_expr(TCCState *s1);
227 static int find_constraint(ASMOperand *operands, int nb_operands,
228 const char *name, const char **pp);
230 static int tcc_assemble(TCCState *s1, int do_preprocess);
231 #endif
233 static void asm_instr(void);
234 static void asm_global_instr(void);
236 /********************************************************/
237 /* global variables */
239 #ifdef TCC_TARGET_I386
240 #include "i386-gen.c"
241 #endif
243 #ifdef TCC_TARGET_ARM
244 #include "arm-gen.c"
245 #endif
247 #ifdef TCC_TARGET_C67
248 #include "c67-gen.c"
249 #endif
251 #ifdef TCC_TARGET_X86_64
252 #include "x86_64-gen.c"
253 #endif
255 #ifdef CONFIG_TCC_STATIC
257 #define RTLD_LAZY 0x001
258 #define RTLD_NOW 0x002
259 #define RTLD_GLOBAL 0x100
260 #define RTLD_DEFAULT NULL
262 /* dummy function for profiling */
263 void *dlopen(const char *filename, int flag)
265 return NULL;
268 void dlclose(void *p)
272 const char *dlerror(void)
274 return "error";
277 typedef struct TCCSyms {
278 char *str;
279 void *ptr;
280 } TCCSyms;
282 #define TCCSYM(a) { #a, &a, },
284 /* add the symbol you want here if no dynamic linking is done */
285 static TCCSyms tcc_syms[] = {
286 #if !defined(CONFIG_TCCBOOT)
287 TCCSYM(printf)
288 TCCSYM(fprintf)
289 TCCSYM(fopen)
290 TCCSYM(fclose)
291 #endif
292 { NULL, NULL },
295 void *resolve_sym(TCCState *s1, const char *symbol, int type)
297 TCCSyms *p;
298 p = tcc_syms;
299 while (p->str != NULL) {
300 if (!strcmp(p->str, symbol))
301 return p->ptr;
302 p++;
304 return NULL;
307 #elif !defined(_WIN32)
309 #include <dlfcn.h>
311 void *resolve_sym(TCCState *s1, const char *sym, int type)
313 return dlsym(RTLD_DEFAULT, sym);
316 #endif
318 /********************************************************/
320 /* we use our own 'finite' function to avoid potential problems with
321 non standard math libs */
322 /* XXX: endianness dependent */
323 int ieee_finite(double d)
325 int *p = (int *)&d;
326 return ((unsigned)((p[1] | 0x800fffff) + 1)) >> 31;
329 /* copy a string and truncate it. */
330 char *pstrcpy(char *buf, int buf_size, const char *s)
332 char *q, *q_end;
333 int c;
335 if (buf_size > 0) {
336 q = buf;
337 q_end = buf + buf_size - 1;
338 while (q < q_end) {
339 c = *s++;
340 if (c == '\0')
341 break;
342 *q++ = c;
344 *q = '\0';
346 return buf;
349 /* strcat and truncate. */
350 char *pstrcat(char *buf, int buf_size, const char *s)
352 int len;
353 len = strlen(buf);
354 if (len < buf_size)
355 pstrcpy(buf + len, buf_size - len, s);
356 return buf;
359 /* extract the basename of a file */
360 char *tcc_basename(const char *name)
362 char *p = strchr(name, 0);
363 while (p > name && !IS_PATHSEP(p[-1]))
364 --p;
365 return p;
368 char *tcc_fileextension (const char *name)
370 char *b = tcc_basename(name);
371 char *e = strrchr(b, '.');
372 return e ? e : strchr(b, 0);
375 #ifdef _WIN32
376 char *normalize_slashes(char *path)
378 char *p;
379 for (p = path; *p; ++p)
380 if (*p == '\\')
381 *p = '/';
382 return path;
385 void tcc_set_lib_path_w32(TCCState *s)
387 /* on win32, we suppose the lib and includes are at the location
388 of 'tcc.exe' */
389 char path[1024], *p;
390 GetModuleFileNameA(NULL, path, sizeof path);
391 p = tcc_basename(normalize_slashes(strlwr(path)));
392 if (p - 5 > path && 0 == strncmp(p - 5, "/bin/", 5))
393 p -= 5;
394 else if (p > path)
395 p--;
396 *p = 0;
397 tcc_set_lib_path(s, path);
399 #endif
401 void set_pages_executable(void *ptr, unsigned long length)
403 #ifdef _WIN32
404 unsigned long old_protect;
405 VirtualProtect(ptr, length, PAGE_EXECUTE_READWRITE, &old_protect);
406 #else
407 unsigned long start, end;
408 start = (unsigned long)ptr & ~(PAGESIZE - 1);
409 end = (unsigned long)ptr + length;
410 end = (end + PAGESIZE - 1) & ~(PAGESIZE - 1);
411 mprotect((void *)start, end - start, PROT_READ | PROT_WRITE | PROT_EXEC);
412 #endif
415 /* memory management */
416 #ifdef MEM_DEBUG
417 int mem_cur_size;
418 int mem_max_size;
419 unsigned malloc_usable_size(void*);
420 #endif
422 void tcc_free(void *ptr)
424 #ifdef MEM_DEBUG
425 mem_cur_size -= malloc_usable_size(ptr);
426 #endif
427 free(ptr);
430 void *tcc_malloc(unsigned long size)
432 void *ptr;
433 ptr = malloc(size);
434 if (!ptr && size)
435 error("memory full");
436 #ifdef MEM_DEBUG
437 mem_cur_size += malloc_usable_size(ptr);
438 if (mem_cur_size > mem_max_size)
439 mem_max_size = mem_cur_size;
440 #endif
441 return ptr;
444 void *tcc_mallocz(unsigned long size)
446 void *ptr;
447 ptr = tcc_malloc(size);
448 memset(ptr, 0, size);
449 return ptr;
452 void *tcc_realloc(void *ptr, unsigned long size)
454 void *ptr1;
455 #ifdef MEM_DEBUG
456 mem_cur_size -= malloc_usable_size(ptr);
457 #endif
458 ptr1 = realloc(ptr, size);
459 #ifdef MEM_DEBUG
460 /* NOTE: count not correct if alloc error, but not critical */
461 mem_cur_size += malloc_usable_size(ptr1);
462 if (mem_cur_size > mem_max_size)
463 mem_max_size = mem_cur_size;
464 #endif
465 return ptr1;
468 char *tcc_strdup(const char *str)
470 char *ptr;
471 ptr = tcc_malloc(strlen(str) + 1);
472 strcpy(ptr, str);
473 return ptr;
476 #define free(p) use_tcc_free(p)
477 #define malloc(s) use_tcc_malloc(s)
478 #define realloc(p, s) use_tcc_realloc(p, s)
480 void dynarray_add(void ***ptab, int *nb_ptr, void *data)
482 int nb, nb_alloc;
483 void **pp;
485 nb = *nb_ptr;
486 pp = *ptab;
487 /* every power of two we double array size */
488 if ((nb & (nb - 1)) == 0) {
489 if (!nb)
490 nb_alloc = 1;
491 else
492 nb_alloc = nb * 2;
493 pp = tcc_realloc(pp, nb_alloc * sizeof(void *));
494 if (!pp)
495 error("memory full");
496 *ptab = pp;
498 pp[nb++] = data;
499 *nb_ptr = nb;
502 void dynarray_reset(void *pp, int *n)
504 void **p;
505 for (p = *(void***)pp; *n; ++p, --*n)
506 if (*p)
507 tcc_free(*p);
508 tcc_free(*(void**)pp);
509 *(void**)pp = NULL;
512 /* symbol allocator */
513 static Sym *__sym_malloc(void)
515 Sym *sym_pool, *sym, *last_sym;
516 int i;
518 sym_pool = tcc_malloc(SYM_POOL_NB * sizeof(Sym));
519 dynarray_add(&sym_pools, &nb_sym_pools, sym_pool);
521 last_sym = sym_free_first;
522 sym = sym_pool;
523 for(i = 0; i < SYM_POOL_NB; i++) {
524 sym->next = last_sym;
525 last_sym = sym;
526 sym++;
528 sym_free_first = last_sym;
529 return last_sym;
532 static inline Sym *sym_malloc(void)
534 Sym *sym;
535 sym = sym_free_first;
536 if (!sym)
537 sym = __sym_malloc();
538 sym_free_first = sym->next;
539 return sym;
542 static inline void sym_free(Sym *sym)
544 sym->next = sym_free_first;
545 sym_free_first = sym;
548 Section *new_section(TCCState *s1, const char *name, int sh_type, int sh_flags)
550 Section *sec;
552 sec = tcc_mallocz(sizeof(Section) + strlen(name));
553 strcpy(sec->name, name);
554 sec->sh_type = sh_type;
555 sec->sh_flags = sh_flags;
556 switch(sh_type) {
557 case SHT_HASH:
558 case SHT_REL:
559 case SHT_RELA:
560 case SHT_DYNSYM:
561 case SHT_SYMTAB:
562 case SHT_DYNAMIC:
563 sec->sh_addralign = 4;
564 break;
565 case SHT_STRTAB:
566 sec->sh_addralign = 1;
567 break;
568 default:
569 sec->sh_addralign = 32; /* default conservative alignment */
570 break;
573 if (sh_flags & SHF_PRIVATE) {
574 dynarray_add((void ***)&s1->priv_sections, &s1->nb_priv_sections, sec);
575 } else {
576 sec->sh_num = s1->nb_sections;
577 dynarray_add((void ***)&s1->sections, &s1->nb_sections, sec);
580 return sec;
583 static void free_section(Section *s)
585 tcc_free(s->data);
588 /* realloc section and set its content to zero */
589 static void section_realloc(Section *sec, unsigned long new_size)
591 unsigned long size;
592 unsigned char *data;
594 size = sec->data_allocated;
595 if (size == 0)
596 size = 1;
597 while (size < new_size)
598 size = size * 2;
599 data = tcc_realloc(sec->data, size);
600 if (!data)
601 error("memory full");
602 memset(data + sec->data_allocated, 0, size - sec->data_allocated);
603 sec->data = data;
604 sec->data_allocated = size;
607 /* reserve at least 'size' bytes in section 'sec' from
608 sec->data_offset. */
609 static void *section_ptr_add(Section *sec, unsigned long size)
611 unsigned long offset, offset1;
613 offset = sec->data_offset;
614 offset1 = offset + size;
615 if (offset1 > sec->data_allocated)
616 section_realloc(sec, offset1);
617 sec->data_offset = offset1;
618 return sec->data + offset;
621 /* return a reference to a section, and create it if it does not
622 exists */
623 Section *find_section(TCCState *s1, const char *name)
625 Section *sec;
626 int i;
627 for(i = 1; i < s1->nb_sections; i++) {
628 sec = s1->sections[i];
629 if (!strcmp(name, sec->name))
630 return sec;
632 /* sections are created as PROGBITS */
633 return new_section(s1, name, SHT_PROGBITS, SHF_ALLOC);
636 /* update sym->c so that it points to an external symbol in section
637 'section' with value 'value' */
638 static void put_extern_sym2(Sym *sym, Section *section,
639 unsigned long value, unsigned long size,
640 int can_add_underscore)
642 int sym_type, sym_bind, sh_num, info, other, attr;
643 ElfW(Sym) *esym;
644 const char *name;
645 char buf1[256];
647 if (section == NULL)
648 sh_num = SHN_UNDEF;
649 else if (section == SECTION_ABS)
650 sh_num = SHN_ABS;
651 else
652 sh_num = section->sh_num;
654 other = attr = 0;
656 if ((sym->type.t & VT_BTYPE) == VT_FUNC) {
657 sym_type = STT_FUNC;
658 #ifdef TCC_TARGET_PE
659 if (sym->type.ref)
660 attr = sym->type.ref->r;
661 if (FUNC_EXPORT(attr))
662 other |= 1;
663 if (FUNC_CALL(attr) == FUNC_STDCALL)
664 other |= 2;
665 #endif
666 } else {
667 sym_type = STT_OBJECT;
670 if (sym->type.t & VT_STATIC)
671 sym_bind = STB_LOCAL;
672 else
673 sym_bind = STB_GLOBAL;
675 if (!sym->c) {
676 name = get_tok_str(sym->v, NULL);
677 #ifdef CONFIG_TCC_BCHECK
678 if (tcc_state->do_bounds_check) {
679 char buf[32];
681 /* XXX: avoid doing that for statics ? */
682 /* if bound checking is activated, we change some function
683 names by adding the "__bound" prefix */
684 switch(sym->v) {
685 #if 0
686 /* XXX: we rely only on malloc hooks */
687 case TOK_malloc:
688 case TOK_free:
689 case TOK_realloc:
690 case TOK_memalign:
691 case TOK_calloc:
692 #endif
693 case TOK_memcpy:
694 case TOK_memmove:
695 case TOK_memset:
696 case TOK_strlen:
697 case TOK_strcpy:
698 case TOK_alloca:
699 strcpy(buf, "__bound_");
700 strcat(buf, name);
701 name = buf;
702 break;
705 #endif
707 #ifdef TCC_TARGET_PE
708 if ((other & 2) && can_add_underscore) {
709 sprintf(buf1, "_%s@%d", name, FUNC_ARGS(attr));
710 name = buf1;
711 } else
712 #endif
713 if (tcc_state->leading_underscore && can_add_underscore) {
714 buf1[0] = '_';
715 pstrcpy(buf1 + 1, sizeof(buf1) - 1, name);
716 name = buf1;
718 info = ELFW(ST_INFO)(sym_bind, sym_type);
719 sym->c = add_elf_sym(symtab_section, value, size, info, other, sh_num, name);
720 } else {
721 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
722 esym->st_value = value;
723 esym->st_size = size;
724 esym->st_shndx = sh_num;
725 esym->st_other |= other;
729 static void put_extern_sym(Sym *sym, Section *section,
730 unsigned long value, unsigned long size)
732 put_extern_sym2(sym, section, value, size, 1);
735 /* add a new relocation entry to symbol 'sym' in section 's' */
736 static void greloc(Section *s, Sym *sym, unsigned long offset, int type)
738 if (!sym->c)
739 put_extern_sym(sym, NULL, 0, 0);
740 /* now we can add ELF relocation info */
741 put_elf_reloc(symtab_section, s, offset, type, sym->c);
744 static inline int isid(int c)
746 return (c >= 'a' && c <= 'z') ||
747 (c >= 'A' && c <= 'Z') ||
748 c == '_';
751 static inline int isnum(int c)
753 return c >= '0' && c <= '9';
756 static inline int isoct(int c)
758 return c >= '0' && c <= '7';
761 static inline int toup(int c)
763 if (c >= 'a' && c <= 'z')
764 return c - 'a' + 'A';
765 else
766 return c;
769 static void strcat_vprintf(char *buf, int buf_size, const char *fmt, va_list ap)
771 int len;
772 len = strlen(buf);
773 vsnprintf(buf + len, buf_size - len, fmt, ap);
776 static void strcat_printf(char *buf, int buf_size, const char *fmt, ...)
778 va_list ap;
779 va_start(ap, fmt);
780 strcat_vprintf(buf, buf_size, fmt, ap);
781 va_end(ap);
784 void error1(TCCState *s1, int is_warning, const char *fmt, va_list ap)
786 char buf[2048];
787 BufferedFile **f;
789 buf[0] = '\0';
790 if (file) {
791 for(f = s1->include_stack; f < s1->include_stack_ptr; f++)
792 strcat_printf(buf, sizeof(buf), "In file included from %s:%d:\n",
793 (*f)->filename, (*f)->line_num);
794 if (file->line_num > 0) {
795 strcat_printf(buf, sizeof(buf),
796 "%s:%d: ", file->filename, file->line_num);
797 } else {
798 strcat_printf(buf, sizeof(buf),
799 "%s: ", file->filename);
801 } else {
802 strcat_printf(buf, sizeof(buf),
803 "tcc: ");
805 if (is_warning)
806 strcat_printf(buf, sizeof(buf), "warning: ");
807 else
808 strcat_printf(buf, sizeof(buf), "error: ");
809 strcat_vprintf(buf, sizeof(buf), fmt, ap);
811 if (!s1->error_func) {
812 /* default case: stderr */
813 fprintf(stderr, "%s\n", buf);
814 } else {
815 s1->error_func(s1->error_opaque, buf);
817 if (!is_warning || s1->warn_error)
818 s1->nb_errors++;
821 void tcc_set_error_func(TCCState *s, void *error_opaque,
822 void (*error_func)(void *opaque, const char *msg))
824 s->error_opaque = error_opaque;
825 s->error_func = error_func;
828 /* error without aborting current compilation */
829 void error_noabort(const char *fmt, ...)
831 TCCState *s1 = tcc_state;
832 va_list ap;
834 va_start(ap, fmt);
835 error1(s1, 0, fmt, ap);
836 va_end(ap);
839 void error(const char *fmt, ...)
841 TCCState *s1 = tcc_state;
842 va_list ap;
844 va_start(ap, fmt);
845 error1(s1, 0, fmt, ap);
846 va_end(ap);
847 /* better than nothing: in some cases, we accept to handle errors */
848 if (s1->error_set_jmp_enabled) {
849 longjmp(s1->error_jmp_buf, 1);
850 } else {
851 /* XXX: eliminate this someday */
852 exit(1);
856 void expect(const char *msg)
858 error("%s expected", msg);
861 void warning(const char *fmt, ...)
863 TCCState *s1 = tcc_state;
864 va_list ap;
866 if (s1->warn_none)
867 return;
869 va_start(ap, fmt);
870 error1(s1, 1, fmt, ap);
871 va_end(ap);
874 void skip(int c)
876 if (tok != c)
877 error("'%c' expected", c);
878 next();
881 static void test_lvalue(void)
883 if (!(vtop->r & VT_LVAL))
884 expect("lvalue");
887 /* CString handling */
889 static void cstr_realloc(CString *cstr, int new_size)
891 int size;
892 void *data;
894 size = cstr->size_allocated;
895 if (size == 0)
896 size = 8; /* no need to allocate a too small first string */
897 while (size < new_size)
898 size = size * 2;
899 data = tcc_realloc(cstr->data_allocated, size);
900 if (!data)
901 error("memory full");
902 cstr->data_allocated = data;
903 cstr->size_allocated = size;
904 cstr->data = data;
907 /* add a byte */
908 static inline void cstr_ccat(CString *cstr, int ch)
910 int size;
911 size = cstr->size + 1;
912 if (size > cstr->size_allocated)
913 cstr_realloc(cstr, size);
914 ((unsigned char *)cstr->data)[size - 1] = ch;
915 cstr->size = size;
918 static void cstr_cat(CString *cstr, const char *str)
920 int c;
921 for(;;) {
922 c = *str;
923 if (c == '\0')
924 break;
925 cstr_ccat(cstr, c);
926 str++;
930 /* add a wide char */
931 static void cstr_wccat(CString *cstr, int ch)
933 int size;
934 size = cstr->size + sizeof(nwchar_t);
935 if (size > cstr->size_allocated)
936 cstr_realloc(cstr, size);
937 *(nwchar_t *)(((unsigned char *)cstr->data) + size - sizeof(nwchar_t)) = ch;
938 cstr->size = size;
941 static void cstr_new(CString *cstr)
943 memset(cstr, 0, sizeof(CString));
946 /* free string and reset it to NULL */
947 static void cstr_free(CString *cstr)
949 tcc_free(cstr->data_allocated);
950 cstr_new(cstr);
953 #define cstr_reset(cstr) cstr_free(cstr)
955 /* XXX: unicode ? */
956 static void add_char(CString *cstr, int c)
958 if (c == '\'' || c == '\"' || c == '\\') {
959 /* XXX: could be more precise if char or string */
960 cstr_ccat(cstr, '\\');
962 if (c >= 32 && c <= 126) {
963 cstr_ccat(cstr, c);
964 } else {
965 cstr_ccat(cstr, '\\');
966 if (c == '\n') {
967 cstr_ccat(cstr, 'n');
968 } else {
969 cstr_ccat(cstr, '0' + ((c >> 6) & 7));
970 cstr_ccat(cstr, '0' + ((c >> 3) & 7));
971 cstr_ccat(cstr, '0' + (c & 7));
976 /* push, without hashing */
977 static Sym *sym_push2(Sym **ps, int v, int t, long c)
979 Sym *s;
980 s = sym_malloc();
981 s->v = v;
982 s->type.t = t;
983 s->c = c;
984 s->next = NULL;
985 /* add in stack */
986 s->prev = *ps;
987 *ps = s;
988 return s;
991 /* find a symbol and return its associated structure. 's' is the top
992 of the symbol stack */
993 static Sym *sym_find2(Sym *s, int v)
995 while (s) {
996 if (s->v == v)
997 return s;
998 s = s->prev;
1000 return NULL;
1003 /* structure lookup */
1004 static inline Sym *struct_find(int v)
1006 v -= TOK_IDENT;
1007 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1008 return NULL;
1009 return table_ident[v]->sym_struct;
1012 /* find an identifier */
1013 static inline Sym *sym_find(int v)
1015 v -= TOK_IDENT;
1016 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1017 return NULL;
1018 return table_ident[v]->sym_identifier;
1021 /* push a given symbol on the symbol stack */
1022 static Sym *sym_push(int v, CType *type, int r, int c)
1024 Sym *s, **ps;
1025 TokenSym *ts;
1027 if (local_stack)
1028 ps = &local_stack;
1029 else
1030 ps = &global_stack;
1031 s = sym_push2(ps, v, type->t, c);
1032 s->type.ref = type->ref;
1033 s->r = r;
1034 /* don't record fields or anonymous symbols */
1035 /* XXX: simplify */
1036 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
1037 /* record symbol in token array */
1038 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
1039 if (v & SYM_STRUCT)
1040 ps = &ts->sym_struct;
1041 else
1042 ps = &ts->sym_identifier;
1043 s->prev_tok = *ps;
1044 *ps = s;
1046 return s;
1049 /* push a global identifier */
1050 static Sym *global_identifier_push(int v, int t, int c)
1052 Sym *s, **ps;
1053 s = sym_push2(&global_stack, v, t, c);
1054 /* don't record anonymous symbol */
1055 if (v < SYM_FIRST_ANOM) {
1056 ps = &table_ident[v - TOK_IDENT]->sym_identifier;
1057 /* modify the top most local identifier, so that
1058 sym_identifier will point to 's' when popped */
1059 while (*ps != NULL)
1060 ps = &(*ps)->prev_tok;
1061 s->prev_tok = NULL;
1062 *ps = s;
1064 return s;
1067 /* pop symbols until top reaches 'b' */
1068 static void sym_pop(Sym **ptop, Sym *b)
1070 Sym *s, *ss, **ps;
1071 TokenSym *ts;
1072 int v;
1074 s = *ptop;
1075 while(s != b) {
1076 ss = s->prev;
1077 v = s->v;
1078 /* remove symbol in token array */
1079 /* XXX: simplify */
1080 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
1081 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
1082 if (v & SYM_STRUCT)
1083 ps = &ts->sym_struct;
1084 else
1085 ps = &ts->sym_identifier;
1086 *ps = s->prev_tok;
1088 sym_free(s);
1089 s = ss;
1091 *ptop = b;
1094 /* I/O layer */
1096 BufferedFile *tcc_open(TCCState *s1, const char *filename)
1098 int fd;
1099 BufferedFile *bf;
1101 if (strcmp(filename, "-") == 0)
1102 fd = 0, filename = "stdin";
1103 else
1104 fd = open(filename, O_RDONLY | O_BINARY);
1105 if ((s1->verbose == 2 && fd >= 0) || s1->verbose == 3)
1106 printf("%s %*s%s\n", fd < 0 ? "nf":"->",
1107 (s1->include_stack_ptr - s1->include_stack), "", filename);
1108 if (fd < 0)
1109 return NULL;
1110 bf = tcc_malloc(sizeof(BufferedFile));
1111 bf->fd = fd;
1112 bf->buf_ptr = bf->buffer;
1113 bf->buf_end = bf->buffer;
1114 bf->buffer[0] = CH_EOB; /* put eob symbol */
1115 pstrcpy(bf->filename, sizeof(bf->filename), filename);
1116 #ifdef _WIN32
1117 normalize_slashes(bf->filename);
1118 #endif
1119 bf->line_num = 1;
1120 bf->ifndef_macro = 0;
1121 bf->ifdef_stack_ptr = s1->ifdef_stack_ptr;
1122 // printf("opening '%s'\n", filename);
1123 return bf;
1126 void tcc_close(BufferedFile *bf)
1128 total_lines += bf->line_num;
1129 close(bf->fd);
1130 tcc_free(bf);
1133 #include "tccpp.c"
1134 #include "tccgen.c"
1137 /* compile the C file opened in 'file'. Return non zero if errors. */
1138 static int tcc_compile(TCCState *s1)
1140 Sym *define_start;
1141 char buf[512];
1142 volatile int section_sym;
1144 #ifdef INC_DEBUG
1145 printf("%s: **** new file\n", file->filename);
1146 #endif
1147 preprocess_init(s1);
1149 cur_text_section = NULL;
1150 funcname = "";
1151 anon_sym = SYM_FIRST_ANOM;
1153 /* file info: full path + filename */
1154 section_sym = 0; /* avoid warning */
1155 if (s1->do_debug) {
1156 section_sym = put_elf_sym(symtab_section, 0, 0,
1157 ELFW(ST_INFO)(STB_LOCAL, STT_SECTION), 0,
1158 text_section->sh_num, NULL);
1159 getcwd(buf, sizeof(buf));
1160 #ifdef _WIN32
1161 normalize_slashes(buf);
1162 #endif
1163 pstrcat(buf, sizeof(buf), "/");
1164 put_stabs_r(buf, N_SO, 0, 0,
1165 text_section->data_offset, text_section, section_sym);
1166 put_stabs_r(file->filename, N_SO, 0, 0,
1167 text_section->data_offset, text_section, section_sym);
1169 /* an elf symbol of type STT_FILE must be put so that STB_LOCAL
1170 symbols can be safely used */
1171 put_elf_sym(symtab_section, 0, 0,
1172 ELFW(ST_INFO)(STB_LOCAL, STT_FILE), 0,
1173 SHN_ABS, file->filename);
1175 /* define some often used types */
1176 int_type.t = VT_INT;
1178 char_pointer_type.t = VT_BYTE;
1179 mk_pointer(&char_pointer_type);
1181 func_old_type.t = VT_FUNC;
1182 func_old_type.ref = sym_push(SYM_FIELD, &int_type, FUNC_CDECL, FUNC_OLD);
1184 #if defined(TCC_ARM_EABI) && defined(TCC_ARM_VFP)
1185 float_type.t = VT_FLOAT;
1186 double_type.t = VT_DOUBLE;
1188 func_float_type.t = VT_FUNC;
1189 func_float_type.ref = sym_push(SYM_FIELD, &float_type, FUNC_CDECL, FUNC_OLD);
1190 func_double_type.t = VT_FUNC;
1191 func_double_type.ref = sym_push(SYM_FIELD, &double_type, FUNC_CDECL, FUNC_OLD);
1192 #endif
1194 #if 0
1195 /* define 'void *alloca(unsigned int)' builtin function */
1197 Sym *s1;
1199 p = anon_sym++;
1200 sym = sym_push(p, mk_pointer(VT_VOID), FUNC_CDECL, FUNC_NEW);
1201 s1 = sym_push(SYM_FIELD, VT_UNSIGNED | VT_INT, 0, 0);
1202 s1->next = NULL;
1203 sym->next = s1;
1204 sym_push(TOK_alloca, VT_FUNC | (p << VT_STRUCT_SHIFT), VT_CONST, 0);
1206 #endif
1208 define_start = define_stack;
1209 nocode_wanted = 1;
1211 if (setjmp(s1->error_jmp_buf) == 0) {
1212 s1->nb_errors = 0;
1213 s1->error_set_jmp_enabled = 1;
1215 ch = file->buf_ptr[0];
1216 tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
1217 parse_flags = PARSE_FLAG_PREPROCESS | PARSE_FLAG_TOK_NUM;
1218 next();
1219 decl(VT_CONST);
1220 if (tok != TOK_EOF)
1221 expect("declaration");
1223 /* end of translation unit info */
1224 if (s1->do_debug) {
1225 put_stabs_r(NULL, N_SO, 0, 0,
1226 text_section->data_offset, text_section, section_sym);
1229 s1->error_set_jmp_enabled = 0;
1231 /* reset define stack, but leave -Dsymbols (may be incorrect if
1232 they are undefined) */
1233 free_defines(define_start);
1235 gen_inline_functions();
1237 sym_pop(&global_stack, NULL);
1238 sym_pop(&local_stack, NULL);
1240 return s1->nb_errors != 0 ? -1 : 0;
1243 int tcc_compile_string(TCCState *s, const char *str)
1245 BufferedFile bf1, *bf = &bf1;
1246 int ret, len;
1247 char *buf;
1249 /* init file structure */
1250 bf->fd = -1;
1251 /* XXX: avoid copying */
1252 len = strlen(str);
1253 buf = tcc_malloc(len + 1);
1254 if (!buf)
1255 return -1;
1256 memcpy(buf, str, len);
1257 buf[len] = CH_EOB;
1258 bf->buf_ptr = buf;
1259 bf->buf_end = buf + len;
1260 pstrcpy(bf->filename, sizeof(bf->filename), "<string>");
1261 bf->line_num = 1;
1262 file = bf;
1263 ret = tcc_compile(s);
1264 file = NULL;
1265 tcc_free(buf);
1267 /* currently, no need to close */
1268 return ret;
1271 /* define a preprocessor symbol. A value can also be provided with the '=' operator */
1272 void tcc_define_symbol(TCCState *s1, const char *sym, const char *value)
1274 BufferedFile bf1, *bf = &bf1;
1276 pstrcpy(bf->buffer, IO_BUF_SIZE, sym);
1277 pstrcat(bf->buffer, IO_BUF_SIZE, " ");
1278 /* default value */
1279 if (!value)
1280 value = "1";
1281 pstrcat(bf->buffer, IO_BUF_SIZE, value);
1283 /* init file structure */
1284 bf->fd = -1;
1285 bf->buf_ptr = bf->buffer;
1286 bf->buf_end = bf->buffer + strlen(bf->buffer);
1287 *bf->buf_end = CH_EOB;
1288 bf->filename[0] = '\0';
1289 bf->line_num = 1;
1290 file = bf;
1292 s1->include_stack_ptr = s1->include_stack;
1294 /* parse with define parser */
1295 ch = file->buf_ptr[0];
1296 next_nomacro();
1297 parse_define();
1298 file = NULL;
1301 /* undefine a preprocessor symbol */
1302 void tcc_undefine_symbol(TCCState *s1, const char *sym)
1304 TokenSym *ts;
1305 Sym *s;
1306 ts = tok_alloc(sym, strlen(sym));
1307 s = define_find(ts->tok);
1308 /* undefine symbol by putting an invalid name */
1309 if (s)
1310 define_undef(s);
1313 #ifdef CONFIG_TCC_ASM
1315 #ifdef TCC_TARGET_I386
1316 #include "i386-asm.c"
1317 #endif
1318 #include "tccasm.c"
1320 #else
1321 static void asm_instr(void)
1323 error("inline asm() not supported");
1325 static void asm_global_instr(void)
1327 error("inline asm() not supported");
1329 #endif
1331 #include "tccelf.c"
1333 #ifdef TCC_TARGET_COFF
1334 #include "tcccoff.c"
1335 #endif
1337 #ifdef TCC_TARGET_PE
1338 #include "tccpe.c"
1339 #endif
1341 #ifdef CONFIG_TCC_BACKTRACE
1342 /* print the position in the source file of PC value 'pc' by reading
1343 the stabs debug information */
1344 static unsigned long rt_printline(unsigned long wanted_pc)
1346 Stab_Sym *sym, *sym_end;
1347 char func_name[128], last_func_name[128];
1348 unsigned long func_addr, last_pc, pc;
1349 const char *incl_files[INCLUDE_STACK_SIZE];
1350 int incl_index, len, last_line_num, i;
1351 const char *str, *p;
1353 fprintf(stderr, "0x%08lx:", wanted_pc);
1355 func_name[0] = '\0';
1356 func_addr = 0;
1357 incl_index = 0;
1358 last_func_name[0] = '\0';
1359 last_pc = 0xffffffff;
1360 last_line_num = 1;
1361 sym = (Stab_Sym *)stab_section->data + 1;
1362 sym_end = (Stab_Sym *)(stab_section->data + stab_section->data_offset);
1363 while (sym < sym_end) {
1364 switch(sym->n_type) {
1365 /* function start or end */
1366 case N_FUN:
1367 if (sym->n_strx == 0) {
1368 /* we test if between last line and end of function */
1369 pc = sym->n_value + func_addr;
1370 if (wanted_pc >= last_pc && wanted_pc < pc)
1371 goto found;
1372 func_name[0] = '\0';
1373 func_addr = 0;
1374 } else {
1375 str = stabstr_section->data + sym->n_strx;
1376 p = strchr(str, ':');
1377 if (!p) {
1378 pstrcpy(func_name, sizeof(func_name), str);
1379 } else {
1380 len = p - str;
1381 if (len > sizeof(func_name) - 1)
1382 len = sizeof(func_name) - 1;
1383 memcpy(func_name, str, len);
1384 func_name[len] = '\0';
1386 func_addr = sym->n_value;
1388 break;
1389 /* line number info */
1390 case N_SLINE:
1391 pc = sym->n_value + func_addr;
1392 if (wanted_pc >= last_pc && wanted_pc < pc)
1393 goto found;
1394 last_pc = pc;
1395 last_line_num = sym->n_desc;
1396 /* XXX: slow! */
1397 strcpy(last_func_name, func_name);
1398 break;
1399 /* include files */
1400 case N_BINCL:
1401 str = stabstr_section->data + sym->n_strx;
1402 add_incl:
1403 if (incl_index < INCLUDE_STACK_SIZE) {
1404 incl_files[incl_index++] = str;
1406 break;
1407 case N_EINCL:
1408 if (incl_index > 1)
1409 incl_index--;
1410 break;
1411 case N_SO:
1412 if (sym->n_strx == 0) {
1413 incl_index = 0; /* end of translation unit */
1414 } else {
1415 str = stabstr_section->data + sym->n_strx;
1416 /* do not add path */
1417 len = strlen(str);
1418 if (len > 0 && str[len - 1] != '/')
1419 goto add_incl;
1421 break;
1423 sym++;
1426 /* second pass: we try symtab symbols (no line number info) */
1427 incl_index = 0;
1429 ElfW(Sym) *sym, *sym_end;
1430 int type;
1432 sym_end = (ElfW(Sym) *)(symtab_section->data + symtab_section->data_offset);
1433 for(sym = (ElfW(Sym) *)symtab_section->data + 1;
1434 sym < sym_end;
1435 sym++) {
1436 type = ELFW(ST_TYPE)(sym->st_info);
1437 if (type == STT_FUNC) {
1438 if (wanted_pc >= sym->st_value &&
1439 wanted_pc < sym->st_value + sym->st_size) {
1440 pstrcpy(last_func_name, sizeof(last_func_name),
1441 strtab_section->data + sym->st_name);
1442 func_addr = sym->st_value;
1443 goto found;
1448 /* did not find any info: */
1449 fprintf(stderr, " ???\n");
1450 return 0;
1451 found:
1452 if (last_func_name[0] != '\0') {
1453 fprintf(stderr, " %s()", last_func_name);
1455 if (incl_index > 0) {
1456 fprintf(stderr, " (%s:%d",
1457 incl_files[incl_index - 1], last_line_num);
1458 for(i = incl_index - 2; i >= 0; i--)
1459 fprintf(stderr, ", included from %s", incl_files[i]);
1460 fprintf(stderr, ")");
1462 fprintf(stderr, "\n");
1463 return func_addr;
1466 #ifdef __i386__
1467 /* fix for glibc 2.1 */
1468 #ifndef REG_EIP
1469 #define REG_EIP EIP
1470 #define REG_EBP EBP
1471 #endif
1473 /* return the PC at frame level 'level'. Return non zero if not found */
1474 static int rt_get_caller_pc(unsigned long *paddr,
1475 ucontext_t *uc, int level)
1477 unsigned long fp;
1478 int i;
1480 if (level == 0) {
1481 #if defined(__FreeBSD__)
1482 *paddr = uc->uc_mcontext.mc_eip;
1483 #elif defined(__dietlibc__)
1484 *paddr = uc->uc_mcontext.eip;
1485 #else
1486 *paddr = uc->uc_mcontext.gregs[REG_EIP];
1487 #endif
1488 return 0;
1489 } else {
1490 #if defined(__FreeBSD__)
1491 fp = uc->uc_mcontext.mc_ebp;
1492 #elif defined(__dietlibc__)
1493 fp = uc->uc_mcontext.ebp;
1494 #else
1495 fp = uc->uc_mcontext.gregs[REG_EBP];
1496 #endif
1497 for(i=1;i<level;i++) {
1498 /* XXX: check address validity with program info */
1499 if (fp <= 0x1000 || fp >= 0xc0000000)
1500 return -1;
1501 fp = ((unsigned long *)fp)[0];
1503 *paddr = ((unsigned long *)fp)[1];
1504 return 0;
1507 #elif defined(__x86_64__)
1508 /* return the PC at frame level 'level'. Return non zero if not found */
1509 static int rt_get_caller_pc(unsigned long *paddr,
1510 ucontext_t *uc, int level)
1512 unsigned long fp;
1513 int i;
1515 if (level == 0) {
1516 /* XXX: only support linux */
1517 *paddr = uc->uc_mcontext.gregs[REG_RIP];
1518 return 0;
1519 } else {
1520 fp = uc->uc_mcontext.gregs[REG_RBP];
1521 for(i=1;i<level;i++) {
1522 /* XXX: check address validity with program info */
1523 if (fp <= 0x1000)
1524 return -1;
1525 fp = ((unsigned long *)fp)[0];
1527 *paddr = ((unsigned long *)fp)[1];
1528 return 0;
1531 #else
1532 #warning add arch specific rt_get_caller_pc()
1533 static int rt_get_caller_pc(unsigned long *paddr,
1534 ucontext_t *uc, int level)
1536 return -1;
1538 #endif
1540 /* emit a run time error at position 'pc' */
1541 void rt_error(ucontext_t *uc, const char *fmt, ...)
1543 va_list ap;
1544 unsigned long pc;
1545 int i;
1547 va_start(ap, fmt);
1548 fprintf(stderr, "Runtime error: ");
1549 vfprintf(stderr, fmt, ap);
1550 fprintf(stderr, "\n");
1551 for(i=0;i<num_callers;i++) {
1552 if (rt_get_caller_pc(&pc, uc, i) < 0)
1553 break;
1554 if (i == 0)
1555 fprintf(stderr, "at ");
1556 else
1557 fprintf(stderr, "by ");
1558 pc = rt_printline(pc);
1559 if (pc == rt_prog_main && pc)
1560 break;
1562 exit(255);
1563 va_end(ap);
1566 /* signal handler for fatal errors */
1567 static void sig_error(int signum, siginfo_t *siginf, void *puc)
1569 ucontext_t *uc = puc;
1571 switch(signum) {
1572 case SIGFPE:
1573 switch(siginf->si_code) {
1574 case FPE_INTDIV:
1575 case FPE_FLTDIV:
1576 rt_error(uc, "division by zero");
1577 break;
1578 default:
1579 rt_error(uc, "floating point exception");
1580 break;
1582 break;
1583 case SIGBUS:
1584 case SIGSEGV:
1585 if (rt_bound_error_msg && *rt_bound_error_msg)
1586 rt_error(uc, *rt_bound_error_msg);
1587 else
1588 rt_error(uc, "dereferencing invalid pointer");
1589 break;
1590 case SIGILL:
1591 rt_error(uc, "illegal instruction");
1592 break;
1593 case SIGABRT:
1594 rt_error(uc, "abort() called");
1595 break;
1596 default:
1597 rt_error(uc, "caught signal %d", signum);
1598 break;
1600 exit(255);
1603 #endif
1605 /* copy code into memory passed in by the caller and do all relocations
1606 (needed before using tcc_get_symbol()).
1607 returns -1 on error and required size if ptr is NULL */
1608 int tcc_relocate(TCCState *s1, void *ptr)
1610 Section *s;
1611 unsigned long offset, length, mem;
1612 int i;
1614 if (0 == s1->runtime_added) {
1615 s1->runtime_added = 1;
1616 s1->nb_errors = 0;
1617 #ifdef TCC_TARGET_PE
1618 pe_add_runtime(s1);
1619 relocate_common_syms();
1620 tcc_add_linker_symbols(s1);
1621 #else
1622 tcc_add_runtime(s1);
1623 relocate_common_syms();
1624 tcc_add_linker_symbols(s1);
1625 build_got_entries(s1);
1626 #endif
1629 offset = 0, mem = (unsigned long)ptr;
1630 for(i = 1; i < s1->nb_sections; i++) {
1631 s = s1->sections[i];
1632 if (0 == (s->sh_flags & SHF_ALLOC))
1633 continue;
1634 length = s->data_offset;
1635 s->sh_addr = mem ? (mem + offset + 15) & ~15 : 0;
1636 offset = (offset + length + 15) & ~15;
1639 /* relocate symbols */
1640 relocate_syms(s1, 1);
1641 if (s1->nb_errors)
1642 return -1;
1644 #ifdef TCC_TARGET_X86_64
1645 s1->runtime_plt_and_got_offset = 0;
1646 s1->runtime_plt_and_got = (char *)(mem + offset);
1647 /* double the size of the buffer for got and plt entries
1648 XXX: calculate exact size for them? */
1649 offset *= 2;
1650 #endif
1652 if (0 == mem)
1653 return offset + 15;
1655 /* relocate each section */
1656 for(i = 1; i < s1->nb_sections; i++) {
1657 s = s1->sections[i];
1658 if (s->reloc)
1659 relocate_section(s1, s);
1662 for(i = 1; i < s1->nb_sections; i++) {
1663 s = s1->sections[i];
1664 if (0 == (s->sh_flags & SHF_ALLOC))
1665 continue;
1666 length = s->data_offset;
1667 // printf("%-12s %08x %04x\n", s->name, s->sh_addr, length);
1668 ptr = (void*)s->sh_addr;
1669 if (NULL == s->data || s->sh_type == SHT_NOBITS)
1670 memset(ptr, 0, length);
1671 else
1672 memcpy(ptr, s->data, length);
1673 /* mark executable sections as executable in memory */
1674 if (s->sh_flags & SHF_EXECINSTR)
1675 set_pages_executable(ptr, length);
1677 #ifdef TCC_TARGET_X86_64
1678 set_pages_executable(s1->runtime_plt_and_got,
1679 s1->runtime_plt_and_got_offset);
1680 #endif
1681 return 0;
1684 /* launch the compiled program with the given arguments */
1685 int tcc_run(TCCState *s1, int argc, char **argv)
1687 int (*prog_main)(int, char **);
1688 void *ptr;
1689 int ret;
1691 ret = tcc_relocate(s1, NULL);
1692 if (ret < 0)
1693 return -1;
1694 ptr = tcc_malloc(ret);
1695 tcc_relocate(s1, ptr);
1697 prog_main = tcc_get_symbol_err(s1, "main");
1699 if (s1->do_debug) {
1700 #ifdef CONFIG_TCC_BACKTRACE
1701 struct sigaction sigact;
1702 /* install TCC signal handlers to print debug info on fatal
1703 runtime errors */
1704 sigact.sa_flags = SA_SIGINFO | SA_RESETHAND;
1705 sigact.sa_sigaction = sig_error;
1706 sigemptyset(&sigact.sa_mask);
1707 sigaction(SIGFPE, &sigact, NULL);
1708 sigaction(SIGILL, &sigact, NULL);
1709 sigaction(SIGSEGV, &sigact, NULL);
1710 sigaction(SIGBUS, &sigact, NULL);
1711 sigaction(SIGABRT, &sigact, NULL);
1712 #else
1713 error("debug mode not available");
1714 #endif
1717 #ifdef CONFIG_TCC_BCHECK
1718 if (s1->do_bounds_check) {
1719 void (*bound_init)(void);
1720 void (*bound_exit)(void);
1721 /* set error function */
1722 rt_bound_error_msg = tcc_get_symbol_err(s1, "__bound_error_msg");
1723 rt_prog_main = (unsigned long)prog_main;
1724 /* XXX: use .init section so that it also work in binary ? */
1725 bound_init = tcc_get_symbol_err(s1, "__bound_init");
1726 bound_exit = tcc_get_symbol_err(s1, "__bound_exit");
1727 bound_init();
1728 ret = (*prog_main)(argc, argv);
1729 bound_exit();
1730 } else
1731 #endif
1732 ret = (*prog_main)(argc, argv);
1733 tcc_free(ptr);
1734 return ret;
1737 void tcc_memstats(void)
1739 #ifdef MEM_DEBUG
1740 printf("memory in use: %d\n", mem_cur_size);
1741 #endif
1744 static void tcc_cleanup(void)
1746 int i, n;
1748 if (NULL == tcc_state)
1749 return;
1750 tcc_state = NULL;
1752 /* free -D defines */
1753 free_defines(NULL);
1755 /* free tokens */
1756 n = tok_ident - TOK_IDENT;
1757 for(i = 0; i < n; i++)
1758 tcc_free(table_ident[i]);
1759 tcc_free(table_ident);
1761 /* free sym_pools */
1762 dynarray_reset(&sym_pools, &nb_sym_pools);
1763 /* string buffer */
1764 cstr_free(&tokcstr);
1765 /* reset symbol stack */
1766 sym_free_first = NULL;
1767 /* cleanup from error/setjmp */
1768 macro_ptr = NULL;
1771 TCCState *tcc_new(void)
1773 TCCState *s;
1775 tcc_cleanup();
1777 s = tcc_mallocz(sizeof(TCCState));
1778 if (!s)
1779 return NULL;
1780 tcc_state = s;
1781 s->output_type = TCC_OUTPUT_MEMORY;
1782 s->tcc_lib_path = CONFIG_TCCDIR;
1784 preprocess_new();
1786 /* we add dummy defines for some special macros to speed up tests
1787 and to have working defined() */
1788 define_push(TOK___LINE__, MACRO_OBJ, NULL, NULL);
1789 define_push(TOK___FILE__, MACRO_OBJ, NULL, NULL);
1790 define_push(TOK___DATE__, MACRO_OBJ, NULL, NULL);
1791 define_push(TOK___TIME__, MACRO_OBJ, NULL, NULL);
1793 /* standard defines */
1794 tcc_define_symbol(s, "__STDC__", NULL);
1795 tcc_define_symbol(s, "__STDC_VERSION__", "199901L");
1796 #if defined(TCC_TARGET_I386)
1797 tcc_define_symbol(s, "__i386__", NULL);
1798 #endif
1799 #if defined(TCC_TARGET_X86_64)
1800 tcc_define_symbol(s, "__x86_64__", NULL);
1801 #endif
1802 #if defined(TCC_TARGET_ARM)
1803 tcc_define_symbol(s, "__ARM_ARCH_4__", NULL);
1804 tcc_define_symbol(s, "__arm_elf__", NULL);
1805 tcc_define_symbol(s, "__arm_elf", NULL);
1806 tcc_define_symbol(s, "arm_elf", NULL);
1807 tcc_define_symbol(s, "__arm__", NULL);
1808 tcc_define_symbol(s, "__arm", NULL);
1809 tcc_define_symbol(s, "arm", NULL);
1810 tcc_define_symbol(s, "__APCS_32__", NULL);
1811 #endif
1812 #ifdef TCC_TARGET_PE
1813 tcc_define_symbol(s, "_WIN32", NULL);
1814 #else
1815 tcc_define_symbol(s, "__unix__", NULL);
1816 tcc_define_symbol(s, "__unix", NULL);
1817 #if defined(__linux)
1818 tcc_define_symbol(s, "__linux__", NULL);
1819 tcc_define_symbol(s, "__linux", NULL);
1820 #endif
1821 #endif
1822 /* tiny C specific defines */
1823 tcc_define_symbol(s, "__TINYC__", NULL);
1825 /* tiny C & gcc defines */
1826 tcc_define_symbol(s, "__SIZE_TYPE__", "unsigned int");
1827 tcc_define_symbol(s, "__PTRDIFF_TYPE__", "int");
1828 #ifdef TCC_TARGET_PE
1829 tcc_define_symbol(s, "__WCHAR_TYPE__", "unsigned short");
1830 #else
1831 tcc_define_symbol(s, "__WCHAR_TYPE__", "int");
1832 #endif
1834 #ifndef TCC_TARGET_PE
1835 /* default library paths */
1836 tcc_add_library_path(s, CONFIG_SYSROOT "/usr/local/lib");
1837 tcc_add_library_path(s, CONFIG_SYSROOT "/usr/lib");
1838 tcc_add_library_path(s, CONFIG_SYSROOT "/lib");
1839 #endif
1841 /* no section zero */
1842 dynarray_add((void ***)&s->sections, &s->nb_sections, NULL);
1844 /* create standard sections */
1845 text_section = new_section(s, ".text", SHT_PROGBITS, SHF_ALLOC | SHF_EXECINSTR);
1846 data_section = new_section(s, ".data", SHT_PROGBITS, SHF_ALLOC | SHF_WRITE);
1847 bss_section = new_section(s, ".bss", SHT_NOBITS, SHF_ALLOC | SHF_WRITE);
1849 /* symbols are always generated for linking stage */
1850 symtab_section = new_symtab(s, ".symtab", SHT_SYMTAB, 0,
1851 ".strtab",
1852 ".hashtab", SHF_PRIVATE);
1853 strtab_section = symtab_section->link;
1855 /* private symbol table for dynamic symbols */
1856 s->dynsymtab_section = new_symtab(s, ".dynsymtab", SHT_SYMTAB, SHF_PRIVATE,
1857 ".dynstrtab",
1858 ".dynhashtab", SHF_PRIVATE);
1859 s->alacarte_link = 1;
1861 #ifdef CHAR_IS_UNSIGNED
1862 s->char_is_unsigned = 1;
1863 #endif
1864 #if defined(TCC_TARGET_PE) && 0
1865 /* XXX: currently the PE linker is not ready to support that */
1866 s->leading_underscore = 1;
1867 #endif
1868 return s;
1871 void tcc_delete(TCCState *s1)
1873 int i;
1875 tcc_cleanup();
1877 /* free all sections */
1878 for(i = 1; i < s1->nb_sections; i++)
1879 free_section(s1->sections[i]);
1880 dynarray_reset(&s1->sections, &s1->nb_sections);
1882 for(i = 0; i < s1->nb_priv_sections; i++)
1883 free_section(s1->priv_sections[i]);
1884 dynarray_reset(&s1->priv_sections, &s1->nb_priv_sections);
1886 /* free any loaded DLLs */
1887 for ( i = 0; i < s1->nb_loaded_dlls; i++) {
1888 DLLReference *ref = s1->loaded_dlls[i];
1889 if ( ref->handle )
1890 dlclose(ref->handle);
1893 /* free loaded dlls array */
1894 dynarray_reset(&s1->loaded_dlls, &s1->nb_loaded_dlls);
1896 /* free library paths */
1897 dynarray_reset(&s1->library_paths, &s1->nb_library_paths);
1899 /* free include paths */
1900 dynarray_reset(&s1->cached_includes, &s1->nb_cached_includes);
1901 dynarray_reset(&s1->include_paths, &s1->nb_include_paths);
1902 dynarray_reset(&s1->sysinclude_paths, &s1->nb_sysinclude_paths);
1904 tcc_free(s1);
1907 int tcc_add_include_path(TCCState *s1, const char *pathname)
1909 char *pathname1;
1911 pathname1 = tcc_strdup(pathname);
1912 dynarray_add((void ***)&s1->include_paths, &s1->nb_include_paths, pathname1);
1913 return 0;
1916 int tcc_add_sysinclude_path(TCCState *s1, const char *pathname)
1918 char *pathname1;
1920 pathname1 = tcc_strdup(pathname);
1921 dynarray_add((void ***)&s1->sysinclude_paths, &s1->nb_sysinclude_paths, pathname1);
1922 return 0;
1925 static int tcc_add_file_internal(TCCState *s1, const char *filename, int flags)
1927 const char *ext;
1928 ElfW(Ehdr) ehdr;
1929 int fd, ret;
1930 BufferedFile *saved_file;
1932 /* find source file type with extension */
1933 ext = tcc_fileextension(filename);
1934 if (ext[0])
1935 ext++;
1937 /* open the file */
1938 saved_file = file;
1939 file = tcc_open(s1, filename);
1940 if (!file) {
1941 if (flags & AFF_PRINT_ERROR) {
1942 error_noabort("file '%s' not found", filename);
1944 ret = -1;
1945 goto fail1;
1948 if (flags & AFF_PREPROCESS) {
1949 ret = tcc_preprocess(s1);
1950 } else if (!ext[0] || !PATHCMP(ext, "c")) {
1951 /* C file assumed */
1952 ret = tcc_compile(s1);
1953 } else
1954 #ifdef CONFIG_TCC_ASM
1955 if (!strcmp(ext, "S")) {
1956 /* preprocessed assembler */
1957 ret = tcc_assemble(s1, 1);
1958 } else if (!strcmp(ext, "s")) {
1959 /* non preprocessed assembler */
1960 ret = tcc_assemble(s1, 0);
1961 } else
1962 #endif
1963 #ifdef TCC_TARGET_PE
1964 if (!PATHCMP(ext, "def")) {
1965 ret = pe_load_def_file(s1, file->fd);
1966 } else
1967 #endif
1969 fd = file->fd;
1970 /* assume executable format: auto guess file type */
1971 ret = read(fd, &ehdr, sizeof(ehdr));
1972 lseek(fd, 0, SEEK_SET);
1973 if (ret <= 0) {
1974 error_noabort("could not read header");
1975 goto fail;
1976 } else if (ret != sizeof(ehdr)) {
1977 goto try_load_script;
1980 if (ehdr.e_ident[0] == ELFMAG0 &&
1981 ehdr.e_ident[1] == ELFMAG1 &&
1982 ehdr.e_ident[2] == ELFMAG2 &&
1983 ehdr.e_ident[3] == ELFMAG3) {
1984 file->line_num = 0; /* do not display line number if error */
1985 if (ehdr.e_type == ET_REL) {
1986 ret = tcc_load_object_file(s1, fd, 0);
1987 } else if (ehdr.e_type == ET_DYN) {
1988 if (s1->output_type == TCC_OUTPUT_MEMORY) {
1989 #ifdef TCC_TARGET_PE
1990 ret = -1;
1991 #else
1992 void *h;
1993 h = dlopen(filename, RTLD_GLOBAL | RTLD_LAZY);
1994 if (h)
1995 ret = 0;
1996 else
1997 ret = -1;
1998 #endif
1999 } else {
2000 ret = tcc_load_dll(s1, fd, filename,
2001 (flags & AFF_REFERENCED_DLL) != 0);
2003 } else {
2004 error_noabort("unrecognized ELF file");
2005 goto fail;
2007 } else if (memcmp((char *)&ehdr, ARMAG, 8) == 0) {
2008 file->line_num = 0; /* do not display line number if error */
2009 ret = tcc_load_archive(s1, fd);
2010 } else
2011 #ifdef TCC_TARGET_COFF
2012 if (*(uint16_t *)(&ehdr) == COFF_C67_MAGIC) {
2013 ret = tcc_load_coff(s1, fd);
2014 } else
2015 #endif
2016 #ifdef TCC_TARGET_PE
2017 if (pe_test_res_file(&ehdr, ret)) {
2018 ret = pe_load_res_file(s1, fd);
2019 } else
2020 #endif
2022 /* as GNU ld, consider it is an ld script if not recognized */
2023 try_load_script:
2024 ret = tcc_load_ldscript(s1);
2025 if (ret < 0) {
2026 error_noabort("unrecognized file type");
2027 goto fail;
2031 the_end:
2032 tcc_close(file);
2033 fail1:
2034 file = saved_file;
2035 return ret;
2036 fail:
2037 ret = -1;
2038 goto the_end;
2041 int tcc_add_file(TCCState *s, const char *filename)
2043 if (s->output_type == TCC_OUTPUT_PREPROCESS)
2044 return tcc_add_file_internal(s, filename, AFF_PRINT_ERROR | AFF_PREPROCESS);
2045 else
2046 return tcc_add_file_internal(s, filename, AFF_PRINT_ERROR);
2049 int tcc_add_library_path(TCCState *s, const char *pathname)
2051 char *pathname1;
2053 pathname1 = tcc_strdup(pathname);
2054 dynarray_add((void ***)&s->library_paths, &s->nb_library_paths, pathname1);
2055 return 0;
2058 /* find and load a dll. Return non zero if not found */
2059 /* XXX: add '-rpath' option support ? */
2060 static int tcc_add_dll(TCCState *s, const char *filename, int flags)
2062 char buf[1024];
2063 int i;
2065 for(i = 0; i < s->nb_library_paths; i++) {
2066 snprintf(buf, sizeof(buf), "%s/%s",
2067 s->library_paths[i], filename);
2068 if (tcc_add_file_internal(s, buf, flags) == 0)
2069 return 0;
2071 return -1;
2074 /* the library name is the same as the argument of the '-l' option */
2075 int tcc_add_library(TCCState *s, const char *libraryname)
2077 char buf[1024];
2078 int i;
2080 /* first we look for the dynamic library if not static linking */
2081 if (!s->static_link) {
2082 #ifdef TCC_TARGET_PE
2083 snprintf(buf, sizeof(buf), "%s.def", libraryname);
2084 #else
2085 snprintf(buf, sizeof(buf), "lib%s.so", libraryname);
2086 #endif
2087 if (tcc_add_dll(s, buf, 0) == 0)
2088 return 0;
2091 /* then we look for the static library */
2092 for(i = 0; i < s->nb_library_paths; i++) {
2093 snprintf(buf, sizeof(buf), "%s/lib%s.a",
2094 s->library_paths[i], libraryname);
2095 if (tcc_add_file_internal(s, buf, 0) == 0)
2096 return 0;
2098 return -1;
2101 int tcc_add_symbol(TCCState *s, const char *name, void *val)
2103 add_elf_sym(symtab_section, (unsigned long)val, 0,
2104 ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE), 0,
2105 SHN_ABS, name);
2106 return 0;
2109 int tcc_set_output_type(TCCState *s, int output_type)
2111 char buf[1024];
2113 s->output_type = output_type;
2115 if (!s->nostdinc) {
2116 /* default include paths */
2117 /* XXX: reverse order needed if -isystem support */
2118 #ifndef TCC_TARGET_PE
2119 tcc_add_sysinclude_path(s, CONFIG_SYSROOT "/usr/local/include");
2120 tcc_add_sysinclude_path(s, CONFIG_SYSROOT "/usr/include");
2121 #endif
2122 snprintf(buf, sizeof(buf), "%s/include", s->tcc_lib_path);
2123 tcc_add_sysinclude_path(s, buf);
2124 #ifdef TCC_TARGET_PE
2125 snprintf(buf, sizeof(buf), "%s/include/winapi", s->tcc_lib_path);
2126 tcc_add_sysinclude_path(s, buf);
2127 #endif
2130 /* if bound checking, then add corresponding sections */
2131 #ifdef CONFIG_TCC_BCHECK
2132 if (s->do_bounds_check) {
2133 /* define symbol */
2134 tcc_define_symbol(s, "__BOUNDS_CHECKING_ON", NULL);
2135 /* create bounds sections */
2136 bounds_section = new_section(s, ".bounds",
2137 SHT_PROGBITS, SHF_ALLOC);
2138 lbounds_section = new_section(s, ".lbounds",
2139 SHT_PROGBITS, SHF_ALLOC);
2141 #endif
2143 if (s->char_is_unsigned) {
2144 tcc_define_symbol(s, "__CHAR_UNSIGNED__", NULL);
2147 /* add debug sections */
2148 if (s->do_debug) {
2149 /* stab symbols */
2150 stab_section = new_section(s, ".stab", SHT_PROGBITS, 0);
2151 stab_section->sh_entsize = sizeof(Stab_Sym);
2152 stabstr_section = new_section(s, ".stabstr", SHT_STRTAB, 0);
2153 put_elf_str(stabstr_section, "");
2154 stab_section->link = stabstr_section;
2155 /* put first entry */
2156 put_stabs("", 0, 0, 0, 0);
2159 /* add libc crt1/crti objects */
2160 #ifndef TCC_TARGET_PE
2161 if ((output_type == TCC_OUTPUT_EXE || output_type == TCC_OUTPUT_DLL) &&
2162 !s->nostdlib) {
2163 if (output_type != TCC_OUTPUT_DLL)
2164 tcc_add_file(s, CONFIG_TCC_CRT_PREFIX "/crt1.o");
2165 tcc_add_file(s, CONFIG_TCC_CRT_PREFIX "/crti.o");
2167 #endif
2169 #ifdef TCC_TARGET_PE
2170 snprintf(buf, sizeof(buf), "%s/lib", s->tcc_lib_path);
2171 tcc_add_library_path(s, buf);
2172 #endif
2174 return 0;
2177 #define WD_ALL 0x0001 /* warning is activated when using -Wall */
2178 #define FD_INVERT 0x0002 /* invert value before storing */
2180 typedef struct FlagDef {
2181 uint16_t offset;
2182 uint16_t flags;
2183 const char *name;
2184 } FlagDef;
2186 static const FlagDef warning_defs[] = {
2187 { offsetof(TCCState, warn_unsupported), 0, "unsupported" },
2188 { offsetof(TCCState, warn_write_strings), 0, "write-strings" },
2189 { offsetof(TCCState, warn_error), 0, "error" },
2190 { offsetof(TCCState, warn_implicit_function_declaration), WD_ALL,
2191 "implicit-function-declaration" },
2194 static int set_flag(TCCState *s, const FlagDef *flags, int nb_flags,
2195 const char *name, int value)
2197 int i;
2198 const FlagDef *p;
2199 const char *r;
2201 r = name;
2202 if (r[0] == 'n' && r[1] == 'o' && r[2] == '-') {
2203 r += 3;
2204 value = !value;
2206 for(i = 0, p = flags; i < nb_flags; i++, p++) {
2207 if (!strcmp(r, p->name))
2208 goto found;
2210 return -1;
2211 found:
2212 if (p->flags & FD_INVERT)
2213 value = !value;
2214 *(int *)((uint8_t *)s + p->offset) = value;
2215 return 0;
2219 /* set/reset a warning */
2220 int tcc_set_warning(TCCState *s, const char *warning_name, int value)
2222 int i;
2223 const FlagDef *p;
2225 if (!strcmp(warning_name, "all")) {
2226 for(i = 0, p = warning_defs; i < countof(warning_defs); i++, p++) {
2227 if (p->flags & WD_ALL)
2228 *(int *)((uint8_t *)s + p->offset) = 1;
2230 return 0;
2231 } else {
2232 return set_flag(s, warning_defs, countof(warning_defs),
2233 warning_name, value);
2237 static const FlagDef flag_defs[] = {
2238 { offsetof(TCCState, char_is_unsigned), 0, "unsigned-char" },
2239 { offsetof(TCCState, char_is_unsigned), FD_INVERT, "signed-char" },
2240 { offsetof(TCCState, nocommon), FD_INVERT, "common" },
2241 { offsetof(TCCState, leading_underscore), 0, "leading-underscore" },
2244 /* set/reset a flag */
2245 int tcc_set_flag(TCCState *s, const char *flag_name, int value)
2247 return set_flag(s, flag_defs, countof(flag_defs),
2248 flag_name, value);
2251 /* set CONFIG_TCCDIR at runtime */
2252 void tcc_set_lib_path(TCCState *s, const char *path)
2254 s->tcc_lib_path = tcc_strdup(path);
2257 void tcc_print_stats(TCCState *s, int64_t total_time)
2259 double tt;
2260 tt = (double)total_time / 1000000.0;
2261 if (tt < 0.001)
2262 tt = 0.001;
2263 if (total_bytes < 1)
2264 total_bytes = 1;
2265 printf("%d idents, %d lines, %d bytes, %0.3f s, %d lines/s, %0.1f MB/s\n",
2266 tok_ident - TOK_IDENT, total_lines, total_bytes,
2267 tt, (int)(total_lines / tt),
2268 total_bytes / tt / 1000000.0);