Remove useless changes from 31ca000d in configure
[tinycc.git] / libtcc.c
blobf06047622f8833db7065adad349f99762b1a90bf
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 #define NEED_FLOAT_TYPES
22 #include "tcc.h"
24 /********************************************************/
25 /* global variables */
27 /* use GNU C extensions */
28 ST_DATA int gnu_ext = 1;
30 /* use TinyCC extensions */
31 ST_DATA int tcc_ext = 1;
33 /* XXX: get rid of this ASAP */
34 ST_DATA struct TCCState *tcc_state;
36 #ifdef CONFIG_TCC_BACKTRACE
37 ST_DATA int num_callers = 6;
38 ST_DATA const char **rt_bound_error_msg;
39 ST_DATA void *rt_prog_main;
40 #endif
42 /********************************************************/
44 #ifndef NOTALLINONE
45 #include "tccpp.c"
46 #include "tccgen.c"
47 #include "tccelf.c"
48 #include "tccrun.c"
49 #ifdef TCC_TARGET_I386
50 #include "i386-gen.c"
51 #endif
52 #ifdef TCC_TARGET_ARM
53 #include "arm-gen.c"
54 #endif
55 #ifdef TCC_TARGET_C67
56 #include "c67-gen.c"
57 #endif
58 #ifdef TCC_TARGET_X86_64
59 #include "x86_64-gen.c"
60 #endif
61 #ifdef CONFIG_TCC_ASM
62 #include "tccasm.c"
63 #if defined TCC_TARGET_I386 || defined TCC_TARGET_X86_64
64 #include "i386-asm.c"
65 #endif
66 #endif
67 #ifdef TCC_TARGET_COFF
68 #include "tcccoff.c"
69 #endif
70 #ifdef TCC_TARGET_PE
71 #include "tccpe.c"
72 #endif
73 #endif /* ALL_IN_ONE */
75 /********************************************************/
76 #ifndef CONFIG_TCC_ASM
77 ST_FUNC void asm_instr(void)
79 error("inline asm() not supported");
81 ST_FUNC void asm_global_instr(void)
83 error("inline asm() not supported");
85 #endif
87 /********************************************************/
89 #ifdef _WIN32
90 static char *normalize_slashes(char *path)
92 char *p;
93 for (p = path; *p; ++p)
94 if (*p == '\\')
95 *p = '/';
96 return path;
99 static HMODULE tcc_module;
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)
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);
115 #ifndef CONFIG_TCC_STATIC
116 void dlclose(void *p)
118 FreeLibrary((HMODULE)p);
120 #endif
122 #ifdef LIBTCC_AS_DLL
123 BOOL WINAPI DllMain (HANDLE hDll, DWORD dwReason, LPVOID lpReserved)
125 if (DLL_PROCESS_ATTACH == dwReason)
126 tcc_module = hDll;
127 return TRUE;
129 #endif
130 #endif
132 /********************************************************/
133 /* copy a string and truncate it. */
134 PUB_FUNC char *pstrcpy(char *buf, int buf_size, const char *s)
136 char *q, *q_end;
137 int c;
139 if (buf_size > 0) {
140 q = buf;
141 q_end = buf + buf_size - 1;
142 while (q < q_end) {
143 c = *s++;
144 if (c == '\0')
145 break;
146 *q++ = c;
148 *q = '\0';
150 return buf;
153 /* strcat and truncate. */
154 PUB_FUNC char *pstrcat(char *buf, int buf_size, const char *s)
156 int len;
157 len = strlen(buf);
158 if (len < buf_size)
159 pstrcpy(buf + len, buf_size - len, s);
160 return buf;
163 /* extract the basename of a file */
164 PUB_FUNC char *tcc_basename(const char *name)
166 char *p = strchr(name, 0);
167 while (p > name && !IS_PATHSEP(p[-1]))
168 --p;
169 return p;
172 /* extract extension part of a file
174 * (if no extension, return pointer to end-of-string)
176 PUB_FUNC char *tcc_fileextension (const char *name)
178 char *b = tcc_basename(name);
179 char *e = strrchr(b, '.');
180 return e ? e : strchr(b, 0);
183 /********************************************************/
184 /* memory management */
186 #undef free
187 #undef malloc
188 #undef realloc
190 #ifdef MEM_DEBUG
191 int mem_cur_size;
192 int mem_max_size;
193 unsigned malloc_usable_size(void*);
194 #endif
196 PUB_FUNC void tcc_free(void *ptr)
198 #ifdef MEM_DEBUG
199 mem_cur_size -= malloc_usable_size(ptr);
200 #endif
201 free(ptr);
204 PUB_FUNC void *tcc_malloc(unsigned long size)
206 void *ptr;
207 ptr = malloc(size);
208 if (!ptr && size)
209 error("memory full");
210 #ifdef MEM_DEBUG
211 mem_cur_size += malloc_usable_size(ptr);
212 if (mem_cur_size > mem_max_size)
213 mem_max_size = mem_cur_size;
214 #endif
215 return ptr;
218 PUB_FUNC void *tcc_mallocz(unsigned long size)
220 void *ptr;
221 ptr = tcc_malloc(size);
222 memset(ptr, 0, size);
223 return ptr;
226 PUB_FUNC void *tcc_realloc(void *ptr, unsigned long size)
228 void *ptr1;
229 #ifdef MEM_DEBUG
230 mem_cur_size -= malloc_usable_size(ptr);
231 #endif
232 ptr1 = realloc(ptr, size);
233 #ifdef MEM_DEBUG
234 /* NOTE: count not correct if alloc error, but not critical */
235 mem_cur_size += malloc_usable_size(ptr1);
236 if (mem_cur_size > mem_max_size)
237 mem_max_size = mem_cur_size;
238 #endif
239 return ptr1;
242 PUB_FUNC char *tcc_strdup(const char *str)
244 char *ptr;
245 ptr = tcc_malloc(strlen(str) + 1);
246 strcpy(ptr, str);
247 return ptr;
250 /* out must not point to a valid dynarray since a new one is created */
251 PUB_FUNC int tcc_split_path_components(const char *in,
252 const char * const *prefixs,
253 int nb_prefixs, char ***out)
255 int i, nb_components = 0;
256 char *path_component;
257 const char *end_component;
258 size_t path_size;
260 *out = NULL;
261 end_component = in;
262 do {
263 while (*end_component && *end_component != ':')
264 ++end_component;
265 for (i = 0; i < nb_prefixs; i++) {
266 path_size = (strlen(prefixs[i]) + 1) * sizeof(char)
267 + (end_component - in);
268 path_component = tcc_malloc(path_size);
269 pstrcpy(path_component, path_size, prefixs[i]);
270 pstrcat(path_component, path_size, in);
271 dynarray_add((void ***) out, &nb_components, path_component);
273 in = ++end_component;
274 } while (*end_component);
275 return nb_components;
278 PUB_FUNC void tcc_memstats(void)
280 #ifdef MEM_DEBUG
281 printf("memory in use: %d\n", mem_cur_size);
282 #endif
285 #define free(p) use_tcc_free(p)
286 #define malloc(s) use_tcc_malloc(s)
287 #define realloc(p, s) use_tcc_realloc(p, s)
289 /********************************************************/
290 /* dynarrays */
292 PUB_FUNC void dynarray_add(void ***ptab, int *nb_ptr, void *data)
294 int nb, nb_alloc;
295 void **pp;
297 nb = *nb_ptr;
298 pp = *ptab;
299 /* every power of two we double array size */
300 if ((nb & (nb - 1)) == 0) {
301 if (!nb)
302 nb_alloc = 1;
303 else
304 nb_alloc = nb * 2;
305 pp = tcc_realloc(pp, nb_alloc * sizeof(void *));
306 if (!pp)
307 error("memory full");
308 *ptab = pp;
310 pp[nb++] = data;
311 *nb_ptr = nb;
314 PUB_FUNC void dynarray_reset(void *pp, int *n)
316 void **p;
317 for (p = *(void***)pp; *n; ++p, --*n)
318 if (*p)
319 tcc_free(*p);
320 tcc_free(*(void**)pp);
321 *(void**)pp = NULL;
324 /* we use our own 'finite' function to avoid potential problems with
325 non standard math libs */
326 /* XXX: endianness dependent */
327 ST_FUNC int ieee_finite(double d)
329 int *p = (int *)&d;
330 return ((unsigned)((p[1] | 0x800fffff) + 1)) >> 31;
333 /********************************************************/
335 ST_FUNC Section *new_section(TCCState *s1, const char *name, int sh_type, int sh_flags)
337 Section *sec;
339 sec = tcc_mallocz(sizeof(Section) + strlen(name));
340 strcpy(sec->name, name);
341 sec->sh_type = sh_type;
342 sec->sh_flags = sh_flags;
343 switch(sh_type) {
344 case SHT_HASH:
345 case SHT_REL:
346 case SHT_RELA:
347 case SHT_DYNSYM:
348 case SHT_SYMTAB:
349 case SHT_DYNAMIC:
350 sec->sh_addralign = 4;
351 break;
352 case SHT_STRTAB:
353 sec->sh_addralign = 1;
354 break;
355 default:
356 sec->sh_addralign = 32; /* default conservative alignment */
357 break;
360 if (sh_flags & SHF_PRIVATE) {
361 dynarray_add((void ***)&s1->priv_sections, &s1->nb_priv_sections, sec);
362 } else {
363 sec->sh_num = s1->nb_sections;
364 dynarray_add((void ***)&s1->sections, &s1->nb_sections, sec);
367 return sec;
370 static void free_section(Section *s)
372 tcc_free(s->data);
375 /* realloc section and set its content to zero */
376 ST_FUNC void section_realloc(Section *sec, unsigned long new_size)
378 unsigned long size;
379 unsigned char *data;
381 size = sec->data_allocated;
382 if (size == 0)
383 size = 1;
384 while (size < new_size)
385 size = size * 2;
386 data = tcc_realloc(sec->data, size);
387 if (!data)
388 error("memory full");
389 memset(data + sec->data_allocated, 0, size - sec->data_allocated);
390 sec->data = data;
391 sec->data_allocated = size;
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)
398 unsigned long offset, offset1;
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;
408 /* reserve at least 'size' bytes from section start */
409 ST_FUNC void section_reserve(Section *sec, unsigned long size)
411 if (size > sec->data_allocated)
412 section_realloc(sec, size);
413 if (size > sec->data_offset)
414 sec->data_offset = size;
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)
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;
428 /* sections are created as PROGBITS */
429 return new_section(s1, name, SHT_PROGBITS, SHF_ALLOC);
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 unsigned long value, unsigned long size,
436 int can_add_underscore)
438 int sym_type, sym_bind, sh_num, info, other;
439 ElfW(Sym) *esym;
440 const char *name;
441 char buf1[256];
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;
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;
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;
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];
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;
497 #endif
498 other = 0;
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;
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;
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;
525 if (sym->asm_label) {
526 name = sym->asm_label;
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;
538 ST_FUNC void put_extern_sym(Sym *sym, Section *section,
539 unsigned long value, unsigned long size)
541 put_extern_sym2(sym, section, value, size, 1);
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)
547 int c = 0;
548 if (sym) {
549 if (0 == sym->c)
550 put_extern_sym(sym, NULL, 0, 0);
551 c = sym->c;
553 /* now we can add ELF relocation info */
554 put_elf_reloc(symtab_section, s, offset, type, c);
557 /********************************************************/
559 static void strcat_vprintf(char *buf, int buf_size, const char *fmt, va_list ap)
561 int len;
562 len = strlen(buf);
563 vsnprintf(buf + len, buf_size - len, fmt, ap);
566 static void strcat_printf(char *buf, int buf_size, const char *fmt, ...)
568 va_list ap;
569 va_start(ap, fmt);
570 strcat_vprintf(buf, buf_size, fmt, ap);
571 va_end(ap);
574 static void error1(TCCState *s1, int is_warning, const char *fmt, va_list ap)
576 char buf[2048];
577 BufferedFile **f;
579 buf[0] = '\0';
580 if (file) {
581 for(f = s1->include_stack; f < s1->include_stack_ptr; f++)
582 strcat_printf(buf, sizeof(buf), "In file included from %s:%d:\n",
583 (*f)->filename, (*f)->line_num);
584 if (file->line_num > 0) {
585 strcat_printf(buf, sizeof(buf),
586 "%s:%d: ", file->filename, file->line_num);
587 } else {
588 strcat_printf(buf, sizeof(buf),
589 "%s: ", file->filename);
591 } else {
592 strcat_printf(buf, sizeof(buf),
593 "tcc: ");
595 if (is_warning)
596 strcat_printf(buf, sizeof(buf), "warning: ");
597 else
598 strcat_printf(buf, sizeof(buf), "error: ");
599 strcat_vprintf(buf, sizeof(buf), fmt, ap);
601 if (!s1->error_func) {
602 /* default case: stderr */
603 fprintf(stderr, "%s\n", buf);
604 } else {
605 s1->error_func(s1->error_opaque, buf);
607 if (!is_warning || s1->warn_error)
608 s1->nb_errors++;
611 LIBTCCAPI void tcc_set_error_func(TCCState *s, void *error_opaque,
612 void (*error_func)(void *opaque, const char *msg))
614 s->error_opaque = error_opaque;
615 s->error_func = error_func;
618 /* error without aborting current compilation */
619 PUB_FUNC void error_noabort(const char *fmt, ...)
621 TCCState *s1 = tcc_state;
622 va_list ap;
624 va_start(ap, fmt);
625 error1(s1, 0, fmt, ap);
626 va_end(ap);
629 PUB_FUNC void error(const char *fmt, ...)
631 TCCState *s1 = tcc_state;
632 va_list ap;
634 va_start(ap, fmt);
635 error1(s1, 0, fmt, ap);
636 va_end(ap);
637 /* better than nothing: in some cases, we accept to handle errors */
638 if (s1->error_set_jmp_enabled) {
639 longjmp(s1->error_jmp_buf, 1);
640 } else {
641 /* XXX: eliminate this someday */
642 exit(1);
646 PUB_FUNC void expect(const char *msg)
648 error("%s expected", msg);
651 PUB_FUNC void warning(const char *fmt, ...)
653 TCCState *s1 = tcc_state;
654 va_list ap;
656 if (s1->warn_none)
657 return;
659 va_start(ap, fmt);
660 error1(s1, 1, fmt, ap);
661 va_end(ap);
664 /********************************************************/
665 /* I/O layer */
667 ST_FUNC void tcc_open_bf(TCCState *s1, const char *filename, int initlen)
669 BufferedFile *bf;
670 int buflen = initlen ? initlen : IO_BUF_SIZE;
672 bf = tcc_malloc(sizeof(BufferedFile) + buflen);
673 bf->buf_ptr = bf->buffer;
674 bf->buf_end = bf->buffer + initlen;
675 bf->buf_end[0] = CH_EOB; /* put eob symbol */
676 pstrcpy(bf->filename, sizeof(bf->filename), filename);
677 #ifdef _WIN32
678 normalize_slashes(bf->filename);
679 #endif
680 bf->line_num = 1;
681 bf->ifndef_macro = 0;
682 bf->ifdef_stack_ptr = s1->ifdef_stack_ptr;
683 bf->fd = -1;
684 bf->prev = file;
685 file = bf;
688 ST_FUNC void tcc_close(void)
690 BufferedFile *bf = file;
691 if (bf->fd > 0) {
692 close(bf->fd);
693 total_lines += bf->line_num;
695 file = bf->prev;
696 tcc_free(bf);
699 ST_FUNC int tcc_open(TCCState *s1, const char *filename)
701 int fd;
702 if (strcmp(filename, "-") == 0)
703 fd = 0, filename = "stdin";
704 else
705 fd = open(filename, O_RDONLY | O_BINARY);
706 if ((s1->verbose == 2 && fd >= 0) || s1->verbose == 3)
707 printf("%s %*s%s\n", fd < 0 ? "nf":"->",
708 (int)(s1->include_stack_ptr - s1->include_stack), "", filename);
709 if (fd < 0)
710 return -1;
712 tcc_open_bf(s1, filename, 0);
713 file->fd = fd;
714 return fd;
717 /* compile the C file opened in 'file'. Return non zero if errors. */
718 static int tcc_compile(TCCState *s1)
720 Sym *define_start;
721 SValue *pvtop;
722 char buf[512];
723 volatile int section_sym;
725 #ifdef INC_DEBUG
726 printf("%s: **** new file\n", file->filename);
727 #endif
728 preprocess_init(s1);
730 cur_text_section = NULL;
731 funcname = "";
732 anon_sym = SYM_FIRST_ANOM;
734 /* file info: full path + filename */
735 section_sym = 0; /* avoid warning */
736 if (s1->do_debug) {
737 section_sym = put_elf_sym(symtab_section, 0, 0,
738 ELFW(ST_INFO)(STB_LOCAL, STT_SECTION), 0,
739 text_section->sh_num, NULL);
740 getcwd(buf, sizeof(buf));
741 #ifdef _WIN32
742 normalize_slashes(buf);
743 #endif
744 pstrcat(buf, sizeof(buf), "/");
745 put_stabs_r(buf, N_SO, 0, 0,
746 text_section->data_offset, text_section, section_sym);
747 put_stabs_r(file->filename, N_SO, 0, 0,
748 text_section->data_offset, text_section, section_sym);
750 /* an elf symbol of type STT_FILE must be put so that STB_LOCAL
751 symbols can be safely used */
752 put_elf_sym(symtab_section, 0, 0,
753 ELFW(ST_INFO)(STB_LOCAL, STT_FILE), 0,
754 SHN_ABS, file->filename);
756 /* define some often used types */
757 int_type.t = VT_INT;
759 char_pointer_type.t = VT_BYTE;
760 mk_pointer(&char_pointer_type);
762 func_old_type.t = VT_FUNC;
763 func_old_type.ref = sym_push(SYM_FIELD, &int_type, FUNC_CDECL, FUNC_OLD);
765 #if defined(TCC_ARM_EABI) && defined(TCC_ARM_VFP)
766 float_type.t = VT_FLOAT;
767 double_type.t = VT_DOUBLE;
769 func_float_type.t = VT_FUNC;
770 func_float_type.ref = sym_push(SYM_FIELD, &float_type, FUNC_CDECL, FUNC_OLD);
771 func_double_type.t = VT_FUNC;
772 func_double_type.ref = sym_push(SYM_FIELD, &double_type, FUNC_CDECL, FUNC_OLD);
773 #endif
775 #if 0
776 /* define 'void *alloca(unsigned int)' builtin function */
778 Sym *s1;
780 p = anon_sym++;
781 sym = sym_push(p, mk_pointer(VT_VOID), FUNC_CDECL, FUNC_NEW);
782 s1 = sym_push(SYM_FIELD, VT_UNSIGNED | VT_INT, 0, 0);
783 s1->next = NULL;
784 sym->next = s1;
785 sym_push(TOK_alloca, VT_FUNC | (p << VT_STRUCT_SHIFT), VT_CONST, 0);
787 #endif
789 define_start = define_stack;
790 nocode_wanted = 1;
792 if (setjmp(s1->error_jmp_buf) == 0) {
793 s1->nb_errors = 0;
794 s1->error_set_jmp_enabled = 1;
796 ch = file->buf_ptr[0];
797 tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
798 parse_flags = PARSE_FLAG_PREPROCESS | PARSE_FLAG_TOK_NUM;
799 pvtop = vtop;
800 next();
801 decl(VT_CONST);
802 if (tok != TOK_EOF)
803 expect("declaration");
804 if (pvtop != vtop)
805 warning("internal compiler error: vstack leak? (%d)", vtop - pvtop);
807 /* end of translation unit info */
808 if (s1->do_debug) {
809 put_stabs_r(NULL, N_SO, 0, 0,
810 text_section->data_offset, text_section, section_sym);
814 s1->error_set_jmp_enabled = 0;
816 /* reset define stack, but leave -Dsymbols (may be incorrect if
817 they are undefined) */
818 free_defines(define_start);
820 gen_inline_functions();
822 sym_pop(&global_stack, NULL);
823 sym_pop(&local_stack, NULL);
825 return s1->nb_errors != 0 ? -1 : 0;
828 LIBTCCAPI int tcc_compile_string(TCCState *s, const char *str)
830 int len, ret;
831 len = strlen(str);
833 tcc_open_bf(s, "<string>", len);
834 memcpy(file->buffer, str, len);
835 ret = tcc_compile(s);
836 tcc_close();
837 return ret;
840 /* define a preprocessor symbol. A value can also be provided with the '=' operator */
841 LIBTCCAPI void tcc_define_symbol(TCCState *s1, const char *sym, const char *value)
843 int len1, len2;
844 /* default value */
845 if (!value)
846 value = "1";
847 len1 = strlen(sym);
848 len2 = strlen(value);
850 /* init file structure */
851 tcc_open_bf(s1, "<define>", len1 + len2 + 1);
852 memcpy(file->buffer, sym, len1);
853 file->buffer[len1] = ' ';
854 memcpy(file->buffer + len1 + 1, value, len2);
856 /* parse with define parser */
857 ch = file->buf_ptr[0];
858 next_nomacro();
859 parse_define();
861 tcc_close();
864 /* undefine a preprocessor symbol */
865 LIBTCCAPI void tcc_undefine_symbol(TCCState *s1, const char *sym)
867 TokenSym *ts;
868 Sym *s;
869 ts = tok_alloc(sym, strlen(sym));
870 s = define_find(ts->tok);
871 /* undefine symbol by putting an invalid name */
872 if (s)
873 define_undef(s);
876 static void tcc_cleanup(void)
878 int i, n;
880 if (NULL == tcc_state)
881 return;
882 tcc_state = NULL;
884 /* free -D defines */
885 free_defines(NULL);
887 /* free tokens */
888 n = tok_ident - TOK_IDENT;
889 for(i = 0; i < n; i++)
890 tcc_free(table_ident[i]);
891 tcc_free(table_ident);
893 /* free sym_pools */
894 dynarray_reset(&sym_pools, &nb_sym_pools);
895 /* string buffer */
896 cstr_free(&tokcstr);
897 /* reset symbol stack */
898 sym_free_first = NULL;
899 /* cleanup from error/setjmp */
900 macro_ptr = NULL;
903 LIBTCCAPI TCCState *tcc_new(void)
905 TCCState *s;
906 char buffer[100];
907 int a,b,c;
909 tcc_cleanup();
911 s = tcc_mallocz(sizeof(TCCState));
912 if (!s)
913 return NULL;
914 tcc_state = s;
915 #ifdef _WIN32
916 tcc_set_lib_path_w32(s);
917 #else
918 tcc_set_lib_path(s, CONFIG_TCCDIR);
919 #endif
920 s->output_type = TCC_OUTPUT_MEMORY;
921 preprocess_new();
922 s->include_stack_ptr = s->include_stack;
924 /* we add dummy defines for some special macros to speed up tests
925 and to have working defined() */
926 define_push(TOK___LINE__, MACRO_OBJ, NULL, NULL);
927 define_push(TOK___FILE__, MACRO_OBJ, NULL, NULL);
928 define_push(TOK___DATE__, MACRO_OBJ, NULL, NULL);
929 define_push(TOK___TIME__, MACRO_OBJ, NULL, NULL);
931 /* standard defines */
932 tcc_define_symbol(s, "__STDC__", NULL);
933 tcc_define_symbol(s, "__STDC_VERSION__", "199901L");
934 #if defined(TCC_TARGET_I386)
935 tcc_define_symbol(s, "__i386__", NULL);
936 tcc_define_symbol(s, "__i386", NULL);
937 tcc_define_symbol(s, "i386", NULL);
938 #endif
939 #if defined(TCC_TARGET_X86_64)
940 tcc_define_symbol(s, "__x86_64__", NULL);
941 #endif
942 #if defined(TCC_TARGET_ARM)
943 tcc_define_symbol(s, "__ARM_ARCH_4__", NULL);
944 tcc_define_symbol(s, "__arm_elf__", NULL);
945 tcc_define_symbol(s, "__arm_elf", NULL);
946 tcc_define_symbol(s, "arm_elf", NULL);
947 tcc_define_symbol(s, "__arm__", NULL);
948 tcc_define_symbol(s, "__arm", NULL);
949 tcc_define_symbol(s, "arm", NULL);
950 tcc_define_symbol(s, "__APCS_32__", NULL);
951 #endif
952 #ifdef TCC_TARGET_PE
953 tcc_define_symbol(s, "_WIN32", NULL);
954 #ifdef TCC_TARGET_X86_64
955 tcc_define_symbol(s, "_WIN64", NULL);
956 #endif
957 #else
958 tcc_define_symbol(s, "__unix__", NULL);
959 tcc_define_symbol(s, "__unix", NULL);
960 tcc_define_symbol(s, "unix", NULL);
961 #if defined(__FreeBSD__)
962 #define str(s) #s
963 tcc_define_symbol(s, "__FreeBSD__", str( __FreeBSD__));
964 #undef str
965 #endif
966 #if defined(__FreeBSD_kernel__)
967 tcc_define_symbol(s, "__FreeBSD_kernel__", NULL);
968 #endif
969 #if defined(__linux)
970 tcc_define_symbol(s, "__linux__", NULL);
971 tcc_define_symbol(s, "__linux", NULL);
972 #endif
973 #endif
974 /* tiny C specific defines */
975 sscanf(TCC_VERSION, "%d.%d.%d", &a, &b, &c);
976 sprintf(buffer, "%d", a*10000 + b*100 + c);
977 tcc_define_symbol(s, "__TINYC__", buffer);
979 /* tiny C & gcc defines */
980 #if defined TCC_TARGET_PE && defined TCC_TARGET_X86_64
981 tcc_define_symbol(s, "__SIZE_TYPE__", "unsigned long long");
982 tcc_define_symbol(s, "__PTRDIFF_TYPE__", "long long");
983 #else
984 tcc_define_symbol(s, "__SIZE_TYPE__", "unsigned long");
985 tcc_define_symbol(s, "__PTRDIFF_TYPE__", "long");
986 #endif
988 #ifdef TCC_TARGET_PE
989 tcc_define_symbol(s, "__WCHAR_TYPE__", "unsigned short");
990 #else
991 tcc_define_symbol(s, "__WCHAR_TYPE__", "int");
992 #endif
994 /* glibc defines */
995 tcc_define_symbol(s, "__REDIRECT_NTH(name, proto, alias)", "name proto __asm__ (#alias) __THROW");
997 #ifndef TCC_TARGET_PE
998 /* default library paths */
999 tcc_add_library_path(s, CONFIG_TCC_CRT_PREFIX);
1000 tcc_add_library_path(s, CONFIG_SYSROOT CONFIG_TCC_LDDIR);
1001 tcc_add_library_path(s, CONFIG_SYSROOT "/usr/local"CONFIG_TCC_LDDIR);
1002 #ifdef CONFIG_TCC_EXTRA_LDDIR
1004 int i, nb_extra_lddirs, nb_prefixs;
1005 char **extra_lddirs;
1006 char extra_lddir_str[] = CONFIG_TCC_EXTRA_LDDIR;
1007 const char lddir_prefix1[] = CONFIG_SYSROOT;
1008 const char lddir_prefix2[] = CONFIG_SYSROOT "/usr/local";
1009 const char * const lddir_prefixs[] = {lddir_prefix1, lddir_prefix2};
1011 nb_prefixs = sizeof lddir_prefixs / sizeof *lddir_prefixs;
1012 nb_extra_lddirs = tcc_split_path_components(CONFIG_TCC_EXTRA_LDDIR,
1013 lddir_prefixs, nb_prefixs,
1014 &extra_lddirs);
1015 for (i = 0; i < nb_extra_lddirs; i++)
1016 tcc_add_library_path(s, extra_lddirs[i]);
1017 dynarray_reset(&extra_lddirs, &nb_extra_lddirs);
1019 #endif
1020 #endif
1022 /* no section zero */
1023 dynarray_add((void ***)&s->sections, &s->nb_sections, NULL);
1025 /* create standard sections */
1026 text_section = new_section(s, ".text", SHT_PROGBITS, SHF_ALLOC | SHF_EXECINSTR);
1027 data_section = new_section(s, ".data", SHT_PROGBITS, SHF_ALLOC | SHF_WRITE);
1028 bss_section = new_section(s, ".bss", SHT_NOBITS, SHF_ALLOC | SHF_WRITE);
1030 /* symbols are always generated for linking stage */
1031 symtab_section = new_symtab(s, ".symtab", SHT_SYMTAB, 0,
1032 ".strtab",
1033 ".hashtab", SHF_PRIVATE);
1034 strtab_section = symtab_section->link;
1036 /* private symbol table for dynamic symbols */
1037 s->dynsymtab_section = new_symtab(s, ".dynsymtab", SHT_SYMTAB, SHF_PRIVATE,
1038 ".dynstrtab",
1039 ".dynhashtab", SHF_PRIVATE);
1040 s->alacarte_link = 1;
1041 s->nocommon = 1;
1043 #ifdef CHAR_IS_UNSIGNED
1044 s->char_is_unsigned = 1;
1045 #endif
1046 /* enable this if you want symbols with leading underscore on windows: */
1047 #if defined(TCC_TARGET_PE) && 0
1048 s->leading_underscore = 1;
1049 #endif
1050 if (s->section_align == 0)
1051 s->section_align = ELF_PAGE_SIZE;
1052 #ifdef TCC_TARGET_I386
1053 s->seg_size = 32;
1054 #endif
1055 return s;
1058 LIBTCCAPI void tcc_delete(TCCState *s1)
1060 int i;
1062 tcc_cleanup();
1064 /* free all sections */
1065 for(i = 1; i < s1->nb_sections; i++)
1066 free_section(s1->sections[i]);
1067 dynarray_reset(&s1->sections, &s1->nb_sections);
1069 for(i = 0; i < s1->nb_priv_sections; i++)
1070 free_section(s1->priv_sections[i]);
1071 dynarray_reset(&s1->priv_sections, &s1->nb_priv_sections);
1073 /* free any loaded DLLs */
1074 for ( i = 0; i < s1->nb_loaded_dlls; i++) {
1075 DLLReference *ref = s1->loaded_dlls[i];
1076 if ( ref->handle )
1077 dlclose(ref->handle);
1080 /* free loaded dlls array */
1081 dynarray_reset(&s1->loaded_dlls, &s1->nb_loaded_dlls);
1083 /* free library paths */
1084 dynarray_reset(&s1->library_paths, &s1->nb_library_paths);
1086 /* free include paths */
1087 dynarray_reset(&s1->cached_includes, &s1->nb_cached_includes);
1088 dynarray_reset(&s1->include_paths, &s1->nb_include_paths);
1089 dynarray_reset(&s1->sysinclude_paths, &s1->nb_sysinclude_paths);
1091 tcc_free(s1->tcc_lib_path);
1093 dynarray_reset(&s1->input_files, &s1->nb_input_files);
1094 dynarray_reset(&s1->input_libs, &s1->nb_input_libs);
1095 dynarray_reset(&s1->target_deps, &s1->nb_target_deps);
1097 #ifdef HAVE_SELINUX
1098 munmap (s1->write_mem, s1->mem_size);
1099 munmap (s1->runtime_mem, s1->mem_size);
1100 #else
1101 tcc_free(s1->runtime_mem);
1102 #endif
1103 tcc_free(s1);
1106 LIBTCCAPI int tcc_add_include_path(TCCState *s1, const char *pathname)
1108 char *pathname1;
1110 pathname1 = tcc_strdup(pathname);
1111 dynarray_add((void ***)&s1->include_paths, &s1->nb_include_paths, pathname1);
1112 return 0;
1115 LIBTCCAPI int tcc_add_sysinclude_path(TCCState *s1, const char *pathname)
1117 char *pathname1;
1119 pathname1 = tcc_strdup(pathname);
1120 dynarray_add((void ***)&s1->sysinclude_paths, &s1->nb_sysinclude_paths, pathname1);
1121 return 0;
1124 ST_FUNC int tcc_add_file_internal(TCCState *s1, const char *filename, int flags)
1126 const char *ext;
1127 ElfW(Ehdr) ehdr;
1128 int fd, ret, size;
1130 /* find source file type with extension */
1131 ext = tcc_fileextension(filename);
1132 if (ext[0])
1133 ext++;
1135 #ifdef CONFIG_TCC_ASM
1136 /* if .S file, define __ASSEMBLER__ like gcc does */
1137 if (!strcmp(ext, "S"))
1138 tcc_define_symbol(s1, "__ASSEMBLER__", NULL);
1139 #endif
1141 /* open the file */
1142 ret = tcc_open(s1, filename);
1143 if (ret < 0) {
1144 if (flags & AFF_PRINT_ERROR)
1145 error_noabort("file '%s' not found", filename);
1146 return ret;
1149 /* update target deps */
1150 dynarray_add((void ***)&s1->target_deps, &s1->nb_target_deps,
1151 tcc_strdup(filename));
1153 if (flags & AFF_PREPROCESS) {
1154 ret = tcc_preprocess(s1);
1155 goto the_end;
1158 if (!ext[0] || !PATHCMP(ext, "c")) {
1159 /* C file assumed */
1160 ret = tcc_compile(s1);
1161 goto the_end;
1164 #ifdef CONFIG_TCC_ASM
1165 if (!strcmp(ext, "S")) {
1166 /* preprocessed assembler */
1167 ret = tcc_assemble(s1, 1);
1168 goto the_end;
1171 if (!strcmp(ext, "s")) {
1172 /* non preprocessed assembler */
1173 ret = tcc_assemble(s1, 0);
1174 goto the_end;
1176 #endif
1178 fd = file->fd;
1179 /* assume executable format: auto guess file type */
1180 size = read(fd, &ehdr, sizeof(ehdr));
1181 lseek(fd, 0, SEEK_SET);
1182 if (size <= 0) {
1183 error_noabort("could not read header");
1184 goto the_end;
1187 if (size == sizeof(ehdr) &&
1188 ehdr.e_ident[0] == ELFMAG0 &&
1189 ehdr.e_ident[1] == ELFMAG1 &&
1190 ehdr.e_ident[2] == ELFMAG2 &&
1191 ehdr.e_ident[3] == ELFMAG3) {
1193 /* do not display line number if error */
1194 file->line_num = 0;
1195 if (ehdr.e_type == ET_REL) {
1196 ret = tcc_load_object_file(s1, fd, 0);
1197 goto the_end;
1200 #ifndef TCC_TARGET_PE
1201 if (ehdr.e_type == ET_DYN) {
1202 if (s1->output_type == TCC_OUTPUT_MEMORY) {
1203 void *h;
1204 h = dlopen(filename, RTLD_GLOBAL | RTLD_LAZY);
1205 if (h)
1206 ret = 0;
1207 } else {
1208 ret = tcc_load_dll(s1, fd, filename,
1209 (flags & AFF_REFERENCED_DLL) != 0);
1211 goto the_end;
1213 #endif
1214 error_noabort("unrecognized ELF file");
1215 goto the_end;
1218 if (memcmp((char *)&ehdr, ARMAG, 8) == 0) {
1219 file->line_num = 0; /* do not display line number if error */
1220 ret = tcc_load_archive(s1, fd);
1221 goto the_end;
1224 #ifdef TCC_TARGET_COFF
1225 if (*(uint16_t *)(&ehdr) == COFF_C67_MAGIC) {
1226 ret = tcc_load_coff(s1, fd);
1227 goto the_end;
1229 #endif
1231 #ifdef TCC_TARGET_PE
1232 ret = pe_load_file(s1, filename, fd);
1233 #else
1234 /* as GNU ld, consider it is an ld script if not recognized */
1235 ret = tcc_load_ldscript(s1);
1236 #endif
1237 if (ret < 0)
1238 error_noabort("unrecognized file type");
1240 the_end:
1241 tcc_close();
1242 return ret;
1245 LIBTCCAPI int tcc_add_file(TCCState *s, const char *filename)
1247 dynarray_add((void ***)&s->input_files, &s->nb_input_files, tcc_strdup(filename));
1249 if (s->output_type == TCC_OUTPUT_PREPROCESS)
1250 return tcc_add_file_internal(s, filename, AFF_PRINT_ERROR | AFF_PREPROCESS);
1251 else
1252 return tcc_add_file_internal(s, filename, AFF_PRINT_ERROR);
1255 LIBTCCAPI int tcc_add_library_path(TCCState *s, const char *pathname)
1257 char *pathname1;
1259 pathname1 = tcc_strdup(pathname);
1260 dynarray_add((void ***)&s->library_paths, &s->nb_library_paths, pathname1);
1261 return 0;
1264 /* find and load a dll. Return non zero if not found */
1265 /* XXX: add '-rpath' option support ? */
1266 ST_FUNC int tcc_add_dll(TCCState *s, const char *filename, int flags)
1268 char buf[1024];
1269 int i;
1271 for(i = 0; i < s->nb_library_paths; i++) {
1272 snprintf(buf, sizeof(buf), "%s/%s",
1273 s->library_paths[i], filename);
1274 if (tcc_add_file_internal(s, buf, flags) == 0)
1275 return 0;
1277 return -1;
1280 /* the library name is the same as the argument of the '-l' option */
1281 LIBTCCAPI int tcc_add_library(TCCState *s, const char *libraryname)
1283 char buf[1024];
1284 int i;
1286 dynarray_add((void ***)&s->input_libs, &s->nb_input_libs, tcc_strdup(libraryname));
1288 /* first we look for the dynamic library if not static linking */
1289 if (!s->static_link) {
1290 #ifdef TCC_TARGET_PE
1291 if (pe_add_dll(s, libraryname) == 0)
1292 return 0;
1293 #else
1294 snprintf(buf, sizeof(buf), "lib%s.so", libraryname);
1295 if (tcc_add_dll(s, buf, 0) == 0)
1296 return 0;
1297 #endif
1299 /* then we look for the static library */
1300 for(i = 0; i < s->nb_library_paths; i++) {
1301 snprintf(buf, sizeof(buf), "%s/lib%s.a",
1302 s->library_paths[i], libraryname);
1303 if (tcc_add_file_internal(s, buf, 0) == 0)
1304 return 0;
1306 return -1;
1309 LIBTCCAPI int tcc_add_symbol(TCCState *s, const char *name, const void *val)
1311 #ifdef TCC_TARGET_PE
1312 pe_putimport(s, 0, name, val);
1313 #else
1314 add_elf_sym(symtab_section, (uplong)val, 0,
1315 ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE), 0,
1316 SHN_ABS, name);
1317 #endif
1318 return 0;
1321 LIBTCCAPI int tcc_set_output_type(TCCState *s, int output_type)
1323 char buf[1024];
1325 s->output_type = output_type;
1327 if (!s->nostdinc) {
1328 /* default include paths */
1329 /* -isystem paths have already been handled */
1330 #ifndef TCC_TARGET_PE
1332 int i, nb_extra_incdirs, nb_prefixs;
1333 char **extra_incdirs;
1334 const char incdir_prefix1[] = CONFIG_SYSROOT "/usr/local/include";
1335 const char incdir_prefix2[] = CONFIG_SYSROOT "/usr/include";
1336 const char * const incdir_prefixs[] = {incdir_prefix1,
1337 incdir_prefix2};
1339 nb_prefixs = sizeof incdir_prefixs / sizeof *incdir_prefixs;
1340 nb_extra_incdirs = tcc_split_path_components(CONFIG_TCC_INCSUBDIR,
1341 incdir_prefixs,
1342 nb_prefixs,
1343 &extra_incdirs);
1344 for (i = 0; i < nb_extra_incdirs; i++)
1345 tcc_add_sysinclude_path(s, extra_incdirs[i]);
1346 dynarray_reset(&extra_incdirs, &nb_extra_incdirs);
1348 #endif
1349 snprintf(buf, sizeof(buf), "%s/include", s->tcc_lib_path);
1350 tcc_add_sysinclude_path(s, buf);
1351 #ifdef TCC_TARGET_PE
1352 snprintf(buf, sizeof(buf), "%s/include/winapi", s->tcc_lib_path);
1353 tcc_add_sysinclude_path(s, buf);
1354 #endif
1357 /* if bound checking, then add corresponding sections */
1358 #ifdef CONFIG_TCC_BCHECK
1359 if (s->do_bounds_check) {
1360 /* define symbol */
1361 tcc_define_symbol(s, "__BOUNDS_CHECKING_ON", NULL);
1362 /* create bounds sections */
1363 bounds_section = new_section(s, ".bounds",
1364 SHT_PROGBITS, SHF_ALLOC);
1365 lbounds_section = new_section(s, ".lbounds",
1366 SHT_PROGBITS, SHF_ALLOC);
1368 #endif
1370 if (s->char_is_unsigned) {
1371 tcc_define_symbol(s, "__CHAR_UNSIGNED__", NULL);
1374 /* add debug sections */
1375 if (s->do_debug) {
1376 /* stab symbols */
1377 stab_section = new_section(s, ".stab", SHT_PROGBITS, 0);
1378 stab_section->sh_entsize = sizeof(Stab_Sym);
1379 stabstr_section = new_section(s, ".stabstr", SHT_STRTAB, 0);
1380 put_elf_str(stabstr_section, "");
1381 stab_section->link = stabstr_section;
1382 /* put first entry */
1383 put_stabs("", 0, 0, 0, 0);
1386 /* add libc crt1/crti objects */
1387 #ifndef TCC_TARGET_PE
1388 if ((output_type == TCC_OUTPUT_EXE || output_type == TCC_OUTPUT_DLL) &&
1389 !s->nostdlib) {
1390 if (output_type != TCC_OUTPUT_DLL)
1391 tcc_add_file(s, CONFIG_TCC_CRT_PREFIX "/crt1.o");
1392 tcc_add_file(s, CONFIG_TCC_CRT_PREFIX "/crti.o");
1394 #endif
1396 #ifdef TCC_TARGET_PE
1397 #ifdef CONFIG_TCC_CROSSLIB
1398 snprintf(buf, sizeof(buf), "%s/" CONFIG_TCC_CROSSLIB, s->tcc_lib_path);
1399 tcc_add_library_path(s, buf);
1400 #endif
1401 snprintf(buf, sizeof(buf), "%s/lib", s->tcc_lib_path);
1402 tcc_add_library_path(s, buf);
1403 #ifdef _WIN32
1404 if (GetSystemDirectory(buf, sizeof buf))
1405 tcc_add_library_path(s, buf);
1406 #endif
1407 #endif
1409 return 0;
1412 #define WD_ALL 0x0001 /* warning is activated when using -Wall */
1413 #define FD_INVERT 0x0002 /* invert value before storing */
1415 typedef struct FlagDef {
1416 uint16_t offset;
1417 uint16_t flags;
1418 const char *name;
1419 } FlagDef;
1421 static const FlagDef warning_defs[] = {
1422 { offsetof(TCCState, warn_unsupported), 0, "unsupported" },
1423 { offsetof(TCCState, warn_write_strings), 0, "write-strings" },
1424 { offsetof(TCCState, warn_error), 0, "error" },
1425 { offsetof(TCCState, warn_implicit_function_declaration), WD_ALL,
1426 "implicit-function-declaration" },
1429 ST_FUNC int set_flag(TCCState *s, const FlagDef *flags, int nb_flags,
1430 const char *name, int value)
1432 int i;
1433 const FlagDef *p;
1434 const char *r;
1436 r = name;
1437 if (r[0] == 'n' && r[1] == 'o' && r[2] == '-') {
1438 r += 3;
1439 value = !value;
1441 for(i = 0, p = flags; i < nb_flags; i++, p++) {
1442 if (!strcmp(r, p->name))
1443 goto found;
1445 return -1;
1446 found:
1447 if (p->flags & FD_INVERT)
1448 value = !value;
1449 *(int *)((uint8_t *)s + p->offset) = value;
1450 return 0;
1453 /* set/reset a warning */
1454 LIBTCCAPI int tcc_set_warning(TCCState *s, const char *warning_name, int value)
1456 int i;
1457 const FlagDef *p;
1459 if (!strcmp(warning_name, "all")) {
1460 for(i = 0, p = warning_defs; i < countof(warning_defs); i++, p++) {
1461 if (p->flags & WD_ALL)
1462 *(int *)((uint8_t *)s + p->offset) = 1;
1464 return 0;
1465 } else {
1466 return set_flag(s, warning_defs, countof(warning_defs),
1467 warning_name, value);
1471 static const FlagDef flag_defs[] = {
1472 { offsetof(TCCState, char_is_unsigned), 0, "unsigned-char" },
1473 { offsetof(TCCState, char_is_unsigned), FD_INVERT, "signed-char" },
1474 { offsetof(TCCState, nocommon), FD_INVERT, "common" },
1475 { offsetof(TCCState, leading_underscore), 0, "leading-underscore" },
1478 /* set/reset a flag */
1479 PUB_FUNC int tcc_set_flag(TCCState *s, const char *flag_name, int value)
1481 return set_flag(s, flag_defs, countof(flag_defs),
1482 flag_name, value);
1486 static int strstart(const char *str, const char *val, char **ptr)
1488 const char *p, *q;
1489 p = str;
1490 q = val;
1491 while (*q != '\0') {
1492 if (*p != *q)
1493 return 0;
1494 p++;
1495 q++;
1497 if (ptr)
1498 *ptr = (char *) p;
1499 return 1;
1503 /* Like strstart, but automatically takes into account that ld options can
1505 * - start with double or single dash (e.g. '--soname' or '-soname')
1506 * - arguments can be given as separate or after '=' (e.g. '-Wl,-soname,x.so'
1507 * or '-Wl,-soname=x.so')
1509 * you provide `val` always in 'option[=]' form (no leading -)
1511 static int link_option(const char *str, const char *val, char **ptr)
1513 const char *p, *q;
1515 /* there should be 1 or 2 dashes */
1516 if (*str++ != '-')
1517 return 0;
1518 if (*str == '-')
1519 str++;
1521 /* then str & val should match (potentialy up to '=') */
1522 p = str;
1523 q = val;
1525 while (*q != '\0' && *q != '=') {
1526 if (*p != *q)
1527 return 0;
1528 p++;
1529 q++;
1532 /* '=' near eos means ',' or '=' is ok */
1533 if (*q == '=') {
1534 if (*p != ',' && *p != '=')
1535 return 0;
1536 p++;
1537 q++;
1540 if (ptr)
1541 *ptr = (char *) p;
1542 return 1;
1546 /* set linker options */
1547 PUB_FUNC const char * tcc_set_linker(TCCState *s, char *option, int multi)
1549 char *p = option;
1550 char *end;
1552 while (option && *option) {
1553 end = NULL;
1554 if (link_option(option, "Bsymbolic", &p)) {
1555 s->symbolic = TRUE;
1556 #ifdef TCC_TARGET_PE
1557 } else if (link_option(option, "file-alignment=", &p)) {
1558 s->pe_file_align = strtoul(p, &end, 16);
1559 #endif
1560 } else if (link_option(option, "fini=", &p)) {
1561 s->fini_symbol = p;
1562 if (s->warn_unsupported)
1563 warning("ignoring -fini %s", p);
1565 } else if (link_option(option, "image-base=", &p)) {
1566 s->text_addr = strtoul(p, &end, 16);
1567 s->has_text_addr = 1;
1568 } else if (link_option(option, "init=", &p)) {
1569 s->init_symbol = p;
1570 if (s->warn_unsupported)
1571 warning("ignoring -init %s", p);
1573 } else if (link_option(option, "oformat=", &p)) {
1574 #if defined(TCC_TARGET_PE)
1575 if (strstart(p, "pe-", NULL)) {
1576 #else
1577 #if defined(TCC_TARGET_X86_64)
1578 if (strstart(p, "elf64-", NULL)) {
1579 #else
1580 if (strstart(p, "elf32-", NULL)) {
1581 #endif
1582 #endif
1583 s->output_format = TCC_OUTPUT_FORMAT_ELF;
1584 } else if (!strcmp(p, "binary")) {
1585 s->output_format = TCC_OUTPUT_FORMAT_BINARY;
1586 } else
1587 #ifdef TCC_TARGET_COFF
1588 if (!strcmp(p, "coff")) {
1589 s->output_format = TCC_OUTPUT_FORMAT_COFF;
1590 } else
1591 #endif
1593 return p;
1596 } else if (link_option(option, "rpath=", &p)) {
1597 s->rpath = p;
1598 } else if (link_option(option, "section-alignment=", &p)) {
1599 s->section_align = strtoul(p, &end, 16);
1600 } else if (link_option(option, "soname=", &p)) {
1601 s->soname = p;
1602 multi = 0;
1603 #ifdef TCC_TARGET_PE
1604 } else if (link_option(option, "subsystem=", &p)) {
1605 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
1606 if (!strcmp(p, "native")) {
1607 s->pe_subsystem = 1;
1608 } else if (!strcmp(p, "console")) {
1609 s->pe_subsystem = 3;
1610 } else if (!strcmp(p, "gui")) {
1611 s->pe_subsystem = 2;
1612 } else if (!strcmp(p, "posix")) {
1613 s->pe_subsystem = 7;
1614 } else if (!strcmp(p, "efiapp")) {
1615 s->pe_subsystem = 10;
1616 } else if (!strcmp(p, "efiboot")) {
1617 s->pe_subsystem = 11;
1618 } else if (!strcmp(p, "efiruntime")) {
1619 s->pe_subsystem = 12;
1620 } else if (!strcmp(p, "efirom")) {
1621 s->pe_subsystem = 13;
1622 #elif defined(TCC_TARGET_ARM)
1623 if (!strcmp(p, "wince")) {
1624 s->pe_subsystem = 9;
1625 #endif
1626 } else {
1627 return p;
1629 #endif
1631 } else if (link_option(option, "Ttext=", &p)) {
1632 s->text_addr = strtoul(p, &end, 16);
1633 s->has_text_addr = 1;
1635 } else {
1636 return option;
1639 if (multi) {
1640 option = NULL;
1641 p = strchr( (end) ? end : p, ',');
1642 if (p) {
1643 *p = 0; /* terminate last option */
1644 option = ++p;
1646 } else
1647 option = NULL;
1649 return NULL;
1652 PUB_FUNC void tcc_print_stats(TCCState *s, int64_t total_time)
1654 double tt;
1655 tt = (double)total_time / 1000000.0;
1656 if (tt < 0.001)
1657 tt = 0.001;
1658 if (total_bytes < 1)
1659 total_bytes = 1;
1660 printf("%d idents, %d lines, %d bytes, %0.3f s, %d lines/s, %0.1f MB/s\n",
1661 tok_ident - TOK_IDENT, total_lines, total_bytes,
1662 tt, (int)(total_lines / tt),
1663 total_bytes / tt / 1000000.0);
1666 /* set CONFIG_TCCDIR at runtime */
1667 LIBTCCAPI void tcc_set_lib_path(TCCState *s, const char *path)
1669 tcc_free(s->tcc_lib_path);
1670 s->tcc_lib_path = tcc_strdup(path);
1673 PUB_FUNC void set_num_callers(int n)
1675 #ifdef CONFIG_TCC_BACKTRACE
1676 num_callers = n;
1677 #endif
1681 LIBTCCAPI const char *tcc_default_target(TCCState *s)
1683 /* FIXME will break in multithreaded case */
1684 static char outfile_default[1024];
1686 char *ext;
1687 const char *name =
1688 strcmp(s->input_files[0], "-") == 0 ? "a"
1689 : tcc_basename(s->input_files[0]);
1690 pstrcpy(outfile_default, sizeof(outfile_default), name);
1691 ext = tcc_fileextension(outfile_default);
1692 #ifdef TCC_TARGET_PE
1693 if (s->output_type == TCC_OUTPUT_DLL)
1694 strcpy(ext, ".dll");
1695 else
1696 if (s->output_type == TCC_OUTPUT_EXE)
1697 strcpy(ext, ".exe");
1698 else
1699 #endif
1700 if (( (s->output_type == TCC_OUTPUT_OBJ && !s->reloc_output) ||
1701 (s->output_type == TCC_OUTPUT_PREPROCESS) )
1702 && *ext)
1703 strcpy(ext, ".o");
1704 else
1705 pstrcpy(outfile_default, sizeof(outfile_default), "a.out");
1707 return outfile_default;
1711 LIBTCCAPI void tcc_gen_makedeps(TCCState *s, const char *target, const char *filename)
1713 FILE *depout;
1714 char buf[1024], *ext;
1715 int i;
1717 if (!target)
1718 target = tcc_default_target(s);
1720 if (!filename) {
1721 /* compute filename automatically
1722 * dir/file.o -> dir/file.d */
1723 pstrcpy(buf, sizeof(buf), target);
1724 ext = tcc_fileextension(buf);
1725 pstrcpy(ext, sizeof(buf) - (ext-buf), ".d");
1726 filename = buf;
1729 if (s->verbose)
1730 printf("<- %s\n", filename);
1732 /* XXX return err codes instead of error() ? */
1733 depout = fopen(filename, "w");
1734 if (!depout)
1735 error("could not open '%s'", filename);
1737 fprintf(depout, "%s : \\\n", target);
1738 for (i=0; i<s->nb_target_deps; ++i)
1739 fprintf(depout, "\t%s \\\n", s->target_deps[i]);
1740 fprintf(depout, "\n");
1741 fclose(depout);