Default to create progs with symbols (incl. debug)
[tinycc.git] / libtcc.c
blobf97336e65fc0d344fd94a110e0820835b58683c7
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 PUB_FUNC void tcc_memstats(void)
252 #ifdef MEM_DEBUG
253 printf("memory in use: %d\n", mem_cur_size);
254 #endif
257 #define free(p) use_tcc_free(p)
258 #define malloc(s) use_tcc_malloc(s)
259 #define realloc(p, s) use_tcc_realloc(p, s)
261 /********************************************************/
262 /* dynarrays */
264 PUB_FUNC void dynarray_add(void ***ptab, int *nb_ptr, void *data)
266 int nb, nb_alloc;
267 void **pp;
269 nb = *nb_ptr;
270 pp = *ptab;
271 /* every power of two we double array size */
272 if ((nb & (nb - 1)) == 0) {
273 if (!nb)
274 nb_alloc = 1;
275 else
276 nb_alloc = nb * 2;
277 pp = tcc_realloc(pp, nb_alloc * sizeof(void *));
278 if (!pp)
279 error("memory full");
280 *ptab = pp;
282 pp[nb++] = data;
283 *nb_ptr = nb;
286 PUB_FUNC void dynarray_reset(void *pp, int *n)
288 void **p;
289 for (p = *(void***)pp; *n; ++p, --*n)
290 if (*p)
291 tcc_free(*p);
292 tcc_free(*(void**)pp);
293 *(void**)pp = NULL;
296 /* we use our own 'finite' function to avoid potential problems with
297 non standard math libs */
298 /* XXX: endianness dependent */
299 ST_FUNC int ieee_finite(double d)
301 int *p = (int *)&d;
302 return ((unsigned)((p[1] | 0x800fffff) + 1)) >> 31;
305 /********************************************************/
307 ST_FUNC Section *new_section(TCCState *s1, const char *name, int sh_type, int sh_flags)
309 Section *sec;
311 sec = tcc_mallocz(sizeof(Section) + strlen(name));
312 strcpy(sec->name, name);
313 sec->sh_type = sh_type;
314 sec->sh_flags = sh_flags;
315 switch(sh_type) {
316 case SHT_HASH:
317 case SHT_REL:
318 case SHT_RELA:
319 case SHT_DYNSYM:
320 case SHT_SYMTAB:
321 case SHT_DYNAMIC:
322 sec->sh_addralign = 4;
323 break;
324 case SHT_STRTAB:
325 sec->sh_addralign = 1;
326 break;
327 default:
328 sec->sh_addralign = 32; /* default conservative alignment */
329 break;
332 if (sh_flags & SHF_PRIVATE) {
333 dynarray_add((void ***)&s1->priv_sections, &s1->nb_priv_sections, sec);
334 } else {
335 sec->sh_num = s1->nb_sections;
336 dynarray_add((void ***)&s1->sections, &s1->nb_sections, sec);
339 return sec;
342 static void free_section(Section *s)
344 tcc_free(s->data);
347 /* realloc section and set its content to zero */
348 ST_FUNC void section_realloc(Section *sec, unsigned long new_size)
350 unsigned long size;
351 unsigned char *data;
353 size = sec->data_allocated;
354 if (size == 0)
355 size = 1;
356 while (size < new_size)
357 size = size * 2;
358 data = tcc_realloc(sec->data, size);
359 if (!data)
360 error("memory full");
361 memset(data + sec->data_allocated, 0, size - sec->data_allocated);
362 sec->data = data;
363 sec->data_allocated = size;
366 /* reserve at least 'size' bytes in section 'sec' from
367 sec->data_offset. */
368 ST_FUNC void *section_ptr_add(Section *sec, unsigned long size)
370 unsigned long offset, offset1;
372 offset = sec->data_offset;
373 offset1 = offset + size;
374 if (offset1 > sec->data_allocated)
375 section_realloc(sec, offset1);
376 sec->data_offset = offset1;
377 return sec->data + offset;
380 /* reserve at least 'size' bytes from section start */
381 ST_FUNC void section_reserve(Section *sec, unsigned long size)
383 if (size > sec->data_allocated)
384 section_realloc(sec, size);
385 if (size > sec->data_offset)
386 sec->data_offset = size;
389 /* return a reference to a section, and create it if it does not
390 exists */
391 ST_FUNC Section *find_section(TCCState *s1, const char *name)
393 Section *sec;
394 int i;
395 for(i = 1; i < s1->nb_sections; i++) {
396 sec = s1->sections[i];
397 if (!strcmp(name, sec->name))
398 return sec;
400 /* sections are created as PROGBITS */
401 return new_section(s1, name, SHT_PROGBITS, SHF_ALLOC);
404 /* update sym->c so that it points to an external symbol in section
405 'section' with value 'value' */
406 ST_FUNC void put_extern_sym2(Sym *sym, Section *section,
407 unsigned long value, unsigned long size,
408 int can_add_underscore)
410 int sym_type, sym_bind, sh_num, info, other;
411 ElfW(Sym) *esym;
412 const char *name;
413 char buf1[256];
415 if (section == NULL)
416 sh_num = SHN_UNDEF;
417 else if (section == SECTION_ABS)
418 sh_num = SHN_ABS;
419 else
420 sh_num = section->sh_num;
422 if ((sym->type.t & VT_BTYPE) == VT_FUNC) {
423 sym_type = STT_FUNC;
424 } else if ((sym->type.t & VT_BTYPE) == VT_VOID) {
425 sym_type = STT_NOTYPE;
426 } else {
427 sym_type = STT_OBJECT;
430 if (sym->type.t & VT_STATIC)
431 sym_bind = STB_LOCAL;
432 else {
433 if (sym->type.t & VT_WEAK)
434 sym_bind = STB_WEAK;
435 else
436 sym_bind = STB_GLOBAL;
439 if (!sym->c) {
440 name = get_tok_str(sym->v, NULL);
441 #ifdef CONFIG_TCC_BCHECK
442 if (tcc_state->do_bounds_check) {
443 char buf[32];
445 /* XXX: avoid doing that for statics ? */
446 /* if bound checking is activated, we change some function
447 names by adding the "__bound" prefix */
448 switch(sym->v) {
449 #ifdef TCC_TARGET_PE
450 /* XXX: we rely only on malloc hooks */
451 case TOK_malloc:
452 case TOK_free:
453 case TOK_realloc:
454 case TOK_memalign:
455 case TOK_calloc:
456 #endif
457 case TOK_memcpy:
458 case TOK_memmove:
459 case TOK_memset:
460 case TOK_strlen:
461 case TOK_strcpy:
462 case TOK_alloca:
463 strcpy(buf, "__bound_");
464 strcat(buf, name);
465 name = buf;
466 break;
469 #endif
470 other = 0;
472 #ifdef TCC_TARGET_PE
473 if (sym->type.t & VT_EXPORT)
474 other |= 1;
475 if (sym_type == STT_FUNC && sym->type.ref) {
476 int attr = sym->type.ref->r;
477 if (FUNC_EXPORT(attr))
478 other |= 1;
479 if (FUNC_CALL(attr) == FUNC_STDCALL && can_add_underscore) {
480 sprintf(buf1, "_%s@%d", name, FUNC_ARGS(attr) * PTR_SIZE);
481 name = buf1;
482 other |= 2;
483 can_add_underscore = 0;
485 } else {
486 if (find_elf_sym(tcc_state->dynsymtab_section, name))
487 other |= 4;
488 if (sym->type.t & VT_IMPORT)
489 other |= 4;
491 #endif
492 if (tcc_state->leading_underscore && can_add_underscore) {
493 buf1[0] = '_';
494 pstrcpy(buf1 + 1, sizeof(buf1) - 1, name);
495 name = buf1;
497 if (sym->asm_label) {
498 name = sym->asm_label;
500 info = ELFW(ST_INFO)(sym_bind, sym_type);
501 sym->c = add_elf_sym(symtab_section, value, size, info, other, sh_num, name);
502 } else {
503 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
504 esym->st_value = value;
505 esym->st_size = size;
506 esym->st_shndx = sh_num;
510 ST_FUNC void put_extern_sym(Sym *sym, Section *section,
511 unsigned long value, unsigned long size)
513 put_extern_sym2(sym, section, value, size, 1);
516 /* add a new relocation entry to symbol 'sym' in section 's' */
517 ST_FUNC void greloc(Section *s, Sym *sym, unsigned long offset, int type)
519 int c = 0;
520 if (sym) {
521 if (0 == sym->c)
522 put_extern_sym(sym, NULL, 0, 0);
523 c = sym->c;
525 /* now we can add ELF relocation info */
526 put_elf_reloc(symtab_section, s, offset, type, c);
529 /********************************************************/
531 static void strcat_vprintf(char *buf, int buf_size, const char *fmt, va_list ap)
533 int len;
534 len = strlen(buf);
535 vsnprintf(buf + len, buf_size - len, fmt, ap);
538 static void strcat_printf(char *buf, int buf_size, const char *fmt, ...)
540 va_list ap;
541 va_start(ap, fmt);
542 strcat_vprintf(buf, buf_size, fmt, ap);
543 va_end(ap);
546 static void error1(TCCState *s1, int is_warning, const char *fmt, va_list ap)
548 char buf[2048];
549 BufferedFile **f;
551 buf[0] = '\0';
552 if (file) {
553 for(f = s1->include_stack; f < s1->include_stack_ptr; f++)
554 strcat_printf(buf, sizeof(buf), "In file included from %s:%d:\n",
555 (*f)->filename, (*f)->line_num);
556 if (file->line_num > 0) {
557 strcat_printf(buf, sizeof(buf),
558 "%s:%d: ", file->filename, file->line_num);
559 } else {
560 strcat_printf(buf, sizeof(buf),
561 "%s: ", file->filename);
563 } else {
564 strcat_printf(buf, sizeof(buf),
565 "tcc: ");
567 if (is_warning)
568 strcat_printf(buf, sizeof(buf), "warning: ");
569 else
570 strcat_printf(buf, sizeof(buf), "error: ");
571 strcat_vprintf(buf, sizeof(buf), fmt, ap);
573 if (!s1->error_func) {
574 /* default case: stderr */
575 fprintf(stderr, "%s\n", buf);
576 } else {
577 s1->error_func(s1->error_opaque, buf);
579 if (!is_warning || s1->warn_error)
580 s1->nb_errors++;
583 LIBTCCAPI void tcc_set_error_func(TCCState *s, void *error_opaque,
584 void (*error_func)(void *opaque, const char *msg))
586 s->error_opaque = error_opaque;
587 s->error_func = error_func;
590 /* error without aborting current compilation */
591 PUB_FUNC void error_noabort(const char *fmt, ...)
593 TCCState *s1 = tcc_state;
594 va_list ap;
596 va_start(ap, fmt);
597 error1(s1, 0, fmt, ap);
598 va_end(ap);
601 PUB_FUNC void error(const char *fmt, ...)
603 TCCState *s1 = tcc_state;
604 va_list ap;
606 va_start(ap, fmt);
607 error1(s1, 0, fmt, ap);
608 va_end(ap);
609 /* better than nothing: in some cases, we accept to handle errors */
610 if (s1->error_set_jmp_enabled) {
611 longjmp(s1->error_jmp_buf, 1);
612 } else {
613 /* XXX: eliminate this someday */
614 exit(1);
618 PUB_FUNC void expect(const char *msg)
620 error("%s expected", msg);
623 PUB_FUNC void warning(const char *fmt, ...)
625 TCCState *s1 = tcc_state;
626 va_list ap;
628 if (s1->warn_none)
629 return;
631 va_start(ap, fmt);
632 error1(s1, 1, fmt, ap);
633 va_end(ap);
636 /********************************************************/
637 /* I/O layer */
639 ST_FUNC void tcc_open_bf(TCCState *s1, const char *filename, int initlen)
641 BufferedFile *bf;
642 int buflen = initlen ? initlen : IO_BUF_SIZE;
644 bf = tcc_malloc(sizeof(BufferedFile) + buflen);
645 bf->buf_ptr = bf->buffer;
646 bf->buf_end = bf->buffer + initlen;
647 bf->buf_end[0] = CH_EOB; /* put eob symbol */
648 pstrcpy(bf->filename, sizeof(bf->filename), filename);
649 #ifdef _WIN32
650 normalize_slashes(bf->filename);
651 #endif
652 bf->line_num = 1;
653 bf->ifndef_macro = 0;
654 bf->ifdef_stack_ptr = s1->ifdef_stack_ptr;
655 bf->fd = -1;
656 bf->prev = file;
657 file = bf;
660 ST_FUNC void tcc_close(void)
662 BufferedFile *bf = file;
663 if (bf->fd > 0) {
664 close(bf->fd);
665 total_lines += bf->line_num;
667 file = bf->prev;
668 tcc_free(bf);
671 ST_FUNC int tcc_open(TCCState *s1, const char *filename)
673 int fd;
674 if (strcmp(filename, "-") == 0)
675 fd = 0, filename = "stdin";
676 else
677 fd = open(filename, O_RDONLY | O_BINARY);
678 if ((s1->verbose == 2 && fd >= 0) || s1->verbose == 3)
679 printf("%s %*s%s\n", fd < 0 ? "nf":"->",
680 (int)(s1->include_stack_ptr - s1->include_stack), "", filename);
681 if (fd < 0)
682 return -1;
684 tcc_open_bf(s1, filename, 0);
685 file->fd = fd;
686 return fd;
689 /* compile the C file opened in 'file'. Return non zero if errors. */
690 static int tcc_compile(TCCState *s1)
692 Sym *define_start;
693 SValue *pvtop;
694 char buf[512];
695 volatile int section_sym;
697 #ifdef INC_DEBUG
698 printf("%s: **** new file\n", file->filename);
699 #endif
700 preprocess_init(s1);
702 cur_text_section = NULL;
703 funcname = "";
704 anon_sym = SYM_FIRST_ANOM;
706 /* file info: full path + filename */
707 section_sym = 0; /* avoid warning */
708 if (s1->do_debug) {
709 section_sym = put_elf_sym(symtab_section, 0, 0,
710 ELFW(ST_INFO)(STB_LOCAL, STT_SECTION), 0,
711 text_section->sh_num, NULL);
712 getcwd(buf, sizeof(buf));
713 #ifdef _WIN32
714 normalize_slashes(buf);
715 #endif
716 pstrcat(buf, sizeof(buf), "/");
717 put_stabs_r(buf, N_SO, 0, 0,
718 text_section->data_offset, text_section, section_sym);
719 put_stabs_r(file->filename, N_SO, 0, 0,
720 text_section->data_offset, text_section, section_sym);
722 /* an elf symbol of type STT_FILE must be put so that STB_LOCAL
723 symbols can be safely used */
724 put_elf_sym(symtab_section, 0, 0,
725 ELFW(ST_INFO)(STB_LOCAL, STT_FILE), 0,
726 SHN_ABS, file->filename);
728 /* define some often used types */
729 int_type.t = VT_INT;
731 char_pointer_type.t = VT_BYTE;
732 mk_pointer(&char_pointer_type);
734 func_old_type.t = VT_FUNC;
735 func_old_type.ref = sym_push(SYM_FIELD, &int_type, FUNC_CDECL, FUNC_OLD);
737 #if defined(TCC_ARM_EABI) && defined(TCC_ARM_VFP)
738 float_type.t = VT_FLOAT;
739 double_type.t = VT_DOUBLE;
741 func_float_type.t = VT_FUNC;
742 func_float_type.ref = sym_push(SYM_FIELD, &float_type, FUNC_CDECL, FUNC_OLD);
743 func_double_type.t = VT_FUNC;
744 func_double_type.ref = sym_push(SYM_FIELD, &double_type, FUNC_CDECL, FUNC_OLD);
745 #endif
747 #if 0
748 /* define 'void *alloca(unsigned int)' builtin function */
750 Sym *s1;
752 p = anon_sym++;
753 sym = sym_push(p, mk_pointer(VT_VOID), FUNC_CDECL, FUNC_NEW);
754 s1 = sym_push(SYM_FIELD, VT_UNSIGNED | VT_INT, 0, 0);
755 s1->next = NULL;
756 sym->next = s1;
757 sym_push(TOK_alloca, VT_FUNC | (p << VT_STRUCT_SHIFT), VT_CONST, 0);
759 #endif
761 define_start = define_stack;
762 nocode_wanted = 1;
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 pvtop = vtop;
772 next();
773 decl(VT_CONST);
774 if (tok != TOK_EOF)
775 expect("declaration");
776 if (pvtop != vtop)
777 warning("internal compiler error: vstack leak? (%d)", vtop - pvtop);
779 /* end of translation unit info */
780 if (s1->do_debug) {
781 put_stabs_r(NULL, N_SO, 0, 0,
782 text_section->data_offset, text_section, section_sym);
786 s1->error_set_jmp_enabled = 0;
788 /* reset define stack, but leave -Dsymbols (may be incorrect if
789 they are undefined) */
790 free_defines(define_start);
792 gen_inline_functions();
794 sym_pop(&global_stack, NULL);
795 sym_pop(&local_stack, NULL);
797 return s1->nb_errors != 0 ? -1 : 0;
800 LIBTCCAPI int tcc_compile_string(TCCState *s, const char *str)
802 int len, ret;
803 len = strlen(str);
805 tcc_open_bf(s, "<string>", len);
806 memcpy(file->buffer, str, len);
807 ret = tcc_compile(s);
808 tcc_close();
809 return ret;
812 /* define a preprocessor symbol. A value can also be provided with the '=' operator */
813 LIBTCCAPI void tcc_define_symbol(TCCState *s1, const char *sym, const char *value)
815 int len1, len2;
816 /* default value */
817 if (!value)
818 value = "1";
819 len1 = strlen(sym);
820 len2 = strlen(value);
822 /* init file structure */
823 tcc_open_bf(s1, "<define>", len1 + len2 + 1);
824 memcpy(file->buffer, sym, len1);
825 file->buffer[len1] = ' ';
826 memcpy(file->buffer + len1 + 1, value, len2);
828 /* parse with define parser */
829 ch = file->buf_ptr[0];
830 next_nomacro();
831 parse_define();
833 tcc_close();
836 /* undefine a preprocessor symbol */
837 LIBTCCAPI void tcc_undefine_symbol(TCCState *s1, const char *sym)
839 TokenSym *ts;
840 Sym *s;
841 ts = tok_alloc(sym, strlen(sym));
842 s = define_find(ts->tok);
843 /* undefine symbol by putting an invalid name */
844 if (s)
845 define_undef(s);
848 static void tcc_cleanup(void)
850 int i, n;
852 if (NULL == tcc_state)
853 return;
854 tcc_state = NULL;
856 /* free -D defines */
857 free_defines(NULL);
859 /* free tokens */
860 n = tok_ident - TOK_IDENT;
861 for(i = 0; i < n; i++)
862 tcc_free(table_ident[i]);
863 tcc_free(table_ident);
865 /* free sym_pools */
866 dynarray_reset(&sym_pools, &nb_sym_pools);
867 /* string buffer */
868 cstr_free(&tokcstr);
869 /* reset symbol stack */
870 sym_free_first = NULL;
871 /* cleanup from error/setjmp */
872 macro_ptr = NULL;
875 LIBTCCAPI TCCState *tcc_new(void)
877 TCCState *s;
878 char buffer[100];
879 int a,b,c;
881 tcc_cleanup();
883 s = tcc_mallocz(sizeof(TCCState));
884 if (!s)
885 return NULL;
886 tcc_state = s;
887 #ifdef _WIN32
888 tcc_set_lib_path_w32(s);
889 #else
890 tcc_set_lib_path(s, CONFIG_TCCDIR);
891 #endif
892 s->output_type = TCC_OUTPUT_MEMORY;
893 preprocess_new();
894 s->include_stack_ptr = s->include_stack;
896 /* we add dummy defines for some special macros to speed up tests
897 and to have working defined() */
898 define_push(TOK___LINE__, MACRO_OBJ, NULL, NULL);
899 define_push(TOK___FILE__, MACRO_OBJ, NULL, NULL);
900 define_push(TOK___DATE__, MACRO_OBJ, NULL, NULL);
901 define_push(TOK___TIME__, MACRO_OBJ, NULL, NULL);
903 /* standard defines */
904 tcc_define_symbol(s, "__STDC__", NULL);
905 tcc_define_symbol(s, "__STDC_VERSION__", "199901L");
906 #if defined(TCC_TARGET_I386)
907 tcc_define_symbol(s, "__i386__", NULL);
908 tcc_define_symbol(s, "__i386", NULL);
909 tcc_define_symbol(s, "i386", NULL);
910 #endif
911 #if defined(TCC_TARGET_X86_64)
912 tcc_define_symbol(s, "__x86_64__", NULL);
913 #endif
914 #if defined(TCC_TARGET_ARM)
915 tcc_define_symbol(s, "__ARM_ARCH_4__", NULL);
916 tcc_define_symbol(s, "__arm_elf__", NULL);
917 tcc_define_symbol(s, "__arm_elf", NULL);
918 tcc_define_symbol(s, "arm_elf", NULL);
919 tcc_define_symbol(s, "__arm__", NULL);
920 tcc_define_symbol(s, "__arm", NULL);
921 tcc_define_symbol(s, "arm", NULL);
922 tcc_define_symbol(s, "__APCS_32__", NULL);
923 #endif
924 #ifdef TCC_TARGET_PE
925 tcc_define_symbol(s, "_WIN32", NULL);
926 #ifdef TCC_TARGET_X86_64
927 tcc_define_symbol(s, "_WIN64", NULL);
928 #endif
929 #else
930 tcc_define_symbol(s, "__unix__", NULL);
931 tcc_define_symbol(s, "__unix", NULL);
932 tcc_define_symbol(s, "unix", NULL);
933 #if defined(__FreeBSD__)
934 #define str(s) #s
935 tcc_define_symbol(s, "__FreeBSD__", str( __FreeBSD__));
936 #undef str
937 #endif
938 #if defined(__FreeBSD_kernel__)
939 tcc_define_symbol(s, "__FreeBSD_kernel__", NULL);
940 #endif
941 #if defined(__linux)
942 tcc_define_symbol(s, "__linux__", NULL);
943 tcc_define_symbol(s, "__linux", NULL);
944 #endif
945 #endif
946 /* tiny C specific defines */
947 sscanf(TCC_VERSION, "%d.%d.%d", &a, &b, &c);
948 sprintf(buffer, "%d", a*10000 + b*100 + c);
949 tcc_define_symbol(s, "__TINYC__", buffer);
951 /* tiny C & gcc defines */
952 #if defined TCC_TARGET_PE && defined TCC_TARGET_X86_64
953 tcc_define_symbol(s, "__SIZE_TYPE__", "unsigned long long");
954 tcc_define_symbol(s, "__PTRDIFF_TYPE__", "long long");
955 #else
956 tcc_define_symbol(s, "__SIZE_TYPE__", "unsigned long");
957 tcc_define_symbol(s, "__PTRDIFF_TYPE__", "long");
958 #endif
960 #ifdef TCC_TARGET_PE
961 tcc_define_symbol(s, "__WCHAR_TYPE__", "unsigned short");
962 #else
963 tcc_define_symbol(s, "__WCHAR_TYPE__", "int");
964 #endif
966 /* glibc defines */
967 tcc_define_symbol(s, "__REDIRECT_NTH(name, proto, alias)", "name proto __asm__ (#alias) __THROW");
969 #ifndef TCC_TARGET_PE
970 /* default library paths */
971 tcc_add_library_path(s, CONFIG_TCC_CRT_PREFIX);
972 tcc_add_library_path(s, CONFIG_SYSROOT CONFIG_TCC_LDDIR);
973 tcc_add_library_path(s, CONFIG_SYSROOT "/usr/local"CONFIG_TCC_LDDIR);
974 #endif
976 /* no section zero */
977 dynarray_add((void ***)&s->sections, &s->nb_sections, NULL);
979 /* create standard sections */
980 text_section = new_section(s, ".text", SHT_PROGBITS, SHF_ALLOC | SHF_EXECINSTR);
981 data_section = new_section(s, ".data", SHT_PROGBITS, SHF_ALLOC | SHF_WRITE);
982 bss_section = new_section(s, ".bss", SHT_NOBITS, SHF_ALLOC | SHF_WRITE);
984 /* symbols are always generated for linking stage */
985 symtab_section = new_symtab(s, ".symtab", SHT_SYMTAB, 0,
986 ".strtab",
987 ".hashtab", SHF_PRIVATE);
988 strtab_section = symtab_section->link;
990 /* private symbol table for dynamic symbols */
991 s->dynsymtab_section = new_symtab(s, ".dynsymtab", SHT_SYMTAB, SHF_PRIVATE,
992 ".dynstrtab",
993 ".dynhashtab", SHF_PRIVATE);
994 s->alacarte_link = 1;
995 s->nocommon = 1;
997 #ifdef CHAR_IS_UNSIGNED
998 s->char_is_unsigned = 1;
999 #endif
1000 /* enable this if you want symbols with leading underscore on windows: */
1001 #if defined(TCC_TARGET_PE) && 0
1002 s->leading_underscore = 1;
1003 #endif
1004 if (s->section_align == 0)
1005 s->section_align = ELF_PAGE_SIZE;
1006 #ifdef TCC_TARGET_I386
1007 s->seg_size = 32;
1008 #endif
1009 return s;
1012 LIBTCCAPI void tcc_delete(TCCState *s1)
1014 int i;
1016 tcc_cleanup();
1018 /* free all sections */
1019 for(i = 1; i < s1->nb_sections; i++)
1020 free_section(s1->sections[i]);
1021 dynarray_reset(&s1->sections, &s1->nb_sections);
1023 for(i = 0; i < s1->nb_priv_sections; i++)
1024 free_section(s1->priv_sections[i]);
1025 dynarray_reset(&s1->priv_sections, &s1->nb_priv_sections);
1027 /* free any loaded DLLs */
1028 for ( i = 0; i < s1->nb_loaded_dlls; i++) {
1029 DLLReference *ref = s1->loaded_dlls[i];
1030 if ( ref->handle )
1031 dlclose(ref->handle);
1034 /* free loaded dlls array */
1035 dynarray_reset(&s1->loaded_dlls, &s1->nb_loaded_dlls);
1037 /* free library paths */
1038 dynarray_reset(&s1->library_paths, &s1->nb_library_paths);
1040 /* free include paths */
1041 dynarray_reset(&s1->cached_includes, &s1->nb_cached_includes);
1042 dynarray_reset(&s1->include_paths, &s1->nb_include_paths);
1043 dynarray_reset(&s1->sysinclude_paths, &s1->nb_sysinclude_paths);
1045 tcc_free(s1->tcc_lib_path);
1047 dynarray_reset(&s1->input_files, &s1->nb_input_files);
1048 dynarray_reset(&s1->input_libs, &s1->nb_input_libs);
1049 dynarray_reset(&s1->target_deps, &s1->nb_target_deps);
1051 #ifdef HAVE_SELINUX
1052 munmap (s1->write_mem, s1->mem_size);
1053 munmap (s1->runtime_mem, s1->mem_size);
1054 #else
1055 tcc_free(s1->runtime_mem);
1056 #endif
1057 tcc_free(s1);
1060 LIBTCCAPI int tcc_add_include_path(TCCState *s1, const char *pathname)
1062 char *pathname1;
1064 pathname1 = tcc_strdup(pathname);
1065 dynarray_add((void ***)&s1->include_paths, &s1->nb_include_paths, pathname1);
1066 return 0;
1069 LIBTCCAPI int tcc_add_sysinclude_path(TCCState *s1, const char *pathname)
1071 char *pathname1;
1073 pathname1 = tcc_strdup(pathname);
1074 dynarray_add((void ***)&s1->sysinclude_paths, &s1->nb_sysinclude_paths, pathname1);
1075 return 0;
1078 ST_FUNC int tcc_add_file_internal(TCCState *s1, const char *filename, int flags)
1080 const char *ext;
1081 ElfW(Ehdr) ehdr;
1082 int fd, ret, size;
1084 /* find source file type with extension */
1085 ext = tcc_fileextension(filename);
1086 if (ext[0])
1087 ext++;
1089 #ifdef CONFIG_TCC_ASM
1090 /* if .S file, define __ASSEMBLER__ like gcc does */
1091 if (!strcmp(ext, "S"))
1092 tcc_define_symbol(s1, "__ASSEMBLER__", NULL);
1093 #endif
1095 /* open the file */
1096 ret = tcc_open(s1, filename);
1097 if (ret < 0) {
1098 if (flags & AFF_PRINT_ERROR)
1099 error_noabort("file '%s' not found", filename);
1100 return ret;
1103 /* update target deps */
1104 dynarray_add((void ***)&s1->target_deps, &s1->nb_target_deps,
1105 tcc_strdup(filename));
1107 if (flags & AFF_PREPROCESS) {
1108 ret = tcc_preprocess(s1);
1109 goto the_end;
1112 if (!ext[0] || !PATHCMP(ext, "c")) {
1113 /* C file assumed */
1114 ret = tcc_compile(s1);
1115 goto the_end;
1118 #ifdef CONFIG_TCC_ASM
1119 if (!strcmp(ext, "S")) {
1120 /* preprocessed assembler */
1121 ret = tcc_assemble(s1, 1);
1122 goto the_end;
1125 if (!strcmp(ext, "s")) {
1126 /* non preprocessed assembler */
1127 ret = tcc_assemble(s1, 0);
1128 goto the_end;
1130 #endif
1132 fd = file->fd;
1133 /* assume executable format: auto guess file type */
1134 size = read(fd, &ehdr, sizeof(ehdr));
1135 lseek(fd, 0, SEEK_SET);
1136 if (size <= 0) {
1137 error_noabort("could not read header");
1138 goto the_end;
1141 if (size == sizeof(ehdr) &&
1142 ehdr.e_ident[0] == ELFMAG0 &&
1143 ehdr.e_ident[1] == ELFMAG1 &&
1144 ehdr.e_ident[2] == ELFMAG2 &&
1145 ehdr.e_ident[3] == ELFMAG3) {
1147 /* do not display line number if error */
1148 file->line_num = 0;
1149 if (ehdr.e_type == ET_REL) {
1150 ret = tcc_load_object_file(s1, fd, 0);
1151 goto the_end;
1154 #ifndef TCC_TARGET_PE
1155 if (ehdr.e_type == ET_DYN) {
1156 if (s1->output_type == TCC_OUTPUT_MEMORY) {
1157 void *h;
1158 h = dlopen(filename, RTLD_GLOBAL | RTLD_LAZY);
1159 if (h)
1160 ret = 0;
1161 } else {
1162 ret = tcc_load_dll(s1, fd, filename,
1163 (flags & AFF_REFERENCED_DLL) != 0);
1165 goto the_end;
1167 #endif
1168 error_noabort("unrecognized ELF file");
1169 goto the_end;
1172 if (memcmp((char *)&ehdr, ARMAG, 8) == 0) {
1173 file->line_num = 0; /* do not display line number if error */
1174 ret = tcc_load_archive(s1, fd);
1175 goto the_end;
1178 #ifdef TCC_TARGET_COFF
1179 if (*(uint16_t *)(&ehdr) == COFF_C67_MAGIC) {
1180 ret = tcc_load_coff(s1, fd);
1181 goto the_end;
1183 #endif
1185 #ifdef TCC_TARGET_PE
1186 ret = pe_load_file(s1, filename, fd);
1187 #else
1188 /* as GNU ld, consider it is an ld script if not recognized */
1189 ret = tcc_load_ldscript(s1);
1190 #endif
1191 if (ret < 0)
1192 error_noabort("unrecognized file type");
1194 the_end:
1195 tcc_close();
1196 return ret;
1199 LIBTCCAPI int tcc_add_file(TCCState *s, const char *filename)
1201 dynarray_add((void ***)&s->input_files, &s->nb_input_files, tcc_strdup(filename));
1203 if (s->output_type == TCC_OUTPUT_PREPROCESS)
1204 return tcc_add_file_internal(s, filename, AFF_PRINT_ERROR | AFF_PREPROCESS);
1205 else
1206 return tcc_add_file_internal(s, filename, AFF_PRINT_ERROR);
1209 LIBTCCAPI int tcc_add_library_path(TCCState *s, const char *pathname)
1211 char *pathname1;
1213 pathname1 = tcc_strdup(pathname);
1214 dynarray_add((void ***)&s->library_paths, &s->nb_library_paths, pathname1);
1215 return 0;
1218 /* find and load a dll. Return non zero if not found */
1219 /* XXX: add '-rpath' option support ? */
1220 ST_FUNC int tcc_add_dll(TCCState *s, const char *filename, int flags)
1222 char buf[1024];
1223 int i;
1225 for(i = 0; i < s->nb_library_paths; i++) {
1226 snprintf(buf, sizeof(buf), "%s/%s",
1227 s->library_paths[i], filename);
1228 if (tcc_add_file_internal(s, buf, flags) == 0)
1229 return 0;
1231 return -1;
1234 /* the library name is the same as the argument of the '-l' option */
1235 LIBTCCAPI int tcc_add_library(TCCState *s, const char *libraryname)
1237 char buf[1024];
1238 int i;
1240 dynarray_add((void ***)&s->input_libs, &s->nb_input_libs, tcc_strdup(libraryname));
1242 /* first we look for the dynamic library if not static linking */
1243 if (!s->static_link) {
1244 #ifdef TCC_TARGET_PE
1245 if (pe_add_dll(s, libraryname) == 0)
1246 return 0;
1247 #else
1248 snprintf(buf, sizeof(buf), "lib%s.so", libraryname);
1249 if (tcc_add_dll(s, buf, 0) == 0)
1250 return 0;
1251 #endif
1253 /* then we look for the static library */
1254 for(i = 0; i < s->nb_library_paths; i++) {
1255 snprintf(buf, sizeof(buf), "%s/lib%s.a",
1256 s->library_paths[i], libraryname);
1257 if (tcc_add_file_internal(s, buf, 0) == 0)
1258 return 0;
1260 return -1;
1263 LIBTCCAPI int tcc_add_symbol(TCCState *s, const char *name, const void *val)
1265 #ifdef TCC_TARGET_PE
1266 pe_putimport(s, 0, name, val);
1267 #else
1268 add_elf_sym(symtab_section, (uplong)val, 0,
1269 ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE), 0,
1270 SHN_ABS, name);
1271 #endif
1272 return 0;
1275 LIBTCCAPI int tcc_set_output_type(TCCState *s, int output_type)
1277 char buf[1024];
1279 s->output_type = output_type;
1281 if (!s->nostdinc) {
1282 /* default include paths */
1283 /* -isystem paths have already been handled */
1284 #ifndef TCC_TARGET_PE
1285 tcc_add_sysinclude_path(s, CONFIG_SYSROOT "/usr/local/include");
1286 tcc_add_sysinclude_path(s, CONFIG_SYSROOT "/usr/include");
1287 #endif
1288 snprintf(buf, sizeof(buf), "%s/include", s->tcc_lib_path);
1289 tcc_add_sysinclude_path(s, buf);
1290 #ifdef TCC_TARGET_PE
1291 snprintf(buf, sizeof(buf), "%s/include/winapi", s->tcc_lib_path);
1292 tcc_add_sysinclude_path(s, buf);
1293 #endif
1296 /* if bound checking, then add corresponding sections */
1297 #ifdef CONFIG_TCC_BCHECK
1298 if (s->do_bounds_check) {
1299 /* define symbol */
1300 tcc_define_symbol(s, "__BOUNDS_CHECKING_ON", NULL);
1301 /* create bounds sections */
1302 bounds_section = new_section(s, ".bounds",
1303 SHT_PROGBITS, SHF_ALLOC);
1304 lbounds_section = new_section(s, ".lbounds",
1305 SHT_PROGBITS, SHF_ALLOC);
1307 #endif
1309 if (s->char_is_unsigned) {
1310 tcc_define_symbol(s, "__CHAR_UNSIGNED__", NULL);
1313 /* add debug sections */
1314 if (s->do_debug) {
1315 /* stab symbols */
1316 stab_section = new_section(s, ".stab", SHT_PROGBITS, 0);
1317 stab_section->sh_entsize = sizeof(Stab_Sym);
1318 stabstr_section = new_section(s, ".stabstr", SHT_STRTAB, 0);
1319 put_elf_str(stabstr_section, "");
1320 stab_section->link = stabstr_section;
1321 /* put first entry */
1322 put_stabs("", 0, 0, 0, 0);
1325 /* add libc crt1/crti objects */
1326 #ifndef TCC_TARGET_PE
1327 if ((output_type == TCC_OUTPUT_EXE || output_type == TCC_OUTPUT_DLL) &&
1328 !s->nostdlib) {
1329 if (output_type != TCC_OUTPUT_DLL)
1330 tcc_add_file(s, CONFIG_TCC_CRT_PREFIX "/crt1.o");
1331 tcc_add_file(s, CONFIG_TCC_CRT_PREFIX "/crti.o");
1333 #endif
1335 #ifdef TCC_TARGET_PE
1336 #ifdef CONFIG_TCC_CROSSLIB
1337 snprintf(buf, sizeof(buf), "%s/" CONFIG_TCC_CROSSLIB, s->tcc_lib_path);
1338 tcc_add_library_path(s, buf);
1339 #endif
1340 snprintf(buf, sizeof(buf), "%s/lib", s->tcc_lib_path);
1341 tcc_add_library_path(s, buf);
1342 #ifdef _WIN32
1343 if (GetSystemDirectory(buf, sizeof buf))
1344 tcc_add_library_path(s, buf);
1345 #endif
1346 #endif
1348 return 0;
1351 #define WD_ALL 0x0001 /* warning is activated when using -Wall */
1352 #define FD_INVERT 0x0002 /* invert value before storing */
1354 typedef struct FlagDef {
1355 uint16_t offset;
1356 uint16_t flags;
1357 const char *name;
1358 } FlagDef;
1360 static const FlagDef warning_defs[] = {
1361 { offsetof(TCCState, warn_unsupported), 0, "unsupported" },
1362 { offsetof(TCCState, warn_write_strings), 0, "write-strings" },
1363 { offsetof(TCCState, warn_error), 0, "error" },
1364 { offsetof(TCCState, warn_implicit_function_declaration), WD_ALL,
1365 "implicit-function-declaration" },
1368 ST_FUNC int set_flag(TCCState *s, const FlagDef *flags, int nb_flags,
1369 const char *name, int value)
1371 int i;
1372 const FlagDef *p;
1373 const char *r;
1375 r = name;
1376 if (r[0] == 'n' && r[1] == 'o' && r[2] == '-') {
1377 r += 3;
1378 value = !value;
1380 for(i = 0, p = flags; i < nb_flags; i++, p++) {
1381 if (!strcmp(r, p->name))
1382 goto found;
1384 return -1;
1385 found:
1386 if (p->flags & FD_INVERT)
1387 value = !value;
1388 *(int *)((uint8_t *)s + p->offset) = value;
1389 return 0;
1392 /* set/reset a warning */
1393 LIBTCCAPI int tcc_set_warning(TCCState *s, const char *warning_name, int value)
1395 int i;
1396 const FlagDef *p;
1398 if (!strcmp(warning_name, "all")) {
1399 for(i = 0, p = warning_defs; i < countof(warning_defs); i++, p++) {
1400 if (p->flags & WD_ALL)
1401 *(int *)((uint8_t *)s + p->offset) = 1;
1403 return 0;
1404 } else {
1405 return set_flag(s, warning_defs, countof(warning_defs),
1406 warning_name, value);
1410 static const FlagDef flag_defs[] = {
1411 { offsetof(TCCState, char_is_unsigned), 0, "unsigned-char" },
1412 { offsetof(TCCState, char_is_unsigned), FD_INVERT, "signed-char" },
1413 { offsetof(TCCState, nocommon), FD_INVERT, "common" },
1414 { offsetof(TCCState, leading_underscore), 0, "leading-underscore" },
1417 /* set/reset a flag */
1418 PUB_FUNC int tcc_set_flag(TCCState *s, const char *flag_name, int value)
1420 return set_flag(s, flag_defs, countof(flag_defs),
1421 flag_name, value);
1425 static int strstart(const char *str, const char *val, char **ptr)
1427 const char *p, *q;
1428 p = str;
1429 q = val;
1430 while (*q != '\0') {
1431 if (*p != *q)
1432 return 0;
1433 p++;
1434 q++;
1436 if (ptr)
1437 *ptr = (char *) p;
1438 return 1;
1442 /* Like strstart, but automatically takes into account that ld options can
1444 * - start with double or single dash (e.g. '--soname' or '-soname')
1445 * - arguments can be given as separate or after '=' (e.g. '-Wl,-soname,x.so'
1446 * or '-Wl,-soname=x.so')
1448 * you provide `val` always in 'option[=]' form (no leading -)
1450 static int link_option(const char *str, const char *val, char **ptr)
1452 const char *p, *q;
1454 /* there should be 1 or 2 dashes */
1455 if (*str++ != '-')
1456 return 0;
1457 if (*str == '-')
1458 str++;
1460 /* then str & val should match (potentialy up to '=') */
1461 p = str;
1462 q = val;
1464 while (*q != '\0' && *q != '=') {
1465 if (*p != *q)
1466 return 0;
1467 p++;
1468 q++;
1471 /* '=' near eos means ',' or '=' is ok */
1472 if (*q == '=') {
1473 if (*p != ',' && *p != '=')
1474 return 0;
1475 p++;
1476 q++;
1479 if (ptr)
1480 *ptr = (char *) p;
1481 return 1;
1485 /* set linker options */
1486 PUB_FUNC const char * tcc_set_linker(TCCState *s, char *option, int multi)
1488 char *p = option;
1489 char *end;
1491 while (option && *option) {
1492 end = NULL;
1493 if (link_option(option, "Bsymbolic", &p)) {
1494 s->symbolic = TRUE;
1495 #ifdef TCC_TARGET_PE
1496 } else if (link_option(option, "file-alignment=", &p)) {
1497 s->pe_file_align = strtoul(p, &end, 16);
1498 #endif
1499 } else if (link_option(option, "fini=", &p)) {
1500 s->fini_symbol = p;
1501 if (s->warn_unsupported)
1502 warning("ignoring -fini %s", p);
1504 } else if (link_option(option, "image-base=", &p)) {
1505 s->text_addr = strtoul(p, &end, 16);
1506 s->has_text_addr = 1;
1507 } else if (link_option(option, "init=", &p)) {
1508 s->init_symbol = p;
1509 if (s->warn_unsupported)
1510 warning("ignoring -init %s", p);
1512 } else if (link_option(option, "oformat=", &p)) {
1513 #if defined(TCC_TARGET_PE)
1514 if (strstart(p, "pe-", NULL)) {
1515 #else
1516 #if defined(TCC_TARGET_X86_64)
1517 if (strstart(p, "elf64-", NULL)) {
1518 #else
1519 if (strstart(p, "elf32-", NULL)) {
1520 #endif
1521 #endif
1522 s->output_format = TCC_OUTPUT_FORMAT_ELF;
1523 } else if (!strcmp(p, "binary")) {
1524 s->output_format = TCC_OUTPUT_FORMAT_BINARY;
1525 } else
1526 #ifdef TCC_TARGET_COFF
1527 if (!strcmp(p, "coff")) {
1528 s->output_format = TCC_OUTPUT_FORMAT_COFF;
1529 } else
1530 #endif
1532 return p;
1535 } else if (link_option(option, "rpath=", &p)) {
1536 s->rpath = p;
1537 } else if (link_option(option, "section-alignment=", &p)) {
1538 s->section_align = strtoul(p, &end, 16);
1539 } else if (link_option(option, "soname=", &p)) {
1540 s->soname = p;
1541 multi = 0;
1542 #ifdef TCC_TARGET_PE
1543 } else if (link_option(option, "subsystem=", &p)) {
1544 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
1545 if (!strcmp(p, "native")) {
1546 s->pe_subsystem = 1;
1547 } else if (!strcmp(p, "console")) {
1548 s->pe_subsystem = 3;
1549 } else if (!strcmp(p, "gui")) {
1550 s->pe_subsystem = 2;
1551 } else if (!strcmp(p, "posix")) {
1552 s->pe_subsystem = 7;
1553 } else if (!strcmp(p, "efiapp")) {
1554 s->pe_subsystem = 10;
1555 } else if (!strcmp(p, "efiboot")) {
1556 s->pe_subsystem = 11;
1557 } else if (!strcmp(p, "efiruntime")) {
1558 s->pe_subsystem = 12;
1559 } else if (!strcmp(p, "efirom")) {
1560 s->pe_subsystem = 13;
1561 #elif defined(TCC_TARGET_ARM)
1562 if (!strcmp(p, "wince")) {
1563 s->pe_subsystem = 9;
1564 #endif
1565 } else {
1566 return p;
1568 #endif
1570 } else if (link_option(option, "Ttext=", &p)) {
1571 s->text_addr = strtoul(p, &end, 16);
1572 s->has_text_addr = 1;
1574 } else {
1575 return option;
1578 if (multi) {
1579 option = NULL;
1580 p = strchr( (end) ? end : p, ',');
1581 if (p) {
1582 *p = 0; /* terminate last option */
1583 option = ++p;
1585 } else
1586 option = NULL;
1588 return NULL;
1591 PUB_FUNC void tcc_print_stats(TCCState *s, int64_t total_time)
1593 double tt;
1594 tt = (double)total_time / 1000000.0;
1595 if (tt < 0.001)
1596 tt = 0.001;
1597 if (total_bytes < 1)
1598 total_bytes = 1;
1599 printf("%d idents, %d lines, %d bytes, %0.3f s, %d lines/s, %0.1f MB/s\n",
1600 tok_ident - TOK_IDENT, total_lines, total_bytes,
1601 tt, (int)(total_lines / tt),
1602 total_bytes / tt / 1000000.0);
1605 /* set CONFIG_TCCDIR at runtime */
1606 LIBTCCAPI void tcc_set_lib_path(TCCState *s, const char *path)
1608 tcc_free(s->tcc_lib_path);
1609 s->tcc_lib_path = tcc_strdup(path);
1612 PUB_FUNC void set_num_callers(int n)
1614 #ifdef CONFIG_TCC_BACKTRACE
1615 num_callers = n;
1616 #endif
1620 LIBTCCAPI const char *tcc_default_target(TCCState *s)
1622 /* FIXME will break in multithreaded case */
1623 static char outfile_default[1024];
1625 char *ext;
1626 const char *name =
1627 strcmp(s->input_files[0], "-") == 0 ? "a"
1628 : tcc_basename(s->input_files[0]);
1629 pstrcpy(outfile_default, sizeof(outfile_default), name);
1630 ext = tcc_fileextension(outfile_default);
1631 #ifdef TCC_TARGET_PE
1632 if (s->output_type == TCC_OUTPUT_DLL)
1633 strcpy(ext, ".dll");
1634 else
1635 if (s->output_type == TCC_OUTPUT_EXE)
1636 strcpy(ext, ".exe");
1637 else
1638 #endif
1639 if (( (s->output_type == TCC_OUTPUT_OBJ && !s->reloc_output) ||
1640 (s->output_type == TCC_OUTPUT_PREPROCESS) )
1641 && *ext)
1642 strcpy(ext, ".o");
1643 else
1644 pstrcpy(outfile_default, sizeof(outfile_default), "a.out");
1646 return outfile_default;
1650 LIBTCCAPI void tcc_gen_makedeps(TCCState *s, const char *target, const char *filename)
1652 FILE *depout;
1653 char buf[1024], *ext;
1654 int i;
1656 if (!target)
1657 target = tcc_default_target(s);
1659 if (!filename) {
1660 /* compute filename automatically
1661 * dir/file.o -> dir/file.d */
1662 pstrcpy(buf, sizeof(buf), target);
1663 ext = tcc_fileextension(buf);
1664 pstrcpy(ext, sizeof(buf) - (ext-buf), ".d");
1665 filename = buf;
1668 if (s->verbose)
1669 printf("<- %s\n", filename);
1671 /* XXX return err codes instead of error() ? */
1672 depout = fopen(filename, "w");
1673 if (!depout)
1674 error("could not open '%s'", filename);
1676 fprintf(depout, "%s : \\\n", target);
1677 for (i=0; i<s->nb_target_deps; ++i)
1678 fprintf(depout, "\t%s \\\n", s->target_deps[i]);
1679 fprintf(depout, "\n");
1680 fclose(depout);