win64: va_arg with structures
[tinycc.git] / libtcc.c
blob9fa0dd82764879a99c2992e742bf870ee4fc363d
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 /* use GNU C extensions */
27 ST_DATA int gnu_ext = 1;
29 /* use TinyCC extensions */
30 ST_DATA int tcc_ext = 1;
32 /* XXX: get rid of this ASAP */
33 ST_DATA struct TCCState *tcc_state;
35 #ifdef CONFIG_TCC_BACKTRACE
36 ST_DATA int num_callers = 6;
37 ST_DATA const char **rt_bound_error_msg;
38 ST_DATA void *rt_prog_main;
39 #endif
41 /********************************************************/
43 #ifdef ONE_SOURCE
44 #include "tccpp.c"
45 #include "tccgen.c"
46 #include "tccelf.c"
47 #include "tccrun.c"
48 #ifdef TCC_TARGET_I386
49 #include "i386-gen.c"
50 #endif
51 #ifdef TCC_TARGET_ARM
52 #include "arm-gen.c"
53 #endif
54 #ifdef TCC_TARGET_C67
55 #include "c67-gen.c"
56 #endif
57 #ifdef TCC_TARGET_X86_64
58 #include "x86_64-gen.c"
59 #endif
60 #ifdef CONFIG_TCC_ASM
61 #include "tccasm.c"
62 #if defined TCC_TARGET_I386 || defined TCC_TARGET_X86_64
63 #include "i386-asm.c"
64 #endif
65 #endif
66 #ifdef TCC_TARGET_COFF
67 #include "tcccoff.c"
68 #endif
69 #ifdef TCC_TARGET_PE
70 #include "tccpe.c"
71 #endif
72 #endif /* ALL_IN_ONE */
74 /********************************************************/
75 #ifndef CONFIG_TCC_ASM
76 ST_FUNC void asm_instr(void)
78 error("inline asm() not supported");
80 ST_FUNC void asm_global_instr(void)
82 error("inline asm() not supported");
84 #endif
86 /********************************************************/
88 #ifdef _WIN32
89 static char *normalize_slashes(char *path)
91 char *p;
92 for (p = path; *p; ++p)
93 if (*p == '\\')
94 *p = '/';
95 return path;
98 static HMODULE tcc_module;
100 /* on win32, we suppose the lib and includes are at the location of 'tcc.exe' */
101 static void tcc_set_lib_path_w32(TCCState *s)
103 char path[1024], *p;
104 GetModuleFileNameA(tcc_module, path, sizeof path);
105 p = tcc_basename(normalize_slashes(strlwr(path)));
106 if (p - 5 > path && 0 == strncmp(p - 5, "/bin/", 5))
107 p -= 5;
108 else if (p > path)
109 p--;
110 *p = 0;
111 tcc_set_lib_path(s, path);
114 #ifndef CONFIG_TCC_STATIC
115 void dlclose(void *p)
117 FreeLibrary((HMODULE)p);
119 #endif
121 #ifdef LIBTCC_AS_DLL
122 BOOL WINAPI DllMain (HANDLE hDll, DWORD dwReason, LPVOID lpReserved)
124 if (DLL_PROCESS_ATTACH == dwReason)
125 tcc_module = hDll;
126 return TRUE;
128 #endif
129 #endif
131 /********************************************************/
132 /* copy a string and truncate it. */
133 PUB_FUNC char *pstrcpy(char *buf, int buf_size, const char *s)
135 char *q, *q_end;
136 int c;
138 if (buf_size > 0) {
139 q = buf;
140 q_end = buf + buf_size - 1;
141 while (q < q_end) {
142 c = *s++;
143 if (c == '\0')
144 break;
145 *q++ = c;
147 *q = '\0';
149 return buf;
152 /* strcat and truncate. */
153 PUB_FUNC char *pstrcat(char *buf, int buf_size, const char *s)
155 int len;
156 len = strlen(buf);
157 if (len < buf_size)
158 pstrcpy(buf + len, buf_size - len, s);
159 return buf;
162 /* extract the basename of a file */
163 PUB_FUNC char *tcc_basename(const char *name)
165 char *p = strchr(name, 0);
166 while (p > name && !IS_PATHSEP(p[-1]))
167 --p;
168 return p;
171 /* extract extension part of a file
173 * (if no extension, return pointer to end-of-string)
175 PUB_FUNC char *tcc_fileextension (const char *name)
177 char *b = tcc_basename(name);
178 char *e = strrchr(b, '.');
179 return e ? e : strchr(b, 0);
182 /********************************************************/
183 /* memory management */
185 #undef free
186 #undef malloc
187 #undef realloc
189 #ifdef MEM_DEBUG
190 int mem_cur_size;
191 int mem_max_size;
192 unsigned malloc_usable_size(void*);
193 #endif
195 PUB_FUNC void tcc_free(void *ptr)
197 #ifdef MEM_DEBUG
198 mem_cur_size -= malloc_usable_size(ptr);
199 #endif
200 free(ptr);
203 PUB_FUNC void *tcc_malloc(unsigned long size)
205 void *ptr;
206 ptr = malloc(size);
207 if (!ptr && size)
208 error("memory full");
209 #ifdef MEM_DEBUG
210 mem_cur_size += malloc_usable_size(ptr);
211 if (mem_cur_size > mem_max_size)
212 mem_max_size = mem_cur_size;
213 #endif
214 return ptr;
217 PUB_FUNC void *tcc_mallocz(unsigned long size)
219 void *ptr;
220 ptr = tcc_malloc(size);
221 memset(ptr, 0, size);
222 return ptr;
225 PUB_FUNC void *tcc_realloc(void *ptr, unsigned long size)
227 void *ptr1;
228 #ifdef MEM_DEBUG
229 mem_cur_size -= malloc_usable_size(ptr);
230 #endif
231 ptr1 = realloc(ptr, size);
232 #ifdef MEM_DEBUG
233 /* NOTE: count not correct if alloc error, but not critical */
234 mem_cur_size += malloc_usable_size(ptr1);
235 if (mem_cur_size > mem_max_size)
236 mem_max_size = mem_cur_size;
237 #endif
238 return ptr1;
241 PUB_FUNC char *tcc_strdup(const char *str)
243 char *ptr;
244 ptr = tcc_malloc(strlen(str) + 1);
245 strcpy(ptr, str);
246 return ptr;
249 PUB_FUNC void tcc_memstats(void)
251 #ifdef MEM_DEBUG
252 printf("memory in use: %d\n", mem_cur_size);
253 #endif
256 #define free(p) use_tcc_free(p)
257 #define malloc(s) use_tcc_malloc(s)
258 #define realloc(p, s) use_tcc_realloc(p, s)
260 /********************************************************/
261 /* dynarrays */
263 PUB_FUNC void dynarray_add(void ***ptab, int *nb_ptr, void *data)
265 int nb, nb_alloc;
266 void **pp;
268 nb = *nb_ptr;
269 pp = *ptab;
270 /* every power of two we double array size */
271 if ((nb & (nb - 1)) == 0) {
272 if (!nb)
273 nb_alloc = 1;
274 else
275 nb_alloc = nb * 2;
276 pp = tcc_realloc(pp, nb_alloc * sizeof(void *));
277 if (!pp)
278 error("memory full");
279 *ptab = pp;
281 pp[nb++] = data;
282 *nb_ptr = nb;
285 PUB_FUNC void dynarray_reset(void *pp, int *n)
287 void **p;
288 for (p = *(void***)pp; *n; ++p, --*n)
289 if (*p)
290 tcc_free(*p);
291 tcc_free(*(void**)pp);
292 *(void**)pp = NULL;
295 /* out must not point to a valid dynarray since a new one is created */
296 PUB_FUNC int tcc_split_path(const char *in, const char * const *prefixs,
297 int nb_prefixs, char ***out)
299 int i, nb_comps = 0;
300 char *path;
301 const char *end;
302 size_t size;
304 *out = NULL;
305 do {
306 end = in;
307 while (*end && *end != ':')
308 ++end;
309 for (i = 0; i < nb_prefixs; i++) {
310 size = (strlen(prefixs[i]) + 1) * sizeof(char)
311 + (end - in);
312 path = tcc_malloc(size);
313 pstrcpy(path, size, prefixs[i]);
314 pstrcat(path, size, in);
315 dynarray_add((void ***) out, &nb_comps, path);
317 in = end + 1;
318 } while (*end);
319 return nb_comps;
322 /* we use our own 'finite' function to avoid potential problems with
323 non standard math libs */
324 /* XXX: endianness dependent */
325 ST_FUNC int ieee_finite(double d)
327 int *p = (int *)&d;
328 return ((unsigned)((p[1] | 0x800fffff) + 1)) >> 31;
331 /********************************************************/
333 ST_FUNC Section *new_section(TCCState *s1, const char *name, int sh_type, int sh_flags)
335 Section *sec;
337 sec = tcc_mallocz(sizeof(Section) + strlen(name));
338 strcpy(sec->name, name);
339 sec->sh_type = sh_type;
340 sec->sh_flags = sh_flags;
341 switch(sh_type) {
342 case SHT_HASH:
343 case SHT_REL:
344 case SHT_RELA:
345 case SHT_DYNSYM:
346 case SHT_SYMTAB:
347 case SHT_DYNAMIC:
348 sec->sh_addralign = 4;
349 break;
350 case SHT_STRTAB:
351 sec->sh_addralign = 1;
352 break;
353 default:
354 sec->sh_addralign = 32; /* default conservative alignment */
355 break;
358 if (sh_flags & SHF_PRIVATE) {
359 dynarray_add((void ***)&s1->priv_sections, &s1->nb_priv_sections, sec);
360 } else {
361 sec->sh_num = s1->nb_sections;
362 dynarray_add((void ***)&s1->sections, &s1->nb_sections, sec);
365 return sec;
368 static void free_section(Section *s)
370 tcc_free(s->data);
373 /* realloc section and set its content to zero */
374 ST_FUNC void section_realloc(Section *sec, unsigned long new_size)
376 unsigned long size;
377 unsigned char *data;
379 size = sec->data_allocated;
380 if (size == 0)
381 size = 1;
382 while (size < new_size)
383 size = size * 2;
384 data = tcc_realloc(sec->data, size);
385 if (!data)
386 error("memory full");
387 memset(data + sec->data_allocated, 0, size - sec->data_allocated);
388 sec->data = data;
389 sec->data_allocated = size;
392 /* reserve at least 'size' bytes in section 'sec' from
393 sec->data_offset. */
394 ST_FUNC void *section_ptr_add(Section *sec, unsigned long size)
396 unsigned long offset, offset1;
398 offset = sec->data_offset;
399 offset1 = offset + size;
400 if (offset1 > sec->data_allocated)
401 section_realloc(sec, offset1);
402 sec->data_offset = offset1;
403 return sec->data + offset;
406 /* reserve at least 'size' bytes from section start */
407 ST_FUNC void section_reserve(Section *sec, unsigned long size)
409 if (size > sec->data_allocated)
410 section_realloc(sec, size);
411 if (size > sec->data_offset)
412 sec->data_offset = size;
415 /* return a reference to a section, and create it if it does not
416 exists */
417 ST_FUNC Section *find_section(TCCState *s1, const char *name)
419 Section *sec;
420 int i;
421 for(i = 1; i < s1->nb_sections; i++) {
422 sec = s1->sections[i];
423 if (!strcmp(name, sec->name))
424 return sec;
426 /* sections are created as PROGBITS */
427 return new_section(s1, name, SHT_PROGBITS, SHF_ALLOC);
430 /* update sym->c so that it points to an external symbol in section
431 'section' with value 'value' */
432 ST_FUNC void put_extern_sym2(Sym *sym, Section *section,
433 unsigned long value, unsigned long size,
434 int can_add_underscore)
436 int sym_type, sym_bind, sh_num, info, other;
437 ElfW(Sym) *esym;
438 const char *name;
439 char buf1[256];
441 if (section == NULL)
442 sh_num = SHN_UNDEF;
443 else if (section == SECTION_ABS)
444 sh_num = SHN_ABS;
445 else
446 sh_num = section->sh_num;
448 if ((sym->type.t & VT_BTYPE) == VT_FUNC) {
449 sym_type = STT_FUNC;
450 } else if ((sym->type.t & VT_BTYPE) == VT_VOID) {
451 sym_type = STT_NOTYPE;
452 } else {
453 sym_type = STT_OBJECT;
456 if (sym->type.t & VT_STATIC)
457 sym_bind = STB_LOCAL;
458 else {
459 if (sym->type.t & VT_WEAK)
460 sym_bind = STB_WEAK;
461 else
462 sym_bind = STB_GLOBAL;
465 if (!sym->c) {
466 name = get_tok_str(sym->v, NULL);
467 #ifdef CONFIG_TCC_BCHECK
468 if (tcc_state->do_bounds_check) {
469 char buf[32];
471 /* XXX: avoid doing that for statics ? */
472 /* if bound checking is activated, we change some function
473 names by adding the "__bound" prefix */
474 switch(sym->v) {
475 #ifdef TCC_TARGET_PE
476 /* XXX: we rely only on malloc hooks */
477 case TOK_malloc:
478 case TOK_free:
479 case TOK_realloc:
480 case TOK_memalign:
481 case TOK_calloc:
482 #endif
483 case TOK_memcpy:
484 case TOK_memmove:
485 case TOK_memset:
486 case TOK_strlen:
487 case TOK_strcpy:
488 case TOK_alloca:
489 strcpy(buf, "__bound_");
490 strcat(buf, name);
491 name = buf;
492 break;
495 #endif
496 other = 0;
498 #ifdef TCC_TARGET_PE
499 if (sym->type.t & VT_EXPORT)
500 other |= 1;
501 if (sym_type == STT_FUNC && sym->type.ref) {
502 int attr = sym->type.ref->r;
503 if (FUNC_EXPORT(attr))
504 other |= 1;
505 if (FUNC_CALL(attr) == FUNC_STDCALL && can_add_underscore) {
506 sprintf(buf1, "_%s@%d", name, FUNC_ARGS(attr) * PTR_SIZE);
507 name = buf1;
508 other |= 2;
509 can_add_underscore = 0;
511 } else {
512 if (find_elf_sym(tcc_state->dynsymtab_section, name))
513 other |= 4;
514 if (sym->type.t & VT_IMPORT)
515 other |= 4;
517 #endif
518 if (tcc_state->leading_underscore && can_add_underscore) {
519 buf1[0] = '_';
520 pstrcpy(buf1 + 1, sizeof(buf1) - 1, name);
521 name = buf1;
523 if (sym->asm_label) {
524 name = sym->asm_label;
526 info = ELFW(ST_INFO)(sym_bind, sym_type);
527 sym->c = add_elf_sym(symtab_section, value, size, info, other, sh_num, name);
528 } else {
529 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
530 esym->st_value = value;
531 esym->st_size = size;
532 esym->st_shndx = sh_num;
536 ST_FUNC void put_extern_sym(Sym *sym, Section *section,
537 unsigned long value, unsigned long size)
539 put_extern_sym2(sym, section, value, size, 1);
542 /* add a new relocation entry to symbol 'sym' in section 's' */
543 ST_FUNC void greloc(Section *s, Sym *sym, unsigned long offset, int type)
545 int c = 0;
546 if (sym) {
547 if (0 == sym->c)
548 put_extern_sym(sym, NULL, 0, 0);
549 c = sym->c;
551 /* now we can add ELF relocation info */
552 put_elf_reloc(symtab_section, s, offset, type, c);
555 /********************************************************/
557 static void strcat_vprintf(char *buf, int buf_size, const char *fmt, va_list ap)
559 int len;
560 len = strlen(buf);
561 vsnprintf(buf + len, buf_size - len, fmt, ap);
564 static void strcat_printf(char *buf, int buf_size, const char *fmt, ...)
566 va_list ap;
567 va_start(ap, fmt);
568 strcat_vprintf(buf, buf_size, fmt, ap);
569 va_end(ap);
572 static void error1(TCCState *s1, int is_warning, const char *fmt, va_list ap)
574 char buf[2048];
575 BufferedFile **f;
577 buf[0] = '\0';
578 if (file) {
579 for(f = s1->include_stack; f < s1->include_stack_ptr; f++)
580 strcat_printf(buf, sizeof(buf), "In file included from %s:%d:\n",
581 (*f)->filename, (*f)->line_num);
582 if (file->line_num > 0) {
583 strcat_printf(buf, sizeof(buf),
584 "%s:%d: ", file->filename, file->line_num);
585 } else {
586 strcat_printf(buf, sizeof(buf),
587 "%s: ", file->filename);
589 } else {
590 strcat_printf(buf, sizeof(buf),
591 "tcc: ");
593 if (is_warning)
594 strcat_printf(buf, sizeof(buf), "warning: ");
595 else
596 strcat_printf(buf, sizeof(buf), "error: ");
597 strcat_vprintf(buf, sizeof(buf), fmt, ap);
599 if (!s1->error_func) {
600 /* default case: stderr */
601 fprintf(stderr, "%s\n", buf);
602 } else {
603 s1->error_func(s1->error_opaque, buf);
605 if (!is_warning || s1->warn_error)
606 s1->nb_errors++;
609 LIBTCCAPI void tcc_set_error_func(TCCState *s, void *error_opaque,
610 void (*error_func)(void *opaque, const char *msg))
612 s->error_opaque = error_opaque;
613 s->error_func = error_func;
616 /* error without aborting current compilation */
617 PUB_FUNC void error_noabort(const char *fmt, ...)
619 TCCState *s1 = tcc_state;
620 va_list ap;
622 va_start(ap, fmt);
623 error1(s1, 0, fmt, ap);
624 va_end(ap);
627 PUB_FUNC void error(const char *fmt, ...)
629 TCCState *s1 = tcc_state;
630 va_list ap;
632 va_start(ap, fmt);
633 error1(s1, 0, fmt, ap);
634 va_end(ap);
635 /* better than nothing: in some cases, we accept to handle errors */
636 if (s1->error_set_jmp_enabled) {
637 longjmp(s1->error_jmp_buf, 1);
638 } else {
639 /* XXX: eliminate this someday */
640 exit(1);
644 PUB_FUNC void expect(const char *msg)
646 error("%s expected", msg);
649 PUB_FUNC void warning(const char *fmt, ...)
651 TCCState *s1 = tcc_state;
652 va_list ap;
654 if (s1->warn_none)
655 return;
657 va_start(ap, fmt);
658 error1(s1, 1, fmt, ap);
659 va_end(ap);
662 /********************************************************/
663 /* I/O layer */
665 ST_FUNC void tcc_open_bf(TCCState *s1, const char *filename, int initlen)
667 BufferedFile *bf;
668 int buflen = initlen ? initlen : IO_BUF_SIZE;
670 bf = tcc_malloc(sizeof(BufferedFile) + buflen);
671 bf->buf_ptr = bf->buffer;
672 bf->buf_end = bf->buffer + initlen;
673 bf->buf_end[0] = CH_EOB; /* put eob symbol */
674 pstrcpy(bf->filename, sizeof(bf->filename), filename);
675 #ifdef _WIN32
676 normalize_slashes(bf->filename);
677 #endif
678 bf->line_num = 1;
679 bf->ifndef_macro = 0;
680 bf->ifdef_stack_ptr = s1->ifdef_stack_ptr;
681 bf->fd = -1;
682 bf->prev = file;
683 file = bf;
686 ST_FUNC void tcc_close(void)
688 BufferedFile *bf = file;
689 if (bf->fd > 0) {
690 close(bf->fd);
691 total_lines += bf->line_num;
693 file = bf->prev;
694 tcc_free(bf);
697 ST_FUNC int tcc_open(TCCState *s1, const char *filename)
699 int fd;
700 if (strcmp(filename, "-") == 0)
701 fd = 0, filename = "stdin";
702 else
703 fd = open(filename, O_RDONLY | O_BINARY);
704 if ((s1->verbose == 2 && fd >= 0) || s1->verbose == 3)
705 printf("%s %*s%s\n", fd < 0 ? "nf":"->",
706 (int)(s1->include_stack_ptr - s1->include_stack), "", filename);
707 if (fd < 0)
708 return -1;
710 tcc_open_bf(s1, filename, 0);
711 file->fd = fd;
712 return fd;
715 /* compile the C file opened in 'file'. Return non zero if errors. */
716 static int tcc_compile(TCCState *s1)
718 Sym *define_start;
719 SValue *pvtop;
720 char buf[512];
721 volatile int section_sym;
723 #ifdef INC_DEBUG
724 printf("%s: **** new file\n", file->filename);
725 #endif
726 preprocess_init(s1);
728 cur_text_section = NULL;
729 funcname = "";
730 anon_sym = SYM_FIRST_ANOM;
732 /* file info: full path + filename */
733 section_sym = 0; /* avoid warning */
734 if (s1->do_debug) {
735 section_sym = put_elf_sym(symtab_section, 0, 0,
736 ELFW(ST_INFO)(STB_LOCAL, STT_SECTION), 0,
737 text_section->sh_num, NULL);
738 getcwd(buf, sizeof(buf));
739 #ifdef _WIN32
740 normalize_slashes(buf);
741 #endif
742 pstrcat(buf, sizeof(buf), "/");
743 put_stabs_r(buf, N_SO, 0, 0,
744 text_section->data_offset, text_section, section_sym);
745 put_stabs_r(file->filename, N_SO, 0, 0,
746 text_section->data_offset, text_section, section_sym);
748 /* an elf symbol of type STT_FILE must be put so that STB_LOCAL
749 symbols can be safely used */
750 put_elf_sym(symtab_section, 0, 0,
751 ELFW(ST_INFO)(STB_LOCAL, STT_FILE), 0,
752 SHN_ABS, file->filename);
754 /* define some often used types */
755 int_type.t = VT_INT;
757 char_pointer_type.t = VT_BYTE;
758 mk_pointer(&char_pointer_type);
760 func_old_type.t = VT_FUNC;
761 func_old_type.ref = sym_push(SYM_FIELD, &int_type, FUNC_CDECL, FUNC_OLD);
763 #if defined(TCC_ARM_EABI) && defined(TCC_ARM_VFP)
764 float_type.t = VT_FLOAT;
765 double_type.t = VT_DOUBLE;
767 func_float_type.t = VT_FUNC;
768 func_float_type.ref = sym_push(SYM_FIELD, &float_type, FUNC_CDECL, FUNC_OLD);
769 func_double_type.t = VT_FUNC;
770 func_double_type.ref = sym_push(SYM_FIELD, &double_type, FUNC_CDECL, FUNC_OLD);
771 #endif
773 #if 0
774 /* define 'void *alloca(unsigned int)' builtin function */
776 Sym *s1;
778 p = anon_sym++;
779 sym = sym_push(p, mk_pointer(VT_VOID), FUNC_CDECL, FUNC_NEW);
780 s1 = sym_push(SYM_FIELD, VT_UNSIGNED | VT_INT, 0, 0);
781 s1->next = NULL;
782 sym->next = s1;
783 sym_push(TOK_alloca, VT_FUNC | (p << VT_STRUCT_SHIFT), VT_CONST, 0);
785 #endif
787 define_start = define_stack;
788 nocode_wanted = 1;
790 if (setjmp(s1->error_jmp_buf) == 0) {
791 s1->nb_errors = 0;
792 s1->error_set_jmp_enabled = 1;
794 ch = file->buf_ptr[0];
795 tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
796 parse_flags = PARSE_FLAG_PREPROCESS | PARSE_FLAG_TOK_NUM;
797 pvtop = vtop;
798 next();
799 decl(VT_CONST);
800 if (tok != TOK_EOF)
801 expect("declaration");
802 if (pvtop != vtop)
803 warning("internal compiler error: vstack leak? (%d)", vtop - pvtop);
805 /* end of translation unit info */
806 if (s1->do_debug) {
807 put_stabs_r(NULL, N_SO, 0, 0,
808 text_section->data_offset, text_section, section_sym);
812 s1->error_set_jmp_enabled = 0;
814 /* reset define stack, but leave -Dsymbols (may be incorrect if
815 they are undefined) */
816 free_defines(define_start);
818 gen_inline_functions();
820 sym_pop(&global_stack, NULL);
821 sym_pop(&local_stack, NULL);
823 return s1->nb_errors != 0 ? -1 : 0;
826 LIBTCCAPI int tcc_compile_string(TCCState *s, const char *str)
828 int len, ret;
829 len = strlen(str);
831 tcc_open_bf(s, "<string>", len);
832 memcpy(file->buffer, str, len);
833 ret = tcc_compile(s);
834 tcc_close();
835 return ret;
838 /* define a preprocessor symbol. A value can also be provided with the '=' operator */
839 LIBTCCAPI void tcc_define_symbol(TCCState *s1, const char *sym, const char *value)
841 int len1, len2;
842 /* default value */
843 if (!value)
844 value = "1";
845 len1 = strlen(sym);
846 len2 = strlen(value);
848 /* init file structure */
849 tcc_open_bf(s1, "<define>", len1 + len2 + 1);
850 memcpy(file->buffer, sym, len1);
851 file->buffer[len1] = ' ';
852 memcpy(file->buffer + len1 + 1, value, len2);
854 /* parse with define parser */
855 ch = file->buf_ptr[0];
856 next_nomacro();
857 parse_define();
859 tcc_close();
862 /* undefine a preprocessor symbol */
863 LIBTCCAPI void tcc_undefine_symbol(TCCState *s1, const char *sym)
865 TokenSym *ts;
866 Sym *s;
867 ts = tok_alloc(sym, strlen(sym));
868 s = define_find(ts->tok);
869 /* undefine symbol by putting an invalid name */
870 if (s)
871 define_undef(s);
874 static void tcc_cleanup(void)
876 int i, n;
878 if (NULL == tcc_state)
879 return;
880 tcc_state = NULL;
882 /* free -D defines */
883 free_defines(NULL);
885 /* free tokens */
886 n = tok_ident - TOK_IDENT;
887 for(i = 0; i < n; i++)
888 tcc_free(table_ident[i]);
889 tcc_free(table_ident);
891 /* free sym_pools */
892 dynarray_reset(&sym_pools, &nb_sym_pools);
893 /* string buffer */
894 cstr_free(&tokcstr);
895 /* reset symbol stack */
896 sym_free_first = NULL;
897 /* cleanup from error/setjmp */
898 macro_ptr = NULL;
901 LIBTCCAPI TCCState *tcc_new(void)
903 TCCState *s;
904 char buffer[100];
905 int a,b,c;
907 tcc_cleanup();
909 s = tcc_mallocz(sizeof(TCCState));
910 if (!s)
911 return NULL;
912 tcc_state = s;
913 #ifdef _WIN32
914 tcc_set_lib_path_w32(s);
915 #else
916 tcc_set_lib_path(s, CONFIG_TCCDIR);
917 #endif
918 s->output_type = TCC_OUTPUT_MEMORY;
919 preprocess_new();
920 s->include_stack_ptr = s->include_stack;
922 /* we add dummy defines for some special macros to speed up tests
923 and to have working defined() */
924 define_push(TOK___LINE__, MACRO_OBJ, NULL, NULL);
925 define_push(TOK___FILE__, MACRO_OBJ, NULL, NULL);
926 define_push(TOK___DATE__, MACRO_OBJ, NULL, NULL);
927 define_push(TOK___TIME__, MACRO_OBJ, NULL, NULL);
929 /* standard defines */
930 tcc_define_symbol(s, "__STDC__", NULL);
931 tcc_define_symbol(s, "__STDC_VERSION__", "199901L");
932 #if defined(TCC_TARGET_I386)
933 tcc_define_symbol(s, "__i386__", NULL);
934 tcc_define_symbol(s, "__i386", NULL);
935 tcc_define_symbol(s, "i386", NULL);
936 #endif
937 #if defined(TCC_TARGET_X86_64)
938 tcc_define_symbol(s, "__x86_64__", NULL);
939 #endif
940 #if defined(TCC_TARGET_ARM)
941 tcc_define_symbol(s, "__ARM_ARCH_4__", NULL);
942 tcc_define_symbol(s, "__arm_elf__", NULL);
943 tcc_define_symbol(s, "__arm_elf", NULL);
944 tcc_define_symbol(s, "arm_elf", NULL);
945 tcc_define_symbol(s, "__arm__", NULL);
946 tcc_define_symbol(s, "__arm", NULL);
947 tcc_define_symbol(s, "arm", NULL);
948 tcc_define_symbol(s, "__APCS_32__", NULL);
949 #endif
950 #ifdef TCC_TARGET_PE
951 tcc_define_symbol(s, "_WIN32", NULL);
952 #ifdef TCC_TARGET_X86_64
953 tcc_define_symbol(s, "_WIN64", NULL);
954 #endif
955 #else
956 tcc_define_symbol(s, "__unix__", NULL);
957 tcc_define_symbol(s, "__unix", NULL);
958 tcc_define_symbol(s, "unix", NULL);
959 #if defined(__FreeBSD__)
960 #define str(s) #s
961 tcc_define_symbol(s, "__FreeBSD__", str( __FreeBSD__));
962 #undef str
963 #endif
964 #if defined(__FreeBSD_kernel__)
965 tcc_define_symbol(s, "__FreeBSD_kernel__", NULL);
966 #endif
967 #if defined(__linux)
968 tcc_define_symbol(s, "__linux__", NULL);
969 tcc_define_symbol(s, "__linux", NULL);
970 #endif
971 #endif
972 /* tiny C specific defines */
973 sscanf(TCC_VERSION, "%d.%d.%d", &a, &b, &c);
974 sprintf(buffer, "%d", a*10000 + b*100 + c);
975 tcc_define_symbol(s, "__TINYC__", buffer);
977 /* tiny C & gcc defines */
978 #if defined TCC_TARGET_PE && defined TCC_TARGET_X86_64
979 tcc_define_symbol(s, "__SIZE_TYPE__", "unsigned long long");
980 tcc_define_symbol(s, "__PTRDIFF_TYPE__", "long long");
981 #else
982 tcc_define_symbol(s, "__SIZE_TYPE__", "unsigned long");
983 tcc_define_symbol(s, "__PTRDIFF_TYPE__", "long");
984 #endif
986 #ifdef TCC_TARGET_PE
987 tcc_define_symbol(s, "__WCHAR_TYPE__", "unsigned short");
988 #else
989 tcc_define_symbol(s, "__WCHAR_TYPE__", "int");
990 #endif
992 /* glibc defines */
993 tcc_define_symbol(s, "__REDIRECT_NTH(name, proto, alias)", "name proto __asm__ (#alias) __THROW");
995 #ifndef TCC_TARGET_PE
996 /* default library paths */
997 tcc_add_library_path(s, CONFIG_TCC_CRT_PREFIX);
998 tcc_add_library_path(s, CONFIG_SYSROOT CONFIG_TCC_LDDIR);
999 tcc_add_library_path(s, CONFIG_SYSROOT "/usr/local"CONFIG_TCC_LDDIR);
1000 #ifdef CONFIG_TCC_EXTRA_LDDIR
1002 int i, nb_extra_lddirs, nb_prefixs;
1003 char **extra_lddirs;
1004 char extra_lddir_str[] = CONFIG_TCC_EXTRA_LDDIR;
1005 const char lddir_prefix1[] = CONFIG_SYSROOT;
1006 const char lddir_prefix2[] = CONFIG_SYSROOT "/usr/local";
1007 const char * const lddir_prefixs[] = {lddir_prefix1, lddir_prefix2};
1009 nb_prefixs = sizeof lddir_prefixs / sizeof *lddir_prefixs;
1010 nb_extra_lddirs = tcc_split_path(CONFIG_TCC_EXTRA_LDDIR,
1011 lddir_prefixs, nb_prefixs,
1012 &extra_lddirs);
1013 for (i = 0; i < nb_extra_lddirs; i++)
1014 tcc_add_library_path(s, extra_lddirs[i]);
1015 dynarray_reset(&extra_lddirs, &nb_extra_lddirs);
1017 #endif
1018 #endif
1020 /* no section zero */
1021 dynarray_add((void ***)&s->sections, &s->nb_sections, NULL);
1023 /* create standard sections */
1024 text_section = new_section(s, ".text", SHT_PROGBITS, SHF_ALLOC | SHF_EXECINSTR);
1025 data_section = new_section(s, ".data", SHT_PROGBITS, SHF_ALLOC | SHF_WRITE);
1026 bss_section = new_section(s, ".bss", SHT_NOBITS, SHF_ALLOC | SHF_WRITE);
1028 /* symbols are always generated for linking stage */
1029 symtab_section = new_symtab(s, ".symtab", SHT_SYMTAB, 0,
1030 ".strtab",
1031 ".hashtab", SHF_PRIVATE);
1032 strtab_section = symtab_section->link;
1034 /* private symbol table for dynamic symbols */
1035 s->dynsymtab_section = new_symtab(s, ".dynsymtab", SHT_SYMTAB, SHF_PRIVATE,
1036 ".dynstrtab",
1037 ".dynhashtab", SHF_PRIVATE);
1038 s->alacarte_link = 1;
1039 s->nocommon = 1;
1041 #ifdef CHAR_IS_UNSIGNED
1042 s->char_is_unsigned = 1;
1043 #endif
1044 /* enable this if you want symbols with leading underscore on windows: */
1045 #if defined(TCC_TARGET_PE) && 0
1046 s->leading_underscore = 1;
1047 #endif
1048 if (s->section_align == 0)
1049 s->section_align = ELF_PAGE_SIZE;
1050 #ifdef TCC_TARGET_I386
1051 s->seg_size = 32;
1052 #endif
1053 return s;
1056 LIBTCCAPI void tcc_delete(TCCState *s1)
1058 int i;
1060 tcc_cleanup();
1062 /* free all sections */
1063 for(i = 1; i < s1->nb_sections; i++)
1064 free_section(s1->sections[i]);
1065 dynarray_reset(&s1->sections, &s1->nb_sections);
1067 for(i = 0; i < s1->nb_priv_sections; i++)
1068 free_section(s1->priv_sections[i]);
1069 dynarray_reset(&s1->priv_sections, &s1->nb_priv_sections);
1071 /* free any loaded DLLs */
1072 for ( i = 0; i < s1->nb_loaded_dlls; i++) {
1073 DLLReference *ref = s1->loaded_dlls[i];
1074 if ( ref->handle )
1075 dlclose(ref->handle);
1078 /* free loaded dlls array */
1079 dynarray_reset(&s1->loaded_dlls, &s1->nb_loaded_dlls);
1081 /* free library paths */
1082 dynarray_reset(&s1->library_paths, &s1->nb_library_paths);
1084 /* free include paths */
1085 dynarray_reset(&s1->cached_includes, &s1->nb_cached_includes);
1086 dynarray_reset(&s1->include_paths, &s1->nb_include_paths);
1087 dynarray_reset(&s1->sysinclude_paths, &s1->nb_sysinclude_paths);
1089 tcc_free(s1->tcc_lib_path);
1091 dynarray_reset(&s1->input_files, &s1->nb_input_files);
1092 dynarray_reset(&s1->input_libs, &s1->nb_input_libs);
1093 dynarray_reset(&s1->target_deps, &s1->nb_target_deps);
1095 #ifdef HAVE_SELINUX
1096 munmap (s1->write_mem, s1->mem_size);
1097 munmap (s1->runtime_mem, s1->mem_size);
1098 #else
1099 tcc_free(s1->runtime_mem);
1100 #endif
1101 tcc_free(s1);
1104 LIBTCCAPI int tcc_add_include_path(TCCState *s1, const char *pathname)
1106 char *pathname1;
1108 pathname1 = tcc_strdup(pathname);
1109 dynarray_add((void ***)&s1->include_paths, &s1->nb_include_paths, pathname1);
1110 return 0;
1113 LIBTCCAPI int tcc_add_sysinclude_path(TCCState *s1, const char *pathname)
1115 char *pathname1;
1117 pathname1 = tcc_strdup(pathname);
1118 dynarray_add((void ***)&s1->sysinclude_paths, &s1->nb_sysinclude_paths, pathname1);
1119 return 0;
1122 ST_FUNC int tcc_add_file_internal(TCCState *s1, const char *filename, int flags)
1124 const char *ext;
1125 ElfW(Ehdr) ehdr;
1126 int fd, ret, size;
1128 /* find source file type with extension */
1129 ext = tcc_fileextension(filename);
1130 if (ext[0])
1131 ext++;
1133 #ifdef CONFIG_TCC_ASM
1134 /* if .S file, define __ASSEMBLER__ like gcc does */
1135 if (!strcmp(ext, "S"))
1136 tcc_define_symbol(s1, "__ASSEMBLER__", NULL);
1137 #endif
1139 /* open the file */
1140 ret = tcc_open(s1, filename);
1141 if (ret < 0) {
1142 if (flags & AFF_PRINT_ERROR)
1143 error_noabort("file '%s' not found", filename);
1144 return ret;
1147 /* update target deps */
1148 dynarray_add((void ***)&s1->target_deps, &s1->nb_target_deps,
1149 tcc_strdup(filename));
1151 if (flags & AFF_PREPROCESS) {
1152 ret = tcc_preprocess(s1);
1153 goto the_end;
1156 if (!ext[0] || !PATHCMP(ext, "c")) {
1157 /* C file assumed */
1158 ret = tcc_compile(s1);
1159 goto the_end;
1162 #ifdef CONFIG_TCC_ASM
1163 if (!strcmp(ext, "S")) {
1164 /* preprocessed assembler */
1165 ret = tcc_assemble(s1, 1);
1166 goto the_end;
1169 if (!strcmp(ext, "s")) {
1170 /* non preprocessed assembler */
1171 ret = tcc_assemble(s1, 0);
1172 goto the_end;
1174 #endif
1176 fd = file->fd;
1177 /* assume executable format: auto guess file type */
1178 size = read(fd, &ehdr, sizeof(ehdr));
1179 lseek(fd, 0, SEEK_SET);
1180 if (size <= 0) {
1181 error_noabort("could not read header");
1182 goto the_end;
1185 if (size == sizeof(ehdr) &&
1186 ehdr.e_ident[0] == ELFMAG0 &&
1187 ehdr.e_ident[1] == ELFMAG1 &&
1188 ehdr.e_ident[2] == ELFMAG2 &&
1189 ehdr.e_ident[3] == ELFMAG3) {
1191 /* do not display line number if error */
1192 file->line_num = 0;
1193 if (ehdr.e_type == ET_REL) {
1194 ret = tcc_load_object_file(s1, fd, 0);
1195 goto the_end;
1198 #ifndef TCC_TARGET_PE
1199 if (ehdr.e_type == ET_DYN) {
1200 if (s1->output_type == TCC_OUTPUT_MEMORY) {
1201 void *h;
1202 h = dlopen(filename, RTLD_GLOBAL | RTLD_LAZY);
1203 if (h)
1204 ret = 0;
1205 } else {
1206 ret = tcc_load_dll(s1, fd, filename,
1207 (flags & AFF_REFERENCED_DLL) != 0);
1209 goto the_end;
1211 #endif
1212 error_noabort("unrecognized ELF file");
1213 goto the_end;
1216 if (memcmp((char *)&ehdr, ARMAG, 8) == 0) {
1217 file->line_num = 0; /* do not display line number if error */
1218 ret = tcc_load_archive(s1, fd);
1219 goto the_end;
1222 #ifdef TCC_TARGET_COFF
1223 if (*(uint16_t *)(&ehdr) == COFF_C67_MAGIC) {
1224 ret = tcc_load_coff(s1, fd);
1225 goto the_end;
1227 #endif
1229 #ifdef TCC_TARGET_PE
1230 ret = pe_load_file(s1, filename, fd);
1231 #else
1232 /* as GNU ld, consider it is an ld script if not recognized */
1233 ret = tcc_load_ldscript(s1);
1234 #endif
1235 if (ret < 0)
1236 error_noabort("unrecognized file type");
1238 the_end:
1239 tcc_close();
1240 return ret;
1243 LIBTCCAPI int tcc_add_file(TCCState *s, const char *filename)
1245 dynarray_add((void ***)&s->input_files, &s->nb_input_files, tcc_strdup(filename));
1247 if (s->output_type == TCC_OUTPUT_PREPROCESS)
1248 return tcc_add_file_internal(s, filename, AFF_PRINT_ERROR | AFF_PREPROCESS);
1249 else
1250 return tcc_add_file_internal(s, filename, AFF_PRINT_ERROR);
1253 LIBTCCAPI int tcc_add_library_path(TCCState *s, const char *pathname)
1255 char *pathname1;
1257 pathname1 = tcc_strdup(pathname);
1258 dynarray_add((void ***)&s->library_paths, &s->nb_library_paths, pathname1);
1259 return 0;
1262 /* find and load a dll. Return non zero if not found */
1263 /* XXX: add '-rpath' option support ? */
1264 ST_FUNC int tcc_add_dll(TCCState *s, const char *filename, int flags)
1266 char buf[1024];
1267 int i;
1269 for(i = 0; i < s->nb_library_paths; i++) {
1270 snprintf(buf, sizeof(buf), "%s/%s",
1271 s->library_paths[i], filename);
1272 if (tcc_add_file_internal(s, buf, flags) == 0)
1273 return 0;
1275 return -1;
1278 /* the library name is the same as the argument of the '-l' option */
1279 LIBTCCAPI int tcc_add_library(TCCState *s, const char *libraryname)
1281 char buf[1024];
1282 int i;
1284 dynarray_add((void ***)&s->input_libs, &s->nb_input_libs, tcc_strdup(libraryname));
1286 /* first we look for the dynamic library if not static linking */
1287 if (!s->static_link) {
1288 #ifdef TCC_TARGET_PE
1289 if (pe_add_dll(s, libraryname) == 0)
1290 return 0;
1291 #else
1292 snprintf(buf, sizeof(buf), "lib%s.so", libraryname);
1293 if (tcc_add_dll(s, buf, 0) == 0)
1294 return 0;
1295 #endif
1297 /* then we look for the static library */
1298 for(i = 0; i < s->nb_library_paths; i++) {
1299 snprintf(buf, sizeof(buf), "%s/lib%s.a",
1300 s->library_paths[i], libraryname);
1301 if (tcc_add_file_internal(s, buf, 0) == 0)
1302 return 0;
1304 return -1;
1307 LIBTCCAPI int tcc_add_symbol(TCCState *s, const char *name, const void *val)
1309 #ifdef TCC_TARGET_PE
1310 pe_putimport(s, 0, name, val);
1311 #else
1312 add_elf_sym(symtab_section, (uplong)val, 0,
1313 ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE), 0,
1314 SHN_ABS, name);
1315 #endif
1316 return 0;
1319 LIBTCCAPI int tcc_set_output_type(TCCState *s, int output_type)
1321 char buf[1024];
1323 s->output_type = output_type;
1325 if (!s->nostdinc) {
1326 /* default include paths */
1327 /* -isystem paths have already been handled */
1328 #ifndef TCC_TARGET_PE
1330 int i, nb_extra_incdirs, nb_prefixs;
1331 char **extra_incdirs;
1332 const char incdir_prefix1[] = CONFIG_SYSROOT "/usr/local/include";
1333 const char incdir_prefix2[] = CONFIG_SYSROOT "/usr/include";
1334 const char * const incdir_prefixs[] = {incdir_prefix1,
1335 incdir_prefix2};
1337 nb_prefixs = sizeof incdir_prefixs / sizeof *incdir_prefixs;
1338 nb_extra_incdirs = tcc_split_path(CONFIG_TCC_INCSUBDIR,
1339 incdir_prefixs, nb_prefixs,
1340 &extra_incdirs);
1341 for (i = 0; i < nb_extra_incdirs; i++)
1342 tcc_add_sysinclude_path(s, extra_incdirs[i]);
1343 dynarray_reset(&extra_incdirs, &nb_extra_incdirs);
1345 #endif
1346 snprintf(buf, sizeof(buf), "%s/include", s->tcc_lib_path);
1347 tcc_add_sysinclude_path(s, buf);
1348 #ifdef TCC_TARGET_PE
1349 snprintf(buf, sizeof(buf), "%s/include/winapi", s->tcc_lib_path);
1350 tcc_add_sysinclude_path(s, buf);
1351 #endif
1354 /* if bound checking, then add corresponding sections */
1355 #ifdef CONFIG_TCC_BCHECK
1356 if (s->do_bounds_check) {
1357 /* define symbol */
1358 tcc_define_symbol(s, "__BOUNDS_CHECKING_ON", NULL);
1359 /* create bounds sections */
1360 bounds_section = new_section(s, ".bounds",
1361 SHT_PROGBITS, SHF_ALLOC);
1362 lbounds_section = new_section(s, ".lbounds",
1363 SHT_PROGBITS, SHF_ALLOC);
1365 #endif
1367 if (s->char_is_unsigned) {
1368 tcc_define_symbol(s, "__CHAR_UNSIGNED__", NULL);
1371 /* add debug sections */
1372 if (s->do_debug) {
1373 /* stab symbols */
1374 stab_section = new_section(s, ".stab", SHT_PROGBITS, 0);
1375 stab_section->sh_entsize = sizeof(Stab_Sym);
1376 stabstr_section = new_section(s, ".stabstr", SHT_STRTAB, 0);
1377 put_elf_str(stabstr_section, "");
1378 stab_section->link = stabstr_section;
1379 /* put first entry */
1380 put_stabs("", 0, 0, 0, 0);
1383 /* add libc crt1/crti objects */
1384 #ifndef TCC_TARGET_PE
1385 if ((output_type == TCC_OUTPUT_EXE || output_type == TCC_OUTPUT_DLL) &&
1386 !s->nostdlib) {
1387 if (output_type != TCC_OUTPUT_DLL)
1388 tcc_add_file(s, CONFIG_TCC_CRT_PREFIX "/crt1.o");
1389 tcc_add_file(s, CONFIG_TCC_CRT_PREFIX "/crti.o");
1391 #endif
1393 #ifdef TCC_TARGET_PE
1394 #ifdef CONFIG_TCC_CROSSLIB
1395 snprintf(buf, sizeof(buf), "%s/" CONFIG_TCC_CROSSLIB, s->tcc_lib_path);
1396 tcc_add_library_path(s, buf);
1397 #endif
1398 snprintf(buf, sizeof(buf), "%s/lib", s->tcc_lib_path);
1399 tcc_add_library_path(s, buf);
1400 #ifdef _WIN32
1401 if (GetSystemDirectory(buf, sizeof buf))
1402 tcc_add_library_path(s, buf);
1403 #endif
1404 #endif
1406 return 0;
1409 #define WD_ALL 0x0001 /* warning is activated when using -Wall */
1410 #define FD_INVERT 0x0002 /* invert value before storing */
1412 typedef struct FlagDef {
1413 uint16_t offset;
1414 uint16_t flags;
1415 const char *name;
1416 } FlagDef;
1418 static const FlagDef warning_defs[] = {
1419 { offsetof(TCCState, warn_unsupported), 0, "unsupported" },
1420 { offsetof(TCCState, warn_write_strings), 0, "write-strings" },
1421 { offsetof(TCCState, warn_error), 0, "error" },
1422 { offsetof(TCCState, warn_implicit_function_declaration), WD_ALL,
1423 "implicit-function-declaration" },
1426 ST_FUNC int set_flag(TCCState *s, const FlagDef *flags, int nb_flags,
1427 const char *name, int value)
1429 int i;
1430 const FlagDef *p;
1431 const char *r;
1433 r = name;
1434 if (r[0] == 'n' && r[1] == 'o' && r[2] == '-') {
1435 r += 3;
1436 value = !value;
1438 for(i = 0, p = flags; i < nb_flags; i++, p++) {
1439 if (!strcmp(r, p->name))
1440 goto found;
1442 return -1;
1443 found:
1444 if (p->flags & FD_INVERT)
1445 value = !value;
1446 *(int *)((uint8_t *)s + p->offset) = value;
1447 return 0;
1450 /* set/reset a warning */
1451 LIBTCCAPI int tcc_set_warning(TCCState *s, const char *warning_name, int value)
1453 int i;
1454 const FlagDef *p;
1456 if (!strcmp(warning_name, "all")) {
1457 for(i = 0, p = warning_defs; i < countof(warning_defs); i++, p++) {
1458 if (p->flags & WD_ALL)
1459 *(int *)((uint8_t *)s + p->offset) = 1;
1461 return 0;
1462 } else {
1463 return set_flag(s, warning_defs, countof(warning_defs),
1464 warning_name, value);
1468 static const FlagDef flag_defs[] = {
1469 { offsetof(TCCState, char_is_unsigned), 0, "unsigned-char" },
1470 { offsetof(TCCState, char_is_unsigned), FD_INVERT, "signed-char" },
1471 { offsetof(TCCState, nocommon), FD_INVERT, "common" },
1472 { offsetof(TCCState, leading_underscore), 0, "leading-underscore" },
1475 /* set/reset a flag */
1476 PUB_FUNC int tcc_set_flag(TCCState *s, const char *flag_name, int value)
1478 return set_flag(s, flag_defs, countof(flag_defs),
1479 flag_name, value);
1483 static int strstart(const char *str, const char *val, char **ptr)
1485 const char *p, *q;
1486 p = str;
1487 q = val;
1488 while (*q != '\0') {
1489 if (*p != *q)
1490 return 0;
1491 p++;
1492 q++;
1494 if (ptr)
1495 *ptr = (char *) p;
1496 return 1;
1500 /* Like strstart, but automatically takes into account that ld options can
1502 * - start with double or single dash (e.g. '--soname' or '-soname')
1503 * - arguments can be given as separate or after '=' (e.g. '-Wl,-soname,x.so'
1504 * or '-Wl,-soname=x.so')
1506 * you provide `val` always in 'option[=]' form (no leading -)
1508 static int link_option(const char *str, const char *val, char **ptr)
1510 const char *p, *q;
1512 /* there should be 1 or 2 dashes */
1513 if (*str++ != '-')
1514 return 0;
1515 if (*str == '-')
1516 str++;
1518 /* then str & val should match (potentialy up to '=') */
1519 p = str;
1520 q = val;
1522 while (*q != '\0' && *q != '=') {
1523 if (*p != *q)
1524 return 0;
1525 p++;
1526 q++;
1529 /* '=' near eos means ',' or '=' is ok */
1530 if (*q == '=') {
1531 if (*p != ',' && *p != '=')
1532 return 0;
1533 p++;
1534 q++;
1537 if (ptr)
1538 *ptr = (char *) p;
1539 return 1;
1543 /* set linker options */
1544 PUB_FUNC const char * tcc_set_linker(TCCState *s, char *option, int multi)
1546 char *p = option;
1547 char *end;
1549 while (option && *option) {
1550 end = NULL;
1551 if (link_option(option, "Bsymbolic", &p)) {
1552 s->symbolic = TRUE;
1553 } else if (link_option(option, "fini=", &p)) {
1554 s->fini_symbol = p;
1555 if (s->warn_unsupported)
1556 warning("ignoring -fini %s", p);
1557 } else if (link_option(option, "image-base=", &p)) {
1558 s->text_addr = strtoul(p, &end, 16);
1559 s->has_text_addr = 1;
1560 } else if (link_option(option, "init=", &p)) {
1561 s->init_symbol = p;
1562 if (s->warn_unsupported)
1563 warning("ignoring -init %s", p);
1564 } else if (link_option(option, "oformat=", &p)) {
1565 #if defined(TCC_TARGET_PE)
1566 if (strstart(p, "pe-", NULL)) {
1567 #else
1568 #if defined(TCC_TARGET_X86_64)
1569 if (strstart(p, "elf64-", NULL)) {
1570 #else
1571 if (strstart(p, "elf32-", NULL)) {
1572 #endif
1573 #endif
1574 s->output_format = TCC_OUTPUT_FORMAT_ELF;
1575 } else if (!strcmp(p, "binary")) {
1576 s->output_format = TCC_OUTPUT_FORMAT_BINARY;
1577 } else
1578 #ifdef TCC_TARGET_COFF
1579 if (!strcmp(p, "coff")) {
1580 s->output_format = TCC_OUTPUT_FORMAT_COFF;
1581 } else
1582 #endif
1584 return p;
1587 } else if (link_option(option, "rpath=", &p)) {
1588 s->rpath = p;
1589 } else if (link_option(option, "section-alignment=", &p)) {
1590 s->section_align = strtoul(p, &end, 16);
1591 } else if (link_option(option, "soname=", &p)) {
1592 s->soname = p;
1593 multi = 0;
1594 #ifdef TCC_TARGET_PE
1595 } else if (link_option(option, "file-alignment=", &p)) {
1596 s->pe_file_align = strtoul(p, &end, 16);
1597 } else if (link_option(option, "stack=", &p)) {
1598 s->pe_stack_size = strtoul(p, &end, 10);
1599 } else if (link_option(option, "subsystem=", &p)) {
1600 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
1601 if (!strcmp(p, "native")) {
1602 s->pe_subsystem = 1;
1603 } else if (!strcmp(p, "console")) {
1604 s->pe_subsystem = 3;
1605 } else if (!strcmp(p, "gui")) {
1606 s->pe_subsystem = 2;
1607 } else if (!strcmp(p, "posix")) {
1608 s->pe_subsystem = 7;
1609 } else if (!strcmp(p, "efiapp")) {
1610 s->pe_subsystem = 10;
1611 } else if (!strcmp(p, "efiboot")) {
1612 s->pe_subsystem = 11;
1613 } else if (!strcmp(p, "efiruntime")) {
1614 s->pe_subsystem = 12;
1615 } else if (!strcmp(p, "efirom")) {
1616 s->pe_subsystem = 13;
1617 #elif defined(TCC_TARGET_ARM)
1618 if (!strcmp(p, "wince")) {
1619 s->pe_subsystem = 9;
1620 #endif
1621 } else {
1622 return p;
1624 #endif
1626 } else if (link_option(option, "Ttext=", &p)) {
1627 s->text_addr = strtoul(p, &end, 16);
1628 s->has_text_addr = 1;
1630 } else {
1631 return option;
1634 if (multi) {
1635 option = NULL;
1636 p = strchr( (end) ? end : p, ',');
1637 if (p) {
1638 *p = 0; /* terminate last option */
1639 option = ++p;
1641 } else
1642 option = NULL;
1644 return NULL;
1647 PUB_FUNC void tcc_print_stats(TCCState *s, int64_t total_time)
1649 double tt;
1650 tt = (double)total_time / 1000000.0;
1651 if (tt < 0.001)
1652 tt = 0.001;
1653 if (total_bytes < 1)
1654 total_bytes = 1;
1655 printf("%d idents, %d lines, %d bytes, %0.3f s, %d lines/s, %0.1f MB/s\n",
1656 tok_ident - TOK_IDENT, total_lines, total_bytes,
1657 tt, (int)(total_lines / tt),
1658 total_bytes / tt / 1000000.0);
1661 /* set CONFIG_TCCDIR at runtime */
1662 LIBTCCAPI void tcc_set_lib_path(TCCState *s, const char *path)
1664 tcc_free(s->tcc_lib_path);
1665 s->tcc_lib_path = tcc_strdup(path);
1668 PUB_FUNC void set_num_callers(int n)
1670 #ifdef CONFIG_TCC_BACKTRACE
1671 num_callers = n;
1672 #endif
1676 LIBTCCAPI const char *tcc_default_target(TCCState *s)
1678 /* FIXME will break in multithreaded case */
1679 static char outfile_default[1024];
1681 char *ext;
1682 const char *name =
1683 strcmp(s->input_files[0], "-") == 0 ? "a"
1684 : tcc_basename(s->input_files[0]);
1685 pstrcpy(outfile_default, sizeof(outfile_default), name);
1686 ext = tcc_fileextension(outfile_default);
1687 #ifdef TCC_TARGET_PE
1688 if (s->output_type == TCC_OUTPUT_DLL)
1689 strcpy(ext, ".dll");
1690 else
1691 if (s->output_type == TCC_OUTPUT_EXE)
1692 strcpy(ext, ".exe");
1693 else
1694 #endif
1695 if (( (s->output_type == TCC_OUTPUT_OBJ && !s->reloc_output) ||
1696 (s->output_type == TCC_OUTPUT_PREPROCESS) )
1697 && *ext)
1698 strcpy(ext, ".o");
1699 else
1700 pstrcpy(outfile_default, sizeof(outfile_default), "a.out");
1702 return outfile_default;
1706 LIBTCCAPI void tcc_gen_makedeps(TCCState *s, const char *target, const char *filename)
1708 FILE *depout;
1709 char buf[1024], *ext;
1710 int i;
1712 if (!target)
1713 target = tcc_default_target(s);
1715 if (!filename) {
1716 /* compute filename automatically
1717 * dir/file.o -> dir/file.d */
1718 pstrcpy(buf, sizeof(buf), target);
1719 ext = tcc_fileextension(buf);
1720 pstrcpy(ext, sizeof(buf) - (ext-buf), ".d");
1721 filename = buf;
1724 if (s->verbose)
1725 printf("<- %s\n", filename);
1727 /* XXX return err codes instead of error() ? */
1728 depout = fopen(filename, "w");
1729 if (!depout)
1730 error("could not open '%s'", filename);
1732 fprintf(depout, "%s : \\\n", target);
1733 for (i=0; i<s->nb_target_deps; ++i)
1734 fprintf(depout, "\t%s \\\n", s->target_deps[i]);
1735 fprintf(depout, "\n");
1736 fclose(depout);