Define __ARM_PCS_VFP in hardfloat compilation mode
[tinycc.git] / libtcc.c
1 /*
2  *  TCC - Tiny C Compiler
3  * 
4  *  Copyright (c) 2001-2004 Fabrice Bellard
5  *
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.
10  *
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.
15  *
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
19  */
20
21 #include "tcc.h"
22
23 /********************************************************/
24 /* global variables */
25
26 /* use GNU C extensions */
27 ST_DATA int gnu_ext = 1;
28
29 /* use TinyCC extensions */
30 ST_DATA int tcc_ext = 1;
31
32 /* XXX: get rid of this ASAP */
33 ST_DATA struct TCCState *tcc_state;
34
35 /********************************************************/
36
37 #ifdef ONE_SOURCE
38 #include "tccpp.c"
39 #include "tccgen.c"
40 #include "tccelf.c"
41 #include "tccrun.c"
42 #ifdef TCC_TARGET_I386
43 #include "i386-gen.c"
44 #endif
45 #ifdef TCC_TARGET_ARM
46 #include "arm-gen.c"
47 #endif
48 #ifdef TCC_TARGET_C67
49 #include "c67-gen.c"
50 #endif
51 #ifdef TCC_TARGET_X86_64
52 #include "x86_64-gen.c"
53 #endif
54 #ifdef CONFIG_TCC_ASM
55 #include "tccasm.c"
56 #if defined TCC_TARGET_I386 || defined TCC_TARGET_X86_64
57 #include "i386-asm.c"
58 #endif
59 #endif
60 #ifdef TCC_TARGET_COFF
61 #include "tcccoff.c"
62 #endif
63 #ifdef TCC_TARGET_PE
64 #include "tccpe.c"
65 #endif
66 #endif /* ONE_SOURCE */
67
68 /********************************************************/
69 #ifndef CONFIG_TCC_ASM
70 ST_FUNC void asm_instr(void)
71 {
72     tcc_error("inline asm() not supported");
73 }
74 ST_FUNC void asm_global_instr(void)
75 {
76     tcc_error("inline asm() not supported");
77 }
78 #endif
79
80 /********************************************************/
81
82 #ifdef _WIN32
83 // GCC appears to use '/' for relative paths and '\\' for absolute paths on Windows
84 static char *normalize_slashes(char *path)
85 {
86     char *p;
87     if (path[1] == ':') {
88         for (p = path+2; *p; ++p)
89             if (*p == '/')
90                 *p = '\\';
91     } else {
92         for (p = path; *p; ++p)
93             if (*p == '\\')
94                 *p = '/';
95     }
96     return path;
97 }
98
99 static HMODULE tcc_module;
100
101 /* on win32, we suppose the lib and includes are at the location of 'tcc.exe' */
102 static void tcc_set_lib_path_w32(TCCState *s)
103 {
104     char path[1024], *p;
105     GetModuleFileNameA(tcc_module, path, sizeof path);
106     p = tcc_basename(normalize_slashes(strlwr(path)));
107     if (p - 5 > path && 0 == strncmp(p - 5, "/bin/", 5))
108         p -= 5;
109     else if (p > path)
110         p--;
111     *p = 0;
112     tcc_set_lib_path(s, path);
113 }
114
115 #ifdef TCC_TARGET_PE
116 static void tcc_add_systemdir(TCCState *s)
117 {
118     char buf[1000];
119     GetSystemDirectory(buf, sizeof buf);
120     tcc_add_library_path(s, normalize_slashes(buf));
121 }
122 #endif
123
124 #ifndef CONFIG_TCC_STATIC
125 void dlclose(void *p)
126 {
127     FreeLibrary((HMODULE)p);
128 }
129 #endif
130
131 #ifdef LIBTCC_AS_DLL
132 BOOL WINAPI DllMain (HANDLE hDll, DWORD dwReason, LPVOID lpReserved)
133 {
134     if (DLL_PROCESS_ATTACH == dwReason)
135         tcc_module = hDll;
136     return TRUE;
137 }
138 #endif
139 #endif
140
141 /********************************************************/
142 /* copy a string and truncate it. */
143 PUB_FUNC char *pstrcpy(char *buf, int buf_size, const char *s)
144 {
145     char *q, *q_end;
146     int c;
147
148     if (buf_size > 0) {
149         q = buf;
150         q_end = buf + buf_size - 1;
151         while (q < q_end) {
152             c = *s++;
153             if (c == '\0')
154                 break;
155             *q++ = c;
156         }
157         *q = '\0';
158     }
159     return buf;
160 }
161
162 /* strcat and truncate. */
163 PUB_FUNC char *pstrcat(char *buf, int buf_size, const char *s)
164 {
165     int len;
166     len = strlen(buf);
167     if (len < buf_size) 
168         pstrcpy(buf + len, buf_size - len, s);
169     return buf;
170 }
171
172 PUB_FUNC char *pstrncpy(char *out, const char *in, size_t num)
173 {
174     memcpy(out, in, num);
175     out[num] = '\0';
176     return out;
177 }
178
179 /* extract the basename of a file */
180 PUB_FUNC char *tcc_basename(const char *name)
181 {
182     char *p = strchr(name, 0);
183     while (p > name && !IS_DIRSEP(p[-1]))
184         --p;
185     return p;
186 }
187
188 /* extract extension part of a file
189  *
190  * (if no extension, return pointer to end-of-string)
191  */
192 PUB_FUNC char *tcc_fileextension (const char *name)
193 {
194     char *b = tcc_basename(name);
195     char *e = strrchr(b, '.');
196     return e ? e : strchr(b, 0);
197 }
198
199 /********************************************************/
200 /* memory management */
201
202 #undef free
203 #undef malloc
204 #undef realloc
205
206 #ifdef MEM_DEBUG
207 ST_DATA int mem_cur_size;
208 ST_DATA int mem_max_size;
209 unsigned malloc_usable_size(void*);
210 #endif
211
212 PUB_FUNC void tcc_free(void *ptr)
213 {
214 #ifdef MEM_DEBUG
215     mem_cur_size -= malloc_usable_size(ptr);
216 #endif
217     free(ptr);
218 }
219
220 PUB_FUNC void *tcc_malloc(unsigned long size)
221 {
222     void *ptr;
223     ptr = malloc(size);
224     if (!ptr && size)
225         tcc_error("memory full");
226 #ifdef MEM_DEBUG
227     mem_cur_size += malloc_usable_size(ptr);
228     if (mem_cur_size > mem_max_size)
229         mem_max_size = mem_cur_size;
230 #endif
231     return ptr;
232 }
233
234 PUB_FUNC void *tcc_mallocz(unsigned long size)
235 {
236     void *ptr;
237     ptr = tcc_malloc(size);
238     memset(ptr, 0, size);
239     return ptr;
240 }
241
242 PUB_FUNC void *tcc_realloc(void *ptr, unsigned long size)
243 {
244     void *ptr1;
245 #ifdef MEM_DEBUG
246     mem_cur_size -= malloc_usable_size(ptr);
247 #endif
248     ptr1 = realloc(ptr, size);
249     if (!ptr1 && size)
250         tcc_error("memory full");
251 #ifdef MEM_DEBUG
252     /* NOTE: count not correct if alloc error, but not critical */
253     mem_cur_size += malloc_usable_size(ptr1);
254     if (mem_cur_size > mem_max_size)
255         mem_max_size = mem_cur_size;
256 #endif
257     return ptr1;
258 }
259
260 PUB_FUNC char *tcc_strdup(const char *str)
261 {
262     char *ptr;
263     ptr = tcc_malloc(strlen(str) + 1);
264     strcpy(ptr, str);
265     return ptr;
266 }
267
268 PUB_FUNC void tcc_memstats(void)
269 {
270 #ifdef MEM_DEBUG
271     printf("memory: %d bytes, max = %d bytes\n", mem_cur_size, mem_max_size);
272 #endif
273 }
274
275 #define free(p) use_tcc_free(p)
276 #define malloc(s) use_tcc_malloc(s)
277 #define realloc(p, s) use_tcc_realloc(p, s)
278
279 /********************************************************/
280 /* dynarrays */
281
282 ST_FUNC void dynarray_add(void ***ptab, int *nb_ptr, void *data)
283 {
284     int nb, nb_alloc;
285     void **pp;
286     
287     nb = *nb_ptr;
288     pp = *ptab;
289     /* every power of two we double array size */
290     if ((nb & (nb - 1)) == 0) {
291         if (!nb)
292             nb_alloc = 1;
293         else
294             nb_alloc = nb * 2;
295         pp = tcc_realloc(pp, nb_alloc * sizeof(void *));
296         *ptab = pp;
297     }
298     pp[nb++] = data;
299     *nb_ptr = nb;
300 }
301
302 ST_FUNC void dynarray_reset(void *pp, int *n)
303 {
304     void **p;
305     for (p = *(void***)pp; *n; ++p, --*n)
306         if (*p)
307             tcc_free(*p);
308     tcc_free(*(void**)pp);
309     *(void**)pp = NULL;
310 }
311
312 static void tcc_split_path(TCCState *s, void ***p_ary, int *p_nb_ary, const char *in)
313 {
314     const char *p;
315     do {
316         int c;
317         CString str;
318
319         cstr_new(&str);
320         for (p = in; c = *p, c != '\0' && c != PATHSEP; ++p) {
321             if (c == '{' && p[1] && p[2] == '}') {
322                 c = p[1], p += 2;
323                 if (c == 'B')
324                     cstr_cat(&str, s->tcc_lib_path);
325             } else {
326                 cstr_ccat(&str, c);
327             }
328         }
329         cstr_ccat(&str, '\0');
330         dynarray_add(p_ary, p_nb_ary, str.data);
331         in = p+1;
332     } while (*p);
333 }
334
335 /********************************************************/
336
337 ST_FUNC Section *new_section(TCCState *s1, const char *name, int sh_type, int sh_flags)
338 {
339     Section *sec;
340
341     sec = tcc_mallocz(sizeof(Section) + strlen(name));
342     strcpy(sec->name, name);
343     sec->sh_type = sh_type;
344     sec->sh_flags = sh_flags;
345     switch(sh_type) {
346     case SHT_HASH:
347     case SHT_REL:
348     case SHT_RELA:
349     case SHT_DYNSYM:
350     case SHT_SYMTAB:
351     case SHT_DYNAMIC:
352         sec->sh_addralign = 4;
353         break;
354     case SHT_STRTAB:
355         sec->sh_addralign = 1;
356         break;
357     default:
358         sec->sh_addralign = 32; /* default conservative alignment */
359         break;
360     }
361
362     if (sh_flags & SHF_PRIVATE) {
363         dynarray_add((void ***)&s1->priv_sections, &s1->nb_priv_sections, sec);
364     } else {
365         sec->sh_num = s1->nb_sections;
366         dynarray_add((void ***)&s1->sections, &s1->nb_sections, sec);
367     }
368
369     return sec;
370 }
371
372 static void free_section(Section *s)
373 {
374     tcc_free(s->data);
375 }
376
377 /* realloc section and set its content to zero */
378 ST_FUNC void section_realloc(Section *sec, unsigned long new_size)
379 {
380     unsigned long size;
381     unsigned char *data;
382     
383     size = sec->data_allocated;
384     if (size == 0)
385         size = 1;
386     while (size < new_size)
387         size = size * 2;
388     data = tcc_realloc(sec->data, size);
389     memset(data + sec->data_allocated, 0, size - sec->data_allocated);
390     sec->data = data;
391     sec->data_allocated = size;
392 }
393
394 /* reserve at least 'size' bytes in section 'sec' from
395    sec->data_offset. */
396 ST_FUNC void *section_ptr_add(Section *sec, unsigned long size)
397 {
398     unsigned long offset, offset1;
399
400     offset = sec->data_offset;
401     offset1 = offset + size;
402     if (offset1 > sec->data_allocated)
403         section_realloc(sec, offset1);
404     sec->data_offset = offset1;
405     return sec->data + offset;
406 }
407
408 /* reserve at least 'size' bytes from section start */
409 ST_FUNC void section_reserve(Section *sec, unsigned long size)
410 {
411     if (size > sec->data_allocated)
412         section_realloc(sec, size);
413     if (size > sec->data_offset)
414         sec->data_offset = size;
415 }
416
417 /* return a reference to a section, and create it if it does not
418    exists */
419 ST_FUNC Section *find_section(TCCState *s1, const char *name)
420 {
421     Section *sec;
422     int i;
423     for(i = 1; i < s1->nb_sections; i++) {
424         sec = s1->sections[i];
425         if (!strcmp(name, sec->name)) 
426             return sec;
427     }
428     /* sections are created as PROGBITS */
429     return new_section(s1, name, SHT_PROGBITS, SHF_ALLOC);
430 }
431
432 /* update sym->c so that it points to an external symbol in section
433    'section' with value 'value' */
434 ST_FUNC void put_extern_sym2(Sym *sym, Section *section, 
435                             addr_t value, unsigned long size,
436                             int can_add_underscore)
437 {
438     int sym_type, sym_bind, sh_num, info, other;
439     ElfW(Sym) *esym;
440     const char *name;
441     char buf1[256];
442
443     if (section == NULL)
444         sh_num = SHN_UNDEF;
445     else if (section == SECTION_ABS) 
446         sh_num = SHN_ABS;
447     else
448         sh_num = section->sh_num;
449
450     if ((sym->type.t & VT_BTYPE) == VT_FUNC) {
451         sym_type = STT_FUNC;
452     } else if ((sym->type.t & VT_BTYPE) == VT_VOID) {
453         sym_type = STT_NOTYPE;
454     } else {
455         sym_type = STT_OBJECT;
456     }
457
458     if (sym->type.t & VT_STATIC)
459         sym_bind = STB_LOCAL;
460     else {
461         if (sym->type.t & VT_WEAK)
462             sym_bind = STB_WEAK;
463         else
464             sym_bind = STB_GLOBAL;
465     }
466
467     if (!sym->c) {
468         name = get_tok_str(sym->v, NULL);
469 #ifdef CONFIG_TCC_BCHECK
470         if (tcc_state->do_bounds_check) {
471             char buf[32];
472
473             /* XXX: avoid doing that for statics ? */
474             /* if bound checking is activated, we change some function
475                names by adding the "__bound" prefix */
476             switch(sym->v) {
477 #ifdef TCC_TARGET_PE
478             /* XXX: we rely only on malloc hooks */
479             case TOK_malloc: 
480             case TOK_free: 
481             case TOK_realloc: 
482             case TOK_memalign: 
483             case TOK_calloc: 
484 #endif
485             case TOK_memcpy: 
486             case TOK_memmove:
487             case TOK_memset:
488             case TOK_strlen:
489             case TOK_strcpy:
490             case TOK_alloca:
491                 strcpy(buf, "__bound_");
492                 strcat(buf, name);
493                 name = buf;
494                 break;
495             }
496         }
497 #endif
498         other = 0;
499
500 #ifdef TCC_TARGET_PE
501         if (sym->type.t & VT_EXPORT)
502             other |= 1;
503         if (sym_type == STT_FUNC && sym->type.ref) {
504             int attr = sym->type.ref->r;
505             if (FUNC_EXPORT(attr))
506                 other |= 1;
507             if (FUNC_CALL(attr) == FUNC_STDCALL && can_add_underscore) {
508                 sprintf(buf1, "_%s@%d", name, FUNC_ARGS(attr) * PTR_SIZE);
509                 name = buf1;
510                 other |= 2;
511                 can_add_underscore = 0;
512             }
513         } else {
514             if (find_elf_sym(tcc_state->dynsymtab_section, name))
515                 other |= 4;
516             if (sym->type.t & VT_IMPORT)
517                 other |= 4;
518         }
519 #endif
520         if (tcc_state->leading_underscore && can_add_underscore) {
521             buf1[0] = '_';
522             pstrcpy(buf1 + 1, sizeof(buf1) - 1, name);
523             name = buf1;
524         }
525         if (sym->asm_label) {
526             name = sym->asm_label;
527         }
528         info = ELFW(ST_INFO)(sym_bind, sym_type);
529         sym->c = add_elf_sym(symtab_section, value, size, info, other, sh_num, name);
530     } else {
531         esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
532         esym->st_value = value;
533         esym->st_size = size;
534         esym->st_shndx = sh_num;
535     }
536 }
537
538 ST_FUNC void put_extern_sym(Sym *sym, Section *section, 
539                            addr_t value, unsigned long size)
540 {
541     put_extern_sym2(sym, section, value, size, 1);
542 }
543
544 /* add a new relocation entry to symbol 'sym' in section 's' */
545 ST_FUNC void greloc(Section *s, Sym *sym, unsigned long offset, int type)
546 {
547     int c = 0;
548     if (sym) {
549         if (0 == sym->c)
550             put_extern_sym(sym, NULL, 0, 0);
551         c = sym->c;
552     }
553     /* now we can add ELF relocation info */
554     put_elf_reloc(symtab_section, s, offset, type, c);
555 }
556
557 /********************************************************/
558
559 static void strcat_vprintf(char *buf, int buf_size, const char *fmt, va_list ap)
560 {
561     int len;
562     len = strlen(buf);
563     vsnprintf(buf + len, buf_size - len, fmt, ap);
564 }
565
566 static void strcat_printf(char *buf, int buf_size, const char *fmt, ...)
567 {
568     va_list ap;
569     va_start(ap, fmt);
570     strcat_vprintf(buf, buf_size, fmt, ap);
571     va_end(ap);
572 }
573
574 static void error1(TCCState *s1, int is_warning, const char *fmt, va_list ap)
575 {
576     char buf[2048];
577     BufferedFile **pf, *f;
578     
579     buf[0] = '\0';
580     /* use upper file if inline ":asm:" or token ":paste:" */
581     for (f = file; f && f->filename[0] == ':'; f = f->prev)
582      ;
583     if (f) {
584         for(pf = s1->include_stack; pf < s1->include_stack_ptr; pf++)
585             strcat_printf(buf, sizeof(buf), "In file included from %s:%d:\n",
586                 (*pf)->filename, (*pf)->line_num);
587         if (f->line_num > 0) {
588             strcat_printf(buf, sizeof(buf), "%s:%d: ",
589                 f->filename, f->line_num);
590         } else {
591             strcat_printf(buf, sizeof(buf), "%s: ",
592                 f->filename);
593         }
594     } else {
595         strcat_printf(buf, sizeof(buf), "tcc: ");
596     }
597     if (is_warning)
598         strcat_printf(buf, sizeof(buf), "warning: ");
599     else
600         strcat_printf(buf, sizeof(buf), "error: ");
601     strcat_vprintf(buf, sizeof(buf), fmt, ap);
602
603     if (!s1->error_func) {
604         /* default case: stderr */
605         fprintf(stderr, "%s\n", buf);
606     } else {
607         s1->error_func(s1->error_opaque, buf);
608     }
609     if (!is_warning || s1->warn_error)
610         s1->nb_errors++;
611 }
612
613 LIBTCCAPI void tcc_set_error_func(TCCState *s, void *error_opaque,
614                         void (*error_func)(void *opaque, const char *msg))
615 {
616     s->error_opaque = error_opaque;
617     s->error_func = error_func;
618 }
619
620 /* error without aborting current compilation */
621 PUB_FUNC void tcc_error_noabort(const char *fmt, ...)
622 {
623     TCCState *s1 = tcc_state;
624     va_list ap;
625
626     va_start(ap, fmt);
627     error1(s1, 0, fmt, ap);
628     va_end(ap);
629 }
630
631 PUB_FUNC void tcc_error(const char *fmt, ...)
632 {
633     TCCState *s1 = tcc_state;
634     va_list ap;
635
636     va_start(ap, fmt);
637     error1(s1, 0, fmt, ap);
638     va_end(ap);
639     /* better than nothing: in some cases, we accept to handle errors */
640     if (s1->error_set_jmp_enabled) {
641         longjmp(s1->error_jmp_buf, 1);
642     } else {
643         /* XXX: eliminate this someday */
644         exit(1);
645     }
646 }
647
648 PUB_FUNC void tcc_warning(const char *fmt, ...)
649 {
650     TCCState *s1 = tcc_state;
651     va_list ap;
652
653     if (s1->warn_none)
654         return;
655
656     va_start(ap, fmt);
657     error1(s1, 1, fmt, ap);
658     va_end(ap);
659 }
660
661 /********************************************************/
662 /* I/O layer */
663
664 ST_FUNC void tcc_open_bf(TCCState *s1, const char *filename, int initlen)
665 {
666     BufferedFile *bf;
667     int buflen = initlen ? initlen : IO_BUF_SIZE;
668
669     bf = tcc_malloc(sizeof(BufferedFile) + buflen);
670     bf->buf_ptr = bf->buffer;
671     bf->buf_end = bf->buffer + initlen;
672     bf->buf_end[0] = CH_EOB; /* put eob symbol */
673     pstrcpy(bf->filename, sizeof(bf->filename), filename);
674 #ifdef _WIN32
675     normalize_slashes(bf->filename);
676 #endif
677     bf->line_num = 1;
678     bf->ifndef_macro = 0;
679     bf->ifdef_stack_ptr = s1->ifdef_stack_ptr;
680     bf->fd = -1;
681     bf->prev = file;
682     file = bf;
683 }
684
685 ST_FUNC void tcc_close(void)
686 {
687     BufferedFile *bf = file;
688     if (bf->fd > 0) {
689         close(bf->fd);
690         total_lines += bf->line_num;
691     }
692     file = bf->prev;
693     tcc_free(bf);
694 }
695
696 ST_FUNC int tcc_open(TCCState *s1, const char *filename)
697 {
698     int fd;
699     if (strcmp(filename, "-") == 0)
700         fd = 0, filename = "stdin";
701     else
702         fd = open(filename, O_RDONLY | O_BINARY);
703     if ((s1->verbose == 2 && fd >= 0) || s1->verbose == 3)
704         printf("%s %*s%s\n", fd < 0 ? "nf":"->",
705                (int)(s1->include_stack_ptr - s1->include_stack), "", filename);
706     if (fd < 0)
707         return -1;
708
709     tcc_open_bf(s1, filename, 0);
710     file->fd = fd;
711     return fd;
712 }
713
714 /* compile the C file opened in 'file'. Return non zero if errors. */
715 static int tcc_compile(TCCState *s1)
716 {
717     Sym *define_start;
718     SValue *pvtop;
719     char buf[512];
720     volatile int section_sym;
721
722 #ifdef INC_DEBUG
723     printf("%s: **** new file\n", file->filename);
724 #endif
725     preprocess_init(s1);
726
727     cur_text_section = NULL;
728     funcname = "";
729     anon_sym = SYM_FIRST_ANOM; 
730
731     /* file info: full path + filename */
732     section_sym = 0; /* avoid warning */
733     if (s1->do_debug) {
734         section_sym = put_elf_sym(symtab_section, 0, 0, 
735                                   ELFW(ST_INFO)(STB_LOCAL, STT_SECTION), 0, 
736                                   text_section->sh_num, NULL);
737         getcwd(buf, sizeof(buf));
738 #ifdef _WIN32
739         normalize_slashes(buf);
740 #endif
741         pstrcat(buf, sizeof(buf), "/");
742         put_stabs_r(buf, N_SO, 0, 0, 
743                     text_section->data_offset, text_section, section_sym);
744         put_stabs_r(file->filename, N_SO, 0, 0, 
745                     text_section->data_offset, text_section, section_sym);
746     }
747     /* an elf symbol of type STT_FILE must be put so that STB_LOCAL
748        symbols can be safely used */
749     put_elf_sym(symtab_section, 0, 0, 
750                 ELFW(ST_INFO)(STB_LOCAL, STT_FILE), 0, 
751                 SHN_ABS, file->filename);
752
753     /* define some often used types */
754     int_type.t = VT_INT;
755
756     char_pointer_type.t = VT_BYTE;
757     mk_pointer(&char_pointer_type);
758
759 #if PTR_SIZE == 4
760     size_type.t = VT_INT;
761 #else
762     size_type.t = VT_LLONG;
763 #endif
764
765     func_old_type.t = VT_FUNC;
766     func_old_type.ref = sym_push(SYM_FIELD, &int_type, FUNC_CDECL, FUNC_OLD);
767 #ifdef TCC_TARGET_ARM
768     arm_init_types();
769 #endif
770
771 #if 0
772     /* define 'void *alloca(unsigned int)' builtin function */
773     {
774         Sym *s1;
775
776         p = anon_sym++;
777         sym = sym_push(p, mk_pointer(VT_VOID), FUNC_CDECL, FUNC_NEW);
778         s1 = sym_push(SYM_FIELD, VT_UNSIGNED | VT_INT, 0, 0);
779         s1->next = NULL;
780         sym->next = s1;
781         sym_push(TOK_alloca, VT_FUNC | (p << VT_STRUCT_SHIFT), VT_CONST, 0);
782     }
783 #endif
784
785     define_start = define_stack;
786     nocode_wanted = 1;
787
788     if (setjmp(s1->error_jmp_buf) == 0) {
789         s1->nb_errors = 0;
790         s1->error_set_jmp_enabled = 1;
791
792         ch = file->buf_ptr[0];
793         tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
794         parse_flags = PARSE_FLAG_PREPROCESS | PARSE_FLAG_TOK_NUM;
795         pvtop = vtop;
796         next();
797         decl(VT_CONST);
798         if (tok != TOK_EOF)
799             expect("declaration");
800         if (pvtop != vtop)
801             tcc_warning("internal compiler error: vstack leak? (%d)", vtop - pvtop);
802
803         /* end of translation unit info */
804         if (s1->do_debug) {
805             put_stabs_r(NULL, N_SO, 0, 0, 
806                         text_section->data_offset, text_section, section_sym);
807         }
808     }
809
810     s1->error_set_jmp_enabled = 0;
811
812     /* reset define stack, but leave -Dsymbols (may be incorrect if
813        they are undefined) */
814     free_defines(define_start); 
815
816     gen_inline_functions();
817
818     sym_pop(&global_stack, NULL);
819     sym_pop(&local_stack, NULL);
820
821     return s1->nb_errors != 0 ? -1 : 0;
822 }
823
824 LIBTCCAPI int tcc_compile_string(TCCState *s, const char *str)
825 {
826     int len, ret;
827     len = strlen(str);
828
829     tcc_open_bf(s, "<string>", len);
830     memcpy(file->buffer, str, len);
831     ret = tcc_compile(s);
832     tcc_close();
833     return ret;
834 }
835
836 /* define a preprocessor symbol. A value can also be provided with the '=' operator */
837 LIBTCCAPI void tcc_define_symbol(TCCState *s1, const char *sym, const char *value)
838 {
839     int len1, len2;
840     /* default value */
841     if (!value)
842         value = "1";
843     len1 = strlen(sym);
844     len2 = strlen(value);
845
846     /* init file structure */
847     tcc_open_bf(s1, "<define>", len1 + len2 + 1);
848     memcpy(file->buffer, sym, len1);
849     file->buffer[len1] = ' ';
850     memcpy(file->buffer + len1 + 1, value, len2);
851
852     /* parse with define parser */
853     ch = file->buf_ptr[0];
854     next_nomacro();
855     parse_define();
856
857     tcc_close();
858 }
859
860 /* undefine a preprocessor symbol */
861 LIBTCCAPI void tcc_undefine_symbol(TCCState *s1, const char *sym)
862 {
863     TokenSym *ts;
864     Sym *s;
865     ts = tok_alloc(sym, strlen(sym));
866     s = define_find(ts->tok);
867     /* undefine symbol by putting an invalid name */
868     if (s)
869         define_undef(s);
870 }
871
872 /* cleanup all static data used during compilation */
873 static void tcc_cleanup(void)
874 {
875     int i, n;
876     if (NULL == tcc_state)
877         return;
878     tcc_state = NULL;
879
880     /* free -D defines */
881     free_defines(NULL);
882
883     /* free tokens */
884     n = tok_ident - TOK_IDENT;
885     for(i = 0; i < n; i++)
886         tcc_free(table_ident[i]);
887     tcc_free(table_ident);
888
889     /* free sym_pools */
890     dynarray_reset(&sym_pools, &nb_sym_pools);
891     /* string buffer */
892     cstr_free(&tokcstr);
893     /* reset symbol stack */
894     sym_free_first = NULL;
895     /* cleanup from error/setjmp */
896     macro_ptr = NULL;
897 }
898
899 LIBTCCAPI TCCState *tcc_new(void)
900 {
901     TCCState *s;
902     char buffer[100];
903     int a,b,c;
904
905     tcc_cleanup();
906
907     s = tcc_mallocz(sizeof(TCCState));
908     if (!s)
909         return NULL;
910     tcc_state = s;
911 #ifdef _WIN32
912     tcc_set_lib_path_w32(s);
913 #else
914     tcc_set_lib_path(s, CONFIG_TCCDIR);
915 #endif
916     s->output_type = TCC_OUTPUT_MEMORY;
917     preprocess_new();
918     s->include_stack_ptr = s->include_stack;
919
920     /* we add dummy defines for some special macros to speed up tests
921        and to have working defined() */
922     define_push(TOK___LINE__, MACRO_OBJ, NULL, NULL);
923     define_push(TOK___FILE__, MACRO_OBJ, NULL, NULL);
924     define_push(TOK___DATE__, MACRO_OBJ, NULL, NULL);
925     define_push(TOK___TIME__, MACRO_OBJ, NULL, NULL);
926
927     /* define __TINYC__ 92X  */
928     sscanf(TCC_VERSION, "%d.%d.%d", &a, &b, &c);
929     sprintf(buffer, "%d", a*10000 + b*100 + c);
930     tcc_define_symbol(s, "__TINYC__", buffer);
931
932     /* standard defines */
933     tcc_define_symbol(s, "__STDC__", NULL);
934     tcc_define_symbol(s, "__STDC_VERSION__", "199901L");
935     tcc_define_symbol(s, "__STDC_HOSTED__", NULL);
936
937     /* target defines */
938 #if defined(TCC_TARGET_I386)
939     tcc_define_symbol(s, "__i386__", NULL);
940     tcc_define_symbol(s, "__i386", NULL);
941     tcc_define_symbol(s, "i386", NULL);
942 #elif defined(TCC_TARGET_X86_64)
943     tcc_define_symbol(s, "__x86_64__", NULL);
944 #elif defined(TCC_TARGET_ARM)
945     tcc_define_symbol(s, "__ARM_ARCH_4__", NULL);
946     tcc_define_symbol(s, "__arm_elf__", NULL);
947     tcc_define_symbol(s, "__arm_elf", NULL);
948     tcc_define_symbol(s, "arm_elf", NULL);
949     tcc_define_symbol(s, "__arm__", NULL);
950     tcc_define_symbol(s, "__arm", NULL);
951     tcc_define_symbol(s, "arm", NULL);
952     tcc_define_symbol(s, "__APCS_32__", NULL);
953 #if defined(TCC_ARM_HARDFLOAT)
954     tcc_define_symbol(s, "__ARM_PCS_VFP", NULL);
955 #endif
956 #endif
957
958 #ifdef TCC_TARGET_PE
959     tcc_define_symbol(s, "_WIN32", NULL);
960 # ifdef TCC_TARGET_X86_64
961     tcc_define_symbol(s, "_WIN64", NULL);
962 # endif
963 #else
964     tcc_define_symbol(s, "__unix__", NULL);
965     tcc_define_symbol(s, "__unix", NULL);
966     tcc_define_symbol(s, "unix", NULL);
967 # if defined(__linux)
968     tcc_define_symbol(s, "__linux__", NULL);
969     tcc_define_symbol(s, "__linux", NULL);
970 # endif
971 # if defined(__FreeBSD__)
972 #  define str(s) #s
973     tcc_define_symbol(s, "__FreeBSD__", str( __FreeBSD__));
974 #  undef str
975 # endif
976 # if defined(__FreeBSD_kernel__)
977     tcc_define_symbol(s, "__FreeBSD_kernel__", NULL);
978 # endif
979 #endif
980
981     /* TinyCC & gcc defines */
982 #if defined TCC_TARGET_PE && defined TCC_TARGET_X86_64
983     tcc_define_symbol(s, "__SIZE_TYPE__", "unsigned long long");
984     tcc_define_symbol(s, "__PTRDIFF_TYPE__", "long long");
985 #else
986     tcc_define_symbol(s, "__SIZE_TYPE__", "unsigned long");
987     tcc_define_symbol(s, "__PTRDIFF_TYPE__", "long");
988 #endif
989
990 #ifdef TCC_TARGET_PE
991     tcc_define_symbol(s, "__WCHAR_TYPE__", "unsigned short");
992 #else
993     tcc_define_symbol(s, "__WCHAR_TYPE__", "int");
994 #endif
995
996 #ifndef TCC_TARGET_PE
997     /* glibc defines */
998     tcc_define_symbol(s, "__REDIRECT(name, proto, alias)", "name proto __asm__ (#alias)");
999     tcc_define_symbol(s, "__REDIRECT_NTH(name, proto, alias)", "name proto __asm__ (#alias) __THROW");
1000     /* default library paths */
1001     tcc_add_library_path(s, CONFIG_TCC_LIBPATHS);
1002     /* paths for crt objects */
1003     tcc_split_path(s, (void ***)&s->crt_paths, &s->nb_crt_paths, CONFIG_TCC_CRTPREFIX);
1004 #endif
1005
1006     /* no section zero */
1007     dynarray_add((void ***)&s->sections, &s->nb_sections, NULL);
1008
1009     /* create standard sections */
1010     text_section = new_section(s, ".text", SHT_PROGBITS, SHF_ALLOC | SHF_EXECINSTR);
1011     data_section = new_section(s, ".data", SHT_PROGBITS, SHF_ALLOC | SHF_WRITE);
1012     bss_section = new_section(s, ".bss", SHT_NOBITS, SHF_ALLOC | SHF_WRITE);
1013
1014     /* symbols are always generated for linking stage */
1015     symtab_section = new_symtab(s, ".symtab", SHT_SYMTAB, 0,
1016                                 ".strtab",
1017                                 ".hashtab", SHF_PRIVATE); 
1018     strtab_section = symtab_section->link;
1019     s->symtab = symtab_section;
1020     
1021     /* private symbol table for dynamic symbols */
1022     s->dynsymtab_section = new_symtab(s, ".dynsymtab", SHT_SYMTAB, SHF_PRIVATE,
1023                                       ".dynstrtab", 
1024                                       ".dynhashtab", SHF_PRIVATE);
1025     s->alacarte_link = 1;
1026     s->nocommon = 1;
1027     s->section_align = ELF_PAGE_SIZE;
1028
1029 #ifdef CHAR_IS_UNSIGNED
1030     s->char_is_unsigned = 1;
1031 #endif
1032     /* enable this if you want symbols with leading underscore on windows: */
1033 #if 0 /* def TCC_TARGET_PE */
1034     s->leading_underscore = 1;
1035 #endif
1036 #ifdef TCC_TARGET_I386
1037     s->seg_size = 32;
1038 #endif
1039     return s;
1040 }
1041
1042 LIBTCCAPI void tcc_delete(TCCState *s1)
1043 {
1044     int i;
1045
1046     tcc_cleanup();
1047
1048     /* free all sections */
1049     for(i = 1; i < s1->nb_sections; i++)
1050         free_section(s1->sections[i]);
1051     dynarray_reset(&s1->sections, &s1->nb_sections);
1052
1053     for(i = 0; i < s1->nb_priv_sections; i++)
1054         free_section(s1->priv_sections[i]);
1055     dynarray_reset(&s1->priv_sections, &s1->nb_priv_sections);
1056         
1057     /* free any loaded DLLs */
1058 #ifdef TCC_IS_NATIVE
1059     for ( i = 0; i < s1->nb_loaded_dlls; i++) {
1060         DLLReference *ref = s1->loaded_dlls[i];
1061         if ( ref->handle )
1062             dlclose(ref->handle);
1063     }
1064 #endif
1065     
1066     /* free loaded dlls array */
1067     dynarray_reset(&s1->loaded_dlls, &s1->nb_loaded_dlls);
1068
1069     /* free library paths */
1070     dynarray_reset(&s1->library_paths, &s1->nb_library_paths);
1071     dynarray_reset(&s1->crt_paths, &s1->nb_crt_paths);
1072
1073     /* free include paths */
1074     dynarray_reset(&s1->cached_includes, &s1->nb_cached_includes);
1075     dynarray_reset(&s1->include_paths, &s1->nb_include_paths);
1076     dynarray_reset(&s1->sysinclude_paths, &s1->nb_sysinclude_paths);
1077
1078     tcc_free(s1->tcc_lib_path);
1079     tcc_free(s1->soname);
1080     tcc_free(s1->rpath);
1081     tcc_free(s1->init_symbol);
1082     tcc_free(s1->fini_symbol);
1083     tcc_free(s1->outfile);
1084     tcc_free(s1->deps_outfile);
1085     dynarray_reset(&s1->files, &s1->nb_files);
1086     dynarray_reset(&s1->target_deps, &s1->nb_target_deps);
1087
1088 #ifdef TCC_IS_NATIVE
1089 # ifdef HAVE_SELINUX
1090     munmap (s1->write_mem, s1->mem_size);
1091     munmap (s1->runtime_mem, s1->mem_size);    
1092 # else
1093     tcc_free(s1->runtime_mem);
1094 # endif
1095 #endif
1096
1097     tcc_free(s1);
1098 }
1099
1100 LIBTCCAPI int tcc_add_include_path(TCCState *s, const char *pathname)
1101 {
1102     tcc_split_path(s, (void ***)&s->include_paths, &s->nb_include_paths, pathname);
1103     return 0;
1104 }
1105
1106 LIBTCCAPI int tcc_add_sysinclude_path(TCCState *s, const char *pathname)
1107 {
1108     tcc_split_path(s, (void ***)&s->sysinclude_paths, &s->nb_sysinclude_paths, pathname);
1109     return 0;
1110 }
1111
1112 ST_FUNC int tcc_add_file_internal(TCCState *s1, const char *filename, int flags)
1113 {
1114     const char *ext;
1115     ElfW(Ehdr) ehdr;
1116     int fd, ret, size;
1117
1118     /* find source file type with extension */
1119     ext = tcc_fileextension(filename);
1120     if (ext[0])
1121         ext++;
1122
1123 #ifdef CONFIG_TCC_ASM
1124     /* if .S file, define __ASSEMBLER__ like gcc does */
1125     if (!strcmp(ext, "S"))
1126         tcc_define_symbol(s1, "__ASSEMBLER__", NULL);
1127 #endif
1128
1129     /* open the file */
1130     ret = tcc_open(s1, filename);
1131     if (ret < 0) {
1132         if (flags & AFF_PRINT_ERROR)
1133             tcc_error_noabort("file '%s' not found", filename);
1134         return ret;
1135     }
1136
1137     /* update target deps */
1138     dynarray_add((void ***)&s1->target_deps, &s1->nb_target_deps,
1139             tcc_strdup(filename));
1140
1141     if (flags & AFF_PREPROCESS) {
1142         ret = tcc_preprocess(s1);
1143         goto the_end;
1144     }
1145
1146     if (!ext[0] || !PATHCMP(ext, "c")) {
1147         /* C file assumed */
1148         ret = tcc_compile(s1);
1149         goto the_end;
1150     }
1151
1152 #ifdef CONFIG_TCC_ASM
1153     if (!strcmp(ext, "S")) {
1154         /* preprocessed assembler */
1155         ret = tcc_assemble(s1, 1);
1156         goto the_end;
1157     }
1158
1159     if (!strcmp(ext, "s")) {
1160         /* non preprocessed assembler */
1161         ret = tcc_assemble(s1, 0);
1162         goto the_end;
1163     }
1164 #endif
1165
1166     fd = file->fd;
1167     /* assume executable format: auto guess file type */
1168     size = read(fd, &ehdr, sizeof(ehdr));
1169     lseek(fd, 0, SEEK_SET);
1170     if (size <= 0) {
1171         tcc_error_noabort("could not read header");
1172         goto the_end;
1173     }
1174
1175     if (size == sizeof(ehdr) &&
1176         ehdr.e_ident[0] == ELFMAG0 &&
1177         ehdr.e_ident[1] == ELFMAG1 &&
1178         ehdr.e_ident[2] == ELFMAG2 &&
1179         ehdr.e_ident[3] == ELFMAG3) {
1180
1181         /* do not display line number if error */
1182         file->line_num = 0;
1183         if (ehdr.e_type == ET_REL) {
1184             ret = tcc_load_object_file(s1, fd, 0);
1185             goto the_end;
1186
1187         }
1188 #ifndef TCC_TARGET_PE
1189         if (ehdr.e_type == ET_DYN) {
1190             if (s1->output_type == TCC_OUTPUT_MEMORY) {
1191 #ifdef TCC_IS_NATIVE
1192                 void *h;
1193                 h = dlopen(filename, RTLD_GLOBAL | RTLD_LAZY);
1194                 if (h)
1195 #endif
1196                     ret = 0;
1197             } else {
1198                 ret = tcc_load_dll(s1, fd, filename, 
1199                                    (flags & AFF_REFERENCED_DLL) != 0);
1200             }
1201             goto the_end;
1202         }
1203 #endif
1204         tcc_error_noabort("unrecognized ELF file");
1205         goto the_end;
1206     }
1207
1208     if (memcmp((char *)&ehdr, ARMAG, 8) == 0) {
1209         file->line_num = 0; /* do not display line number if error */
1210         ret = tcc_load_archive(s1, fd);
1211         goto the_end;
1212     }
1213
1214 #ifdef TCC_TARGET_COFF
1215     if (*(uint16_t *)(&ehdr) == COFF_C67_MAGIC) {
1216         ret = tcc_load_coff(s1, fd);
1217         goto the_end;
1218     }
1219 #endif
1220
1221 #ifdef TCC_TARGET_PE
1222     ret = pe_load_file(s1, filename, fd);
1223 #else
1224     /* as GNU ld, consider it is an ld script if not recognized */
1225     ret = tcc_load_ldscript(s1);
1226 #endif
1227     if (ret < 0)
1228         tcc_error_noabort("unrecognized file type");
1229
1230 the_end:
1231     tcc_close();
1232     return ret;
1233 }
1234
1235 LIBTCCAPI int tcc_add_file(TCCState *s, const char *filename)
1236 {
1237     if (s->output_type == TCC_OUTPUT_PREPROCESS)
1238         return tcc_add_file_internal(s, filename, AFF_PRINT_ERROR | AFF_PREPROCESS);
1239     else
1240         return tcc_add_file_internal(s, filename, AFF_PRINT_ERROR);
1241 }
1242
1243 LIBTCCAPI int tcc_add_library_path(TCCState *s, const char *pathname)
1244 {
1245     tcc_split_path(s, (void ***)&s->library_paths, &s->nb_library_paths, pathname);
1246     return 0;
1247 }
1248
1249 static int tcc_add_library_internal(TCCState *s, const char *fmt,
1250     const char *filename, int flags, char **paths, int nb_paths)
1251 {
1252     char buf[1024];
1253     int i;
1254
1255     for(i = 0; i < nb_paths; i++) {
1256         snprintf(buf, sizeof(buf), fmt, paths[i], filename);
1257         if (tcc_add_file_internal(s, buf, flags) == 0)
1258             return 0;
1259     }
1260     return -1;
1261 }
1262
1263 /* find and load a dll. Return non zero if not found */
1264 /* XXX: add '-rpath' option support ? */
1265 ST_FUNC int tcc_add_dll(TCCState *s, const char *filename, int flags)
1266 {
1267     return tcc_add_library_internal(s, "%s/%s", filename, flags,
1268         s->library_paths, s->nb_library_paths);
1269 }
1270
1271 ST_FUNC int tcc_add_crt(TCCState *s, const char *filename)
1272 {
1273     if (-1 == tcc_add_library_internal(s, "%s/%s",
1274         filename, 0, s->crt_paths, s->nb_crt_paths))
1275         tcc_error_noabort("file '%s' not found", filename);
1276     return 0;
1277 }
1278
1279 /* the library name is the same as the argument of the '-l' option */
1280 LIBTCCAPI int tcc_add_library(TCCState *s, const char *libraryname)
1281 {
1282 #ifdef TCC_TARGET_PE
1283     const char *libs[] = { "%s/%s.def", "%s/lib%s.def", "%s/%s.dll", "%s/lib%s.dll", "%s/lib%s.a", NULL };
1284     const char **pp = s->static_link ? libs + 4 : libs;
1285 #else
1286     const char *libs[] = { "%s/lib%s.so", "%s/lib%s.a", NULL };
1287     const char **pp = s->static_link ? libs + 1 : libs;
1288 #endif
1289     while (*pp) {
1290         if (0 == tcc_add_library_internal(s, *pp,
1291             libraryname, 0, s->library_paths, s->nb_library_paths))
1292             return 0;
1293         ++pp;
1294     }
1295     return -1;
1296 }
1297
1298 LIBTCCAPI int tcc_add_symbol(TCCState *s, const char *name, const void *val)
1299 {
1300 #ifdef TCC_TARGET_PE
1301     /* On x86_64 'val' might not be reachable with a 32bit offset.
1302        So it is handled here as if it were in a DLL. */
1303     pe_putimport(s, 0, name, (uintptr_t)val);
1304 #else
1305     /* XXX: Same problem on linux but currently "solved" elsewhere
1306        via the rather dirty 'runtime_plt_and_got' hack. */
1307     add_elf_sym(symtab_section, (uintptr_t)val, 0,
1308         ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE), 0,
1309         SHN_ABS, name);
1310 #endif
1311     return 0;
1312 }
1313
1314 LIBTCCAPI int tcc_set_output_type(TCCState *s, int output_type)
1315 {
1316     s->output_type = output_type;
1317
1318     if (!s->nostdinc) {
1319         /* default include paths */
1320         /* -isystem paths have already been handled */
1321         tcc_add_sysinclude_path(s, CONFIG_TCC_SYSINCLUDEPATHS);
1322     }
1323
1324     /* if bound checking, then add corresponding sections */
1325 #ifdef CONFIG_TCC_BCHECK
1326     if (s->do_bounds_check) {
1327         /* define symbol */
1328         tcc_define_symbol(s, "__BOUNDS_CHECKING_ON", NULL);
1329         /* create bounds sections */
1330         bounds_section = new_section(s, ".bounds", 
1331                                      SHT_PROGBITS, SHF_ALLOC);
1332         lbounds_section = new_section(s, ".lbounds", 
1333                                       SHT_PROGBITS, SHF_ALLOC);
1334     }
1335 #endif
1336
1337     if (s->char_is_unsigned) {
1338         tcc_define_symbol(s, "__CHAR_UNSIGNED__", NULL);
1339     }
1340
1341     /* add debug sections */
1342     if (s->do_debug) {
1343         /* stab symbols */
1344         stab_section = new_section(s, ".stab", SHT_PROGBITS, 0);
1345         stab_section->sh_entsize = sizeof(Stab_Sym);
1346         stabstr_section = new_section(s, ".stabstr", SHT_STRTAB, 0);
1347         put_elf_str(stabstr_section, "");
1348         stab_section->link = stabstr_section;
1349         /* put first entry */
1350         put_stabs("", 0, 0, 0, 0);
1351     }
1352
1353 #ifdef TCC_TARGET_PE
1354     tcc_add_library_path(s, CONFIG_TCC_LIBPATHS);
1355 # ifdef _WIN32
1356     tcc_add_systemdir(s);
1357 # endif
1358 #else
1359     /* add libc crt1/crti objects */
1360     if ((output_type == TCC_OUTPUT_EXE || output_type == TCC_OUTPUT_DLL) &&
1361         !s->nostdlib) {
1362         if (output_type != TCC_OUTPUT_DLL)
1363             tcc_add_crt(s, "crt1.o");
1364         tcc_add_crt(s, "crti.o");
1365     }
1366 #endif
1367     return 0;
1368 }
1369
1370 LIBTCCAPI void tcc_set_lib_path(TCCState *s, const char *path)
1371 {
1372     tcc_free(s->tcc_lib_path);
1373     s->tcc_lib_path = tcc_strdup(path);
1374 }
1375
1376 #define WD_ALL    0x0001 /* warning is activated when using -Wall */
1377 #define FD_INVERT 0x0002 /* invert value before storing */
1378
1379 typedef struct FlagDef {
1380     uint16_t offset;
1381     uint16_t flags;
1382     const char *name;
1383 } FlagDef;
1384
1385 static const FlagDef warning_defs[] = {
1386     { offsetof(TCCState, warn_unsupported), 0, "unsupported" },
1387     { offsetof(TCCState, warn_write_strings), 0, "write-strings" },
1388     { offsetof(TCCState, warn_error), 0, "error" },
1389     { offsetof(TCCState, warn_implicit_function_declaration), WD_ALL,
1390       "implicit-function-declaration" },
1391 };
1392
1393 ST_FUNC int set_flag(TCCState *s, const FlagDef *flags, int nb_flags,
1394                     const char *name, int value)
1395 {
1396     int i;
1397     const FlagDef *p;
1398     const char *r;
1399
1400     r = name;
1401     if (r[0] == 'n' && r[1] == 'o' && r[2] == '-') {
1402         r += 3;
1403         value = !value;
1404     }
1405     for(i = 0, p = flags; i < nb_flags; i++, p++) {
1406         if (!strcmp(r, p->name))
1407             goto found;
1408     }
1409     return -1;
1410  found:
1411     if (p->flags & FD_INVERT)
1412         value = !value;
1413     *(int *)((uint8_t *)s + p->offset) = value;
1414     return 0;
1415 }
1416
1417 /* set/reset a warning */
1418 static int tcc_set_warning(TCCState *s, const char *warning_name, int value)
1419 {
1420     int i;
1421     const FlagDef *p;
1422
1423     if (!strcmp(warning_name, "all")) {
1424         for(i = 0, p = warning_defs; i < countof(warning_defs); i++, p++) {
1425             if (p->flags & WD_ALL)
1426                 *(int *)((uint8_t *)s + p->offset) = 1;
1427         }
1428         return 0;
1429     } else {
1430         return set_flag(s, warning_defs, countof(warning_defs),
1431                         warning_name, value);
1432     }
1433 }
1434
1435 static const FlagDef flag_defs[] = {
1436     { offsetof(TCCState, char_is_unsigned), 0, "unsigned-char" },
1437     { offsetof(TCCState, char_is_unsigned), FD_INVERT, "signed-char" },
1438     { offsetof(TCCState, nocommon), FD_INVERT, "common" },
1439     { offsetof(TCCState, leading_underscore), 0, "leading-underscore" },
1440 };
1441
1442 /* set/reset a flag */
1443 static int tcc_set_flag(TCCState *s, const char *flag_name, int value)
1444 {
1445     return set_flag(s, flag_defs, countof(flag_defs),
1446                     flag_name, value);
1447 }
1448
1449
1450 static int strstart(const char *val, const char **str)
1451 {
1452     const char *p, *q;
1453     p = *str;
1454     q = val;
1455     while (*q) {
1456         if (*p != *q)
1457             return 0;
1458         p++;
1459         q++;
1460     }
1461     *str = p;
1462     return 1;
1463 }
1464
1465 /* Like strstart, but automatically takes into account that ld options can
1466  *
1467  * - start with double or single dash (e.g. '--soname' or '-soname')
1468  * - arguments can be given as separate or after '=' (e.g. '-Wl,-soname,x.so'
1469  *   or '-Wl,-soname=x.so')
1470  *
1471  * you provide `val` always in 'option[=]' form (no leading -)
1472  */
1473 static int link_option(const char *str, const char *val, const char **ptr)
1474 {
1475     const char *p, *q;
1476
1477     /* there should be 1 or 2 dashes */
1478     if (*str++ != '-')
1479         return 0;
1480     if (*str == '-')
1481         str++;
1482
1483     /* then str & val should match (potentialy up to '=') */
1484     p = str;
1485     q = val;
1486
1487     while (*q != '\0' && *q != '=') {
1488         if (*p != *q)
1489             return 0;
1490         p++;
1491         q++;
1492     }
1493
1494     /* '=' near eos means ',' or '=' is ok */
1495     if (*q == '=') {
1496         if (*p != ',' && *p != '=')
1497             return 0;
1498         p++;
1499         q++;
1500     }
1501
1502     if (ptr)
1503         *ptr = p;
1504     return 1;
1505 }
1506
1507 static const char *skip_linker_arg(const char **str)
1508 {
1509     const char *s1 = *str;
1510     const char *s2 = strchr(s1, ',');
1511     *str = s2 ? s2++ : (s2 = s1 + strlen(s1));
1512     return s2;
1513 }
1514
1515 static char *copy_linker_arg(const char *p)
1516 {
1517     const char *q = p;
1518     skip_linker_arg(&q);
1519     return pstrncpy(tcc_malloc(q - p + 1), p, q - p);
1520 }
1521
1522 /* set linker options */
1523 static int tcc_set_linker(TCCState *s, const char *option)
1524 {
1525     while (option && *option) {
1526
1527         const char *p = option;
1528         char *end = NULL;
1529         int ignoring = 0;
1530
1531         if (link_option(option, "Bsymbolic", &p)) {
1532             s->symbolic = 1;
1533         } else if (link_option(option, "nostdlib", &p)) {
1534             s->nostdlib = 1;
1535         } else if (link_option(option, "fini=", &p)) {
1536             s->fini_symbol = copy_linker_arg(p);
1537             ignoring = 1;
1538         } else if (link_option(option, "image-base=", &p)
1539                 || link_option(option, "Ttext=", &p)) {
1540             s->text_addr = strtoull(p, &end, 16);
1541             s->has_text_addr = 1;
1542         } else if (link_option(option, "init=", &p)) {
1543             s->init_symbol = copy_linker_arg(p);
1544             ignoring = 1;
1545         } else if (link_option(option, "oformat=", &p)) {
1546 #if defined(TCC_TARGET_PE)
1547             if (strstart("pe-", &p)) {
1548 #elif defined(TCC_TARGET_X86_64)
1549             if (strstart("elf64-", &p)) {
1550 #else
1551             if (strstart("elf32-", &p)) {
1552 #endif
1553                 s->output_format = TCC_OUTPUT_FORMAT_ELF;
1554             } else if (!strcmp(p, "binary")) {
1555                 s->output_format = TCC_OUTPUT_FORMAT_BINARY;
1556 #ifdef TCC_TARGET_COFF
1557             } else if (!strcmp(p, "coff")) {
1558                 s->output_format = TCC_OUTPUT_FORMAT_COFF;
1559 #endif
1560             } else
1561                 goto err;
1562
1563         } else if (link_option(option, "rpath=", &p)) {
1564             s->rpath = copy_linker_arg(p);
1565         } else if (link_option(option, "section-alignment=", &p)) {
1566             s->section_align = strtoul(p, &end, 16);
1567         } else if (link_option(option, "soname=", &p)) {
1568             s->soname = copy_linker_arg(p);
1569 #ifdef TCC_TARGET_PE
1570         } else if (link_option(option, "file-alignment=", &p)) {
1571             s->pe_file_align = strtoul(p, &end, 16);
1572         } else if (link_option(option, "stack=", &p)) {
1573             s->pe_stack_size = strtoul(p, &end, 10);
1574         } else if (link_option(option, "subsystem=", &p)) {
1575 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
1576             if (!strcmp(p, "native")) {
1577                 s->pe_subsystem = 1;
1578             } else if (!strcmp(p, "console")) {
1579                 s->pe_subsystem = 3;
1580             } else if (!strcmp(p, "gui")) {
1581                 s->pe_subsystem = 2;
1582             } else if (!strcmp(p, "posix")) {
1583                 s->pe_subsystem = 7;
1584             } else if (!strcmp(p, "efiapp")) {
1585                 s->pe_subsystem = 10;
1586             } else if (!strcmp(p, "efiboot")) {
1587                 s->pe_subsystem = 11;
1588             } else if (!strcmp(p, "efiruntime")) {
1589                 s->pe_subsystem = 12;
1590             } else if (!strcmp(p, "efirom")) {
1591                 s->pe_subsystem = 13;
1592 #elif defined(TCC_TARGET_ARM)
1593             if (!strcmp(p, "wince")) {
1594                 s->pe_subsystem = 9;
1595 #endif
1596             } else
1597                 goto err;
1598 #endif
1599         } else
1600             goto err;
1601
1602         if (ignoring && s->warn_unsupported) err: {
1603             char buf[100], *e;
1604             pstrcpy(buf, sizeof buf, e = copy_linker_arg(option)), tcc_free(e);
1605             if (ignoring)
1606                 tcc_warning("unsupported linker option '%s'", buf);
1607             else
1608                 tcc_error("unsupported linker option '%s'", buf);
1609         }
1610         option = skip_linker_arg(&p);
1611     }
1612     return 0;
1613 }
1614
1615 typedef struct TCCOption {
1616     const char *name;
1617     uint16_t index;
1618     uint16_t flags;
1619 } TCCOption;
1620
1621 enum {
1622     TCC_OPTION_HELP,
1623     TCC_OPTION_I,
1624     TCC_OPTION_D,
1625     TCC_OPTION_U,
1626     TCC_OPTION_L,
1627     TCC_OPTION_B,
1628     TCC_OPTION_l,
1629     TCC_OPTION_bench,
1630     TCC_OPTION_bt,
1631     TCC_OPTION_b,
1632     TCC_OPTION_g,
1633     TCC_OPTION_c,
1634     TCC_OPTION_static,
1635     TCC_OPTION_shared,
1636     TCC_OPTION_soname,
1637     TCC_OPTION_o,
1638     TCC_OPTION_r,
1639     TCC_OPTION_s,
1640     TCC_OPTION_Wl,
1641     TCC_OPTION_W,
1642     TCC_OPTION_O,
1643     TCC_OPTION_m,
1644     TCC_OPTION_f,
1645     TCC_OPTION_isystem,
1646     TCC_OPTION_nostdinc,
1647     TCC_OPTION_nostdlib,
1648     TCC_OPTION_print_search_dirs,
1649     TCC_OPTION_rdynamic,
1650     TCC_OPTION_pedantic,
1651     TCC_OPTION_pthread,
1652     TCC_OPTION_run,
1653     TCC_OPTION_norunsrc,
1654     TCC_OPTION_v,
1655     TCC_OPTION_w,
1656     TCC_OPTION_pipe,
1657     TCC_OPTION_E,
1658     TCC_OPTION_MD,
1659     TCC_OPTION_MF,
1660     TCC_OPTION_x,
1661     TCC_OPTION_dumpversion,
1662 };
1663
1664 #define TCC_OPTION_HAS_ARG 0x0001
1665 #define TCC_OPTION_NOSEP   0x0002 /* cannot have space before option and arg */
1666
1667 static const TCCOption tcc_options[] = {
1668     { "h", TCC_OPTION_HELP, 0 },
1669     { "-help", TCC_OPTION_HELP, 0 },
1670     { "?", TCC_OPTION_HELP, 0 },
1671     { "I", TCC_OPTION_I, TCC_OPTION_HAS_ARG },
1672     { "D", TCC_OPTION_D, TCC_OPTION_HAS_ARG },
1673     { "U", TCC_OPTION_U, TCC_OPTION_HAS_ARG },
1674     { "L", TCC_OPTION_L, TCC_OPTION_HAS_ARG },
1675     { "B", TCC_OPTION_B, TCC_OPTION_HAS_ARG },
1676     { "l", TCC_OPTION_l, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1677     { "bench", TCC_OPTION_bench, 0 },
1678 #ifdef CONFIG_TCC_BACKTRACE
1679     { "bt", TCC_OPTION_bt, TCC_OPTION_HAS_ARG },
1680 #endif
1681 #ifdef CONFIG_TCC_BCHECK
1682     { "b", TCC_OPTION_b, 0 },
1683 #endif
1684     { "g", TCC_OPTION_g, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1685     { "c", TCC_OPTION_c, 0 },
1686     { "static", TCC_OPTION_static, 0 },
1687     { "shared", TCC_OPTION_shared, 0 },
1688     { "soname", TCC_OPTION_soname, TCC_OPTION_HAS_ARG },
1689     { "o", TCC_OPTION_o, TCC_OPTION_HAS_ARG },
1690     { "pedantic", TCC_OPTION_pedantic, 0},
1691     { "pthread", TCC_OPTION_pthread, 0},
1692     { "run", TCC_OPTION_run, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1693     { "norunsrc", TCC_OPTION_norunsrc, 0 },
1694     { "rdynamic", TCC_OPTION_rdynamic, 0 },
1695     { "r", TCC_OPTION_r, 0 },
1696     { "s", TCC_OPTION_s, 0 },
1697     { "Wl,", TCC_OPTION_Wl, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1698     { "W", TCC_OPTION_W, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1699     { "O", TCC_OPTION_O, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1700     { "m", TCC_OPTION_m, TCC_OPTION_HAS_ARG },
1701     { "f", TCC_OPTION_f, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1702     { "isystem", TCC_OPTION_isystem, TCC_OPTION_HAS_ARG },
1703     { "nostdinc", TCC_OPTION_nostdinc, 0 },
1704     { "nostdlib", TCC_OPTION_nostdlib, 0 },
1705     { "print-search-dirs", TCC_OPTION_print_search_dirs, 0 }, 
1706     { "v", TCC_OPTION_v, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1707     { "w", TCC_OPTION_w, 0 },
1708     { "pipe", TCC_OPTION_pipe, 0},
1709     { "E", TCC_OPTION_E, 0},
1710     { "MD", TCC_OPTION_MD, 0},
1711     { "MF", TCC_OPTION_MF, TCC_OPTION_HAS_ARG },
1712     { "x", TCC_OPTION_x, TCC_OPTION_HAS_ARG },
1713     { "dumpversion", TCC_OPTION_dumpversion, 0},
1714     { NULL, 0, 0 },
1715 };
1716
1717 static void parse_option_D(TCCState *s1, const char *optarg)
1718 {
1719     char *sym = tcc_strdup(optarg);
1720     char *value = strchr(sym, '=');
1721     if (value)
1722         *value++ = '\0';
1723     tcc_define_symbol(s1, sym, value);
1724     tcc_free(sym);
1725 }
1726
1727 PUB_FUNC int tcc_parse_args(TCCState *s, int argc, char **argv)
1728 {
1729     const TCCOption *popt;
1730     const char *optarg, *r;
1731     int run = 0;
1732     int norunsrc = 0;
1733     int pthread = 0;
1734     int optind = 0;
1735
1736     /* collect -Wl options for input such as "-Wl,-rpath -Wl,<path>" */
1737     CString linker_arg;
1738     cstr_new(&linker_arg);
1739
1740     while (optind < argc) {
1741
1742         r = argv[optind++];
1743         if (r[0] != '-' || r[1] == '\0') {
1744             /* add a new file */
1745             if (!run || !norunsrc)
1746               dynarray_add((void ***)&s->files, &s->nb_files, tcc_strdup(r));
1747             if (run) {
1748                 optind--;
1749                 /* argv[0] will be this file */
1750                 break;
1751             }
1752             continue;
1753         }
1754
1755         /* find option in table */
1756         for(popt = tcc_options; ; ++popt) {
1757             const char *p1 = popt->name;
1758             const char *r1 = r + 1;
1759             if (p1 == NULL)
1760                 tcc_error("invalid option -- '%s'", r);
1761             if (!strstart(p1, &r1))
1762                 continue;
1763             optarg = r1;
1764             if (popt->flags & TCC_OPTION_HAS_ARG) {
1765                 if (*r1 == '\0' && !(popt->flags & TCC_OPTION_NOSEP)) {
1766                     if (optind >= argc)
1767                         tcc_error("argument to '%s' is missing", r);
1768                     optarg = argv[optind++];
1769                 }
1770             } else if (*r1 != '\0')
1771                 continue;
1772             break;
1773         }
1774
1775         switch(popt->index) {
1776         case TCC_OPTION_HELP:
1777             return 0;
1778         case TCC_OPTION_I:
1779             if (tcc_add_include_path(s, optarg) < 0)
1780                 tcc_error("too many include paths");
1781             break;
1782         case TCC_OPTION_D:
1783             parse_option_D(s, optarg);
1784             break;
1785         case TCC_OPTION_U:
1786             tcc_undefine_symbol(s, optarg);
1787             break;
1788         case TCC_OPTION_L:
1789             tcc_add_library_path(s, optarg);
1790             break;
1791         case TCC_OPTION_B:
1792             /* set tcc utilities path (mainly for tcc development) */
1793             tcc_set_lib_path(s, optarg);
1794             break;
1795         case TCC_OPTION_l:
1796             dynarray_add((void ***)&s->files, &s->nb_files, tcc_strdup(r));
1797             s->nb_libraries++;
1798             break;
1799         case TCC_OPTION_pthread:
1800             parse_option_D(s, "_REENTRANT");
1801             pthread = 1;
1802             break;
1803         case TCC_OPTION_bench:
1804             s->do_bench = 1;
1805             break;
1806 #ifdef CONFIG_TCC_BACKTRACE
1807         case TCC_OPTION_bt:
1808             tcc_set_num_callers(atoi(optarg));
1809             break;
1810 #endif
1811 #ifdef CONFIG_TCC_BCHECK
1812         case TCC_OPTION_b:
1813             s->do_bounds_check = 1;
1814             s->do_debug = 1;
1815             break;
1816 #endif
1817         case TCC_OPTION_g:
1818             s->do_debug = 1;
1819             break;
1820         case TCC_OPTION_c:
1821             s->output_type = TCC_OUTPUT_OBJ;
1822             break;
1823         case TCC_OPTION_static:
1824             s->static_link = 1;
1825             break;
1826         case TCC_OPTION_shared:
1827             s->output_type = TCC_OUTPUT_DLL;
1828             break;
1829         case TCC_OPTION_soname:
1830             s->soname = tcc_strdup(optarg);
1831             break;
1832         case TCC_OPTION_m:
1833             s->option_m = tcc_strdup(optarg);
1834             break;
1835         case TCC_OPTION_o:
1836             s->outfile = tcc_strdup(optarg);
1837             break;
1838         case TCC_OPTION_r:
1839             /* generate a .o merging several output files */
1840             s->option_r = 1;
1841             s->output_type = TCC_OUTPUT_OBJ;
1842             break;
1843         case TCC_OPTION_isystem:
1844             tcc_add_sysinclude_path(s, optarg);
1845             break;
1846         case TCC_OPTION_nostdinc:
1847             s->nostdinc = 1;
1848             break;
1849         case TCC_OPTION_nostdlib:
1850             s->nostdlib = 1;
1851             break;
1852         case TCC_OPTION_print_search_dirs:
1853             s->print_search_dirs = 1;
1854             break;
1855         case TCC_OPTION_run:
1856             s->output_type = TCC_OUTPUT_MEMORY;
1857             tcc_set_options(s, optarg);
1858             run = 1;
1859             break;
1860         case TCC_OPTION_norunsrc:
1861             norunsrc = 1;
1862             break;
1863         case TCC_OPTION_v:
1864             do ++s->verbose; while (*optarg++ == 'v');
1865             break;
1866         case TCC_OPTION_f:
1867             if (tcc_set_flag(s, optarg, 1) < 0 && s->warn_unsupported)
1868                 goto unsupported_option;
1869             break;
1870         case TCC_OPTION_W:
1871             if (tcc_set_warning(s, optarg, 1) < 0 && 
1872                 s->warn_unsupported)
1873                 goto unsupported_option;
1874             break;
1875         case TCC_OPTION_w:
1876             s->warn_none = 1;
1877             break;
1878         case TCC_OPTION_rdynamic:
1879             s->rdynamic = 1;
1880             break;
1881         case TCC_OPTION_Wl:
1882             if (linker_arg.size)
1883                 --linker_arg.size, cstr_ccat(&linker_arg, ',');
1884             cstr_cat(&linker_arg, optarg);
1885             cstr_ccat(&linker_arg, '\0');
1886             break;
1887         case TCC_OPTION_E:
1888             s->output_type = TCC_OUTPUT_PREPROCESS;
1889             break;
1890         case TCC_OPTION_MD:
1891             s->gen_deps = 1;
1892             break;
1893         case TCC_OPTION_MF:
1894             s->deps_outfile = tcc_strdup(optarg);
1895             break;
1896         case TCC_OPTION_dumpversion:
1897             printf ("%s\n", TCC_VERSION);
1898             exit(0);
1899         case TCC_OPTION_O:
1900         case TCC_OPTION_pedantic:
1901         case TCC_OPTION_pipe:
1902         case TCC_OPTION_s:
1903         case TCC_OPTION_x:
1904             /* ignored */
1905             break;
1906         default:
1907             if (s->warn_unsupported) {
1908             unsupported_option:
1909                 tcc_warning("unsupported option '%s'", r);
1910             }
1911             break;
1912         }
1913     }
1914
1915     if (pthread && s->output_type != TCC_OUTPUT_OBJ)
1916         tcc_set_options(s, "-lpthread");
1917
1918     tcc_set_linker(s, (const char *)linker_arg.data);
1919     cstr_free(&linker_arg);
1920
1921     return optind;
1922 }
1923
1924 LIBTCCAPI int tcc_set_options(TCCState *s, const char *str)
1925 {
1926     const char *s1;
1927     char **argv, *arg;
1928     int argc, len;
1929     int ret;
1930
1931     argc = 0, argv = NULL;
1932     for(;;) {
1933         while (is_space(*str))
1934             str++;
1935         if (*str == '\0')
1936             break;
1937         s1 = str;
1938         while (*str != '\0' && !is_space(*str))
1939             str++;
1940         len = str - s1;
1941         arg = tcc_malloc(len + 1);
1942         pstrncpy(arg, s1, len);
1943         dynarray_add((void ***)&argv, &argc, arg);
1944     }
1945     ret = tcc_parse_args(s, argc, argv);
1946     dynarray_reset(&argv, &argc);
1947     return ret;
1948 }
1949
1950 PUB_FUNC void tcc_print_stats(TCCState *s, int64_t total_time)
1951 {
1952     double tt;
1953     tt = (double)total_time / 1000000.0;
1954     if (tt < 0.001)
1955         tt = 0.001;
1956     if (total_bytes < 1)
1957         total_bytes = 1;
1958     printf("%d idents, %d lines, %d bytes, %0.3f s, %d lines/s, %0.1f MB/s\n", 
1959            tok_ident - TOK_IDENT, total_lines, total_bytes,
1960            tt, (int)(total_lines / tt),
1961            total_bytes / tt / 1000000.0);
1962 }
1963
1964 PUB_FUNC void tcc_set_environment(TCCState *s)
1965 {
1966     char * path;
1967     
1968     path = getenv("C_INCLUDE_PATH");
1969     if(path != NULL) {
1970         tcc_add_include_path(s, path);
1971     }
1972     path = getenv("CPATH");
1973     if(path != NULL) {
1974         tcc_add_include_path(s, path);
1975     }
1976     path = getenv("LIBRARY_PATH");
1977     if(path != NULL) {
1978         tcc_add_library_path(s, path);
1979     }
1980 }