Avoid crash with "Avoid a crash with weak symbols for "make test""
[tinycc.git] / libtcc.c
blob2575a051f29ab8d85cc1d879c003945da999427d
1 /*
2 * TCC - Tiny C Compiler
3 *
4 * Copyright (c) 2001-2004 Fabrice Bellard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 #include "tcc.h"
23 /********************************************************/
24 /* global variables */
26 /* use GNU C extensions */
27 ST_DATA int gnu_ext = 1;
29 /* use TinyCC extensions */
30 ST_DATA int tcc_ext = 1;
32 /* XXX: get rid of this ASAP */
33 ST_DATA struct TCCState *tcc_state;
35 #ifdef CONFIG_TCC_BACKTRACE
36 ST_DATA int num_callers = 6;
37 ST_DATA const char **rt_bound_error_msg;
38 ST_DATA void *rt_prog_main;
39 #endif
41 /********************************************************/
43 #ifndef NOTALLINONE
44 #include "tccpp.c"
45 #include "tccgen.c"
46 #include "tccelf.c"
47 #include "tccrun.c"
48 #ifdef TCC_TARGET_I386
49 #include "i386-gen.c"
50 #endif
51 #ifdef TCC_TARGET_ARM
52 #include "arm-gen.c"
53 #endif
54 #ifdef TCC_TARGET_C67
55 #include "c67-gen.c"
56 #endif
57 #ifdef TCC_TARGET_X86_64
58 #include "x86_64-gen.c"
59 #endif
60 #ifdef CONFIG_TCC_ASM
61 #include "tccasm.c"
62 #if defined TCC_TARGET_I386 || defined TCC_TARGET_X86_64
63 #include "i386-asm.c"
64 #endif
65 #endif
66 #ifdef TCC_TARGET_COFF
67 #include "tcccoff.c"
68 #endif
69 #ifdef TCC_TARGET_PE
70 #include "tccpe.c"
71 #endif
72 #endif /* ALL_IN_ONE */
74 /********************************************************/
75 #ifndef CONFIG_TCC_ASM
76 ST_FUNC void asm_instr(void)
78 error("inline asm() not supported");
80 ST_FUNC void asm_global_instr(void)
82 error("inline asm() not supported");
84 #endif
86 /********************************************************/
88 #ifdef _WIN32
89 static char *normalize_slashes(char *path)
91 char *p;
92 for (p = path; *p; ++p)
93 if (*p == '\\')
94 *p = '/';
95 return path;
98 static HMODULE tcc_module;
100 /* on win32, we suppose the lib and includes are at the location of 'tcc.exe' */
101 static void tcc_set_lib_path_w32(TCCState *s)
103 char path[1024], *p;
104 GetModuleFileNameA(tcc_module, path, sizeof path);
105 p = tcc_basename(normalize_slashes(strlwr(path)));
106 if (p - 5 > path && 0 == strncmp(p - 5, "/bin/", 5))
107 p -= 5;
108 else if (p > path)
109 p--;
110 *p = 0;
111 tcc_set_lib_path(s, path);
114 #ifndef CONFIG_TCC_STATIC
115 void dlclose(void *p)
117 FreeLibrary((HMODULE)p);
119 #endif
121 #ifdef LIBTCC_AS_DLL
122 BOOL WINAPI DllMain (HANDLE hDll, DWORD dwReason, LPVOID lpReserved)
124 if (DLL_PROCESS_ATTACH == dwReason)
125 tcc_module = hDll;
126 return TRUE;
128 #endif
129 #endif
131 /********************************************************/
132 /* copy a string and truncate it. */
133 PUB_FUNC char *pstrcpy(char *buf, int buf_size, const char *s)
135 char *q, *q_end;
136 int c;
138 if (buf_size > 0) {
139 q = buf;
140 q_end = buf + buf_size - 1;
141 while (q < q_end) {
142 c = *s++;
143 if (c == '\0')
144 break;
145 *q++ = c;
147 *q = '\0';
149 return buf;
152 /* strcat and truncate. */
153 PUB_FUNC char *pstrcat(char *buf, int buf_size, const char *s)
155 int len;
156 len = strlen(buf);
157 if (len < buf_size)
158 pstrcpy(buf + len, buf_size - len, s);
159 return buf;
162 /* extract the basename of a file */
163 PUB_FUNC char *tcc_basename(const char *name)
165 char *p = strchr(name, 0);
166 while (p > name && !IS_PATHSEP(p[-1]))
167 --p;
168 return p;
171 /* extract extension part of a file
173 * (if no extension, return pointer to end-of-string)
175 PUB_FUNC char *tcc_fileextension (const char *name)
177 char *b = tcc_basename(name);
178 char *e = strrchr(b, '.');
179 return e ? e : strchr(b, 0);
182 /********************************************************/
183 /* memory management */
185 #undef free
186 #undef malloc
187 #undef realloc
189 #ifdef MEM_DEBUG
190 int mem_cur_size;
191 int mem_max_size;
192 unsigned malloc_usable_size(void*);
193 #endif
195 PUB_FUNC void tcc_free(void *ptr)
197 #ifdef MEM_DEBUG
198 mem_cur_size -= malloc_usable_size(ptr);
199 #endif
200 free(ptr);
203 PUB_FUNC void *tcc_malloc(unsigned long size)
205 void *ptr;
206 ptr = malloc(size);
207 if (!ptr && size)
208 error("memory full");
209 #ifdef MEM_DEBUG
210 mem_cur_size += malloc_usable_size(ptr);
211 if (mem_cur_size > mem_max_size)
212 mem_max_size = mem_cur_size;
213 #endif
214 return ptr;
217 PUB_FUNC void *tcc_mallocz(unsigned long size)
219 void *ptr;
220 ptr = tcc_malloc(size);
221 memset(ptr, 0, size);
222 return ptr;
225 PUB_FUNC void *tcc_realloc(void *ptr, unsigned long size)
227 void *ptr1;
228 #ifdef MEM_DEBUG
229 mem_cur_size -= malloc_usable_size(ptr);
230 #endif
231 ptr1 = realloc(ptr, size);
232 #ifdef MEM_DEBUG
233 /* NOTE: count not correct if alloc error, but not critical */
234 mem_cur_size += malloc_usable_size(ptr1);
235 if (mem_cur_size > mem_max_size)
236 mem_max_size = mem_cur_size;
237 #endif
238 return ptr1;
241 PUB_FUNC char *tcc_strdup(const char *str)
243 char *ptr;
244 ptr = tcc_malloc(strlen(str) + 1);
245 strcpy(ptr, str);
246 return ptr;
249 PUB_FUNC void tcc_memstats(void)
251 #ifdef MEM_DEBUG
252 printf("memory in use: %d\n", mem_cur_size);
253 #endif
256 #define free(p) use_tcc_free(p)
257 #define malloc(s) use_tcc_malloc(s)
258 #define realloc(p, s) use_tcc_realloc(p, s)
260 /********************************************************/
261 /* dynarrays */
263 PUB_FUNC void dynarray_add(void ***ptab, int *nb_ptr, void *data)
265 int nb, nb_alloc;
266 void **pp;
268 nb = *nb_ptr;
269 pp = *ptab;
270 /* every power of two we double array size */
271 if ((nb & (nb - 1)) == 0) {
272 if (!nb)
273 nb_alloc = 1;
274 else
275 nb_alloc = nb * 2;
276 pp = tcc_realloc(pp, nb_alloc * sizeof(void *));
277 if (!pp)
278 error("memory full");
279 *ptab = pp;
281 pp[nb++] = data;
282 *nb_ptr = nb;
285 PUB_FUNC void dynarray_reset(void *pp, int *n)
287 void **p;
288 for (p = *(void***)pp; *n; ++p, --*n)
289 if (*p)
290 tcc_free(*p);
291 tcc_free(*(void**)pp);
292 *(void**)pp = NULL;
295 /* we use our own 'finite' function to avoid potential problems with
296 non standard math libs */
297 /* XXX: endianness dependent */
298 ST_FUNC int ieee_finite(double d)
300 int *p = (int *)&d;
301 return ((unsigned)((p[1] | 0x800fffff) + 1)) >> 31;
304 /********************************************************/
306 ST_FUNC Section *new_section(TCCState *s1, const char *name, int sh_type, int sh_flags)
308 Section *sec;
310 sec = tcc_mallocz(sizeof(Section) + strlen(name));
311 strcpy(sec->name, name);
312 sec->sh_type = sh_type;
313 sec->sh_flags = sh_flags;
314 switch(sh_type) {
315 case SHT_HASH:
316 case SHT_REL:
317 case SHT_RELA:
318 case SHT_DYNSYM:
319 case SHT_SYMTAB:
320 case SHT_DYNAMIC:
321 sec->sh_addralign = 4;
322 break;
323 case SHT_STRTAB:
324 sec->sh_addralign = 1;
325 break;
326 default:
327 sec->sh_addralign = 32; /* default conservative alignment */
328 break;
331 if (sh_flags & SHF_PRIVATE) {
332 dynarray_add((void ***)&s1->priv_sections, &s1->nb_priv_sections, sec);
333 } else {
334 sec->sh_num = s1->nb_sections;
335 dynarray_add((void ***)&s1->sections, &s1->nb_sections, sec);
338 return sec;
341 static void free_section(Section *s)
343 tcc_free(s->data);
346 /* realloc section and set its content to zero */
347 ST_FUNC void section_realloc(Section *sec, unsigned long new_size)
349 unsigned long size;
350 unsigned char *data;
352 size = sec->data_allocated;
353 if (size == 0)
354 size = 1;
355 while (size < new_size)
356 size = size * 2;
357 data = tcc_realloc(sec->data, size);
358 if (!data)
359 error("memory full");
360 memset(data + sec->data_allocated, 0, size - sec->data_allocated);
361 sec->data = data;
362 sec->data_allocated = size;
365 /* reserve at least 'size' bytes in section 'sec' from
366 sec->data_offset. */
367 ST_FUNC void *section_ptr_add(Section *sec, unsigned long size)
369 unsigned long offset, offset1;
371 offset = sec->data_offset;
372 offset1 = offset + size;
373 if (offset1 > sec->data_allocated)
374 section_realloc(sec, offset1);
375 sec->data_offset = offset1;
376 return sec->data + offset;
379 /* reserve at least 'size' bytes from section start */
380 ST_FUNC void section_reserve(Section *sec, unsigned long size)
382 if (size > sec->data_allocated)
383 section_realloc(sec, size);
384 if (size > sec->data_offset)
385 sec->data_offset = size;
388 /* return a reference to a section, and create it if it does not
389 exists */
390 ST_FUNC Section *find_section(TCCState *s1, const char *name)
392 Section *sec;
393 int i;
394 for(i = 1; i < s1->nb_sections; i++) {
395 sec = s1->sections[i];
396 if (!strcmp(name, sec->name))
397 return sec;
399 /* sections are created as PROGBITS */
400 return new_section(s1, name, SHT_PROGBITS, SHF_ALLOC);
403 /* update sym->c so that it points to an external symbol in section
404 'section' with value 'value' */
405 ST_FUNC void put_extern_sym2(Sym *sym, Section *section,
406 unsigned long value, unsigned long size,
407 int can_add_underscore)
409 int sym_type, sym_bind, sh_num, info, other;
410 ElfW(Sym) *esym;
411 const char *name;
412 char buf1[256];
414 if (section == NULL)
415 sh_num = SHN_UNDEF;
416 else if (section == SECTION_ABS)
417 sh_num = SHN_ABS;
418 else
419 sh_num = section->sh_num;
421 if ((sym->type.t & VT_BTYPE) == VT_FUNC) {
422 sym_type = STT_FUNC;
423 } else if ((sym->type.t & VT_BTYPE) == VT_VOID) {
424 sym_type = STT_NOTYPE;
425 } else {
426 sym_type = STT_OBJECT;
429 if (sym->type.t & VT_STATIC)
430 sym_bind = STB_LOCAL;
431 else {
432 if (sym_type == STT_FUNC && sym->type.ref && FUNC_WEAK(sym->type.ref->r))
433 sym_bind = STB_WEAK;
434 else
435 sym_bind = STB_GLOBAL;
438 if (!sym->c) {
439 name = get_tok_str(sym->v, NULL);
440 #ifdef CONFIG_TCC_BCHECK
441 if (tcc_state->do_bounds_check) {
442 char buf[32];
444 /* XXX: avoid doing that for statics ? */
445 /* if bound checking is activated, we change some function
446 names by adding the "__bound" prefix */
447 switch(sym->v) {
448 #ifdef TCC_TARGET_PE
449 /* XXX: we rely only on malloc hooks */
450 case TOK_malloc:
451 case TOK_free:
452 case TOK_realloc:
453 case TOK_memalign:
454 case TOK_calloc:
455 #endif
456 case TOK_memcpy:
457 case TOK_memmove:
458 case TOK_memset:
459 case TOK_strlen:
460 case TOK_strcpy:
461 case TOK_alloca:
462 strcpy(buf, "__bound_");
463 strcat(buf, name);
464 name = buf;
465 break;
468 #endif
469 other = 0;
471 #ifdef TCC_TARGET_PE
472 if (sym->type.t & VT_EXPORT)
473 other |= 1;
474 if (sym_type == STT_FUNC && sym->type.ref) {
475 int attr = sym->type.ref->r;
476 if (FUNC_EXPORT(attr))
477 other |= 1;
478 if (FUNC_CALL(attr) == FUNC_STDCALL && can_add_underscore) {
479 sprintf(buf1, "_%s@%d", name, FUNC_ARGS(attr) * PTR_SIZE);
480 name = buf1;
481 other |= 2;
482 can_add_underscore = 0;
484 } else {
485 if (find_elf_sym(tcc_state->dynsymtab_section, name))
486 other |= 4;
487 if (sym->type.t & VT_IMPORT)
488 other |= 4;
490 #endif
491 if (tcc_state->leading_underscore && can_add_underscore) {
492 buf1[0] = '_';
493 pstrcpy(buf1 + 1, sizeof(buf1) - 1, name);
494 name = buf1;
496 info = ELFW(ST_INFO)(sym_bind, sym_type);
497 sym->c = add_elf_sym(symtab_section, value, size, info, other, sh_num, name);
498 } else {
499 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
500 esym->st_value = value;
501 esym->st_size = size;
502 esym->st_shndx = sh_num;
506 ST_FUNC void put_extern_sym(Sym *sym, Section *section,
507 unsigned long value, unsigned long size)
509 put_extern_sym2(sym, section, value, size, 1);
512 /* add a new relocation entry to symbol 'sym' in section 's' */
513 ST_FUNC void greloc(Section *s, Sym *sym, unsigned long offset, int type)
515 int c = 0;
516 if (sym) {
517 if (0 == sym->c)
518 put_extern_sym(sym, NULL, 0, 0);
519 c = sym->c;
521 /* now we can add ELF relocation info */
522 put_elf_reloc(symtab_section, s, offset, type, c);
525 /********************************************************/
527 static void strcat_vprintf(char *buf, int buf_size, const char *fmt, va_list ap)
529 int len;
530 len = strlen(buf);
531 vsnprintf(buf + len, buf_size - len, fmt, ap);
534 static void strcat_printf(char *buf, int buf_size, const char *fmt, ...)
536 va_list ap;
537 va_start(ap, fmt);
538 strcat_vprintf(buf, buf_size, fmt, ap);
539 va_end(ap);
542 static void error1(TCCState *s1, int is_warning, const char *fmt, va_list ap)
544 char buf[2048];
545 BufferedFile **f;
547 buf[0] = '\0';
548 if (file) {
549 for(f = s1->include_stack; f < s1->include_stack_ptr; f++)
550 strcat_printf(buf, sizeof(buf), "In file included from %s:%d:\n",
551 (*f)->filename, (*f)->line_num);
552 if (file->line_num > 0) {
553 strcat_printf(buf, sizeof(buf),
554 "%s:%d: ", file->filename, file->line_num);
555 } else {
556 strcat_printf(buf, sizeof(buf),
557 "%s: ", file->filename);
559 } else {
560 strcat_printf(buf, sizeof(buf),
561 "tcc: ");
563 if (is_warning)
564 strcat_printf(buf, sizeof(buf), "warning: ");
565 else
566 strcat_printf(buf, sizeof(buf), "error: ");
567 strcat_vprintf(buf, sizeof(buf), fmt, ap);
569 if (!s1->error_func) {
570 /* default case: stderr */
571 fprintf(stderr, "%s\n", buf);
572 } else {
573 s1->error_func(s1->error_opaque, buf);
575 if (!is_warning || s1->warn_error)
576 s1->nb_errors++;
579 LIBTCCAPI void tcc_set_error_func(TCCState *s, void *error_opaque,
580 void (*error_func)(void *opaque, const char *msg))
582 s->error_opaque = error_opaque;
583 s->error_func = error_func;
586 /* error without aborting current compilation */
587 PUB_FUNC void error_noabort(const char *fmt, ...)
589 TCCState *s1 = tcc_state;
590 va_list ap;
592 va_start(ap, fmt);
593 error1(s1, 0, fmt, ap);
594 va_end(ap);
597 PUB_FUNC void error(const char *fmt, ...)
599 TCCState *s1 = tcc_state;
600 va_list ap;
602 va_start(ap, fmt);
603 error1(s1, 0, fmt, ap);
604 va_end(ap);
605 /* better than nothing: in some cases, we accept to handle errors */
606 if (s1->error_set_jmp_enabled) {
607 longjmp(s1->error_jmp_buf, 1);
608 } else {
609 /* XXX: eliminate this someday */
610 exit(1);
614 PUB_FUNC void expect(const char *msg)
616 error("%s expected", msg);
619 PUB_FUNC void warning(const char *fmt, ...)
621 TCCState *s1 = tcc_state;
622 va_list ap;
624 if (s1->warn_none)
625 return;
627 va_start(ap, fmt);
628 error1(s1, 1, fmt, ap);
629 va_end(ap);
632 /********************************************************/
633 /* I/O layer */
635 ST_FUNC BufferedFile *tcc_open(TCCState *s1, const char *filename)
637 int fd;
638 BufferedFile *bf;
640 if (strcmp(filename, "-") == 0)
641 fd = 0, filename = "stdin";
642 else
643 fd = open(filename, O_RDONLY | O_BINARY);
644 if ((s1->verbose == 2 && fd >= 0) || s1->verbose == 3)
645 printf("%s %*s%s\n", fd < 0 ? "nf":"->",
646 (int)(s1->include_stack_ptr - s1->include_stack), "", filename);
647 if (fd < 0)
648 return NULL;
649 bf = tcc_malloc(sizeof(BufferedFile));
650 bf->fd = fd;
651 bf->buf_ptr = bf->buffer;
652 bf->buf_end = bf->buffer;
653 bf->buffer[0] = CH_EOB; /* put eob symbol */
654 pstrcpy(bf->filename, sizeof(bf->filename), filename);
655 #ifdef _WIN32
656 normalize_slashes(bf->filename);
657 #endif
658 bf->line_num = 1;
659 bf->ifndef_macro = 0;
660 bf->ifdef_stack_ptr = s1->ifdef_stack_ptr;
661 // printf("opening '%s'\n", filename);
662 return bf;
665 ST_FUNC void tcc_close(BufferedFile *bf)
667 total_lines += bf->line_num;
668 close(bf->fd);
669 tcc_free(bf);
672 /* compile the C file opened in 'file'. Return non zero if errors. */
673 static int tcc_compile(TCCState *s1)
675 Sym *define_start;
676 char buf[512];
677 volatile int section_sym;
679 #ifdef INC_DEBUG
680 printf("%s: **** new file\n", file->filename);
681 #endif
682 preprocess_init(s1);
684 cur_text_section = NULL;
685 funcname = "";
686 anon_sym = SYM_FIRST_ANOM;
688 /* file info: full path + filename */
689 section_sym = 0; /* avoid warning */
690 if (s1->do_debug) {
691 section_sym = put_elf_sym(symtab_section, 0, 0,
692 ELFW(ST_INFO)(STB_LOCAL, STT_SECTION), 0,
693 text_section->sh_num, NULL);
694 getcwd(buf, sizeof(buf));
695 #ifdef _WIN32
696 normalize_slashes(buf);
697 #endif
698 pstrcat(buf, sizeof(buf), "/");
699 put_stabs_r(buf, N_SO, 0, 0,
700 text_section->data_offset, text_section, section_sym);
701 put_stabs_r(file->filename, N_SO, 0, 0,
702 text_section->data_offset, text_section, section_sym);
704 /* an elf symbol of type STT_FILE must be put so that STB_LOCAL
705 symbols can be safely used */
706 put_elf_sym(symtab_section, 0, 0,
707 ELFW(ST_INFO)(STB_LOCAL, STT_FILE), 0,
708 SHN_ABS, file->filename);
710 /* define some often used types */
711 int_type.t = VT_INT;
713 char_pointer_type.t = VT_BYTE;
714 mk_pointer(&char_pointer_type);
716 func_old_type.t = VT_FUNC;
717 func_old_type.ref = sym_push(SYM_FIELD, &int_type, FUNC_CDECL, FUNC_OLD);
719 #if defined(TCC_ARM_EABI) && defined(TCC_ARM_VFP)
720 float_type.t = VT_FLOAT;
721 double_type.t = VT_DOUBLE;
723 func_float_type.t = VT_FUNC;
724 func_float_type.ref = sym_push(SYM_FIELD, &float_type, FUNC_CDECL, FUNC_OLD);
725 func_double_type.t = VT_FUNC;
726 func_double_type.ref = sym_push(SYM_FIELD, &double_type, FUNC_CDECL, FUNC_OLD);
727 #endif
729 #if 0
730 /* define 'void *alloca(unsigned int)' builtin function */
732 Sym *s1;
734 p = anon_sym++;
735 sym = sym_push(p, mk_pointer(VT_VOID), FUNC_CDECL, FUNC_NEW);
736 s1 = sym_push(SYM_FIELD, VT_UNSIGNED | VT_INT, 0, 0);
737 s1->next = NULL;
738 sym->next = s1;
739 sym_push(TOK_alloca, VT_FUNC | (p << VT_STRUCT_SHIFT), VT_CONST, 0);
741 #endif
743 define_start = define_stack;
744 nocode_wanted = 1;
746 if (setjmp(s1->error_jmp_buf) == 0) {
747 s1->nb_errors = 0;
748 s1->error_set_jmp_enabled = 1;
750 ch = file->buf_ptr[0];
751 tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
752 parse_flags = PARSE_FLAG_PREPROCESS | PARSE_FLAG_TOK_NUM;
753 next();
754 decl(VT_CONST);
755 if (tok != TOK_EOF)
756 expect("declaration");
758 /* end of translation unit info */
759 if (s1->do_debug) {
760 put_stabs_r(NULL, N_SO, 0, 0,
761 text_section->data_offset, text_section, section_sym);
764 s1->error_set_jmp_enabled = 0;
766 /* reset define stack, but leave -Dsymbols (may be incorrect if
767 they are undefined) */
768 free_defines(define_start);
770 gen_inline_functions();
772 sym_pop(&global_stack, NULL);
773 sym_pop(&local_stack, NULL);
775 return s1->nb_errors != 0 ? -1 : 0;
778 LIBTCCAPI int tcc_compile_string(TCCState *s, const char *str)
780 BufferedFile bf1, *bf = &bf1;
781 int ret, len;
782 char *buf;
784 /* init file structure */
785 bf->fd = -1;
786 /* XXX: avoid copying */
787 len = strlen(str);
788 buf = tcc_malloc(len + 1);
789 if (!buf)
790 return -1;
791 memcpy(buf, str, len);
792 buf[len] = CH_EOB;
793 bf->buf_ptr = buf;
794 bf->buf_end = buf + len;
795 pstrcpy(bf->filename, sizeof(bf->filename), "<string>");
796 bf->line_num = 1;
797 file = bf;
798 ret = tcc_compile(s);
799 file = NULL;
800 tcc_free(buf);
802 /* currently, no need to close */
803 return ret;
806 /* define a preprocessor symbol. A value can also be provided with the '=' operator */
807 LIBTCCAPI void tcc_define_symbol(TCCState *s1, const char *sym, const char *value)
809 BufferedFile bf1, *bf = &bf1;
811 pstrcpy(bf->buffer, IO_BUF_SIZE, sym);
812 pstrcat(bf->buffer, IO_BUF_SIZE, " ");
813 /* default value */
814 if (!value)
815 value = "1";
816 pstrcat(bf->buffer, IO_BUF_SIZE, value);
818 /* init file structure */
819 bf->fd = -1;
820 bf->buf_ptr = bf->buffer;
821 bf->buf_end = bf->buffer + strlen(bf->buffer);
822 *bf->buf_end = CH_EOB;
823 bf->filename[0] = '\0';
824 bf->line_num = 1;
825 file = bf;
827 s1->include_stack_ptr = s1->include_stack;
829 /* parse with define parser */
830 ch = file->buf_ptr[0];
831 next_nomacro();
832 parse_define();
833 file = NULL;
836 /* undefine a preprocessor symbol */
837 LIBTCCAPI void tcc_undefine_symbol(TCCState *s1, const char *sym)
839 TokenSym *ts;
840 Sym *s;
841 ts = tok_alloc(sym, strlen(sym));
842 s = define_find(ts->tok);
843 /* undefine symbol by putting an invalid name */
844 if (s)
845 define_undef(s);
848 static void tcc_cleanup(void)
850 int i, n;
852 if (NULL == tcc_state)
853 return;
854 tcc_state = NULL;
856 /* free -D defines */
857 free_defines(NULL);
859 /* free tokens */
860 n = tok_ident - TOK_IDENT;
861 for(i = 0; i < n; i++)
862 tcc_free(table_ident[i]);
863 tcc_free(table_ident);
865 /* free sym_pools */
866 dynarray_reset(&sym_pools, &nb_sym_pools);
867 /* string buffer */
868 cstr_free(&tokcstr);
869 /* reset symbol stack */
870 sym_free_first = NULL;
871 /* cleanup from error/setjmp */
872 macro_ptr = NULL;
875 LIBTCCAPI TCCState *tcc_new(void)
877 TCCState *s;
878 char buffer[100];
879 int a,b,c;
881 tcc_cleanup();
883 s = tcc_mallocz(sizeof(TCCState));
884 if (!s)
885 return NULL;
886 tcc_state = s;
887 #ifdef _WIN32
888 tcc_set_lib_path_w32(s);
889 #else
890 tcc_set_lib_path(s, CONFIG_TCCDIR);
891 #endif
892 s->output_type = TCC_OUTPUT_MEMORY;
893 preprocess_new();
895 /* we add dummy defines for some special macros to speed up tests
896 and to have working defined() */
897 define_push(TOK___LINE__, MACRO_OBJ, NULL, NULL);
898 define_push(TOK___FILE__, MACRO_OBJ, NULL, NULL);
899 define_push(TOK___DATE__, MACRO_OBJ, NULL, NULL);
900 define_push(TOK___TIME__, MACRO_OBJ, NULL, NULL);
902 /* standard defines */
903 tcc_define_symbol(s, "__STDC__", NULL);
904 tcc_define_symbol(s, "__STDC_VERSION__", "199901L");
905 #if defined(TCC_TARGET_I386)
906 tcc_define_symbol(s, "__i386__", NULL);
907 tcc_define_symbol(s, "__i386", NULL);
908 tcc_define_symbol(s, "i386", NULL);
909 #endif
910 #if defined(TCC_TARGET_X86_64)
911 tcc_define_symbol(s, "__x86_64__", NULL);
912 #endif
913 #if defined(TCC_TARGET_ARM)
914 tcc_define_symbol(s, "__ARM_ARCH_4__", NULL);
915 tcc_define_symbol(s, "__arm_elf__", NULL);
916 tcc_define_symbol(s, "__arm_elf", NULL);
917 tcc_define_symbol(s, "arm_elf", NULL);
918 tcc_define_symbol(s, "__arm__", NULL);
919 tcc_define_symbol(s, "__arm", NULL);
920 tcc_define_symbol(s, "arm", NULL);
921 tcc_define_symbol(s, "__APCS_32__", NULL);
922 #endif
923 #ifdef TCC_TARGET_PE
924 tcc_define_symbol(s, "_WIN32", NULL);
925 #ifdef TCC_TARGET_X86_64
926 tcc_define_symbol(s, "_WIN64", NULL);
927 #endif
928 #else
929 tcc_define_symbol(s, "__unix__", NULL);
930 tcc_define_symbol(s, "__unix", NULL);
931 tcc_define_symbol(s, "unix", NULL);
932 #if defined(__FreeBSD__)
933 #define str(s) #s
934 tcc_define_symbol(s, "__FreeBSD__", str( __FreeBSD__));
935 #undef str
936 #endif
937 #if defined(__linux)
938 tcc_define_symbol(s, "__linux__", NULL);
939 tcc_define_symbol(s, "__linux", NULL);
940 #endif
941 #endif
942 /* tiny C specific defines */
943 sscanf(TCC_VERSION, "%d.%d.%d", &a, &b, &c);
944 sprintf(buffer, "%d", a*10000 + b*100 + c);
945 tcc_define_symbol(s, "__TINYC__", buffer);
947 /* tiny C & gcc defines */
948 #if defined TCC_TARGET_PE && defined TCC_TARGET_X86_64
949 tcc_define_symbol(s, "__SIZE_TYPE__", "unsigned long long");
950 tcc_define_symbol(s, "__PTRDIFF_TYPE__", "long long");
951 #else
952 tcc_define_symbol(s, "__SIZE_TYPE__", "unsigned long");
953 tcc_define_symbol(s, "__PTRDIFF_TYPE__", "long");
954 #endif
956 #ifdef TCC_TARGET_PE
957 tcc_define_symbol(s, "__WCHAR_TYPE__", "unsigned short");
958 #else
959 tcc_define_symbol(s, "__WCHAR_TYPE__", "int");
960 #endif
962 #ifndef TCC_TARGET_PE
963 /* default library paths */
964 # if defined(TCC_TARGET_X86_64_CENTOS)
965 tcc_add_library_path(s, CONFIG_SYSROOT "/usr/lib64");
966 tcc_add_library_path(s, CONFIG_SYSROOT "/lib64");
967 tcc_add_library_path(s, CONFIG_SYSROOT "/usr/local/lib64");
968 # else
969 tcc_add_library_path(s, CONFIG_SYSROOT "/usr/lib");
970 tcc_add_library_path(s, CONFIG_SYSROOT "/lib");
971 tcc_add_library_path(s, CONFIG_SYSROOT "/usr/local/lib");
972 # endif
973 #endif
975 /* no section zero */
976 dynarray_add((void ***)&s->sections, &s->nb_sections, NULL);
978 /* create standard sections */
979 text_section = new_section(s, ".text", SHT_PROGBITS, SHF_ALLOC | SHF_EXECINSTR);
980 data_section = new_section(s, ".data", SHT_PROGBITS, SHF_ALLOC | SHF_WRITE);
981 bss_section = new_section(s, ".bss", SHT_NOBITS, SHF_ALLOC | SHF_WRITE);
983 /* symbols are always generated for linking stage */
984 symtab_section = new_symtab(s, ".symtab", SHT_SYMTAB, 0,
985 ".strtab",
986 ".hashtab", SHF_PRIVATE);
987 strtab_section = symtab_section->link;
989 /* private symbol table for dynamic symbols */
990 s->dynsymtab_section = new_symtab(s, ".dynsymtab", SHT_SYMTAB, SHF_PRIVATE,
991 ".dynstrtab",
992 ".dynhashtab", SHF_PRIVATE);
993 s->alacarte_link = 1;
994 s->nocommon = 1;
996 #ifdef CHAR_IS_UNSIGNED
997 s->char_is_unsigned = 1;
998 #endif
999 #if defined(TCC_TARGET_PE) && 0
1000 /* XXX: currently the PE linker is not ready to support that */
1001 s->leading_underscore = 1;
1002 #endif
1003 if (s->section_align == 0)
1004 s->section_align = ELF_PAGE_SIZE;
1005 #ifdef TCC_TARGET_I386
1006 s->seg_size = 32;
1007 #endif
1008 return s;
1011 LIBTCCAPI void tcc_delete(TCCState *s1)
1013 int i;
1015 tcc_cleanup();
1017 /* free all sections */
1018 for(i = 1; i < s1->nb_sections; i++)
1019 free_section(s1->sections[i]);
1020 dynarray_reset(&s1->sections, &s1->nb_sections);
1022 for(i = 0; i < s1->nb_priv_sections; i++)
1023 free_section(s1->priv_sections[i]);
1024 dynarray_reset(&s1->priv_sections, &s1->nb_priv_sections);
1026 /* free any loaded DLLs */
1027 for ( i = 0; i < s1->nb_loaded_dlls; i++) {
1028 DLLReference *ref = s1->loaded_dlls[i];
1029 if ( ref->handle )
1030 dlclose(ref->handle);
1033 /* free loaded dlls array */
1034 dynarray_reset(&s1->loaded_dlls, &s1->nb_loaded_dlls);
1036 /* free library paths */
1037 dynarray_reset(&s1->library_paths, &s1->nb_library_paths);
1039 /* free include paths */
1040 dynarray_reset(&s1->cached_includes, &s1->nb_cached_includes);
1041 dynarray_reset(&s1->include_paths, &s1->nb_include_paths);
1042 dynarray_reset(&s1->sysinclude_paths, &s1->nb_sysinclude_paths);
1044 tcc_free(s1->tcc_lib_path);
1046 dynarray_reset(&s1->input_files, &s1->nb_input_files);
1047 dynarray_reset(&s1->input_libs, &s1->nb_input_libs);
1048 dynarray_reset(&s1->target_deps, &s1->nb_target_deps);
1050 #ifdef HAVE_SELINUX
1051 munmap (s1->write_mem, s1->mem_size);
1052 munmap (s1->runtime_mem, s1->mem_size);
1053 #else
1054 tcc_free(s1->runtime_mem);
1055 #endif
1056 tcc_free(s1);
1059 LIBTCCAPI int tcc_add_include_path(TCCState *s1, const char *pathname)
1061 char *pathname1;
1063 pathname1 = tcc_strdup(pathname);
1064 dynarray_add((void ***)&s1->include_paths, &s1->nb_include_paths, pathname1);
1065 return 0;
1068 LIBTCCAPI int tcc_add_sysinclude_path(TCCState *s1, const char *pathname)
1070 char *pathname1;
1072 pathname1 = tcc_strdup(pathname);
1073 dynarray_add((void ***)&s1->sysinclude_paths, &s1->nb_sysinclude_paths, pathname1);
1074 return 0;
1077 ST_FUNC int tcc_add_file_internal(TCCState *s1, const char *filename, int flags)
1079 const char *ext;
1080 ElfW(Ehdr) ehdr;
1081 int fd, ret, size;
1082 BufferedFile *saved_file;
1084 ret = -1;
1086 /* find source file type with extension */
1087 ext = tcc_fileextension(filename);
1088 if (ext[0])
1089 ext++;
1091 /* open the file */
1092 saved_file = file;
1093 file = tcc_open(s1, filename);
1094 if (!file) {
1095 if (flags & AFF_PRINT_ERROR)
1096 error_noabort("file '%s' not found", filename);
1097 goto the_end;
1100 /* update target deps */
1101 dynarray_add((void ***)&s1->target_deps, &s1->nb_target_deps,
1102 tcc_strdup(filename));
1104 if (flags & AFF_PREPROCESS) {
1105 ret = tcc_preprocess(s1);
1106 goto the_end;
1109 if (!ext[0] || !PATHCMP(ext, "c")) {
1110 /* C file assumed */
1111 ret = tcc_compile(s1);
1112 goto the_end;
1115 #ifdef CONFIG_TCC_ASM
1116 if (!strcmp(ext, "S")) {
1117 /* preprocessed assembler */
1118 ret = tcc_assemble(s1, 1);
1119 goto the_end;
1122 if (!strcmp(ext, "s")) {
1123 /* non preprocessed assembler */
1124 ret = tcc_assemble(s1, 0);
1125 goto the_end;
1127 #endif
1129 fd = file->fd;
1130 /* assume executable format: auto guess file type */
1131 size = read(fd, &ehdr, sizeof(ehdr));
1132 lseek(fd, 0, SEEK_SET);
1133 if (size <= 0) {
1134 error_noabort("could not read header");
1135 goto the_end;
1138 if (size == sizeof(ehdr) &&
1139 ehdr.e_ident[0] == ELFMAG0 &&
1140 ehdr.e_ident[1] == ELFMAG1 &&
1141 ehdr.e_ident[2] == ELFMAG2 &&
1142 ehdr.e_ident[3] == ELFMAG3) {
1144 /* do not display line number if error */
1145 file->line_num = 0;
1146 if (ehdr.e_type == ET_REL) {
1147 ret = tcc_load_object_file(s1, fd, 0);
1148 goto the_end;
1151 #ifndef TCC_TARGET_PE
1152 if (ehdr.e_type == ET_DYN) {
1153 if (s1->output_type == TCC_OUTPUT_MEMORY) {
1154 void *h;
1155 h = dlopen(filename, RTLD_GLOBAL | RTLD_LAZY);
1156 if (h)
1157 ret = 0;
1158 } else {
1159 ret = tcc_load_dll(s1, fd, filename,
1160 (flags & AFF_REFERENCED_DLL) != 0);
1162 goto the_end;
1164 #endif
1165 error_noabort("unrecognized ELF file");
1166 goto the_end;
1169 if (memcmp((char *)&ehdr, ARMAG, 8) == 0) {
1170 file->line_num = 0; /* do not display line number if error */
1171 ret = tcc_load_archive(s1, fd);
1172 goto the_end;
1175 #ifdef TCC_TARGET_COFF
1176 if (*(uint16_t *)(&ehdr) == COFF_C67_MAGIC) {
1177 ret = tcc_load_coff(s1, fd);
1178 goto the_end;
1180 #endif
1182 #ifdef TCC_TARGET_PE
1183 ret = pe_load_file(s1, filename, fd);
1184 #else
1185 /* as GNU ld, consider it is an ld script if not recognized */
1186 ret = tcc_load_ldscript(s1);
1187 #endif
1188 if (ret < 0)
1189 error_noabort("unrecognized file type");
1191 the_end:
1192 if (file)
1193 tcc_close(file);
1194 file = saved_file;
1195 return ret;
1198 LIBTCCAPI int tcc_add_file(TCCState *s, const char *filename)
1200 dynarray_add((void ***)&s->input_files, &s->nb_input_files, tcc_strdup(filename));
1202 if (s->output_type == TCC_OUTPUT_PREPROCESS)
1203 return tcc_add_file_internal(s, filename, AFF_PRINT_ERROR | AFF_PREPROCESS);
1204 else
1205 return tcc_add_file_internal(s, filename, AFF_PRINT_ERROR);
1208 LIBTCCAPI int tcc_add_library_path(TCCState *s, const char *pathname)
1210 char *pathname1;
1212 pathname1 = tcc_strdup(pathname);
1213 dynarray_add((void ***)&s->library_paths, &s->nb_library_paths, pathname1);
1214 return 0;
1217 /* find and load a dll. Return non zero if not found */
1218 /* XXX: add '-rpath' option support ? */
1219 ST_FUNC int tcc_add_dll(TCCState *s, const char *filename, int flags)
1221 char buf[1024];
1222 int i;
1224 for(i = 0; i < s->nb_library_paths; i++) {
1225 snprintf(buf, sizeof(buf), "%s/%s",
1226 s->library_paths[i], filename);
1227 if (tcc_add_file_internal(s, buf, flags) == 0)
1228 return 0;
1230 return -1;
1233 /* the library name is the same as the argument of the '-l' option */
1234 LIBTCCAPI int tcc_add_library(TCCState *s, const char *libraryname)
1236 char buf[1024];
1237 int i;
1239 dynarray_add((void ***)&s->input_libs, &s->nb_input_libs, tcc_strdup(libraryname));
1241 /* first we look for the dynamic library if not static linking */
1242 if (!s->static_link) {
1243 #ifdef TCC_TARGET_PE
1244 if (pe_add_dll(s, libraryname) == 0)
1245 return 0;
1246 #else
1247 snprintf(buf, sizeof(buf), "lib%s.so", libraryname);
1248 if (tcc_add_dll(s, buf, 0) == 0)
1249 return 0;
1250 #endif
1252 /* then we look for the static library */
1253 for(i = 0; i < s->nb_library_paths; i++) {
1254 snprintf(buf, sizeof(buf), "%s/lib%s.a",
1255 s->library_paths[i], libraryname);
1256 if (tcc_add_file_internal(s, buf, 0) == 0)
1257 return 0;
1259 return -1;
1262 LIBTCCAPI int tcc_add_symbol(TCCState *s, const char *name, const void *val)
1264 #ifdef TCC_TARGET_PE
1265 pe_putimport(s, 0, name, val);
1266 #else
1267 add_elf_sym(symtab_section, (uplong)val, 0,
1268 ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE), 0,
1269 SHN_ABS, name);
1270 #endif
1271 return 0;
1274 LIBTCCAPI int tcc_set_output_type(TCCState *s, int output_type)
1276 char buf[1024];
1278 s->output_type = output_type;
1280 if (!s->nostdinc) {
1281 /* default include paths */
1282 /* XXX: reverse order needed if -isystem support */
1283 #ifndef TCC_TARGET_PE
1284 tcc_add_sysinclude_path(s, CONFIG_SYSROOT "/usr/local/include");
1285 tcc_add_sysinclude_path(s, CONFIG_SYSROOT "/usr/include");
1286 #endif
1287 snprintf(buf, sizeof(buf), "%s/include", s->tcc_lib_path);
1288 tcc_add_sysinclude_path(s, buf);
1289 #ifdef TCC_TARGET_PE
1290 snprintf(buf, sizeof(buf), "%s/include/winapi", s->tcc_lib_path);
1291 tcc_add_sysinclude_path(s, buf);
1292 #endif
1295 /* if bound checking, then add corresponding sections */
1296 #ifdef CONFIG_TCC_BCHECK
1297 if (s->do_bounds_check) {
1298 /* define symbol */
1299 tcc_define_symbol(s, "__BOUNDS_CHECKING_ON", NULL);
1300 /* create bounds sections */
1301 bounds_section = new_section(s, ".bounds",
1302 SHT_PROGBITS, SHF_ALLOC);
1303 lbounds_section = new_section(s, ".lbounds",
1304 SHT_PROGBITS, SHF_ALLOC);
1306 #endif
1308 if (s->char_is_unsigned) {
1309 tcc_define_symbol(s, "__CHAR_UNSIGNED__", NULL);
1312 /* add debug sections */
1313 if (s->do_debug) {
1314 /* stab symbols */
1315 stab_section = new_section(s, ".stab", SHT_PROGBITS, 0);
1316 stab_section->sh_entsize = sizeof(Stab_Sym);
1317 stabstr_section = new_section(s, ".stabstr", SHT_STRTAB, 0);
1318 put_elf_str(stabstr_section, "");
1319 stab_section->link = stabstr_section;
1320 /* put first entry */
1321 put_stabs("", 0, 0, 0, 0);
1324 /* add libc crt1/crti objects */
1325 #ifndef TCC_TARGET_PE
1326 if ((output_type == TCC_OUTPUT_EXE || output_type == TCC_OUTPUT_DLL) &&
1327 !s->nostdlib) {
1328 if (output_type != TCC_OUTPUT_DLL)
1329 tcc_add_file(s, CONFIG_TCC_CRT_PREFIX "/crt1.o");
1330 tcc_add_file(s, CONFIG_TCC_CRT_PREFIX "/crti.o");
1332 #endif
1334 #ifdef TCC_TARGET_PE
1335 snprintf(buf, sizeof(buf), "%s/lib", s->tcc_lib_path);
1336 tcc_add_library_path(s, buf);
1337 #ifdef _WIN32
1338 if (GetSystemDirectory(buf, sizeof buf))
1339 tcc_add_library_path(s, buf);
1340 #endif
1341 #endif
1343 return 0;
1346 #define WD_ALL 0x0001 /* warning is activated when using -Wall */
1347 #define FD_INVERT 0x0002 /* invert value before storing */
1349 typedef struct FlagDef {
1350 uint16_t offset;
1351 uint16_t flags;
1352 const char *name;
1353 } FlagDef;
1355 static const FlagDef warning_defs[] = {
1356 { offsetof(TCCState, warn_unsupported), 0, "unsupported" },
1357 { offsetof(TCCState, warn_write_strings), 0, "write-strings" },
1358 { offsetof(TCCState, warn_error), 0, "error" },
1359 { offsetof(TCCState, warn_implicit_function_declaration), WD_ALL,
1360 "implicit-function-declaration" },
1363 ST_FUNC int set_flag(TCCState *s, const FlagDef *flags, int nb_flags,
1364 const char *name, int value)
1366 int i;
1367 const FlagDef *p;
1368 const char *r;
1370 r = name;
1371 if (r[0] == 'n' && r[1] == 'o' && r[2] == '-') {
1372 r += 3;
1373 value = !value;
1375 for(i = 0, p = flags; i < nb_flags; i++, p++) {
1376 if (!strcmp(r, p->name))
1377 goto found;
1379 return -1;
1380 found:
1381 if (p->flags & FD_INVERT)
1382 value = !value;
1383 *(int *)((uint8_t *)s + p->offset) = value;
1384 return 0;
1387 /* set/reset a warning */
1388 LIBTCCAPI int tcc_set_warning(TCCState *s, const char *warning_name, int value)
1390 int i;
1391 const FlagDef *p;
1393 if (!strcmp(warning_name, "all")) {
1394 for(i = 0, p = warning_defs; i < countof(warning_defs); i++, p++) {
1395 if (p->flags & WD_ALL)
1396 *(int *)((uint8_t *)s + p->offset) = 1;
1398 return 0;
1399 } else {
1400 return set_flag(s, warning_defs, countof(warning_defs),
1401 warning_name, value);
1405 static const FlagDef flag_defs[] = {
1406 { offsetof(TCCState, char_is_unsigned), 0, "unsigned-char" },
1407 { offsetof(TCCState, char_is_unsigned), FD_INVERT, "signed-char" },
1408 { offsetof(TCCState, nocommon), FD_INVERT, "common" },
1409 { offsetof(TCCState, leading_underscore), 0, "leading-underscore" },
1412 /* set/reset a flag */
1413 PUB_FUNC int tcc_set_flag(TCCState *s, const char *flag_name, int value)
1415 return set_flag(s, flag_defs, countof(flag_defs),
1416 flag_name, value);
1420 static int strstart(const char *str, const char *val, char **ptr)
1422 const char *p, *q;
1423 p = str;
1424 q = val;
1425 while (*q != '\0') {
1426 if (*p != *q)
1427 return 0;
1428 p++;
1429 q++;
1431 if (ptr)
1432 *ptr = (char *) p;
1433 return 1;
1436 /* set linker options */
1437 PUB_FUNC const char * tcc_set_linker(TCCState *s, char *option, int multi)
1439 char *p = option;
1440 char *end;
1442 while (option && *option) {
1443 end = NULL;
1444 if (strstart(option, "-Bsymbolic", &p)) {
1445 s->symbolic = TRUE;
1446 #ifdef TCC_TARGET_PE
1447 } else if (strstart(option, "--file-alignment,", &p)) {
1448 s->pe_file_align = strtoul(p, &end, 16);
1449 #endif
1450 } else if (strstart(option, "-fini,", &p)) {
1451 s->fini_symbol = p;
1452 if (s->warn_unsupported)
1453 warning("ignoring -fini %s", p);
1455 } else if (strstart(option, "--image-base,", &p)) {
1456 s->text_addr = strtoul(p, &end, 16);
1457 s->has_text_addr = 1;
1458 } else if (strstart(option, "-init,", &p)) {
1459 s->init_symbol = p;
1460 if (s->warn_unsupported)
1461 warning("ignoring -init %s", p);
1463 } else if (strstart(option, "--oformat,", &p)) {
1464 #if defined(TCC_TARGET_PE)
1465 if (strstart(p, "pe-", NULL)) {
1466 #else
1467 #if defined(TCC_TARGET_X86_64)
1468 if (strstart(p, "elf64-", NULL)) {
1469 #else
1470 if (strstart(p, "elf32-", NULL)) {
1471 #endif
1472 #endif
1473 s->output_format = TCC_OUTPUT_FORMAT_ELF;
1474 } else if (!strcmp(p, "binary")) {
1475 s->output_format = TCC_OUTPUT_FORMAT_BINARY;
1476 } else
1477 #ifdef TCC_TARGET_COFF
1478 if (!strcmp(p, "coff")) {
1479 s->output_format = TCC_OUTPUT_FORMAT_COFF;
1480 } else
1481 #endif
1483 return p;
1486 } else if (strstart(option, "-rpath=", &p)) {
1487 s->rpath = p;
1488 } else if (strstart(option, "--section-alignment,", &p)) {
1489 s->section_align = strtoul(p, &end, 16);
1490 } else if (strstart(option, "-soname,", &p)) {
1491 s->soname = p;
1492 multi = 0;
1493 #ifdef TCC_TARGET_PE
1494 } else if (strstart(option, "--subsystem,", &p)) {
1495 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
1496 if (!strcmp(p, "native")) {
1497 s->pe_subsystem = 1;
1498 } else if (!strcmp(p, "console")) {
1499 s->pe_subsystem = 3;
1500 } else if (!strcmp(p, "gui")) {
1501 s->pe_subsystem = 2;
1502 } else if (!strcmp(p, "posix")) {
1503 s->pe_subsystem = 7;
1504 } else if (!strcmp(p, "efiapp")) {
1505 s->pe_subsystem = 10;
1506 } else if (!strcmp(p, "efiboot")) {
1507 s->pe_subsystem = 11;
1508 } else if (!strcmp(p, "efiruntime")) {
1509 s->pe_subsystem = 12;
1510 } else if (!strcmp(p, "efirom")) {
1511 s->pe_subsystem = 13;
1512 #elif defined(TCC_TARGET_ARM)
1513 if (!strcmp(p, "wince")) {
1514 s->pe_subsystem = 9;
1515 #endif
1516 } else {
1517 return p;
1519 #endif
1521 } else if (strstart(option, "-Ttext,", &p)) {
1522 s->text_addr = strtoul(p, &end, 16);
1523 s->has_text_addr = 1;
1525 } else {
1526 return option;
1529 if (multi) {
1530 option = NULL;
1531 p = strchr( (end) ? end : p, ',');
1532 if (p) {
1533 *p = 0; /* terminate last option */
1534 option = ++p;
1536 } else
1537 option = NULL;
1539 return NULL;
1542 PUB_FUNC void tcc_print_stats(TCCState *s, int64_t total_time)
1544 double tt;
1545 tt = (double)total_time / 1000000.0;
1546 if (tt < 0.001)
1547 tt = 0.001;
1548 if (total_bytes < 1)
1549 total_bytes = 1;
1550 printf("%d idents, %d lines, %d bytes, %0.3f s, %d lines/s, %0.1f MB/s\n",
1551 tok_ident - TOK_IDENT, total_lines, total_bytes,
1552 tt, (int)(total_lines / tt),
1553 total_bytes / tt / 1000000.0);
1556 /* set CONFIG_TCCDIR at runtime */
1557 LIBTCCAPI void tcc_set_lib_path(TCCState *s, const char *path)
1559 tcc_free(s->tcc_lib_path);
1560 s->tcc_lib_path = tcc_strdup(path);
1563 PUB_FUNC void set_num_callers(int n)
1565 #ifdef CONFIG_TCC_BACKTRACE
1566 num_callers = n;
1567 #endif
1571 LIBTCCAPI const char *tcc_default_target(TCCState *s)
1573 /* FIXME will break in multithreaded case */
1574 static char outfile_default[1024];
1576 char *ext;
1577 const char *name =
1578 strcmp(s->input_files[0], "-") == 0 ? "a"
1579 : tcc_basename(s->input_files[0]);
1580 pstrcpy(outfile_default, sizeof(outfile_default), name);
1581 ext = tcc_fileextension(outfile_default);
1582 #ifdef TCC_TARGET_PE
1583 if (s->output_type == TCC_OUTPUT_DLL)
1584 strcpy(ext, ".dll");
1585 else
1586 if (s->output_type == TCC_OUTPUT_EXE)
1587 strcpy(ext, ".exe");
1588 else
1589 #endif
1590 if (( (s->output_type == TCC_OUTPUT_OBJ && !s->reloc_output) ||
1591 (s->output_type == TCC_OUTPUT_PREPROCESS) )
1592 && *ext)
1593 strcpy(ext, ".o");
1594 else
1595 pstrcpy(outfile_default, sizeof(outfile_default), "a.out");
1597 return outfile_default;
1601 LIBTCCAPI void tcc_gen_makedeps(TCCState *s, const char *target, const char *filename)
1603 FILE *depout;
1604 char buf[1024], *ext;
1605 int i;
1607 if (!target)
1608 target = tcc_default_target(s);
1610 if (!filename) {
1611 /* compute filename automatically
1612 * dir/file.o -> dir/file.d */
1613 pstrcpy(buf, sizeof(buf), target);
1614 ext = tcc_fileextension(buf);
1615 pstrcpy(ext, sizeof(buf) - (ext-buf), ".d");
1616 filename = buf;
1619 if (s->verbose)
1620 printf("<- %s\n", filename);
1622 /* XXX return err codes instead of error() ? */
1623 depout = fopen(filename, "w");
1624 if (!depout)
1625 error("could not open '%s'", filename);
1627 fprintf(depout, "%s : \\\n", target);
1628 for (i=0; i<s->nb_target_deps; ++i)
1629 fprintf(depout, "\t%s \\\n", s->target_deps[i]);
1630 fprintf(depout, "\n");
1631 fclose(depout);