bitfields: Implement MS compatible layout
[tinycc.git] / libtcc.c
blob68c3f9d0173c0b704789691670999b36b28cd953
1 /*
2 * TCC - Tiny C Compiler
4 * Copyright (c) 2001-2004 Fabrice Bellard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 #include "tcc.h"
23 /********************************************************/
24 /* global variables */
26 /* use GNU C extensions */
27 ST_DATA int gnu_ext = 1;
29 /* use TinyCC extensions */
30 ST_DATA int tcc_ext = 1;
32 /* XXX: get rid of this ASAP */
33 ST_DATA struct TCCState *tcc_state;
35 /********************************************************/
37 #ifdef ONE_SOURCE
38 #include "tccpp.c"
39 #include "tccgen.c"
40 #include "tccelf.c"
41 #include "tccrun.c"
42 #ifdef TCC_TARGET_I386
43 #include "i386-gen.c"
44 #include "i386-link.c"
45 #endif
46 #ifdef TCC_TARGET_ARM
47 #include "arm-gen.c"
48 #include "arm-link.c"
49 #endif
50 #ifdef TCC_TARGET_ARM64
51 #include "arm64-gen.c"
52 #include "arm64-link.c"
53 #endif
54 #ifdef TCC_TARGET_C67
55 #include "c67-gen.c"
56 #include "c67-link.c"
57 #endif
58 #ifdef TCC_TARGET_X86_64
59 #include "x86_64-gen.c"
60 #include "x86_64-link.c"
61 #endif
62 #ifdef CONFIG_TCC_ASM
63 #include "tccasm.c"
64 #if defined TCC_TARGET_I386 || defined TCC_TARGET_X86_64
65 #include "i386-asm.c"
66 #endif
67 #endif
68 #ifdef TCC_TARGET_COFF
69 #include "tcccoff.c"
70 #endif
71 #ifdef TCC_TARGET_PE
72 #include "tccpe.c"
73 #endif
74 #endif /* ONE_SOURCE */
76 /********************************************************/
77 #ifndef CONFIG_TCC_ASM
78 ST_FUNC void asm_instr(void)
80 tcc_error("inline asm() not supported");
82 ST_FUNC void asm_global_instr(void)
84 tcc_error("inline asm() not supported");
86 #endif
88 /********************************************************/
89 #ifdef _WIN32
90 ST_FUNC char *normalize_slashes(char *path)
92 char *p;
93 for (p = path; *p; ++p)
94 if (*p == '\\')
95 *p = '/';
96 return path;
99 static HMODULE tcc_module;
101 /* on win32, we suppose the lib and includes are at the location of 'tcc.exe' */
102 static void tcc_set_lib_path_w32(TCCState *s)
104 char path[1024], *p;
105 GetModuleFileNameA(tcc_module, path, sizeof path);
106 p = tcc_basename(normalize_slashes(strlwr(path)));
107 if (p - 5 > path && 0 == strncmp(p - 5, "/bin/", 5))
108 p -= 5;
109 else if (p > path)
110 p--;
111 *p = 0;
112 tcc_set_lib_path(s, path);
115 #ifdef TCC_TARGET_PE
116 static void tcc_add_systemdir(TCCState *s)
118 char buf[1000];
119 GetSystemDirectory(buf, sizeof buf);
120 tcc_add_library_path(s, normalize_slashes(buf));
122 #endif
124 #ifdef LIBTCC_AS_DLL
125 BOOL WINAPI DllMain (HINSTANCE hDll, DWORD dwReason, LPVOID lpReserved)
127 if (DLL_PROCESS_ATTACH == dwReason)
128 tcc_module = hDll;
129 return TRUE;
131 #endif
132 #endif
134 /********************************************************/
135 /* copy a string and truncate it. */
136 PUB_FUNC char *pstrcpy(char *buf, int buf_size, const char *s)
138 char *q, *q_end;
139 int c;
141 if (buf_size > 0) {
142 q = buf;
143 q_end = buf + buf_size - 1;
144 while (q < q_end) {
145 c = *s++;
146 if (c == '\0')
147 break;
148 *q++ = c;
150 *q = '\0';
152 return buf;
155 /* strcat and truncate. */
156 PUB_FUNC char *pstrcat(char *buf, int buf_size, const char *s)
158 int len;
159 len = strlen(buf);
160 if (len < buf_size)
161 pstrcpy(buf + len, buf_size - len, s);
162 return buf;
165 PUB_FUNC char *pstrncpy(char *out, const char *in, size_t num)
167 memcpy(out, in, num);
168 out[num] = '\0';
169 return out;
172 /* extract the basename of a file */
173 PUB_FUNC char *tcc_basename(const char *name)
175 char *p = strchr(name, 0);
176 while (p > name && !IS_DIRSEP(p[-1]))
177 --p;
178 return p;
181 /* extract extension part of a file
183 * (if no extension, return pointer to end-of-string)
185 PUB_FUNC char *tcc_fileextension (const char *name)
187 char *b = tcc_basename(name);
188 char *e = strrchr(b, '.');
189 return e ? e : strchr(b, 0);
192 /********************************************************/
193 /* memory management */
195 #undef free
196 #undef malloc
197 #undef realloc
199 #ifndef MEM_DEBUG
201 PUB_FUNC void tcc_free(void *ptr)
203 free(ptr);
206 PUB_FUNC void *tcc_malloc(unsigned long size)
208 void *ptr;
209 ptr = malloc(size);
210 if (!ptr && size)
211 tcc_error("memory full (malloc)");
212 return ptr;
215 PUB_FUNC void *tcc_mallocz(unsigned long size)
217 void *ptr;
218 ptr = tcc_malloc(size);
219 memset(ptr, 0, size);
220 return ptr;
223 PUB_FUNC void *tcc_realloc(void *ptr, unsigned long size)
225 void *ptr1;
226 ptr1 = realloc(ptr, size);
227 if (!ptr1 && size)
228 tcc_error("memory full (realloc)");
229 return ptr1;
232 PUB_FUNC char *tcc_strdup(const char *str)
234 char *ptr;
235 ptr = tcc_malloc(strlen(str) + 1);
236 strcpy(ptr, str);
237 return ptr;
240 PUB_FUNC void tcc_memstats(int bench)
244 #else
246 #define MEM_DEBUG_MAGIC1 0xFEEDDEB1
247 #define MEM_DEBUG_MAGIC2 0xFEEDDEB2
248 #define MEM_DEBUG_FILE_LEN 15
250 struct mem_debug_header {
251 size_t magic1;
252 size_t size;
253 struct mem_debug_header *prev;
254 struct mem_debug_header *next;
255 size_t line_num;
256 char file_name[MEM_DEBUG_FILE_LEN + 1];
257 size_t magic2;
260 typedef struct mem_debug_header mem_debug_header_t;
262 static mem_debug_header_t *mem_debug_chain;
263 static size_t mem_cur_size;
264 static size_t mem_max_size;
266 PUB_FUNC void *tcc_malloc_debug(unsigned long size, const char *file, int line)
268 void *ptr;
269 int ofs;
271 mem_debug_header_t *header;
273 ptr = malloc(sizeof(mem_debug_header_t) + size);
274 if (!ptr)
275 tcc_error("memory full (malloc)");
277 mem_cur_size += size;
278 if (mem_cur_size > mem_max_size)
279 mem_max_size = mem_cur_size;
281 header = (mem_debug_header_t *)ptr;
283 header->magic1 = MEM_DEBUG_MAGIC1;
284 header->magic2 = MEM_DEBUG_MAGIC2;
285 header->size = size;
286 header->line_num = line;
288 ofs = strlen(file) - MEM_DEBUG_FILE_LEN;
289 strncpy(header->file_name, file + (ofs > 0 ? ofs : 0), MEM_DEBUG_FILE_LEN);
290 header->file_name[MEM_DEBUG_FILE_LEN] = 0;
292 header->next = mem_debug_chain;
293 header->prev = NULL;
295 if (header->next)
296 header->next->prev = header;
298 mem_debug_chain = header;
300 ptr = (char *)ptr + sizeof(mem_debug_header_t);
301 return ptr;
304 PUB_FUNC void tcc_free_debug(void *ptr)
306 mem_debug_header_t *header;
308 if (!ptr)
309 return;
311 ptr = (char *)ptr - sizeof(mem_debug_header_t);
312 header = (mem_debug_header_t *)ptr;
313 if (header->magic1 != MEM_DEBUG_MAGIC1 ||
314 header->magic2 != MEM_DEBUG_MAGIC2 ||
315 header->size == (size_t)-1 )
317 tcc_error("tcc_free check failed");
320 mem_cur_size -= header->size;
321 header->size = (size_t)-1;
323 if (header->next)
324 header->next->prev = header->prev;
326 if (header->prev)
327 header->prev->next = header->next;
329 if (header == mem_debug_chain)
330 mem_debug_chain = header->next;
332 free(ptr);
336 PUB_FUNC void *tcc_mallocz_debug(unsigned long size, const char *file, int line)
338 void *ptr;
339 ptr = tcc_malloc_debug(size,file,line);
340 memset(ptr, 0, size);
341 return ptr;
344 PUB_FUNC void *tcc_realloc_debug(void *ptr, unsigned long size, const char *file, int line)
346 mem_debug_header_t *header;
347 int mem_debug_chain_update = 0;
349 if (!ptr) {
350 ptr = tcc_malloc_debug(size, file, line);
351 return ptr;
354 ptr = (char *)ptr - sizeof(mem_debug_header_t);
355 header = (mem_debug_header_t *)ptr;
356 if (header->magic1 != MEM_DEBUG_MAGIC1 ||
357 header->magic2 != MEM_DEBUG_MAGIC2 ||
358 header->size == (size_t)-1 )
360 check_error:
361 tcc_error("tcc_realloc check failed");
364 mem_debug_chain_update = (header == mem_debug_chain);
366 mem_cur_size -= header->size;
367 ptr = realloc(ptr, sizeof(mem_debug_header_t) + size);
368 if (!ptr)
369 tcc_error("memory full (realloc)");
371 header = (mem_debug_header_t *)ptr;
372 if (header->magic1 != MEM_DEBUG_MAGIC1 ||
373 header->magic2 != MEM_DEBUG_MAGIC2)
375 goto check_error;
378 mem_cur_size += size;
379 if (mem_cur_size > mem_max_size)
380 mem_max_size = mem_cur_size;
382 header->size = size;
383 if (header->next)
384 header->next->prev = header;
386 if (header->prev)
387 header->prev->next = header;
389 if (mem_debug_chain_update)
390 mem_debug_chain = header;
392 ptr = (char *)ptr + sizeof(mem_debug_header_t);
393 return ptr;
396 PUB_FUNC char *tcc_strdup_debug(const char *str, const char *file, int line)
398 char *ptr;
399 ptr = tcc_malloc_debug(strlen(str) + 1, file, line);
400 strcpy(ptr, str);
401 return ptr;
404 PUB_FUNC void tcc_memstats(int bench)
406 if (mem_cur_size) {
407 mem_debug_header_t *header = mem_debug_chain;
409 fprintf(stderr, "MEM_DEBUG: mem_leak= %d bytes, mem_max_size= %d bytes\n",
410 mem_cur_size, mem_max_size);
412 while (header) {
413 fprintf(stderr, "%s:%u: error: %u bytes leaked\n",
414 header->file_name, header->line_num, header->size);
415 header = header->next;
418 else if (bench)
419 fprintf(stderr, "mem_max_size= %d bytes\n", mem_max_size);
422 #undef MEM_DEBUG_MAGIC1
423 #undef MEM_DEBUG_MAGIC2
424 #undef MEM_DEBUG_FILE_LEN
426 #endif
428 #define free(p) use_tcc_free(p)
429 #define malloc(s) use_tcc_malloc(s)
430 #define realloc(p, s) use_tcc_realloc(p, s)
432 /********************************************************/
433 /* dynarrays */
435 ST_FUNC void dynarray_add(void ***ptab, int *nb_ptr, void *data)
437 int nb, nb_alloc;
438 void **pp;
440 nb = *nb_ptr;
441 pp = *ptab;
442 /* every power of two we double array size */
443 if ((nb & (nb - 1)) == 0) {
444 if (!nb)
445 nb_alloc = 1;
446 else
447 nb_alloc = nb * 2;
448 pp = tcc_realloc(pp, nb_alloc * sizeof(void *));
449 *ptab = pp;
451 pp[nb++] = data;
452 *nb_ptr = nb;
455 ST_FUNC void dynarray_reset(void *pp, int *n)
457 void **p;
458 for (p = *(void***)pp; *n; ++p, --*n)
459 if (*p)
460 tcc_free(*p);
461 tcc_free(*(void**)pp);
462 *(void**)pp = NULL;
465 static void tcc_split_path(TCCState *s, void ***p_ary, int *p_nb_ary, const char *in)
467 const char *p;
468 do {
469 int c;
470 CString str;
472 cstr_new(&str);
473 for (p = in; c = *p, c != '\0' && c != PATHSEP; ++p) {
474 if (c == '{' && p[1] && p[2] == '}') {
475 c = p[1], p += 2;
476 if (c == 'B')
477 cstr_cat(&str, s->tcc_lib_path, -1);
478 } else {
479 cstr_ccat(&str, c);
482 if (str.size) {
483 cstr_ccat(&str, '\0');
484 dynarray_add(p_ary, p_nb_ary, tcc_strdup(str.data));
486 cstr_free(&str);
487 in = p+1;
488 } while (*p);
491 /********************************************************/
493 static void strcat_vprintf(char *buf, int buf_size, const char *fmt, va_list ap)
495 int len;
496 len = strlen(buf);
497 vsnprintf(buf + len, buf_size - len, fmt, ap);
500 static void strcat_printf(char *buf, int buf_size, const char *fmt, ...)
502 va_list ap;
503 va_start(ap, fmt);
504 strcat_vprintf(buf, buf_size, fmt, ap);
505 va_end(ap);
508 static void error1(TCCState *s1, int is_warning, const char *fmt, va_list ap)
510 char buf[2048];
511 BufferedFile **pf, *f;
513 buf[0] = '\0';
514 /* use upper file if inline ":asm:" or token ":paste:" */
515 for (f = file; f && f->filename[0] == ':'; f = f->prev)
517 if (f) {
518 for(pf = s1->include_stack; pf < s1->include_stack_ptr; pf++)
519 strcat_printf(buf, sizeof(buf), "In file included from %s:%d:\n",
520 (*pf)->filename, (*pf)->line_num);
521 if (f->line_num > 0) {
522 strcat_printf(buf, sizeof(buf), "%s:%d: ",
523 f->filename, f->line_num - !!(tok_flags & TOK_FLAG_BOL));
524 } else {
525 strcat_printf(buf, sizeof(buf), "%s: ",
526 f->filename);
528 } else {
529 strcat_printf(buf, sizeof(buf), "tcc: ");
531 if (is_warning)
532 strcat_printf(buf, sizeof(buf), "warning: ");
533 else
534 strcat_printf(buf, sizeof(buf), "error: ");
535 strcat_vprintf(buf, sizeof(buf), fmt, ap);
537 if (!s1->error_func) {
538 /* default case: stderr */
539 if (s1->ppfp) /* print a newline during tcc -E */
540 fprintf(s1->ppfp, "\n"), fflush(s1->ppfp);
541 fprintf(stderr, "%s\n", buf);
542 fflush(stderr); /* print error/warning now (win32) */
543 } else {
544 s1->error_func(s1->error_opaque, buf);
546 if (!is_warning || s1->warn_error)
547 s1->nb_errors++;
550 LIBTCCAPI void tcc_set_error_func(TCCState *s, void *error_opaque,
551 void (*error_func)(void *opaque, const char *msg))
553 s->error_opaque = error_opaque;
554 s->error_func = error_func;
557 /* error without aborting current compilation */
558 PUB_FUNC void tcc_error_noabort(const char *fmt, ...)
560 TCCState *s1 = tcc_state;
561 va_list ap;
563 va_start(ap, fmt);
564 error1(s1, 0, fmt, ap);
565 va_end(ap);
568 PUB_FUNC void tcc_error(const char *fmt, ...)
570 TCCState *s1 = tcc_state;
571 va_list ap;
573 va_start(ap, fmt);
574 error1(s1, 0, fmt, ap);
575 va_end(ap);
576 /* better than nothing: in some cases, we accept to handle errors */
577 if (s1->error_set_jmp_enabled) {
578 longjmp(s1->error_jmp_buf, 1);
579 } else {
580 /* XXX: eliminate this someday */
581 exit(1);
585 PUB_FUNC void tcc_warning(const char *fmt, ...)
587 TCCState *s1 = tcc_state;
588 va_list ap;
590 if (s1->warn_none)
591 return;
593 va_start(ap, fmt);
594 error1(s1, 1, fmt, ap);
595 va_end(ap);
598 /********************************************************/
599 /* I/O layer */
601 ST_FUNC void tcc_open_bf(TCCState *s1, const char *filename, int initlen)
603 BufferedFile *bf;
604 int buflen = initlen ? initlen : IO_BUF_SIZE;
606 bf = tcc_mallocz(sizeof(BufferedFile) + buflen);
607 bf->buf_ptr = bf->buffer;
608 bf->buf_end = bf->buffer + initlen;
609 bf->buf_end[0] = CH_EOB; /* put eob symbol */
610 pstrcpy(bf->filename, sizeof(bf->filename), filename);
611 #ifdef _WIN32
612 normalize_slashes(bf->filename);
613 #endif
614 bf->line_num = 1;
615 bf->ifdef_stack_ptr = s1->ifdef_stack_ptr;
616 bf->fd = -1;
617 bf->prev = file;
618 file = bf;
621 ST_FUNC void tcc_close(void)
623 BufferedFile *bf = file;
624 if (bf->fd > 0) {
625 close(bf->fd);
626 total_lines += bf->line_num;
628 file = bf->prev;
629 tcc_free(bf);
632 ST_FUNC int tcc_open(TCCState *s1, const char *filename)
634 int fd;
635 if (strcmp(filename, "-") == 0)
636 fd = 0, filename = "<stdin>";
637 else
638 fd = open(filename, O_RDONLY | O_BINARY);
639 if ((s1->verbose == 2 && fd >= 0) || s1->verbose == 3)
640 printf("%s %*s%s\n", fd < 0 ? "nf":"->",
641 (int)(s1->include_stack_ptr - s1->include_stack), "", filename);
642 if (fd < 0)
643 return -1;
645 tcc_open_bf(s1, filename, 0);
646 file->fd = fd;
647 return fd;
650 /* compile the C file opened in 'file'. Return non zero if errors. */
651 static int tcc_compile(TCCState *s1)
653 Sym *define_start;
655 preprocess_start(s1);
656 define_start = define_stack;
658 if (setjmp(s1->error_jmp_buf) == 0) {
659 s1->nb_errors = 0;
660 s1->error_set_jmp_enabled = 1;
662 tccgen_start(s1);
663 #ifdef INC_DEBUG
664 printf("%s: **** new file\n", file->filename);
665 #endif
666 ch = file->buf_ptr[0];
667 tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
668 parse_flags = PARSE_FLAG_PREPROCESS | PARSE_FLAG_TOK_NUM | PARSE_FLAG_TOK_STR;
669 next();
670 decl(VT_CONST);
671 if (tok != TOK_EOF)
672 expect("declaration");
673 /* reset define stack, but keep -D and built-ins */
674 free_defines(define_start);
675 tccgen_end(s1);
677 s1->error_set_jmp_enabled = 0;
679 free_inline_functions(s1);
680 sym_pop(&global_stack, NULL, 0);
681 sym_pop(&local_stack, NULL, 0);
682 return s1->nb_errors != 0 ? -1 : 0;
685 LIBTCCAPI int tcc_compile_string(TCCState *s, const char *str)
687 int len, ret;
689 len = strlen(str);
690 tcc_open_bf(s, "<string>", len);
691 memcpy(file->buffer, str, len);
692 ret = tcc_compile(s);
693 tcc_close();
694 return ret;
697 /* define a preprocessor symbol. A value can also be provided with the '=' operator */
698 LIBTCCAPI void tcc_define_symbol(TCCState *s1, const char *sym, const char *value)
700 int len1, len2;
701 /* default value */
702 if (!value)
703 value = "1";
704 len1 = strlen(sym);
705 len2 = strlen(value);
707 /* init file structure */
708 tcc_open_bf(s1, "<define>", len1 + len2 + 1);
709 memcpy(file->buffer, sym, len1);
710 file->buffer[len1] = ' ';
711 memcpy(file->buffer + len1 + 1, value, len2);
713 /* parse with define parser */
714 ch = file->buf_ptr[0];
715 next_nomacro();
716 parse_define();
718 tcc_close();
721 /* undefine a preprocessor symbol */
722 LIBTCCAPI void tcc_undefine_symbol(TCCState *s1, const char *sym)
724 TokenSym *ts;
725 Sym *s;
726 ts = tok_alloc(sym, strlen(sym));
727 s = define_find(ts->tok);
728 /* undefine symbol by putting an invalid name */
729 if (s)
730 define_undef(s);
733 /* cleanup all static data used during compilation */
734 static void tcc_cleanup(void)
736 if (NULL == tcc_state)
737 return;
738 tccpp_delete(tcc_state);
739 tcc_state = NULL;
740 /* free sym_pools */
741 dynarray_reset(&sym_pools, &nb_sym_pools);
742 /* reset symbol stack */
743 sym_free_first = NULL;
746 LIBTCCAPI TCCState *tcc_new(void)
748 TCCState *s;
750 tcc_cleanup();
752 s = tcc_mallocz(sizeof(TCCState));
753 if (!s)
754 return NULL;
755 tcc_state = s;
757 s->alacarte_link = 1;
758 s->nocommon = 1;
759 s->warn_implicit_function_declaration = 1;
760 s->ms_bitfields = 0;
762 #ifdef CHAR_IS_UNSIGNED
763 s->char_is_unsigned = 1;
764 #endif
765 #ifdef TCC_TARGET_I386
766 s->seg_size = 32;
767 #endif
768 #ifdef TCC_IS_NATIVE
769 s->runtime_main = "main";
770 #endif
771 /* enable this if you want symbols with leading underscore on windows: */
772 #if 0 /* def TCC_TARGET_PE */
773 s->leading_underscore = 1;
774 #endif
775 #ifdef _WIN32
776 tcc_set_lib_path_w32(s);
777 #else
778 tcc_set_lib_path(s, CONFIG_TCCDIR);
779 #endif
780 tccelf_new(s);
781 tccpp_new(s);
783 /* we add dummy defines for some special macros to speed up tests
784 and to have working defined() */
785 define_push(TOK___LINE__, MACRO_OBJ, NULL, NULL);
786 define_push(TOK___FILE__, MACRO_OBJ, NULL, NULL);
787 define_push(TOK___DATE__, MACRO_OBJ, NULL, NULL);
788 define_push(TOK___TIME__, MACRO_OBJ, NULL, NULL);
790 /* define __TINYC__ 92X */
791 char buffer[32]; int a,b,c;
792 sscanf(TCC_VERSION, "%d.%d.%d", &a, &b, &c);
793 sprintf(buffer, "%d", a*10000 + b*100 + c);
794 tcc_define_symbol(s, "__TINYC__", buffer);
797 /* standard defines */
798 tcc_define_symbol(s, "__STDC__", NULL);
799 tcc_define_symbol(s, "__STDC_VERSION__", "199901L");
800 tcc_define_symbol(s, "__STDC_HOSTED__", NULL);
802 /* target defines */
803 #if defined(TCC_TARGET_I386)
804 tcc_define_symbol(s, "__i386__", NULL);
805 tcc_define_symbol(s, "__i386", NULL);
806 tcc_define_symbol(s, "i386", NULL);
807 #elif defined(TCC_TARGET_X86_64)
808 tcc_define_symbol(s, "__x86_64__", NULL);
809 #elif defined(TCC_TARGET_ARM)
810 tcc_define_symbol(s, "__ARM_ARCH_4__", NULL);
811 tcc_define_symbol(s, "__arm_elf__", NULL);
812 tcc_define_symbol(s, "__arm_elf", NULL);
813 tcc_define_symbol(s, "arm_elf", NULL);
814 tcc_define_symbol(s, "__arm__", NULL);
815 tcc_define_symbol(s, "__arm", NULL);
816 tcc_define_symbol(s, "arm", NULL);
817 tcc_define_symbol(s, "__APCS_32__", NULL);
818 tcc_define_symbol(s, "__ARMEL__", NULL);
819 #if defined(TCC_ARM_EABI)
820 tcc_define_symbol(s, "__ARM_EABI__", NULL);
821 #endif
822 #if defined(TCC_ARM_HARDFLOAT)
823 s->float_abi = ARM_HARD_FLOAT;
824 tcc_define_symbol(s, "__ARM_PCS_VFP", NULL);
825 #else
826 s->float_abi = ARM_SOFTFP_FLOAT;
827 #endif
828 #elif defined(TCC_TARGET_ARM64)
829 tcc_define_symbol(s, "__aarch64__", NULL);
830 #endif
832 #ifdef TCC_TARGET_PE
833 tcc_define_symbol(s, "_WIN32", NULL);
834 # ifdef TCC_TARGET_X86_64
835 tcc_define_symbol(s, "_WIN64", NULL);
836 # endif
837 #else
838 tcc_define_symbol(s, "__unix__", NULL);
839 tcc_define_symbol(s, "__unix", NULL);
840 tcc_define_symbol(s, "unix", NULL);
841 # if defined(__linux__)
842 tcc_define_symbol(s, "__linux__", NULL);
843 tcc_define_symbol(s, "__linux", NULL);
844 # endif
845 # if defined(__FreeBSD__)
846 tcc_define_symbol(s, "__FreeBSD__", "__FreeBSD__");
847 /* No 'Thread Storage Local' on FreeBSD with tcc */
848 tcc_define_symbol(s, "__NO_TLS", NULL);
849 # endif
850 # if defined(__FreeBSD_kernel__)
851 tcc_define_symbol(s, "__FreeBSD_kernel__", NULL);
852 # endif
853 #endif
854 # if defined(__NetBSD__)
855 tcc_define_symbol(s, "__NetBSD__", "__NetBSD__");
856 # endif
857 # if defined(__OpenBSD__)
858 tcc_define_symbol(s, "__OpenBSD__", "__OpenBSD__");
859 # endif
861 /* TinyCC & gcc defines */
862 #if defined(TCC_TARGET_PE) && defined(TCC_TARGET_X86_64)
863 /* 64bit Windows. */
864 tcc_define_symbol(s, "__SIZE_TYPE__", "unsigned long long");
865 tcc_define_symbol(s, "__PTRDIFF_TYPE__", "long long");
866 tcc_define_symbol(s, "__LLP64__", NULL);
867 #elif defined(TCC_TARGET_X86_64) || defined(TCC_TARGET_ARM64)
868 /* Other 64bit systems. */
869 tcc_define_symbol(s, "__SIZE_TYPE__", "unsigned long");
870 tcc_define_symbol(s, "__PTRDIFF_TYPE__", "long");
871 tcc_define_symbol(s, "__LP64__", NULL);
872 #else
873 /* Other 32bit systems. */
874 tcc_define_symbol(s, "__SIZE_TYPE__", "unsigned long");
875 tcc_define_symbol(s, "__PTRDIFF_TYPE__", "long");
876 tcc_define_symbol(s, "__ILP32__", NULL);
877 #endif
879 #ifdef TCC_TARGET_PE
880 tcc_define_symbol(s, "__WCHAR_TYPE__", "unsigned short");
881 tcc_define_symbol(s, "__WINT_TYPE__", "unsigned short");
882 #else
883 tcc_define_symbol(s, "__WCHAR_TYPE__", "int");
884 /* wint_t is unsigned int by default, but (signed) int on BSDs
885 and unsigned short on windows. Other OSes might have still
886 other conventions, sigh. */
887 # if defined(__FreeBSD__) || defined (__FreeBSD_kernel__) \
888 || defined(__NetBSD__) || defined(__OpenBSD__)
889 tcc_define_symbol(s, "__WINT_TYPE__", "int");
890 # ifdef __FreeBSD__
891 /* define __GNUC__ to have some useful stuff from sys/cdefs.h
892 that are unconditionally used in FreeBSDs other system headers :/ */
893 tcc_define_symbol(s, "__GNUC__", "2");
894 tcc_define_symbol(s, "__GNUC_MINOR__", "7");
895 tcc_define_symbol(s, "__builtin_alloca", "alloca");
896 # endif
897 # else
898 tcc_define_symbol(s, "__WINT_TYPE__", "unsigned int");
899 /* glibc defines */
900 tcc_define_symbol(s, "__REDIRECT(name, proto, alias)",
901 "name proto __asm__ (#alias)");
902 tcc_define_symbol(s, "__REDIRECT_NTH(name, proto, alias)",
903 "name proto __asm__ (#alias) __THROW");
904 # endif
905 #endif /* ndef TCC_TARGET_PE */
907 /* Some GCC builtins that are simple to express as macros. */
908 tcc_define_symbol(s, "__builtin_extract_return_addr(x)", "x");
910 return s;
913 LIBTCCAPI void tcc_delete(TCCState *s1)
915 int bench = s1->do_bench;
917 tcc_cleanup();
919 /* free sections */
920 tccelf_delete(s1);
922 /* free library paths */
923 dynarray_reset(&s1->library_paths, &s1->nb_library_paths);
924 dynarray_reset(&s1->crt_paths, &s1->nb_crt_paths);
926 /* free include paths */
927 dynarray_reset(&s1->cached_includes, &s1->nb_cached_includes);
928 dynarray_reset(&s1->include_paths, &s1->nb_include_paths);
929 dynarray_reset(&s1->sysinclude_paths, &s1->nb_sysinclude_paths);
931 tcc_free(s1->tcc_lib_path);
932 tcc_free(s1->soname);
933 tcc_free(s1->rpath);
934 tcc_free(s1->init_symbol);
935 tcc_free(s1->fini_symbol);
936 tcc_free(s1->outfile);
937 tcc_free(s1->deps_outfile);
938 dynarray_reset(&s1->files, &s1->nb_files);
939 dynarray_reset(&s1->target_deps, &s1->nb_target_deps);
940 dynarray_reset(&s1->pragma_libs, &s1->nb_pragma_libs);
942 #ifdef TCC_IS_NATIVE
943 /* free runtime memory */
944 tcc_run_free(s1);
945 #endif
947 tcc_free(s1);
948 tcc_memstats(bench);
951 LIBTCCAPI int tcc_set_output_type(TCCState *s, int output_type)
953 s->output_type = output_type;
955 /* always elf for objects */
956 if (output_type == TCC_OUTPUT_OBJ)
957 s->output_format = TCC_OUTPUT_FORMAT_ELF;
959 if (s->char_is_unsigned)
960 tcc_define_symbol(s, "__CHAR_UNSIGNED__", NULL);
962 if (!s->nostdinc) {
963 /* default include paths */
964 /* -isystem paths have already been handled */
965 tcc_add_sysinclude_path(s, CONFIG_TCC_SYSINCLUDEPATHS);
968 #ifdef CONFIG_TCC_BCHECK
969 if (s->do_bounds_check) {
970 /* if bound checking, then add corresponding sections */
971 tccelf_bounds_new(s);
972 /* define symbol */
973 tcc_define_symbol(s, "__BOUNDS_CHECKING_ON", NULL);
975 #endif
976 if (s->do_debug) {
977 /* add debug sections */
978 tccelf_stab_new(s);
981 tcc_add_library_path(s, CONFIG_TCC_LIBPATHS);
983 #ifdef TCC_TARGET_PE
984 # ifdef _WIN32
985 if (!s->nostdlib && output_type != TCC_OUTPUT_OBJ)
986 tcc_add_systemdir(s);
987 # endif
988 #else
989 /* paths for crt objects */
990 tcc_split_path(s, (void ***)&s->crt_paths, &s->nb_crt_paths, CONFIG_TCC_CRTPREFIX);
991 /* add libc crt1/crti objects */
992 if ((output_type == TCC_OUTPUT_EXE || output_type == TCC_OUTPUT_DLL) &&
993 !s->nostdlib) {
994 if (output_type != TCC_OUTPUT_DLL)
995 tcc_add_crt(s, "crt1.o");
996 tcc_add_crt(s, "crti.o");
998 #endif
999 return 0;
1002 LIBTCCAPI int tcc_add_include_path(TCCState *s, const char *pathname)
1004 tcc_split_path(s, (void ***)&s->include_paths, &s->nb_include_paths, pathname);
1005 return 0;
1008 LIBTCCAPI int tcc_add_sysinclude_path(TCCState *s, const char *pathname)
1010 tcc_split_path(s, (void ***)&s->sysinclude_paths, &s->nb_sysinclude_paths, pathname);
1011 return 0;
1014 ST_FUNC int tcc_add_file_internal(TCCState *s1, const char *filename, int flags)
1016 int ret, filetype;
1018 filetype = flags & 0x0F;
1019 if (filetype == 0) {
1020 /* use a file extension to detect a filetype */
1021 const char *ext = tcc_fileextension(filename);
1022 if (ext[0]) {
1023 ext++;
1024 if (!strcmp(ext, "S"))
1025 filetype = AFF_TYPE_ASMPP;
1026 else if (!strcmp(ext, "s"))
1027 filetype = AFF_TYPE_ASM;
1028 else if (!PATHCMP(ext, "c") || !PATHCMP(ext, "i"))
1029 filetype = AFF_TYPE_C;
1030 else
1031 filetype = AFF_TYPE_BIN;
1032 } else {
1033 filetype = AFF_TYPE_C;
1037 /* open the file */
1038 ret = tcc_open(s1, filename);
1039 if (ret < 0) {
1040 if (flags & AFF_PRINT_ERROR)
1041 tcc_error_noabort("file '%s' not found", filename);
1042 return ret;
1045 /* update target deps */
1046 dynarray_add((void ***)&s1->target_deps, &s1->nb_target_deps,
1047 tcc_strdup(filename));
1049 parse_flags = 0;
1050 /* if .S file, define __ASSEMBLER__ like gcc does */
1051 if (filetype == AFF_TYPE_ASM || filetype == AFF_TYPE_ASMPP) {
1052 tcc_define_symbol(s1, "__ASSEMBLER__", NULL);
1053 parse_flags = PARSE_FLAG_ASM_FILE;
1056 if (flags & AFF_PREPROCESS) {
1057 ret = tcc_preprocess(s1);
1058 } else if (filetype == AFF_TYPE_C) {
1059 ret = tcc_compile(s1);
1060 #ifdef CONFIG_TCC_ASM
1061 } else if (filetype == AFF_TYPE_ASMPP) {
1062 /* non preprocessed assembler */
1063 ret = tcc_assemble(s1, 1);
1064 } else if (filetype == AFF_TYPE_ASM) {
1065 /* preprocessed assembler */
1066 ret = tcc_assemble(s1, 0);
1067 #endif
1068 } else {
1069 ElfW(Ehdr) ehdr;
1070 int fd, obj_type;
1072 fd = file->fd;
1073 obj_type = tcc_object_type(fd, &ehdr);
1074 lseek(fd, 0, SEEK_SET);
1076 /* do not display line number if error */
1077 file->line_num = 0;
1079 switch (obj_type) {
1080 case AFF_BINTYPE_REL:
1081 ret = tcc_load_object_file(s1, fd, 0);
1082 break;
1083 #ifndef TCC_TARGET_PE
1084 case AFF_BINTYPE_DYN:
1085 if (s1->output_type == TCC_OUTPUT_MEMORY) {
1086 ret = 0;
1087 #ifdef TCC_IS_NATIVE
1088 if (NULL == dlopen(filename, RTLD_GLOBAL | RTLD_LAZY))
1089 ret = -1;
1090 #endif
1091 } else {
1092 ret = tcc_load_dll(s1, fd, filename,
1093 (flags & AFF_REFERENCED_DLL) != 0);
1095 break;
1096 #endif
1097 case AFF_BINTYPE_AR:
1098 ret = tcc_load_archive(s1, fd);
1099 break;
1100 #ifdef TCC_TARGET_COFF
1101 case AFF_BINTYPE_C67:
1102 ret = tcc_load_coff(s1, fd);
1103 break;
1104 #endif
1105 default:
1106 #ifdef TCC_TARGET_PE
1107 ret = pe_load_file(s1, filename, fd);
1108 #else
1109 /* as GNU ld, consider it is an ld script if not recognized */
1110 ret = tcc_load_ldscript(s1);
1111 #endif
1112 if (ret < 0)
1113 tcc_error_noabort("unrecognized file type");
1114 break;
1117 tcc_close();
1118 return ret;
1121 LIBTCCAPI int tcc_add_file(TCCState *s, const char *filename)
1123 if (s->output_type == TCC_OUTPUT_PREPROCESS)
1124 return tcc_add_file_internal(s, filename, AFF_PRINT_ERROR | AFF_PREPROCESS | s->filetype);
1125 else
1126 return tcc_add_file_internal(s, filename, AFF_PRINT_ERROR | s->filetype);
1129 LIBTCCAPI int tcc_add_library_path(TCCState *s, const char *pathname)
1131 tcc_split_path(s, (void ***)&s->library_paths, &s->nb_library_paths, pathname);
1132 return 0;
1135 static int tcc_add_library_internal(TCCState *s, const char *fmt,
1136 const char *filename, int flags, char **paths, int nb_paths)
1138 char buf[1024];
1139 int i;
1141 for(i = 0; i < nb_paths; i++) {
1142 snprintf(buf, sizeof(buf), fmt, paths[i], filename);
1143 if (tcc_add_file_internal(s, buf, flags | AFF_TYPE_BIN) == 0)
1144 return 0;
1146 return -1;
1149 #ifndef TCC_TARGET_PE
1150 /* find and load a dll. Return non zero if not found */
1151 /* XXX: add '-rpath' option support ? */
1152 ST_FUNC int tcc_add_dll(TCCState *s, const char *filename, int flags)
1154 return tcc_add_library_internal(s, "%s/%s", filename, flags,
1155 s->library_paths, s->nb_library_paths);
1157 #endif
1159 ST_FUNC int tcc_add_crt(TCCState *s, const char *filename)
1161 if (-1 == tcc_add_library_internal(s, "%s/%s",
1162 filename, 0, s->crt_paths, s->nb_crt_paths))
1163 tcc_error_noabort("file '%s' not found", filename);
1164 return 0;
1167 /* the library name is the same as the argument of the '-l' option */
1168 LIBTCCAPI int tcc_add_library(TCCState *s, const char *libraryname)
1170 #ifdef TCC_TARGET_PE
1171 const char *libs[] = { "%s/%s.def", "%s/lib%s.def", "%s/%s.dll", "%s/lib%s.dll", "%s/lib%s.a", NULL };
1172 const char **pp = s->static_link ? libs + 4 : libs;
1173 #else
1174 const char *libs[] = { "%s/lib%s.so", "%s/lib%s.a", NULL };
1175 const char **pp = s->static_link ? libs + 1 : libs;
1176 #endif
1177 while (*pp) {
1178 if (0 == tcc_add_library_internal(s, *pp,
1179 libraryname, 0, s->library_paths, s->nb_library_paths))
1180 return 0;
1181 ++pp;
1183 return -1;
1186 PUB_FUNC int tcc_add_library_err(TCCState *s, const char *libname)
1188 int ret = tcc_add_library(s, libname);
1189 if (ret < 0)
1190 tcc_error_noabort("library 'lib%s' not found", libname);
1191 return ret;
1194 /* habdle #pragma comment(lib,) */
1195 ST_FUNC void tcc_add_pragma_libs(TCCState *s1)
1197 int i;
1198 for (i = 0; i < s1->nb_pragma_libs; i++)
1199 tcc_add_library_err(s1, s1->pragma_libs[i]);
1202 LIBTCCAPI int tcc_add_symbol(TCCState *s, const char *name, const void *val)
1204 #ifdef TCC_TARGET_PE
1205 /* On x86_64 'val' might not be reachable with a 32bit offset.
1206 So it is handled here as if it were in a DLL. */
1207 pe_putimport(s, 0, name, (uintptr_t)val);
1208 #else
1209 set_elf_sym(symtab_section, (uintptr_t)val, 0,
1210 ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE), 0,
1211 SHN_ABS, name);
1212 #endif
1213 return 0;
1216 LIBTCCAPI void tcc_set_lib_path(TCCState *s, const char *path)
1218 tcc_free(s->tcc_lib_path);
1219 s->tcc_lib_path = tcc_strdup(path);
1222 #define WD_ALL 0x0001 /* warning is activated when using -Wall */
1223 #define FD_INVERT 0x0002 /* invert value before storing */
1225 typedef struct FlagDef {
1226 uint16_t offset;
1227 uint16_t flags;
1228 const char *name;
1229 } FlagDef;
1231 static const FlagDef warning_defs[] = {
1232 { offsetof(TCCState, warn_unsupported), 0, "unsupported" },
1233 { offsetof(TCCState, warn_write_strings), 0, "write-strings" },
1234 { offsetof(TCCState, warn_error), 0, "error" },
1235 { offsetof(TCCState, warn_implicit_function_declaration), WD_ALL,
1236 "implicit-function-declaration" },
1239 static int no_flag(const char **pp)
1241 const char *p = *pp;
1242 if (*p != 'n' || *++p != 'o' || *++p != '-')
1243 return 0;
1244 *pp = p + 1;
1245 return 1;
1248 ST_FUNC int set_flag(TCCState *s, const FlagDef *flags, int nb_flags,
1249 const char *name, int value)
1251 int i;
1252 const FlagDef *p;
1253 const char *r;
1255 r = name;
1256 if (no_flag(&r))
1257 value = !value;
1259 for(i = 0, p = flags; i < nb_flags; i++, p++) {
1260 if (!strcmp(r, p->name))
1261 goto found;
1263 return -1;
1264 found:
1265 if (p->flags & FD_INVERT)
1266 value = !value;
1267 *(int *)((uint8_t *)s + p->offset) = value;
1268 return 0;
1271 /* set/reset a warning */
1272 static int tcc_set_warning(TCCState *s, const char *warning_name, int value)
1274 int i;
1275 const FlagDef *p;
1277 if (!strcmp(warning_name, "all")) {
1278 for(i = 0, p = warning_defs; i < countof(warning_defs); i++, p++) {
1279 if (p->flags & WD_ALL)
1280 *(int *)((uint8_t *)s + p->offset) = 1;
1282 return 0;
1283 } else {
1284 return set_flag(s, warning_defs, countof(warning_defs),
1285 warning_name, value);
1289 static const FlagDef flag_defs[] = {
1290 { offsetof(TCCState, char_is_unsigned), 0, "unsigned-char" },
1291 { offsetof(TCCState, char_is_unsigned), FD_INVERT, "signed-char" },
1292 { offsetof(TCCState, nocommon), FD_INVERT, "common" },
1293 { offsetof(TCCState, leading_underscore), 0, "leading-underscore" },
1294 { offsetof(TCCState, ms_extensions), 0, "ms-extensions" },
1295 { offsetof(TCCState, old_struct_init_code), 0, "old-struct-init-code" },
1296 { offsetof(TCCState, dollars_in_identifiers), 0, "dollars-in-identifiers" },
1299 /* set/reset a flag */
1300 static int tcc_set_flag(TCCState *s, const char *flag_name, int value)
1302 return set_flag(s, flag_defs, countof(flag_defs),
1303 flag_name, value);
1306 static const FlagDef m_defs[] = {
1307 #ifdef TCC_TARGET_X86_64
1308 { offsetof(TCCState, nosse), FD_INVERT, "sse" },
1309 #endif
1310 { 0, 0, " no flag" },
1312 static int tcc_set_m_flag(TCCState *s, const char *flag_name, int value)
1314 return set_flag(s, m_defs, countof(m_defs), flag_name, value);
1317 static int strstart(const char *val, const char **str)
1319 const char *p, *q;
1320 p = *str;
1321 q = val;
1322 while (*q) {
1323 if (*p != *q)
1324 return 0;
1325 p++;
1326 q++;
1328 *str = p;
1329 return 1;
1332 /* Like strstart, but automatically takes into account that ld options can
1334 * - start with double or single dash (e.g. '--soname' or '-soname')
1335 * - arguments can be given as separate or after '=' (e.g. '-Wl,-soname,x.so'
1336 * or '-Wl,-soname=x.so')
1338 * you provide `val` always in 'option[=]' form (no leading -)
1340 static int link_option(const char *str, const char *val, const char **ptr)
1342 const char *p, *q;
1343 int ret;
1345 /* there should be 1 or 2 dashes */
1346 if (*str++ != '-')
1347 return 0;
1348 if (*str == '-')
1349 str++;
1351 /* then str & val should match (potentialy up to '=') */
1352 p = str;
1353 q = val;
1355 ret = 1;
1356 if (q[0] == '?') {
1357 ++q;
1358 if (no_flag(&p))
1359 ret = -1;
1362 while (*q != '\0' && *q != '=') {
1363 if (*p != *q)
1364 return 0;
1365 p++;
1366 q++;
1369 /* '=' near eos means ',' or '=' is ok */
1370 if (*q == '=') {
1371 if (*p == 0)
1372 *ptr = p;
1373 if (*p != ',' && *p != '=')
1374 return 0;
1375 p++;
1377 *ptr = p;
1378 return ret;
1381 static const char *skip_linker_arg(const char **str)
1383 const char *s1 = *str;
1384 const char *s2 = strchr(s1, ',');
1385 *str = s2 ? s2++ : (s2 = s1 + strlen(s1));
1386 return s2;
1389 static char *copy_linker_arg(const char *p)
1391 const char *q = p;
1392 skip_linker_arg(&q);
1393 return pstrncpy(tcc_malloc(q - p + 1), p, q - p);
1396 /* set linker options */
1397 static int tcc_set_linker(TCCState *s, const char *option)
1399 while (*option) {
1401 const char *p = NULL;
1402 char *end = NULL;
1403 int ignoring = 0;
1404 int ret;
1406 if (link_option(option, "Bsymbolic", &p)) {
1407 s->symbolic = 1;
1408 } else if (link_option(option, "nostdlib", &p)) {
1409 s->nostdlib = 1;
1410 } else if (link_option(option, "fini=", &p)) {
1411 s->fini_symbol = copy_linker_arg(p);
1412 ignoring = 1;
1413 } else if (link_option(option, "image-base=", &p)
1414 || link_option(option, "Ttext=", &p)) {
1415 s->text_addr = strtoull(p, &end, 16);
1416 s->has_text_addr = 1;
1417 } else if (link_option(option, "init=", &p)) {
1418 s->init_symbol = copy_linker_arg(p);
1419 ignoring = 1;
1420 } else if (link_option(option, "oformat=", &p)) {
1421 #if defined(TCC_TARGET_PE)
1422 if (strstart("pe-", &p)) {
1423 #elif defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
1424 if (strstart("elf64-", &p)) {
1425 #else
1426 if (strstart("elf32-", &p)) {
1427 #endif
1428 s->output_format = TCC_OUTPUT_FORMAT_ELF;
1429 } else if (!strcmp(p, "binary")) {
1430 s->output_format = TCC_OUTPUT_FORMAT_BINARY;
1431 #ifdef TCC_TARGET_COFF
1432 } else if (!strcmp(p, "coff")) {
1433 s->output_format = TCC_OUTPUT_FORMAT_COFF;
1434 #endif
1435 } else
1436 goto err;
1438 } else if (link_option(option, "as-needed", &p)) {
1439 ignoring = 1;
1440 } else if (link_option(option, "O", &p)) {
1441 ignoring = 1;
1442 } else if (link_option(option, "rpath=", &p)) {
1443 s->rpath = copy_linker_arg(p);
1444 } else if (link_option(option, "section-alignment=", &p)) {
1445 s->section_align = strtoul(p, &end, 16);
1446 } else if (link_option(option, "soname=", &p)) {
1447 s->soname = copy_linker_arg(p);
1448 #ifdef TCC_TARGET_PE
1449 } else if (link_option(option, "file-alignment=", &p)) {
1450 s->pe_file_align = strtoul(p, &end, 16);
1451 } else if (link_option(option, "stack=", &p)) {
1452 s->pe_stack_size = strtoul(p, &end, 10);
1453 } else if (link_option(option, "subsystem=", &p)) {
1454 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
1455 if (!strcmp(p, "native")) {
1456 s->pe_subsystem = 1;
1457 } else if (!strcmp(p, "console")) {
1458 s->pe_subsystem = 3;
1459 } else if (!strcmp(p, "gui")) {
1460 s->pe_subsystem = 2;
1461 } else if (!strcmp(p, "posix")) {
1462 s->pe_subsystem = 7;
1463 } else if (!strcmp(p, "efiapp")) {
1464 s->pe_subsystem = 10;
1465 } else if (!strcmp(p, "efiboot")) {
1466 s->pe_subsystem = 11;
1467 } else if (!strcmp(p, "efiruntime")) {
1468 s->pe_subsystem = 12;
1469 } else if (!strcmp(p, "efirom")) {
1470 s->pe_subsystem = 13;
1471 #elif defined(TCC_TARGET_ARM)
1472 if (!strcmp(p, "wince")) {
1473 s->pe_subsystem = 9;
1474 #endif
1475 } else
1476 goto err;
1477 #endif
1478 } else if (ret = link_option(option, "?whole-archive", &p), ret) {
1479 s->alacarte_link = ret < 0;
1480 } else if (p) {
1481 return 0;
1482 } else {
1483 err:
1484 tcc_error("unsupported linker option '%s'", option);
1487 if (ignoring && s->warn_unsupported)
1488 tcc_warning("unsupported linker option '%s'", option);
1490 option = skip_linker_arg(&p);
1492 return 1;
1495 typedef struct TCCOption {
1496 const char *name;
1497 uint16_t index;
1498 uint16_t flags;
1499 } TCCOption;
1501 enum {
1502 TCC_OPTION_HELP,
1503 TCC_OPTION_I,
1504 TCC_OPTION_D,
1505 TCC_OPTION_U,
1506 TCC_OPTION_P,
1507 TCC_OPTION_L,
1508 TCC_OPTION_B,
1509 TCC_OPTION_l,
1510 TCC_OPTION_bench,
1511 TCC_OPTION_bt,
1512 TCC_OPTION_b,
1513 TCC_OPTION_g,
1514 TCC_OPTION_c,
1515 TCC_OPTION_dumpversion,
1516 TCC_OPTION_d,
1517 TCC_OPTION_float_abi,
1518 TCC_OPTION_static,
1519 TCC_OPTION_std,
1520 TCC_OPTION_shared,
1521 TCC_OPTION_soname,
1522 TCC_OPTION_o,
1523 TCC_OPTION_r,
1524 TCC_OPTION_s,
1525 TCC_OPTION_traditional,
1526 TCC_OPTION_Wl,
1527 TCC_OPTION_Wp,
1528 TCC_OPTION_W,
1529 TCC_OPTION_O,
1530 TCC_OPTION_mms_bitfields,
1531 TCC_OPTION_m,
1532 TCC_OPTION_f,
1533 TCC_OPTION_isystem,
1534 TCC_OPTION_iwithprefix,
1535 TCC_OPTION_include,
1536 TCC_OPTION_nostdinc,
1537 TCC_OPTION_nostdlib,
1538 TCC_OPTION_print_search_dirs,
1539 TCC_OPTION_rdynamic,
1540 TCC_OPTION_param,
1541 TCC_OPTION_pedantic,
1542 TCC_OPTION_pthread,
1543 TCC_OPTION_run,
1544 TCC_OPTION_v,
1545 TCC_OPTION_w,
1546 TCC_OPTION_pipe,
1547 TCC_OPTION_E,
1548 TCC_OPTION_MD,
1549 TCC_OPTION_MF,
1550 TCC_OPTION_x
1553 #define TCC_OPTION_HAS_ARG 0x0001
1554 #define TCC_OPTION_NOSEP 0x0002 /* cannot have space before option and arg */
1556 static const TCCOption tcc_options[] = {
1557 { "h", TCC_OPTION_HELP, 0 },
1558 { "-help", TCC_OPTION_HELP, 0 },
1559 { "?", TCC_OPTION_HELP, 0 },
1560 { "I", TCC_OPTION_I, TCC_OPTION_HAS_ARG },
1561 { "D", TCC_OPTION_D, TCC_OPTION_HAS_ARG },
1562 { "U", TCC_OPTION_U, TCC_OPTION_HAS_ARG },
1563 { "P", TCC_OPTION_P, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1564 { "L", TCC_OPTION_L, TCC_OPTION_HAS_ARG },
1565 { "B", TCC_OPTION_B, TCC_OPTION_HAS_ARG },
1566 { "l", TCC_OPTION_l, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1567 { "bench", TCC_OPTION_bench, 0 },
1568 #ifdef CONFIG_TCC_BACKTRACE
1569 { "bt", TCC_OPTION_bt, TCC_OPTION_HAS_ARG },
1570 #endif
1571 #ifdef CONFIG_TCC_BCHECK
1572 { "b", TCC_OPTION_b, 0 },
1573 #endif
1574 { "g", TCC_OPTION_g, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1575 { "c", TCC_OPTION_c, 0 },
1576 { "dumpversion", TCC_OPTION_dumpversion, 0},
1577 { "d", TCC_OPTION_d, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1578 #ifdef TCC_TARGET_ARM
1579 { "mfloat-abi", TCC_OPTION_float_abi, TCC_OPTION_HAS_ARG },
1580 #endif
1581 { "static", TCC_OPTION_static, 0 },
1582 { "std", TCC_OPTION_std, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1583 { "shared", TCC_OPTION_shared, 0 },
1584 { "soname", TCC_OPTION_soname, TCC_OPTION_HAS_ARG },
1585 { "o", TCC_OPTION_o, TCC_OPTION_HAS_ARG },
1586 { "-param", TCC_OPTION_param, TCC_OPTION_HAS_ARG },
1587 { "pedantic", TCC_OPTION_pedantic, 0},
1588 { "pthread", TCC_OPTION_pthread, 0},
1589 { "run", TCC_OPTION_run, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1590 { "rdynamic", TCC_OPTION_rdynamic, 0 },
1591 { "r", TCC_OPTION_r, 0 },
1592 { "s", TCC_OPTION_s, 0 },
1593 { "traditional", TCC_OPTION_traditional, 0 },
1594 { "Wl,", TCC_OPTION_Wl, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1595 { "Wp,", TCC_OPTION_Wp, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1596 { "W", TCC_OPTION_W, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1597 { "O", TCC_OPTION_O, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1598 { "mms-bitfields", TCC_OPTION_mms_bitfields, 0}, /* must go before option 'm' */
1599 { "m", TCC_OPTION_m, TCC_OPTION_HAS_ARG },
1600 { "f", TCC_OPTION_f, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1601 { "isystem", TCC_OPTION_isystem, TCC_OPTION_HAS_ARG },
1602 { "iwithprefix", TCC_OPTION_iwithprefix, TCC_OPTION_HAS_ARG },
1603 { "include", TCC_OPTION_include, TCC_OPTION_HAS_ARG },
1604 { "nostdinc", TCC_OPTION_nostdinc, 0 },
1605 { "nostdlib", TCC_OPTION_nostdlib, 0 },
1606 { "print-search-dirs", TCC_OPTION_print_search_dirs, 0 },
1607 { "v", TCC_OPTION_v, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1608 { "w", TCC_OPTION_w, 0 },
1609 { "pipe", TCC_OPTION_pipe, 0},
1610 { "E", TCC_OPTION_E, 0},
1611 { "MD", TCC_OPTION_MD, 0},
1612 { "MF", TCC_OPTION_MF, TCC_OPTION_HAS_ARG },
1613 { "x", TCC_OPTION_x, TCC_OPTION_HAS_ARG },
1614 { NULL, 0, 0 },
1617 static void parse_option_D(TCCState *s1, const char *optarg)
1619 char *sym = tcc_strdup(optarg);
1620 char *value = strchr(sym, '=');
1621 if (value)
1622 *value++ = '\0';
1623 tcc_define_symbol(s1, sym, value);
1624 tcc_free(sym);
1627 static void args_parser_add_file(TCCState *s, const char* filename, int filetype)
1629 struct filespec *f = tcc_malloc(sizeof *f + strlen(filename));
1630 f->type = filetype;
1631 strcpy(f->name, filename);
1632 dynarray_add((void ***)&s->files, &s->nb_files, f);
1635 /* read list file */
1636 static void args_parser_listfile(TCCState *s, const char *filename)
1638 int fd;
1639 size_t len;
1640 char *p;
1642 fd = open(filename, O_RDONLY | O_BINARY);
1643 if (fd < 0)
1644 tcc_error("file '%s' not found", filename);
1646 len = lseek(fd, 0, SEEK_END);
1647 p = tcc_malloc(len + 1), p[len] = 0;
1648 lseek(fd, 0, SEEK_SET), read(fd, p, len), close(fd);
1649 tcc_set_options(s, p);
1650 tcc_free(p);
1653 PUB_FUNC int tcc_parse_args(TCCState *s, int argc, char **argv)
1655 const TCCOption *popt;
1656 const char *optarg, *r;
1657 int optind = 0;
1658 int run = 0;
1659 int x;
1660 int last_o = -1;
1661 CString linker_arg; /* collect -Wl options */
1662 char buf[1024];
1664 cstr_new(&linker_arg);
1666 while (optind < argc) {
1668 r = argv[optind++];
1670 reparse:
1671 if (r[0] == '@' && r[1] != '\0') {
1672 args_parser_listfile(s, r + 1);
1673 continue;
1676 if (r[0] != '-' || r[1] == '\0') {
1677 args_parser_add_file(s, r, s->filetype);
1678 if (run) {
1679 optind--;
1680 /* argv[0] will be this file */
1681 break;
1683 continue;
1686 /* find option in table */
1687 for(popt = tcc_options; ; ++popt) {
1688 const char *p1 = popt->name;
1689 const char *r1 = r + 1;
1690 if (p1 == NULL)
1691 tcc_error("invalid option -- '%s'", r);
1692 if (!strstart(p1, &r1))
1693 continue;
1694 optarg = r1;
1695 if (popt->flags & TCC_OPTION_HAS_ARG) {
1696 if (*r1 == '\0' && !(popt->flags & TCC_OPTION_NOSEP)) {
1697 if (optind >= argc)
1698 arg_err:
1699 tcc_error("argument to '%s' is missing", r);
1700 optarg = argv[optind++];
1702 } else if (*r1 != '\0')
1703 continue;
1704 break;
1707 switch(popt->index) {
1708 case TCC_OPTION_HELP:
1709 return 0;
1710 case TCC_OPTION_I:
1711 tcc_add_include_path(s, optarg);
1712 break;
1713 case TCC_OPTION_D:
1714 parse_option_D(s, optarg);
1715 break;
1716 case TCC_OPTION_U:
1717 tcc_undefine_symbol(s, optarg);
1718 break;
1719 case TCC_OPTION_L:
1720 tcc_add_library_path(s, optarg);
1721 break;
1722 case TCC_OPTION_B:
1723 /* set tcc utilities path (mainly for tcc development) */
1724 tcc_set_lib_path(s, optarg);
1725 break;
1726 case TCC_OPTION_l:
1727 args_parser_add_file(s, optarg, AFF_TYPE_LIBWH - s->alacarte_link);
1728 s->nb_libraries++;
1729 break;
1730 case TCC_OPTION_pthread:
1731 parse_option_D(s, "_REENTRANT");
1732 s->option_pthread = 1;
1733 break;
1734 case TCC_OPTION_bench:
1735 s->do_bench = 1;
1736 break;
1737 #ifdef CONFIG_TCC_BACKTRACE
1738 case TCC_OPTION_bt:
1739 tcc_set_num_callers(atoi(optarg));
1740 break;
1741 #endif
1742 #ifdef CONFIG_TCC_BCHECK
1743 case TCC_OPTION_b:
1744 s->do_bounds_check = 1;
1745 s->do_debug = 1;
1746 break;
1747 #endif
1748 case TCC_OPTION_g:
1749 s->do_debug = 1;
1750 break;
1751 case TCC_OPTION_c:
1752 x = TCC_OUTPUT_OBJ;
1753 set_output_type:
1754 if (s->output_type)
1755 tcc_warning("-%s: overriding compiler action already specified", popt->name);
1756 s->output_type = x;
1757 break;
1758 case TCC_OPTION_d:
1759 if (*optarg == 'D')
1760 s->dflag = 3;
1761 else if (*optarg == 'M')
1762 s->dflag = 7;
1763 else
1764 goto unsupported_option;
1765 break;
1766 #ifdef TCC_TARGET_ARM
1767 case TCC_OPTION_float_abi:
1768 /* tcc doesn't support soft float yet */
1769 if (!strcmp(optarg, "softfp")) {
1770 s->float_abi = ARM_SOFTFP_FLOAT;
1771 tcc_undefine_symbol(s, "__ARM_PCS_VFP");
1772 } else if (!strcmp(optarg, "hard"))
1773 s->float_abi = ARM_HARD_FLOAT;
1774 else
1775 tcc_error("unsupported float abi '%s'", optarg);
1776 break;
1777 #endif
1778 case TCC_OPTION_static:
1779 s->static_link = 1;
1780 break;
1781 case TCC_OPTION_std:
1782 /* silently ignore, a current purpose:
1783 allow to use a tcc as a reference compiler for "make test" */
1784 break;
1785 case TCC_OPTION_shared:
1786 x = TCC_OUTPUT_DLL;
1787 goto set_output_type;
1788 case TCC_OPTION_soname:
1789 s->soname = tcc_strdup(optarg);
1790 break;
1791 case TCC_OPTION_m:
1792 if (!strcmp(optarg, "32") || !strcmp(optarg, "64"))
1793 s->option_m = tcc_strdup(optarg);
1794 else if (tcc_set_m_flag(s, optarg, 1) < 0)
1795 goto unsupported_option;
1796 break;
1797 case TCC_OPTION_o:
1798 if (s->outfile) {
1799 tcc_warning("multiple -o option");
1800 tcc_free(s->outfile);
1802 s->outfile = tcc_strdup(optarg);
1803 break;
1804 case TCC_OPTION_r:
1805 /* generate a .o merging several output files */
1806 s->option_r = 1;
1807 x = TCC_OUTPUT_OBJ;
1808 goto set_output_type;
1809 case TCC_OPTION_isystem:
1810 tcc_add_sysinclude_path(s, optarg);
1811 break;
1812 case TCC_OPTION_iwithprefix:
1813 snprintf(buf, sizeof buf, "{B}/%s", optarg);
1814 tcc_add_sysinclude_path(s, buf);
1815 break;
1816 case TCC_OPTION_include:
1817 dynarray_add((void ***)&s->cmd_include_files,
1818 &s->nb_cmd_include_files, tcc_strdup(optarg));
1819 break;
1820 case TCC_OPTION_nostdinc:
1821 s->nostdinc = 1;
1822 break;
1823 case TCC_OPTION_nostdlib:
1824 s->nostdlib = 1;
1825 break;
1826 case TCC_OPTION_print_search_dirs:
1827 s->print_search_dirs = 1;
1828 break;
1829 case TCC_OPTION_run:
1830 #ifndef TCC_IS_NATIVE
1831 tcc_error("-run is not available in a cross compiler");
1832 #endif
1833 tcc_set_options(s, optarg);
1834 run = 1;
1835 x = TCC_OUTPUT_MEMORY;
1836 goto set_output_type;
1837 case TCC_OPTION_v:
1838 do ++s->verbose; while (*optarg++ == 'v');
1839 break;
1840 case TCC_OPTION_f:
1841 if (tcc_set_flag(s, optarg, 1) < 0)
1842 goto unsupported_option;
1843 break;
1844 case TCC_OPTION_W:
1845 if (tcc_set_warning(s, optarg, 1) < 0)
1846 goto unsupported_option;
1847 break;
1848 case TCC_OPTION_w:
1849 s->warn_none = 1;
1850 break;
1851 case TCC_OPTION_rdynamic:
1852 s->rdynamic = 1;
1853 break;
1854 case TCC_OPTION_Wl:
1855 if (linker_arg.size)
1856 --linker_arg.size, cstr_ccat(&linker_arg, ',');
1857 cstr_cat(&linker_arg, optarg, 0);
1858 if (tcc_set_linker(s, linker_arg.data))
1859 cstr_free(&linker_arg);
1860 break;
1861 case TCC_OPTION_Wp:
1862 r = optarg;
1863 goto reparse;
1864 case TCC_OPTION_E:
1865 x = TCC_OUTPUT_PREPROCESS;
1866 goto set_output_type;
1867 case TCC_OPTION_P:
1868 s->Pflag = atoi(optarg) + 1;
1869 break;
1870 case TCC_OPTION_MD:
1871 s->gen_deps = 1;
1872 break;
1873 case TCC_OPTION_MF:
1874 s->deps_outfile = tcc_strdup(optarg);
1875 break;
1876 case TCC_OPTION_dumpversion:
1877 printf ("%s\n", TCC_VERSION);
1878 exit(0);
1879 break;
1880 case TCC_OPTION_x:
1881 if (*optarg == 'c')
1882 s->filetype = AFF_TYPE_C;
1883 else if (*optarg == 'a')
1884 s->filetype = AFF_TYPE_ASMPP;
1885 else if (*optarg == 'n')
1886 s->filetype = AFF_TYPE_NONE;
1887 else
1888 tcc_warning("unsupported language '%s'", optarg);
1889 break;
1890 case TCC_OPTION_O:
1891 last_o = atoi(optarg);
1892 break;
1893 case TCC_OPTION_mms_bitfields:
1894 s->ms_bitfields = 1;
1895 break;
1896 case TCC_OPTION_traditional:
1897 case TCC_OPTION_pedantic:
1898 case TCC_OPTION_pipe:
1899 case TCC_OPTION_s:
1900 /* ignored */
1901 break;
1902 default:
1903 unsupported_option:
1904 if (s->warn_unsupported)
1905 tcc_warning("unsupported option '%s'", r);
1906 break;
1910 if (last_o > 0)
1911 tcc_define_symbol(s, "__OPTIMIZE__", NULL);
1913 if (linker_arg.size) {
1914 r = linker_arg.data;
1915 goto arg_err;
1918 return optind;
1921 LIBTCCAPI int tcc_set_options(TCCState *s, const char *r)
1923 char **argv;
1924 int argc;
1925 int ret, q, c;
1926 CString str;
1928 argc = 0, argv = NULL;
1929 for(;;) {
1930 while (c = (unsigned char)*r, c && c <= ' ')
1931 ++r;
1932 if (c == 0)
1933 break;
1934 q = 0;
1935 cstr_new(&str);
1936 while (c = (unsigned char)*r, c) {
1937 ++r;
1938 if (c == '\\' && (*r == '"' || *r == '\\')) {
1939 c = *r++;
1940 } else if (c == '"') {
1941 q = !q;
1942 continue;
1943 } else if (q == 0 && c <= ' ') {
1944 break;
1946 cstr_ccat(&str, c);
1948 cstr_ccat(&str, 0);
1949 //printf("<%s>\n", str.data), fflush(stdout);
1950 dynarray_add((void ***)&argv, &argc, tcc_strdup(str.data));
1951 cstr_free(&str);
1953 ret = tcc_parse_args(s, argc, argv);
1954 dynarray_reset(&argv, &argc);
1955 return ret;
1958 PUB_FUNC void tcc_print_stats(TCCState *s, unsigned total_time)
1960 if (total_time < 1)
1961 total_time = 1;
1962 if (total_bytes < 1)
1963 total_bytes = 1;
1964 fprintf(stderr, "%d idents, %d lines, %d bytes, %0.3f s, %u lines/s, %0.1f MB/s\n",
1965 tok_ident - TOK_IDENT, total_lines, total_bytes,
1966 (double)total_time/1000,
1967 (unsigned)total_lines*1000/total_time,
1968 (double)total_bytes/1000/total_time);
1971 PUB_FUNC void tcc_set_environment(TCCState *s)
1973 char * path;
1975 path = getenv("C_INCLUDE_PATH");
1976 if(path != NULL) {
1977 tcc_add_include_path(s, path);
1979 path = getenv("CPATH");
1980 if(path != NULL) {
1981 tcc_add_include_path(s, path);
1983 path = getenv("LIBRARY_PATH");
1984 if(path != NULL) {
1985 tcc_add_library_path(s, path);