win64: add tiny unwind data for setjmp/longjmp
[tinycc/kirr.git] / libtcc.c
blob9be8c1c6c6be2414191d72a41ef61fce6ff7b573
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 #ifdef LIBTCC_AS_DLL
115 BOOL WINAPI DllMain (HANDLE hDll, DWORD dwReason, LPVOID lpReserved)
117 if (DLL_PROCESS_ATTACH == dwReason)
118 tcc_module = hDll;
119 return TRUE;
121 #endif
122 #endif
124 /********************************************************/
125 /* copy a string and truncate it. */
126 PUB_FUNC char *pstrcpy(char *buf, int buf_size, const char *s)
128 char *q, *q_end;
129 int c;
131 if (buf_size > 0) {
132 q = buf;
133 q_end = buf + buf_size - 1;
134 while (q < q_end) {
135 c = *s++;
136 if (c == '\0')
137 break;
138 *q++ = c;
140 *q = '\0';
142 return buf;
145 /* strcat and truncate. */
146 PUB_FUNC char *pstrcat(char *buf, int buf_size, const char *s)
148 int len;
149 len = strlen(buf);
150 if (len < buf_size)
151 pstrcpy(buf + len, buf_size - len, s);
152 return buf;
155 /* extract the basename of a file */
156 PUB_FUNC char *tcc_basename(const char *name)
158 char *p = strchr(name, 0);
159 while (p > name && !IS_PATHSEP(p[-1]))
160 --p;
161 return p;
164 PUB_FUNC char *tcc_fileextension (const char *name)
166 char *b = tcc_basename(name);
167 char *e = strrchr(b, '.');
168 return e ? e : strchr(b, 0);
171 /********************************************************/
172 /* memory management */
174 #undef free
175 #undef malloc
176 #undef realloc
178 #ifdef MEM_DEBUG
179 int mem_cur_size;
180 int mem_max_size;
181 unsigned malloc_usable_size(void*);
182 #endif
184 PUB_FUNC void tcc_free(void *ptr)
186 #ifdef MEM_DEBUG
187 mem_cur_size -= malloc_usable_size(ptr);
188 #endif
189 free(ptr);
192 PUB_FUNC void *tcc_malloc(unsigned long size)
194 void *ptr;
195 ptr = malloc(size);
196 if (!ptr && size)
197 error("memory full");
198 #ifdef MEM_DEBUG
199 mem_cur_size += malloc_usable_size(ptr);
200 if (mem_cur_size > mem_max_size)
201 mem_max_size = mem_cur_size;
202 #endif
203 return ptr;
206 PUB_FUNC void *tcc_mallocz(unsigned long size)
208 void *ptr;
209 ptr = tcc_malloc(size);
210 memset(ptr, 0, size);
211 return ptr;
214 PUB_FUNC void *tcc_realloc(void *ptr, unsigned long size)
216 void *ptr1;
217 #ifdef MEM_DEBUG
218 mem_cur_size -= malloc_usable_size(ptr);
219 #endif
220 ptr1 = realloc(ptr, size);
221 #ifdef MEM_DEBUG
222 /* NOTE: count not correct if alloc error, but not critical */
223 mem_cur_size += malloc_usable_size(ptr1);
224 if (mem_cur_size > mem_max_size)
225 mem_max_size = mem_cur_size;
226 #endif
227 return ptr1;
230 PUB_FUNC char *tcc_strdup(const char *str)
232 char *ptr;
233 ptr = tcc_malloc(strlen(str) + 1);
234 strcpy(ptr, str);
235 return ptr;
238 PUB_FUNC void tcc_memstats(void)
240 #ifdef MEM_DEBUG
241 printf("memory in use: %d\n", mem_cur_size);
242 #endif
245 #define free(p) use_tcc_free(p)
246 #define malloc(s) use_tcc_malloc(s)
247 #define realloc(p, s) use_tcc_realloc(p, s)
249 /********************************************************/
250 /* dynarrays */
252 PUB_FUNC void dynarray_add(void ***ptab, int *nb_ptr, void *data)
254 int nb, nb_alloc;
255 void **pp;
257 nb = *nb_ptr;
258 pp = *ptab;
259 /* every power of two we double array size */
260 if ((nb & (nb - 1)) == 0) {
261 if (!nb)
262 nb_alloc = 1;
263 else
264 nb_alloc = nb * 2;
265 pp = tcc_realloc(pp, nb_alloc * sizeof(void *));
266 if (!pp)
267 error("memory full");
268 *ptab = pp;
270 pp[nb++] = data;
271 *nb_ptr = nb;
274 PUB_FUNC void dynarray_reset(void *pp, int *n)
276 void **p;
277 for (p = *(void***)pp; *n; ++p, --*n)
278 if (*p)
279 tcc_free(*p);
280 tcc_free(*(void**)pp);
281 *(void**)pp = NULL;
284 /* we use our own 'finite' function to avoid potential problems with
285 non standard math libs */
286 /* XXX: endianness dependent */
287 ST_FUNC int ieee_finite(double d)
289 int *p = (int *)&d;
290 return ((unsigned)((p[1] | 0x800fffff) + 1)) >> 31;
293 /********************************************************/
295 ST_FUNC Section *new_section(TCCState *s1, const char *name, int sh_type, int sh_flags)
297 Section *sec;
299 sec = tcc_mallocz(sizeof(Section) + strlen(name));
300 strcpy(sec->name, name);
301 sec->sh_type = sh_type;
302 sec->sh_flags = sh_flags;
303 switch(sh_type) {
304 case SHT_HASH:
305 case SHT_REL:
306 case SHT_RELA:
307 case SHT_DYNSYM:
308 case SHT_SYMTAB:
309 case SHT_DYNAMIC:
310 sec->sh_addralign = 4;
311 break;
312 case SHT_STRTAB:
313 sec->sh_addralign = 1;
314 break;
315 default:
316 sec->sh_addralign = 32; /* default conservative alignment */
317 break;
320 if (sh_flags & SHF_PRIVATE) {
321 dynarray_add((void ***)&s1->priv_sections, &s1->nb_priv_sections, sec);
322 } else {
323 sec->sh_num = s1->nb_sections;
324 dynarray_add((void ***)&s1->sections, &s1->nb_sections, sec);
327 return sec;
330 static void free_section(Section *s)
332 tcc_free(s->data);
335 /* realloc section and set its content to zero */
336 ST_FUNC void section_realloc(Section *sec, unsigned long new_size)
338 unsigned long size;
339 unsigned char *data;
341 size = sec->data_allocated;
342 if (size == 0)
343 size = 1;
344 while (size < new_size)
345 size = size * 2;
346 data = tcc_realloc(sec->data, size);
347 if (!data)
348 error("memory full");
349 memset(data + sec->data_allocated, 0, size - sec->data_allocated);
350 sec->data = data;
351 sec->data_allocated = size;
354 /* reserve at least 'size' bytes in section 'sec' from
355 sec->data_offset. */
356 ST_FUNC void *section_ptr_add(Section *sec, unsigned long size)
358 unsigned long offset, offset1;
360 offset = sec->data_offset;
361 offset1 = offset + size;
362 if (offset1 > sec->data_allocated)
363 section_realloc(sec, offset1);
364 sec->data_offset = offset1;
365 return sec->data + offset;
368 /* return a reference to a section, and create it if it does not
369 exists */
370 ST_FUNC Section *find_section(TCCState *s1, const char *name)
372 Section *sec;
373 int i;
374 for(i = 1; i < s1->nb_sections; i++) {
375 sec = s1->sections[i];
376 if (!strcmp(name, sec->name))
377 return sec;
379 /* sections are created as PROGBITS */
380 return new_section(s1, name, SHT_PROGBITS, SHF_ALLOC);
383 /* update sym->c so that it points to an external symbol in section
384 'section' with value 'value' */
385 ST_FUNC void put_extern_sym2(Sym *sym, Section *section,
386 unsigned long value, unsigned long size,
387 int can_add_underscore)
389 int sym_type, sym_bind, sh_num, info, other, attr;
390 ElfW(Sym) *esym;
391 const char *name;
392 char buf1[256];
394 if (section == NULL)
395 sh_num = SHN_UNDEF;
396 else if (section == SECTION_ABS)
397 sh_num = SHN_ABS;
398 else
399 sh_num = section->sh_num;
401 other = attr = 0;
403 if ((sym->type.t & VT_BTYPE) == VT_FUNC) {
404 sym_type = STT_FUNC;
405 #ifdef TCC_TARGET_PE
406 if (sym->type.ref)
407 attr = sym->type.ref->r;
408 if (FUNC_EXPORT(attr))
409 other |= 1;
410 if (FUNC_CALL(attr) == FUNC_STDCALL)
411 other |= 2;
412 #endif
413 } else if ((sym->type.t & VT_BTYPE) == VT_VOID) {
414 sym_type = STT_NOTYPE;
415 } else {
416 sym_type = STT_OBJECT;
417 #ifdef TCC_TARGET_PE
418 if (sym->type.t & VT_EXPORT)
419 other |= 1;
420 #endif
423 if (sym->type.t & VT_STATIC)
424 sym_bind = STB_LOCAL;
425 else
426 sym_bind = STB_GLOBAL;
428 if (!sym->c) {
429 name = get_tok_str(sym->v, NULL);
430 #ifdef CONFIG_TCC_BCHECK
431 if (tcc_state->do_bounds_check) {
432 char buf[32];
434 /* XXX: avoid doing that for statics ? */
435 /* if bound checking is activated, we change some function
436 names by adding the "__bound" prefix */
437 switch(sym->v) {
438 #ifdef TCC_TARGET_PE
439 /* XXX: we rely only on malloc hooks */
440 case TOK_malloc:
441 case TOK_free:
442 case TOK_realloc:
443 case TOK_memalign:
444 case TOK_calloc:
445 #endif
446 case TOK_memcpy:
447 case TOK_memmove:
448 case TOK_memset:
449 case TOK_strlen:
450 case TOK_strcpy:
451 case TOK_alloca:
452 strcpy(buf, "__bound_");
453 strcat(buf, name);
454 name = buf;
455 break;
458 #endif
460 #ifdef TCC_TARGET_PE
461 if ((other & 2) && can_add_underscore) {
462 sprintf(buf1, "_%s@%d", name, FUNC_ARGS(attr));
463 name = buf1;
464 } else
465 #endif
466 if (tcc_state->leading_underscore && can_add_underscore) {
467 buf1[0] = '_';
468 pstrcpy(buf1 + 1, sizeof(buf1) - 1, name);
469 name = buf1;
471 info = ELFW(ST_INFO)(sym_bind, sym_type);
472 sym->c = add_elf_sym(symtab_section, value, size, info, other, sh_num, name);
473 } else {
474 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
475 esym->st_value = value;
476 esym->st_size = size;
477 esym->st_shndx = sh_num;
478 esym->st_other |= other;
482 ST_FUNC void put_extern_sym(Sym *sym, Section *section,
483 unsigned long value, unsigned long size)
485 put_extern_sym2(sym, section, value, size, 1);
488 /* add a new relocation entry to symbol 'sym' in section 's' */
489 ST_FUNC void greloc(Section *s, Sym *sym, unsigned long offset, int type)
491 int c = 0;
492 if (sym) {
493 if (0 == sym->c)
494 put_extern_sym(sym, NULL, 0, 0);
495 c = sym->c;
497 /* now we can add ELF relocation info */
498 put_elf_reloc(symtab_section, s, offset, type, c);
501 /********************************************************/
503 static void strcat_vprintf(char *buf, int buf_size, const char *fmt, va_list ap)
505 int len;
506 len = strlen(buf);
507 vsnprintf(buf + len, buf_size - len, fmt, ap);
510 static void strcat_printf(char *buf, int buf_size, const char *fmt, ...)
512 va_list ap;
513 va_start(ap, fmt);
514 strcat_vprintf(buf, buf_size, fmt, ap);
515 va_end(ap);
518 static void error1(TCCState *s1, int is_warning, const char *fmt, va_list ap)
520 char buf[2048];
521 BufferedFile **f;
523 buf[0] = '\0';
524 if (file) {
525 for(f = s1->include_stack; f < s1->include_stack_ptr; f++)
526 strcat_printf(buf, sizeof(buf), "In file included from %s:%d:\n",
527 (*f)->filename, (*f)->line_num);
528 if (file->line_num > 0) {
529 strcat_printf(buf, sizeof(buf),
530 "%s:%d: ", file->filename, file->line_num);
531 } else {
532 strcat_printf(buf, sizeof(buf),
533 "%s: ", file->filename);
535 } else {
536 strcat_printf(buf, sizeof(buf),
537 "tcc: ");
539 if (is_warning)
540 strcat_printf(buf, sizeof(buf), "warning: ");
541 else
542 strcat_printf(buf, sizeof(buf), "error: ");
543 strcat_vprintf(buf, sizeof(buf), fmt, ap);
545 if (!s1->error_func) {
546 /* default case: stderr */
547 fprintf(stderr, "%s\n", buf);
548 } else {
549 s1->error_func(s1->error_opaque, buf);
551 if (!is_warning || s1->warn_error)
552 s1->nb_errors++;
555 LIBTCCAPI void tcc_set_error_func(TCCState *s, void *error_opaque,
556 void (*error_func)(void *opaque, const char *msg))
558 s->error_opaque = error_opaque;
559 s->error_func = error_func;
562 /* error without aborting current compilation */
563 PUB_FUNC void error_noabort(const char *fmt, ...)
565 TCCState *s1 = tcc_state;
566 va_list ap;
568 va_start(ap, fmt);
569 error1(s1, 0, fmt, ap);
570 va_end(ap);
573 PUB_FUNC void error(const char *fmt, ...)
575 TCCState *s1 = tcc_state;
576 va_list ap;
578 va_start(ap, fmt);
579 error1(s1, 0, fmt, ap);
580 va_end(ap);
581 /* better than nothing: in some cases, we accept to handle errors */
582 if (s1->error_set_jmp_enabled) {
583 longjmp(s1->error_jmp_buf, 1);
584 } else {
585 /* XXX: eliminate this someday */
586 exit(1);
590 PUB_FUNC void expect(const char *msg)
592 error("%s expected", msg);
595 PUB_FUNC void warning(const char *fmt, ...)
597 TCCState *s1 = tcc_state;
598 va_list ap;
600 if (s1->warn_none)
601 return;
603 va_start(ap, fmt);
604 error1(s1, 1, fmt, ap);
605 va_end(ap);
608 /********************************************************/
609 /* I/O layer */
611 ST_FUNC BufferedFile *tcc_open(TCCState *s1, const char *filename)
613 int fd;
614 BufferedFile *bf;
616 if (strcmp(filename, "-") == 0)
617 fd = 0, filename = "stdin";
618 else
619 fd = open(filename, O_RDONLY | O_BINARY);
620 if ((s1->verbose == 2 && fd >= 0) || s1->verbose == 3)
621 printf("%s %*s%s\n", fd < 0 ? "nf":"->",
622 (int)(s1->include_stack_ptr - s1->include_stack), "", filename);
623 if (fd < 0)
624 return NULL;
625 bf = tcc_malloc(sizeof(BufferedFile));
626 bf->fd = fd;
627 bf->buf_ptr = bf->buffer;
628 bf->buf_end = bf->buffer;
629 bf->buffer[0] = CH_EOB; /* put eob symbol */
630 pstrcpy(bf->filename, sizeof(bf->filename), filename);
631 #ifdef _WIN32
632 normalize_slashes(bf->filename);
633 #endif
634 bf->line_num = 1;
635 bf->ifndef_macro = 0;
636 bf->ifdef_stack_ptr = s1->ifdef_stack_ptr;
637 // printf("opening '%s'\n", filename);
638 return bf;
641 ST_FUNC void tcc_close(BufferedFile *bf)
643 total_lines += bf->line_num;
644 close(bf->fd);
645 tcc_free(bf);
648 /* compile the C file opened in 'file'. Return non zero if errors. */
649 static int tcc_compile(TCCState *s1)
651 Sym *define_start;
652 char buf[512];
653 volatile int section_sym;
655 #ifdef INC_DEBUG
656 printf("%s: **** new file\n", file->filename);
657 #endif
658 preprocess_init(s1);
660 cur_text_section = NULL;
661 funcname = "";
662 anon_sym = SYM_FIRST_ANOM;
664 /* file info: full path + filename */
665 section_sym = 0; /* avoid warning */
666 if (s1->do_debug) {
667 section_sym = put_elf_sym(symtab_section, 0, 0,
668 ELFW(ST_INFO)(STB_LOCAL, STT_SECTION), 0,
669 text_section->sh_num, NULL);
670 getcwd(buf, sizeof(buf));
671 #ifdef _WIN32
672 normalize_slashes(buf);
673 #endif
674 pstrcat(buf, sizeof(buf), "/");
675 put_stabs_r(buf, N_SO, 0, 0,
676 text_section->data_offset, text_section, section_sym);
677 put_stabs_r(file->filename, N_SO, 0, 0,
678 text_section->data_offset, text_section, section_sym);
680 /* an elf symbol of type STT_FILE must be put so that STB_LOCAL
681 symbols can be safely used */
682 put_elf_sym(symtab_section, 0, 0,
683 ELFW(ST_INFO)(STB_LOCAL, STT_FILE), 0,
684 SHN_ABS, file->filename);
686 /* define some often used types */
687 int_type.t = VT_INT;
689 char_pointer_type.t = VT_BYTE;
690 mk_pointer(&char_pointer_type);
692 func_old_type.t = VT_FUNC;
693 func_old_type.ref = sym_push(SYM_FIELD, &int_type, FUNC_CDECL, FUNC_OLD);
695 #if defined(TCC_ARM_EABI) && defined(TCC_ARM_VFP)
696 float_type.t = VT_FLOAT;
697 double_type.t = VT_DOUBLE;
699 func_float_type.t = VT_FUNC;
700 func_float_type.ref = sym_push(SYM_FIELD, &float_type, FUNC_CDECL, FUNC_OLD);
701 func_double_type.t = VT_FUNC;
702 func_double_type.ref = sym_push(SYM_FIELD, &double_type, FUNC_CDECL, FUNC_OLD);
703 #endif
705 #if 0
706 /* define 'void *alloca(unsigned int)' builtin function */
708 Sym *s1;
710 p = anon_sym++;
711 sym = sym_push(p, mk_pointer(VT_VOID), FUNC_CDECL, FUNC_NEW);
712 s1 = sym_push(SYM_FIELD, VT_UNSIGNED | VT_INT, 0, 0);
713 s1->next = NULL;
714 sym->next = s1;
715 sym_push(TOK_alloca, VT_FUNC | (p << VT_STRUCT_SHIFT), VT_CONST, 0);
717 #endif
719 define_start = define_stack;
720 nocode_wanted = 1;
722 if (setjmp(s1->error_jmp_buf) == 0) {
723 s1->nb_errors = 0;
724 s1->error_set_jmp_enabled = 1;
726 ch = file->buf_ptr[0];
727 tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
728 parse_flags = PARSE_FLAG_PREPROCESS | PARSE_FLAG_TOK_NUM;
729 next();
730 decl(VT_CONST);
731 if (tok != TOK_EOF)
732 expect("declaration");
734 /* end of translation unit info */
735 if (s1->do_debug) {
736 put_stabs_r(NULL, N_SO, 0, 0,
737 text_section->data_offset, text_section, section_sym);
740 s1->error_set_jmp_enabled = 0;
742 /* reset define stack, but leave -Dsymbols (may be incorrect if
743 they are undefined) */
744 free_defines(define_start);
746 gen_inline_functions();
748 sym_pop(&global_stack, NULL);
749 sym_pop(&local_stack, NULL);
751 return s1->nb_errors != 0 ? -1 : 0;
754 LIBTCCAPI int tcc_compile_string(TCCState *s, const char *str)
756 BufferedFile bf1, *bf = &bf1;
757 int ret, len;
758 char *buf;
760 /* init file structure */
761 bf->fd = -1;
762 /* XXX: avoid copying */
763 len = strlen(str);
764 buf = tcc_malloc(len + 1);
765 if (!buf)
766 return -1;
767 memcpy(buf, str, len);
768 buf[len] = CH_EOB;
769 bf->buf_ptr = buf;
770 bf->buf_end = buf + len;
771 pstrcpy(bf->filename, sizeof(bf->filename), "<string>");
772 bf->line_num = 1;
773 file = bf;
774 ret = tcc_compile(s);
775 file = NULL;
776 tcc_free(buf);
778 /* currently, no need to close */
779 return ret;
782 /* define a preprocessor symbol. A value can also be provided with the '=' operator */
783 LIBTCCAPI void tcc_define_symbol(TCCState *s1, const char *sym, const char *value)
785 BufferedFile bf1, *bf = &bf1;
787 pstrcpy(bf->buffer, IO_BUF_SIZE, sym);
788 pstrcat(bf->buffer, IO_BUF_SIZE, " ");
789 /* default value */
790 if (!value)
791 value = "1";
792 pstrcat(bf->buffer, IO_BUF_SIZE, value);
794 /* init file structure */
795 bf->fd = -1;
796 bf->buf_ptr = bf->buffer;
797 bf->buf_end = bf->buffer + strlen(bf->buffer);
798 *bf->buf_end = CH_EOB;
799 bf->filename[0] = '\0';
800 bf->line_num = 1;
801 file = bf;
803 s1->include_stack_ptr = s1->include_stack;
805 /* parse with define parser */
806 ch = file->buf_ptr[0];
807 next_nomacro();
808 parse_define();
809 file = NULL;
812 /* undefine a preprocessor symbol */
813 LIBTCCAPI void tcc_undefine_symbol(TCCState *s1, const char *sym)
815 TokenSym *ts;
816 Sym *s;
817 ts = tok_alloc(sym, strlen(sym));
818 s = define_find(ts->tok);
819 /* undefine symbol by putting an invalid name */
820 if (s)
821 define_undef(s);
824 static void tcc_cleanup(void)
826 int i, n;
828 if (NULL == tcc_state)
829 return;
830 tcc_state = NULL;
832 /* free -D defines */
833 free_defines(NULL);
835 /* free tokens */
836 n = tok_ident - TOK_IDENT;
837 for(i = 0; i < n; i++)
838 tcc_free(table_ident[i]);
839 tcc_free(table_ident);
841 /* free sym_pools */
842 dynarray_reset(&sym_pools, &nb_sym_pools);
843 /* string buffer */
844 cstr_free(&tokcstr);
845 /* reset symbol stack */
846 sym_free_first = NULL;
847 /* cleanup from error/setjmp */
848 macro_ptr = NULL;
851 LIBTCCAPI TCCState *tcc_new(void)
853 TCCState *s;
854 char buffer[100];
855 int a,b,c;
857 tcc_cleanup();
859 s = tcc_mallocz(sizeof(TCCState));
860 if (!s)
861 return NULL;
862 tcc_state = s;
863 #ifdef _WIN32
864 tcc_set_lib_path_w32(s);
865 #else
866 tcc_set_lib_path(s, CONFIG_TCCDIR);
867 #endif
868 s->output_type = TCC_OUTPUT_MEMORY;
869 preprocess_new();
871 /* we add dummy defines for some special macros to speed up tests
872 and to have working defined() */
873 define_push(TOK___LINE__, MACRO_OBJ, NULL, NULL);
874 define_push(TOK___FILE__, MACRO_OBJ, NULL, NULL);
875 define_push(TOK___DATE__, MACRO_OBJ, NULL, NULL);
876 define_push(TOK___TIME__, MACRO_OBJ, NULL, NULL);
878 /* standard defines */
879 tcc_define_symbol(s, "__STDC__", NULL);
880 tcc_define_symbol(s, "__STDC_VERSION__", "199901L");
881 #if defined(TCC_TARGET_I386)
882 tcc_define_symbol(s, "__i386__", "1");
883 tcc_define_symbol(s, "__i386", "1");
884 tcc_define_symbol(s, "i386", "1");
885 #endif
886 #if defined(TCC_TARGET_X86_64)
887 tcc_define_symbol(s, "__x86_64__", NULL);
888 #endif
889 #if defined(TCC_TARGET_ARM)
890 tcc_define_symbol(s, "__ARM_ARCH_4__", NULL);
891 tcc_define_symbol(s, "__arm_elf__", NULL);
892 tcc_define_symbol(s, "__arm_elf", NULL);
893 tcc_define_symbol(s, "arm_elf", NULL);
894 tcc_define_symbol(s, "__arm__", NULL);
895 tcc_define_symbol(s, "__arm", NULL);
896 tcc_define_symbol(s, "arm", NULL);
897 tcc_define_symbol(s, "__APCS_32__", NULL);
898 #endif
899 #ifdef TCC_TARGET_PE
900 tcc_define_symbol(s, "_WIN32", NULL);
901 #ifdef TCC_TARGET_X86_64
902 tcc_define_symbol(s, "_WIN64", NULL);
903 #endif
904 #else
905 tcc_define_symbol(s, "__unix__", "1");
906 tcc_define_symbol(s, "__unix", "1");
907 tcc_define_symbol(s, "unix", "1");
908 #if defined(__FreeBSD__)
909 #define str(s) #s
910 tcc_define_symbol(s, "__FreeBSD__", str( __FreeBSD__));
911 tcc_define_symbol(s, "__INTEL_COMPILER", "1");
912 #undef str
913 #endif
914 #if defined(__linux)
915 tcc_define_symbol(s, "__linux__", NULL);
916 tcc_define_symbol(s, "__linux", NULL);
917 #endif
918 #endif
919 /* tiny C specific defines */
920 sscanf(TCC_VERSION, "%d.%d.%d", &a, &b, &c);
921 sprintf(buffer, "%d", a*10000 + b*100 + c);
922 tcc_define_symbol(s, "__TINYC__", buffer);
924 /* tiny C & gcc defines */
925 tcc_define_symbol(s, "__SIZE_TYPE__", "unsigned long");
926 tcc_define_symbol(s, "__PTRDIFF_TYPE__", "long");
927 #ifdef TCC_TARGET_PE
928 tcc_define_symbol(s, "__WCHAR_TYPE__", "unsigned short");
929 #else
930 tcc_define_symbol(s, "__WCHAR_TYPE__", "int");
931 #endif
933 #ifndef TCC_TARGET_PE
934 /* default library paths */
935 tcc_add_library_path(s, CONFIG_SYSROOT "/usr/local/lib");
936 tcc_add_library_path(s, CONFIG_SYSROOT "/usr/lib");
937 tcc_add_library_path(s, CONFIG_SYSROOT "/lib");
938 #endif
940 /* no section zero */
941 dynarray_add((void ***)&s->sections, &s->nb_sections, NULL);
943 /* create standard sections */
944 text_section = new_section(s, ".text", SHT_PROGBITS, SHF_ALLOC | SHF_EXECINSTR);
945 data_section = new_section(s, ".data", SHT_PROGBITS, SHF_ALLOC | SHF_WRITE);
946 bss_section = new_section(s, ".bss", SHT_NOBITS, SHF_ALLOC | SHF_WRITE);
948 /* symbols are always generated for linking stage */
949 symtab_section = new_symtab(s, ".symtab", SHT_SYMTAB, 0,
950 ".strtab",
951 ".hashtab", SHF_PRIVATE);
952 strtab_section = symtab_section->link;
954 /* private symbol table for dynamic symbols */
955 s->dynsymtab_section = new_symtab(s, ".dynsymtab", SHT_SYMTAB, SHF_PRIVATE,
956 ".dynstrtab",
957 ".dynhashtab", SHF_PRIVATE);
958 s->alacarte_link = 1;
959 s->nocommon = 1;
961 #ifdef CHAR_IS_UNSIGNED
962 s->char_is_unsigned = 1;
963 #endif
964 #if defined(TCC_TARGET_PE) && 0
965 /* XXX: currently the PE linker is not ready to support that */
966 s->leading_underscore = 1;
967 #endif
968 if (s->section_align == 0)
969 s->section_align = ELF_PAGE_SIZE;
970 #ifdef TCC_TARGET_I386
971 s->seg_size = 32;
972 #endif
973 return s;
976 LIBTCCAPI void tcc_delete(TCCState *s1)
978 int i;
980 tcc_cleanup();
982 /* free all sections */
983 for(i = 1; i < s1->nb_sections; i++)
984 free_section(s1->sections[i]);
985 dynarray_reset(&s1->sections, &s1->nb_sections);
987 for(i = 0; i < s1->nb_priv_sections; i++)
988 free_section(s1->priv_sections[i]);
989 dynarray_reset(&s1->priv_sections, &s1->nb_priv_sections);
991 /* free any loaded DLLs */
992 for ( i = 0; i < s1->nb_loaded_dlls; i++) {
993 DLLReference *ref = s1->loaded_dlls[i];
994 if ( ref->handle )
995 dlclose(ref->handle);
998 /* free loaded dlls array */
999 dynarray_reset(&s1->loaded_dlls, &s1->nb_loaded_dlls);
1001 /* free library paths */
1002 dynarray_reset(&s1->library_paths, &s1->nb_library_paths);
1004 /* free include paths */
1005 dynarray_reset(&s1->cached_includes, &s1->nb_cached_includes);
1006 dynarray_reset(&s1->include_paths, &s1->nb_include_paths);
1007 dynarray_reset(&s1->sysinclude_paths, &s1->nb_sysinclude_paths);
1009 tcc_free(s1->tcc_lib_path);
1010 tcc_free(s1->runtime_mem);
1011 tcc_free(s1);
1014 LIBTCCAPI int tcc_add_include_path(TCCState *s1, const char *pathname)
1016 char *pathname1;
1018 pathname1 = tcc_strdup(pathname);
1019 dynarray_add((void ***)&s1->include_paths, &s1->nb_include_paths, pathname1);
1020 return 0;
1023 LIBTCCAPI int tcc_add_sysinclude_path(TCCState *s1, const char *pathname)
1025 char *pathname1;
1027 pathname1 = tcc_strdup(pathname);
1028 dynarray_add((void ***)&s1->sysinclude_paths, &s1->nb_sysinclude_paths, pathname1);
1029 return 0;
1032 static int tcc_add_file_internal(TCCState *s1, const char *filename, int flags)
1034 const char *ext;
1035 ElfW(Ehdr) ehdr;
1036 int fd, ret, size;
1037 BufferedFile *saved_file;
1039 ret = -1;
1041 /* find source file type with extension */
1042 ext = tcc_fileextension(filename);
1043 if (ext[0])
1044 ext++;
1046 /* open the file */
1047 saved_file = file;
1048 file = tcc_open(s1, filename);
1049 if (!file) {
1050 if (flags & AFF_PRINT_ERROR)
1051 error_noabort("file '%s' not found", filename);
1052 goto the_end;
1055 if (flags & AFF_PREPROCESS) {
1056 ret = tcc_preprocess(s1);
1057 goto the_end;
1060 if (!ext[0] || !PATHCMP(ext, "c")) {
1061 /* C file assumed */
1062 ret = tcc_compile(s1);
1063 goto the_end;
1066 #ifdef CONFIG_TCC_ASM
1067 if (!strcmp(ext, "S")) {
1068 /* preprocessed assembler */
1069 ret = tcc_assemble(s1, 1);
1070 goto the_end;
1073 if (!strcmp(ext, "s")) {
1074 /* non preprocessed assembler */
1075 ret = tcc_assemble(s1, 0);
1076 goto the_end;
1078 #endif
1080 fd = file->fd;
1081 /* assume executable format: auto guess file type */
1082 size = read(fd, &ehdr, sizeof(ehdr));
1083 lseek(fd, 0, SEEK_SET);
1084 if (size <= 0) {
1085 error_noabort("could not read header");
1086 goto the_end;
1089 if (size == sizeof(ehdr) &&
1090 ehdr.e_ident[0] == ELFMAG0 &&
1091 ehdr.e_ident[1] == ELFMAG1 &&
1092 ehdr.e_ident[2] == ELFMAG2 &&
1093 ehdr.e_ident[3] == ELFMAG3) {
1095 /* do not display line number if error */
1096 file->line_num = 0;
1097 if (ehdr.e_type == ET_REL) {
1098 ret = tcc_load_object_file(s1, fd, 0);
1099 goto the_end;
1102 #ifndef TCC_TARGET_PE
1103 if (ehdr.e_type == ET_DYN) {
1104 if (s1->output_type == TCC_OUTPUT_MEMORY) {
1105 void *h;
1106 h = dlopen(filename, RTLD_GLOBAL | RTLD_LAZY);
1107 if (h)
1108 ret = 0;
1109 } else {
1110 ret = tcc_load_dll(s1, fd, filename,
1111 (flags & AFF_REFERENCED_DLL) != 0);
1113 goto the_end;
1115 #endif
1116 error_noabort("unrecognized ELF file");
1117 goto the_end;
1120 if (memcmp((char *)&ehdr, ARMAG, 8) == 0) {
1121 file->line_num = 0; /* do not display line number if error */
1122 ret = tcc_load_archive(s1, fd);
1123 goto the_end;
1126 #ifdef TCC_TARGET_COFF
1127 if (*(uint16_t *)(&ehdr) == COFF_C67_MAGIC) {
1128 ret = tcc_load_coff(s1, fd);
1129 goto the_end;
1131 #endif
1133 #ifdef TCC_TARGET_PE
1134 ret = pe_load_file(s1, filename, fd);
1135 #else
1136 /* as GNU ld, consider it is an ld script if not recognized */
1137 ret = tcc_load_ldscript(s1);
1138 #endif
1139 if (ret < 0)
1140 error_noabort("unrecognized file type");
1142 the_end:
1143 if (file)
1144 tcc_close(file);
1145 file = saved_file;
1146 return ret;
1149 LIBTCCAPI int tcc_add_file(TCCState *s, const char *filename)
1151 if (s->output_type == TCC_OUTPUT_PREPROCESS)
1152 return tcc_add_file_internal(s, filename, AFF_PRINT_ERROR | AFF_PREPROCESS);
1153 else
1154 return tcc_add_file_internal(s, filename, AFF_PRINT_ERROR);
1157 LIBTCCAPI int tcc_add_library_path(TCCState *s, const char *pathname)
1159 char *pathname1;
1161 pathname1 = tcc_strdup(pathname);
1162 dynarray_add((void ***)&s->library_paths, &s->nb_library_paths, pathname1);
1163 return 0;
1166 /* find and load a dll. Return non zero if not found */
1167 /* XXX: add '-rpath' option support ? */
1168 ST_FUNC int tcc_add_dll(TCCState *s, const char *filename, int flags)
1170 char buf[1024];
1171 int i;
1173 for(i = 0; i < s->nb_library_paths; i++) {
1174 snprintf(buf, sizeof(buf), "%s/%s",
1175 s->library_paths[i], filename);
1176 if (tcc_add_file_internal(s, buf, flags) == 0)
1177 return 0;
1179 return -1;
1182 /* the library name is the same as the argument of the '-l' option */
1183 LIBTCCAPI int tcc_add_library(TCCState *s, const char *libraryname)
1185 char buf[1024];
1186 int i;
1188 /* first we look for the dynamic library if not static linking */
1189 if (!s->static_link) {
1190 #ifdef TCC_TARGET_PE
1191 if (pe_add_dll(s, libraryname) == 0)
1192 return 0;
1193 #else
1194 snprintf(buf, sizeof(buf), "lib%s.so", libraryname);
1195 if (tcc_add_dll(s, buf, 0) == 0)
1196 return 0;
1197 #endif
1199 /* then we look for the static library */
1200 for(i = 0; i < s->nb_library_paths; i++) {
1201 snprintf(buf, sizeof(buf), "%s/lib%s.a",
1202 s->library_paths[i], libraryname);
1203 if (tcc_add_file_internal(s, buf, 0) == 0)
1204 return 0;
1206 return -1;
1209 LIBTCCAPI int tcc_add_symbol(TCCState *s, const char *name, void *val)
1211 add_elf_sym(symtab_section, (uplong)val, 0,
1212 ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE), 0,
1213 SHN_ABS, name);
1214 return 0;
1217 LIBTCCAPI int tcc_set_output_type(TCCState *s, int output_type)
1219 char buf[1024];
1221 s->output_type = output_type;
1223 if (!s->nostdinc) {
1224 /* default include paths */
1225 /* XXX: reverse order needed if -isystem support */
1226 #ifndef TCC_TARGET_PE
1227 tcc_add_sysinclude_path(s, CONFIG_SYSROOT "/usr/local/include");
1228 tcc_add_sysinclude_path(s, CONFIG_SYSROOT "/usr/include");
1229 #endif
1230 snprintf(buf, sizeof(buf), "%s/include", s->tcc_lib_path);
1231 tcc_add_sysinclude_path(s, buf);
1232 #ifdef TCC_TARGET_PE
1233 snprintf(buf, sizeof(buf), "%s/include/winapi", s->tcc_lib_path);
1234 tcc_add_sysinclude_path(s, buf);
1235 #endif
1238 /* if bound checking, then add corresponding sections */
1239 #ifdef CONFIG_TCC_BCHECK
1240 if (s->do_bounds_check) {
1241 /* define symbol */
1242 tcc_define_symbol(s, "__BOUNDS_CHECKING_ON", NULL);
1243 /* create bounds sections */
1244 bounds_section = new_section(s, ".bounds",
1245 SHT_PROGBITS, SHF_ALLOC);
1246 lbounds_section = new_section(s, ".lbounds",
1247 SHT_PROGBITS, SHF_ALLOC);
1249 #endif
1251 if (s->char_is_unsigned) {
1252 tcc_define_symbol(s, "__CHAR_UNSIGNED__", NULL);
1255 /* add debug sections */
1256 if (s->do_debug) {
1257 /* stab symbols */
1258 stab_section = new_section(s, ".stab", SHT_PROGBITS, 0);
1259 stab_section->sh_entsize = sizeof(Stab_Sym);
1260 stabstr_section = new_section(s, ".stabstr", SHT_STRTAB, 0);
1261 put_elf_str(stabstr_section, "");
1262 stab_section->link = stabstr_section;
1263 /* put first entry */
1264 put_stabs("", 0, 0, 0, 0);
1267 /* add libc crt1/crti objects */
1268 #ifndef TCC_TARGET_PE
1269 if ((output_type == TCC_OUTPUT_EXE || output_type == TCC_OUTPUT_DLL) &&
1270 !s->nostdlib) {
1271 if (output_type != TCC_OUTPUT_DLL)
1272 tcc_add_file(s, CONFIG_TCC_CRT_PREFIX "/crt1.o");
1273 tcc_add_file(s, CONFIG_TCC_CRT_PREFIX "/crti.o");
1275 #endif
1277 #ifdef TCC_TARGET_PE
1278 snprintf(buf, sizeof(buf), "%s/lib", s->tcc_lib_path);
1279 tcc_add_library_path(s, buf);
1280 #ifdef _WIN32
1281 if (GetSystemDirectory(buf, sizeof buf))
1282 tcc_add_library_path(s, buf);
1283 #endif
1284 #endif
1286 return 0;
1289 #define WD_ALL 0x0001 /* warning is activated when using -Wall */
1290 #define FD_INVERT 0x0002 /* invert value before storing */
1292 typedef struct FlagDef {
1293 uint16_t offset;
1294 uint16_t flags;
1295 const char *name;
1296 } FlagDef;
1298 static const FlagDef warning_defs[] = {
1299 { offsetof(TCCState, warn_unsupported), 0, "unsupported" },
1300 { offsetof(TCCState, warn_write_strings), 0, "write-strings" },
1301 { offsetof(TCCState, warn_error), 0, "error" },
1302 { offsetof(TCCState, warn_implicit_function_declaration), WD_ALL,
1303 "implicit-function-declaration" },
1306 ST_FUNC int set_flag(TCCState *s, const FlagDef *flags, int nb_flags,
1307 const char *name, int value)
1309 int i;
1310 const FlagDef *p;
1311 const char *r;
1313 r = name;
1314 if (r[0] == 'n' && r[1] == 'o' && r[2] == '-') {
1315 r += 3;
1316 value = !value;
1318 for(i = 0, p = flags; i < nb_flags; i++, p++) {
1319 if (!strcmp(r, p->name))
1320 goto found;
1322 return -1;
1323 found:
1324 if (p->flags & FD_INVERT)
1325 value = !value;
1326 *(int *)((uint8_t *)s + p->offset) = value;
1327 return 0;
1330 /* set/reset a warning */
1331 LIBTCCAPI int tcc_set_warning(TCCState *s, const char *warning_name, int value)
1333 int i;
1334 const FlagDef *p;
1336 if (!strcmp(warning_name, "all")) {
1337 for(i = 0, p = warning_defs; i < countof(warning_defs); i++, p++) {
1338 if (p->flags & WD_ALL)
1339 *(int *)((uint8_t *)s + p->offset) = 1;
1341 return 0;
1342 } else {
1343 return set_flag(s, warning_defs, countof(warning_defs),
1344 warning_name, value);
1348 static const FlagDef flag_defs[] = {
1349 { offsetof(TCCState, char_is_unsigned), 0, "unsigned-char" },
1350 { offsetof(TCCState, char_is_unsigned), FD_INVERT, "signed-char" },
1351 { offsetof(TCCState, nocommon), FD_INVERT, "common" },
1352 { offsetof(TCCState, leading_underscore), 0, "leading-underscore" },
1355 /* set/reset a flag */
1356 PUB_FUNC int tcc_set_flag(TCCState *s, const char *flag_name, int value)
1358 return set_flag(s, flag_defs, countof(flag_defs),
1359 flag_name, value);
1362 PUB_FUNC void tcc_print_stats(TCCState *s, int64_t total_time)
1364 double tt;
1365 tt = (double)total_time / 1000000.0;
1366 if (tt < 0.001)
1367 tt = 0.001;
1368 if (total_bytes < 1)
1369 total_bytes = 1;
1370 printf("%d idents, %d lines, %d bytes, %0.3f s, %d lines/s, %0.1f MB/s\n",
1371 tok_ident - TOK_IDENT, total_lines, total_bytes,
1372 tt, (int)(total_lines / tt),
1373 total_bytes / tt / 1000000.0);
1376 /* set CONFIG_TCCDIR at runtime */
1377 LIBTCCAPI void tcc_set_lib_path(TCCState *s, const char *path)
1379 tcc_free(s->tcc_lib_path);
1380 s->tcc_lib_path = tcc_strdup(path);
1383 PUB_FUNC void set_num_callers(int n)
1385 #ifdef CONFIG_TCC_BACKTRACE
1386 num_callers = n;
1387 #endif