Added what I call virtual io to tinycc this way we can make a monolitic executable...
[tinycc.git] / libtcc.c
blobf554f7436b1a8e984efc6e218f68d04c48b9360f
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 #ifdef ONE_SOURCE
38 #include "tccpp.c"
39 #include "tccgen.c"
40 #include "tccelf.c"
41 #include "tccrun.c"
42 #ifdef TCC_TARGET_I386
43 #include "i386-gen.c"
44 #endif
45 #ifdef TCC_TARGET_ARM
46 #include "arm-gen.c"
47 #endif
48 #ifdef TCC_TARGET_C67
49 #include "c67-gen.c"
50 #endif
51 #ifdef TCC_TARGET_X86_64
52 #include "x86_64-gen.c"
53 #endif
54 #ifdef CONFIG_TCC_ASM
55 #include "tccasm.c"
56 #if defined TCC_TARGET_I386 || defined TCC_TARGET_X86_64
57 #include "i386-asm.c"
58 #endif
59 #endif
60 #ifdef TCC_TARGET_COFF
61 #include "tcccoff.c"
62 #endif
63 #ifdef TCC_TARGET_PE
64 #include "tccpe.c"
65 #endif
66 #endif /* ONE_SOURCE */
68 /********************************************************/
69 #ifndef CONFIG_TCC_ASM
70 ST_FUNC void asm_instr(void)
72 tcc_error("inline asm() not supported");
74 ST_FUNC void asm_global_instr(void)
76 tcc_error("inline asm() not supported");
78 #endif
80 /********************************************************/
82 #ifdef _WIN32
83 static char *normalize_slashes(char *path)
85 char *p;
86 for (p = path; *p; ++p)
87 if (*p == '\\')
88 *p = '/';
89 return path;
92 static HMODULE tcc_module;
94 /* on win32, we suppose the lib and includes are at the location of 'tcc.exe' */
95 static void tcc_set_lib_path_w32(TCCState *s)
97 char path[1024], *p;
98 GetModuleFileNameA(tcc_module, path, sizeof path);
99 p = tcc_basename(normalize_slashes(strlwr(path)));
100 if (p - 5 > path && 0 == strncmp(p - 5, "/bin/", 5))
101 p -= 5;
102 else if (p > path)
103 p--;
104 *p = 0;
105 tcc_set_lib_path(s, path);
108 static void tcc_add_systemdir(TCCState *s)
110 char buf[1000];
111 GetSystemDirectory(buf, sizeof buf);
112 tcc_add_library_path(s, normalize_slashes(buf));
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 PUB_FUNC char *pstrncpy(char *out, const char *in, size_t num)
165 memcpy(out, in, num);
166 out[num] = '\0';
167 return out;
170 /* extract the basename of a file */
171 PUB_FUNC char *tcc_basename(const char *name)
173 char *p = strchr(name, 0);
174 while (p > name && !IS_DIRSEP(p[-1]))
175 --p;
176 return p;
179 /* extract extension part of a file
181 * (if no extension, return pointer to end-of-string)
183 PUB_FUNC char *tcc_fileextension (const char *name)
185 char *b = tcc_basename(name);
186 char *e = strrchr(b, '.');
187 return e ? e : strchr(b, 0);
190 /********************************************************/
191 /* memory management */
193 #undef free
194 #undef malloc
195 #undef realloc
197 #ifdef MEM_DEBUG
198 int mem_cur_size;
199 int mem_max_size;
200 unsigned malloc_usable_size(void*);
201 #endif
203 PUB_FUNC void tcc_free(void *ptr)
205 #ifdef MEM_DEBUG
206 mem_cur_size -= malloc_usable_size(ptr);
207 #endif
208 free(ptr);
211 PUB_FUNC void *tcc_malloc(unsigned long size)
213 void *ptr;
214 ptr = malloc(size);
215 if (!ptr && size)
216 tcc_error("memory full");
217 #ifdef MEM_DEBUG
218 mem_cur_size += malloc_usable_size(ptr);
219 if (mem_cur_size > mem_max_size)
220 mem_max_size = mem_cur_size;
221 #endif
222 return ptr;
225 PUB_FUNC void *tcc_mallocz(unsigned long size)
227 void *ptr;
228 ptr = tcc_malloc(size);
229 memset(ptr, 0, size);
230 return ptr;
233 PUB_FUNC void *tcc_realloc(void *ptr, unsigned long size)
235 void *ptr1;
236 #ifdef MEM_DEBUG
237 mem_cur_size -= malloc_usable_size(ptr);
238 #endif
239 ptr1 = realloc(ptr, size);
240 if (!ptr1 && size)
241 tcc_error("memory full");
242 #ifdef MEM_DEBUG
243 /* NOTE: count not correct if alloc error, but not critical */
244 mem_cur_size += malloc_usable_size(ptr1);
245 if (mem_cur_size > mem_max_size)
246 mem_max_size = mem_cur_size;
247 #endif
248 return ptr1;
251 PUB_FUNC char *tcc_strdup(const char *str)
253 char *ptr;
254 ptr = tcc_malloc(strlen(str) + 1);
255 strcpy(ptr, str);
256 return ptr;
259 PUB_FUNC void tcc_memstats(void)
261 #ifdef MEM_DEBUG
262 printf("memory in use: %d\n", mem_cur_size);
263 #endif
266 #define free(p) use_tcc_free(p)
267 #define malloc(s) use_tcc_malloc(s)
268 #define realloc(p, s) use_tcc_realloc(p, s)
270 /********************************************************/
271 /* virtual io */
273 LIBTCCAPI void tcc_set_vio_module(TCCState *s, vio_module_t *vio_module){
274 s->vio_module = vio_module;
275 vio_module->tcc_state = s;
278 void vio_initialize(vio_fd *fd) {
279 fd->fd = -1;
280 fd->vio_udata = NULL;
281 fd->vio_module = NULL;
284 int vio_open(struct TCCState *s, vio_fd *fd, const char *fn, int oflag) {
285 int rc;
286 vio_initialize(fd);
287 fd->vio_module = s->vio_module;
288 if(s->vio_module && (s->vio_module->call_vio_open_flags & CALL_VIO_OPEN_FIRST)) {
289 rc = s->vio_module->vio_open(fd, fn, oflag);
290 if(rc >= 0) return rc;
293 fd->fd = open(fn, oflag);
295 if(fd->fd < 0 && s->vio_module && (s->vio_module->call_vio_open_flags & CALL_VIO_OPEN_LAST)) {
296 rc = s->vio_module->vio_open(fd, fn, oflag);
297 if(rc >= 0) return rc;
299 //printf("vio_open = %d %s\n", fd->fd, fn);
300 return fd->fd;
303 off_t vio_lseek(vio_fd fd, off_t offset, int whence) {
304 if(fd.vio_udata) {
305 return fd.vio_module->vio_lseek(fd, offset, whence);
307 return lseek(fd.fd, offset, whence);
310 size_t vio_read(vio_fd fd, void *buf, size_t bytes) {
311 if(fd.vio_udata) {
312 return fd.vio_module->vio_read(fd, buf, bytes);
314 return read(fd.fd, buf, bytes);
317 int vio_close(vio_fd *fd) {
318 int rc = 0;
319 if(fd->vio_udata){
320 fd->vio_module->vio_close(fd);
321 } else rc = close(fd->fd);
322 vio_initialize(fd);
323 return rc;
326 /********************************************************/
327 /* dynarrays */
329 PUB_FUNC void dynarray_add(void ***ptab, int *nb_ptr, void *data)
331 int nb, nb_alloc;
332 void **pp;
334 nb = *nb_ptr;
335 pp = *ptab;
336 /* every power of two we double array size */
337 if ((nb & (nb - 1)) == 0) {
338 if (!nb)
339 nb_alloc = 1;
340 else
341 nb_alloc = nb * 2;
342 pp = tcc_realloc(pp, nb_alloc * sizeof(void *));
343 *ptab = pp;
345 pp[nb++] = data;
346 *nb_ptr = nb;
349 PUB_FUNC void dynarray_reset(void *pp, int *n)
351 void **p;
352 for (p = *(void***)pp; *n; ++p, --*n)
353 if (*p)
354 tcc_free(*p);
355 tcc_free(*(void**)pp);
356 *(void**)pp = NULL;
359 static void tcc_split_path(TCCState *s, void ***p_ary, int *p_nb_ary, const char *in)
361 const char *p;
362 do {
363 int c;
364 CString str;
366 cstr_new(&str);
367 for (p = in; c = *p, c != '\0' && c != PATHSEP; ++p) {
368 if (c == '{' && p[1] && p[2] == '}') {
369 c = p[1], p += 2;
370 if (c == 'B')
371 cstr_cat(&str, s->tcc_lib_path);
372 } else {
373 cstr_ccat(&str, c);
376 cstr_ccat(&str, '\0');
377 dynarray_add(p_ary, p_nb_ary, str.data);
378 in = p+1;
379 } while (*p);
382 /********************************************************/
384 ST_FUNC Section *new_section(TCCState *s1, const char *name, int sh_type, int sh_flags)
386 Section *sec;
388 sec = tcc_mallocz(sizeof(Section) + strlen(name));
389 strcpy(sec->name, name);
390 sec->sh_type = sh_type;
391 sec->sh_flags = sh_flags;
392 switch(sh_type) {
393 case SHT_HASH:
394 case SHT_REL:
395 case SHT_RELA:
396 case SHT_DYNSYM:
397 case SHT_SYMTAB:
398 case SHT_DYNAMIC:
399 sec->sh_addralign = 4;
400 break;
401 case SHT_STRTAB:
402 sec->sh_addralign = 1;
403 break;
404 default:
405 sec->sh_addralign = 32; /* default conservative alignment */
406 break;
409 if (sh_flags & SHF_PRIVATE) {
410 dynarray_add((void ***)&s1->priv_sections, &s1->nb_priv_sections, sec);
411 } else {
412 sec->sh_num = s1->nb_sections;
413 dynarray_add((void ***)&s1->sections, &s1->nb_sections, sec);
416 return sec;
419 static void free_section(Section *s)
421 tcc_free(s->data);
424 /* realloc section and set its content to zero */
425 ST_FUNC void section_realloc(Section *sec, unsigned long new_size)
427 unsigned long size;
428 unsigned char *data;
430 size = sec->data_allocated;
431 if (size == 0)
432 size = 1;
433 while (size < new_size)
434 size = size * 2;
435 data = tcc_realloc(sec->data, size);
436 memset(data + sec->data_allocated, 0, size - sec->data_allocated);
437 sec->data = data;
438 sec->data_allocated = size;
441 /* reserve at least 'size' bytes in section 'sec' from
442 sec->data_offset. */
443 ST_FUNC void *section_ptr_add(Section *sec, unsigned long size)
445 unsigned long offset, offset1;
447 offset = sec->data_offset;
448 offset1 = offset + size;
449 if (offset1 > sec->data_allocated)
450 section_realloc(sec, offset1);
451 sec->data_offset = offset1;
452 return sec->data + offset;
455 /* reserve at least 'size' bytes from section start */
456 ST_FUNC void section_reserve(Section *sec, unsigned long size)
458 if (size > sec->data_allocated)
459 section_realloc(sec, size);
460 if (size > sec->data_offset)
461 sec->data_offset = size;
464 /* return a reference to a section, and create it if it does not
465 exists */
466 ST_FUNC Section *find_section(TCCState *s1, const char *name)
468 Section *sec;
469 int i;
470 for(i = 1; i < s1->nb_sections; i++) {
471 sec = s1->sections[i];
472 if (!strcmp(name, sec->name))
473 return sec;
475 /* sections are created as PROGBITS */
476 return new_section(s1, name, SHT_PROGBITS, SHF_ALLOC);
479 /* update sym->c so that it points to an external symbol in section
480 'section' with value 'value' */
481 ST_FUNC void put_extern_sym2(Sym *sym, Section *section,
482 uplong value, unsigned long size,
483 int can_add_underscore)
485 int sym_type, sym_bind, sh_num, info, other;
486 ElfW(Sym) *esym;
487 const char *name;
488 char buf1[256];
490 if (section == NULL)
491 sh_num = SHN_UNDEF;
492 else if (section == SECTION_ABS)
493 sh_num = SHN_ABS;
494 else
495 sh_num = section->sh_num;
497 if ((sym->type.t & VT_BTYPE) == VT_FUNC) {
498 sym_type = STT_FUNC;
499 } else if ((sym->type.t & VT_BTYPE) == VT_VOID) {
500 sym_type = STT_NOTYPE;
501 } else {
502 sym_type = STT_OBJECT;
505 if (sym->type.t & VT_STATIC)
506 sym_bind = STB_LOCAL;
507 else {
508 if (sym->type.t & VT_WEAK)
509 sym_bind = STB_WEAK;
510 else
511 sym_bind = STB_GLOBAL;
514 if (!sym->c) {
515 name = get_tok_str(sym->v, NULL);
516 #ifdef CONFIG_TCC_BCHECK
517 if (tcc_state->do_bounds_check) {
518 char buf[32];
520 /* XXX: avoid doing that for statics ? */
521 /* if bound checking is activated, we change some function
522 names by adding the "__bound" prefix */
523 switch(sym->v) {
524 #ifdef TCC_TARGET_PE
525 /* XXX: we rely only on malloc hooks */
526 case TOK_malloc:
527 case TOK_free:
528 case TOK_realloc:
529 case TOK_memalign:
530 case TOK_calloc:
531 #endif
532 case TOK_memcpy:
533 case TOK_memmove:
534 case TOK_memset:
535 case TOK_strlen:
536 case TOK_strcpy:
537 case TOK_alloca:
538 strcpy(buf, "__bound_");
539 strcat(buf, name);
540 name = buf;
541 break;
544 #endif
545 other = 0;
547 #ifdef TCC_TARGET_PE
548 if (sym->type.t & VT_EXPORT)
549 other |= 1;
550 if (sym_type == STT_FUNC && sym->type.ref) {
551 int attr = sym->type.ref->r;
552 if (FUNC_EXPORT(attr))
553 other |= 1;
554 if (FUNC_CALL(attr) == FUNC_STDCALL && can_add_underscore) {
555 sprintf(buf1, "_%s@%d", name, FUNC_ARGS(attr) * PTR_SIZE);
556 name = buf1;
557 other |= 2;
558 can_add_underscore = 0;
560 } else {
561 if (find_elf_sym(tcc_state->dynsymtab_section, name))
562 other |= 4;
563 if (sym->type.t & VT_IMPORT)
564 other |= 4;
566 #endif
567 if (tcc_state->leading_underscore && can_add_underscore) {
568 buf1[0] = '_';
569 pstrcpy(buf1 + 1, sizeof(buf1) - 1, name);
570 name = buf1;
572 if (sym->asm_label) {
573 name = sym->asm_label;
575 info = ELFW(ST_INFO)(sym_bind, sym_type);
576 sym->c = add_elf_sym(symtab_section, value, size, info, other, sh_num, name);
577 } else {
578 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
579 esym->st_value = value;
580 esym->st_size = size;
581 esym->st_shndx = sh_num;
585 ST_FUNC void put_extern_sym(Sym *sym, Section *section,
586 uplong value, unsigned long size)
588 put_extern_sym2(sym, section, value, size, 1);
591 /* add a new relocation entry to symbol 'sym' in section 's' */
592 ST_FUNC void greloc(Section *s, Sym *sym, unsigned long offset, int type)
594 int c = 0;
595 if (sym) {
596 if (0 == sym->c)
597 put_extern_sym(sym, NULL, 0, 0);
598 c = sym->c;
600 /* now we can add ELF relocation info */
601 put_elf_reloc(symtab_section, s, offset, type, c);
604 /********************************************************/
606 static void strcat_vprintf(char *buf, int buf_size, const char *fmt, va_list ap)
608 int len;
609 len = strlen(buf);
610 vsnprintf(buf + len, buf_size - len, fmt, ap);
613 static void strcat_printf(char *buf, int buf_size, const char *fmt, ...)
615 va_list ap;
616 va_start(ap, fmt);
617 strcat_vprintf(buf, buf_size, fmt, ap);
618 va_end(ap);
621 static void error1(TCCState *s1, int is_warning, const char *fmt, va_list ap)
623 char buf[2048];
624 BufferedFile **f;
626 buf[0] = '\0';
627 if (file) {
628 for(f = s1->include_stack; f < s1->include_stack_ptr; f++)
629 strcat_printf(buf, sizeof(buf), "In file included from %s:%d:\n",
630 (*f)->filename, (*f)->line_num);
631 if (file->line_num > 0) {
632 strcat_printf(buf, sizeof(buf),
633 "%s:%d: ", file->filename, file->line_num);
634 } else {
635 strcat_printf(buf, sizeof(buf),
636 "%s: ", file->filename);
638 } else {
639 strcat_printf(buf, sizeof(buf),
640 "tcc: ");
642 if (is_warning)
643 strcat_printf(buf, sizeof(buf), "warning: ");
644 else
645 strcat_printf(buf, sizeof(buf), "error: ");
646 strcat_vprintf(buf, sizeof(buf), fmt, ap);
648 if (!s1->error_func) {
649 /* default case: stderr */
650 fprintf(stderr, "%s\n", buf);
651 } else {
652 s1->error_func(s1->error_opaque, buf);
654 if (!is_warning || s1->warn_error)
655 s1->nb_errors++;
658 LIBTCCAPI void tcc_set_error_func(TCCState *s, void *error_opaque,
659 void (*error_func)(void *opaque, const char *msg))
661 s->error_opaque = error_opaque;
662 s->error_func = error_func;
665 /* error without aborting current compilation */
666 PUB_FUNC void tcc_error_noabort(const char *fmt, ...)
668 TCCState *s1 = tcc_state;
669 va_list ap;
671 va_start(ap, fmt);
672 error1(s1, 0, fmt, ap);
673 va_end(ap);
676 PUB_FUNC void tcc_error(const char *fmt, ...)
678 TCCState *s1 = tcc_state;
679 va_list ap;
681 va_start(ap, fmt);
682 error1(s1, 0, fmt, ap);
683 va_end(ap);
684 /* better than nothing: in some cases, we accept to handle errors */
685 if (s1->error_set_jmp_enabled) {
686 longjmp(s1->error_jmp_buf, 1);
687 } else {
688 /* XXX: eliminate this someday */
689 exit(1);
693 PUB_FUNC void tcc_warning(const char *fmt, ...)
695 TCCState *s1 = tcc_state;
696 va_list ap;
698 if (s1->warn_none)
699 return;
701 va_start(ap, fmt);
702 error1(s1, 1, fmt, ap);
703 va_end(ap);
706 /********************************************************/
707 /* I/O layer */
709 ST_FUNC void tcc_open_bf(TCCState *s1, const char *filename, int initlen)
711 BufferedFile *bf;
712 int buflen = initlen ? initlen : IO_BUF_SIZE;
714 bf = tcc_malloc(sizeof(BufferedFile) + buflen);
715 bf->buf_ptr = bf->buffer;
716 bf->buf_end = bf->buffer + initlen;
717 bf->buf_end[0] = CH_EOB; /* put eob symbol */
718 pstrcpy(bf->filename, sizeof(bf->filename), filename);
719 #ifdef _WIN32
720 normalize_slashes(bf->filename);
721 #endif
722 bf->line_num = 1;
723 bf->ifndef_macro = 0;
724 bf->ifdef_stack_ptr = s1->ifdef_stack_ptr;
725 vio_initialize(&bf->fd);
726 bf->prev = file;
727 file = bf;
730 ST_FUNC void tcc_close(void)
732 BufferedFile *bf = file;
733 if (bf->fd.fd > 0) {
734 vio_close(&bf->fd);
735 total_lines += bf->line_num;
737 file = bf->prev;
738 tcc_free(bf);
741 ST_FUNC vio_fd tcc_open(TCCState *s1, const char *filename)
743 vio_fd fd;
744 if (strcmp(filename, "-") == 0) {
745 vio_initialize(&fd);
746 fd.fd = 0, filename = "stdin";
748 else
749 vio_open(s1, &fd, filename, O_RDONLY | O_BINARY);
750 if ((s1->verbose == 2 && fd.fd >= 0) || s1->verbose == 3)
751 printf("%s %*s%s\n", fd.fd < 0 ? "nf":"->",
752 (int)(s1->include_stack_ptr - s1->include_stack), "", filename);
753 if (fd.fd < 0)
754 return fd;
756 tcc_open_bf(s1, filename, 0);
757 file->fd = fd;
758 return fd;
761 /* compile the C file opened in 'file'. Return non zero if errors. */
762 static int tcc_compile(TCCState *s1)
764 Sym *define_start;
765 SValue *pvtop;
766 char buf[512];
767 volatile int section_sym;
769 #ifdef INC_DEBUG
770 printf("%s: **** new file\n", file->filename);
771 #endif
772 preprocess_init(s1);
774 cur_text_section = NULL;
775 funcname = "";
776 anon_sym = SYM_FIRST_ANOM;
778 /* file info: full path + filename */
779 section_sym = 0; /* avoid warning */
780 if (s1->do_debug) {
781 section_sym = put_elf_sym(symtab_section, 0, 0,
782 ELFW(ST_INFO)(STB_LOCAL, STT_SECTION), 0,
783 text_section->sh_num, NULL);
784 getcwd(buf, sizeof(buf));
785 #ifdef _WIN32
786 normalize_slashes(buf);
787 #endif
788 pstrcat(buf, sizeof(buf), "/");
789 put_stabs_r(buf, N_SO, 0, 0,
790 text_section->data_offset, text_section, section_sym);
791 put_stabs_r(file->filename, N_SO, 0, 0,
792 text_section->data_offset, text_section, section_sym);
794 /* an elf symbol of type STT_FILE must be put so that STB_LOCAL
795 symbols can be safely used */
796 put_elf_sym(symtab_section, 0, 0,
797 ELFW(ST_INFO)(STB_LOCAL, STT_FILE), 0,
798 SHN_ABS, file->filename);
800 /* define some often used types */
801 int_type.t = VT_INT;
803 char_pointer_type.t = VT_BYTE;
804 mk_pointer(&char_pointer_type);
806 #if PTR_SIZE == 4
807 size_type.t = VT_INT;
808 #else
809 size_type.t = VT_LLONG;
810 #endif
812 func_old_type.t = VT_FUNC;
813 func_old_type.ref = sym_push(SYM_FIELD, &int_type, FUNC_CDECL, FUNC_OLD);
815 #if defined(TCC_ARM_EABI) && defined(TCC_ARM_VFP)
816 float_type.t = VT_FLOAT;
817 double_type.t = VT_DOUBLE;
819 func_float_type.t = VT_FUNC;
820 func_float_type.ref = sym_push(SYM_FIELD, &float_type, FUNC_CDECL, FUNC_OLD);
821 func_double_type.t = VT_FUNC;
822 func_double_type.ref = sym_push(SYM_FIELD, &double_type, FUNC_CDECL, FUNC_OLD);
823 #endif
825 #if 0
826 /* define 'void *alloca(unsigned int)' builtin function */
828 Sym *s1;
830 p = anon_sym++;
831 sym = sym_push(p, mk_pointer(VT_VOID), FUNC_CDECL, FUNC_NEW);
832 s1 = sym_push(SYM_FIELD, VT_UNSIGNED | VT_INT, 0, 0);
833 s1->next = NULL;
834 sym->next = s1;
835 sym_push(TOK_alloca, VT_FUNC | (p << VT_STRUCT_SHIFT), VT_CONST, 0);
837 #endif
839 define_start = define_stack;
840 nocode_wanted = 1;
842 if (setjmp(s1->error_jmp_buf) == 0) {
843 s1->nb_errors = 0;
844 s1->error_set_jmp_enabled = 1;
846 ch = file->buf_ptr[0];
847 tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
848 parse_flags = PARSE_FLAG_PREPROCESS | PARSE_FLAG_TOK_NUM;
849 pvtop = vtop;
850 next();
851 decl(VT_CONST);
852 if (tok != TOK_EOF)
853 expect("declaration");
854 if (pvtop != vtop)
855 tcc_warning("internal compiler error: vstack leak? (%d)", vtop - pvtop);
857 /* end of translation unit info */
858 if (s1->do_debug) {
859 put_stabs_r(NULL, N_SO, 0, 0,
860 text_section->data_offset, text_section, section_sym);
864 s1->error_set_jmp_enabled = 0;
866 /* reset define stack, but leave -Dsymbols (may be incorrect if
867 they are undefined) */
868 free_defines(define_start);
870 gen_inline_functions();
872 sym_pop(&global_stack, NULL);
873 sym_pop(&local_stack, NULL);
875 return s1->nb_errors != 0 ? -1 : 0;
878 LIBTCCAPI int tcc_compile_named_string(TCCState *s, const char *str, const char *strname)
880 int len, ret;
881 len = strlen(str);
883 tcc_open_bf(s, strname ? strname : "<string>", len);
884 memcpy(file->buffer, str, len);
885 ret = tcc_compile(s);
886 tcc_close();
887 return ret;
890 LIBTCCAPI int tcc_compile_string(TCCState *s, const char *str)
892 return tcc_compile_named_string(s, str, NULL);
895 /* define a preprocessor symbol. A value can also be provided with the '=' operator */
896 LIBTCCAPI void tcc_define_symbol(TCCState *s1, const char *sym, const char *value)
898 int len1, len2;
899 /* default value */
900 if (!value)
901 value = "1";
902 len1 = strlen(sym);
903 len2 = strlen(value);
905 /* init file structure */
906 tcc_open_bf(s1, "<define>", len1 + len2 + 1);
907 memcpy(file->buffer, sym, len1);
908 file->buffer[len1] = ' ';
909 memcpy(file->buffer + len1 + 1, value, len2);
911 /* parse with define parser */
912 ch = file->buf_ptr[0];
913 next_nomacro();
914 parse_define();
916 tcc_close();
919 /* undefine a preprocessor symbol */
920 LIBTCCAPI void tcc_undefine_symbol(TCCState *s1, const char *sym)
922 TokenSym *ts;
923 Sym *s;
924 ts = tok_alloc(sym, strlen(sym));
925 s = define_find(ts->tok);
926 /* undefine symbol by putting an invalid name */
927 if (s)
928 define_undef(s);
931 static void tcc_cleanup(void)
933 int i, n;
935 if (NULL == tcc_state)
936 return;
937 tcc_state = NULL;
939 /* free -D defines */
940 free_defines(NULL);
942 /* free tokens */
943 n = tok_ident - TOK_IDENT;
944 for(i = 0; i < n; i++)
945 tcc_free(table_ident[i]);
946 tcc_free(table_ident);
948 /* free sym_pools */
949 dynarray_reset(&sym_pools, &nb_sym_pools);
950 /* string buffer */
951 cstr_free(&tokcstr);
952 /* reset symbol stack */
953 sym_free_first = NULL;
954 /* cleanup from error/setjmp */
955 macro_ptr = NULL;
958 LIBTCCAPI TCCState *tcc_new(void)
960 TCCState *s;
961 char buffer[100];
962 int a,b,c;
964 tcc_cleanup();
966 s = tcc_mallocz(sizeof(TCCState));
967 if (!s)
968 return NULL;
969 tcc_state = s;
970 #ifdef _WIN32
971 tcc_set_lib_path_w32(s);
972 #else
973 tcc_set_lib_path(s, CONFIG_TCCDIR);
974 #endif
975 s->output_type = TCC_OUTPUT_MEMORY;
976 preprocess_new();
977 s->include_stack_ptr = s->include_stack;
979 /* we add dummy defines for some special macros to speed up tests
980 and to have working defined() */
981 define_push(TOK___LINE__, MACRO_OBJ, NULL, NULL);
982 define_push(TOK___FILE__, MACRO_OBJ, NULL, NULL);
983 define_push(TOK___DATE__, MACRO_OBJ, NULL, NULL);
984 define_push(TOK___TIME__, MACRO_OBJ, NULL, NULL);
986 /* standard defines */
987 tcc_define_symbol(s, "__STDC__", NULL);
988 tcc_define_symbol(s, "__STDC_VERSION__", "199901L");
989 #if defined(TCC_TARGET_I386)
990 tcc_define_symbol(s, "__i386__", NULL);
991 tcc_define_symbol(s, "__i386", NULL);
992 tcc_define_symbol(s, "i386", NULL);
993 #endif
994 #if defined(TCC_TARGET_X86_64)
995 tcc_define_symbol(s, "__x86_64__", NULL);
996 #endif
997 #if defined(TCC_TARGET_ARM)
998 tcc_define_symbol(s, "__ARM_ARCH_4__", NULL);
999 tcc_define_symbol(s, "__arm_elf__", NULL);
1000 tcc_define_symbol(s, "__arm_elf", NULL);
1001 tcc_define_symbol(s, "arm_elf", NULL);
1002 tcc_define_symbol(s, "__arm__", NULL);
1003 tcc_define_symbol(s, "__arm", NULL);
1004 tcc_define_symbol(s, "arm", NULL);
1005 tcc_define_symbol(s, "__APCS_32__", NULL);
1006 #endif
1007 #ifdef TCC_TARGET_PE
1008 tcc_define_symbol(s, "_WIN32", NULL);
1009 #ifdef TCC_TARGET_X86_64
1010 tcc_define_symbol(s, "_WIN64", NULL);
1011 #endif
1012 #else
1013 tcc_define_symbol(s, "__unix__", NULL);
1014 tcc_define_symbol(s, "__unix", NULL);
1015 tcc_define_symbol(s, "unix", NULL);
1016 #if defined(__FreeBSD__)
1017 #define str(s) #s
1018 tcc_define_symbol(s, "__FreeBSD__", str( __FreeBSD__));
1019 #undef str
1020 #endif
1021 #if defined(__FreeBSD_kernel__)
1022 tcc_define_symbol(s, "__FreeBSD_kernel__", NULL);
1023 #endif
1024 #if defined(__linux)
1025 tcc_define_symbol(s, "__linux__", NULL);
1026 tcc_define_symbol(s, "__linux", NULL);
1027 #endif
1028 #endif
1029 /* tiny C specific defines */
1030 sscanf(TCC_VERSION, "%d.%d.%d", &a, &b, &c);
1031 sprintf(buffer, "%d", a*10000 + b*100 + c);
1032 tcc_define_symbol(s, "__TINYC__", buffer);
1034 /* tiny C & gcc defines */
1035 #if defined TCC_TARGET_PE && defined TCC_TARGET_X86_64
1036 tcc_define_symbol(s, "__SIZE_TYPE__", "unsigned long long");
1037 tcc_define_symbol(s, "__PTRDIFF_TYPE__", "long long");
1038 #else
1039 tcc_define_symbol(s, "__SIZE_TYPE__", "unsigned long");
1040 tcc_define_symbol(s, "__PTRDIFF_TYPE__", "long");
1041 #endif
1043 #ifdef TCC_TARGET_PE
1044 tcc_define_symbol(s, "__WCHAR_TYPE__", "unsigned short");
1045 #else
1046 tcc_define_symbol(s, "__WCHAR_TYPE__", "int");
1047 #endif
1049 /* glibc defines */
1050 tcc_define_symbol(s, "__REDIRECT(name, proto, alias)", "name proto __asm__ (#alias)");
1051 tcc_define_symbol(s, "__REDIRECT_NTH(name, proto, alias)", "name proto __asm__ (#alias) __THROW");
1053 #ifndef TCC_TARGET_PE
1054 /* default library paths */
1055 tcc_add_library_path(s, CONFIG_TCC_LIBPATHS);
1056 /* paths for crt objects */
1057 tcc_split_path(s, (void ***)&s->crt_paths, &s->nb_crt_paths, CONFIG_TCC_CRTPREFIX);
1058 #endif
1060 /* no section zero */
1061 dynarray_add((void ***)&s->sections, &s->nb_sections, NULL);
1063 /* create standard sections */
1064 text_section = new_section(s, ".text", SHT_PROGBITS, SHF_ALLOC | SHF_EXECINSTR);
1065 data_section = new_section(s, ".data", SHT_PROGBITS, SHF_ALLOC | SHF_WRITE);
1066 bss_section = new_section(s, ".bss", SHT_NOBITS, SHF_ALLOC | SHF_WRITE);
1068 /* symbols are always generated for linking stage */
1069 symtab_section = new_symtab(s, ".symtab", SHT_SYMTAB, 0,
1070 ".strtab",
1071 ".hashtab", SHF_PRIVATE);
1072 strtab_section = symtab_section->link;
1073 s->symtab = symtab_section;
1075 /* private symbol table for dynamic symbols */
1076 s->dynsymtab_section = new_symtab(s, ".dynsymtab", SHT_SYMTAB, SHF_PRIVATE,
1077 ".dynstrtab",
1078 ".dynhashtab", SHF_PRIVATE);
1079 s->alacarte_link = 1;
1080 s->nocommon = 1;
1082 #ifdef CHAR_IS_UNSIGNED
1083 s->char_is_unsigned = 1;
1084 #endif
1085 /* enable this if you want symbols with leading underscore on windows: */
1086 #if defined(TCC_TARGET_PE) && 0
1087 s->leading_underscore = 1;
1088 #endif
1089 if (s->section_align == 0)
1090 s->section_align = ELF_PAGE_SIZE;
1091 #ifdef TCC_TARGET_I386
1092 s->seg_size = 32;
1093 #endif
1094 s->vio_module = NULL;
1095 return s;
1098 LIBTCCAPI void tcc_delete(TCCState *s1)
1100 int i;
1102 tcc_cleanup();
1104 /* free all sections */
1105 for(i = 1; i < s1->nb_sections; i++)
1106 free_section(s1->sections[i]);
1107 dynarray_reset(&s1->sections, &s1->nb_sections);
1109 for(i = 0; i < s1->nb_priv_sections; i++)
1110 free_section(s1->priv_sections[i]);
1111 dynarray_reset(&s1->priv_sections, &s1->nb_priv_sections);
1113 /* free any loaded DLLs */
1114 for ( i = 0; i < s1->nb_loaded_dlls; i++) {
1115 DLLReference *ref = s1->loaded_dlls[i];
1116 if ( ref->handle )
1117 dlclose(ref->handle);
1120 /* free loaded dlls array */
1121 dynarray_reset(&s1->loaded_dlls, &s1->nb_loaded_dlls);
1123 /* free library paths */
1124 dynarray_reset(&s1->library_paths, &s1->nb_library_paths);
1125 dynarray_reset(&s1->crt_paths, &s1->nb_crt_paths);
1127 /* free include paths */
1128 dynarray_reset(&s1->cached_includes, &s1->nb_cached_includes);
1129 dynarray_reset(&s1->include_paths, &s1->nb_include_paths);
1130 dynarray_reset(&s1->sysinclude_paths, &s1->nb_sysinclude_paths);
1132 dynarray_reset(&s1->target_deps, &s1->nb_target_deps);
1134 tcc_free(s1->tcc_lib_path);
1136 #ifdef HAVE_SELINUX
1137 munmap (s1->write_mem, s1->mem_size);
1138 munmap (s1->runtime_mem, s1->mem_size);
1139 #else
1140 tcc_free(s1->runtime_mem);
1141 #endif
1142 tcc_free(s1);
1145 LIBTCCAPI int tcc_add_include_path(TCCState *s, const char *pathname)
1147 tcc_split_path(s, (void ***)&s->include_paths, &s->nb_include_paths, pathname);
1148 return 0;
1151 LIBTCCAPI int tcc_add_sysinclude_path(TCCState *s, const char *pathname)
1153 tcc_split_path(s, (void ***)&s->sysinclude_paths, &s->nb_sysinclude_paths, pathname);
1154 return 0;
1157 ST_FUNC int tcc_add_file_internal(TCCState *s1, const char *filename, int flags)
1159 const char *ext;
1160 ElfW(Ehdr) ehdr;
1161 int ret=0, size;
1162 vio_fd fd;
1164 /* find source file type with extension */
1165 ext = tcc_fileextension(filename);
1166 if (ext[0])
1167 ext++;
1169 #ifdef CONFIG_TCC_ASM
1170 /* if .S file, define __ASSEMBLER__ like gcc does */
1171 if (!strcmp(ext, "S"))
1172 tcc_define_symbol(s1, "__ASSEMBLER__", NULL);
1173 #endif
1175 /* open the file */
1176 fd = tcc_open(s1, filename);
1177 if (fd.fd < 0) {
1178 if (flags & AFF_PRINT_ERROR)
1179 tcc_error_noabort("file '%s' not found", filename);
1180 return fd.fd;
1183 /* update target deps */
1184 dynarray_add((void ***)&s1->target_deps, &s1->nb_target_deps,
1185 tcc_strdup(filename));
1187 if (flags & AFF_PREPROCESS) {
1188 ret = tcc_preprocess(s1);
1189 goto the_end;
1192 if (!ext[0] || !PATHCMP(ext, "c")) {
1193 /* C file assumed */
1194 ret = tcc_compile(s1);
1195 goto the_end;
1198 #ifdef CONFIG_TCC_ASM
1199 if (!strcmp(ext, "S")) {
1200 /* preprocessed assembler */
1201 ret = tcc_assemble(s1, 1);
1202 goto the_end;
1205 if (!strcmp(ext, "s")) {
1206 /* non preprocessed assembler */
1207 ret = tcc_assemble(s1, 0);
1208 goto the_end;
1210 #endif
1212 fd = file->fd;
1213 /* assume executable format: auto guess file type */
1214 size = vio_read(fd, &ehdr, sizeof(ehdr));
1215 vio_lseek(fd, 0, SEEK_SET);
1216 if (size <= 0) {
1217 tcc_error_noabort("could not read header");
1218 goto the_end;
1221 if (size == sizeof(ehdr) &&
1222 ehdr.e_ident[0] == ELFMAG0 &&
1223 ehdr.e_ident[1] == ELFMAG1 &&
1224 ehdr.e_ident[2] == ELFMAG2 &&
1225 ehdr.e_ident[3] == ELFMAG3) {
1227 /* do not display line number if error */
1228 file->line_num = 0;
1229 if (ehdr.e_type == ET_REL) {
1230 ret = tcc_load_object_file(s1, fd, 0);
1231 goto the_end;
1234 #ifndef TCC_TARGET_PE
1235 if (ehdr.e_type == ET_DYN) {
1236 if (s1->output_type == TCC_OUTPUT_MEMORY) {
1237 void *h;
1238 h = dlopen(filename, RTLD_GLOBAL | RTLD_LAZY);
1239 if (h)
1240 ret = 0;
1241 } else {
1242 ret = tcc_load_dll(s1, fd, filename,
1243 (flags & AFF_REFERENCED_DLL) != 0);
1245 goto the_end;
1247 #endif
1248 tcc_error_noabort("unrecognized ELF file");
1249 goto the_end;
1252 if (memcmp((char *)&ehdr, ARMAG, 8) == 0) {
1253 file->line_num = 0; /* do not display line number if error */
1254 ret = tcc_load_archive(s1, fd);
1255 goto the_end;
1258 #ifdef TCC_TARGET_COFF
1259 if (*(uint16_t *)(&ehdr) == COFF_C67_MAGIC) {
1260 ret = tcc_load_coff(s1, fd);
1261 goto the_end;
1263 #endif
1265 #ifdef TCC_TARGET_PE
1266 ret = pe_load_file(s1, filename, fd);
1267 #else
1268 /* as GNU ld, consider it is an ld script if not recognized */
1269 ret = tcc_load_ldscript(s1);
1270 #endif
1271 if (ret < 0)
1272 tcc_error_noabort("unrecognized file type");
1274 the_end:
1275 tcc_close();
1276 return ret;
1279 LIBTCCAPI int tcc_add_file(TCCState *s, const char *filename)
1281 if (s->output_type == TCC_OUTPUT_PREPROCESS)
1282 return tcc_add_file_internal(s, filename, AFF_PRINT_ERROR | AFF_PREPROCESS);
1283 else
1284 return tcc_add_file_internal(s, filename, AFF_PRINT_ERROR);
1287 LIBTCCAPI int tcc_add_library_path(TCCState *s, const char *pathname)
1289 tcc_split_path(s, (void ***)&s->library_paths, &s->nb_library_paths, pathname);
1290 return 0;
1293 static int tcc_add_library_internal(TCCState *s, const char *fmt,
1294 const char *filename, int flags, char **paths, int nb_paths)
1296 char buf[1024];
1297 int i;
1299 for(i = 0; i < nb_paths; i++) {
1300 snprintf(buf, sizeof(buf), fmt, paths[i], filename);
1301 if (tcc_add_file_internal(s, buf, flags) == 0)
1302 return 0;
1304 return -1;
1307 #ifndef TCC_TARGET_PE
1308 /* find and load a dll. Return non zero if not found */
1309 /* XXX: add '-rpath' option support ? */
1310 ST_FUNC int tcc_add_dll(TCCState *s, const char *filename, int flags)
1312 return tcc_add_library_internal(s, "%s/%s", filename, flags,
1313 s->library_paths, s->nb_library_paths);
1315 #endif
1317 ST_FUNC int tcc_add_crt(TCCState *s, const char *filename)
1319 if (-1 == tcc_add_library_internal(s, "%s/%s",
1320 filename, 0, s->crt_paths, s->nb_crt_paths))
1321 tcc_error_noabort("file '%s' not found", filename);
1322 return 0;
1325 /* the library name is the same as the argument of the '-l' option */
1326 LIBTCCAPI int tcc_add_library(TCCState *s, const char *libraryname)
1328 #ifdef TCC_TARGET_PE
1329 const char *libs[] = { "%s/%s.def", "%s/lib%s.def", "%s/%s.dll", "%s/lib%s.dll", "%s/lib%s.a", NULL };
1330 const char **pp = s->static_link ? libs + 4 : libs;
1331 #else
1332 const char *libs[] = { "%s/lib%s.so", "%s/lib%s.a", NULL };
1333 const char **pp = s->static_link ? libs + 1 : libs;
1334 #endif
1335 while (*pp) {
1336 if (0 == tcc_add_library_internal(s, *pp,
1337 libraryname, 0, s->library_paths, s->nb_library_paths))
1338 return 0;
1339 ++pp;
1341 return -1;
1344 LIBTCCAPI int tcc_add_symbol(TCCState *s, const char *name, const void *val)
1346 #ifdef TCC_TARGET_PE
1347 pe_putimport(s, 0, name, val);
1348 #else
1349 add_elf_sym(symtab_section, (uplong)val, 0,
1350 ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE), 0,
1351 SHN_ABS, name);
1352 #endif
1353 return 0;
1356 LIBTCCAPI int tcc_set_output_type(TCCState *s, int output_type)
1358 s->output_type = output_type;
1360 if (!s->nostdinc) {
1361 /* default include paths */
1362 /* -isystem paths have already been handled */
1363 tcc_add_sysinclude_path(s, CONFIG_TCC_SYSINCLUDEPATHS);
1366 /* if bound checking, then add corresponding sections */
1367 #ifdef CONFIG_TCC_BCHECK
1368 if (s->do_bounds_check) {
1369 /* define symbol */
1370 tcc_define_symbol(s, "__BOUNDS_CHECKING_ON", NULL);
1371 /* create bounds sections */
1372 bounds_section = new_section(s, ".bounds",
1373 SHT_PROGBITS, SHF_ALLOC);
1374 lbounds_section = new_section(s, ".lbounds",
1375 SHT_PROGBITS, SHF_ALLOC);
1377 #endif
1379 if (s->char_is_unsigned) {
1380 tcc_define_symbol(s, "__CHAR_UNSIGNED__", NULL);
1383 /* add debug sections */
1384 if (s->do_debug) {
1385 /* stab symbols */
1386 stab_section = new_section(s, ".stab", SHT_PROGBITS, 0);
1387 stab_section->sh_entsize = sizeof(Stab_Sym);
1388 stabstr_section = new_section(s, ".stabstr", SHT_STRTAB, 0);
1389 put_elf_str(stabstr_section, "");
1390 stab_section->link = stabstr_section;
1391 /* put first entry */
1392 put_stabs("", 0, 0, 0, 0);
1395 #ifdef TCC_TARGET_PE
1396 tcc_add_library_path(s, CONFIG_TCC_LIBPATHS);
1397 # ifdef _WIN32
1398 tcc_add_systemdir(s);
1399 # endif
1400 #else
1401 /* add libc crt1/crti objects */
1402 if ((output_type == TCC_OUTPUT_EXE || output_type == TCC_OUTPUT_DLL) &&
1403 !s->nostdlib) {
1404 if (output_type != TCC_OUTPUT_DLL)
1405 tcc_add_crt(s, "crt1.o");
1406 tcc_add_crt(s, "crti.o");
1408 #endif
1409 return 0;
1412 #define WD_ALL 0x0001 /* warning is activated when using -Wall */
1413 #define FD_INVERT 0x0002 /* invert value before storing */
1415 typedef struct FlagDef {
1416 uint16_t offset;
1417 uint16_t flags;
1418 const char *name;
1419 } FlagDef;
1421 static const FlagDef warning_defs[] = {
1422 { offsetof(TCCState, warn_unsupported), 0, "unsupported" },
1423 { offsetof(TCCState, warn_write_strings), 0, "write-strings" },
1424 { offsetof(TCCState, warn_error), 0, "error" },
1425 { offsetof(TCCState, warn_implicit_function_declaration), WD_ALL,
1426 "implicit-function-declaration" },
1429 ST_FUNC int set_flag(TCCState *s, const FlagDef *flags, int nb_flags,
1430 const char *name, int value)
1432 int i;
1433 const FlagDef *p;
1434 const char *r;
1436 r = name;
1437 if (r[0] == 'n' && r[1] == 'o' && r[2] == '-') {
1438 r += 3;
1439 value = !value;
1441 for(i = 0, p = flags; i < nb_flags; i++, p++) {
1442 if (!strcmp(r, p->name))
1443 goto found;
1445 return -1;
1446 found:
1447 if (p->flags & FD_INVERT)
1448 value = !value;
1449 *(int *)((uint8_t *)s + p->offset) = value;
1450 return 0;
1453 /* enable debug */
1454 LIBTCCAPI void tcc_enable_debug(TCCState *s)
1456 s->do_debug = 1;
1459 /* set/reset a warning */
1460 LIBTCCAPI int tcc_set_warning(TCCState *s, const char *warning_name, int value)
1462 int i;
1463 const FlagDef *p;
1465 if (!strcmp(warning_name, "all")) {
1466 for(i = 0, p = warning_defs; i < countof(warning_defs); i++, p++) {
1467 if (p->flags & WD_ALL)
1468 *(int *)((uint8_t *)s + p->offset) = 1;
1470 return 0;
1471 } else {
1472 return set_flag(s, warning_defs, countof(warning_defs),
1473 warning_name, value);
1477 static const FlagDef flag_defs[] = {
1478 { offsetof(TCCState, char_is_unsigned), 0, "unsigned-char" },
1479 { offsetof(TCCState, char_is_unsigned), FD_INVERT, "signed-char" },
1480 { offsetof(TCCState, nocommon), FD_INVERT, "common" },
1481 { offsetof(TCCState, leading_underscore), 0, "leading-underscore" },
1484 /* set/reset a flag */
1485 PUB_FUNC int tcc_set_flag(TCCState *s, const char *flag_name, int value)
1487 return set_flag(s, flag_defs, countof(flag_defs),
1488 flag_name, value);
1492 static int strstart(const char *str, const char *val, char **ptr)
1494 const char *p, *q;
1495 p = str;
1496 q = val;
1497 while (*q != '\0') {
1498 if (*p != *q)
1499 return 0;
1500 p++;
1501 q++;
1503 if (ptr)
1504 *ptr = (char *) p;
1505 return 1;
1509 /* Like strstart, but automatically takes into account that ld options can
1511 * - start with double or single dash (e.g. '--soname' or '-soname')
1512 * - arguments can be given as separate or after '=' (e.g. '-Wl,-soname,x.so'
1513 * or '-Wl,-soname=x.so')
1515 * you provide `val` always in 'option[=]' form (no leading -)
1517 static int link_option(const char *str, const char *val, char **ptr)
1519 const char *p, *q;
1521 /* there should be 1 or 2 dashes */
1522 if (*str++ != '-')
1523 return 0;
1524 if (*str == '-')
1525 str++;
1527 /* then str & val should match (potentialy up to '=') */
1528 p = str;
1529 q = val;
1531 while (*q != '\0' && *q != '=') {
1532 if (*p != *q)
1533 return 0;
1534 p++;
1535 q++;
1538 /* '=' near eos means ',' or '=' is ok */
1539 if (*q == '=') {
1540 if (*p != ',' && *p != '=')
1541 return 0;
1542 p++;
1543 q++;
1546 if (ptr)
1547 *ptr = (char *) p;
1548 return 1;
1552 /* set linker options */
1553 PUB_FUNC const char * tcc_set_linker(TCCState *s, char *option, int multi)
1555 char *p = option;
1556 char *end;
1558 while (option && *option) {
1559 end = NULL;
1560 if (link_option(option, "Bsymbolic", &p)) {
1561 s->symbolic = TRUE;
1562 } else if (link_option(option, "nostdlib", &p)) {
1563 s->nostdlib = TRUE;
1564 } else if (link_option(option, "fini=", &p)) {
1565 s->fini_symbol = p;
1566 if (s->warn_unsupported)
1567 tcc_warning("ignoring -fini %s", p);
1568 } else if (link_option(option, "image-base=", &p)) {
1569 s->text_addr = strtoull(p, &end, 16);
1570 s->has_text_addr = 1;
1571 } else if (link_option(option, "init=", &p)) {
1572 s->init_symbol = p;
1573 if (s->warn_unsupported)
1574 tcc_warning("ignoring -init %s", p);
1575 } else if (link_option(option, "oformat=", &p)) {
1576 #if defined(TCC_TARGET_PE)
1577 if (strstart(p, "pe-", NULL)) {
1578 #else
1579 #if defined(TCC_TARGET_X86_64)
1580 if (strstart(p, "elf64-", NULL)) {
1581 #else
1582 if (strstart(p, "elf32-", NULL)) {
1583 #endif
1584 #endif
1585 s->output_format = TCC_OUTPUT_FORMAT_ELF;
1586 } else if (!strcmp(p, "binary")) {
1587 s->output_format = TCC_OUTPUT_FORMAT_BINARY;
1588 } else
1589 #ifdef TCC_TARGET_COFF
1590 if (!strcmp(p, "coff")) {
1591 s->output_format = TCC_OUTPUT_FORMAT_COFF;
1592 } else
1593 #endif
1595 return p;
1598 } else if (link_option(option, "rpath=", &p)) {
1599 s->rpath = p;
1600 } else if (link_option(option, "section-alignment=", &p)) {
1601 s->section_align = strtoul(p, &end, 16);
1602 } else if (link_option(option, "soname=", &p)) {
1603 s->soname = p;
1604 multi = 0;
1605 #ifdef TCC_TARGET_PE
1606 } else if (link_option(option, "file-alignment=", &p)) {
1607 s->pe_file_align = strtoul(p, &end, 16);
1608 } else if (link_option(option, "stack=", &p)) {
1609 s->pe_stack_size = strtoul(p, &end, 10);
1610 } else if (link_option(option, "subsystem=", &p)) {
1611 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
1612 if (!strcmp(p, "native")) {
1613 s->pe_subsystem = 1;
1614 } else if (!strcmp(p, "console")) {
1615 s->pe_subsystem = 3;
1616 } else if (!strcmp(p, "gui")) {
1617 s->pe_subsystem = 2;
1618 } else if (!strcmp(p, "posix")) {
1619 s->pe_subsystem = 7;
1620 } else if (!strcmp(p, "efiapp")) {
1621 s->pe_subsystem = 10;
1622 } else if (!strcmp(p, "efiboot")) {
1623 s->pe_subsystem = 11;
1624 } else if (!strcmp(p, "efiruntime")) {
1625 s->pe_subsystem = 12;
1626 } else if (!strcmp(p, "efirom")) {
1627 s->pe_subsystem = 13;
1628 #elif defined(TCC_TARGET_ARM)
1629 if (!strcmp(p, "wince")) {
1630 s->pe_subsystem = 9;
1631 #endif
1632 } else {
1633 return p;
1635 #endif
1637 } else if (link_option(option, "Ttext=", &p)) {
1638 s->text_addr = strtoull(p, &end, 16);
1639 s->has_text_addr = 1;
1640 } else {
1641 char *comma_ptr = strchr(option, ',');
1642 if (comma_ptr)
1643 *comma_ptr = '\0';
1644 return option;
1647 if (multi) {
1648 option = NULL;
1649 p = strchr( (end) ? end : p, ',');
1650 if (p) {
1651 *p = 0; /* terminate last option */
1652 option = ++p;
1654 } else
1655 option = NULL;
1657 return NULL;
1660 PUB_FUNC void tcc_print_stats(TCCState *s, int64_t total_time)
1662 double tt;
1663 tt = (double)total_time / 1000000.0;
1664 if (tt < 0.001)
1665 tt = 0.001;
1666 if (total_bytes < 1)
1667 total_bytes = 1;
1668 printf("%d idents, %d lines, %d bytes, %0.3f s, %d lines/s, %0.1f MB/s\n",
1669 tok_ident - TOK_IDENT, total_lines, total_bytes,
1670 tt, (int)(total_lines / tt),
1671 total_bytes / tt / 1000000.0);
1674 /* set CONFIG_TCCDIR at runtime */
1675 LIBTCCAPI void tcc_set_lib_path(TCCState *s, const char *path)
1677 tcc_free(s->tcc_lib_path);
1678 s->tcc_lib_path = tcc_strdup(path);
1681 PUB_FUNC char *tcc_default_target(TCCState *s, const char *default_file)
1683 char buf[1024];
1684 char *ext;
1685 const char *name = "a";
1687 if (default_file && strcmp(default_file, "-"))
1688 name = tcc_basename(default_file);
1689 pstrcpy(buf, sizeof(buf), name);
1690 ext = tcc_fileextension(buf);
1691 #ifdef TCC_TARGET_PE
1692 if (s->output_type == TCC_OUTPUT_DLL)
1693 strcpy(ext, ".dll");
1694 else
1695 if (s->output_type == TCC_OUTPUT_EXE)
1696 strcpy(ext, ".exe");
1697 else
1698 #endif
1699 if (( (s->output_type == TCC_OUTPUT_OBJ && !s->reloc_output) ||
1700 (s->output_type == TCC_OUTPUT_PREPROCESS) )
1701 && *ext)
1702 strcpy(ext, ".o");
1703 else
1704 pstrcpy(buf, sizeof(buf), "a.out");
1706 return tcc_strdup(buf);
1710 PUB_FUNC void tcc_gen_makedeps(TCCState *s, const char *target, const char *filename)
1712 FILE *depout;
1713 char buf[1024], *ext;
1714 int i;
1716 if (!filename) {
1717 /* compute filename automatically
1718 * dir/file.o -> dir/file.d */
1719 pstrcpy(buf, sizeof(buf), target);
1720 ext = tcc_fileextension(buf);
1721 pstrcpy(ext, sizeof(buf) - (ext-buf), ".d");
1722 filename = buf;
1725 if (s->verbose)
1726 printf("<- %s\n", filename);
1728 /* XXX return err codes instead of error() ? */
1729 depout = fopen(filename, "w");
1730 if (!depout)
1731 tcc_error("could not open '%s'", filename);
1733 fprintf(depout, "%s : \\\n", target);
1734 for (i=0; i<s->nb_target_deps; ++i)
1735 fprintf(depout, " %s \\\n", s->target_deps[i]);
1736 fprintf(depout, "\n");
1737 fclose(depout);