arm64: Fix regression introduced by 6245db9.
[tinycc.git] / libtcc.c
blobaff7dcc7da7e05a6de29d24161e6e43212c84ad7
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 tccgen_end(s1);
675 s1->error_set_jmp_enabled = 0;
677 free_inline_functions(s1);
678 /* reset define stack, but keep -D and built-ins */
679 free_defines(define_start);
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->sym_attrs);
945 tcc_free(s1);
946 tcc_memstats(bench);
949 LIBTCCAPI int tcc_set_output_type(TCCState *s, int output_type)
951 s->output_type = output_type;
953 /* always elf for objects */
954 if (output_type == TCC_OUTPUT_OBJ)
955 s->output_format = TCC_OUTPUT_FORMAT_ELF;
957 if (s->char_is_unsigned)
958 tcc_define_symbol(s, "__CHAR_UNSIGNED__", NULL);
960 if (!s->nostdinc) {
961 /* default include paths */
962 /* -isystem paths have already been handled */
963 tcc_add_sysinclude_path(s, CONFIG_TCC_SYSINCLUDEPATHS);
966 #ifdef CONFIG_TCC_BCHECK
967 if (s->do_bounds_check) {
968 /* if bound checking, then add corresponding sections */
969 tccelf_bounds_new(s);
970 /* define symbol */
971 tcc_define_symbol(s, "__BOUNDS_CHECKING_ON", NULL);
973 #endif
974 if (s->do_debug) {
975 /* add debug sections */
976 tccelf_stab_new(s);
979 tcc_add_library_path(s, CONFIG_TCC_LIBPATHS);
981 #ifdef TCC_TARGET_PE
982 # ifdef _WIN32
983 if (!s->nostdlib && output_type != TCC_OUTPUT_OBJ)
984 tcc_add_systemdir(s);
985 # endif
986 #else
987 /* paths for crt objects */
988 tcc_split_path(s, (void ***)&s->crt_paths, &s->nb_crt_paths, CONFIG_TCC_CRTPREFIX);
989 /* add libc crt1/crti objects */
990 if ((output_type == TCC_OUTPUT_EXE || output_type == TCC_OUTPUT_DLL) &&
991 !s->nostdlib) {
992 if (output_type != TCC_OUTPUT_DLL)
993 tcc_add_crt(s, "crt1.o");
994 tcc_add_crt(s, "crti.o");
996 #endif
997 return 0;
1000 LIBTCCAPI int tcc_add_include_path(TCCState *s, const char *pathname)
1002 tcc_split_path(s, (void ***)&s->include_paths, &s->nb_include_paths, pathname);
1003 return 0;
1006 LIBTCCAPI int tcc_add_sysinclude_path(TCCState *s, const char *pathname)
1008 tcc_split_path(s, (void ***)&s->sysinclude_paths, &s->nb_sysinclude_paths, pathname);
1009 return 0;
1012 ST_FUNC int tcc_add_file_internal(TCCState *s1, const char *filename, int flags)
1014 int ret, filetype;
1016 filetype = flags & 0x0F;
1017 if (filetype == 0) {
1018 /* use a file extension to detect a filetype */
1019 const char *ext = tcc_fileextension(filename);
1020 if (ext[0]) {
1021 ext++;
1022 if (!strcmp(ext, "S"))
1023 filetype = AFF_TYPE_ASMPP;
1024 else if (!strcmp(ext, "s"))
1025 filetype = AFF_TYPE_ASM;
1026 else if (!PATHCMP(ext, "c") || !PATHCMP(ext, "i"))
1027 filetype = AFF_TYPE_C;
1028 else
1029 filetype = AFF_TYPE_BIN;
1030 } else {
1031 filetype = AFF_TYPE_C;
1035 /* open the file */
1036 ret = tcc_open(s1, filename);
1037 if (ret < 0) {
1038 if (flags & AFF_PRINT_ERROR)
1039 tcc_error_noabort("file '%s' not found", filename);
1040 return ret;
1043 /* update target deps */
1044 dynarray_add((void ***)&s1->target_deps, &s1->nb_target_deps,
1045 tcc_strdup(filename));
1047 parse_flags = 0;
1048 /* if .S file, define __ASSEMBLER__ like gcc does */
1049 if (filetype == AFF_TYPE_ASM || filetype == AFF_TYPE_ASMPP) {
1050 tcc_define_symbol(s1, "__ASSEMBLER__", NULL);
1051 parse_flags = PARSE_FLAG_ASM_FILE;
1054 if (flags & AFF_PREPROCESS) {
1055 ret = tcc_preprocess(s1);
1056 } else if (filetype == AFF_TYPE_C) {
1057 ret = tcc_compile(s1);
1058 #ifdef CONFIG_TCC_ASM
1059 } else if (filetype == AFF_TYPE_ASMPP) {
1060 /* non preprocessed assembler */
1061 ret = tcc_assemble(s1, 1);
1062 } else if (filetype == AFF_TYPE_ASM) {
1063 /* preprocessed assembler */
1064 ret = tcc_assemble(s1, 0);
1065 #endif
1066 } else {
1067 ElfW(Ehdr) ehdr;
1068 int fd, obj_type;
1070 fd = file->fd;
1071 obj_type = tcc_object_type(fd, &ehdr);
1072 lseek(fd, 0, SEEK_SET);
1074 /* do not display line number if error */
1075 file->line_num = 0;
1077 switch (obj_type) {
1078 case AFF_BINTYPE_REL:
1079 ret = tcc_load_object_file(s1, fd, 0);
1080 break;
1081 #ifndef TCC_TARGET_PE
1082 case AFF_BINTYPE_DYN:
1083 if (s1->output_type == TCC_OUTPUT_MEMORY) {
1084 ret = 0;
1085 #ifdef TCC_IS_NATIVE
1086 if (NULL == dlopen(filename, RTLD_GLOBAL | RTLD_LAZY))
1087 ret = -1;
1088 #endif
1089 } else {
1090 ret = tcc_load_dll(s1, fd, filename,
1091 (flags & AFF_REFERENCED_DLL) != 0);
1093 break;
1094 #endif
1095 case AFF_BINTYPE_AR:
1096 ret = tcc_load_archive(s1, fd);
1097 break;
1098 #ifdef TCC_TARGET_COFF
1099 case AFF_BINTYPE_C67:
1100 ret = tcc_load_coff(s1, fd);
1101 break;
1102 #endif
1103 default:
1104 #ifdef TCC_TARGET_PE
1105 ret = pe_load_file(s1, filename, fd);
1106 #else
1107 /* as GNU ld, consider it is an ld script if not recognized */
1108 ret = tcc_load_ldscript(s1);
1109 #endif
1110 if (ret < 0)
1111 tcc_error_noabort("unrecognized file type");
1112 break;
1115 tcc_close();
1116 return ret;
1119 LIBTCCAPI int tcc_add_file(TCCState *s, const char *filename)
1121 if (s->output_type == TCC_OUTPUT_PREPROCESS)
1122 return tcc_add_file_internal(s, filename, AFF_PRINT_ERROR | AFF_PREPROCESS | s->filetype);
1123 else
1124 return tcc_add_file_internal(s, filename, AFF_PRINT_ERROR | s->filetype);
1127 LIBTCCAPI int tcc_add_library_path(TCCState *s, const char *pathname)
1129 tcc_split_path(s, (void ***)&s->library_paths, &s->nb_library_paths, pathname);
1130 return 0;
1133 static int tcc_add_library_internal(TCCState *s, const char *fmt,
1134 const char *filename, int flags, char **paths, int nb_paths)
1136 char buf[1024];
1137 int i;
1139 for(i = 0; i < nb_paths; i++) {
1140 snprintf(buf, sizeof(buf), fmt, paths[i], filename);
1141 if (tcc_add_file_internal(s, buf, flags | AFF_TYPE_BIN) == 0)
1142 return 0;
1144 return -1;
1147 #ifndef TCC_TARGET_PE
1148 /* find and load a dll. Return non zero if not found */
1149 /* XXX: add '-rpath' option support ? */
1150 ST_FUNC int tcc_add_dll(TCCState *s, const char *filename, int flags)
1152 return tcc_add_library_internal(s, "%s/%s", filename, flags,
1153 s->library_paths, s->nb_library_paths);
1155 #endif
1157 ST_FUNC int tcc_add_crt(TCCState *s, const char *filename)
1159 if (-1 == tcc_add_library_internal(s, "%s/%s",
1160 filename, 0, s->crt_paths, s->nb_crt_paths))
1161 tcc_error_noabort("file '%s' not found", filename);
1162 return 0;
1165 /* the library name is the same as the argument of the '-l' option */
1166 LIBTCCAPI int tcc_add_library(TCCState *s, const char *libraryname)
1168 #ifdef TCC_TARGET_PE
1169 const char *libs[] = { "%s/%s.def", "%s/lib%s.def", "%s/%s.dll", "%s/lib%s.dll", "%s/lib%s.a", NULL };
1170 const char **pp = s->static_link ? libs + 4 : libs;
1171 #else
1172 const char *libs[] = { "%s/lib%s.so", "%s/lib%s.a", NULL };
1173 const char **pp = s->static_link ? libs + 1 : libs;
1174 #endif
1175 while (*pp) {
1176 if (0 == tcc_add_library_internal(s, *pp,
1177 libraryname, 0, s->library_paths, s->nb_library_paths))
1178 return 0;
1179 ++pp;
1181 return -1;
1184 PUB_FUNC int tcc_add_library_err(TCCState *s, const char *libname)
1186 int ret = tcc_add_library(s, libname);
1187 if (ret < 0)
1188 tcc_error_noabort("library 'lib%s' not found", libname);
1189 return ret;
1192 /* habdle #pragma comment(lib,) */
1193 ST_FUNC void tcc_add_pragma_libs(TCCState *s1)
1195 int i;
1196 for (i = 0; i < s1->nb_pragma_libs; i++)
1197 tcc_add_library_err(s1, s1->pragma_libs[i]);
1200 LIBTCCAPI int tcc_add_symbol(TCCState *s, const char *name, const void *val)
1202 #ifdef TCC_TARGET_PE
1203 /* On x86_64 'val' might not be reachable with a 32bit offset.
1204 So it is handled here as if it were in a DLL. */
1205 pe_putimport(s, 0, name, (uintptr_t)val);
1206 #else
1207 set_elf_sym(symtab_section, (uintptr_t)val, 0,
1208 ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE), 0,
1209 SHN_ABS, name);
1210 #endif
1211 return 0;
1214 LIBTCCAPI void tcc_set_lib_path(TCCState *s, const char *path)
1216 tcc_free(s->tcc_lib_path);
1217 s->tcc_lib_path = tcc_strdup(path);
1220 #define WD_ALL 0x0001 /* warning is activated when using -Wall */
1221 #define FD_INVERT 0x0002 /* invert value before storing */
1223 typedef struct FlagDef {
1224 uint16_t offset;
1225 uint16_t flags;
1226 const char *name;
1227 } FlagDef;
1229 static const FlagDef warning_defs[] = {
1230 { offsetof(TCCState, warn_unsupported), 0, "unsupported" },
1231 { offsetof(TCCState, warn_write_strings), 0, "write-strings" },
1232 { offsetof(TCCState, warn_error), 0, "error" },
1233 { offsetof(TCCState, warn_implicit_function_declaration), WD_ALL,
1234 "implicit-function-declaration" },
1237 static int no_flag(const char **pp)
1239 const char *p = *pp;
1240 if (*p != 'n' || *++p != 'o' || *++p != '-')
1241 return 0;
1242 *pp = p + 1;
1243 return 1;
1246 ST_FUNC int set_flag(TCCState *s, const FlagDef *flags, int nb_flags,
1247 const char *name, int value)
1249 int i;
1250 const FlagDef *p;
1251 const char *r;
1253 r = name;
1254 if (no_flag(&r))
1255 value = !value;
1257 for(i = 0, p = flags; i < nb_flags; i++, p++) {
1258 if (!strcmp(r, p->name))
1259 goto found;
1261 return -1;
1262 found:
1263 if (p->flags & FD_INVERT)
1264 value = !value;
1265 *(int *)((uint8_t *)s + p->offset) = value;
1266 return 0;
1269 /* set/reset a warning */
1270 static int tcc_set_warning(TCCState *s, const char *warning_name, int value)
1272 int i;
1273 const FlagDef *p;
1275 if (!strcmp(warning_name, "all")) {
1276 for(i = 0, p = warning_defs; i < countof(warning_defs); i++, p++) {
1277 if (p->flags & WD_ALL)
1278 *(int *)((uint8_t *)s + p->offset) = 1;
1280 return 0;
1281 } else {
1282 return set_flag(s, warning_defs, countof(warning_defs),
1283 warning_name, value);
1287 static const FlagDef flag_defs[] = {
1288 { offsetof(TCCState, char_is_unsigned), 0, "unsigned-char" },
1289 { offsetof(TCCState, char_is_unsigned), FD_INVERT, "signed-char" },
1290 { offsetof(TCCState, nocommon), FD_INVERT, "common" },
1291 { offsetof(TCCState, leading_underscore), 0, "leading-underscore" },
1292 { offsetof(TCCState, ms_extensions), 0, "ms-extensions" },
1293 { offsetof(TCCState, old_struct_init_code), 0, "old-struct-init-code" },
1294 { offsetof(TCCState, dollars_in_identifiers), 0, "dollars-in-identifiers" },
1297 /* set/reset a flag */
1298 static int tcc_set_flag(TCCState *s, const char *flag_name, int value)
1300 return set_flag(s, flag_defs, countof(flag_defs),
1301 flag_name, value);
1305 static int strstart(const char *val, const char **str)
1307 const char *p, *q;
1308 p = *str;
1309 q = val;
1310 while (*q) {
1311 if (*p != *q)
1312 return 0;
1313 p++;
1314 q++;
1316 *str = p;
1317 return 1;
1320 /* Like strstart, but automatically takes into account that ld options can
1322 * - start with double or single dash (e.g. '--soname' or '-soname')
1323 * - arguments can be given as separate or after '=' (e.g. '-Wl,-soname,x.so'
1324 * or '-Wl,-soname=x.so')
1326 * you provide `val` always in 'option[=]' form (no leading -)
1328 static int link_option(const char *str, const char *val, const char **ptr)
1330 const char *p, *q;
1331 int ret;
1333 /* there should be 1 or 2 dashes */
1334 if (*str++ != '-')
1335 return 0;
1336 if (*str == '-')
1337 str++;
1339 /* then str & val should match (potentialy up to '=') */
1340 p = str;
1341 q = val;
1343 ret = 1;
1344 if (q[0] == '?') {
1345 ++q;
1346 if (no_flag(&p))
1347 ret = -1;
1350 while (*q != '\0' && *q != '=') {
1351 if (*p != *q)
1352 return 0;
1353 p++;
1354 q++;
1357 /* '=' near eos means ',' or '=' is ok */
1358 if (*q == '=') {
1359 if (*p == 0)
1360 *ptr = p;
1361 if (*p != ',' && *p != '=')
1362 return 0;
1363 p++;
1365 *ptr = p;
1366 return ret;
1369 static const char *skip_linker_arg(const char **str)
1371 const char *s1 = *str;
1372 const char *s2 = strchr(s1, ',');
1373 *str = s2 ? s2++ : (s2 = s1 + strlen(s1));
1374 return s2;
1377 static char *copy_linker_arg(const char *p)
1379 const char *q = p;
1380 skip_linker_arg(&q);
1381 return pstrncpy(tcc_malloc(q - p + 1), p, q - p);
1384 /* set linker options */
1385 static int tcc_set_linker(TCCState *s, const char *option)
1387 while (*option) {
1389 const char *p = NULL;
1390 char *end = NULL;
1391 int ignoring = 0;
1392 int ret;
1394 if (link_option(option, "Bsymbolic", &p)) {
1395 s->symbolic = 1;
1396 } else if (link_option(option, "nostdlib", &p)) {
1397 s->nostdlib = 1;
1398 } else if (link_option(option, "fini=", &p)) {
1399 s->fini_symbol = copy_linker_arg(p);
1400 ignoring = 1;
1401 } else if (link_option(option, "image-base=", &p)
1402 || link_option(option, "Ttext=", &p)) {
1403 s->text_addr = strtoull(p, &end, 16);
1404 s->has_text_addr = 1;
1405 } else if (link_option(option, "init=", &p)) {
1406 s->init_symbol = copy_linker_arg(p);
1407 ignoring = 1;
1408 } else if (link_option(option, "oformat=", &p)) {
1409 #if defined(TCC_TARGET_PE)
1410 if (strstart("pe-", &p)) {
1411 #elif defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
1412 if (strstart("elf64-", &p)) {
1413 #else
1414 if (strstart("elf32-", &p)) {
1415 #endif
1416 s->output_format = TCC_OUTPUT_FORMAT_ELF;
1417 } else if (!strcmp(p, "binary")) {
1418 s->output_format = TCC_OUTPUT_FORMAT_BINARY;
1419 #ifdef TCC_TARGET_COFF
1420 } else if (!strcmp(p, "coff")) {
1421 s->output_format = TCC_OUTPUT_FORMAT_COFF;
1422 #endif
1423 } else
1424 goto err;
1426 } else if (link_option(option, "as-needed", &p)) {
1427 ignoring = 1;
1428 } else if (link_option(option, "O", &p)) {
1429 ignoring = 1;
1430 } else if (link_option(option, "rpath=", &p)) {
1431 s->rpath = copy_linker_arg(p);
1432 } else if (link_option(option, "section-alignment=", &p)) {
1433 s->section_align = strtoul(p, &end, 16);
1434 } else if (link_option(option, "soname=", &p)) {
1435 s->soname = copy_linker_arg(p);
1436 #ifdef TCC_TARGET_PE
1437 } else if (link_option(option, "file-alignment=", &p)) {
1438 s->pe_file_align = strtoul(p, &end, 16);
1439 } else if (link_option(option, "stack=", &p)) {
1440 s->pe_stack_size = strtoul(p, &end, 10);
1441 } else if (link_option(option, "subsystem=", &p)) {
1442 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
1443 if (!strcmp(p, "native")) {
1444 s->pe_subsystem = 1;
1445 } else if (!strcmp(p, "console")) {
1446 s->pe_subsystem = 3;
1447 } else if (!strcmp(p, "gui")) {
1448 s->pe_subsystem = 2;
1449 } else if (!strcmp(p, "posix")) {
1450 s->pe_subsystem = 7;
1451 } else if (!strcmp(p, "efiapp")) {
1452 s->pe_subsystem = 10;
1453 } else if (!strcmp(p, "efiboot")) {
1454 s->pe_subsystem = 11;
1455 } else if (!strcmp(p, "efiruntime")) {
1456 s->pe_subsystem = 12;
1457 } else if (!strcmp(p, "efirom")) {
1458 s->pe_subsystem = 13;
1459 #elif defined(TCC_TARGET_ARM)
1460 if (!strcmp(p, "wince")) {
1461 s->pe_subsystem = 9;
1462 #endif
1463 } else
1464 goto err;
1465 #endif
1466 } else if (ret = link_option(option, "?whole-archive", &p), ret) {
1467 s->alacarte_link = ret < 0;
1468 } else if (p) {
1469 return 0;
1470 } else {
1471 err:
1472 tcc_error("unsupported linker option '%s'", option);
1475 if (ignoring && s->warn_unsupported)
1476 tcc_warning("unsupported linker option '%s'", option);
1478 option = skip_linker_arg(&p);
1480 return 1;
1483 typedef struct TCCOption {
1484 const char *name;
1485 uint16_t index;
1486 uint16_t flags;
1487 } TCCOption;
1489 enum {
1490 TCC_OPTION_HELP,
1491 TCC_OPTION_I,
1492 TCC_OPTION_D,
1493 TCC_OPTION_U,
1494 TCC_OPTION_P,
1495 TCC_OPTION_L,
1496 TCC_OPTION_B,
1497 TCC_OPTION_l,
1498 TCC_OPTION_bench,
1499 TCC_OPTION_bt,
1500 TCC_OPTION_b,
1501 TCC_OPTION_g,
1502 TCC_OPTION_c,
1503 TCC_OPTION_dumpversion,
1504 TCC_OPTION_d,
1505 TCC_OPTION_float_abi,
1506 TCC_OPTION_static,
1507 TCC_OPTION_std,
1508 TCC_OPTION_shared,
1509 TCC_OPTION_soname,
1510 TCC_OPTION_o,
1511 TCC_OPTION_r,
1512 TCC_OPTION_s,
1513 TCC_OPTION_traditional,
1514 TCC_OPTION_Wl,
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_nostdinc,
1523 TCC_OPTION_nostdlib,
1524 TCC_OPTION_print_search_dirs,
1525 TCC_OPTION_rdynamic,
1526 TCC_OPTION_pedantic,
1527 TCC_OPTION_pthread,
1528 TCC_OPTION_run,
1529 TCC_OPTION_v,
1530 TCC_OPTION_w,
1531 TCC_OPTION_pipe,
1532 TCC_OPTION_E,
1533 TCC_OPTION_MD,
1534 TCC_OPTION_MF,
1535 TCC_OPTION_x
1538 #define TCC_OPTION_HAS_ARG 0x0001
1539 #define TCC_OPTION_NOSEP 0x0002 /* cannot have space before option and arg */
1541 static const TCCOption tcc_options[] = {
1542 { "h", TCC_OPTION_HELP, 0 },
1543 { "-help", TCC_OPTION_HELP, 0 },
1544 { "?", TCC_OPTION_HELP, 0 },
1545 { "I", TCC_OPTION_I, TCC_OPTION_HAS_ARG },
1546 { "D", TCC_OPTION_D, TCC_OPTION_HAS_ARG },
1547 { "U", TCC_OPTION_U, TCC_OPTION_HAS_ARG },
1548 { "P", TCC_OPTION_P, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1549 { "L", TCC_OPTION_L, TCC_OPTION_HAS_ARG },
1550 { "B", TCC_OPTION_B, TCC_OPTION_HAS_ARG },
1551 { "l", TCC_OPTION_l, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1552 { "bench", TCC_OPTION_bench, 0 },
1553 #ifdef CONFIG_TCC_BACKTRACE
1554 { "bt", TCC_OPTION_bt, TCC_OPTION_HAS_ARG },
1555 #endif
1556 #ifdef CONFIG_TCC_BCHECK
1557 { "b", TCC_OPTION_b, 0 },
1558 #endif
1559 { "g", TCC_OPTION_g, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1560 { "c", TCC_OPTION_c, 0 },
1561 { "dumpversion", TCC_OPTION_dumpversion, 0},
1562 { "d", TCC_OPTION_d, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1563 #ifdef TCC_TARGET_ARM
1564 { "mfloat-abi", TCC_OPTION_float_abi, TCC_OPTION_HAS_ARG },
1565 #endif
1566 { "static", TCC_OPTION_static, 0 },
1567 { "std", TCC_OPTION_std, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1568 { "shared", TCC_OPTION_shared, 0 },
1569 { "soname", TCC_OPTION_soname, TCC_OPTION_HAS_ARG },
1570 { "o", TCC_OPTION_o, TCC_OPTION_HAS_ARG },
1571 { "pedantic", TCC_OPTION_pedantic, 0},
1572 { "pthread", TCC_OPTION_pthread, 0},
1573 { "run", TCC_OPTION_run, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1574 { "rdynamic", TCC_OPTION_rdynamic, 0 },
1575 { "r", TCC_OPTION_r, 0 },
1576 { "s", TCC_OPTION_s, 0 },
1577 { "traditional", TCC_OPTION_traditional, 0 },
1578 { "Wl,", TCC_OPTION_Wl, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1579 { "W", TCC_OPTION_W, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1580 { "O", TCC_OPTION_O, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1581 { "mms-bitfields", TCC_OPTION_mms_bitfields, 0}, /* must go before option 'm' */
1582 { "m", TCC_OPTION_m, TCC_OPTION_HAS_ARG },
1583 { "f", TCC_OPTION_f, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1584 { "isystem", TCC_OPTION_isystem, TCC_OPTION_HAS_ARG },
1585 { "iwithprefix", TCC_OPTION_iwithprefix, TCC_OPTION_HAS_ARG },
1586 { "nostdinc", TCC_OPTION_nostdinc, 0 },
1587 { "nostdlib", TCC_OPTION_nostdlib, 0 },
1588 { "print-search-dirs", TCC_OPTION_print_search_dirs, 0 },
1589 { "v", TCC_OPTION_v, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1590 { "w", TCC_OPTION_w, 0 },
1591 { "pipe", TCC_OPTION_pipe, 0},
1592 { "E", TCC_OPTION_E, 0},
1593 { "MD", TCC_OPTION_MD, 0},
1594 { "MF", TCC_OPTION_MF, TCC_OPTION_HAS_ARG },
1595 { "x", TCC_OPTION_x, TCC_OPTION_HAS_ARG },
1596 { NULL, 0, 0 },
1599 static void parse_option_D(TCCState *s1, const char *optarg)
1601 char *sym = tcc_strdup(optarg);
1602 char *value = strchr(sym, '=');
1603 if (value)
1604 *value++ = '\0';
1605 tcc_define_symbol(s1, sym, value);
1606 tcc_free(sym);
1609 static void args_parser_add_file(TCCState *s, const char* filename, int filetype)
1611 struct filespec *f = tcc_malloc(sizeof *f + strlen(filename));
1612 f->type = filetype;
1613 strcpy(f->name, filename);
1614 dynarray_add((void ***)&s->files, &s->nb_files, f);
1617 /* read list file */
1618 static void args_parser_listfile(TCCState *s, const char *filename)
1620 int fd;
1621 size_t len;
1622 char *p;
1624 fd = open(filename, O_RDONLY | O_BINARY);
1625 if (fd < 0)
1626 tcc_error("file '%s' not found", filename);
1628 len = lseek(fd, 0, SEEK_END);
1629 p = tcc_malloc(len + 1), p[len] = 0;
1630 lseek(fd, 0, SEEK_SET), read(fd, p, len), close(fd);
1631 tcc_set_options(s, p);
1632 tcc_free(p);
1635 PUB_FUNC int tcc_parse_args(TCCState *s, int argc, char **argv)
1637 const TCCOption *popt;
1638 const char *optarg, *r;
1639 int optind = 0;
1640 int run = 0;
1641 int x;
1642 CString linker_arg; /* collect -Wl options */
1643 char buf[1024];
1645 cstr_new(&linker_arg);
1647 while (optind < argc) {
1649 r = argv[optind++];
1651 if (r[0] == '@' && r[1] != '\0') {
1652 args_parser_listfile(s, r + 1);
1653 continue;
1656 if (r[0] != '-' || r[1] == '\0') {
1657 args_parser_add_file(s, r, s->filetype);
1658 if (run) {
1659 optind--;
1660 /* argv[0] will be this file */
1661 break;
1663 continue;
1666 /* find option in table */
1667 for(popt = tcc_options; ; ++popt) {
1668 const char *p1 = popt->name;
1669 const char *r1 = r + 1;
1670 if (p1 == NULL)
1671 tcc_error("invalid option -- '%s'", r);
1672 if (!strstart(p1, &r1))
1673 continue;
1674 optarg = r1;
1675 if (popt->flags & TCC_OPTION_HAS_ARG) {
1676 if (*r1 == '\0' && !(popt->flags & TCC_OPTION_NOSEP)) {
1677 if (optind >= argc)
1678 arg_err:
1679 tcc_error("argument to '%s' is missing", r);
1680 optarg = argv[optind++];
1682 } else if (*r1 != '\0')
1683 continue;
1684 break;
1687 switch(popt->index) {
1688 case TCC_OPTION_HELP:
1689 return 0;
1690 case TCC_OPTION_I:
1691 tcc_add_include_path(s, optarg);
1692 break;
1693 case TCC_OPTION_D:
1694 parse_option_D(s, optarg);
1695 break;
1696 case TCC_OPTION_U:
1697 tcc_undefine_symbol(s, optarg);
1698 break;
1699 case TCC_OPTION_L:
1700 tcc_add_library_path(s, optarg);
1701 break;
1702 case TCC_OPTION_B:
1703 /* set tcc utilities path (mainly for tcc development) */
1704 tcc_set_lib_path(s, optarg);
1705 break;
1706 case TCC_OPTION_l:
1707 args_parser_add_file(s, optarg, AFF_TYPE_LIBWH - s->alacarte_link);
1708 s->nb_libraries++;
1709 break;
1710 case TCC_OPTION_pthread:
1711 parse_option_D(s, "_REENTRANT");
1712 s->option_pthread = 1;
1713 break;
1714 case TCC_OPTION_bench:
1715 s->do_bench = 1;
1716 break;
1717 #ifdef CONFIG_TCC_BACKTRACE
1718 case TCC_OPTION_bt:
1719 tcc_set_num_callers(atoi(optarg));
1720 break;
1721 #endif
1722 #ifdef CONFIG_TCC_BCHECK
1723 case TCC_OPTION_b:
1724 s->do_bounds_check = 1;
1725 s->do_debug = 1;
1726 break;
1727 #endif
1728 case TCC_OPTION_g:
1729 s->do_debug = 1;
1730 break;
1731 case TCC_OPTION_c:
1732 x = TCC_OUTPUT_OBJ;
1733 set_output_type:
1734 if (s->output_type)
1735 tcc_warning("-%s: overriding compiler action already specified", popt->name);
1736 s->output_type = x;
1737 break;
1738 case TCC_OPTION_d:
1739 if (*optarg == 'D')
1740 s->dflag = 3;
1741 else if (*optarg == 'M')
1742 s->dflag = 7;
1743 else
1744 goto unsupported_option;
1745 break;
1746 #ifdef TCC_TARGET_ARM
1747 case TCC_OPTION_float_abi:
1748 /* tcc doesn't support soft float yet */
1749 if (!strcmp(optarg, "softfp")) {
1750 s->float_abi = ARM_SOFTFP_FLOAT;
1751 tcc_undefine_symbol(s, "__ARM_PCS_VFP");
1752 } else if (!strcmp(optarg, "hard"))
1753 s->float_abi = ARM_HARD_FLOAT;
1754 else
1755 tcc_error("unsupported float abi '%s'", optarg);
1756 break;
1757 #endif
1758 case TCC_OPTION_static:
1759 s->static_link = 1;
1760 break;
1761 case TCC_OPTION_std:
1762 /* silently ignore, a current purpose:
1763 allow to use a tcc as a reference compiler for "make test" */
1764 break;
1765 case TCC_OPTION_shared:
1766 x = TCC_OUTPUT_DLL;
1767 goto set_output_type;
1768 case TCC_OPTION_soname:
1769 s->soname = tcc_strdup(optarg);
1770 break;
1771 case TCC_OPTION_m:
1772 s->option_m = tcc_strdup(optarg);
1773 break;
1774 case TCC_OPTION_o:
1775 if (s->outfile) {
1776 tcc_warning("multiple -o option");
1777 tcc_free(s->outfile);
1779 s->outfile = tcc_strdup(optarg);
1780 break;
1781 case TCC_OPTION_r:
1782 /* generate a .o merging several output files */
1783 s->option_r = 1;
1784 x = TCC_OUTPUT_OBJ;
1785 goto set_output_type;
1786 case TCC_OPTION_isystem:
1787 tcc_add_sysinclude_path(s, optarg);
1788 break;
1789 case TCC_OPTION_iwithprefix:
1790 snprintf(buf, sizeof buf, "{B}/%s", optarg);
1791 tcc_add_sysinclude_path(s, buf);
1792 break;
1793 case TCC_OPTION_nostdinc:
1794 s->nostdinc = 1;
1795 break;
1796 case TCC_OPTION_nostdlib:
1797 s->nostdlib = 1;
1798 break;
1799 case TCC_OPTION_print_search_dirs:
1800 s->print_search_dirs = 1;
1801 break;
1802 case TCC_OPTION_run:
1803 #ifndef TCC_IS_NATIVE
1804 tcc_error("-run is not available in a cross compiler");
1805 #endif
1806 tcc_set_options(s, optarg);
1807 run = 1;
1808 x = TCC_OUTPUT_MEMORY;
1809 goto set_output_type;
1810 case TCC_OPTION_v:
1811 do ++s->verbose; while (*optarg++ == 'v');
1812 break;
1813 case TCC_OPTION_f:
1814 if (tcc_set_flag(s, optarg, 1) < 0)
1815 goto unsupported_option;
1816 break;
1817 case TCC_OPTION_W:
1818 if (tcc_set_warning(s, optarg, 1) < 0)
1819 goto unsupported_option;
1820 break;
1821 case TCC_OPTION_w:
1822 s->warn_none = 1;
1823 break;
1824 case TCC_OPTION_rdynamic:
1825 s->rdynamic = 1;
1826 break;
1827 case TCC_OPTION_Wl:
1828 if (linker_arg.size)
1829 --linker_arg.size, cstr_ccat(&linker_arg, ',');
1830 cstr_cat(&linker_arg, optarg, 0);
1831 if (tcc_set_linker(s, linker_arg.data))
1832 cstr_free(&linker_arg);
1833 break;
1834 case TCC_OPTION_E:
1835 x = TCC_OUTPUT_PREPROCESS;
1836 goto set_output_type;
1837 case TCC_OPTION_P:
1838 s->Pflag = atoi(optarg) + 1;
1839 break;
1840 case TCC_OPTION_MD:
1841 s->gen_deps = 1;
1842 break;
1843 case TCC_OPTION_MF:
1844 s->deps_outfile = tcc_strdup(optarg);
1845 break;
1846 case TCC_OPTION_dumpversion:
1847 printf ("%s\n", TCC_VERSION);
1848 exit(0);
1849 break;
1850 case TCC_OPTION_x:
1851 if (*optarg == 'c')
1852 s->filetype = AFF_TYPE_C;
1853 else if (*optarg == 'a')
1854 s->filetype = AFF_TYPE_ASMPP;
1855 else if (*optarg == 'n')
1856 s->filetype = AFF_TYPE_NONE;
1857 else
1858 tcc_warning("unsupported language '%s'", optarg);
1859 break;
1860 case TCC_OPTION_O:
1861 x = atoi(optarg);
1862 if (x > 0)
1863 tcc_define_symbol(s, "__OPTIMIZE__", NULL);
1864 break;
1865 case TCC_OPTION_mms_bitfields:
1866 s->ms_bitfields = 1;
1867 break;
1868 case TCC_OPTION_traditional:
1869 case TCC_OPTION_pedantic:
1870 case TCC_OPTION_pipe:
1871 case TCC_OPTION_s:
1872 /* ignored */
1873 break;
1874 default:
1875 unsupported_option:
1876 if (s->warn_unsupported)
1877 tcc_warning("unsupported option '%s'", r);
1878 break;
1882 if (linker_arg.size) {
1883 r = linker_arg.data;
1884 goto arg_err;
1887 return optind;
1890 LIBTCCAPI int tcc_set_options(TCCState *s, const char *r)
1892 char **argv;
1893 int argc;
1894 int ret, q, c;
1895 CString str;
1897 argc = 0, argv = NULL;
1898 for(;;) {
1899 while (c = (unsigned char)*r, c && c <= ' ')
1900 ++r;
1901 if (c == 0)
1902 break;
1903 q = 0;
1904 cstr_new(&str);
1905 while (c = (unsigned char)*r, c) {
1906 ++r;
1907 if (c == '\\' && (*r == '"' || *r == '\\')) {
1908 c = *r++;
1909 } else if (c == '"') {
1910 q = !q;
1911 continue;
1912 } else if (q == 0 && c <= ' ') {
1913 break;
1915 cstr_ccat(&str, c);
1917 cstr_ccat(&str, 0);
1918 //printf("<%s>\n", str.data), fflush(stdout);
1919 dynarray_add((void ***)&argv, &argc, tcc_strdup(str.data));
1920 cstr_free(&str);
1922 ret = tcc_parse_args(s, argc, argv);
1923 dynarray_reset(&argv, &argc);
1924 return ret;
1927 PUB_FUNC void tcc_print_stats(TCCState *s, unsigned total_time)
1929 if (total_time < 1)
1930 total_time = 1;
1931 if (total_bytes < 1)
1932 total_bytes = 1;
1933 fprintf(stderr, "%d idents, %d lines, %d bytes, %0.3f s, %u lines/s, %0.1f MB/s\n",
1934 tok_ident - TOK_IDENT, total_lines, total_bytes,
1935 (double)total_time/1000,
1936 (unsigned)total_lines*1000/total_time,
1937 (double)total_bytes/1000/total_time);
1940 PUB_FUNC void tcc_set_environment(TCCState *s)
1942 char * path;
1944 path = getenv("C_INCLUDE_PATH");
1945 if(path != NULL) {
1946 tcc_add_include_path(s, path);
1948 path = getenv("CPATH");
1949 if(path != NULL) {
1950 tcc_add_include_path(s, path);
1952 path = getenv("LIBRARY_PATH");
1953 if(path != NULL) {
1954 tcc_add_library_path(s, path);