x86-asm: Implement fxrstorq and fxsaveq
[tinycc.git] / libtcc.c
blobdac4bb90cd31690b2673b9241ea39c4bd109f861
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);
681 sym_pop(&local_stack, NULL);
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 return s;
910 LIBTCCAPI void tcc_delete(TCCState *s1)
912 int bench = s1->do_bench;
914 tcc_cleanup();
916 /* free sections */
917 tccelf_delete(s1);
919 /* free library paths */
920 dynarray_reset(&s1->library_paths, &s1->nb_library_paths);
921 dynarray_reset(&s1->crt_paths, &s1->nb_crt_paths);
923 /* free include paths */
924 dynarray_reset(&s1->cached_includes, &s1->nb_cached_includes);
925 dynarray_reset(&s1->include_paths, &s1->nb_include_paths);
926 dynarray_reset(&s1->sysinclude_paths, &s1->nb_sysinclude_paths);
928 tcc_free(s1->tcc_lib_path);
929 tcc_free(s1->soname);
930 tcc_free(s1->rpath);
931 tcc_free(s1->init_symbol);
932 tcc_free(s1->fini_symbol);
933 tcc_free(s1->outfile);
934 tcc_free(s1->deps_outfile);
935 dynarray_reset(&s1->files, &s1->nb_files);
936 dynarray_reset(&s1->target_deps, &s1->nb_target_deps);
937 dynarray_reset(&s1->pragma_libs, &s1->nb_pragma_libs);
939 #ifdef TCC_IS_NATIVE
940 /* free runtime memory */
941 tcc_run_free(s1);
942 #endif
944 tcc_free(s1);
945 tcc_memstats(bench);
948 LIBTCCAPI int tcc_set_output_type(TCCState *s, int output_type)
950 s->output_type = output_type;
952 /* always elf for objects */
953 if (output_type == TCC_OUTPUT_OBJ)
954 s->output_format = TCC_OUTPUT_FORMAT_ELF;
956 if (s->char_is_unsigned)
957 tcc_define_symbol(s, "__CHAR_UNSIGNED__", NULL);
959 if (!s->nostdinc) {
960 /* default include paths */
961 /* -isystem paths have already been handled */
962 tcc_add_sysinclude_path(s, CONFIG_TCC_SYSINCLUDEPATHS);
965 #ifdef CONFIG_TCC_BCHECK
966 if (s->do_bounds_check) {
967 /* if bound checking, then add corresponding sections */
968 tccelf_bounds_new(s);
969 /* define symbol */
970 tcc_define_symbol(s, "__BOUNDS_CHECKING_ON", NULL);
972 #endif
973 if (s->do_debug) {
974 /* add debug sections */
975 tccelf_stab_new(s);
978 tcc_add_library_path(s, CONFIG_TCC_LIBPATHS);
980 #ifdef TCC_TARGET_PE
981 # ifdef _WIN32
982 if (!s->nostdlib && output_type != TCC_OUTPUT_OBJ)
983 tcc_add_systemdir(s);
984 # endif
985 #else
986 /* paths for crt objects */
987 tcc_split_path(s, (void ***)&s->crt_paths, &s->nb_crt_paths, CONFIG_TCC_CRTPREFIX);
988 /* add libc crt1/crti objects */
989 if ((output_type == TCC_OUTPUT_EXE || output_type == TCC_OUTPUT_DLL) &&
990 !s->nostdlib) {
991 if (output_type != TCC_OUTPUT_DLL)
992 tcc_add_crt(s, "crt1.o");
993 tcc_add_crt(s, "crti.o");
995 #endif
996 return 0;
999 LIBTCCAPI int tcc_add_include_path(TCCState *s, const char *pathname)
1001 tcc_split_path(s, (void ***)&s->include_paths, &s->nb_include_paths, pathname);
1002 return 0;
1005 LIBTCCAPI int tcc_add_sysinclude_path(TCCState *s, const char *pathname)
1007 tcc_split_path(s, (void ***)&s->sysinclude_paths, &s->nb_sysinclude_paths, pathname);
1008 return 0;
1011 ST_FUNC int tcc_add_file_internal(TCCState *s1, const char *filename, int flags)
1013 int ret, filetype;
1015 filetype = flags & 0x0F;
1016 if (filetype == 0) {
1017 /* use a file extension to detect a filetype */
1018 const char *ext = tcc_fileextension(filename);
1019 if (ext[0]) {
1020 ext++;
1021 if (!strcmp(ext, "S"))
1022 filetype = AFF_TYPE_ASMPP;
1023 else if (!strcmp(ext, "s"))
1024 filetype = AFF_TYPE_ASM;
1025 else if (!PATHCMP(ext, "c") || !PATHCMP(ext, "i"))
1026 filetype = AFF_TYPE_C;
1027 else
1028 filetype = AFF_TYPE_BIN;
1029 } else {
1030 filetype = AFF_TYPE_C;
1034 /* open the file */
1035 ret = tcc_open(s1, filename);
1036 if (ret < 0) {
1037 if (flags & AFF_PRINT_ERROR)
1038 tcc_error_noabort("file '%s' not found", filename);
1039 return ret;
1042 /* update target deps */
1043 dynarray_add((void ***)&s1->target_deps, &s1->nb_target_deps,
1044 tcc_strdup(filename));
1046 parse_flags = 0;
1047 /* if .S file, define __ASSEMBLER__ like gcc does */
1048 if (filetype == AFF_TYPE_ASM || filetype == AFF_TYPE_ASMPP) {
1049 tcc_define_symbol(s1, "__ASSEMBLER__", NULL);
1050 parse_flags = PARSE_FLAG_ASM_FILE;
1053 if (flags & AFF_PREPROCESS) {
1054 ret = tcc_preprocess(s1);
1055 } else if (filetype == AFF_TYPE_C) {
1056 ret = tcc_compile(s1);
1057 #ifdef CONFIG_TCC_ASM
1058 } else if (filetype == AFF_TYPE_ASMPP) {
1059 /* non preprocessed assembler */
1060 ret = tcc_assemble(s1, 1);
1061 } else if (filetype == AFF_TYPE_ASM) {
1062 /* preprocessed assembler */
1063 ret = tcc_assemble(s1, 0);
1064 #endif
1065 } else {
1066 ElfW(Ehdr) ehdr;
1067 int fd, obj_type;
1069 fd = file->fd;
1070 obj_type = tcc_object_type(fd, &ehdr);
1071 lseek(fd, 0, SEEK_SET);
1073 /* do not display line number if error */
1074 file->line_num = 0;
1076 switch (obj_type) {
1077 case AFF_BINTYPE_REL:
1078 ret = tcc_load_object_file(s1, fd, 0);
1079 break;
1080 #ifndef TCC_TARGET_PE
1081 case AFF_BINTYPE_DYN:
1082 if (s1->output_type == TCC_OUTPUT_MEMORY) {
1083 ret = 0;
1084 #ifdef TCC_IS_NATIVE
1085 if (NULL == dlopen(filename, RTLD_GLOBAL | RTLD_LAZY))
1086 ret = -1;
1087 #endif
1088 } else {
1089 ret = tcc_load_dll(s1, fd, filename,
1090 (flags & AFF_REFERENCED_DLL) != 0);
1092 break;
1093 #endif
1094 case AFF_BINTYPE_AR:
1095 ret = tcc_load_archive(s1, fd);
1096 break;
1097 #ifdef TCC_TARGET_COFF
1098 case AFF_BINTYPE_C67:
1099 ret = tcc_load_coff(s1, fd);
1100 break;
1101 #endif
1102 default:
1103 #ifdef TCC_TARGET_PE
1104 ret = pe_load_file(s1, filename, fd);
1105 #else
1106 /* as GNU ld, consider it is an ld script if not recognized */
1107 ret = tcc_load_ldscript(s1);
1108 #endif
1109 if (ret < 0)
1110 tcc_error_noabort("unrecognized file type");
1111 break;
1114 tcc_close();
1115 return ret;
1118 LIBTCCAPI int tcc_add_file(TCCState *s, const char *filename)
1120 if (s->output_type == TCC_OUTPUT_PREPROCESS)
1121 return tcc_add_file_internal(s, filename, AFF_PRINT_ERROR | AFF_PREPROCESS | s->filetype);
1122 else
1123 return tcc_add_file_internal(s, filename, AFF_PRINT_ERROR | s->filetype);
1126 LIBTCCAPI int tcc_add_library_path(TCCState *s, const char *pathname)
1128 tcc_split_path(s, (void ***)&s->library_paths, &s->nb_library_paths, pathname);
1129 return 0;
1132 static int tcc_add_library_internal(TCCState *s, const char *fmt,
1133 const char *filename, int flags, char **paths, int nb_paths)
1135 char buf[1024];
1136 int i;
1138 for(i = 0; i < nb_paths; i++) {
1139 snprintf(buf, sizeof(buf), fmt, paths[i], filename);
1140 if (tcc_add_file_internal(s, buf, flags | AFF_TYPE_BIN) == 0)
1141 return 0;
1143 return -1;
1146 #ifndef TCC_TARGET_PE
1147 /* find and load a dll. Return non zero if not found */
1148 /* XXX: add '-rpath' option support ? */
1149 ST_FUNC int tcc_add_dll(TCCState *s, const char *filename, int flags)
1151 return tcc_add_library_internal(s, "%s/%s", filename, flags,
1152 s->library_paths, s->nb_library_paths);
1154 #endif
1156 ST_FUNC int tcc_add_crt(TCCState *s, const char *filename)
1158 if (-1 == tcc_add_library_internal(s, "%s/%s",
1159 filename, 0, s->crt_paths, s->nb_crt_paths))
1160 tcc_error_noabort("file '%s' not found", filename);
1161 return 0;
1164 /* the library name is the same as the argument of the '-l' option */
1165 LIBTCCAPI int tcc_add_library(TCCState *s, const char *libraryname)
1167 #ifdef TCC_TARGET_PE
1168 const char *libs[] = { "%s/%s.def", "%s/lib%s.def", "%s/%s.dll", "%s/lib%s.dll", "%s/lib%s.a", NULL };
1169 const char **pp = s->static_link ? libs + 4 : libs;
1170 #else
1171 const char *libs[] = { "%s/lib%s.so", "%s/lib%s.a", NULL };
1172 const char **pp = s->static_link ? libs + 1 : libs;
1173 #endif
1174 while (*pp) {
1175 if (0 == tcc_add_library_internal(s, *pp,
1176 libraryname, 0, s->library_paths, s->nb_library_paths))
1177 return 0;
1178 ++pp;
1180 return -1;
1183 PUB_FUNC int tcc_add_library_err(TCCState *s, const char *libname)
1185 int ret = tcc_add_library(s, libname);
1186 if (ret < 0)
1187 tcc_error_noabort("library 'lib%s' not found", libname);
1188 return ret;
1191 /* habdle #pragma comment(lib,) */
1192 ST_FUNC void tcc_add_pragma_libs(TCCState *s1)
1194 int i;
1195 for (i = 0; i < s1->nb_pragma_libs; i++)
1196 tcc_add_library_err(s1, s1->pragma_libs[i]);
1199 LIBTCCAPI int tcc_add_symbol(TCCState *s, const char *name, const void *val)
1201 #ifdef TCC_TARGET_PE
1202 /* On x86_64 'val' might not be reachable with a 32bit offset.
1203 So it is handled here as if it were in a DLL. */
1204 pe_putimport(s, 0, name, (uintptr_t)val);
1205 #else
1206 set_elf_sym(symtab_section, (uintptr_t)val, 0,
1207 ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE), 0,
1208 SHN_ABS, name);
1209 #endif
1210 return 0;
1213 LIBTCCAPI void tcc_set_lib_path(TCCState *s, const char *path)
1215 tcc_free(s->tcc_lib_path);
1216 s->tcc_lib_path = tcc_strdup(path);
1219 #define WD_ALL 0x0001 /* warning is activated when using -Wall */
1220 #define FD_INVERT 0x0002 /* invert value before storing */
1222 typedef struct FlagDef {
1223 uint16_t offset;
1224 uint16_t flags;
1225 const char *name;
1226 } FlagDef;
1228 static const FlagDef warning_defs[] = {
1229 { offsetof(TCCState, warn_unsupported), 0, "unsupported" },
1230 { offsetof(TCCState, warn_write_strings), 0, "write-strings" },
1231 { offsetof(TCCState, warn_error), 0, "error" },
1232 { offsetof(TCCState, warn_implicit_function_declaration), WD_ALL,
1233 "implicit-function-declaration" },
1236 static int no_flag(const char **pp)
1238 const char *p = *pp;
1239 if (*p != 'n' || *++p != 'o' || *++p != '-')
1240 return 0;
1241 *pp = p + 1;
1242 return 1;
1245 ST_FUNC int set_flag(TCCState *s, const FlagDef *flags, int nb_flags,
1246 const char *name, int value)
1248 int i;
1249 const FlagDef *p;
1250 const char *r;
1252 r = name;
1253 if (no_flag(&r))
1254 value = !value;
1256 for(i = 0, p = flags; i < nb_flags; i++, p++) {
1257 if (!strcmp(r, p->name))
1258 goto found;
1260 return -1;
1261 found:
1262 if (p->flags & FD_INVERT)
1263 value = !value;
1264 *(int *)((uint8_t *)s + p->offset) = value;
1265 return 0;
1268 /* set/reset a warning */
1269 static int tcc_set_warning(TCCState *s, const char *warning_name, int value)
1271 int i;
1272 const FlagDef *p;
1274 if (!strcmp(warning_name, "all")) {
1275 for(i = 0, p = warning_defs; i < countof(warning_defs); i++, p++) {
1276 if (p->flags & WD_ALL)
1277 *(int *)((uint8_t *)s + p->offset) = 1;
1279 return 0;
1280 } else {
1281 return set_flag(s, warning_defs, countof(warning_defs),
1282 warning_name, value);
1286 static const FlagDef flag_defs[] = {
1287 { offsetof(TCCState, char_is_unsigned), 0, "unsigned-char" },
1288 { offsetof(TCCState, char_is_unsigned), FD_INVERT, "signed-char" },
1289 { offsetof(TCCState, nocommon), FD_INVERT, "common" },
1290 { offsetof(TCCState, leading_underscore), 0, "leading-underscore" },
1291 { offsetof(TCCState, ms_extensions), 0, "ms-extensions" },
1292 { offsetof(TCCState, old_struct_init_code), 0, "old-struct-init-code" },
1293 { offsetof(TCCState, dollars_in_identifiers), 0, "dollars-in-identifiers" },
1296 /* set/reset a flag */
1297 static int tcc_set_flag(TCCState *s, const char *flag_name, int value)
1299 return set_flag(s, flag_defs, countof(flag_defs),
1300 flag_name, value);
1304 static int strstart(const char *val, const char **str)
1306 const char *p, *q;
1307 p = *str;
1308 q = val;
1309 while (*q) {
1310 if (*p != *q)
1311 return 0;
1312 p++;
1313 q++;
1315 *str = p;
1316 return 1;
1319 /* Like strstart, but automatically takes into account that ld options can
1321 * - start with double or single dash (e.g. '--soname' or '-soname')
1322 * - arguments can be given as separate or after '=' (e.g. '-Wl,-soname,x.so'
1323 * or '-Wl,-soname=x.so')
1325 * you provide `val` always in 'option[=]' form (no leading -)
1327 static int link_option(const char *str, const char *val, const char **ptr)
1329 const char *p, *q;
1330 int ret;
1332 /* there should be 1 or 2 dashes */
1333 if (*str++ != '-')
1334 return 0;
1335 if (*str == '-')
1336 str++;
1338 /* then str & val should match (potentialy up to '=') */
1339 p = str;
1340 q = val;
1342 ret = 1;
1343 if (q[0] == '?') {
1344 ++q;
1345 if (no_flag(&p))
1346 ret = -1;
1349 while (*q != '\0' && *q != '=') {
1350 if (*p != *q)
1351 return 0;
1352 p++;
1353 q++;
1356 /* '=' near eos means ',' or '=' is ok */
1357 if (*q == '=') {
1358 if (*p == 0)
1359 *ptr = p;
1360 if (*p != ',' && *p != '=')
1361 return 0;
1362 p++;
1364 *ptr = p;
1365 return ret;
1368 static const char *skip_linker_arg(const char **str)
1370 const char *s1 = *str;
1371 const char *s2 = strchr(s1, ',');
1372 *str = s2 ? s2++ : (s2 = s1 + strlen(s1));
1373 return s2;
1376 static char *copy_linker_arg(const char *p)
1378 const char *q = p;
1379 skip_linker_arg(&q);
1380 return pstrncpy(tcc_malloc(q - p + 1), p, q - p);
1383 /* set linker options */
1384 static int tcc_set_linker(TCCState *s, const char *option)
1386 while (*option) {
1388 const char *p = NULL;
1389 char *end = NULL;
1390 int ignoring = 0;
1391 int ret;
1393 if (link_option(option, "Bsymbolic", &p)) {
1394 s->symbolic = 1;
1395 } else if (link_option(option, "nostdlib", &p)) {
1396 s->nostdlib = 1;
1397 } else if (link_option(option, "fini=", &p)) {
1398 s->fini_symbol = copy_linker_arg(p);
1399 ignoring = 1;
1400 } else if (link_option(option, "image-base=", &p)
1401 || link_option(option, "Ttext=", &p)) {
1402 s->text_addr = strtoull(p, &end, 16);
1403 s->has_text_addr = 1;
1404 } else if (link_option(option, "init=", &p)) {
1405 s->init_symbol = copy_linker_arg(p);
1406 ignoring = 1;
1407 } else if (link_option(option, "oformat=", &p)) {
1408 #if defined(TCC_TARGET_PE)
1409 if (strstart("pe-", &p)) {
1410 #elif defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
1411 if (strstart("elf64-", &p)) {
1412 #else
1413 if (strstart("elf32-", &p)) {
1414 #endif
1415 s->output_format = TCC_OUTPUT_FORMAT_ELF;
1416 } else if (!strcmp(p, "binary")) {
1417 s->output_format = TCC_OUTPUT_FORMAT_BINARY;
1418 #ifdef TCC_TARGET_COFF
1419 } else if (!strcmp(p, "coff")) {
1420 s->output_format = TCC_OUTPUT_FORMAT_COFF;
1421 #endif
1422 } else
1423 goto err;
1425 } else if (link_option(option, "as-needed", &p)) {
1426 ignoring = 1;
1427 } else if (link_option(option, "O", &p)) {
1428 ignoring = 1;
1429 } else if (link_option(option, "rpath=", &p)) {
1430 s->rpath = copy_linker_arg(p);
1431 } else if (link_option(option, "section-alignment=", &p)) {
1432 s->section_align = strtoul(p, &end, 16);
1433 } else if (link_option(option, "soname=", &p)) {
1434 s->soname = copy_linker_arg(p);
1435 #ifdef TCC_TARGET_PE
1436 } else if (link_option(option, "file-alignment=", &p)) {
1437 s->pe_file_align = strtoul(p, &end, 16);
1438 } else if (link_option(option, "stack=", &p)) {
1439 s->pe_stack_size = strtoul(p, &end, 10);
1440 } else if (link_option(option, "subsystem=", &p)) {
1441 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
1442 if (!strcmp(p, "native")) {
1443 s->pe_subsystem = 1;
1444 } else if (!strcmp(p, "console")) {
1445 s->pe_subsystem = 3;
1446 } else if (!strcmp(p, "gui")) {
1447 s->pe_subsystem = 2;
1448 } else if (!strcmp(p, "posix")) {
1449 s->pe_subsystem = 7;
1450 } else if (!strcmp(p, "efiapp")) {
1451 s->pe_subsystem = 10;
1452 } else if (!strcmp(p, "efiboot")) {
1453 s->pe_subsystem = 11;
1454 } else if (!strcmp(p, "efiruntime")) {
1455 s->pe_subsystem = 12;
1456 } else if (!strcmp(p, "efirom")) {
1457 s->pe_subsystem = 13;
1458 #elif defined(TCC_TARGET_ARM)
1459 if (!strcmp(p, "wince")) {
1460 s->pe_subsystem = 9;
1461 #endif
1462 } else
1463 goto err;
1464 #endif
1465 } else if (ret = link_option(option, "?whole-archive", &p), ret) {
1466 s->alacarte_link = ret < 0;
1467 } else if (p) {
1468 return 0;
1469 } else {
1470 err:
1471 tcc_error("unsupported linker option '%s'", option);
1474 if (ignoring && s->warn_unsupported)
1475 tcc_warning("unsupported linker option '%s'", option);
1477 option = skip_linker_arg(&p);
1479 return 1;
1482 typedef struct TCCOption {
1483 const char *name;
1484 uint16_t index;
1485 uint16_t flags;
1486 } TCCOption;
1488 enum {
1489 TCC_OPTION_HELP,
1490 TCC_OPTION_I,
1491 TCC_OPTION_D,
1492 TCC_OPTION_U,
1493 TCC_OPTION_P,
1494 TCC_OPTION_L,
1495 TCC_OPTION_B,
1496 TCC_OPTION_l,
1497 TCC_OPTION_bench,
1498 TCC_OPTION_bt,
1499 TCC_OPTION_b,
1500 TCC_OPTION_g,
1501 TCC_OPTION_c,
1502 TCC_OPTION_dumpversion,
1503 TCC_OPTION_d,
1504 TCC_OPTION_float_abi,
1505 TCC_OPTION_static,
1506 TCC_OPTION_std,
1507 TCC_OPTION_shared,
1508 TCC_OPTION_soname,
1509 TCC_OPTION_o,
1510 TCC_OPTION_r,
1511 TCC_OPTION_s,
1512 TCC_OPTION_traditional,
1513 TCC_OPTION_Wl,
1514 TCC_OPTION_Wp,
1515 TCC_OPTION_W,
1516 TCC_OPTION_O,
1517 TCC_OPTION_mms_bitfields,
1518 TCC_OPTION_m,
1519 TCC_OPTION_f,
1520 TCC_OPTION_isystem,
1521 TCC_OPTION_iwithprefix,
1522 TCC_OPTION_include,
1523 TCC_OPTION_nostdinc,
1524 TCC_OPTION_nostdlib,
1525 TCC_OPTION_print_search_dirs,
1526 TCC_OPTION_rdynamic,
1527 TCC_OPTION_param,
1528 TCC_OPTION_pedantic,
1529 TCC_OPTION_pthread,
1530 TCC_OPTION_run,
1531 TCC_OPTION_v,
1532 TCC_OPTION_w,
1533 TCC_OPTION_pipe,
1534 TCC_OPTION_E,
1535 TCC_OPTION_MD,
1536 TCC_OPTION_MF,
1537 TCC_OPTION_x
1540 #define TCC_OPTION_HAS_ARG 0x0001
1541 #define TCC_OPTION_NOSEP 0x0002 /* cannot have space before option and arg */
1543 static const TCCOption tcc_options[] = {
1544 { "h", TCC_OPTION_HELP, 0 },
1545 { "-help", TCC_OPTION_HELP, 0 },
1546 { "?", TCC_OPTION_HELP, 0 },
1547 { "I", TCC_OPTION_I, TCC_OPTION_HAS_ARG },
1548 { "D", TCC_OPTION_D, TCC_OPTION_HAS_ARG },
1549 { "U", TCC_OPTION_U, TCC_OPTION_HAS_ARG },
1550 { "P", TCC_OPTION_P, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1551 { "L", TCC_OPTION_L, TCC_OPTION_HAS_ARG },
1552 { "B", TCC_OPTION_B, TCC_OPTION_HAS_ARG },
1553 { "l", TCC_OPTION_l, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1554 { "bench", TCC_OPTION_bench, 0 },
1555 #ifdef CONFIG_TCC_BACKTRACE
1556 { "bt", TCC_OPTION_bt, TCC_OPTION_HAS_ARG },
1557 #endif
1558 #ifdef CONFIG_TCC_BCHECK
1559 { "b", TCC_OPTION_b, 0 },
1560 #endif
1561 { "g", TCC_OPTION_g, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1562 { "c", TCC_OPTION_c, 0 },
1563 { "dumpversion", TCC_OPTION_dumpversion, 0},
1564 { "d", TCC_OPTION_d, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1565 #ifdef TCC_TARGET_ARM
1566 { "mfloat-abi", TCC_OPTION_float_abi, TCC_OPTION_HAS_ARG },
1567 #endif
1568 { "static", TCC_OPTION_static, 0 },
1569 { "std", TCC_OPTION_std, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1570 { "shared", TCC_OPTION_shared, 0 },
1571 { "soname", TCC_OPTION_soname, TCC_OPTION_HAS_ARG },
1572 { "o", TCC_OPTION_o, TCC_OPTION_HAS_ARG },
1573 { "-param", TCC_OPTION_param, TCC_OPTION_HAS_ARG },
1574 { "pedantic", TCC_OPTION_pedantic, 0},
1575 { "pthread", TCC_OPTION_pthread, 0},
1576 { "run", TCC_OPTION_run, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1577 { "rdynamic", TCC_OPTION_rdynamic, 0 },
1578 { "r", TCC_OPTION_r, 0 },
1579 { "s", TCC_OPTION_s, 0 },
1580 { "traditional", TCC_OPTION_traditional, 0 },
1581 { "Wl,", TCC_OPTION_Wl, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1582 { "Wp,", TCC_OPTION_Wp, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1583 { "W", TCC_OPTION_W, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1584 { "O", TCC_OPTION_O, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1585 { "mms-bitfields", TCC_OPTION_mms_bitfields, 0}, /* must go before option 'm' */
1586 { "m", TCC_OPTION_m, TCC_OPTION_HAS_ARG },
1587 { "f", TCC_OPTION_f, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1588 { "isystem", TCC_OPTION_isystem, TCC_OPTION_HAS_ARG },
1589 { "iwithprefix", TCC_OPTION_iwithprefix, TCC_OPTION_HAS_ARG },
1590 { "include", TCC_OPTION_include, TCC_OPTION_HAS_ARG },
1591 { "nostdinc", TCC_OPTION_nostdinc, 0 },
1592 { "nostdlib", TCC_OPTION_nostdlib, 0 },
1593 { "print-search-dirs", TCC_OPTION_print_search_dirs, 0 },
1594 { "v", TCC_OPTION_v, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1595 { "w", TCC_OPTION_w, 0 },
1596 { "pipe", TCC_OPTION_pipe, 0},
1597 { "E", TCC_OPTION_E, 0},
1598 { "MD", TCC_OPTION_MD, 0},
1599 { "MF", TCC_OPTION_MF, TCC_OPTION_HAS_ARG },
1600 { "x", TCC_OPTION_x, TCC_OPTION_HAS_ARG },
1601 { NULL, 0, 0 },
1604 static void parse_option_D(TCCState *s1, const char *optarg)
1606 char *sym = tcc_strdup(optarg);
1607 char *value = strchr(sym, '=');
1608 if (value)
1609 *value++ = '\0';
1610 tcc_define_symbol(s1, sym, value);
1611 tcc_free(sym);
1614 static void args_parser_add_file(TCCState *s, const char* filename, int filetype)
1616 struct filespec *f = tcc_malloc(sizeof *f + strlen(filename));
1617 f->type = filetype;
1618 strcpy(f->name, filename);
1619 dynarray_add((void ***)&s->files, &s->nb_files, f);
1622 /* read list file */
1623 static void args_parser_listfile(TCCState *s, const char *filename)
1625 int fd;
1626 size_t len;
1627 char *p;
1629 fd = open(filename, O_RDONLY | O_BINARY);
1630 if (fd < 0)
1631 tcc_error("file '%s' not found", filename);
1633 len = lseek(fd, 0, SEEK_END);
1634 p = tcc_malloc(len + 1), p[len] = 0;
1635 lseek(fd, 0, SEEK_SET), read(fd, p, len), close(fd);
1636 tcc_set_options(s, p);
1637 tcc_free(p);
1640 PUB_FUNC int tcc_parse_args(TCCState *s, int argc, char **argv)
1642 const TCCOption *popt;
1643 const char *optarg, *r;
1644 int optind = 0;
1645 int run = 0;
1646 int x;
1647 CString linker_arg; /* collect -Wl options */
1648 char buf[1024];
1650 cstr_new(&linker_arg);
1652 while (optind < argc) {
1654 r = argv[optind++];
1656 reparse:
1657 if (r[0] == '@' && r[1] != '\0') {
1658 args_parser_listfile(s, r + 1);
1659 continue;
1662 if (r[0] != '-' || r[1] == '\0') {
1663 args_parser_add_file(s, r, s->filetype);
1664 if (run) {
1665 optind--;
1666 /* argv[0] will be this file */
1667 break;
1669 continue;
1672 /* find option in table */
1673 for(popt = tcc_options; ; ++popt) {
1674 const char *p1 = popt->name;
1675 const char *r1 = r + 1;
1676 if (p1 == NULL)
1677 tcc_error("invalid option -- '%s'", r);
1678 if (!strstart(p1, &r1))
1679 continue;
1680 optarg = r1;
1681 if (popt->flags & TCC_OPTION_HAS_ARG) {
1682 if (*r1 == '\0' && !(popt->flags & TCC_OPTION_NOSEP)) {
1683 if (optind >= argc)
1684 arg_err:
1685 tcc_error("argument to '%s' is missing", r);
1686 optarg = argv[optind++];
1688 } else if (*r1 != '\0')
1689 continue;
1690 break;
1693 switch(popt->index) {
1694 case TCC_OPTION_HELP:
1695 return 0;
1696 case TCC_OPTION_I:
1697 tcc_add_include_path(s, optarg);
1698 break;
1699 case TCC_OPTION_D:
1700 parse_option_D(s, optarg);
1701 break;
1702 case TCC_OPTION_U:
1703 tcc_undefine_symbol(s, optarg);
1704 break;
1705 case TCC_OPTION_L:
1706 tcc_add_library_path(s, optarg);
1707 break;
1708 case TCC_OPTION_B:
1709 /* set tcc utilities path (mainly for tcc development) */
1710 tcc_set_lib_path(s, optarg);
1711 break;
1712 case TCC_OPTION_l:
1713 args_parser_add_file(s, optarg, AFF_TYPE_LIBWH - s->alacarte_link);
1714 s->nb_libraries++;
1715 break;
1716 case TCC_OPTION_pthread:
1717 parse_option_D(s, "_REENTRANT");
1718 s->option_pthread = 1;
1719 break;
1720 case TCC_OPTION_bench:
1721 s->do_bench = 1;
1722 break;
1723 #ifdef CONFIG_TCC_BACKTRACE
1724 case TCC_OPTION_bt:
1725 tcc_set_num_callers(atoi(optarg));
1726 break;
1727 #endif
1728 #ifdef CONFIG_TCC_BCHECK
1729 case TCC_OPTION_b:
1730 s->do_bounds_check = 1;
1731 s->do_debug = 1;
1732 break;
1733 #endif
1734 case TCC_OPTION_g:
1735 s->do_debug = 1;
1736 break;
1737 case TCC_OPTION_c:
1738 x = TCC_OUTPUT_OBJ;
1739 set_output_type:
1740 if (s->output_type)
1741 tcc_warning("-%s: overriding compiler action already specified", popt->name);
1742 s->output_type = x;
1743 break;
1744 case TCC_OPTION_d:
1745 if (*optarg == 'D')
1746 s->dflag = 3;
1747 else if (*optarg == 'M')
1748 s->dflag = 7;
1749 else
1750 goto unsupported_option;
1751 break;
1752 #ifdef TCC_TARGET_ARM
1753 case TCC_OPTION_float_abi:
1754 /* tcc doesn't support soft float yet */
1755 if (!strcmp(optarg, "softfp")) {
1756 s->float_abi = ARM_SOFTFP_FLOAT;
1757 tcc_undefine_symbol(s, "__ARM_PCS_VFP");
1758 } else if (!strcmp(optarg, "hard"))
1759 s->float_abi = ARM_HARD_FLOAT;
1760 else
1761 tcc_error("unsupported float abi '%s'", optarg);
1762 break;
1763 #endif
1764 case TCC_OPTION_static:
1765 s->static_link = 1;
1766 break;
1767 case TCC_OPTION_std:
1768 /* silently ignore, a current purpose:
1769 allow to use a tcc as a reference compiler for "make test" */
1770 break;
1771 case TCC_OPTION_shared:
1772 x = TCC_OUTPUT_DLL;
1773 goto set_output_type;
1774 case TCC_OPTION_soname:
1775 s->soname = tcc_strdup(optarg);
1776 break;
1777 case TCC_OPTION_m:
1778 if (strcmp(optarg, "32") && strcmp(optarg, "64"))
1779 goto unsupported_option;
1780 s->option_m = tcc_strdup(optarg);
1781 break;
1782 case TCC_OPTION_o:
1783 if (s->outfile) {
1784 tcc_warning("multiple -o option");
1785 tcc_free(s->outfile);
1787 s->outfile = tcc_strdup(optarg);
1788 break;
1789 case TCC_OPTION_r:
1790 /* generate a .o merging several output files */
1791 s->option_r = 1;
1792 x = TCC_OUTPUT_OBJ;
1793 goto set_output_type;
1794 case TCC_OPTION_isystem:
1795 tcc_add_sysinclude_path(s, optarg);
1796 break;
1797 case TCC_OPTION_iwithprefix:
1798 snprintf(buf, sizeof buf, "{B}/%s", optarg);
1799 tcc_add_sysinclude_path(s, buf);
1800 break;
1801 case TCC_OPTION_include:
1802 dynarray_add((void ***)&s->cmd_include_files,
1803 &s->nb_cmd_include_files, tcc_strdup(optarg));
1804 break;
1805 case TCC_OPTION_nostdinc:
1806 s->nostdinc = 1;
1807 break;
1808 case TCC_OPTION_nostdlib:
1809 s->nostdlib = 1;
1810 break;
1811 case TCC_OPTION_print_search_dirs:
1812 s->print_search_dirs = 1;
1813 break;
1814 case TCC_OPTION_run:
1815 #ifndef TCC_IS_NATIVE
1816 tcc_error("-run is not available in a cross compiler");
1817 #endif
1818 tcc_set_options(s, optarg);
1819 run = 1;
1820 x = TCC_OUTPUT_MEMORY;
1821 goto set_output_type;
1822 case TCC_OPTION_v:
1823 do ++s->verbose; while (*optarg++ == 'v');
1824 break;
1825 case TCC_OPTION_f:
1826 if (tcc_set_flag(s, optarg, 1) < 0)
1827 goto unsupported_option;
1828 break;
1829 case TCC_OPTION_W:
1830 if (tcc_set_warning(s, optarg, 1) < 0)
1831 goto unsupported_option;
1832 break;
1833 case TCC_OPTION_w:
1834 s->warn_none = 1;
1835 break;
1836 case TCC_OPTION_rdynamic:
1837 s->rdynamic = 1;
1838 break;
1839 case TCC_OPTION_Wl:
1840 if (linker_arg.size)
1841 --linker_arg.size, cstr_ccat(&linker_arg, ',');
1842 cstr_cat(&linker_arg, optarg, 0);
1843 if (tcc_set_linker(s, linker_arg.data))
1844 cstr_free(&linker_arg);
1845 break;
1846 case TCC_OPTION_Wp:
1847 r = optarg;
1848 goto reparse;
1849 case TCC_OPTION_E:
1850 x = TCC_OUTPUT_PREPROCESS;
1851 goto set_output_type;
1852 case TCC_OPTION_P:
1853 s->Pflag = atoi(optarg) + 1;
1854 break;
1855 case TCC_OPTION_MD:
1856 s->gen_deps = 1;
1857 break;
1858 case TCC_OPTION_MF:
1859 s->deps_outfile = tcc_strdup(optarg);
1860 break;
1861 case TCC_OPTION_dumpversion:
1862 printf ("%s\n", TCC_VERSION);
1863 exit(0);
1864 break;
1865 case TCC_OPTION_x:
1866 if (*optarg == 'c')
1867 s->filetype = AFF_TYPE_C;
1868 else if (*optarg == 'a')
1869 s->filetype = AFF_TYPE_ASMPP;
1870 else if (*optarg == 'n')
1871 s->filetype = AFF_TYPE_NONE;
1872 else
1873 tcc_warning("unsupported language '%s'", optarg);
1874 break;
1875 case TCC_OPTION_O:
1876 x = atoi(optarg);
1877 if (x > 0)
1878 tcc_define_symbol(s, "__OPTIMIZE__", NULL);
1879 break;
1880 case TCC_OPTION_mms_bitfields:
1881 s->ms_bitfields = 1;
1882 break;
1883 case TCC_OPTION_traditional:
1884 case TCC_OPTION_pedantic:
1885 case TCC_OPTION_pipe:
1886 case TCC_OPTION_s:
1887 /* ignored */
1888 break;
1889 default:
1890 unsupported_option:
1891 if (s->warn_unsupported)
1892 tcc_warning("unsupported option '%s'", r);
1893 break;
1897 if (linker_arg.size) {
1898 r = linker_arg.data;
1899 goto arg_err;
1902 return optind;
1905 LIBTCCAPI int tcc_set_options(TCCState *s, const char *r)
1907 char **argv;
1908 int argc;
1909 int ret, q, c;
1910 CString str;
1912 argc = 0, argv = NULL;
1913 for(;;) {
1914 while (c = (unsigned char)*r, c && c <= ' ')
1915 ++r;
1916 if (c == 0)
1917 break;
1918 q = 0;
1919 cstr_new(&str);
1920 while (c = (unsigned char)*r, c) {
1921 ++r;
1922 if (c == '\\' && (*r == '"' || *r == '\\')) {
1923 c = *r++;
1924 } else if (c == '"') {
1925 q = !q;
1926 continue;
1927 } else if (q == 0 && c <= ' ') {
1928 break;
1930 cstr_ccat(&str, c);
1932 cstr_ccat(&str, 0);
1933 //printf("<%s>\n", str.data), fflush(stdout);
1934 dynarray_add((void ***)&argv, &argc, tcc_strdup(str.data));
1935 cstr_free(&str);
1937 ret = tcc_parse_args(s, argc, argv);
1938 dynarray_reset(&argv, &argc);
1939 return ret;
1942 PUB_FUNC void tcc_print_stats(TCCState *s, unsigned total_time)
1944 if (total_time < 1)
1945 total_time = 1;
1946 if (total_bytes < 1)
1947 total_bytes = 1;
1948 fprintf(stderr, "%d idents, %d lines, %d bytes, %0.3f s, %u lines/s, %0.1f MB/s\n",
1949 tok_ident - TOK_IDENT, total_lines, total_bytes,
1950 (double)total_time/1000,
1951 (unsigned)total_lines*1000/total_time,
1952 (double)total_bytes/1000/total_time);
1955 PUB_FUNC void tcc_set_environment(TCCState *s)
1957 char * path;
1959 path = getenv("C_INCLUDE_PATH");
1960 if(path != NULL) {
1961 tcc_add_include_path(s, path);
1963 path = getenv("CPATH");
1964 if(path != NULL) {
1965 tcc_add_include_path(s, path);
1967 path = getenv("LIBRARY_PATH");
1968 if(path != NULL) {
1969 tcc_add_library_path(s, path);