tccpe: improve dllimport/export and use for tcc_add_symbol
[tinycc.git] / libtcc.c
blobae80bc6490a1227b29b11bd67d3978381fd53df1
1 /*
2 * TCC - Tiny C Compiler
3 *
4 * Copyright (c) 2001-2004 Fabrice Bellard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 #include "tcc.h"
23 /********************************************************/
24 /* global variables */
26 /* use GNU C extensions */
27 ST_DATA int gnu_ext = 1;
29 /* use TinyCC extensions */
30 ST_DATA int tcc_ext = 1;
32 /* XXX: get rid of this ASAP */
33 ST_DATA struct TCCState *tcc_state;
35 #ifdef CONFIG_TCC_BACKTRACE
36 ST_DATA int num_callers = 6;
37 ST_DATA const char **rt_bound_error_msg;
38 ST_DATA void *rt_prog_main;
39 #endif
41 /********************************************************/
43 #ifndef NOTALLINONE
44 #include "tccpp.c"
45 #include "tccgen.c"
46 #include "tccelf.c"
47 #include "tccrun.c"
48 #ifdef TCC_TARGET_I386
49 #include "i386-gen.c"
50 #endif
51 #ifdef TCC_TARGET_ARM
52 #include "arm-gen.c"
53 #endif
54 #ifdef TCC_TARGET_C67
55 #include "c67-gen.c"
56 #endif
57 #ifdef TCC_TARGET_X86_64
58 #include "x86_64-gen.c"
59 #endif
60 #ifdef CONFIG_TCC_ASM
61 #include "tccasm.c"
62 #if defined TCC_TARGET_I386 || defined TCC_TARGET_X86_64
63 #include "i386-asm.c"
64 #endif
65 #endif
66 #ifdef TCC_TARGET_COFF
67 #include "tcccoff.c"
68 #endif
69 #ifdef TCC_TARGET_PE
70 #include "tccpe.c"
71 #endif
72 #endif /* ALL_IN_ONE */
74 /********************************************************/
75 #ifndef CONFIG_TCC_ASM
76 ST_FUNC void asm_instr(void)
78 error("inline asm() not supported");
80 ST_FUNC void asm_global_instr(void)
82 error("inline asm() not supported");
84 #endif
86 /********************************************************/
88 #ifdef _WIN32
89 static char *normalize_slashes(char *path)
91 char *p;
92 for (p = path; *p; ++p)
93 if (*p == '\\')
94 *p = '/';
95 return path;
98 static HMODULE tcc_module;
100 /* on win32, we suppose the lib and includes are at the location of 'tcc.exe' */
101 static void tcc_set_lib_path_w32(TCCState *s)
103 char path[1024], *p;
104 GetModuleFileNameA(tcc_module, path, sizeof path);
105 p = tcc_basename(normalize_slashes(strlwr(path)));
106 if (p - 5 > path && 0 == strncmp(p - 5, "/bin/", 5))
107 p -= 5;
108 else if (p > path)
109 p--;
110 *p = 0;
111 tcc_set_lib_path(s, path);
114 #ifndef CONFIG_TCC_STATIC
115 void dlclose(void *p)
117 FreeLibrary((HMODULE)p);
119 #endif
121 #ifdef LIBTCC_AS_DLL
122 BOOL WINAPI DllMain (HANDLE hDll, DWORD dwReason, LPVOID lpReserved)
124 if (DLL_PROCESS_ATTACH == dwReason)
125 tcc_module = hDll;
126 return TRUE;
128 #endif
129 #endif
131 /********************************************************/
132 /* copy a string and truncate it. */
133 PUB_FUNC char *pstrcpy(char *buf, int buf_size, const char *s)
135 char *q, *q_end;
136 int c;
138 if (buf_size > 0) {
139 q = buf;
140 q_end = buf + buf_size - 1;
141 while (q < q_end) {
142 c = *s++;
143 if (c == '\0')
144 break;
145 *q++ = c;
147 *q = '\0';
149 return buf;
152 /* strcat and truncate. */
153 PUB_FUNC char *pstrcat(char *buf, int buf_size, const char *s)
155 int len;
156 len = strlen(buf);
157 if (len < buf_size)
158 pstrcpy(buf + len, buf_size - len, s);
159 return buf;
162 /* extract the basename of a file */
163 PUB_FUNC char *tcc_basename(const char *name)
165 char *p = strchr(name, 0);
166 while (p > name && !IS_PATHSEP(p[-1]))
167 --p;
168 return p;
171 PUB_FUNC char *tcc_fileextension (const char *name)
173 char *b = tcc_basename(name);
174 char *e = strrchr(b, '.');
175 return e ? e : strchr(b, 0);
178 /********************************************************/
179 /* memory management */
181 #undef free
182 #undef malloc
183 #undef realloc
185 #ifdef MEM_DEBUG
186 int mem_cur_size;
187 int mem_max_size;
188 unsigned malloc_usable_size(void*);
189 #endif
191 PUB_FUNC void tcc_free(void *ptr)
193 #ifdef MEM_DEBUG
194 mem_cur_size -= malloc_usable_size(ptr);
195 #endif
196 free(ptr);
199 PUB_FUNC void *tcc_malloc(unsigned long size)
201 void *ptr;
202 ptr = malloc(size);
203 if (!ptr && size)
204 error("memory full");
205 #ifdef MEM_DEBUG
206 mem_cur_size += malloc_usable_size(ptr);
207 if (mem_cur_size > mem_max_size)
208 mem_max_size = mem_cur_size;
209 #endif
210 return ptr;
213 PUB_FUNC void *tcc_mallocz(unsigned long size)
215 void *ptr;
216 ptr = tcc_malloc(size);
217 memset(ptr, 0, size);
218 return ptr;
221 PUB_FUNC void *tcc_realloc(void *ptr, unsigned long size)
223 void *ptr1;
224 #ifdef MEM_DEBUG
225 mem_cur_size -= malloc_usable_size(ptr);
226 #endif
227 ptr1 = realloc(ptr, size);
228 #ifdef MEM_DEBUG
229 /* NOTE: count not correct if alloc error, but not critical */
230 mem_cur_size += malloc_usable_size(ptr1);
231 if (mem_cur_size > mem_max_size)
232 mem_max_size = mem_cur_size;
233 #endif
234 return ptr1;
237 PUB_FUNC char *tcc_strdup(const char *str)
239 char *ptr;
240 ptr = tcc_malloc(strlen(str) + 1);
241 strcpy(ptr, str);
242 return ptr;
245 PUB_FUNC void tcc_memstats(void)
247 #ifdef MEM_DEBUG
248 printf("memory in use: %d\n", mem_cur_size);
249 #endif
252 #define free(p) use_tcc_free(p)
253 #define malloc(s) use_tcc_malloc(s)
254 #define realloc(p, s) use_tcc_realloc(p, s)
256 /********************************************************/
257 /* dynarrays */
259 PUB_FUNC void dynarray_add(void ***ptab, int *nb_ptr, void *data)
261 int nb, nb_alloc;
262 void **pp;
264 nb = *nb_ptr;
265 pp = *ptab;
266 /* every power of two we double array size */
267 if ((nb & (nb - 1)) == 0) {
268 if (!nb)
269 nb_alloc = 1;
270 else
271 nb_alloc = nb * 2;
272 pp = tcc_realloc(pp, nb_alloc * sizeof(void *));
273 if (!pp)
274 error("memory full");
275 *ptab = pp;
277 pp[nb++] = data;
278 *nb_ptr = nb;
281 PUB_FUNC void dynarray_reset(void *pp, int *n)
283 void **p;
284 for (p = *(void***)pp; *n; ++p, --*n)
285 if (*p)
286 tcc_free(*p);
287 tcc_free(*(void**)pp);
288 *(void**)pp = NULL;
291 /* we use our own 'finite' function to avoid potential problems with
292 non standard math libs */
293 /* XXX: endianness dependent */
294 ST_FUNC int ieee_finite(double d)
296 int *p = (int *)&d;
297 return ((unsigned)((p[1] | 0x800fffff) + 1)) >> 31;
300 /********************************************************/
302 ST_FUNC Section *new_section(TCCState *s1, const char *name, int sh_type, int sh_flags)
304 Section *sec;
306 sec = tcc_mallocz(sizeof(Section) + strlen(name));
307 strcpy(sec->name, name);
308 sec->sh_type = sh_type;
309 sec->sh_flags = sh_flags;
310 switch(sh_type) {
311 case SHT_HASH:
312 case SHT_REL:
313 case SHT_RELA:
314 case SHT_DYNSYM:
315 case SHT_SYMTAB:
316 case SHT_DYNAMIC:
317 sec->sh_addralign = 4;
318 break;
319 case SHT_STRTAB:
320 sec->sh_addralign = 1;
321 break;
322 default:
323 sec->sh_addralign = 32; /* default conservative alignment */
324 break;
327 if (sh_flags & SHF_PRIVATE) {
328 dynarray_add((void ***)&s1->priv_sections, &s1->nb_priv_sections, sec);
329 } else {
330 sec->sh_num = s1->nb_sections;
331 dynarray_add((void ***)&s1->sections, &s1->nb_sections, sec);
334 return sec;
337 static void free_section(Section *s)
339 tcc_free(s->data);
342 /* realloc section and set its content to zero */
343 ST_FUNC void section_realloc(Section *sec, unsigned long new_size)
345 unsigned long size;
346 unsigned char *data;
348 size = sec->data_allocated;
349 if (size == 0)
350 size = 1;
351 while (size < new_size)
352 size = size * 2;
353 data = tcc_realloc(sec->data, size);
354 if (!data)
355 error("memory full");
356 memset(data + sec->data_allocated, 0, size - sec->data_allocated);
357 sec->data = data;
358 sec->data_allocated = size;
361 /* reserve at least 'size' bytes in section 'sec' from
362 sec->data_offset. */
363 ST_FUNC void *section_ptr_add(Section *sec, unsigned long size)
365 unsigned long offset, offset1;
367 offset = sec->data_offset;
368 offset1 = offset + size;
369 if (offset1 > sec->data_allocated)
370 section_realloc(sec, offset1);
371 sec->data_offset = offset1;
372 return sec->data + offset;
375 /* return a reference to a section, and create it if it does not
376 exists */
377 ST_FUNC Section *find_section(TCCState *s1, const char *name)
379 Section *sec;
380 int i;
381 for(i = 1; i < s1->nb_sections; i++) {
382 sec = s1->sections[i];
383 if (!strcmp(name, sec->name))
384 return sec;
386 /* sections are created as PROGBITS */
387 return new_section(s1, name, SHT_PROGBITS, SHF_ALLOC);
390 /* update sym->c so that it points to an external symbol in section
391 'section' with value 'value' */
392 ST_FUNC void put_extern_sym2(Sym *sym, Section *section,
393 unsigned long value, unsigned long size,
394 int can_add_underscore)
396 int sym_type, sym_bind, sh_num, info, other;
397 ElfW(Sym) *esym;
398 const char *name;
399 char buf1[256];
401 if (section == NULL)
402 sh_num = SHN_UNDEF;
403 else if (section == SECTION_ABS)
404 sh_num = SHN_ABS;
405 else
406 sh_num = section->sh_num;
408 if ((sym->type.t & VT_BTYPE) == VT_FUNC) {
409 sym_type = STT_FUNC;
410 } else if ((sym->type.t & VT_BTYPE) == VT_VOID) {
411 sym_type = STT_NOTYPE;
412 } else {
413 sym_type = STT_OBJECT;
416 if (sym->type.t & VT_STATIC)
417 sym_bind = STB_LOCAL;
418 else
419 sym_bind = STB_GLOBAL;
421 if (!sym->c) {
422 name = get_tok_str(sym->v, NULL);
423 #ifdef CONFIG_TCC_BCHECK
424 if (tcc_state->do_bounds_check) {
425 char buf[32];
427 /* XXX: avoid doing that for statics ? */
428 /* if bound checking is activated, we change some function
429 names by adding the "__bound" prefix */
430 switch(sym->v) {
431 #ifdef TCC_TARGET_PE
432 /* XXX: we rely only on malloc hooks */
433 case TOK_malloc:
434 case TOK_free:
435 case TOK_realloc:
436 case TOK_memalign:
437 case TOK_calloc:
438 #endif
439 case TOK_memcpy:
440 case TOK_memmove:
441 case TOK_memset:
442 case TOK_strlen:
443 case TOK_strcpy:
444 case TOK_alloca:
445 strcpy(buf, "__bound_");
446 strcat(buf, name);
447 name = buf;
448 break;
451 #endif
452 other = 0;
454 #ifdef TCC_TARGET_PE
455 if (sym->type.t & VT_EXPORT)
456 other |= 1;
457 if (sym_type == STT_FUNC && sym->type.ref) {
458 int attr = sym->type.ref->r;
459 if (FUNC_EXPORT(attr))
460 other |= 1;
461 if (FUNC_CALL(attr) == FUNC_STDCALL && can_add_underscore) {
462 sprintf(buf1, "_%s@%d", name, FUNC_ARGS(attr) * PTR_SIZE);
463 name = buf1;
464 other |= 2;
465 can_add_underscore = 0;
467 } else {
468 if (find_elf_sym(tcc_state->dynsymtab_section, name))
469 other |= 4;
470 if (sym->type.t & VT_IMPORT)
471 other |= 4;
473 #endif
474 if (tcc_state->leading_underscore && can_add_underscore) {
475 buf1[0] = '_';
476 pstrcpy(buf1 + 1, sizeof(buf1) - 1, name);
477 name = buf1;
479 info = ELFW(ST_INFO)(sym_bind, sym_type);
480 sym->c = add_elf_sym(symtab_section, value, size, info, other, sh_num, name);
481 } else {
482 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
483 esym->st_value = value;
484 esym->st_size = size;
485 esym->st_shndx = sh_num;
489 ST_FUNC void put_extern_sym(Sym *sym, Section *section,
490 unsigned long value, unsigned long size)
492 put_extern_sym2(sym, section, value, size, 1);
495 /* add a new relocation entry to symbol 'sym' in section 's' */
496 ST_FUNC void greloc(Section *s, Sym *sym, unsigned long offset, int type)
498 int c = 0;
499 if (sym) {
500 if (0 == sym->c)
501 put_extern_sym(sym, NULL, 0, 0);
502 c = sym->c;
504 /* now we can add ELF relocation info */
505 put_elf_reloc(symtab_section, s, offset, type, c);
508 /********************************************************/
510 static void strcat_vprintf(char *buf, int buf_size, const char *fmt, va_list ap)
512 int len;
513 len = strlen(buf);
514 vsnprintf(buf + len, buf_size - len, fmt, ap);
517 static void strcat_printf(char *buf, int buf_size, const char *fmt, ...)
519 va_list ap;
520 va_start(ap, fmt);
521 strcat_vprintf(buf, buf_size, fmt, ap);
522 va_end(ap);
525 static void error1(TCCState *s1, int is_warning, const char *fmt, va_list ap)
527 char buf[2048];
528 BufferedFile **f;
530 buf[0] = '\0';
531 if (file) {
532 for(f = s1->include_stack; f < s1->include_stack_ptr; f++)
533 strcat_printf(buf, sizeof(buf), "In file included from %s:%d:\n",
534 (*f)->filename, (*f)->line_num);
535 if (file->line_num > 0) {
536 strcat_printf(buf, sizeof(buf),
537 "%s:%d: ", file->filename, file->line_num);
538 } else {
539 strcat_printf(buf, sizeof(buf),
540 "%s: ", file->filename);
542 } else {
543 strcat_printf(buf, sizeof(buf),
544 "tcc: ");
546 if (is_warning)
547 strcat_printf(buf, sizeof(buf), "warning: ");
548 else
549 strcat_printf(buf, sizeof(buf), "error: ");
550 strcat_vprintf(buf, sizeof(buf), fmt, ap);
552 if (!s1->error_func) {
553 /* default case: stderr */
554 fprintf(stderr, "%s\n", buf);
555 } else {
556 s1->error_func(s1->error_opaque, buf);
558 if (!is_warning || s1->warn_error)
559 s1->nb_errors++;
562 LIBTCCAPI void tcc_set_error_func(TCCState *s, void *error_opaque,
563 void (*error_func)(void *opaque, const char *msg))
565 s->error_opaque = error_opaque;
566 s->error_func = error_func;
569 /* error without aborting current compilation */
570 PUB_FUNC void error_noabort(const char *fmt, ...)
572 TCCState *s1 = tcc_state;
573 va_list ap;
575 va_start(ap, fmt);
576 error1(s1, 0, fmt, ap);
577 va_end(ap);
580 PUB_FUNC void error(const char *fmt, ...)
582 TCCState *s1 = tcc_state;
583 va_list ap;
585 va_start(ap, fmt);
586 error1(s1, 0, fmt, ap);
587 va_end(ap);
588 /* better than nothing: in some cases, we accept to handle errors */
589 if (s1->error_set_jmp_enabled) {
590 longjmp(s1->error_jmp_buf, 1);
591 } else {
592 /* XXX: eliminate this someday */
593 exit(1);
597 PUB_FUNC void expect(const char *msg)
599 error("%s expected", msg);
602 PUB_FUNC void warning(const char *fmt, ...)
604 TCCState *s1 = tcc_state;
605 va_list ap;
607 if (s1->warn_none)
608 return;
610 va_start(ap, fmt);
611 error1(s1, 1, fmt, ap);
612 va_end(ap);
615 /********************************************************/
616 /* I/O layer */
618 ST_FUNC BufferedFile *tcc_open(TCCState *s1, const char *filename)
620 int fd;
621 BufferedFile *bf;
623 if (strcmp(filename, "-") == 0)
624 fd = 0, filename = "stdin";
625 else
626 fd = open(filename, O_RDONLY | O_BINARY);
627 if ((s1->verbose == 2 && fd >= 0) || s1->verbose == 3)
628 printf("%s %*s%s\n", fd < 0 ? "nf":"->",
629 (int)(s1->include_stack_ptr - s1->include_stack), "", filename);
630 if (fd < 0)
631 return NULL;
632 bf = tcc_malloc(sizeof(BufferedFile));
633 bf->fd = fd;
634 bf->buf_ptr = bf->buffer;
635 bf->buf_end = bf->buffer;
636 bf->buffer[0] = CH_EOB; /* put eob symbol */
637 pstrcpy(bf->filename, sizeof(bf->filename), filename);
638 #ifdef _WIN32
639 normalize_slashes(bf->filename);
640 #endif
641 bf->line_num = 1;
642 bf->ifndef_macro = 0;
643 bf->ifdef_stack_ptr = s1->ifdef_stack_ptr;
644 // printf("opening '%s'\n", filename);
645 return bf;
648 ST_FUNC void tcc_close(BufferedFile *bf)
650 total_lines += bf->line_num;
651 close(bf->fd);
652 tcc_free(bf);
655 /* compile the C file opened in 'file'. Return non zero if errors. */
656 static int tcc_compile(TCCState *s1)
658 Sym *define_start;
659 char buf[512];
660 volatile int section_sym;
662 #ifdef INC_DEBUG
663 printf("%s: **** new file\n", file->filename);
664 #endif
665 preprocess_init(s1);
667 cur_text_section = NULL;
668 funcname = "";
669 anon_sym = SYM_FIRST_ANOM;
671 /* file info: full path + filename */
672 section_sym = 0; /* avoid warning */
673 if (s1->do_debug) {
674 section_sym = put_elf_sym(symtab_section, 0, 0,
675 ELFW(ST_INFO)(STB_LOCAL, STT_SECTION), 0,
676 text_section->sh_num, NULL);
677 getcwd(buf, sizeof(buf));
678 #ifdef _WIN32
679 normalize_slashes(buf);
680 #endif
681 pstrcat(buf, sizeof(buf), "/");
682 put_stabs_r(buf, N_SO, 0, 0,
683 text_section->data_offset, text_section, section_sym);
684 put_stabs_r(file->filename, N_SO, 0, 0,
685 text_section->data_offset, text_section, section_sym);
687 /* an elf symbol of type STT_FILE must be put so that STB_LOCAL
688 symbols can be safely used */
689 put_elf_sym(symtab_section, 0, 0,
690 ELFW(ST_INFO)(STB_LOCAL, STT_FILE), 0,
691 SHN_ABS, file->filename);
693 /* define some often used types */
694 int_type.t = VT_INT;
696 char_pointer_type.t = VT_BYTE;
697 mk_pointer(&char_pointer_type);
699 func_old_type.t = VT_FUNC;
700 func_old_type.ref = sym_push(SYM_FIELD, &int_type, FUNC_CDECL, FUNC_OLD);
702 #if defined(TCC_ARM_EABI) && defined(TCC_ARM_VFP)
703 float_type.t = VT_FLOAT;
704 double_type.t = VT_DOUBLE;
706 func_float_type.t = VT_FUNC;
707 func_float_type.ref = sym_push(SYM_FIELD, &float_type, FUNC_CDECL, FUNC_OLD);
708 func_double_type.t = VT_FUNC;
709 func_double_type.ref = sym_push(SYM_FIELD, &double_type, FUNC_CDECL, FUNC_OLD);
710 #endif
712 #if 0
713 /* define 'void *alloca(unsigned int)' builtin function */
715 Sym *s1;
717 p = anon_sym++;
718 sym = sym_push(p, mk_pointer(VT_VOID), FUNC_CDECL, FUNC_NEW);
719 s1 = sym_push(SYM_FIELD, VT_UNSIGNED | VT_INT, 0, 0);
720 s1->next = NULL;
721 sym->next = s1;
722 sym_push(TOK_alloca, VT_FUNC | (p << VT_STRUCT_SHIFT), VT_CONST, 0);
724 #endif
726 define_start = define_stack;
727 nocode_wanted = 1;
729 if (setjmp(s1->error_jmp_buf) == 0) {
730 s1->nb_errors = 0;
731 s1->error_set_jmp_enabled = 1;
733 ch = file->buf_ptr[0];
734 tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
735 parse_flags = PARSE_FLAG_PREPROCESS | PARSE_FLAG_TOK_NUM;
736 next();
737 decl(VT_CONST);
738 if (tok != TOK_EOF)
739 expect("declaration");
741 /* end of translation unit info */
742 if (s1->do_debug) {
743 put_stabs_r(NULL, N_SO, 0, 0,
744 text_section->data_offset, text_section, section_sym);
747 s1->error_set_jmp_enabled = 0;
749 /* reset define stack, but leave -Dsymbols (may be incorrect if
750 they are undefined) */
751 free_defines(define_start);
753 gen_inline_functions();
755 sym_pop(&global_stack, NULL);
756 sym_pop(&local_stack, NULL);
758 return s1->nb_errors != 0 ? -1 : 0;
761 LIBTCCAPI int tcc_compile_string(TCCState *s, const char *str)
763 BufferedFile bf1, *bf = &bf1;
764 int ret, len;
765 char *buf;
767 /* init file structure */
768 bf->fd = -1;
769 /* XXX: avoid copying */
770 len = strlen(str);
771 buf = tcc_malloc(len + 1);
772 if (!buf)
773 return -1;
774 memcpy(buf, str, len);
775 buf[len] = CH_EOB;
776 bf->buf_ptr = buf;
777 bf->buf_end = buf + len;
778 pstrcpy(bf->filename, sizeof(bf->filename), "<string>");
779 bf->line_num = 1;
780 file = bf;
781 ret = tcc_compile(s);
782 file = NULL;
783 tcc_free(buf);
785 /* currently, no need to close */
786 return ret;
789 /* define a preprocessor symbol. A value can also be provided with the '=' operator */
790 LIBTCCAPI void tcc_define_symbol(TCCState *s1, const char *sym, const char *value)
792 BufferedFile bf1, *bf = &bf1;
794 pstrcpy(bf->buffer, IO_BUF_SIZE, sym);
795 pstrcat(bf->buffer, IO_BUF_SIZE, " ");
796 /* default value */
797 if (!value)
798 value = "1";
799 pstrcat(bf->buffer, IO_BUF_SIZE, value);
801 /* init file structure */
802 bf->fd = -1;
803 bf->buf_ptr = bf->buffer;
804 bf->buf_end = bf->buffer + strlen(bf->buffer);
805 *bf->buf_end = CH_EOB;
806 bf->filename[0] = '\0';
807 bf->line_num = 1;
808 file = bf;
810 s1->include_stack_ptr = s1->include_stack;
812 /* parse with define parser */
813 ch = file->buf_ptr[0];
814 next_nomacro();
815 parse_define();
816 file = NULL;
819 /* undefine a preprocessor symbol */
820 LIBTCCAPI void tcc_undefine_symbol(TCCState *s1, const char *sym)
822 TokenSym *ts;
823 Sym *s;
824 ts = tok_alloc(sym, strlen(sym));
825 s = define_find(ts->tok);
826 /* undefine symbol by putting an invalid name */
827 if (s)
828 define_undef(s);
831 static void tcc_cleanup(void)
833 int i, n;
835 if (NULL == tcc_state)
836 return;
837 tcc_state = NULL;
839 /* free -D defines */
840 free_defines(NULL);
842 /* free tokens */
843 n = tok_ident - TOK_IDENT;
844 for(i = 0; i < n; i++)
845 tcc_free(table_ident[i]);
846 tcc_free(table_ident);
848 /* free sym_pools */
849 dynarray_reset(&sym_pools, &nb_sym_pools);
850 /* string buffer */
851 cstr_free(&tokcstr);
852 /* reset symbol stack */
853 sym_free_first = NULL;
854 /* cleanup from error/setjmp */
855 macro_ptr = NULL;
858 LIBTCCAPI TCCState *tcc_new(void)
860 TCCState *s;
861 char buffer[100];
862 int a,b,c;
864 tcc_cleanup();
866 s = tcc_mallocz(sizeof(TCCState));
867 if (!s)
868 return NULL;
869 tcc_state = s;
870 #ifdef _WIN32
871 tcc_set_lib_path_w32(s);
872 #else
873 tcc_set_lib_path(s, CONFIG_TCCDIR);
874 #endif
875 s->output_type = TCC_OUTPUT_MEMORY;
876 preprocess_new();
878 /* we add dummy defines for some special macros to speed up tests
879 and to have working defined() */
880 define_push(TOK___LINE__, MACRO_OBJ, NULL, NULL);
881 define_push(TOK___FILE__, MACRO_OBJ, NULL, NULL);
882 define_push(TOK___DATE__, MACRO_OBJ, NULL, NULL);
883 define_push(TOK___TIME__, MACRO_OBJ, NULL, NULL);
885 /* standard defines */
886 tcc_define_symbol(s, "__STDC__", NULL);
887 tcc_define_symbol(s, "__STDC_VERSION__", "199901L");
888 #if defined(TCC_TARGET_I386)
889 tcc_define_symbol(s, "__i386__", "1");
890 tcc_define_symbol(s, "__i386", "1");
891 tcc_define_symbol(s, "i386", "1");
892 #endif
893 #if defined(TCC_TARGET_X86_64)
894 tcc_define_symbol(s, "__x86_64__", NULL);
895 #endif
896 #if defined(TCC_TARGET_ARM)
897 tcc_define_symbol(s, "__ARM_ARCH_4__", NULL);
898 tcc_define_symbol(s, "__arm_elf__", NULL);
899 tcc_define_symbol(s, "__arm_elf", NULL);
900 tcc_define_symbol(s, "arm_elf", NULL);
901 tcc_define_symbol(s, "__arm__", NULL);
902 tcc_define_symbol(s, "__arm", NULL);
903 tcc_define_symbol(s, "arm", NULL);
904 tcc_define_symbol(s, "__APCS_32__", NULL);
905 #endif
906 #ifdef TCC_TARGET_PE
907 tcc_define_symbol(s, "_WIN32", NULL);
908 #ifdef TCC_TARGET_X86_64
909 tcc_define_symbol(s, "_WIN64", NULL);
910 #endif
911 #else
912 tcc_define_symbol(s, "__unix__", "1");
913 tcc_define_symbol(s, "__unix", "1");
914 tcc_define_symbol(s, "unix", "1");
915 #if defined(__FreeBSD__)
916 #define str(s) #s
917 tcc_define_symbol(s, "__FreeBSD__", str( __FreeBSD__));
918 tcc_define_symbol(s, "__INTEL_COMPILER", "1");
919 #undef str
920 #endif
921 #if defined(__linux)
922 tcc_define_symbol(s, "__linux__", NULL);
923 tcc_define_symbol(s, "__linux", NULL);
924 #endif
925 #endif
926 /* tiny C specific defines */
927 sscanf(TCC_VERSION, "%d.%d.%d", &a, &b, &c);
928 sprintf(buffer, "%d", a*10000 + b*100 + c);
929 tcc_define_symbol(s, "__TINYC__", buffer);
931 /* tiny C & gcc defines */
932 tcc_define_symbol(s, "__SIZE_TYPE__", "unsigned long");
933 tcc_define_symbol(s, "__PTRDIFF_TYPE__", "long");
934 #ifdef TCC_TARGET_PE
935 tcc_define_symbol(s, "__WCHAR_TYPE__", "unsigned short");
936 #else
937 tcc_define_symbol(s, "__WCHAR_TYPE__", "int");
938 #endif
940 #ifndef TCC_TARGET_PE
941 /* default library paths */
942 tcc_add_library_path(s, CONFIG_SYSROOT "/usr/local/lib");
943 tcc_add_library_path(s, CONFIG_SYSROOT "/usr/lib");
944 tcc_add_library_path(s, CONFIG_SYSROOT "/lib");
945 #endif
947 /* no section zero */
948 dynarray_add((void ***)&s->sections, &s->nb_sections, NULL);
950 /* create standard sections */
951 text_section = new_section(s, ".text", SHT_PROGBITS, SHF_ALLOC | SHF_EXECINSTR);
952 data_section = new_section(s, ".data", SHT_PROGBITS, SHF_ALLOC | SHF_WRITE);
953 bss_section = new_section(s, ".bss", SHT_NOBITS, SHF_ALLOC | SHF_WRITE);
955 /* symbols are always generated for linking stage */
956 symtab_section = new_symtab(s, ".symtab", SHT_SYMTAB, 0,
957 ".strtab",
958 ".hashtab", SHF_PRIVATE);
959 strtab_section = symtab_section->link;
961 /* private symbol table for dynamic symbols */
962 s->dynsymtab_section = new_symtab(s, ".dynsymtab", SHT_SYMTAB, SHF_PRIVATE,
963 ".dynstrtab",
964 ".dynhashtab", SHF_PRIVATE);
965 s->alacarte_link = 1;
966 s->nocommon = 1;
968 #ifdef CHAR_IS_UNSIGNED
969 s->char_is_unsigned = 1;
970 #endif
971 #if defined(TCC_TARGET_PE) && 0
972 /* XXX: currently the PE linker is not ready to support that */
973 s->leading_underscore = 1;
974 #endif
975 if (s->section_align == 0)
976 s->section_align = ELF_PAGE_SIZE;
977 #ifdef TCC_TARGET_I386
978 s->seg_size = 32;
979 #endif
980 return s;
983 LIBTCCAPI void tcc_delete(TCCState *s1)
985 int i;
987 tcc_cleanup();
989 /* free all sections */
990 for(i = 1; i < s1->nb_sections; i++)
991 free_section(s1->sections[i]);
992 dynarray_reset(&s1->sections, &s1->nb_sections);
994 for(i = 0; i < s1->nb_priv_sections; i++)
995 free_section(s1->priv_sections[i]);
996 dynarray_reset(&s1->priv_sections, &s1->nb_priv_sections);
998 /* free any loaded DLLs */
999 for ( i = 0; i < s1->nb_loaded_dlls; i++) {
1000 DLLReference *ref = s1->loaded_dlls[i];
1001 if ( ref->handle )
1002 dlclose(ref->handle);
1005 /* free loaded dlls array */
1006 dynarray_reset(&s1->loaded_dlls, &s1->nb_loaded_dlls);
1008 /* free library paths */
1009 dynarray_reset(&s1->library_paths, &s1->nb_library_paths);
1011 /* free include paths */
1012 dynarray_reset(&s1->cached_includes, &s1->nb_cached_includes);
1013 dynarray_reset(&s1->include_paths, &s1->nb_include_paths);
1014 dynarray_reset(&s1->sysinclude_paths, &s1->nb_sysinclude_paths);
1016 tcc_free(s1->tcc_lib_path);
1017 tcc_free(s1->runtime_mem);
1018 tcc_free(s1);
1021 LIBTCCAPI int tcc_add_include_path(TCCState *s1, const char *pathname)
1023 char *pathname1;
1025 pathname1 = tcc_strdup(pathname);
1026 dynarray_add((void ***)&s1->include_paths, &s1->nb_include_paths, pathname1);
1027 return 0;
1030 LIBTCCAPI int tcc_add_sysinclude_path(TCCState *s1, const char *pathname)
1032 char *pathname1;
1034 pathname1 = tcc_strdup(pathname);
1035 dynarray_add((void ***)&s1->sysinclude_paths, &s1->nb_sysinclude_paths, pathname1);
1036 return 0;
1039 static int tcc_add_file_internal(TCCState *s1, const char *filename, int flags)
1041 const char *ext;
1042 ElfW(Ehdr) ehdr;
1043 int fd, ret, size;
1044 BufferedFile *saved_file;
1046 ret = -1;
1048 /* find source file type with extension */
1049 ext = tcc_fileextension(filename);
1050 if (ext[0])
1051 ext++;
1053 /* open the file */
1054 saved_file = file;
1055 file = tcc_open(s1, filename);
1056 if (!file) {
1057 if (flags & AFF_PRINT_ERROR)
1058 error_noabort("file '%s' not found", filename);
1059 goto the_end;
1062 if (flags & AFF_PREPROCESS) {
1063 ret = tcc_preprocess(s1);
1064 goto the_end;
1067 if (!ext[0] || !PATHCMP(ext, "c")) {
1068 /* C file assumed */
1069 ret = tcc_compile(s1);
1070 goto the_end;
1073 #ifdef CONFIG_TCC_ASM
1074 if (!strcmp(ext, "S")) {
1075 /* preprocessed assembler */
1076 ret = tcc_assemble(s1, 1);
1077 goto the_end;
1080 if (!strcmp(ext, "s")) {
1081 /* non preprocessed assembler */
1082 ret = tcc_assemble(s1, 0);
1083 goto the_end;
1085 #endif
1087 fd = file->fd;
1088 /* assume executable format: auto guess file type */
1089 size = read(fd, &ehdr, sizeof(ehdr));
1090 lseek(fd, 0, SEEK_SET);
1091 if (size <= 0) {
1092 error_noabort("could not read header");
1093 goto the_end;
1096 if (size == sizeof(ehdr) &&
1097 ehdr.e_ident[0] == ELFMAG0 &&
1098 ehdr.e_ident[1] == ELFMAG1 &&
1099 ehdr.e_ident[2] == ELFMAG2 &&
1100 ehdr.e_ident[3] == ELFMAG3) {
1102 /* do not display line number if error */
1103 file->line_num = 0;
1104 if (ehdr.e_type == ET_REL) {
1105 ret = tcc_load_object_file(s1, fd, 0);
1106 goto the_end;
1109 #ifndef TCC_TARGET_PE
1110 if (ehdr.e_type == ET_DYN) {
1111 if (s1->output_type == TCC_OUTPUT_MEMORY) {
1112 void *h;
1113 h = dlopen(filename, RTLD_GLOBAL | RTLD_LAZY);
1114 if (h)
1115 ret = 0;
1116 } else {
1117 ret = tcc_load_dll(s1, fd, filename,
1118 (flags & AFF_REFERENCED_DLL) != 0);
1120 goto the_end;
1122 #endif
1123 error_noabort("unrecognized ELF file");
1124 goto the_end;
1127 if (memcmp((char *)&ehdr, ARMAG, 8) == 0) {
1128 file->line_num = 0; /* do not display line number if error */
1129 ret = tcc_load_archive(s1, fd);
1130 goto the_end;
1133 #ifdef TCC_TARGET_COFF
1134 if (*(uint16_t *)(&ehdr) == COFF_C67_MAGIC) {
1135 ret = tcc_load_coff(s1, fd);
1136 goto the_end;
1138 #endif
1140 #ifdef TCC_TARGET_PE
1141 ret = pe_load_file(s1, filename, fd);
1142 #else
1143 /* as GNU ld, consider it is an ld script if not recognized */
1144 ret = tcc_load_ldscript(s1);
1145 #endif
1146 if (ret < 0)
1147 error_noabort("unrecognized file type");
1149 the_end:
1150 if (file)
1151 tcc_close(file);
1152 file = saved_file;
1153 return ret;
1156 LIBTCCAPI int tcc_add_file(TCCState *s, const char *filename)
1158 if (s->output_type == TCC_OUTPUT_PREPROCESS)
1159 return tcc_add_file_internal(s, filename, AFF_PRINT_ERROR | AFF_PREPROCESS);
1160 else
1161 return tcc_add_file_internal(s, filename, AFF_PRINT_ERROR);
1164 LIBTCCAPI int tcc_add_library_path(TCCState *s, const char *pathname)
1166 char *pathname1;
1168 pathname1 = tcc_strdup(pathname);
1169 dynarray_add((void ***)&s->library_paths, &s->nb_library_paths, pathname1);
1170 return 0;
1173 /* find and load a dll. Return non zero if not found */
1174 /* XXX: add '-rpath' option support ? */
1175 ST_FUNC int tcc_add_dll(TCCState *s, const char *filename, int flags)
1177 char buf[1024];
1178 int i;
1180 for(i = 0; i < s->nb_library_paths; i++) {
1181 snprintf(buf, sizeof(buf), "%s/%s",
1182 s->library_paths[i], filename);
1183 if (tcc_add_file_internal(s, buf, flags) == 0)
1184 return 0;
1186 return -1;
1189 /* the library name is the same as the argument of the '-l' option */
1190 LIBTCCAPI int tcc_add_library(TCCState *s, const char *libraryname)
1192 char buf[1024];
1193 int i;
1195 /* first we look for the dynamic library if not static linking */
1196 if (!s->static_link) {
1197 #ifdef TCC_TARGET_PE
1198 if (pe_add_dll(s, libraryname) == 0)
1199 return 0;
1200 #else
1201 snprintf(buf, sizeof(buf), "lib%s.so", libraryname);
1202 if (tcc_add_dll(s, buf, 0) == 0)
1203 return 0;
1204 #endif
1206 /* then we look for the static library */
1207 for(i = 0; i < s->nb_library_paths; i++) {
1208 snprintf(buf, sizeof(buf), "%s/lib%s.a",
1209 s->library_paths[i], libraryname);
1210 if (tcc_add_file_internal(s, buf, 0) == 0)
1211 return 0;
1213 return -1;
1216 LIBTCCAPI int tcc_add_symbol(TCCState *s, const char *name, void *val)
1218 #ifdef TCC_TARGET_PE
1219 pe_putimport(s, 0, name, val);
1220 #else
1221 add_elf_sym(symtab_section, (uplong)val, 0,
1222 ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE), 0,
1223 SHN_ABS, name);
1224 #endif
1225 return 0;
1228 LIBTCCAPI int tcc_set_output_type(TCCState *s, int output_type)
1230 char buf[1024];
1232 s->output_type = output_type;
1234 if (!s->nostdinc) {
1235 /* default include paths */
1236 /* XXX: reverse order needed if -isystem support */
1237 #ifndef TCC_TARGET_PE
1238 tcc_add_sysinclude_path(s, CONFIG_SYSROOT "/usr/local/include");
1239 tcc_add_sysinclude_path(s, CONFIG_SYSROOT "/usr/include");
1240 #endif
1241 snprintf(buf, sizeof(buf), "%s/include", s->tcc_lib_path);
1242 tcc_add_sysinclude_path(s, buf);
1243 #ifdef TCC_TARGET_PE
1244 snprintf(buf, sizeof(buf), "%s/include/winapi", s->tcc_lib_path);
1245 tcc_add_sysinclude_path(s, buf);
1246 #endif
1249 /* if bound checking, then add corresponding sections */
1250 #ifdef CONFIG_TCC_BCHECK
1251 if (s->do_bounds_check) {
1252 /* define symbol */
1253 tcc_define_symbol(s, "__BOUNDS_CHECKING_ON", NULL);
1254 /* create bounds sections */
1255 bounds_section = new_section(s, ".bounds",
1256 SHT_PROGBITS, SHF_ALLOC);
1257 lbounds_section = new_section(s, ".lbounds",
1258 SHT_PROGBITS, SHF_ALLOC);
1260 #endif
1262 if (s->char_is_unsigned) {
1263 tcc_define_symbol(s, "__CHAR_UNSIGNED__", NULL);
1266 /* add debug sections */
1267 if (s->do_debug) {
1268 /* stab symbols */
1269 stab_section = new_section(s, ".stab", SHT_PROGBITS, 0);
1270 stab_section->sh_entsize = sizeof(Stab_Sym);
1271 stabstr_section = new_section(s, ".stabstr", SHT_STRTAB, 0);
1272 put_elf_str(stabstr_section, "");
1273 stab_section->link = stabstr_section;
1274 /* put first entry */
1275 put_stabs("", 0, 0, 0, 0);
1278 /* add libc crt1/crti objects */
1279 #ifndef TCC_TARGET_PE
1280 if ((output_type == TCC_OUTPUT_EXE || output_type == TCC_OUTPUT_DLL) &&
1281 !s->nostdlib) {
1282 if (output_type != TCC_OUTPUT_DLL)
1283 tcc_add_file(s, CONFIG_TCC_CRT_PREFIX "/crt1.o");
1284 tcc_add_file(s, CONFIG_TCC_CRT_PREFIX "/crti.o");
1286 #endif
1288 #ifdef TCC_TARGET_PE
1289 snprintf(buf, sizeof(buf), "%s/lib", s->tcc_lib_path);
1290 tcc_add_library_path(s, buf);
1291 #ifdef _WIN32
1292 if (GetSystemDirectory(buf, sizeof buf))
1293 tcc_add_library_path(s, buf);
1294 #endif
1295 #endif
1297 return 0;
1300 #define WD_ALL 0x0001 /* warning is activated when using -Wall */
1301 #define FD_INVERT 0x0002 /* invert value before storing */
1303 typedef struct FlagDef {
1304 uint16_t offset;
1305 uint16_t flags;
1306 const char *name;
1307 } FlagDef;
1309 static const FlagDef warning_defs[] = {
1310 { offsetof(TCCState, warn_unsupported), 0, "unsupported" },
1311 { offsetof(TCCState, warn_write_strings), 0, "write-strings" },
1312 { offsetof(TCCState, warn_error), 0, "error" },
1313 { offsetof(TCCState, warn_implicit_function_declaration), WD_ALL,
1314 "implicit-function-declaration" },
1317 ST_FUNC int set_flag(TCCState *s, const FlagDef *flags, int nb_flags,
1318 const char *name, int value)
1320 int i;
1321 const FlagDef *p;
1322 const char *r;
1324 r = name;
1325 if (r[0] == 'n' && r[1] == 'o' && r[2] == '-') {
1326 r += 3;
1327 value = !value;
1329 for(i = 0, p = flags; i < nb_flags; i++, p++) {
1330 if (!strcmp(r, p->name))
1331 goto found;
1333 return -1;
1334 found:
1335 if (p->flags & FD_INVERT)
1336 value = !value;
1337 *(int *)((uint8_t *)s + p->offset) = value;
1338 return 0;
1341 /* set/reset a warning */
1342 LIBTCCAPI int tcc_set_warning(TCCState *s, const char *warning_name, int value)
1344 int i;
1345 const FlagDef *p;
1347 if (!strcmp(warning_name, "all")) {
1348 for(i = 0, p = warning_defs; i < countof(warning_defs); i++, p++) {
1349 if (p->flags & WD_ALL)
1350 *(int *)((uint8_t *)s + p->offset) = 1;
1352 return 0;
1353 } else {
1354 return set_flag(s, warning_defs, countof(warning_defs),
1355 warning_name, value);
1359 static const FlagDef flag_defs[] = {
1360 { offsetof(TCCState, char_is_unsigned), 0, "unsigned-char" },
1361 { offsetof(TCCState, char_is_unsigned), FD_INVERT, "signed-char" },
1362 { offsetof(TCCState, nocommon), FD_INVERT, "common" },
1363 { offsetof(TCCState, leading_underscore), 0, "leading-underscore" },
1366 /* set/reset a flag */
1367 PUB_FUNC int tcc_set_flag(TCCState *s, const char *flag_name, int value)
1369 return set_flag(s, flag_defs, countof(flag_defs),
1370 flag_name, value);
1373 PUB_FUNC void tcc_print_stats(TCCState *s, int64_t total_time)
1375 double tt;
1376 tt = (double)total_time / 1000000.0;
1377 if (tt < 0.001)
1378 tt = 0.001;
1379 if (total_bytes < 1)
1380 total_bytes = 1;
1381 printf("%d idents, %d lines, %d bytes, %0.3f s, %d lines/s, %0.1f MB/s\n",
1382 tok_ident - TOK_IDENT, total_lines, total_bytes,
1383 tt, (int)(total_lines / tt),
1384 total_bytes / tt / 1000000.0);
1387 /* set CONFIG_TCCDIR at runtime */
1388 LIBTCCAPI void tcc_set_lib_path(TCCState *s, const char *path)
1390 tcc_free(s->tcc_lib_path);
1391 s->tcc_lib_path = tcc_strdup(path);
1394 PUB_FUNC void set_num_callers(int n)
1396 #ifdef CONFIG_TCC_BACKTRACE
1397 num_callers = n;
1398 #endif