Optimize cstr_reset() to only reset string to empty, not call free() and later malloc()
[tinycc.git] / libtcc.c
blob6c04caa067ea6e5e0c6a4d1127a5b552843e7053
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 /********************************************************/
37 #ifndef _WIN32
38 #include <limits.h>
39 #endif
41 #ifdef ONE_SOURCE
42 #include "tccpp.c"
43 #include "tccgen.c"
44 #include "tccelf.c"
45 #include "tccrun.c"
46 #ifdef TCC_TARGET_I386
47 #include "i386-gen.c"
48 #endif
49 #ifdef TCC_TARGET_ARM
50 #include "arm-gen.c"
51 #endif
52 #ifdef TCC_TARGET_C67
53 #include "c67-gen.c"
54 #endif
55 #ifdef TCC_TARGET_X86_64
56 #include "x86_64-gen.c"
57 #endif
58 #ifdef CONFIG_TCC_ASM
59 #include "tccasm.c"
60 #if defined TCC_TARGET_I386 || defined TCC_TARGET_X86_64
61 #include "i386-asm.c"
62 #endif
63 #endif
64 #ifdef TCC_TARGET_COFF
65 #include "tcccoff.c"
66 #endif
67 #ifdef TCC_TARGET_PE
68 #include "tccpe.c"
69 #endif
70 #endif /* ONE_SOURCE */
72 /********************************************************/
73 #ifndef CONFIG_TCC_ASM
74 ST_FUNC void asm_instr(void)
76 tcc_error("inline asm() not supported");
78 ST_FUNC void asm_global_instr(void)
80 tcc_error("inline asm() not supported");
82 #endif
84 /********************************************************/
86 #ifdef _WIN32
87 static char *normalize_slashes(char *path)
89 char *p;
90 for (p = path; *p; ++p)
91 if (*p == '\\')
92 *p = '/';
93 return path;
96 static HMODULE tcc_module;
98 /* on win32, we suppose the lib and includes are at the location of 'tcc.exe' */
99 static void tcc_set_lib_path_w32(TCCState *s)
101 char path[1024], *p;
102 GetModuleFileNameA(tcc_module, path, sizeof path);
103 p = tcc_basename(normalize_slashes(strlwr(path)));
104 if (p - 5 > path && 0 == strncmp(p - 5, "/bin/", 5))
105 p -= 5;
106 else if (p > path)
107 p--;
108 *p = 0;
109 tcc_set_lib_path(s, path);
112 static void tcc_add_systemdir(TCCState *s)
114 char buf[1000];
115 GetSystemDirectory(buf, sizeof buf);
116 tcc_add_library_path(s, normalize_slashes(buf));
119 #ifndef CONFIG_TCC_STATIC
120 void dlclose(void *p)
122 FreeLibrary((HMODULE)p);
124 #endif
126 #ifdef LIBTCC_AS_DLL
127 BOOL WINAPI DllMain (HANDLE hDll, DWORD dwReason, LPVOID lpReserved)
129 if (DLL_PROCESS_ATTACH == dwReason)
130 tcc_module = hDll;
131 return TRUE;
133 #endif
134 #endif
136 /********************************************************/
137 /* copy a string and truncate it. */
138 PUB_FUNC char *pstrcpy(char *buf, int buf_size, const char *s)
140 char *q, *q_end;
141 int c;
143 if (buf_size > 0) {
144 q = buf;
145 q_end = buf + buf_size - 1;
146 while (q < q_end) {
147 c = *s++;
148 if (c == '\0')
149 break;
150 *q++ = c;
152 *q = '\0';
154 return buf;
157 /* strcat and truncate. */
158 PUB_FUNC char *pstrcat(char *buf, int buf_size, const char *s)
160 int len;
161 len = strlen(buf);
162 if (len < buf_size)
163 pstrcpy(buf + len, buf_size - len, s);
164 return buf;
167 PUB_FUNC char *pstrncpy(char *out, const char *in, size_t num)
169 memcpy(out, in, num);
170 out[num] = '\0';
171 return out;
174 /* extract the basename of a file */
175 PUB_FUNC char *tcc_basename(const char *name)
177 char *p = strchr(name, 0);
178 while (p > name && !IS_DIRSEP(p[-1]))
179 --p;
180 return p;
183 /* extract extension part of a file
185 * (if no extension, return pointer to end-of-string)
187 PUB_FUNC char *tcc_fileextension (const char *name)
189 char *b = tcc_basename(name);
190 char *e = strrchr(b, '.');
191 return e ? e : strchr(b, 0);
194 /********************************************************/
195 /* memory management */
197 #undef free
198 #undef malloc
199 #undef realloc
201 #ifdef MEM_DEBUG
202 int mem_cur_size;
203 int mem_max_size;
204 unsigned malloc_usable_size(void*);
205 #endif
207 PUB_FUNC void tcc_free(void *ptr)
209 #ifdef MEM_DEBUG
210 mem_cur_size -= malloc_usable_size(ptr);
211 #endif
212 free(ptr);
215 PUB_FUNC void *tcc_malloc(unsigned long size)
217 void *ptr;
218 ptr = malloc(size);
219 if (!ptr && size)
220 tcc_error("memory full");
221 #ifdef MEM_DEBUG
222 mem_cur_size += malloc_usable_size(ptr);
223 if (mem_cur_size > mem_max_size)
224 mem_max_size = mem_cur_size;
225 #endif
226 return ptr;
229 PUB_FUNC void *tcc_mallocz(unsigned long size)
231 void *ptr;
232 ptr = tcc_malloc(size);
233 memset(ptr, 0, size);
234 return ptr;
237 PUB_FUNC void *tcc_realloc(void *ptr, unsigned long size)
239 void *ptr1;
240 #ifdef MEM_DEBUG
241 mem_cur_size -= malloc_usable_size(ptr);
242 #endif
243 ptr1 = realloc(ptr, size);
244 if (!ptr1 && size)
245 tcc_error("memory full");
246 #ifdef MEM_DEBUG
247 /* NOTE: count not correct if alloc error, but not critical */
248 mem_cur_size += malloc_usable_size(ptr1);
249 if (mem_cur_size > mem_max_size)
250 mem_max_size = mem_cur_size;
251 #endif
252 return ptr1;
255 PUB_FUNC char *tcc_strdup(const char *str)
257 char *ptr;
258 ptr = tcc_malloc(strlen(str) + 1);
259 strcpy(ptr, str);
260 return ptr;
263 PUB_FUNC void tcc_memstats(void)
265 #ifdef MEM_DEBUG
266 printf("memory in use: %d\n", mem_cur_size);
267 #endif
270 #define free(p) use_tcc_free(p)
271 #define malloc(s) use_tcc_malloc(s)
272 #define realloc(p, s) use_tcc_realloc(p, s)
274 /********************************************************/
275 /* dynarrays */
277 PUB_FUNC void dynarray_add(void ***ptab, int *nb_ptr, void *data)
279 int nb, nb_alloc;
280 void **pp;
282 nb = *nb_ptr;
283 pp = *ptab;
284 /* every power of two we double array size */
285 if ((nb & (nb - 1)) == 0) {
286 if (!nb)
287 nb_alloc = 1;
288 else
289 nb_alloc = nb * 2;
290 pp = tcc_realloc(pp, nb_alloc * sizeof(void *));
291 *ptab = pp;
293 pp[nb++] = data;
294 *nb_ptr = nb;
297 PUB_FUNC void dynarray_reset(void *pp, int *n)
299 void **p;
300 for (p = *(void***)pp; *n; ++p, --*n)
301 if (*p)
302 tcc_free(*p);
303 tcc_free(*(void**)pp);
304 *(void**)pp = NULL;
307 static void tcc_split_path(TCCState *s, void ***p_ary, int *p_nb_ary, const char *in)
309 const char *p;
310 do {
311 int c;
312 CString str;
314 cstr_new(&str);
315 for (p = in; c = *p, c != '\0' && c != PATHSEP; ++p) {
316 if (c == '{' && p[1] && p[2] == '}') {
317 c = p[1], p += 2;
318 if (c == 'B')
319 cstr_cat(&str, s->tcc_lib_path);
320 } else {
321 cstr_ccat(&str, c);
324 cstr_ccat(&str, '\0');
325 #ifndef _WIN32
327 int i, do_include;
328 char tmp[PATH_MAX];
330 if (realpath(str.data, tmp)) {
331 str.size = 0;
332 cstr_cat(&str, tmp);
333 cstr_ccat(&str, '\0');
336 do_include = 1;
337 for (i = 0; i < *p_nb_ary && do_include; i++) {
338 do_include = do_include &&
339 strcmp((char*)str.data, (char*)(*p_ary)[i]);
342 if (do_include) {
343 dynarray_add(p_ary, p_nb_ary, str.data);
346 #else
347 dynarray_add(p_ary, p_nb_ary, str.data);
348 #endif
349 in = p+1;
350 } while (*p);
353 /********************************************************/
355 ST_FUNC Section *new_section(TCCState *s1, const char *name, int sh_type, int sh_flags)
357 Section *sec;
359 sec = tcc_mallocz(sizeof(Section) + strlen(name));
360 strcpy(sec->name, name);
361 sec->sh_type = sh_type;
362 sec->sh_flags = sh_flags;
363 switch(sh_type) {
364 case SHT_HASH:
365 case SHT_REL:
366 case SHT_RELA:
367 case SHT_DYNSYM:
368 case SHT_SYMTAB:
369 case SHT_DYNAMIC:
370 sec->sh_addralign = 4;
371 break;
372 case SHT_STRTAB:
373 sec->sh_addralign = 1;
374 break;
375 default:
376 sec->sh_addralign = 32; /* default conservative alignment */
377 break;
380 if (sh_flags & SHF_PRIVATE) {
381 dynarray_add((void ***)&s1->priv_sections, &s1->nb_priv_sections, sec);
382 } else {
383 sec->sh_num = s1->nb_sections;
384 dynarray_add((void ***)&s1->sections, &s1->nb_sections, sec);
387 return sec;
390 static void free_section(Section *s)
392 tcc_free(s->data);
395 /* realloc section and set its content to zero */
396 ST_FUNC void section_realloc(Section *sec, unsigned long new_size)
398 unsigned long size;
399 unsigned char *data;
401 size = sec->data_allocated;
402 if (size == 0)
403 size = 1;
404 while (size < new_size)
405 size = size * 2;
406 data = tcc_realloc(sec->data, size);
407 memset(data + sec->data_allocated, 0, size - sec->data_allocated);
408 sec->data = data;
409 sec->data_allocated = size;
412 /* reserve at least 'size' bytes in section 'sec' from
413 sec->data_offset. */
414 ST_FUNC void *section_ptr_add(Section *sec, unsigned long size)
416 unsigned long offset, offset1;
418 offset = sec->data_offset;
419 offset1 = offset + size;
420 if (offset1 > sec->data_allocated)
421 section_realloc(sec, offset1);
422 sec->data_offset = offset1;
423 return sec->data + offset;
426 /* reserve at least 'size' bytes from section start */
427 ST_FUNC void section_reserve(Section *sec, unsigned long size)
429 if (size > sec->data_allocated)
430 section_realloc(sec, size);
431 if (size > sec->data_offset)
432 sec->data_offset = size;
435 /* return a reference to a section, and create it if it does not
436 exists */
437 ST_FUNC Section *find_section(TCCState *s1, const char *name)
439 Section *sec;
440 int i;
441 for(i = 1; i < s1->nb_sections; i++) {
442 sec = s1->sections[i];
443 if (!strcmp(name, sec->name))
444 return sec;
446 /* sections are created as PROGBITS */
447 return new_section(s1, name, SHT_PROGBITS, SHF_ALLOC);
450 /* update sym->c so that it points to an external symbol in section
451 'section' with value 'value' */
452 ST_FUNC void put_extern_sym2(Sym *sym, Section *section,
453 uplong value, unsigned long size,
454 int can_add_underscore)
456 int sym_type, sym_bind, sh_num, info, other;
457 ElfW(Sym) *esym;
458 const char *name;
459 char buf1[256];
461 if (section == NULL)
462 sh_num = SHN_UNDEF;
463 else if (section == SECTION_ABS)
464 sh_num = SHN_ABS;
465 else
466 sh_num = section->sh_num;
468 if ((sym->type.t & VT_BTYPE) == VT_FUNC) {
469 sym_type = STT_FUNC;
470 } else if ((sym->type.t & VT_BTYPE) == VT_VOID) {
471 sym_type = STT_NOTYPE;
472 } else {
473 sym_type = STT_OBJECT;
476 if (sym->type.t & VT_STATIC)
477 sym_bind = STB_LOCAL;
478 else {
479 if (sym->type.t & VT_WEAK)
480 sym_bind = STB_WEAK;
481 else
482 sym_bind = STB_GLOBAL;
485 if (!sym->c) {
486 name = get_tok_str(sym->v, NULL);
487 #ifdef CONFIG_TCC_BCHECK
488 if (tcc_state->do_bounds_check) {
489 char buf[32];
491 /* XXX: avoid doing that for statics ? */
492 /* if bound checking is activated, we change some function
493 names by adding the "__bound" prefix */
494 switch(sym->v) {
495 #ifdef TCC_TARGET_PE
496 /* XXX: we rely only on malloc hooks */
497 case TOK_malloc:
498 case TOK_free:
499 case TOK_realloc:
500 case TOK_memalign:
501 case TOK_calloc:
502 #endif
503 case TOK_memcpy:
504 case TOK_memmove:
505 case TOK_memset:
506 case TOK_strlen:
507 case TOK_strcpy:
508 case TOK_alloca:
509 strcpy(buf, "__bound_");
510 strcat(buf, name);
511 name = buf;
512 break;
515 #endif
516 other = 0;
518 #ifdef TCC_TARGET_PE
519 if (sym->type.t & VT_EXPORT)
520 other |= 1;
521 if (sym_type == STT_FUNC && sym->type.ref) {
522 int attr = sym->type.ref->r;
523 if (FUNC_EXPORT(attr))
524 other |= 1;
525 if (FUNC_CALL(attr) == FUNC_STDCALL && can_add_underscore) {
526 sprintf(buf1, "_%s@%d", name, FUNC_ARGS(attr) * PTR_SIZE);
527 name = buf1;
528 other |= 2;
529 can_add_underscore = 0;
531 } else {
532 if (find_elf_sym(tcc_state->dynsymtab_section, name))
533 other |= 4;
534 if (sym->type.t & VT_IMPORT)
535 other |= 4;
537 #endif
538 if (tcc_state->leading_underscore && can_add_underscore) {
539 buf1[0] = '_';
540 pstrcpy(buf1 + 1, sizeof(buf1) - 1, name);
541 name = buf1;
543 if (sym->asm_label) {
544 name = sym->asm_label;
546 info = ELFW(ST_INFO)(sym_bind, sym_type);
547 sym->c = add_elf_sym(symtab_section, value, size, info, other, sh_num, name);
548 } else {
549 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
550 esym->st_value = value;
551 esym->st_size = size;
552 esym->st_shndx = sh_num;
556 ST_FUNC void put_extern_sym(Sym *sym, Section *section,
557 uplong value, unsigned long size)
559 put_extern_sym2(sym, section, value, size, 1);
562 /* add a new relocation entry to symbol 'sym' in section 's' */
563 ST_FUNC void greloc(Section *s, Sym *sym, unsigned long offset, int type)
565 int c = 0;
566 if (sym) {
567 if (0 == sym->c)
568 put_extern_sym(sym, NULL, 0, 0);
569 c = sym->c;
571 /* now we can add ELF relocation info */
572 put_elf_reloc(symtab_section, s, offset, type, c);
575 /********************************************************/
577 static void strcat_vprintf(char *buf, int buf_size, const char *fmt, va_list ap)
579 int len;
580 len = strlen(buf);
581 vsnprintf(buf + len, buf_size - len, fmt, ap);
584 static void strcat_printf(char *buf, int buf_size, const char *fmt, ...)
586 va_list ap;
587 va_start(ap, fmt);
588 strcat_vprintf(buf, buf_size, fmt, ap);
589 va_end(ap);
592 static void error1(TCCState *s1, int is_warning, const char *fmt, va_list ap)
594 char buf[2048];
595 BufferedFile **f;
597 buf[0] = '\0';
598 if (file) {
599 for(f = s1->include_stack; f < s1->include_stack_ptr; f++)
600 strcat_printf(buf, sizeof(buf), "In file included from %s:%d:\n",
601 (*f)->filename, (*f)->line_num);
602 if (file->line_num > 0) {
603 strcat_printf(buf, sizeof(buf),
604 "%s:%d: ", file->filename, file->line_num);
605 } else {
606 strcat_printf(buf, sizeof(buf),
607 "%s: ", file->filename);
609 } else {
610 strcat_printf(buf, sizeof(buf),
611 "tcc: ");
613 if (is_warning)
614 strcat_printf(buf, sizeof(buf), "warning: ");
615 else
616 strcat_printf(buf, sizeof(buf), "error: ");
617 strcat_vprintf(buf, sizeof(buf), fmt, ap);
619 if (!s1->error_func) {
620 /* default case: stderr */
621 fprintf(stderr, "%s\n", buf);
622 } else {
623 s1->error_func(s1->error_opaque, buf);
625 if (!is_warning || s1->warn_error)
626 s1->nb_errors++;
629 LIBTCCAPI void tcc_set_error_func(TCCState *s, void *error_opaque,
630 void (*error_func)(void *opaque, const char *msg))
632 s->error_opaque = error_opaque;
633 s->error_func = error_func;
636 /* error without aborting current compilation */
637 PUB_FUNC void tcc_error_noabort(const char *fmt, ...)
639 TCCState *s1 = tcc_state;
640 va_list ap;
642 va_start(ap, fmt);
643 error1(s1, 0, fmt, ap);
644 va_end(ap);
647 PUB_FUNC void tcc_error(const char *fmt, ...)
649 TCCState *s1 = tcc_state;
650 va_list ap;
652 va_start(ap, fmt);
653 error1(s1, 0, fmt, ap);
654 va_end(ap);
655 /* better than nothing: in some cases, we accept to handle errors */
656 if (s1->error_set_jmp_enabled) {
657 longjmp(s1->error_jmp_buf, 1);
658 } else {
659 /* XXX: eliminate this someday */
660 exit(1);
664 PUB_FUNC void tcc_warning(const char *fmt, ...)
666 TCCState *s1 = tcc_state;
667 va_list ap;
669 if (s1->warn_none)
670 return;
672 va_start(ap, fmt);
673 error1(s1, 1, fmt, ap);
674 va_end(ap);
677 /********************************************************/
678 /* I/O layer */
680 ST_FUNC void tcc_open_bf(TCCState *s1, const char *filename, int initlen)
682 BufferedFile *bf;
683 int buflen = initlen ? initlen : IO_BUF_SIZE;
685 bf = tcc_malloc(sizeof(BufferedFile) + buflen);
686 bf->buf_ptr = bf->buffer;
687 bf->buf_end = bf->buffer + initlen;
688 bf->buf_end[0] = CH_EOB; /* put eob symbol */
689 pstrcpy(bf->filename, sizeof(bf->filename), filename);
690 #ifdef _WIN32
691 normalize_slashes(bf->filename);
692 #endif
693 bf->line_num = 1;
694 bf->ifndef_macro = 0;
695 bf->ifdef_stack_ptr = s1->ifdef_stack_ptr;
696 bf->fd = -1;
697 bf->prev = file;
698 file = bf;
701 ST_FUNC void tcc_close(void)
703 BufferedFile *bf = file;
704 if (bf->fd > 0) {
705 close(bf->fd);
706 total_lines += bf->line_num;
708 file = bf->prev;
709 tcc_free(bf);
712 ST_FUNC int tcc_open(TCCState *s1, const char *filename)
714 int fd;
715 if (strcmp(filename, "-") == 0)
716 fd = 0, filename = "stdin";
717 else
718 fd = open(filename, O_RDONLY | O_BINARY);
719 if ((s1->verbose == 2 && fd >= 0) || s1->verbose == 3)
720 printf("%s %*s%s\n", fd < 0 ? "nf":"->",
721 (int)(s1->include_stack_ptr - s1->include_stack), "", filename);
722 if (fd < 0)
723 return -1;
725 tcc_open_bf(s1, filename, 0);
726 file->fd = fd;
727 return fd;
730 /* compile the C file opened in 'file'. Return non zero if errors. */
731 static int tcc_compile(TCCState *s1)
733 Sym *define_start;
734 SValue *pvtop;
735 char buf[512];
736 volatile int section_sym;
738 #ifdef INC_DEBUG
739 printf("%s: **** new file\n", file->filename);
740 #endif
741 preprocess_init(s1);
743 cur_text_section = NULL;
744 funcname = "";
745 anon_sym = SYM_FIRST_ANOM;
747 /* file info: full path + filename */
748 section_sym = 0; /* avoid warning */
749 if (s1->do_debug) {
750 section_sym = put_elf_sym(symtab_section, 0, 0,
751 ELFW(ST_INFO)(STB_LOCAL, STT_SECTION), 0,
752 text_section->sh_num, NULL);
753 getcwd(buf, sizeof(buf));
754 #ifdef _WIN32
755 normalize_slashes(buf);
756 #endif
757 pstrcat(buf, sizeof(buf), "/");
758 put_stabs_r(buf, N_SO, 0, 0,
759 text_section->data_offset, text_section, section_sym);
760 put_stabs_r(file->filename, N_SO, 0, 0,
761 text_section->data_offset, text_section, section_sym);
763 /* an elf symbol of type STT_FILE must be put so that STB_LOCAL
764 symbols can be safely used */
765 put_elf_sym(symtab_section, 0, 0,
766 ELFW(ST_INFO)(STB_LOCAL, STT_FILE), 0,
767 SHN_ABS, file->filename);
769 /* define some often used types */
770 int_type.t = VT_INT;
772 char_pointer_type.t = VT_BYTE;
773 mk_pointer(&char_pointer_type);
775 #if PTR_SIZE == 4
776 size_type.t = VT_INT;
777 #else
778 size_type.t = VT_LLONG;
779 #endif
781 func_old_type.t = VT_FUNC;
782 func_old_type.ref = sym_push(SYM_FIELD, &int_type, FUNC_CDECL, FUNC_OLD);
784 #if defined(TCC_ARM_EABI) && defined(TCC_ARM_VFP)
785 float_type.t = VT_FLOAT;
786 double_type.t = VT_DOUBLE;
788 func_float_type.t = VT_FUNC;
789 func_float_type.ref = sym_push(SYM_FIELD, &float_type, FUNC_CDECL, FUNC_OLD);
790 func_double_type.t = VT_FUNC;
791 func_double_type.ref = sym_push(SYM_FIELD, &double_type, FUNC_CDECL, FUNC_OLD);
792 #endif
794 #if 0
795 /* define 'void *alloca(unsigned int)' builtin function */
797 Sym *s1;
799 p = anon_sym++;
800 sym = sym_push(p, mk_pointer(VT_VOID), FUNC_CDECL, FUNC_NEW);
801 s1 = sym_push(SYM_FIELD, VT_UNSIGNED | VT_INT, 0, 0);
802 s1->next = NULL;
803 sym->next = s1;
804 sym_push(TOK_alloca, VT_FUNC | (p << VT_STRUCT_SHIFT), VT_CONST, 0);
806 #endif
808 define_start = define_stack;
809 nocode_wanted = 1;
811 if (setjmp(s1->error_jmp_buf) == 0) {
812 s1->nb_errors = 0;
813 s1->error_set_jmp_enabled = 1;
815 ch = file->buf_ptr[0];
816 tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
817 parse_flags = PARSE_FLAG_PREPROCESS | PARSE_FLAG_TOK_NUM;
818 pvtop = vtop;
819 next();
820 decl(VT_CONST);
821 if (tok != TOK_EOF)
822 expect("declaration");
823 if (pvtop != vtop)
824 tcc_warning("internal compiler error: vstack leak? (%d)", vtop - pvtop);
826 /* end of translation unit info */
827 if (s1->do_debug) {
828 put_stabs_r(NULL, N_SO, 0, 0,
829 text_section->data_offset, text_section, section_sym);
833 s1->error_set_jmp_enabled = 0;
835 /* reset define stack, but leave -Dsymbols (may be incorrect if
836 they are undefined) */
837 free_defines(define_start);
839 gen_inline_functions();
841 sym_pop(&global_stack, NULL);
842 sym_pop(&local_stack, NULL);
844 return s1->nb_errors != 0 ? -1 : 0;
847 LIBTCCAPI int tcc_compile_string(TCCState *s, const char *str)
849 int len, ret;
850 len = strlen(str);
852 tcc_open_bf(s, "<string>", len);
853 memcpy(file->buffer, str, len);
854 ret = tcc_compile(s);
855 tcc_close();
856 return ret;
859 /* define a preprocessor symbol. A value can also be provided with the '=' operator */
860 LIBTCCAPI void tcc_define_symbol(TCCState *s1, const char *sym, const char *value)
862 int len1, len2;
863 /* default value */
864 if (!value)
865 value = "1";
866 len1 = strlen(sym);
867 len2 = strlen(value);
869 /* init file structure */
870 tcc_open_bf(s1, "<define>", len1 + len2 + 1);
871 memcpy(file->buffer, sym, len1);
872 file->buffer[len1] = ' ';
873 memcpy(file->buffer + len1 + 1, value, len2);
875 /* parse with define parser */
876 ch = file->buf_ptr[0];
877 next_nomacro();
878 parse_define();
880 tcc_close();
883 /* undefine a preprocessor symbol */
884 LIBTCCAPI void tcc_undefine_symbol(TCCState *s1, const char *sym)
886 TokenSym *ts;
887 Sym *s;
888 ts = tok_alloc(sym, strlen(sym));
889 s = define_find(ts->tok);
890 /* undefine symbol by putting an invalid name */
891 if (s)
892 define_undef(s);
895 static void tcc_cleanup(void)
897 int i, n;
899 if (NULL == tcc_state)
900 return;
901 tcc_state = NULL;
903 /* free -D defines */
904 free_defines(NULL);
906 /* free tokens */
907 n = tok_ident - TOK_IDENT;
908 for(i = 0; i < n; i++)
909 tcc_free(table_ident[i]);
910 tcc_free(table_ident);
912 /* free sym_pools */
913 dynarray_reset(&sym_pools, &nb_sym_pools);
914 /* string buffer */
915 cstr_free(&tokcstr);
916 /* reset symbol stack */
917 sym_free_first = NULL;
918 /* cleanup from error/setjmp */
919 macro_ptr = NULL;
922 LIBTCCAPI TCCState *tcc_new(void)
924 TCCState *s;
925 char buffer[100];
926 int a,b,c;
928 tcc_cleanup();
930 s = tcc_mallocz(sizeof(TCCState));
931 if (!s)
932 return NULL;
933 tcc_state = s;
934 #ifdef _WIN32
935 tcc_set_lib_path_w32(s);
936 #else
937 tcc_set_lib_path(s, CONFIG_TCCDIR);
938 #endif
939 s->output_type = TCC_OUTPUT_MEMORY;
940 preprocess_new();
941 s->include_stack_ptr = s->include_stack;
943 /* we add dummy defines for some special macros to speed up tests
944 and to have working defined() */
945 define_push(TOK___LINE__, MACRO_OBJ, NULL, NULL);
946 define_push(TOK___FILE__, MACRO_OBJ, NULL, NULL);
947 define_push(TOK___DATE__, MACRO_OBJ, NULL, NULL);
948 define_push(TOK___TIME__, MACRO_OBJ, NULL, NULL);
950 /* standard defines */
951 tcc_define_symbol(s, "__STDC__", NULL);
952 tcc_define_symbol(s, "__STDC_VERSION__", "199901L");
953 #if defined(TCC_TARGET_I386)
954 tcc_define_symbol(s, "__i386__", NULL);
955 tcc_define_symbol(s, "__i386", NULL);
956 tcc_define_symbol(s, "i386", NULL);
957 #endif
958 #if defined(TCC_TARGET_X86_64)
959 tcc_define_symbol(s, "__x86_64__", NULL);
960 #endif
961 #if defined(TCC_TARGET_ARM)
962 tcc_define_symbol(s, "__ARM_ARCH_4__", NULL);
963 tcc_define_symbol(s, "__arm_elf__", NULL);
964 tcc_define_symbol(s, "__arm_elf", NULL);
965 tcc_define_symbol(s, "arm_elf", NULL);
966 tcc_define_symbol(s, "__arm__", NULL);
967 tcc_define_symbol(s, "__arm", NULL);
968 tcc_define_symbol(s, "arm", NULL);
969 tcc_define_symbol(s, "__APCS_32__", NULL);
970 #endif
971 #ifdef TCC_TARGET_PE
972 tcc_define_symbol(s, "_WIN32", NULL);
973 #ifdef TCC_TARGET_X86_64
974 tcc_define_symbol(s, "_WIN64", NULL);
975 #endif
976 #else
977 tcc_define_symbol(s, "__unix__", NULL);
978 tcc_define_symbol(s, "__unix", NULL);
979 tcc_define_symbol(s, "unix", NULL);
980 #if defined(__FreeBSD__)
981 #define str(s) #s
982 tcc_define_symbol(s, "__FreeBSD__", str( __FreeBSD__));
983 #undef str
984 #endif
985 #if defined(__FreeBSD_kernel__)
986 tcc_define_symbol(s, "__FreeBSD_kernel__", NULL);
987 #endif
988 #if defined(__linux)
989 tcc_define_symbol(s, "__linux__", NULL);
990 tcc_define_symbol(s, "__linux", NULL);
991 #endif
992 #endif
993 /* tiny C specific defines */
994 sscanf(TCC_VERSION, "%d.%d.%d", &a, &b, &c);
995 sprintf(buffer, "%d", a*10000 + b*100 + c);
996 tcc_define_symbol(s, "__TINYC__", buffer);
998 /* tiny C & gcc defines */
999 #if defined TCC_TARGET_PE && defined TCC_TARGET_X86_64
1000 tcc_define_symbol(s, "__SIZE_TYPE__", "unsigned long long");
1001 tcc_define_symbol(s, "__PTRDIFF_TYPE__", "long long");
1002 #else
1003 tcc_define_symbol(s, "__SIZE_TYPE__", "unsigned long");
1004 tcc_define_symbol(s, "__PTRDIFF_TYPE__", "long");
1005 #endif
1007 #ifdef TCC_TARGET_PE
1008 tcc_define_symbol(s, "__WCHAR_TYPE__", "unsigned short");
1009 #else
1010 tcc_define_symbol(s, "__WCHAR_TYPE__", "int");
1011 #endif
1013 /* glibc defines */
1014 tcc_define_symbol(s, "__REDIRECT(name, proto, alias)", "name proto __asm__ (#alias)");
1015 tcc_define_symbol(s, "__REDIRECT_NTH(name, proto, alias)", "name proto __asm__ (#alias) __THROW");
1017 #ifndef TCC_TARGET_PE
1018 /* default library paths */
1019 tcc_add_library_path(s, CONFIG_TCC_LIBPATHS);
1020 /* paths for crt objects */
1021 tcc_split_path(s, (void ***)&s->crt_paths, &s->nb_crt_paths, CONFIG_TCC_CRTPREFIX);
1022 #endif
1024 /* no section zero */
1025 dynarray_add((void ***)&s->sections, &s->nb_sections, NULL);
1027 /* create standard sections */
1028 text_section = new_section(s, ".text", SHT_PROGBITS, SHF_ALLOC | SHF_EXECINSTR);
1029 data_section = new_section(s, ".data", SHT_PROGBITS, SHF_ALLOC | SHF_WRITE);
1030 bss_section = new_section(s, ".bss", SHT_NOBITS, SHF_ALLOC | SHF_WRITE);
1032 /* symbols are always generated for linking stage */
1033 symtab_section = new_symtab(s, ".symtab", SHT_SYMTAB, 0,
1034 ".strtab",
1035 ".hashtab", SHF_PRIVATE);
1036 strtab_section = symtab_section->link;
1037 s->symtab = symtab_section;
1039 /* private symbol table for dynamic symbols */
1040 s->dynsymtab_section = new_symtab(s, ".dynsymtab", SHT_SYMTAB, SHF_PRIVATE,
1041 ".dynstrtab",
1042 ".dynhashtab", SHF_PRIVATE);
1043 s->alacarte_link = 1;
1044 s->nocommon = 1;
1046 #ifdef CHAR_IS_UNSIGNED
1047 s->char_is_unsigned = 1;
1048 #endif
1049 /* enable this if you want symbols with leading underscore on windows: */
1050 #if defined(TCC_TARGET_PE) && 0
1051 s->leading_underscore = 1;
1052 #endif
1053 if (s->section_align == 0)
1054 s->section_align = ELF_PAGE_SIZE;
1055 #ifdef TCC_TARGET_I386
1056 s->seg_size = 32;
1057 #endif
1058 return s;
1061 LIBTCCAPI void tcc_delete(TCCState *s1)
1063 int i;
1065 tcc_cleanup();
1067 /* free all sections */
1068 for(i = 1; i < s1->nb_sections; i++)
1069 free_section(s1->sections[i]);
1070 dynarray_reset(&s1->sections, &s1->nb_sections);
1072 for(i = 0; i < s1->nb_priv_sections; i++)
1073 free_section(s1->priv_sections[i]);
1074 dynarray_reset(&s1->priv_sections, &s1->nb_priv_sections);
1076 /* free any loaded DLLs */
1077 for ( i = 0; i < s1->nb_loaded_dlls; i++) {
1078 DLLReference *ref = s1->loaded_dlls[i];
1079 if ( ref->handle )
1080 dlclose(ref->handle);
1083 /* free loaded dlls array */
1084 dynarray_reset(&s1->loaded_dlls, &s1->nb_loaded_dlls);
1086 /* free library paths */
1087 dynarray_reset(&s1->library_paths, &s1->nb_library_paths);
1088 dynarray_reset(&s1->crt_paths, &s1->nb_crt_paths);
1090 /* free include paths */
1091 dynarray_reset(&s1->cached_includes, &s1->nb_cached_includes);
1092 dynarray_reset(&s1->include_paths, &s1->nb_include_paths);
1093 dynarray_reset(&s1->sysinclude_paths, &s1->nb_sysinclude_paths);
1095 dynarray_reset(&s1->target_deps, &s1->nb_target_deps);
1097 tcc_free(s1->tcc_lib_path);
1099 #ifdef HAVE_SELINUX
1100 munmap (s1->write_mem, s1->mem_size);
1101 munmap (s1->runtime_mem, s1->mem_size);
1102 #else
1103 tcc_free(s1->runtime_mem);
1104 #endif
1105 tcc_free(s1);
1108 LIBTCCAPI int tcc_add_include_path(TCCState *s, const char *pathname)
1110 tcc_split_path(s, (void ***)&s->include_paths, &s->nb_include_paths, pathname);
1111 return 0;
1114 LIBTCCAPI int tcc_add_sysinclude_path(TCCState *s, const char *pathname)
1116 tcc_split_path(s, (void ***)&s->sysinclude_paths, &s->nb_sysinclude_paths, pathname);
1117 return 0;
1120 ST_FUNC int tcc_add_file_internal(TCCState *s1, const char *filename, int flags)
1122 const char *ext;
1123 ElfW(Ehdr) ehdr;
1124 int fd, ret, size;
1126 /* find source file type with extension */
1127 ext = tcc_fileextension(filename);
1128 if (ext[0])
1129 ext++;
1131 #ifdef CONFIG_TCC_ASM
1132 /* if .S file, define __ASSEMBLER__ like gcc does */
1133 if (!strcmp(ext, "S"))
1134 tcc_define_symbol(s1, "__ASSEMBLER__", NULL);
1135 #endif
1137 /* open the file */
1138 ret = tcc_open(s1, filename);
1139 if (ret < 0) {
1140 if (flags & AFF_PRINT_ERROR)
1141 tcc_error_noabort("file '%s' not found", filename);
1142 return ret;
1145 /* update target deps */
1146 dynarray_add((void ***)&s1->target_deps, &s1->nb_target_deps,
1147 tcc_strdup(filename));
1149 if (flags & AFF_PREPROCESS) {
1150 ret = tcc_preprocess(s1);
1151 goto the_end;
1154 if (!ext[0] || !PATHCMP(ext, "c")) {
1155 /* C file assumed */
1156 ret = tcc_compile(s1);
1157 goto the_end;
1160 #ifdef CONFIG_TCC_ASM
1161 if (!strcmp(ext, "S")) {
1162 /* preprocessed assembler */
1163 ret = tcc_assemble(s1, 1);
1164 goto the_end;
1167 if (!strcmp(ext, "s")) {
1168 /* non preprocessed assembler */
1169 ret = tcc_assemble(s1, 0);
1170 goto the_end;
1172 #endif
1174 fd = file->fd;
1175 /* assume executable format: auto guess file type */
1176 size = read(fd, &ehdr, sizeof(ehdr));
1177 lseek(fd, 0, SEEK_SET);
1178 if (size <= 0) {
1179 tcc_error_noabort("could not read header");
1180 goto the_end;
1183 if (size == sizeof(ehdr) &&
1184 ehdr.e_ident[0] == ELFMAG0 &&
1185 ehdr.e_ident[1] == ELFMAG1 &&
1186 ehdr.e_ident[2] == ELFMAG2 &&
1187 ehdr.e_ident[3] == ELFMAG3) {
1189 /* do not display line number if error */
1190 file->line_num = 0;
1191 if (ehdr.e_type == ET_REL) {
1192 ret = tcc_load_object_file(s1, fd, 0);
1193 goto the_end;
1196 #ifndef TCC_TARGET_PE
1197 if (ehdr.e_type == ET_DYN) {
1198 if (s1->output_type == TCC_OUTPUT_MEMORY) {
1199 void *h;
1200 h = dlopen(filename, RTLD_GLOBAL | RTLD_LAZY);
1201 if (h)
1202 ret = 0;
1203 } else {
1204 ret = tcc_load_dll(s1, fd, filename,
1205 (flags & AFF_REFERENCED_DLL) != 0);
1207 goto the_end;
1209 #endif
1210 tcc_error_noabort("unrecognized ELF file");
1211 goto the_end;
1214 if (memcmp((char *)&ehdr, ARMAG, 8) == 0) {
1215 file->line_num = 0; /* do not display line number if error */
1216 ret = tcc_load_archive(s1, fd);
1217 goto the_end;
1220 #ifdef TCC_TARGET_COFF
1221 if (*(uint16_t *)(&ehdr) == COFF_C67_MAGIC) {
1222 ret = tcc_load_coff(s1, fd);
1223 goto the_end;
1225 #endif
1227 #ifdef TCC_TARGET_PE
1228 ret = pe_load_file(s1, filename, fd);
1229 #else
1230 /* as GNU ld, consider it is an ld script if not recognized */
1231 ret = tcc_load_ldscript(s1);
1232 #endif
1233 if (ret < 0)
1234 tcc_error_noabort("unrecognized file type");
1236 the_end:
1237 tcc_close();
1238 return ret;
1241 LIBTCCAPI int tcc_add_file(TCCState *s, const char *filename)
1243 if (s->output_type == TCC_OUTPUT_PREPROCESS)
1244 return tcc_add_file_internal(s, filename, AFF_PRINT_ERROR | AFF_PREPROCESS);
1245 else
1246 return tcc_add_file_internal(s, filename, AFF_PRINT_ERROR);
1249 LIBTCCAPI int tcc_add_library_path(TCCState *s, const char *pathname)
1251 tcc_split_path(s, (void ***)&s->library_paths, &s->nb_library_paths, pathname);
1252 return 0;
1255 static int tcc_add_library_internal(TCCState *s, const char *fmt,
1256 const char *filename, int flags, char **paths, int nb_paths)
1258 char buf[1024];
1259 int i;
1261 for(i = 0; i < nb_paths; i++) {
1262 snprintf(buf, sizeof(buf), fmt, paths[i], filename);
1263 if (tcc_add_file_internal(s, buf, flags) == 0)
1264 return 0;
1266 return -1;
1269 #ifndef TCC_TARGET_PE
1270 /* find and load a dll. Return non zero if not found */
1271 /* XXX: add '-rpath' option support ? */
1272 ST_FUNC int tcc_add_dll(TCCState *s, const char *filename, int flags)
1274 return tcc_add_library_internal(s, "%s/%s", filename, flags,
1275 s->library_paths, s->nb_library_paths);
1277 #endif
1279 ST_FUNC int tcc_add_crt(TCCState *s, const char *filename)
1281 if (-1 == tcc_add_library_internal(s, "%s/%s",
1282 filename, 0, s->crt_paths, s->nb_crt_paths))
1283 tcc_error_noabort("file '%s' not found", filename);
1284 return 0;
1287 /* the library name is the same as the argument of the '-l' option */
1288 LIBTCCAPI int tcc_add_library(TCCState *s, const char *libraryname)
1290 #ifdef TCC_TARGET_PE
1291 const char *libs[] = { "%s/%s.def", "%s/lib%s.def", "%s/%s.dll", "%s/lib%s.dll", "%s/lib%s.a", NULL };
1292 const char **pp = s->static_link ? libs + 4 : libs;
1293 #else
1294 const char *libs[] = { "%s/lib%s.so", "%s/lib%s.a", NULL };
1295 const char **pp = s->static_link ? libs + 1 : libs;
1296 #endif
1297 while (*pp) {
1298 if (0 == tcc_add_library_internal(s, *pp,
1299 libraryname, 0, s->library_paths, s->nb_library_paths))
1300 return 0;
1301 ++pp;
1303 return -1;
1306 LIBTCCAPI int tcc_add_symbol(TCCState *s, const char *name, const void *val)
1308 #ifdef TCC_TARGET_PE
1309 pe_putimport(s, 0, name, val);
1310 #else
1311 add_elf_sym(symtab_section, (uplong)val, 0,
1312 ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE), 0,
1313 SHN_ABS, name);
1314 #endif
1315 return 0;
1318 LIBTCCAPI int tcc_set_output_type(TCCState *s, int output_type)
1320 s->output_type = output_type;
1322 if (!s->nostdinc) {
1323 /* default include paths */
1324 /* -isystem paths have already been handled */
1325 tcc_add_sysinclude_path(s, CONFIG_TCC_SYSINCLUDEPATHS);
1328 /* if bound checking, then add corresponding sections */
1329 #ifdef CONFIG_TCC_BCHECK
1330 if (s->do_bounds_check) {
1331 /* define symbol */
1332 tcc_define_symbol(s, "__BOUNDS_CHECKING_ON", NULL);
1333 /* create bounds sections */
1334 bounds_section = new_section(s, ".bounds",
1335 SHT_PROGBITS, SHF_ALLOC);
1336 lbounds_section = new_section(s, ".lbounds",
1337 SHT_PROGBITS, SHF_ALLOC);
1339 #endif
1341 if (s->char_is_unsigned) {
1342 tcc_define_symbol(s, "__CHAR_UNSIGNED__", NULL);
1345 /* add debug sections */
1346 if (s->do_debug) {
1347 /* stab symbols */
1348 stab_section = new_section(s, ".stab", SHT_PROGBITS, 0);
1349 stab_section->sh_entsize = sizeof(Stab_Sym);
1350 stabstr_section = new_section(s, ".stabstr", SHT_STRTAB, 0);
1351 put_elf_str(stabstr_section, "");
1352 stab_section->link = stabstr_section;
1353 /* put first entry */
1354 put_stabs("", 0, 0, 0, 0);
1357 #ifdef TCC_TARGET_PE
1358 tcc_add_library_path(s, CONFIG_TCC_LIBPATHS);
1359 # ifdef _WIN32
1360 tcc_add_systemdir(s);
1361 # endif
1362 #else
1363 /* add libc crt1/crti objects */
1364 if ((output_type == TCC_OUTPUT_EXE || output_type == TCC_OUTPUT_DLL) &&
1365 !s->nostdlib) {
1366 if (output_type != TCC_OUTPUT_DLL)
1367 tcc_add_crt(s, "crt1.o");
1368 tcc_add_crt(s, "crti.o");
1370 #endif
1371 return 0;
1374 #define WD_ALL 0x0001 /* warning is activated when using -Wall */
1375 #define FD_INVERT 0x0002 /* invert value before storing */
1377 typedef struct FlagDef {
1378 uint16_t offset;
1379 uint16_t flags;
1380 const char *name;
1381 } FlagDef;
1383 static const FlagDef warning_defs[] = {
1384 { offsetof(TCCState, warn_unsupported), 0, "unsupported" },
1385 { offsetof(TCCState, warn_write_strings), 0, "write-strings" },
1386 { offsetof(TCCState, warn_error), 0, "error" },
1387 { offsetof(TCCState, warn_implicit_function_declaration), WD_ALL,
1388 "implicit-function-declaration" },
1391 ST_FUNC int set_flag(TCCState *s, const FlagDef *flags, int nb_flags,
1392 const char *name, int value)
1394 int i;
1395 const FlagDef *p;
1396 const char *r;
1398 r = name;
1399 if (r[0] == 'n' && r[1] == 'o' && r[2] == '-') {
1400 r += 3;
1401 value = !value;
1403 for(i = 0, p = flags; i < nb_flags; i++, p++) {
1404 if (!strcmp(r, p->name))
1405 goto found;
1407 return -1;
1408 found:
1409 if (p->flags & FD_INVERT)
1410 value = !value;
1411 *(int *)((uint8_t *)s + p->offset) = value;
1412 return 0;
1415 /* enable debug */
1416 LIBTCCAPI void tcc_enable_debug(TCCState *s)
1418 s->do_debug = 1;
1421 /* set/reset a warning */
1422 LIBTCCAPI int tcc_set_warning(TCCState *s, const char *warning_name, int value)
1424 int i;
1425 const FlagDef *p;
1427 if (!strcmp(warning_name, "all")) {
1428 for(i = 0, p = warning_defs; i < countof(warning_defs); i++, p++) {
1429 if (p->flags & WD_ALL)
1430 *(int *)((uint8_t *)s + p->offset) = 1;
1432 return 0;
1433 } else {
1434 return set_flag(s, warning_defs, countof(warning_defs),
1435 warning_name, value);
1439 static const FlagDef flag_defs[] = {
1440 { offsetof(TCCState, char_is_unsigned), 0, "unsigned-char" },
1441 { offsetof(TCCState, char_is_unsigned), FD_INVERT, "signed-char" },
1442 { offsetof(TCCState, nocommon), FD_INVERT, "common" },
1443 { offsetof(TCCState, leading_underscore), 0, "leading-underscore" },
1446 /* set/reset a flag */
1447 PUB_FUNC int tcc_set_flag(TCCState *s, const char *flag_name, int value)
1449 return set_flag(s, flag_defs, countof(flag_defs),
1450 flag_name, value);
1454 static int strstart(const char *str, const char *val, char **ptr)
1456 const char *p, *q;
1457 p = str;
1458 q = val;
1459 while (*q != '\0') {
1460 if (*p != *q)
1461 return 0;
1462 p++;
1463 q++;
1465 if (ptr)
1466 *ptr = (char *) p;
1467 return 1;
1471 /* Like strstart, but automatically takes into account that ld options can
1473 * - start with double or single dash (e.g. '--soname' or '-soname')
1474 * - arguments can be given as separate or after '=' (e.g. '-Wl,-soname,x.so'
1475 * or '-Wl,-soname=x.so')
1477 * you provide `val` always in 'option[=]' form (no leading -)
1479 static int link_option(const char *str, const char *val, char **ptr)
1481 const char *p, *q;
1483 /* there should be 1 or 2 dashes */
1484 if (*str++ != '-')
1485 return 0;
1486 if (*str == '-')
1487 str++;
1489 /* then str & val should match (potentialy up to '=') */
1490 p = str;
1491 q = val;
1493 while (*q != '\0' && *q != '=') {
1494 if (*p != *q)
1495 return 0;
1496 p++;
1497 q++;
1500 /* '=' near eos means ',' or '=' is ok */
1501 if (*q == '=') {
1502 if (*p != ',' && *p != '=')
1503 return 0;
1504 p++;
1505 q++;
1508 if (ptr)
1509 *ptr = (char *) p;
1510 return 1;
1514 /* set linker options */
1515 PUB_FUNC const char * tcc_set_linker(TCCState *s, char *option, int multi)
1517 char *p = option;
1518 char *end;
1520 while (option && *option) {
1521 end = NULL;
1522 if (link_option(option, "Bsymbolic", &p)) {
1523 s->symbolic = TRUE;
1524 } else if (link_option(option, "nostdlib", &p)) {
1525 s->nostdlib = TRUE;
1526 } else if (link_option(option, "fini=", &p)) {
1527 s->fini_symbol = p;
1528 if (s->warn_unsupported)
1529 tcc_warning("ignoring -fini %s", p);
1530 } else if (link_option(option, "image-base=", &p)) {
1531 s->text_addr = strtoull(p, &end, 16);
1532 s->has_text_addr = 1;
1533 } else if (link_option(option, "init=", &p)) {
1534 s->init_symbol = p;
1535 if (s->warn_unsupported)
1536 tcc_warning("ignoring -init %s", p);
1537 } else if (link_option(option, "oformat=", &p)) {
1538 #if defined(TCC_TARGET_PE)
1539 if (strstart(p, "pe-", NULL)) {
1540 #else
1541 #if defined(TCC_TARGET_X86_64)
1542 if (strstart(p, "elf64-", NULL)) {
1543 #else
1544 if (strstart(p, "elf32-", NULL)) {
1545 #endif
1546 #endif
1547 s->output_format = TCC_OUTPUT_FORMAT_ELF;
1548 } else if (!strcmp(p, "binary")) {
1549 s->output_format = TCC_OUTPUT_FORMAT_BINARY;
1550 } else
1551 #ifdef TCC_TARGET_COFF
1552 if (!strcmp(p, "coff")) {
1553 s->output_format = TCC_OUTPUT_FORMAT_COFF;
1554 } else
1555 #endif
1557 return p;
1560 } else if (link_option(option, "rpath=", &p)) {
1561 s->rpath = p;
1562 } else if (link_option(option, "section-alignment=", &p)) {
1563 s->section_align = strtoul(p, &end, 16);
1564 } else if (link_option(option, "soname=", &p)) {
1565 s->soname = p;
1566 multi = 0;
1567 #ifdef TCC_TARGET_PE
1568 } else if (link_option(option, "file-alignment=", &p)) {
1569 s->pe_file_align = strtoul(p, &end, 16);
1570 } else if (link_option(option, "stack=", &p)) {
1571 s->pe_stack_size = strtoul(p, &end, 10);
1572 } else if (link_option(option, "subsystem=", &p)) {
1573 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
1574 if (!strcmp(p, "native")) {
1575 s->pe_subsystem = 1;
1576 } else if (!strcmp(p, "console")) {
1577 s->pe_subsystem = 3;
1578 } else if (!strcmp(p, "gui")) {
1579 s->pe_subsystem = 2;
1580 } else if (!strcmp(p, "posix")) {
1581 s->pe_subsystem = 7;
1582 } else if (!strcmp(p, "efiapp")) {
1583 s->pe_subsystem = 10;
1584 } else if (!strcmp(p, "efiboot")) {
1585 s->pe_subsystem = 11;
1586 } else if (!strcmp(p, "efiruntime")) {
1587 s->pe_subsystem = 12;
1588 } else if (!strcmp(p, "efirom")) {
1589 s->pe_subsystem = 13;
1590 #elif defined(TCC_TARGET_ARM)
1591 if (!strcmp(p, "wince")) {
1592 s->pe_subsystem = 9;
1593 #endif
1594 } else {
1595 return p;
1597 #endif
1599 } else if (link_option(option, "Ttext=", &p)) {
1600 s->text_addr = strtoull(p, &end, 16);
1601 s->has_text_addr = 1;
1602 } else {
1603 char *comma_ptr = strchr(option, ',');
1604 if (comma_ptr)
1605 *comma_ptr = '\0';
1606 return option;
1609 if (multi) {
1610 option = NULL;
1611 p = strchr( (end) ? end : p, ',');
1612 if (p) {
1613 *p = 0; /* terminate last option */
1614 option = ++p;
1616 } else
1617 option = NULL;
1619 return NULL;
1622 PUB_FUNC void tcc_print_stats(TCCState *s, int64_t total_time)
1624 double tt;
1625 tt = (double)total_time / 1000000.0;
1626 if (tt < 0.001)
1627 tt = 0.001;
1628 if (total_bytes < 1)
1629 total_bytes = 1;
1630 printf("%d idents, %d lines, %d bytes, %0.3f s, %d lines/s, %0.1f MB/s\n",
1631 tok_ident - TOK_IDENT, total_lines, total_bytes,
1632 tt, (int)(total_lines / tt),
1633 total_bytes / tt / 1000000.0);
1636 /* set CONFIG_TCCDIR at runtime */
1637 LIBTCCAPI void tcc_set_lib_path(TCCState *s, const char *path)
1639 tcc_free(s->tcc_lib_path);
1640 s->tcc_lib_path = tcc_strdup(path);
1643 PUB_FUNC char *tcc_default_target(TCCState *s, const char *default_file)
1645 char buf[1024];
1646 char *ext;
1647 const char *name = "a";
1649 if (default_file && strcmp(default_file, "-"))
1650 name = tcc_basename(default_file);
1651 pstrcpy(buf, sizeof(buf), name);
1652 ext = tcc_fileextension(buf);
1653 #ifdef TCC_TARGET_PE
1654 if (s->output_type == TCC_OUTPUT_DLL)
1655 strcpy(ext, ".dll");
1656 else
1657 if (s->output_type == TCC_OUTPUT_EXE)
1658 strcpy(ext, ".exe");
1659 else
1660 #endif
1661 if (( (s->output_type == TCC_OUTPUT_OBJ && !s->reloc_output) ||
1662 (s->output_type == TCC_OUTPUT_PREPROCESS) )
1663 && *ext)
1664 strcpy(ext, ".o");
1665 else
1666 pstrcpy(buf, sizeof(buf), "a.out");
1668 return tcc_strdup(buf);
1672 PUB_FUNC void tcc_gen_makedeps(TCCState *s, const char *target, const char *filename)
1674 FILE *depout;
1675 char buf[1024], *ext;
1676 int i;
1678 if (!filename) {
1679 /* compute filename automatically
1680 * dir/file.o -> dir/file.d */
1681 pstrcpy(buf, sizeof(buf), target);
1682 ext = tcc_fileextension(buf);
1683 pstrcpy(ext, sizeof(buf) - (ext-buf), ".d");
1684 filename = buf;
1687 if (s->verbose)
1688 printf("<- %s\n", filename);
1690 /* XXX return err codes instead of error() ? */
1691 depout = fopen(filename, "w");
1692 if (!depout)
1693 tcc_error("could not open '%s'", filename);
1695 fprintf(depout, "%s : \\\n", target);
1696 for (i=0; i<s->nb_target_deps; ++i)
1697 fprintf(depout, " %s \\\n", s->target_deps[i]);
1698 fprintf(depout, "\n");
1699 fclose(depout);