Actual complete name for DragonFly is 'DragonFly BSD'.
[tinycc.git] / libtcc.c
blob4250933aa260d1903f38311abcd332c5c3e35a8c
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 #endif
45 #ifdef TCC_TARGET_ARM
46 #include "arm-gen.c"
47 #endif
48 #ifdef TCC_TARGET_ARM64
49 #include "arm64-gen.c"
50 #endif
51 #ifdef TCC_TARGET_C67
52 #include "c67-gen.c"
53 #endif
54 #ifdef TCC_TARGET_X86_64
55 #include "x86_64-gen.c"
56 #endif
57 #ifdef CONFIG_TCC_ASM
58 #include "tccasm.c"
59 #if defined TCC_TARGET_I386 || defined TCC_TARGET_X86_64
60 #include "i386-asm.c"
61 #endif
62 #endif
63 #ifdef TCC_TARGET_COFF
64 #include "tcccoff.c"
65 #endif
66 #ifdef TCC_TARGET_PE
67 #include "tccpe.c"
68 #endif
69 #endif /* ONE_SOURCE */
71 /********************************************************/
72 #ifndef CONFIG_TCC_ASM
73 ST_FUNC void asm_instr(void)
75 tcc_error("inline asm() not supported");
77 ST_FUNC void asm_global_instr(void)
79 tcc_error("inline asm() not supported");
81 #endif
83 /********************************************************/
84 #ifdef _WIN32
85 ST_FUNC char *normalize_slashes(char *path)
87 char *p;
88 for (p = path; *p; ++p)
89 if (*p == '\\')
90 *p = '/';
91 return path;
94 static HMODULE tcc_module;
96 /* on win32, we suppose the lib and includes are at the location of 'tcc.exe' */
97 static void tcc_set_lib_path_w32(TCCState *s)
99 char path[1024], *p;
100 GetModuleFileNameA(tcc_module, path, sizeof path);
101 p = tcc_basename(normalize_slashes(strlwr(path)));
102 if (p - 5 > path && 0 == strncmp(p - 5, "/bin/", 5))
103 p -= 5;
104 else if (p > path)
105 p--;
106 *p = 0;
107 tcc_set_lib_path(s, path);
110 #ifdef TCC_TARGET_PE
111 static void tcc_add_systemdir(TCCState *s)
113 char buf[1000];
114 GetSystemDirectory(buf, sizeof buf);
115 tcc_add_library_path(s, normalize_slashes(buf));
117 #endif
119 #ifdef LIBTCC_AS_DLL
120 BOOL WINAPI DllMain (HINSTANCE hDll, DWORD dwReason, LPVOID lpReserved)
122 if (DLL_PROCESS_ATTACH == dwReason)
123 tcc_module = hDll;
124 return TRUE;
126 #endif
127 #endif
129 /********************************************************/
130 /* copy a string and truncate it. */
131 PUB_FUNC char *pstrcpy(char *buf, int buf_size, const char *s)
133 char *q, *q_end;
134 int c;
136 if (buf_size > 0) {
137 q = buf;
138 q_end = buf + buf_size - 1;
139 while (q < q_end) {
140 c = *s++;
141 if (c == '\0')
142 break;
143 *q++ = c;
145 *q = '\0';
147 return buf;
150 /* strcat and truncate. */
151 PUB_FUNC char *pstrcat(char *buf, int buf_size, const char *s)
153 int len;
154 len = strlen(buf);
155 if (len < buf_size)
156 pstrcpy(buf + len, buf_size - len, s);
157 return buf;
160 PUB_FUNC char *pstrncpy(char *out, const char *in, size_t num)
162 memcpy(out, in, num);
163 out[num] = '\0';
164 return out;
167 /* extract the basename of a file */
168 PUB_FUNC char *tcc_basename(const char *name)
170 char *p = strchr(name, 0);
171 while (p > name && !IS_DIRSEP(p[-1]))
172 --p;
173 return p;
176 /* extract extension part of a file
178 * (if no extension, return pointer to end-of-string)
180 PUB_FUNC char *tcc_fileextension (const char *name)
182 char *b = tcc_basename(name);
183 char *e = strrchr(b, '.');
184 return e ? e : strchr(b, 0);
187 /********************************************************/
188 /* memory management */
190 #undef free
191 #undef malloc
192 #undef realloc
194 #ifndef MEM_DEBUG
196 PUB_FUNC void tcc_free(void *ptr)
198 free(ptr);
201 PUB_FUNC void *tcc_malloc(unsigned long size)
203 void *ptr;
204 ptr = malloc(size);
205 if (!ptr && size)
206 tcc_error("memory full (malloc)");
207 return ptr;
210 PUB_FUNC void *tcc_mallocz(unsigned long size)
212 void *ptr;
213 ptr = tcc_malloc(size);
214 memset(ptr, 0, size);
215 return ptr;
218 PUB_FUNC void *tcc_realloc(void *ptr, unsigned long size)
220 void *ptr1;
221 ptr1 = realloc(ptr, size);
222 if (!ptr1 && size)
223 tcc_error("memory full (realloc)");
224 return ptr1;
227 PUB_FUNC char *tcc_strdup(const char *str)
229 char *ptr;
230 ptr = tcc_malloc(strlen(str) + 1);
231 strcpy(ptr, str);
232 return ptr;
235 PUB_FUNC void tcc_memstats(int bench)
239 #else
241 #define MEM_DEBUG_MAGIC1 0xFEEDDEB1
242 #define MEM_DEBUG_MAGIC2 0xFEEDDEB2
243 #define MEM_DEBUG_FILE_LEN 15
245 struct mem_debug_header {
246 size_t magic1;
247 size_t size;
248 struct mem_debug_header *prev;
249 struct mem_debug_header *next;
250 size_t line_num;
251 char file_name[MEM_DEBUG_FILE_LEN + 1];
252 size_t magic2;
255 typedef struct mem_debug_header mem_debug_header_t;
257 static mem_debug_header_t *mem_debug_chain;
258 static size_t mem_cur_size;
259 static size_t mem_max_size;
261 PUB_FUNC void *tcc_malloc_debug(unsigned long size, const char *file, int line)
263 void *ptr;
264 int ofs;
266 mem_debug_header_t *header;
268 ptr = malloc(sizeof(mem_debug_header_t) + size);
269 if (!ptr)
270 tcc_error("memory full (malloc)");
272 mem_cur_size += size;
273 if (mem_cur_size > mem_max_size)
274 mem_max_size = mem_cur_size;
276 header = (mem_debug_header_t *)ptr;
278 header->magic1 = MEM_DEBUG_MAGIC1;
279 header->magic2 = MEM_DEBUG_MAGIC2;
280 header->size = size;
281 header->line_num = line;
283 ofs = strlen(file) - MEM_DEBUG_FILE_LEN;
284 strncpy(header->file_name, file + (ofs > 0 ? ofs : 0), MEM_DEBUG_FILE_LEN);
285 header->file_name[MEM_DEBUG_FILE_LEN] = 0;
287 header->next = mem_debug_chain;
288 header->prev = NULL;
290 if (header->next)
291 header->next->prev = header;
293 mem_debug_chain = header;
295 ptr = (char *)ptr + sizeof(mem_debug_header_t);
296 return ptr;
299 PUB_FUNC void tcc_free_debug(void *ptr)
301 mem_debug_header_t *header;
303 if (!ptr)
304 return;
306 ptr = (char *)ptr - sizeof(mem_debug_header_t);
307 header = (mem_debug_header_t *)ptr;
308 if (header->magic1 != MEM_DEBUG_MAGIC1 ||
309 header->magic2 != MEM_DEBUG_MAGIC2 ||
310 header->size == (size_t)-1 )
312 tcc_error("tcc_free check failed");
315 mem_cur_size -= header->size;
316 header->size = (size_t)-1;
318 if (header->next)
319 header->next->prev = header->prev;
321 if (header->prev)
322 header->prev->next = header->next;
324 if (header == mem_debug_chain)
325 mem_debug_chain = header->next;
327 free(ptr);
331 PUB_FUNC void *tcc_mallocz_debug(unsigned long size, const char *file, int line)
333 void *ptr;
334 ptr = tcc_malloc_debug(size,file,line);
335 memset(ptr, 0, size);
336 return ptr;
339 PUB_FUNC void *tcc_realloc_debug(void *ptr, unsigned long size, const char *file, int line)
341 mem_debug_header_t *header;
342 int mem_debug_chain_update = 0;
344 if (!ptr) {
345 ptr = tcc_malloc_debug(size, file, line);
346 return ptr;
349 ptr = (char *)ptr - sizeof(mem_debug_header_t);
350 header = (mem_debug_header_t *)ptr;
351 if (header->magic1 != MEM_DEBUG_MAGIC1 ||
352 header->magic2 != MEM_DEBUG_MAGIC2 ||
353 header->size == (size_t)-1 )
355 check_error:
356 tcc_error("tcc_realloc check failed");
359 mem_debug_chain_update = (header == mem_debug_chain);
361 mem_cur_size -= header->size;
362 ptr = realloc(ptr, sizeof(mem_debug_header_t) + size);
363 if (!ptr)
364 tcc_error("memory full (realloc)");
366 header = (mem_debug_header_t *)ptr;
367 if (header->magic1 != MEM_DEBUG_MAGIC1 ||
368 header->magic2 != MEM_DEBUG_MAGIC2)
370 goto check_error;
373 mem_cur_size += size;
374 if (mem_cur_size > mem_max_size)
375 mem_max_size = mem_cur_size;
377 header->size = size;
378 if (header->next)
379 header->next->prev = header;
381 if (header->prev)
382 header->prev->next = header;
384 if (mem_debug_chain_update)
385 mem_debug_chain = header;
387 ptr = (char *)ptr + sizeof(mem_debug_header_t);
388 return ptr;
391 PUB_FUNC char *tcc_strdup_debug(const char *str, const char *file, int line)
393 char *ptr;
394 ptr = tcc_malloc_debug(strlen(str) + 1, file, line);
395 strcpy(ptr, str);
396 return ptr;
399 PUB_FUNC void tcc_memstats(int bench)
401 if (mem_cur_size) {
402 mem_debug_header_t *header = mem_debug_chain;
404 fprintf(stderr, "MEM_DEBUG: mem_leak= %d bytes, mem_max_size= %d bytes\n",
405 mem_cur_size, mem_max_size);
407 while (header) {
408 fprintf(stderr, "%s:%u: error: %u bytes leaked\n",
409 header->file_name, header->line_num, header->size);
410 header = header->next;
413 else if (bench)
414 fprintf(stderr, "mem_max_size= %d bytes\n", mem_max_size);
417 #undef MEM_DEBUG_MAGIC1
418 #undef MEM_DEBUG_MAGIC2
419 #undef MEM_DEBUG_FILE_LEN
421 #endif
423 #define free(p) use_tcc_free(p)
424 #define malloc(s) use_tcc_malloc(s)
425 #define realloc(p, s) use_tcc_realloc(p, s)
427 /********************************************************/
428 /* dynarrays */
430 ST_FUNC void dynarray_add(void ***ptab, int *nb_ptr, void *data)
432 int nb, nb_alloc;
433 void **pp;
435 nb = *nb_ptr;
436 pp = *ptab;
437 /* every power of two we double array size */
438 if ((nb & (nb - 1)) == 0) {
439 if (!nb)
440 nb_alloc = 1;
441 else
442 nb_alloc = nb * 2;
443 pp = tcc_realloc(pp, nb_alloc * sizeof(void *));
444 *ptab = pp;
446 pp[nb++] = data;
447 *nb_ptr = nb;
450 ST_FUNC void dynarray_reset(void *pp, int *n)
452 void **p;
453 for (p = *(void***)pp; *n; ++p, --*n)
454 if (*p)
455 tcc_free(*p);
456 tcc_free(*(void**)pp);
457 *(void**)pp = NULL;
460 static void tcc_split_path(TCCState *s, void ***p_ary, int *p_nb_ary, const char *in)
462 const char *p;
463 do {
464 int c;
465 CString str;
467 cstr_new(&str);
468 for (p = in; c = *p, c != '\0' && c != PATHSEP; ++p) {
469 if (c == '{' && p[1] && p[2] == '}') {
470 c = p[1], p += 2;
471 if (c == 'B')
472 cstr_cat(&str, s->tcc_lib_path, -1);
473 } else {
474 cstr_ccat(&str, c);
477 if (str.size) {
478 cstr_ccat(&str, '\0');
479 dynarray_add(p_ary, p_nb_ary, tcc_strdup(str.data));
481 cstr_free(&str);
482 in = p+1;
483 } while (*p);
486 /********************************************************/
488 static void strcat_vprintf(char *buf, int buf_size, const char *fmt, va_list ap)
490 int len;
491 len = strlen(buf);
492 vsnprintf(buf + len, buf_size - len, fmt, ap);
495 static void strcat_printf(char *buf, int buf_size, const char *fmt, ...)
497 va_list ap;
498 va_start(ap, fmt);
499 strcat_vprintf(buf, buf_size, fmt, ap);
500 va_end(ap);
503 static void error1(TCCState *s1, int is_warning, const char *fmt, va_list ap)
505 char buf[2048];
506 BufferedFile **pf, *f;
508 buf[0] = '\0';
509 /* use upper file if inline ":asm:" or token ":paste:" */
510 for (f = file; f && f->filename[0] == ':'; f = f->prev)
512 if (f) {
513 for(pf = s1->include_stack; pf < s1->include_stack_ptr; pf++)
514 strcat_printf(buf, sizeof(buf), "In file included from %s:%d:\n",
515 (*pf)->filename, (*pf)->line_num);
516 if (f->line_num > 0) {
517 strcat_printf(buf, sizeof(buf), "%s:%d: ",
518 f->filename, f->line_num - !!(tok_flags & TOK_FLAG_BOL));
519 } else {
520 strcat_printf(buf, sizeof(buf), "%s: ",
521 f->filename);
523 } else {
524 strcat_printf(buf, sizeof(buf), "tcc: ");
526 if (is_warning)
527 strcat_printf(buf, sizeof(buf), "warning: ");
528 else
529 strcat_printf(buf, sizeof(buf), "error: ");
530 strcat_vprintf(buf, sizeof(buf), fmt, ap);
532 if (!s1->error_func) {
533 /* default case: stderr */
534 if (s1->ppfp) /* print a newline during tcc -E */
535 fprintf(s1->ppfp, "\n"), fflush(s1->ppfp);
536 fprintf(stderr, "%s\n", buf);
537 fflush(stderr); /* print error/warning now (win32) */
538 } else {
539 s1->error_func(s1->error_opaque, buf);
541 if (!is_warning || s1->warn_error)
542 s1->nb_errors++;
545 LIBTCCAPI void tcc_set_error_func(TCCState *s, void *error_opaque,
546 void (*error_func)(void *opaque, const char *msg))
548 s->error_opaque = error_opaque;
549 s->error_func = error_func;
552 /* error without aborting current compilation */
553 PUB_FUNC void tcc_error_noabort(const char *fmt, ...)
555 TCCState *s1 = tcc_state;
556 va_list ap;
558 va_start(ap, fmt);
559 error1(s1, 0, fmt, ap);
560 va_end(ap);
563 PUB_FUNC void tcc_error(const char *fmt, ...)
565 TCCState *s1 = tcc_state;
566 va_list ap;
568 va_start(ap, fmt);
569 error1(s1, 0, fmt, ap);
570 va_end(ap);
571 /* better than nothing: in some cases, we accept to handle errors */
572 if (s1->error_set_jmp_enabled) {
573 longjmp(s1->error_jmp_buf, 1);
574 } else {
575 /* XXX: eliminate this someday */
576 exit(1);
580 PUB_FUNC void tcc_warning(const char *fmt, ...)
582 TCCState *s1 = tcc_state;
583 va_list ap;
585 if (s1->warn_none)
586 return;
588 va_start(ap, fmt);
589 error1(s1, 1, fmt, ap);
590 va_end(ap);
593 /********************************************************/
594 /* I/O layer */
596 ST_FUNC void tcc_open_bf(TCCState *s1, const char *filename, int initlen)
598 BufferedFile *bf;
599 int buflen = initlen ? initlen : IO_BUF_SIZE;
601 bf = tcc_mallocz(sizeof(BufferedFile) + buflen);
602 bf->buf_ptr = bf->buffer;
603 bf->buf_end = bf->buffer + initlen;
604 bf->buf_end[0] = CH_EOB; /* put eob symbol */
605 pstrcpy(bf->filename, sizeof(bf->filename), filename);
606 #ifdef _WIN32
607 normalize_slashes(bf->filename);
608 #endif
609 bf->line_num = 1;
610 bf->ifdef_stack_ptr = s1->ifdef_stack_ptr;
611 bf->fd = -1;
612 bf->prev = file;
613 file = bf;
616 ST_FUNC void tcc_close(void)
618 BufferedFile *bf = file;
619 if (bf->fd > 0) {
620 close(bf->fd);
621 total_lines += bf->line_num;
623 file = bf->prev;
624 tcc_free(bf);
627 ST_FUNC int tcc_open(TCCState *s1, const char *filename)
629 int fd;
630 if (strcmp(filename, "-") == 0)
631 fd = 0, filename = "<stdin>";
632 else
633 fd = open(filename, O_RDONLY | O_BINARY);
634 if ((s1->verbose == 2 && fd >= 0) || s1->verbose == 3)
635 printf("%s %*s%s\n", fd < 0 ? "nf":"->",
636 (int)(s1->include_stack_ptr - s1->include_stack), "", filename);
637 if (fd < 0)
638 return -1;
640 tcc_open_bf(s1, filename, 0);
641 file->fd = fd;
642 return fd;
645 /* compile the C file opened in 'file'. Return non zero if errors. */
646 static int tcc_compile(TCCState *s1)
648 Sym *define_start;
650 preprocess_init(s1);
651 define_start = define_stack;
653 if (setjmp(s1->error_jmp_buf) == 0) {
654 s1->nb_errors = 0;
655 s1->error_set_jmp_enabled = 1;
657 tccgen_start(s1);
658 #ifdef INC_DEBUG
659 printf("%s: **** new file\n", file->filename);
660 #endif
661 ch = file->buf_ptr[0];
662 tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
663 parse_flags = PARSE_FLAG_PREPROCESS | PARSE_FLAG_TOK_NUM | PARSE_FLAG_TOK_STR;
664 next();
665 decl(VT_CONST);
666 if (tok != TOK_EOF)
667 expect("declaration");
668 gen_inline_functions();
669 tccgen_end(s1);
672 s1->error_set_jmp_enabled = 0;
673 /* reset define stack, but keep -D and built-ins */
674 free_defines(define_start);
675 sym_pop(&global_stack, NULL);
676 sym_pop(&local_stack, NULL);
677 return s1->nb_errors != 0 ? -1 : 0;
680 LIBTCCAPI int tcc_compile_string(TCCState *s, const char *str)
682 int len, ret;
684 len = strlen(str);
685 tcc_open_bf(s, "<string>", len);
686 memcpy(file->buffer, str, len);
687 ret = tcc_compile(s);
688 tcc_close();
689 return ret;
692 /* define a preprocessor symbol. A value can also be provided with the '=' operator */
693 LIBTCCAPI void tcc_define_symbol(TCCState *s1, const char *sym, const char *value)
695 int len1, len2;
696 /* default value */
697 if (!value)
698 value = "1";
699 len1 = strlen(sym);
700 len2 = strlen(value);
702 /* init file structure */
703 tcc_open_bf(s1, "<define>", len1 + len2 + 1);
704 memcpy(file->buffer, sym, len1);
705 file->buffer[len1] = ' ';
706 memcpy(file->buffer + len1 + 1, value, len2);
708 /* parse with define parser */
709 ch = file->buf_ptr[0];
710 next_nomacro();
711 parse_define();
713 tcc_close();
716 /* undefine a preprocessor symbol */
717 LIBTCCAPI void tcc_undefine_symbol(TCCState *s1, const char *sym)
719 TokenSym *ts;
720 Sym *s;
721 ts = tok_alloc(sym, strlen(sym));
722 s = define_find(ts->tok);
723 /* undefine symbol by putting an invalid name */
724 if (s)
725 define_undef(s);
728 /* cleanup all static data used during compilation */
729 static void tcc_cleanup(void)
731 if (NULL == tcc_state)
732 return;
733 tcc_state = NULL;
735 preprocess_delete();
737 /* free sym_pools */
738 dynarray_reset(&sym_pools, &nb_sym_pools);
739 /* reset symbol stack */
740 sym_free_first = NULL;
743 LIBTCCAPI TCCState *tcc_new(void)
745 TCCState *s;
746 tcc_cleanup();
748 s = tcc_mallocz(sizeof(TCCState));
749 if (!s)
750 return NULL;
751 tcc_state = s;
753 s->alacarte_link = 1;
754 s->nocommon = 1;
755 s->warn_implicit_function_declaration = 1;
757 #ifdef CHAR_IS_UNSIGNED
758 s->char_is_unsigned = 1;
759 #endif
760 #ifdef TCC_TARGET_I386
761 s->seg_size = 32;
762 #endif
763 #ifdef TCC_IS_NATIVE
764 s->runtime_main = "main";
765 #endif
766 /* enable this if you want symbols with leading underscore on windows: */
767 #if 0 /* def TCC_TARGET_PE */
768 s->leading_underscore = 1;
769 #endif
770 #ifdef _WIN32
771 tcc_set_lib_path_w32(s);
772 #else
773 tcc_set_lib_path(s, CONFIG_TCCDIR);
774 #endif
776 tccelf_new(s);
777 preprocess_new();
778 s->include_stack_ptr = s->include_stack;
780 /* we add dummy defines for some special macros to speed up tests
781 and to have working defined() */
782 define_push(TOK___LINE__, MACRO_OBJ, NULL, NULL);
783 define_push(TOK___FILE__, MACRO_OBJ, NULL, NULL);
784 define_push(TOK___DATE__, MACRO_OBJ, NULL, NULL);
785 define_push(TOK___TIME__, MACRO_OBJ, NULL, NULL);
787 /* define __TINYC__ 92X */
788 char buffer[32]; int a,b,c;
789 sscanf(TCC_VERSION, "%d.%d.%d", &a, &b, &c);
790 sprintf(buffer, "%d", a*10000 + b*100 + c);
791 tcc_define_symbol(s, "__TINYC__", buffer);
794 /* standard defines */
795 tcc_define_symbol(s, "__STDC__", NULL);
796 tcc_define_symbol(s, "__STDC_VERSION__", "199901L");
797 tcc_define_symbol(s, "__STDC_HOSTED__", NULL);
799 /* target defines */
800 #if defined(TCC_TARGET_I386)
801 tcc_define_symbol(s, "__i386__", NULL);
802 tcc_define_symbol(s, "__i386", NULL);
803 tcc_define_symbol(s, "i386", NULL);
804 #elif defined(TCC_TARGET_X86_64)
805 tcc_define_symbol(s, "__x86_64__", NULL);
806 #elif defined(TCC_TARGET_ARM)
807 tcc_define_symbol(s, "__ARM_ARCH_4__", NULL);
808 tcc_define_symbol(s, "__arm_elf__", NULL);
809 tcc_define_symbol(s, "__arm_elf", NULL);
810 tcc_define_symbol(s, "arm_elf", NULL);
811 tcc_define_symbol(s, "__arm__", NULL);
812 tcc_define_symbol(s, "__arm", NULL);
813 tcc_define_symbol(s, "arm", NULL);
814 tcc_define_symbol(s, "__APCS_32__", NULL);
815 tcc_define_symbol(s, "__ARMEL__", NULL);
816 #if defined(TCC_ARM_EABI)
817 tcc_define_symbol(s, "__ARM_EABI__", NULL);
818 #endif
819 #if defined(TCC_ARM_HARDFLOAT)
820 s->float_abi = ARM_HARD_FLOAT;
821 tcc_define_symbol(s, "__ARM_PCS_VFP", NULL);
822 #else
823 s->float_abi = ARM_SOFTFP_FLOAT;
824 #endif
825 #elif defined(TCC_TARGET_ARM64)
826 tcc_define_symbol(s, "__aarch64__", NULL);
827 #endif
829 #ifdef TCC_TARGET_PE
830 tcc_define_symbol(s, "_WIN32", NULL);
831 # ifdef TCC_TARGET_X86_64
832 tcc_define_symbol(s, "_WIN64", NULL);
833 /* Those are defined by Visual Studio */
834 tcc_define_symbol(s, "_M_X64", "100");
835 tcc_define_symbol(s, "_M_AMD64", "100");
836 # else
837 /* Defined by Visual Studio. 300 == 80386. */
838 tcc_define_symbol(s, "_M_IX86", "300");
839 # endif
840 #else
841 tcc_define_symbol(s, "__unix__", NULL);
842 tcc_define_symbol(s, "__unix", NULL);
843 tcc_define_symbol(s, "unix", NULL);
844 # if defined(__linux__)
845 tcc_define_symbol(s, "__linux__", NULL);
846 tcc_define_symbol(s, "__linux", NULL);
847 # endif
848 # if defined(__FreeBSD__)
849 tcc_define_symbol(s, "__FreeBSD__", "__FreeBSD__");
850 /* No 'Thread Storage Local' on FreeBSD with tcc */
851 tcc_define_symbol(s, "__NO_TLS", NULL);
852 # endif
853 # if defined(__FreeBSD_kernel__)
854 tcc_define_symbol(s, "__FreeBSD_kernel__", NULL);
855 # endif
856 #endif
857 # if defined(__NetBSD__)
858 tcc_define_symbol(s, "__NetBSD__", "__NetBSD__");
859 # endif
860 # if defined(__OpenBSD__)
861 tcc_define_symbol(s, "__OpenBSD__", "__OpenBSD__");
862 # endif
864 /* TinyCC & gcc defines */
865 #if defined(TCC_TARGET_PE) && defined(TCC_TARGET_X86_64)
866 /* 64bit Windows. */
867 tcc_define_symbol(s, "__SIZE_TYPE__", "unsigned long long");
868 tcc_define_symbol(s, "__PTRDIFF_TYPE__", "long long");
869 tcc_define_symbol(s, "__LLP64__", NULL);
870 #elif defined(TCC_TARGET_X86_64) || defined(TCC_TARGET_ARM64)
871 /* Other 64bit systems. */
872 tcc_define_symbol(s, "__SIZE_TYPE__", "unsigned long");
873 tcc_define_symbol(s, "__PTRDIFF_TYPE__", "long");
874 tcc_define_symbol(s, "__LP64__", NULL);
875 #else
876 /* Other 32bit systems. */
877 tcc_define_symbol(s, "__SIZE_TYPE__", "unsigned long");
878 tcc_define_symbol(s, "__PTRDIFF_TYPE__", "long");
879 tcc_define_symbol(s, "__ILP32__", NULL);
880 #endif
882 #ifdef TCC_TARGET_PE
883 tcc_define_symbol(s, "__WCHAR_TYPE__", "unsigned short");
884 tcc_define_symbol(s, "__WINT_TYPE__", "unsigned short");
885 #else
886 tcc_define_symbol(s, "__WCHAR_TYPE__", "int");
887 /* wint_t is unsigned int by default, but (signed) int on BSDs
888 and unsigned short on windows. Other OSes might have still
889 other conventions, sigh. */
890 # if defined(__FreeBSD__) || defined (__FreeBSD_kernel__) \
891 || defined(__NetBSD__) || defined(__OpenBSD__)
892 tcc_define_symbol(s, "__WINT_TYPE__", "int");
893 # else
894 tcc_define_symbol(s, "__WINT_TYPE__", "unsigned int");
895 # endif
896 # if 0
897 /* glibc defines */
898 tcc_define_symbol(s, "__REDIRECT(name, proto, alias)",
899 "name proto __asm__ (#alias)");
900 tcc_define_symbol(s, "__REDIRECT_NTH(name, proto, alias)",
901 "name proto __asm__ (#alias) __THROW");
902 # endif
903 # if 1
904 /* define __GNUC__ to have some useful stuff from sys/cdefs.h */
905 tcc_define_symbol(s, "__GNUC__", "2");
906 tcc_define_symbol(s, "__GNUC_MINOR__", "1");
907 tcc_define_symbol(s, "__builtin_alloca", "alloca");
908 tcc_define_symbol(s, "__builtin_memcpy", "memcpy");
909 tcc_define_symbol(s, "__USER_LABEL_PREFIX__", "");
910 # endif
911 #endif /* ndef TCC_TARGET_PE */
913 return s;
916 LIBTCCAPI void tcc_delete(TCCState *s1)
918 int bench = s1->do_bench;
920 tcc_cleanup();
922 /* free sections */
923 tccelf_delete(s1);
925 /* free library paths */
926 dynarray_reset(&s1->library_paths, &s1->nb_library_paths);
927 dynarray_reset(&s1->crt_paths, &s1->nb_crt_paths);
929 /* free include paths */
930 dynarray_reset(&s1->cached_includes, &s1->nb_cached_includes);
931 dynarray_reset(&s1->include_paths, &s1->nb_include_paths);
932 dynarray_reset(&s1->sysinclude_paths, &s1->nb_sysinclude_paths);
934 tcc_free(s1->tcc_lib_path);
935 tcc_free(s1->soname);
936 tcc_free(s1->rpath);
937 tcc_free(s1->init_symbol);
938 tcc_free(s1->fini_symbol);
939 tcc_free(s1->outfile);
940 tcc_free(s1->deps_outfile);
941 dynarray_reset(&s1->files, &s1->nb_files);
942 dynarray_reset(&s1->target_deps, &s1->nb_target_deps);
943 dynarray_reset(&s1->pragma_libs, &s1->nb_pragma_libs);
945 #ifdef TCC_IS_NATIVE
946 # ifdef HAVE_SELINUX
947 munmap (s1->write_mem, s1->mem_size);
948 munmap (s1->runtime_mem, s1->mem_size);
949 # else
950 tcc_free(s1->runtime_mem);
951 # endif
952 #endif
954 tcc_free(s1->sym_attrs);
955 tcc_free(s1);
956 tcc_memstats(bench);
959 LIBTCCAPI int tcc_set_output_type(TCCState *s, int output_type)
961 s->output_type = output_type;
963 /* always elf for objects */
964 if (output_type == TCC_OUTPUT_OBJ)
965 s->output_format = TCC_OUTPUT_FORMAT_ELF;
967 if (s->char_is_unsigned)
968 tcc_define_symbol(s, "__CHAR_UNSIGNED__", NULL);
970 if (!s->nostdinc) {
971 /* default include paths */
972 /* -isystem paths have already been handled */
973 tcc_add_sysinclude_path(s, CONFIG_TCC_SYSINCLUDEPATHS);
976 #ifdef CONFIG_TCC_BCHECK
977 /* if bound checking, then add corresponding sections */
978 if (s->do_bounds_check) {
979 /* define symbol */
980 tcc_define_symbol(s, "__BOUNDS_CHECKING_ON", NULL);
981 /* create bounds sections */
982 bounds_section = new_section(s, ".bounds",
983 SHT_PROGBITS, SHF_ALLOC);
984 lbounds_section = new_section(s, ".lbounds",
985 SHT_PROGBITS, SHF_ALLOC);
987 #endif
988 /* add debug sections */
989 if (s->do_debug) {
990 /* stab symbols */
991 stab_section = new_section(s, ".stab", SHT_PROGBITS, 0);
992 stab_section->sh_entsize = sizeof(Stab_Sym);
993 stabstr_section = new_section(s, ".stabstr", SHT_STRTAB, 0);
994 put_elf_str(stabstr_section, "");
995 stab_section->link = stabstr_section;
996 /* put first entry */
997 put_stabs("", 0, 0, 0, 0);
1000 tcc_add_library_path(s, CONFIG_TCC_LIBPATHS);
1002 #ifdef TCC_TARGET_PE
1003 # ifdef _WIN32
1004 if (!s->nostdlib && output_type != TCC_OUTPUT_OBJ)
1005 tcc_add_systemdir(s);
1006 # endif
1007 #else
1008 /* paths for crt objects */
1009 tcc_split_path(s, (void ***)&s->crt_paths, &s->nb_crt_paths, CONFIG_TCC_CRTPREFIX);
1010 /* add libc crt1/crti objects */
1011 if ((output_type == TCC_OUTPUT_EXE || output_type == TCC_OUTPUT_DLL) &&
1012 !s->nostdlib) {
1013 if (output_type != TCC_OUTPUT_DLL)
1014 tcc_add_crt(s, "crt1.o");
1015 tcc_add_crt(s, "crti.o");
1017 #endif
1018 return 0;
1021 LIBTCCAPI int tcc_add_include_path(TCCState *s, const char *pathname)
1023 tcc_split_path(s, (void ***)&s->include_paths, &s->nb_include_paths, pathname);
1024 return 0;
1027 LIBTCCAPI int tcc_add_sysinclude_path(TCCState *s, const char *pathname)
1029 tcc_split_path(s, (void ***)&s->sysinclude_paths, &s->nb_sysinclude_paths, pathname);
1030 return 0;
1033 ST_FUNC int tcc_add_file_internal(TCCState *s1, const char *filename, int flags)
1035 int ret, filetype;
1037 filetype = flags & 0x0F;
1038 if (filetype == 0) {
1039 /* use a file extension to detect a filetype */
1040 const char *ext = tcc_fileextension(filename);
1041 if (ext[0]) {
1042 ext++;
1043 if (!strcmp(ext, "S"))
1044 filetype = AFF_TYPE_ASMPP;
1045 else if (!strcmp(ext, "s"))
1046 filetype = AFF_TYPE_ASM;
1047 else if (!PATHCMP(ext, "c") || !PATHCMP(ext, "i"))
1048 filetype = AFF_TYPE_C;
1049 else
1050 filetype = AFF_TYPE_BIN;
1051 } else {
1052 filetype = AFF_TYPE_C;
1056 /* open the file */
1057 ret = tcc_open(s1, filename);
1058 if (ret < 0) {
1059 if (flags & AFF_PRINT_ERROR)
1060 tcc_error_noabort("file '%s' not found", filename);
1061 return ret;
1064 /* update target deps */
1065 dynarray_add((void ***)&s1->target_deps, &s1->nb_target_deps,
1066 tcc_strdup(filename));
1068 parse_flags = 0;
1069 /* if .S file, define __ASSEMBLER__ like gcc does */
1070 if (filetype == AFF_TYPE_ASM || filetype == AFF_TYPE_ASMPP) {
1071 tcc_define_symbol(s1, "__ASSEMBLER__", NULL);
1072 parse_flags = PARSE_FLAG_ASM_FILE;
1075 if (flags & AFF_PREPROCESS) {
1076 ret = tcc_preprocess(s1);
1077 } else if (filetype == AFF_TYPE_C) {
1078 ret = tcc_compile(s1);
1079 #ifdef CONFIG_TCC_ASM
1080 } else if (filetype == AFF_TYPE_ASMPP) {
1081 /* non preprocessed assembler */
1082 ret = tcc_assemble(s1, 1);
1083 } else if (filetype == AFF_TYPE_ASM) {
1084 /* preprocessed assembler */
1085 ret = tcc_assemble(s1, 0);
1086 #endif
1087 } else {
1088 ElfW(Ehdr) ehdr;
1089 int fd, obj_type;
1091 fd = file->fd;
1092 obj_type = tcc_object_type(fd, &ehdr);
1093 lseek(fd, 0, SEEK_SET);
1095 /* do not display line number if error */
1096 file->line_num = 0;
1098 switch (obj_type) {
1099 case AFF_BINTYPE_REL:
1100 ret = tcc_load_object_file(s1, fd, 0);
1101 break;
1102 #ifndef TCC_TARGET_PE
1103 case AFF_BINTYPE_DYN:
1104 if (s1->output_type == TCC_OUTPUT_MEMORY) {
1105 ret = 0;
1106 #ifdef TCC_IS_NATIVE
1107 if (NULL == dlopen(filename, RTLD_GLOBAL | RTLD_LAZY))
1108 ret = -1;
1109 #endif
1110 } else {
1111 ret = tcc_load_dll(s1, fd, filename,
1112 (flags & AFF_REFERENCED_DLL) != 0);
1114 break;
1115 #endif
1116 case AFF_BINTYPE_AR:
1117 ret = tcc_load_archive(s1, fd);
1118 break;
1119 #ifdef TCC_TARGET_COFF
1120 case AFF_BINTYPE_C67:
1121 ret = tcc_load_coff(s1, fd);
1122 break;
1123 #endif
1124 default:
1125 #ifdef TCC_TARGET_PE
1126 ret = pe_load_file(s1, filename, fd);
1127 #else
1128 /* as GNU ld, consider it is an ld script if not recognized */
1129 ret = tcc_load_ldscript(s1);
1130 #endif
1131 if (ret < 0)
1132 tcc_error_noabort("unrecognized file type");
1133 break;
1136 tcc_close();
1137 return ret;
1140 LIBTCCAPI int tcc_add_file(TCCState *s, const char *filename)
1142 if (s->output_type == TCC_OUTPUT_PREPROCESS)
1143 return tcc_add_file_internal(s, filename, AFF_PRINT_ERROR | AFF_PREPROCESS | s->filetype);
1144 else
1145 return tcc_add_file_internal(s, filename, AFF_PRINT_ERROR | s->filetype);
1148 LIBTCCAPI int tcc_add_library_path(TCCState *s, const char *pathname)
1150 tcc_split_path(s, (void ***)&s->library_paths, &s->nb_library_paths, pathname);
1151 return 0;
1154 static int tcc_add_library_internal(TCCState *s, const char *fmt,
1155 const char *filename, int flags, char **paths, int nb_paths)
1157 char buf[1024];
1158 int i;
1160 for(i = 0; i < nb_paths; i++) {
1161 snprintf(buf, sizeof(buf), fmt, paths[i], filename);
1162 if (tcc_add_file_internal(s, buf, flags | AFF_TYPE_BIN) == 0)
1163 return 0;
1165 return -1;
1168 #ifndef TCC_TARGET_PE
1169 /* find and load a dll. Return non zero if not found */
1170 /* XXX: add '-rpath' option support ? */
1171 ST_FUNC int tcc_add_dll(TCCState *s, const char *filename, int flags)
1173 return tcc_add_library_internal(s, "%s/%s", filename, flags,
1174 s->library_paths, s->nb_library_paths);
1176 #endif
1178 ST_FUNC int tcc_add_crt(TCCState *s, const char *filename)
1180 if (-1 == tcc_add_library_internal(s, "%s/%s",
1181 filename, 0, s->crt_paths, s->nb_crt_paths))
1182 tcc_error_noabort("file '%s' not found", filename);
1183 return 0;
1186 /* the library name is the same as the argument of the '-l' option */
1187 LIBTCCAPI int tcc_add_library(TCCState *s, const char *libraryname)
1189 #ifdef TCC_TARGET_PE
1190 const char *libs[] = { "%s/%s.def", "%s/lib%s.def", "%s/%s.dll", "%s/lib%s.dll", "%s/lib%s.a", NULL };
1191 const char **pp = s->static_link ? libs + 4 : libs;
1192 #else
1193 const char *libs[] = { "%s/lib%s.so", "%s/lib%s.a", NULL };
1194 const char **pp = s->static_link ? libs + 1 : libs;
1195 #endif
1196 while (*pp) {
1197 if (0 == tcc_add_library_internal(s, *pp,
1198 libraryname, 0, s->library_paths, s->nb_library_paths))
1199 return 0;
1200 ++pp;
1202 return -1;
1205 PUB_FUNC int tcc_add_library_err(TCCState *s, const char *libname)
1207 int ret = tcc_add_library(s, libname);
1208 if (ret < 0)
1209 tcc_error_noabort("cannot find library 'lib%s'", libname);
1210 return ret;
1213 /* habdle #pragma comment(lib,) */
1214 ST_FUNC void tcc_add_pragma_libs(TCCState *s1)
1216 int i;
1217 for (i = 0; i < s1->nb_pragma_libs; i++)
1218 tcc_add_library_err(s1, s1->pragma_libs[i]);
1221 LIBTCCAPI int tcc_add_symbol(TCCState *s, const char *name, const void *val)
1223 #ifdef TCC_TARGET_PE
1224 /* On x86_64 'val' might not be reachable with a 32bit offset.
1225 So it is handled here as if it were in a DLL. */
1226 pe_putimport(s, 0, name, (uintptr_t)val);
1227 #else
1228 add_elf_sym(symtab_section, (uintptr_t)val, 0,
1229 ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE), 0,
1230 SHN_ABS, name);
1231 #endif
1232 return 0;
1235 LIBTCCAPI void tcc_set_lib_path(TCCState *s, const char *path)
1237 tcc_free(s->tcc_lib_path);
1238 s->tcc_lib_path = tcc_strdup(path);
1241 #define WD_ALL 0x0001 /* warning is activated when using -Wall */
1242 #define FD_INVERT 0x0002 /* invert value before storing */
1244 typedef struct FlagDef {
1245 uint16_t offset;
1246 uint16_t flags;
1247 const char *name;
1248 } FlagDef;
1250 static const FlagDef warning_defs[] = {
1251 { offsetof(TCCState, warn_unsupported), 0, "unsupported" },
1252 { offsetof(TCCState, warn_write_strings), 0, "write-strings" },
1253 { offsetof(TCCState, warn_error), 0, "error" },
1254 { offsetof(TCCState, warn_implicit_function_declaration), WD_ALL,
1255 "implicit-function-declaration" },
1258 static int no_flag(const char **pp)
1260 const char *p = *pp;
1261 if (*p != 'n' || *++p != 'o' || *++p != '-')
1262 return 0;
1263 *pp = p + 1;
1264 return 1;
1267 ST_FUNC int set_flag(TCCState *s, const FlagDef *flags, int nb_flags,
1268 const char *name, int value)
1270 int i;
1271 const FlagDef *p;
1272 const char *r;
1274 r = name;
1275 if (no_flag(&r))
1276 value = !value;
1278 for(i = 0, p = flags; i < nb_flags; i++, p++) {
1279 if (!strcmp(r, p->name))
1280 goto found;
1282 return -1;
1283 found:
1284 if (p->flags & FD_INVERT)
1285 value = !value;
1286 *(int *)((uint8_t *)s + p->offset) = value;
1287 return 0;
1290 /* set/reset a warning */
1291 static int tcc_set_warning(TCCState *s, const char *warning_name, int value)
1293 int i;
1294 const FlagDef *p;
1296 if (!strcmp(warning_name, "all")) {
1297 for(i = 0, p = warning_defs; i < countof(warning_defs); i++, p++) {
1298 if (p->flags & WD_ALL)
1299 *(int *)((uint8_t *)s + p->offset) = 1;
1301 return 0;
1302 } else {
1303 return set_flag(s, warning_defs, countof(warning_defs),
1304 warning_name, value);
1308 static const FlagDef flag_defs[] = {
1309 { offsetof(TCCState, char_is_unsigned), 0, "unsigned-char" },
1310 { offsetof(TCCState, char_is_unsigned), FD_INVERT, "signed-char" },
1311 { offsetof(TCCState, nocommon), FD_INVERT, "common" },
1312 { offsetof(TCCState, leading_underscore), 0, "leading-underscore" },
1313 { offsetof(TCCState, ms_extensions), 0, "ms-extensions" },
1314 { offsetof(TCCState, old_struct_init_code), 0, "old-struct-init-code" },
1315 { offsetof(TCCState, dollars_in_identifiers), 0, "dollars-in-identifiers" },
1318 /* set/reset a flag */
1319 static int tcc_set_flag(TCCState *s, const char *flag_name, int value)
1321 return set_flag(s, flag_defs, countof(flag_defs),
1322 flag_name, value);
1326 static int strstart(const char *val, const char **str)
1328 const char *p, *q;
1329 p = *str;
1330 q = val;
1331 while (*q) {
1332 if (*p != *q)
1333 return 0;
1334 p++;
1335 q++;
1337 *str = p;
1338 return 1;
1341 /* Like strstart, but automatically takes into account that ld options can
1343 * - start with double or single dash (e.g. '--soname' or '-soname')
1344 * - arguments can be given as separate or after '=' (e.g. '-Wl,-soname,x.so'
1345 * or '-Wl,-soname=x.so')
1347 * you provide `val` always in 'option[=]' form (no leading -)
1349 static int link_option(const char *str, const char *val, const char **ptr)
1351 const char *p, *q;
1352 int ret;
1354 /* there should be 1 or 2 dashes */
1355 if (*str++ != '-')
1356 return 0;
1357 if (*str == '-')
1358 str++;
1360 /* then str & val should match (potentialy up to '=') */
1361 p = str;
1362 q = val;
1364 ret = 1;
1365 if (q[0] == '?') {
1366 ++q;
1367 if (no_flag(&p))
1368 ret = -1;
1371 while (*q != '\0' && *q != '=') {
1372 if (*p != *q)
1373 return 0;
1374 p++;
1375 q++;
1378 /* '=' near eos means ',' or '=' is ok */
1379 if (*q == '=') {
1380 if (*p == 0)
1381 *ptr = p;
1382 if (*p != ',' && *p != '=')
1383 return 0;
1384 p++;
1386 *ptr = p;
1387 return ret;
1390 static const char *skip_linker_arg(const char **str)
1392 const char *s1 = *str;
1393 const char *s2 = strchr(s1, ',');
1394 *str = s2 ? s2++ : (s2 = s1 + strlen(s1));
1395 return s2;
1398 static char *copy_linker_arg(const char *p)
1400 const char *q = p;
1401 skip_linker_arg(&q);
1402 return pstrncpy(tcc_malloc(q - p + 1), p, q - p);
1405 /* set linker options */
1406 static int tcc_set_linker(TCCState *s, const char *option)
1408 while (*option) {
1410 const char *p = NULL;
1411 char *end = NULL;
1412 int ignoring = 0;
1413 int ret;
1415 if (link_option(option, "Bsymbolic", &p)) {
1416 s->symbolic = 1;
1417 } else if (link_option(option, "nostdlib", &p)) {
1418 s->nostdlib = 1;
1419 } else if (link_option(option, "fini=", &p)) {
1420 s->fini_symbol = copy_linker_arg(p);
1421 ignoring = 1;
1422 } else if (link_option(option, "image-base=", &p)
1423 || link_option(option, "Ttext=", &p)) {
1424 s->text_addr = strtoull(p, &end, 16);
1425 s->has_text_addr = 1;
1426 } else if (link_option(option, "init=", &p)) {
1427 s->init_symbol = copy_linker_arg(p);
1428 ignoring = 1;
1429 } else if (link_option(option, "oformat=", &p)) {
1430 #if defined(TCC_TARGET_PE)
1431 if (strstart("pe-", &p)) {
1432 #elif defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
1433 if (strstart("elf64-", &p)) {
1434 #else
1435 if (strstart("elf32-", &p)) {
1436 #endif
1437 s->output_format = TCC_OUTPUT_FORMAT_ELF;
1438 } else if (!strcmp(p, "binary")) {
1439 s->output_format = TCC_OUTPUT_FORMAT_BINARY;
1440 #ifdef TCC_TARGET_COFF
1441 } else if (!strcmp(p, "coff")) {
1442 s->output_format = TCC_OUTPUT_FORMAT_COFF;
1443 #endif
1444 } else
1445 goto err;
1447 } else if (link_option(option, "as-needed", &p)) {
1448 ignoring = 1;
1449 } else if (link_option(option, "O", &p)) {
1450 ignoring = 1;
1451 } else if (link_option(option, "rpath=", &p)) {
1452 s->rpath = copy_linker_arg(p);
1453 } else if (link_option(option, "section-alignment=", &p)) {
1454 s->section_align = strtoul(p, &end, 16);
1455 } else if (link_option(option, "soname=", &p)) {
1456 s->soname = copy_linker_arg(p);
1457 #ifdef TCC_TARGET_PE
1458 } else if (link_option(option, "file-alignment=", &p)) {
1459 s->pe_file_align = strtoul(p, &end, 16);
1460 } else if (link_option(option, "stack=", &p)) {
1461 s->pe_stack_size = strtoul(p, &end, 10);
1462 } else if (link_option(option, "subsystem=", &p)) {
1463 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
1464 if (!strcmp(p, "native")) {
1465 s->pe_subsystem = 1;
1466 } else if (!strcmp(p, "console")) {
1467 s->pe_subsystem = 3;
1468 } else if (!strcmp(p, "gui")) {
1469 s->pe_subsystem = 2;
1470 } else if (!strcmp(p, "posix")) {
1471 s->pe_subsystem = 7;
1472 } else if (!strcmp(p, "efiapp")) {
1473 s->pe_subsystem = 10;
1474 } else if (!strcmp(p, "efiboot")) {
1475 s->pe_subsystem = 11;
1476 } else if (!strcmp(p, "efiruntime")) {
1477 s->pe_subsystem = 12;
1478 } else if (!strcmp(p, "efirom")) {
1479 s->pe_subsystem = 13;
1480 #elif defined(TCC_TARGET_ARM)
1481 if (!strcmp(p, "wince")) {
1482 s->pe_subsystem = 9;
1483 #endif
1484 } else
1485 goto err;
1486 #endif
1487 } else if (ret = link_option(option, "?whole-archive", &p), ret) {
1488 s->alacarte_link = ret < 0;
1489 } else if (p) {
1490 return 0;
1491 } else {
1492 err:
1493 tcc_error("unsupported linker option '%s'", option);
1496 if (ignoring && s->warn_unsupported)
1497 tcc_warning("unsupported linker option '%s'", option);
1499 option = skip_linker_arg(&p);
1501 return 1;
1504 typedef struct TCCOption {
1505 const char *name;
1506 uint16_t index;
1507 uint16_t flags;
1508 } TCCOption;
1510 enum {
1511 TCC_OPTION_HELP,
1512 TCC_OPTION_I,
1513 TCC_OPTION_D,
1514 TCC_OPTION_U,
1515 TCC_OPTION_P,
1516 TCC_OPTION_L,
1517 TCC_OPTION_B,
1518 TCC_OPTION_l,
1519 TCC_OPTION_bench,
1520 TCC_OPTION_bt,
1521 TCC_OPTION_b,
1522 TCC_OPTION_g,
1523 TCC_OPTION_c,
1524 TCC_OPTION_dumpversion,
1525 TCC_OPTION_d,
1526 TCC_OPTION_float_abi,
1527 TCC_OPTION_static,
1528 TCC_OPTION_std,
1529 TCC_OPTION_shared,
1530 TCC_OPTION_soname,
1531 TCC_OPTION_o,
1532 TCC_OPTION_r,
1533 TCC_OPTION_s,
1534 TCC_OPTION_traditional,
1535 TCC_OPTION_Wl,
1536 TCC_OPTION_W,
1537 TCC_OPTION_O,
1538 TCC_OPTION_m,
1539 TCC_OPTION_f,
1540 TCC_OPTION_isystem,
1541 TCC_OPTION_iwithprefix,
1542 TCC_OPTION_nostdinc,
1543 TCC_OPTION_nostdlib,
1544 TCC_OPTION_print_search_dirs,
1545 TCC_OPTION_rdynamic,
1546 TCC_OPTION_pedantic,
1547 TCC_OPTION_pthread,
1548 TCC_OPTION_run,
1549 TCC_OPTION_v,
1550 TCC_OPTION_w,
1551 TCC_OPTION_pipe,
1552 TCC_OPTION_E,
1553 TCC_OPTION_MD,
1554 TCC_OPTION_MF,
1555 TCC_OPTION_x
1558 #define TCC_OPTION_HAS_ARG 0x0001
1559 #define TCC_OPTION_NOSEP 0x0002 /* cannot have space before option and arg */
1561 static const TCCOption tcc_options[] = {
1562 { "h", TCC_OPTION_HELP, 0 },
1563 { "-help", TCC_OPTION_HELP, 0 },
1564 { "?", TCC_OPTION_HELP, 0 },
1565 { "I", TCC_OPTION_I, TCC_OPTION_HAS_ARG },
1566 { "D", TCC_OPTION_D, TCC_OPTION_HAS_ARG },
1567 { "U", TCC_OPTION_U, TCC_OPTION_HAS_ARG },
1568 { "P", TCC_OPTION_P, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1569 { "L", TCC_OPTION_L, TCC_OPTION_HAS_ARG },
1570 { "B", TCC_OPTION_B, TCC_OPTION_HAS_ARG },
1571 { "l", TCC_OPTION_l, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1572 { "bench", TCC_OPTION_bench, 0 },
1573 #ifdef CONFIG_TCC_BACKTRACE
1574 { "bt", TCC_OPTION_bt, TCC_OPTION_HAS_ARG },
1575 #endif
1576 #ifdef CONFIG_TCC_BCHECK
1577 { "b", TCC_OPTION_b, 0 },
1578 #endif
1579 { "g", TCC_OPTION_g, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1580 { "c", TCC_OPTION_c, 0 },
1581 { "dumpversion", TCC_OPTION_dumpversion, 0},
1582 { "d", TCC_OPTION_d, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1583 #ifdef TCC_TARGET_ARM
1584 { "mfloat-abi", TCC_OPTION_float_abi, TCC_OPTION_HAS_ARG },
1585 #endif
1586 { "static", TCC_OPTION_static, 0 },
1587 { "std", TCC_OPTION_std, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1588 { "shared", TCC_OPTION_shared, 0 },
1589 { "soname", TCC_OPTION_soname, TCC_OPTION_HAS_ARG },
1590 { "o", TCC_OPTION_o, TCC_OPTION_HAS_ARG },
1591 { "pedantic", TCC_OPTION_pedantic, 0},
1592 { "pthread", TCC_OPTION_pthread, 0},
1593 { "run", TCC_OPTION_run, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1594 { "rdynamic", TCC_OPTION_rdynamic, 0 },
1595 { "r", TCC_OPTION_r, 0 },
1596 { "s", TCC_OPTION_s, 0 },
1597 { "traditional", TCC_OPTION_traditional, 0 },
1598 { "Wl,", TCC_OPTION_Wl, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1599 { "W", TCC_OPTION_W, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1600 { "O", TCC_OPTION_O, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1601 { "m", TCC_OPTION_m, TCC_OPTION_HAS_ARG },
1602 { "f", TCC_OPTION_f, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1603 { "isystem", TCC_OPTION_isystem, TCC_OPTION_HAS_ARG },
1604 { "iwithprefix", TCC_OPTION_iwithprefix, TCC_OPTION_HAS_ARG },
1605 { "nostdinc", TCC_OPTION_nostdinc, 0 },
1606 { "nostdlib", TCC_OPTION_nostdlib, 0 },
1607 { "print-search-dirs", TCC_OPTION_print_search_dirs, 0 },
1608 { "v", TCC_OPTION_v, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1609 { "w", TCC_OPTION_w, 0 },
1610 { "pipe", TCC_OPTION_pipe, 0},
1611 { "E", TCC_OPTION_E, 0},
1612 { "MD", TCC_OPTION_MD, 0},
1613 { "MF", TCC_OPTION_MF, TCC_OPTION_HAS_ARG },
1614 { "x", TCC_OPTION_x, TCC_OPTION_HAS_ARG },
1615 { NULL, 0, 0 },
1618 static void parse_option_D(TCCState *s1, const char *optarg)
1620 char *sym = tcc_strdup(optarg);
1621 char *value = strchr(sym, '=');
1622 if (value)
1623 *value++ = '\0';
1624 tcc_define_symbol(s1, sym, value);
1625 tcc_free(sym);
1628 static void args_parser_add_file(TCCState *s, const char* filename, int filetype)
1630 struct filespec *f = tcc_malloc(sizeof *f + strlen(filename));
1631 f->type = filetype;
1632 strcpy(f->name, filename);
1633 dynarray_add((void ***)&s->files, &s->nb_files, f);
1636 /* read list file */
1637 static void args_parser_listfile(TCCState *s, const char *filename)
1639 int fd;
1640 size_t len;
1641 char *p;
1643 fd = open(filename, O_RDONLY | O_BINARY);
1644 if (fd < 0)
1645 tcc_error("file '%s' not found", filename);
1647 len = lseek(fd, 0, SEEK_END);
1648 p = tcc_malloc(len + 1), p[len] = 0;
1649 lseek(fd, 0, SEEK_SET), read(fd, p, len), close(fd);
1650 tcc_set_options(s, p);
1651 tcc_free(p);
1654 PUB_FUNC int tcc_parse_args(TCCState *s, int argc, char **argv)
1656 const TCCOption *popt;
1657 const char *optarg, *r;
1658 int optind = 0;
1659 int run = 0;
1660 int x;
1661 CString linker_arg; /* collect -Wl options */
1662 char buf[1024];
1664 cstr_new(&linker_arg);
1666 while (optind < argc) {
1668 r = argv[optind++];
1670 if (r[0] == '@' && r[1] != '\0') {
1671 args_parser_listfile(s, r + 1);
1672 continue;
1675 if (r[0] != '-' || r[1] == '\0') {
1676 args_parser_add_file(s, r, s->filetype);
1677 if (run) {
1678 optind--;
1679 /* argv[0] will be this file */
1680 break;
1682 continue;
1685 /* find option in table */
1686 for(popt = tcc_options; ; ++popt) {
1687 const char *p1 = popt->name;
1688 const char *r1 = r + 1;
1689 if (p1 == NULL)
1690 tcc_error("invalid option -- '%s'", r);
1691 if (!strstart(p1, &r1))
1692 continue;
1693 optarg = r1;
1694 if (popt->flags & TCC_OPTION_HAS_ARG) {
1695 if (*r1 == '\0' && !(popt->flags & TCC_OPTION_NOSEP)) {
1696 if (optind >= argc)
1697 arg_err:
1698 tcc_error("argument to '%s' is missing", r);
1699 optarg = argv[optind++];
1701 } else if (*r1 != '\0')
1702 continue;
1703 break;
1706 switch(popt->index) {
1707 case TCC_OPTION_HELP:
1708 return 0;
1709 case TCC_OPTION_I:
1710 tcc_add_include_path(s, optarg);
1711 break;
1712 case TCC_OPTION_D:
1713 parse_option_D(s, optarg);
1714 break;
1715 case TCC_OPTION_U:
1716 tcc_undefine_symbol(s, optarg);
1717 break;
1718 case TCC_OPTION_L:
1719 tcc_add_library_path(s, optarg);
1720 break;
1721 case TCC_OPTION_B:
1722 /* set tcc utilities path (mainly for tcc development) */
1723 tcc_set_lib_path(s, optarg);
1724 break;
1725 case TCC_OPTION_l:
1726 args_parser_add_file(s, optarg, AFF_TYPE_LIBWH - s->alacarte_link);
1727 s->nb_libraries++;
1728 break;
1729 case TCC_OPTION_pthread:
1730 parse_option_D(s, "_REENTRANT");
1731 s->option_pthread = 1;
1732 break;
1733 case TCC_OPTION_bench:
1734 s->do_bench = 1;
1735 break;
1736 #ifdef CONFIG_TCC_BACKTRACE
1737 case TCC_OPTION_bt:
1738 tcc_set_num_callers(atoi(optarg));
1739 break;
1740 #endif
1741 #ifdef CONFIG_TCC_BCHECK
1742 case TCC_OPTION_b:
1743 s->do_bounds_check = 1;
1744 s->do_debug = 1;
1745 break;
1746 #endif
1747 case TCC_OPTION_g:
1748 s->do_debug = 1;
1749 break;
1750 case TCC_OPTION_c:
1751 x = TCC_OUTPUT_OBJ;
1752 set_output_type:
1753 if (s->output_type)
1754 tcc_warning("-%s: overriding compiler action already specified", popt->name);
1755 s->output_type = x;
1756 break;
1757 case TCC_OPTION_d:
1758 if (*optarg == 'D')
1759 s->dflag = 3;
1760 else if (*optarg == 'M')
1761 s->dflag = 7;
1762 else
1763 goto unsupported_option;
1764 break;
1765 #ifdef TCC_TARGET_ARM
1766 case TCC_OPTION_float_abi:
1767 /* tcc doesn't support soft float yet */
1768 if (!strcmp(optarg, "softfp")) {
1769 s->float_abi = ARM_SOFTFP_FLOAT;
1770 tcc_undefine_symbol(s, "__ARM_PCS_VFP");
1771 } else if (!strcmp(optarg, "hard"))
1772 s->float_abi = ARM_HARD_FLOAT;
1773 else
1774 tcc_error("unsupported float abi '%s'", optarg);
1775 break;
1776 #endif
1777 case TCC_OPTION_static:
1778 s->static_link = 1;
1779 break;
1780 case TCC_OPTION_std:
1781 /* silently ignore, a current purpose:
1782 allow to use a tcc as a reference compiler for "make test" */
1783 break;
1784 case TCC_OPTION_shared:
1785 x = TCC_OUTPUT_DLL;
1786 goto set_output_type;
1787 case TCC_OPTION_soname:
1788 s->soname = tcc_strdup(optarg);
1789 break;
1790 case TCC_OPTION_m:
1791 s->option_m = tcc_strdup(optarg);
1792 break;
1793 case TCC_OPTION_o:
1794 if (s->outfile) {
1795 tcc_warning("multiple -o option");
1796 tcc_free(s->outfile);
1798 s->outfile = tcc_strdup(optarg);
1799 break;
1800 case TCC_OPTION_r:
1801 /* generate a .o merging several output files */
1802 s->option_r = 1;
1803 x = TCC_OUTPUT_OBJ;
1804 goto set_output_type;
1805 case TCC_OPTION_isystem:
1806 tcc_add_sysinclude_path(s, optarg);
1807 break;
1808 case TCC_OPTION_iwithprefix:
1809 snprintf(buf, sizeof buf, "{B}/%s", optarg);
1810 tcc_add_sysinclude_path(s, buf);
1811 break;
1812 case TCC_OPTION_nostdinc:
1813 s->nostdinc = 1;
1814 break;
1815 case TCC_OPTION_nostdlib:
1816 s->nostdlib = 1;
1817 break;
1818 case TCC_OPTION_print_search_dirs:
1819 s->print_search_dirs = 1;
1820 break;
1821 case TCC_OPTION_run:
1822 #ifndef TCC_IS_NATIVE
1823 tcc_error("-run is not available in a cross compiler");
1824 #endif
1825 tcc_set_options(s, optarg);
1826 run = 1;
1827 x = TCC_OUTPUT_MEMORY;
1828 goto set_output_type;
1829 case TCC_OPTION_v:
1830 do ++s->verbose; while (*optarg++ == 'v');
1831 break;
1832 case TCC_OPTION_f:
1833 if (tcc_set_flag(s, optarg, 1) < 0)
1834 goto unsupported_option;
1835 break;
1836 case TCC_OPTION_W:
1837 if (tcc_set_warning(s, optarg, 1) < 0)
1838 goto unsupported_option;
1839 break;
1840 case TCC_OPTION_w:
1841 s->warn_none = 1;
1842 break;
1843 case TCC_OPTION_rdynamic:
1844 s->rdynamic = 1;
1845 break;
1846 case TCC_OPTION_Wl:
1847 if (linker_arg.size)
1848 --linker_arg.size, cstr_ccat(&linker_arg, ',');
1849 cstr_cat(&linker_arg, optarg, 0);
1850 if (tcc_set_linker(s, linker_arg.data))
1851 cstr_free(&linker_arg);
1852 break;
1853 case TCC_OPTION_E:
1854 x = TCC_OUTPUT_PREPROCESS;
1855 goto set_output_type;
1856 case TCC_OPTION_P:
1857 s->Pflag = atoi(optarg) + 1;
1858 break;
1859 case TCC_OPTION_MD:
1860 s->gen_deps = 1;
1861 break;
1862 case TCC_OPTION_MF:
1863 s->deps_outfile = tcc_strdup(optarg);
1864 break;
1865 case TCC_OPTION_dumpversion:
1866 printf ("%s\n", TCC_VERSION);
1867 exit(0);
1868 break;
1869 case TCC_OPTION_x:
1870 if (*optarg == 'c')
1871 s->filetype = AFF_TYPE_C;
1872 else if (*optarg == 'a')
1873 s->filetype = AFF_TYPE_ASMPP;
1874 else if (*optarg == 'n')
1875 s->filetype = AFF_TYPE_NONE;
1876 else
1877 tcc_warning("unsupported language '%s'", optarg);
1878 break;
1879 case TCC_OPTION_O:
1880 x = atoi(optarg);
1881 if (x > 0)
1882 tcc_define_symbol(s, "__OPTIMIZE__", NULL);
1883 break;
1884 case TCC_OPTION_traditional:
1885 case TCC_OPTION_pedantic:
1886 case TCC_OPTION_pipe:
1887 case TCC_OPTION_s:
1888 /* ignored */
1889 break;
1890 default:
1891 unsupported_option:
1892 if (s->warn_unsupported)
1893 tcc_warning("unsupported option '%s'", r);
1894 break;
1898 if (linker_arg.size) {
1899 r = linker_arg.data;
1900 goto arg_err;
1903 return optind;
1906 LIBTCCAPI int tcc_set_options(TCCState *s, const char *r)
1908 char **argv;
1909 int argc;
1910 int ret, q, c;
1911 CString str;
1913 argc = 0, argv = NULL;
1914 for(;;) {
1915 while (c = (unsigned char)*r, c && c <= ' ')
1916 ++r;
1917 if (c == 0)
1918 break;
1919 q = 0;
1920 cstr_new(&str);
1921 while (c = (unsigned char)*r, c) {
1922 ++r;
1923 if (c == '\\' && (*r == '"' || *r == '\\')) {
1924 c = *r++;
1925 } else if (c == '"') {
1926 q = !q;
1927 continue;
1928 } else if (q == 0 && c <= ' ') {
1929 break;
1931 cstr_ccat(&str, c);
1933 cstr_ccat(&str, 0);
1934 //printf("<%s>\n", str.data), fflush(stdout);
1935 dynarray_add((void ***)&argv, &argc, tcc_strdup(str.data));
1936 cstr_free(&str);
1938 ret = tcc_parse_args(s, argc, argv);
1939 dynarray_reset(&argv, &argc);
1940 return ret;
1943 PUB_FUNC void tcc_print_stats(TCCState *s, int64_t total_time)
1945 double tt;
1946 tt = (double)total_time / 1000000.0;
1947 if (tt < 0.001)
1948 tt = 0.001;
1949 if (total_bytes < 1)
1950 total_bytes = 1;
1951 fprintf(stderr, "%d idents, %d lines, %d bytes, %0.3f s, %d lines/s, %0.1f MB/s\n",
1952 tok_ident - TOK_IDENT, total_lines, total_bytes,
1953 tt, (int)(total_lines / tt),
1954 total_bytes / tt / 1000000.0);
1957 PUB_FUNC void tcc_set_environment(TCCState *s)
1959 char * path;
1961 path = getenv("C_INCLUDE_PATH");
1962 if(path != NULL) {
1963 tcc_add_include_path(s, path);
1965 path = getenv("CPATH");
1966 if(path != NULL) {
1967 tcc_add_include_path(s, path);
1969 path = getenv("LIBRARY_PATH");
1970 if(path != NULL) {
1971 tcc_add_library_path(s, path);