libtcc.c: report vstack "leaks" only if compile succeeded
[tinycc.git] / libtcc.c
blobd15a09b7b6539ebcf9b460d181e74ba256c98e54
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 #ifndef NOTALLINONE
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 /* we use our own 'finite' function to avoid potential problems with
296 non standard math libs */
297 /* XXX: endianness dependent */
298 ST_FUNC int ieee_finite(double d)
300 int *p = (int *)&d;
301 return ((unsigned)((p[1] | 0x800fffff) + 1)) >> 31;
304 /********************************************************/
306 ST_FUNC Section *new_section(TCCState *s1, const char *name, int sh_type, int sh_flags)
308 Section *sec;
310 sec = tcc_mallocz(sizeof(Section) + strlen(name));
311 strcpy(sec->name, name);
312 sec->sh_type = sh_type;
313 sec->sh_flags = sh_flags;
314 switch(sh_type) {
315 case SHT_HASH:
316 case SHT_REL:
317 case SHT_RELA:
318 case SHT_DYNSYM:
319 case SHT_SYMTAB:
320 case SHT_DYNAMIC:
321 sec->sh_addralign = 4;
322 break;
323 case SHT_STRTAB:
324 sec->sh_addralign = 1;
325 break;
326 default:
327 sec->sh_addralign = 32; /* default conservative alignment */
328 break;
331 if (sh_flags & SHF_PRIVATE) {
332 dynarray_add((void ***)&s1->priv_sections, &s1->nb_priv_sections, sec);
333 } else {
334 sec->sh_num = s1->nb_sections;
335 dynarray_add((void ***)&s1->sections, &s1->nb_sections, sec);
338 return sec;
341 static void free_section(Section *s)
343 tcc_free(s->data);
346 /* realloc section and set its content to zero */
347 ST_FUNC void section_realloc(Section *sec, unsigned long new_size)
349 unsigned long size;
350 unsigned char *data;
352 size = sec->data_allocated;
353 if (size == 0)
354 size = 1;
355 while (size < new_size)
356 size = size * 2;
357 data = tcc_realloc(sec->data, size);
358 if (!data)
359 error("memory full");
360 memset(data + sec->data_allocated, 0, size - sec->data_allocated);
361 sec->data = data;
362 sec->data_allocated = size;
365 /* reserve at least 'size' bytes in section 'sec' from
366 sec->data_offset. */
367 ST_FUNC void *section_ptr_add(Section *sec, unsigned long size)
369 unsigned long offset, offset1;
371 offset = sec->data_offset;
372 offset1 = offset + size;
373 if (offset1 > sec->data_allocated)
374 section_realloc(sec, offset1);
375 sec->data_offset = offset1;
376 return sec->data + offset;
379 /* reserve at least 'size' bytes from section start */
380 ST_FUNC void section_reserve(Section *sec, unsigned long size)
382 if (size > sec->data_allocated)
383 section_realloc(sec, size);
384 if (size > sec->data_offset)
385 sec->data_offset = size;
388 /* return a reference to a section, and create it if it does not
389 exists */
390 ST_FUNC Section *find_section(TCCState *s1, const char *name)
392 Section *sec;
393 int i;
394 for(i = 1; i < s1->nb_sections; i++) {
395 sec = s1->sections[i];
396 if (!strcmp(name, sec->name))
397 return sec;
399 /* sections are created as PROGBITS */
400 return new_section(s1, name, SHT_PROGBITS, SHF_ALLOC);
403 /* update sym->c so that it points to an external symbol in section
404 'section' with value 'value' */
405 ST_FUNC void put_extern_sym2(Sym *sym, Section *section,
406 unsigned long value, unsigned long size,
407 int can_add_underscore)
409 int sym_type, sym_bind, sh_num, info, other;
410 ElfW(Sym) *esym;
411 const char *name;
412 char buf1[256];
414 if (section == NULL)
415 sh_num = SHN_UNDEF;
416 else if (section == SECTION_ABS)
417 sh_num = SHN_ABS;
418 else
419 sh_num = section->sh_num;
421 if ((sym->type.t & VT_BTYPE) == VT_FUNC) {
422 sym_type = STT_FUNC;
423 } else if ((sym->type.t & VT_BTYPE) == VT_VOID) {
424 sym_type = STT_NOTYPE;
425 } else {
426 sym_type = STT_OBJECT;
429 if (sym->type.t & VT_STATIC)
430 sym_bind = STB_LOCAL;
431 else {
432 if (sym->type.t & VT_WEAK)
433 sym_bind = STB_WEAK;
434 else
435 sym_bind = STB_GLOBAL;
438 if (!sym->c) {
439 name = get_tok_str(sym->v, NULL);
440 #ifdef CONFIG_TCC_BCHECK
441 if (tcc_state->do_bounds_check) {
442 char buf[32];
444 /* XXX: avoid doing that for statics ? */
445 /* if bound checking is activated, we change some function
446 names by adding the "__bound" prefix */
447 switch(sym->v) {
448 #ifdef TCC_TARGET_PE
449 /* XXX: we rely only on malloc hooks */
450 case TOK_malloc:
451 case TOK_free:
452 case TOK_realloc:
453 case TOK_memalign:
454 case TOK_calloc:
455 #endif
456 case TOK_memcpy:
457 case TOK_memmove:
458 case TOK_memset:
459 case TOK_strlen:
460 case TOK_strcpy:
461 case TOK_alloca:
462 strcpy(buf, "__bound_");
463 strcat(buf, name);
464 name = buf;
465 break;
468 #endif
469 other = 0;
471 #ifdef TCC_TARGET_PE
472 if (sym->type.t & VT_EXPORT)
473 other |= 1;
474 if (sym_type == STT_FUNC && sym->type.ref) {
475 int attr = sym->type.ref->r;
476 if (FUNC_EXPORT(attr))
477 other |= 1;
478 if (FUNC_CALL(attr) == FUNC_STDCALL && can_add_underscore) {
479 sprintf(buf1, "_%s@%d", name, FUNC_ARGS(attr) * PTR_SIZE);
480 name = buf1;
481 other |= 2;
482 can_add_underscore = 0;
484 } else {
485 if (find_elf_sym(tcc_state->dynsymtab_section, name))
486 other |= 4;
487 if (sym->type.t & VT_IMPORT)
488 other |= 4;
490 #endif
491 if (tcc_state->leading_underscore && can_add_underscore) {
492 buf1[0] = '_';
493 pstrcpy(buf1 + 1, sizeof(buf1) - 1, name);
494 name = buf1;
496 if (sym->asm_label) {
497 name = sym->asm_label;
499 info = ELFW(ST_INFO)(sym_bind, sym_type);
500 sym->c = add_elf_sym(symtab_section, value, size, info, other, sh_num, name);
501 } else {
502 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
503 esym->st_value = value;
504 esym->st_size = size;
505 esym->st_shndx = sh_num;
509 ST_FUNC void put_extern_sym(Sym *sym, Section *section,
510 unsigned long value, unsigned long size)
512 put_extern_sym2(sym, section, value, size, 1);
515 /* add a new relocation entry to symbol 'sym' in section 's' */
516 ST_FUNC void greloc(Section *s, Sym *sym, unsigned long offset, int type)
518 int c = 0;
519 if (sym) {
520 if (0 == sym->c)
521 put_extern_sym(sym, NULL, 0, 0);
522 c = sym->c;
524 /* now we can add ELF relocation info */
525 put_elf_reloc(symtab_section, s, offset, type, c);
528 /********************************************************/
530 static void strcat_vprintf(char *buf, int buf_size, const char *fmt, va_list ap)
532 int len;
533 len = strlen(buf);
534 vsnprintf(buf + len, buf_size - len, fmt, ap);
537 static void strcat_printf(char *buf, int buf_size, const char *fmt, ...)
539 va_list ap;
540 va_start(ap, fmt);
541 strcat_vprintf(buf, buf_size, fmt, ap);
542 va_end(ap);
545 static void error1(TCCState *s1, int is_warning, const char *fmt, va_list ap)
547 char buf[2048];
548 BufferedFile **f;
550 buf[0] = '\0';
551 if (file) {
552 for(f = s1->include_stack; f < s1->include_stack_ptr; f++)
553 strcat_printf(buf, sizeof(buf), "In file included from %s:%d:\n",
554 (*f)->filename, (*f)->line_num);
555 if (file->line_num > 0) {
556 strcat_printf(buf, sizeof(buf),
557 "%s:%d: ", file->filename, file->line_num);
558 } else {
559 strcat_printf(buf, sizeof(buf),
560 "%s: ", file->filename);
562 } else {
563 strcat_printf(buf, sizeof(buf),
564 "tcc: ");
566 if (is_warning)
567 strcat_printf(buf, sizeof(buf), "warning: ");
568 else
569 strcat_printf(buf, sizeof(buf), "error: ");
570 strcat_vprintf(buf, sizeof(buf), fmt, ap);
572 if (!s1->error_func) {
573 /* default case: stderr */
574 fprintf(stderr, "%s\n", buf);
575 } else {
576 s1->error_func(s1->error_opaque, buf);
578 if (!is_warning || s1->warn_error)
579 s1->nb_errors++;
582 LIBTCCAPI void tcc_set_error_func(TCCState *s, void *error_opaque,
583 void (*error_func)(void *opaque, const char *msg))
585 s->error_opaque = error_opaque;
586 s->error_func = error_func;
589 /* error without aborting current compilation */
590 PUB_FUNC void error_noabort(const char *fmt, ...)
592 TCCState *s1 = tcc_state;
593 va_list ap;
595 va_start(ap, fmt);
596 error1(s1, 0, fmt, ap);
597 va_end(ap);
600 PUB_FUNC void error(const char *fmt, ...)
602 TCCState *s1 = tcc_state;
603 va_list ap;
605 va_start(ap, fmt);
606 error1(s1, 0, fmt, ap);
607 va_end(ap);
608 /* better than nothing: in some cases, we accept to handle errors */
609 if (s1->error_set_jmp_enabled) {
610 longjmp(s1->error_jmp_buf, 1);
611 } else {
612 /* XXX: eliminate this someday */
613 exit(1);
617 PUB_FUNC void expect(const char *msg)
619 error("%s expected", msg);
622 PUB_FUNC void warning(const char *fmt, ...)
624 TCCState *s1 = tcc_state;
625 va_list ap;
627 if (s1->warn_none)
628 return;
630 va_start(ap, fmt);
631 error1(s1, 1, fmt, ap);
632 va_end(ap);
635 /********************************************************/
636 /* I/O layer */
638 ST_FUNC void tcc_open_bf(TCCState *s1, const char *filename, int initlen)
640 BufferedFile *bf;
641 int buflen = initlen ? initlen : IO_BUF_SIZE;
643 bf = tcc_malloc(sizeof(BufferedFile) + buflen);
644 bf->buf_ptr = bf->buffer;
645 bf->buf_end = bf->buffer + initlen;
646 bf->buf_end[0] = CH_EOB; /* put eob symbol */
647 pstrcpy(bf->filename, sizeof(bf->filename), filename);
648 #ifdef _WIN32
649 normalize_slashes(bf->filename);
650 #endif
651 bf->line_num = 1;
652 bf->ifndef_macro = 0;
653 bf->ifdef_stack_ptr = s1->ifdef_stack_ptr;
654 bf->fd = -1;
655 bf->prev = file;
656 file = bf;
659 ST_FUNC void tcc_close(void)
661 BufferedFile *bf = file;
662 if (bf->fd > 0) {
663 close(bf->fd);
664 total_lines += bf->line_num;
666 file = bf->prev;
667 tcc_free(bf);
670 ST_FUNC int tcc_open(TCCState *s1, const char *filename)
672 int fd;
673 if (strcmp(filename, "-") == 0)
674 fd = 0, filename = "stdin";
675 else
676 fd = open(filename, O_RDONLY | O_BINARY);
677 if ((s1->verbose == 2 && fd >= 0) || s1->verbose == 3)
678 printf("%s %*s%s\n", fd < 0 ? "nf":"->",
679 (int)(s1->include_stack_ptr - s1->include_stack), "", filename);
680 if (fd < 0)
681 return -1;
683 tcc_open_bf(s1, filename, 0);
684 file->fd = fd;
685 return fd;
688 /* compile the C file opened in 'file'. Return non zero if errors. */
689 static int tcc_compile(TCCState *s1)
691 Sym *define_start;
692 SValue *pvtop;
693 char buf[512];
694 volatile int section_sym;
696 #ifdef INC_DEBUG
697 printf("%s: **** new file\n", file->filename);
698 #endif
699 preprocess_init(s1);
701 cur_text_section = NULL;
702 funcname = "";
703 anon_sym = SYM_FIRST_ANOM;
705 /* file info: full path + filename */
706 section_sym = 0; /* avoid warning */
707 if (s1->do_debug) {
708 section_sym = put_elf_sym(symtab_section, 0, 0,
709 ELFW(ST_INFO)(STB_LOCAL, STT_SECTION), 0,
710 text_section->sh_num, NULL);
711 getcwd(buf, sizeof(buf));
712 #ifdef _WIN32
713 normalize_slashes(buf);
714 #endif
715 pstrcat(buf, sizeof(buf), "/");
716 put_stabs_r(buf, N_SO, 0, 0,
717 text_section->data_offset, text_section, section_sym);
718 put_stabs_r(file->filename, N_SO, 0, 0,
719 text_section->data_offset, text_section, section_sym);
721 /* an elf symbol of type STT_FILE must be put so that STB_LOCAL
722 symbols can be safely used */
723 put_elf_sym(symtab_section, 0, 0,
724 ELFW(ST_INFO)(STB_LOCAL, STT_FILE), 0,
725 SHN_ABS, file->filename);
727 /* define some often used types */
728 int_type.t = VT_INT;
730 char_pointer_type.t = VT_BYTE;
731 mk_pointer(&char_pointer_type);
733 func_old_type.t = VT_FUNC;
734 func_old_type.ref = sym_push(SYM_FIELD, &int_type, FUNC_CDECL, FUNC_OLD);
736 #if defined(TCC_ARM_EABI) && defined(TCC_ARM_VFP)
737 float_type.t = VT_FLOAT;
738 double_type.t = VT_DOUBLE;
740 func_float_type.t = VT_FUNC;
741 func_float_type.ref = sym_push(SYM_FIELD, &float_type, FUNC_CDECL, FUNC_OLD);
742 func_double_type.t = VT_FUNC;
743 func_double_type.ref = sym_push(SYM_FIELD, &double_type, FUNC_CDECL, FUNC_OLD);
744 #endif
746 #if 0
747 /* define 'void *alloca(unsigned int)' builtin function */
749 Sym *s1;
751 p = anon_sym++;
752 sym = sym_push(p, mk_pointer(VT_VOID), FUNC_CDECL, FUNC_NEW);
753 s1 = sym_push(SYM_FIELD, VT_UNSIGNED | VT_INT, 0, 0);
754 s1->next = NULL;
755 sym->next = s1;
756 sym_push(TOK_alloca, VT_FUNC | (p << VT_STRUCT_SHIFT), VT_CONST, 0);
758 #endif
760 define_start = define_stack;
761 nocode_wanted = 1;
762 pvtop = vtop;
764 if (setjmp(s1->error_jmp_buf) == 0) {
765 s1->nb_errors = 0;
766 s1->error_set_jmp_enabled = 1;
768 ch = file->buf_ptr[0];
769 tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
770 parse_flags = PARSE_FLAG_PREPROCESS | PARSE_FLAG_TOK_NUM;
771 next();
772 decl(VT_CONST);
773 if (tok != TOK_EOF)
774 expect("declaration");
776 /* end of translation unit info */
777 if (s1->do_debug) {
778 put_stabs_r(NULL, N_SO, 0, 0,
779 text_section->data_offset, text_section, section_sym);
781 } else if (pvtop != vtop) {
782 warning("internal compiler error: vstack leak? (%d)", vtop - pvtop);
785 s1->error_set_jmp_enabled = 0;
787 /* reset define stack, but leave -Dsymbols (may be incorrect if
788 they are undefined) */
789 free_defines(define_start);
791 gen_inline_functions();
793 sym_pop(&global_stack, NULL);
794 sym_pop(&local_stack, NULL);
796 return s1->nb_errors != 0 ? -1 : 0;
799 LIBTCCAPI int tcc_compile_string(TCCState *s, const char *str)
801 int len, ret;
802 len = strlen(str);
804 tcc_open_bf(s, "<string>", len);
805 memcpy(file->buffer, str, len);
806 ret = tcc_compile(s);
807 tcc_close();
808 return ret;
811 /* define a preprocessor symbol. A value can also be provided with the '=' operator */
812 LIBTCCAPI void tcc_define_symbol(TCCState *s1, const char *sym, const char *value)
814 int len1, len2;
815 /* default value */
816 if (!value)
817 value = "1";
818 len1 = strlen(sym);
819 len2 = strlen(value);
821 /* init file structure */
822 tcc_open_bf(s1, "<define>", len1 + len2 + 1);
823 memcpy(file->buffer, sym, len1);
824 file->buffer[len1] = ' ';
825 memcpy(file->buffer + len1 + 1, value, len2);
827 /* parse with define parser */
828 ch = file->buf_ptr[0];
829 next_nomacro();
830 parse_define();
832 tcc_close();
835 /* undefine a preprocessor symbol */
836 LIBTCCAPI void tcc_undefine_symbol(TCCState *s1, const char *sym)
838 TokenSym *ts;
839 Sym *s;
840 ts = tok_alloc(sym, strlen(sym));
841 s = define_find(ts->tok);
842 /* undefine symbol by putting an invalid name */
843 if (s)
844 define_undef(s);
847 static void tcc_cleanup(void)
849 int i, n;
851 if (NULL == tcc_state)
852 return;
853 tcc_state = NULL;
855 /* free -D defines */
856 free_defines(NULL);
858 /* free tokens */
859 n = tok_ident - TOK_IDENT;
860 for(i = 0; i < n; i++)
861 tcc_free(table_ident[i]);
862 tcc_free(table_ident);
864 /* free sym_pools */
865 dynarray_reset(&sym_pools, &nb_sym_pools);
866 /* string buffer */
867 cstr_free(&tokcstr);
868 /* reset symbol stack */
869 sym_free_first = NULL;
870 /* cleanup from error/setjmp */
871 macro_ptr = NULL;
874 LIBTCCAPI TCCState *tcc_new(void)
876 TCCState *s;
877 char buffer[100];
878 int a,b,c;
880 tcc_cleanup();
882 s = tcc_mallocz(sizeof(TCCState));
883 if (!s)
884 return NULL;
885 tcc_state = s;
886 #ifdef _WIN32
887 tcc_set_lib_path_w32(s);
888 #else
889 tcc_set_lib_path(s, CONFIG_TCCDIR);
890 #endif
891 s->output_type = TCC_OUTPUT_MEMORY;
892 preprocess_new();
893 s->include_stack_ptr = s->include_stack;
895 /* we add dummy defines for some special macros to speed up tests
896 and to have working defined() */
897 define_push(TOK___LINE__, MACRO_OBJ, NULL, NULL);
898 define_push(TOK___FILE__, MACRO_OBJ, NULL, NULL);
899 define_push(TOK___DATE__, MACRO_OBJ, NULL, NULL);
900 define_push(TOK___TIME__, MACRO_OBJ, NULL, NULL);
902 /* standard defines */
903 tcc_define_symbol(s, "__STDC__", NULL);
904 tcc_define_symbol(s, "__STDC_VERSION__", "199901L");
905 #if defined(TCC_TARGET_I386)
906 tcc_define_symbol(s, "__i386__", NULL);
907 tcc_define_symbol(s, "__i386", NULL);
908 tcc_define_symbol(s, "i386", NULL);
909 #endif
910 #if defined(TCC_TARGET_X86_64)
911 tcc_define_symbol(s, "__x86_64__", NULL);
912 #endif
913 #if defined(TCC_TARGET_ARM)
914 tcc_define_symbol(s, "__ARM_ARCH_4__", NULL);
915 tcc_define_symbol(s, "__arm_elf__", NULL);
916 tcc_define_symbol(s, "__arm_elf", NULL);
917 tcc_define_symbol(s, "arm_elf", NULL);
918 tcc_define_symbol(s, "__arm__", NULL);
919 tcc_define_symbol(s, "__arm", NULL);
920 tcc_define_symbol(s, "arm", NULL);
921 tcc_define_symbol(s, "__APCS_32__", NULL);
922 #endif
923 #ifdef TCC_TARGET_PE
924 tcc_define_symbol(s, "_WIN32", NULL);
925 #ifdef TCC_TARGET_X86_64
926 tcc_define_symbol(s, "_WIN64", NULL);
927 #endif
928 #else
929 tcc_define_symbol(s, "__unix__", NULL);
930 tcc_define_symbol(s, "__unix", NULL);
931 tcc_define_symbol(s, "unix", NULL);
932 #if defined(__FreeBSD__)
933 #define str(s) #s
934 tcc_define_symbol(s, "__FreeBSD__", str( __FreeBSD__));
935 #undef str
936 #endif
937 #if defined(__FreeBSD_kernel__)
938 tcc_define_symbol(s, "__FreeBSD_kernel__", NULL);
939 #endif
940 #if defined(__linux)
941 tcc_define_symbol(s, "__linux__", NULL);
942 tcc_define_symbol(s, "__linux", NULL);
943 #endif
944 #endif
945 /* tiny C specific defines */
946 sscanf(TCC_VERSION, "%d.%d.%d", &a, &b, &c);
947 sprintf(buffer, "%d", a*10000 + b*100 + c);
948 tcc_define_symbol(s, "__TINYC__", buffer);
950 /* tiny C & gcc defines */
951 #if defined TCC_TARGET_PE && defined TCC_TARGET_X86_64
952 tcc_define_symbol(s, "__SIZE_TYPE__", "unsigned long long");
953 tcc_define_symbol(s, "__PTRDIFF_TYPE__", "long long");
954 #else
955 tcc_define_symbol(s, "__SIZE_TYPE__", "unsigned long");
956 tcc_define_symbol(s, "__PTRDIFF_TYPE__", "long");
957 #endif
959 #ifdef TCC_TARGET_PE
960 tcc_define_symbol(s, "__WCHAR_TYPE__", "unsigned short");
961 #else
962 tcc_define_symbol(s, "__WCHAR_TYPE__", "int");
963 #endif
965 /* glibc defines */
966 tcc_define_symbol(s, "__REDIRECT_NTH(name, proto, alias)", "name proto __asm__ (#alias) __THROW");
968 #ifndef TCC_TARGET_PE
969 /* default library paths */
970 tcc_add_library_path(s, CONFIG_TCC_CRT_PREFIX);
971 tcc_add_library_path(s, CONFIG_SYSROOT CONFIG_TCC_LDDIR);
972 tcc_add_library_path(s, CONFIG_SYSROOT "/usr/local"CONFIG_TCC_LDDIR);
973 #endif
975 /* no section zero */
976 dynarray_add((void ***)&s->sections, &s->nb_sections, NULL);
978 /* create standard sections */
979 text_section = new_section(s, ".text", SHT_PROGBITS, SHF_ALLOC | SHF_EXECINSTR);
980 data_section = new_section(s, ".data", SHT_PROGBITS, SHF_ALLOC | SHF_WRITE);
981 bss_section = new_section(s, ".bss", SHT_NOBITS, SHF_ALLOC | SHF_WRITE);
983 /* symbols are always generated for linking stage */
984 symtab_section = new_symtab(s, ".symtab", SHT_SYMTAB, 0,
985 ".strtab",
986 ".hashtab", SHF_PRIVATE);
987 strtab_section = symtab_section->link;
989 /* private symbol table for dynamic symbols */
990 s->dynsymtab_section = new_symtab(s, ".dynsymtab", SHT_SYMTAB, SHF_PRIVATE,
991 ".dynstrtab",
992 ".dynhashtab", SHF_PRIVATE);
993 s->alacarte_link = 1;
994 s->nocommon = 1;
996 #ifdef CHAR_IS_UNSIGNED
997 s->char_is_unsigned = 1;
998 #endif
999 /* enable this if you want symbols with leading underscore on windows: */
1000 #if defined(TCC_TARGET_PE) && 0
1001 s->leading_underscore = 1;
1002 #endif
1003 if (s->section_align == 0)
1004 s->section_align = ELF_PAGE_SIZE;
1005 #ifdef TCC_TARGET_I386
1006 s->seg_size = 32;
1007 #endif
1008 return s;
1011 LIBTCCAPI void tcc_delete(TCCState *s1)
1013 int i;
1015 tcc_cleanup();
1017 /* free all sections */
1018 for(i = 1; i < s1->nb_sections; i++)
1019 free_section(s1->sections[i]);
1020 dynarray_reset(&s1->sections, &s1->nb_sections);
1022 for(i = 0; i < s1->nb_priv_sections; i++)
1023 free_section(s1->priv_sections[i]);
1024 dynarray_reset(&s1->priv_sections, &s1->nb_priv_sections);
1026 /* free any loaded DLLs */
1027 for ( i = 0; i < s1->nb_loaded_dlls; i++) {
1028 DLLReference *ref = s1->loaded_dlls[i];
1029 if ( ref->handle )
1030 dlclose(ref->handle);
1033 /* free loaded dlls array */
1034 dynarray_reset(&s1->loaded_dlls, &s1->nb_loaded_dlls);
1036 /* free library paths */
1037 dynarray_reset(&s1->library_paths, &s1->nb_library_paths);
1039 /* free include paths */
1040 dynarray_reset(&s1->cached_includes, &s1->nb_cached_includes);
1041 dynarray_reset(&s1->include_paths, &s1->nb_include_paths);
1042 dynarray_reset(&s1->sysinclude_paths, &s1->nb_sysinclude_paths);
1044 tcc_free(s1->tcc_lib_path);
1046 dynarray_reset(&s1->input_files, &s1->nb_input_files);
1047 dynarray_reset(&s1->input_libs, &s1->nb_input_libs);
1048 dynarray_reset(&s1->target_deps, &s1->nb_target_deps);
1050 #ifdef HAVE_SELINUX
1051 munmap (s1->write_mem, s1->mem_size);
1052 munmap (s1->runtime_mem, s1->mem_size);
1053 #else
1054 tcc_free(s1->runtime_mem);
1055 #endif
1056 tcc_free(s1);
1059 LIBTCCAPI int tcc_add_include_path(TCCState *s1, const char *pathname)
1061 char *pathname1;
1063 pathname1 = tcc_strdup(pathname);
1064 dynarray_add((void ***)&s1->include_paths, &s1->nb_include_paths, pathname1);
1065 return 0;
1068 LIBTCCAPI int tcc_add_sysinclude_path(TCCState *s1, const char *pathname)
1070 char *pathname1;
1072 pathname1 = tcc_strdup(pathname);
1073 dynarray_add((void ***)&s1->sysinclude_paths, &s1->nb_sysinclude_paths, pathname1);
1074 return 0;
1077 ST_FUNC int tcc_add_file_internal(TCCState *s1, const char *filename, int flags)
1079 const char *ext;
1080 ElfW(Ehdr) ehdr;
1081 int fd, ret, size;
1083 /* find source file type with extension */
1084 ext = tcc_fileextension(filename);
1085 if (ext[0])
1086 ext++;
1088 #ifdef CONFIG_TCC_ASM
1089 /* if .S file, define __ASSEMBLER__ like gcc does */
1090 if (!strcmp(ext, "S"))
1091 tcc_define_symbol(s1, "__ASSEMBLER__", NULL);
1092 #endif
1094 /* open the file */
1095 ret = tcc_open(s1, filename);
1096 if (ret < 0) {
1097 if (flags & AFF_PRINT_ERROR)
1098 error_noabort("file '%s' not found", filename);
1099 return ret;
1102 /* update target deps */
1103 dynarray_add((void ***)&s1->target_deps, &s1->nb_target_deps,
1104 tcc_strdup(filename));
1106 if (flags & AFF_PREPROCESS) {
1107 ret = tcc_preprocess(s1);
1108 goto the_end;
1111 if (!ext[0] || !PATHCMP(ext, "c")) {
1112 /* C file assumed */
1113 ret = tcc_compile(s1);
1114 goto the_end;
1117 #ifdef CONFIG_TCC_ASM
1118 if (!strcmp(ext, "S")) {
1119 /* preprocessed assembler */
1120 ret = tcc_assemble(s1, 1);
1121 goto the_end;
1124 if (!strcmp(ext, "s")) {
1125 /* non preprocessed assembler */
1126 ret = tcc_assemble(s1, 0);
1127 goto the_end;
1129 #endif
1131 fd = file->fd;
1132 /* assume executable format: auto guess file type */
1133 size = read(fd, &ehdr, sizeof(ehdr));
1134 lseek(fd, 0, SEEK_SET);
1135 if (size <= 0) {
1136 error_noabort("could not read header");
1137 goto the_end;
1140 if (size == sizeof(ehdr) &&
1141 ehdr.e_ident[0] == ELFMAG0 &&
1142 ehdr.e_ident[1] == ELFMAG1 &&
1143 ehdr.e_ident[2] == ELFMAG2 &&
1144 ehdr.e_ident[3] == ELFMAG3) {
1146 /* do not display line number if error */
1147 file->line_num = 0;
1148 if (ehdr.e_type == ET_REL) {
1149 ret = tcc_load_object_file(s1, fd, 0);
1150 goto the_end;
1153 #ifndef TCC_TARGET_PE
1154 if (ehdr.e_type == ET_DYN) {
1155 if (s1->output_type == TCC_OUTPUT_MEMORY) {
1156 void *h;
1157 h = dlopen(filename, RTLD_GLOBAL | RTLD_LAZY);
1158 if (h)
1159 ret = 0;
1160 } else {
1161 ret = tcc_load_dll(s1, fd, filename,
1162 (flags & AFF_REFERENCED_DLL) != 0);
1164 goto the_end;
1166 #endif
1167 error_noabort("unrecognized ELF file");
1168 goto the_end;
1171 if (memcmp((char *)&ehdr, ARMAG, 8) == 0) {
1172 file->line_num = 0; /* do not display line number if error */
1173 ret = tcc_load_archive(s1, fd);
1174 goto the_end;
1177 #ifdef TCC_TARGET_COFF
1178 if (*(uint16_t *)(&ehdr) == COFF_C67_MAGIC) {
1179 ret = tcc_load_coff(s1, fd);
1180 goto the_end;
1182 #endif
1184 #ifdef TCC_TARGET_PE
1185 ret = pe_load_file(s1, filename, fd);
1186 #else
1187 /* as GNU ld, consider it is an ld script if not recognized */
1188 ret = tcc_load_ldscript(s1);
1189 #endif
1190 if (ret < 0)
1191 error_noabort("unrecognized file type");
1193 the_end:
1194 tcc_close();
1195 return ret;
1198 LIBTCCAPI int tcc_add_file(TCCState *s, const char *filename)
1200 dynarray_add((void ***)&s->input_files, &s->nb_input_files, tcc_strdup(filename));
1202 if (s->output_type == TCC_OUTPUT_PREPROCESS)
1203 return tcc_add_file_internal(s, filename, AFF_PRINT_ERROR | AFF_PREPROCESS);
1204 else
1205 return tcc_add_file_internal(s, filename, AFF_PRINT_ERROR);
1208 LIBTCCAPI int tcc_add_library_path(TCCState *s, const char *pathname)
1210 char *pathname1;
1212 pathname1 = tcc_strdup(pathname);
1213 dynarray_add((void ***)&s->library_paths, &s->nb_library_paths, pathname1);
1214 return 0;
1217 /* find and load a dll. Return non zero if not found */
1218 /* XXX: add '-rpath' option support ? */
1219 ST_FUNC int tcc_add_dll(TCCState *s, const char *filename, int flags)
1221 char buf[1024];
1222 int i;
1224 for(i = 0; i < s->nb_library_paths; i++) {
1225 snprintf(buf, sizeof(buf), "%s/%s",
1226 s->library_paths[i], filename);
1227 if (tcc_add_file_internal(s, buf, flags) == 0)
1228 return 0;
1230 return -1;
1233 /* the library name is the same as the argument of the '-l' option */
1234 LIBTCCAPI int tcc_add_library(TCCState *s, const char *libraryname)
1236 char buf[1024];
1237 int i;
1239 dynarray_add((void ***)&s->input_libs, &s->nb_input_libs, tcc_strdup(libraryname));
1241 /* first we look for the dynamic library if not static linking */
1242 if (!s->static_link) {
1243 #ifdef TCC_TARGET_PE
1244 if (pe_add_dll(s, libraryname) == 0)
1245 return 0;
1246 #else
1247 snprintf(buf, sizeof(buf), "lib%s.so", libraryname);
1248 if (tcc_add_dll(s, buf, 0) == 0)
1249 return 0;
1250 #endif
1252 /* then we look for the static library */
1253 for(i = 0; i < s->nb_library_paths; i++) {
1254 snprintf(buf, sizeof(buf), "%s/lib%s.a",
1255 s->library_paths[i], libraryname);
1256 if (tcc_add_file_internal(s, buf, 0) == 0)
1257 return 0;
1259 return -1;
1262 LIBTCCAPI int tcc_add_symbol(TCCState *s, const char *name, const void *val)
1264 #ifdef TCC_TARGET_PE
1265 pe_putimport(s, 0, name, val);
1266 #else
1267 add_elf_sym(symtab_section, (uplong)val, 0,
1268 ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE), 0,
1269 SHN_ABS, name);
1270 #endif
1271 return 0;
1274 LIBTCCAPI int tcc_set_output_type(TCCState *s, int output_type)
1276 char buf[1024];
1278 s->output_type = output_type;
1280 if (!s->nostdinc) {
1281 /* default include paths */
1282 /* -isystem paths have already been handled */
1283 #ifndef TCC_TARGET_PE
1284 tcc_add_sysinclude_path(s, CONFIG_SYSROOT "/usr/local/include");
1285 tcc_add_sysinclude_path(s, CONFIG_SYSROOT "/usr/include");
1286 #endif
1287 snprintf(buf, sizeof(buf), "%s/include", s->tcc_lib_path);
1288 tcc_add_sysinclude_path(s, buf);
1289 #ifdef TCC_TARGET_PE
1290 snprintf(buf, sizeof(buf), "%s/include/winapi", s->tcc_lib_path);
1291 tcc_add_sysinclude_path(s, buf);
1292 #endif
1295 /* if bound checking, then add corresponding sections */
1296 #ifdef CONFIG_TCC_BCHECK
1297 if (s->do_bounds_check) {
1298 /* define symbol */
1299 tcc_define_symbol(s, "__BOUNDS_CHECKING_ON", NULL);
1300 /* create bounds sections */
1301 bounds_section = new_section(s, ".bounds",
1302 SHT_PROGBITS, SHF_ALLOC);
1303 lbounds_section = new_section(s, ".lbounds",
1304 SHT_PROGBITS, SHF_ALLOC);
1306 #endif
1308 if (s->char_is_unsigned) {
1309 tcc_define_symbol(s, "__CHAR_UNSIGNED__", NULL);
1312 /* add debug sections */
1313 if (s->do_debug) {
1314 /* stab symbols */
1315 stab_section = new_section(s, ".stab", SHT_PROGBITS, 0);
1316 stab_section->sh_entsize = sizeof(Stab_Sym);
1317 stabstr_section = new_section(s, ".stabstr", SHT_STRTAB, 0);
1318 put_elf_str(stabstr_section, "");
1319 stab_section->link = stabstr_section;
1320 /* put first entry */
1321 put_stabs("", 0, 0, 0, 0);
1324 /* add libc crt1/crti objects */
1325 #ifndef TCC_TARGET_PE
1326 if ((output_type == TCC_OUTPUT_EXE || output_type == TCC_OUTPUT_DLL) &&
1327 !s->nostdlib) {
1328 if (output_type != TCC_OUTPUT_DLL)
1329 tcc_add_file(s, CONFIG_TCC_CRT_PREFIX "/crt1.o");
1330 tcc_add_file(s, CONFIG_TCC_CRT_PREFIX "/crti.o");
1332 #endif
1334 #ifdef TCC_TARGET_PE
1335 #ifdef CONFIG_TCC_CROSSLIB
1336 snprintf(buf, sizeof(buf), "%s/" CONFIG_TCC_CROSSLIB, s->tcc_lib_path);
1337 tcc_add_library_path(s, buf);
1338 #endif
1339 snprintf(buf, sizeof(buf), "%s/lib", s->tcc_lib_path);
1340 tcc_add_library_path(s, buf);
1341 #ifdef _WIN32
1342 if (GetSystemDirectory(buf, sizeof buf))
1343 tcc_add_library_path(s, buf);
1344 #endif
1345 #endif
1347 return 0;
1350 #define WD_ALL 0x0001 /* warning is activated when using -Wall */
1351 #define FD_INVERT 0x0002 /* invert value before storing */
1353 typedef struct FlagDef {
1354 uint16_t offset;
1355 uint16_t flags;
1356 const char *name;
1357 } FlagDef;
1359 static const FlagDef warning_defs[] = {
1360 { offsetof(TCCState, warn_unsupported), 0, "unsupported" },
1361 { offsetof(TCCState, warn_write_strings), 0, "write-strings" },
1362 { offsetof(TCCState, warn_error), 0, "error" },
1363 { offsetof(TCCState, warn_implicit_function_declaration), WD_ALL,
1364 "implicit-function-declaration" },
1367 ST_FUNC int set_flag(TCCState *s, const FlagDef *flags, int nb_flags,
1368 const char *name, int value)
1370 int i;
1371 const FlagDef *p;
1372 const char *r;
1374 r = name;
1375 if (r[0] == 'n' && r[1] == 'o' && r[2] == '-') {
1376 r += 3;
1377 value = !value;
1379 for(i = 0, p = flags; i < nb_flags; i++, p++) {
1380 if (!strcmp(r, p->name))
1381 goto found;
1383 return -1;
1384 found:
1385 if (p->flags & FD_INVERT)
1386 value = !value;
1387 *(int *)((uint8_t *)s + p->offset) = value;
1388 return 0;
1391 /* set/reset a warning */
1392 LIBTCCAPI int tcc_set_warning(TCCState *s, const char *warning_name, int value)
1394 int i;
1395 const FlagDef *p;
1397 if (!strcmp(warning_name, "all")) {
1398 for(i = 0, p = warning_defs; i < countof(warning_defs); i++, p++) {
1399 if (p->flags & WD_ALL)
1400 *(int *)((uint8_t *)s + p->offset) = 1;
1402 return 0;
1403 } else {
1404 return set_flag(s, warning_defs, countof(warning_defs),
1405 warning_name, value);
1409 static const FlagDef flag_defs[] = {
1410 { offsetof(TCCState, char_is_unsigned), 0, "unsigned-char" },
1411 { offsetof(TCCState, char_is_unsigned), FD_INVERT, "signed-char" },
1412 { offsetof(TCCState, nocommon), FD_INVERT, "common" },
1413 { offsetof(TCCState, leading_underscore), 0, "leading-underscore" },
1416 /* set/reset a flag */
1417 PUB_FUNC int tcc_set_flag(TCCState *s, const char *flag_name, int value)
1419 return set_flag(s, flag_defs, countof(flag_defs),
1420 flag_name, value);
1424 static int strstart(const char *str, const char *val, char **ptr)
1426 const char *p, *q;
1427 p = str;
1428 q = val;
1429 while (*q != '\0') {
1430 if (*p != *q)
1431 return 0;
1432 p++;
1433 q++;
1435 if (ptr)
1436 *ptr = (char *) p;
1437 return 1;
1441 /* Like strstart, but automatically takes into account that ld options can
1443 * - start with double or single dash (e.g. '--soname' or '-soname')
1444 * - arguments can be given as separate or after '=' (e.g. '-Wl,-soname,x.so'
1445 * or '-Wl,-soname=x.so')
1447 * you provide `val` always in 'option[=]' form (no leading -)
1449 static int link_option(const char *str, const char *val, char **ptr)
1451 const char *p, *q;
1453 /* there should be 1 or 2 dashes */
1454 if (*str++ != '-')
1455 return 0;
1456 if (*str == '-')
1457 str++;
1459 /* then str & val should match (potentialy up to '=') */
1460 p = str;
1461 q = val;
1463 while (*q != '\0' && *q != '=') {
1464 if (*p != *q)
1465 return 0;
1466 p++;
1467 q++;
1470 /* '=' near eos means ',' or '=' is ok */
1471 if (*q == '=') {
1472 if (*p != ',' && *p != '=')
1473 return 0;
1474 p++;
1475 q++;
1478 if (ptr)
1479 *ptr = (char *) p;
1480 return 1;
1484 /* set linker options */
1485 PUB_FUNC const char * tcc_set_linker(TCCState *s, char *option, int multi)
1487 char *p = option;
1488 char *end;
1490 while (option && *option) {
1491 end = NULL;
1492 if (link_option(option, "Bsymbolic", &p)) {
1493 s->symbolic = TRUE;
1494 #ifdef TCC_TARGET_PE
1495 } else if (link_option(option, "file-alignment=", &p)) {
1496 s->pe_file_align = strtoul(p, &end, 16);
1497 #endif
1498 } else if (link_option(option, "fini=", &p)) {
1499 s->fini_symbol = p;
1500 if (s->warn_unsupported)
1501 warning("ignoring -fini %s", p);
1503 } else if (link_option(option, "image-base=", &p)) {
1504 s->text_addr = strtoul(p, &end, 16);
1505 s->has_text_addr = 1;
1506 } else if (link_option(option, "init=", &p)) {
1507 s->init_symbol = p;
1508 if (s->warn_unsupported)
1509 warning("ignoring -init %s", p);
1511 } else if (link_option(option, "oformat=", &p)) {
1512 #if defined(TCC_TARGET_PE)
1513 if (strstart(p, "pe-", NULL)) {
1514 #else
1515 #if defined(TCC_TARGET_X86_64)
1516 if (strstart(p, "elf64-", NULL)) {
1517 #else
1518 if (strstart(p, "elf32-", NULL)) {
1519 #endif
1520 #endif
1521 s->output_format = TCC_OUTPUT_FORMAT_ELF;
1522 } else if (!strcmp(p, "binary")) {
1523 s->output_format = TCC_OUTPUT_FORMAT_BINARY;
1524 } else
1525 #ifdef TCC_TARGET_COFF
1526 if (!strcmp(p, "coff")) {
1527 s->output_format = TCC_OUTPUT_FORMAT_COFF;
1528 } else
1529 #endif
1531 return p;
1534 } else if (link_option(option, "rpath=", &p)) {
1535 s->rpath = p;
1536 } else if (link_option(option, "section-alignment=", &p)) {
1537 s->section_align = strtoul(p, &end, 16);
1538 } else if (link_option(option, "soname=", &p)) {
1539 s->soname = p;
1540 multi = 0;
1541 #ifdef TCC_TARGET_PE
1542 } else if (link_option(option, "subsystem=", &p)) {
1543 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
1544 if (!strcmp(p, "native")) {
1545 s->pe_subsystem = 1;
1546 } else if (!strcmp(p, "console")) {
1547 s->pe_subsystem = 3;
1548 } else if (!strcmp(p, "gui")) {
1549 s->pe_subsystem = 2;
1550 } else if (!strcmp(p, "posix")) {
1551 s->pe_subsystem = 7;
1552 } else if (!strcmp(p, "efiapp")) {
1553 s->pe_subsystem = 10;
1554 } else if (!strcmp(p, "efiboot")) {
1555 s->pe_subsystem = 11;
1556 } else if (!strcmp(p, "efiruntime")) {
1557 s->pe_subsystem = 12;
1558 } else if (!strcmp(p, "efirom")) {
1559 s->pe_subsystem = 13;
1560 #elif defined(TCC_TARGET_ARM)
1561 if (!strcmp(p, "wince")) {
1562 s->pe_subsystem = 9;
1563 #endif
1564 } else {
1565 return p;
1567 #endif
1569 } else if (link_option(option, "Ttext=", &p)) {
1570 s->text_addr = strtoul(p, &end, 16);
1571 s->has_text_addr = 1;
1573 } else {
1574 return option;
1577 if (multi) {
1578 option = NULL;
1579 p = strchr( (end) ? end : p, ',');
1580 if (p) {
1581 *p = 0; /* terminate last option */
1582 option = ++p;
1584 } else
1585 option = NULL;
1587 return NULL;
1590 PUB_FUNC void tcc_print_stats(TCCState *s, int64_t total_time)
1592 double tt;
1593 tt = (double)total_time / 1000000.0;
1594 if (tt < 0.001)
1595 tt = 0.001;
1596 if (total_bytes < 1)
1597 total_bytes = 1;
1598 printf("%d idents, %d lines, %d bytes, %0.3f s, %d lines/s, %0.1f MB/s\n",
1599 tok_ident - TOK_IDENT, total_lines, total_bytes,
1600 tt, (int)(total_lines / tt),
1601 total_bytes / tt / 1000000.0);
1604 /* set CONFIG_TCCDIR at runtime */
1605 LIBTCCAPI void tcc_set_lib_path(TCCState *s, const char *path)
1607 tcc_free(s->tcc_lib_path);
1608 s->tcc_lib_path = tcc_strdup(path);
1611 PUB_FUNC void set_num_callers(int n)
1613 #ifdef CONFIG_TCC_BACKTRACE
1614 num_callers = n;
1615 #endif
1619 LIBTCCAPI const char *tcc_default_target(TCCState *s)
1621 /* FIXME will break in multithreaded case */
1622 static char outfile_default[1024];
1624 char *ext;
1625 const char *name =
1626 strcmp(s->input_files[0], "-") == 0 ? "a"
1627 : tcc_basename(s->input_files[0]);
1628 pstrcpy(outfile_default, sizeof(outfile_default), name);
1629 ext = tcc_fileextension(outfile_default);
1630 #ifdef TCC_TARGET_PE
1631 if (s->output_type == TCC_OUTPUT_DLL)
1632 strcpy(ext, ".dll");
1633 else
1634 if (s->output_type == TCC_OUTPUT_EXE)
1635 strcpy(ext, ".exe");
1636 else
1637 #endif
1638 if (( (s->output_type == TCC_OUTPUT_OBJ && !s->reloc_output) ||
1639 (s->output_type == TCC_OUTPUT_PREPROCESS) )
1640 && *ext)
1641 strcpy(ext, ".o");
1642 else
1643 pstrcpy(outfile_default, sizeof(outfile_default), "a.out");
1645 return outfile_default;
1649 LIBTCCAPI void tcc_gen_makedeps(TCCState *s, const char *target, const char *filename)
1651 FILE *depout;
1652 char buf[1024], *ext;
1653 int i;
1655 if (!target)
1656 target = tcc_default_target(s);
1658 if (!filename) {
1659 /* compute filename automatically
1660 * dir/file.o -> dir/file.d */
1661 pstrcpy(buf, sizeof(buf), target);
1662 ext = tcc_fileextension(buf);
1663 pstrcpy(ext, sizeof(buf) - (ext-buf), ".d");
1664 filename = buf;
1667 if (s->verbose)
1668 printf("<- %s\n", filename);
1670 /* XXX return err codes instead of error() ? */
1671 depout = fopen(filename, "w");
1672 if (!depout)
1673 error("could not open '%s'", filename);
1675 fprintf(depout, "%s : \\\n", target);
1676 for (i=0; i<s->nb_target_deps; ++i)
1677 fprintf(depout, "\t%s \\\n", s->target_deps[i]);
1678 fprintf(depout, "\n");
1679 fclose(depout);