configure: prefer lib64 on 64-bit platforms
[tinycc.git] / libtcc.c
blobf184502b4c7df567da1a9560edf26dbb4fe0cc0f
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_start(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 tccgen_end(s1);
670 s1->error_set_jmp_enabled = 0;
672 free_inline_functions(s1);
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 tccpp_delete(tcc_state);
734 tcc_state = NULL;
735 /* free sym_pools */
736 dynarray_reset(&sym_pools, &nb_sym_pools);
737 /* reset symbol stack */
738 sym_free_first = NULL;
741 LIBTCCAPI TCCState *tcc_new(void)
743 TCCState *s;
745 tcc_cleanup();
747 s = tcc_mallocz(sizeof(TCCState));
748 if (!s)
749 return NULL;
750 tcc_state = s;
752 s->alacarte_link = 1;
753 s->nocommon = 1;
754 s->warn_implicit_function_declaration = 1;
756 #ifdef CHAR_IS_UNSIGNED
757 s->char_is_unsigned = 1;
758 #endif
759 #ifdef TCC_TARGET_I386
760 s->seg_size = 32;
761 #endif
762 #ifdef TCC_IS_NATIVE
763 s->runtime_main = "main";
764 #endif
765 /* enable this if you want symbols with leading underscore on windows: */
766 #if 0 /* def TCC_TARGET_PE */
767 s->leading_underscore = 1;
768 #endif
769 #ifdef _WIN32
770 tcc_set_lib_path_w32(s);
771 #else
772 tcc_set_lib_path(s, CONFIG_TCCDIR);
773 #endif
774 tccelf_new(s);
775 tccpp_new(s);
777 /* we add dummy defines for some special macros to speed up tests
778 and to have working defined() */
779 define_push(TOK___LINE__, MACRO_OBJ, NULL, NULL);
780 define_push(TOK___FILE__, MACRO_OBJ, NULL, NULL);
781 define_push(TOK___DATE__, MACRO_OBJ, NULL, NULL);
782 define_push(TOK___TIME__, MACRO_OBJ, NULL, NULL);
784 /* define __TINYC__ 92X */
785 char buffer[32]; int a,b,c;
786 sscanf(TCC_VERSION, "%d.%d.%d", &a, &b, &c);
787 sprintf(buffer, "%d", a*10000 + b*100 + c);
788 tcc_define_symbol(s, "__TINYC__", buffer);
791 /* standard defines */
792 tcc_define_symbol(s, "__STDC__", NULL);
793 tcc_define_symbol(s, "__STDC_VERSION__", "199901L");
794 tcc_define_symbol(s, "__STDC_HOSTED__", NULL);
796 /* target defines */
797 #if defined(TCC_TARGET_I386)
798 tcc_define_symbol(s, "__i386__", NULL);
799 tcc_define_symbol(s, "__i386", NULL);
800 tcc_define_symbol(s, "i386", NULL);
801 #elif defined(TCC_TARGET_X86_64)
802 tcc_define_symbol(s, "__x86_64__", NULL);
803 #elif defined(TCC_TARGET_ARM)
804 tcc_define_symbol(s, "__ARM_ARCH_4__", NULL);
805 tcc_define_symbol(s, "__arm_elf__", NULL);
806 tcc_define_symbol(s, "__arm_elf", NULL);
807 tcc_define_symbol(s, "arm_elf", NULL);
808 tcc_define_symbol(s, "__arm__", NULL);
809 tcc_define_symbol(s, "__arm", NULL);
810 tcc_define_symbol(s, "arm", NULL);
811 tcc_define_symbol(s, "__APCS_32__", NULL);
812 tcc_define_symbol(s, "__ARMEL__", NULL);
813 #if defined(TCC_ARM_EABI)
814 tcc_define_symbol(s, "__ARM_EABI__", NULL);
815 #endif
816 #if defined(TCC_ARM_HARDFLOAT)
817 s->float_abi = ARM_HARD_FLOAT;
818 tcc_define_symbol(s, "__ARM_PCS_VFP", NULL);
819 #else
820 s->float_abi = ARM_SOFTFP_FLOAT;
821 #endif
822 #elif defined(TCC_TARGET_ARM64)
823 tcc_define_symbol(s, "__aarch64__", NULL);
824 #endif
826 #ifdef TCC_TARGET_PE
827 tcc_define_symbol(s, "_WIN32", NULL);
828 # ifdef TCC_TARGET_X86_64
829 tcc_define_symbol(s, "_WIN64", NULL);
830 # endif
831 #else
832 tcc_define_symbol(s, "__unix__", NULL);
833 tcc_define_symbol(s, "__unix", NULL);
834 tcc_define_symbol(s, "unix", NULL);
835 # if defined(__linux__)
836 tcc_define_symbol(s, "__linux__", NULL);
837 tcc_define_symbol(s, "__linux", NULL);
838 # endif
839 # if defined(__FreeBSD__)
840 tcc_define_symbol(s, "__FreeBSD__", "__FreeBSD__");
841 /* No 'Thread Storage Local' on FreeBSD with tcc */
842 tcc_define_symbol(s, "__NO_TLS", NULL);
843 # endif
844 # if defined(__FreeBSD_kernel__)
845 tcc_define_symbol(s, "__FreeBSD_kernel__", NULL);
846 # endif
847 #endif
848 # if defined(__NetBSD__)
849 tcc_define_symbol(s, "__NetBSD__", "__NetBSD__");
850 # endif
851 # if defined(__OpenBSD__)
852 tcc_define_symbol(s, "__OpenBSD__", "__OpenBSD__");
853 # endif
855 /* TinyCC & gcc defines */
856 #if defined(TCC_TARGET_PE) && defined(TCC_TARGET_X86_64)
857 /* 64bit Windows. */
858 tcc_define_symbol(s, "__SIZE_TYPE__", "unsigned long long");
859 tcc_define_symbol(s, "__PTRDIFF_TYPE__", "long long");
860 tcc_define_symbol(s, "__LLP64__", NULL);
861 #elif defined(TCC_TARGET_X86_64) || defined(TCC_TARGET_ARM64)
862 /* Other 64bit systems. */
863 tcc_define_symbol(s, "__SIZE_TYPE__", "unsigned long");
864 tcc_define_symbol(s, "__PTRDIFF_TYPE__", "long");
865 tcc_define_symbol(s, "__LP64__", NULL);
866 #else
867 /* Other 32bit systems. */
868 tcc_define_symbol(s, "__SIZE_TYPE__", "unsigned long");
869 tcc_define_symbol(s, "__PTRDIFF_TYPE__", "long");
870 tcc_define_symbol(s, "__ILP32__", NULL);
871 #endif
873 #ifdef TCC_TARGET_PE
874 tcc_define_symbol(s, "__WCHAR_TYPE__", "unsigned short");
875 tcc_define_symbol(s, "__WINT_TYPE__", "unsigned short");
876 #else
877 tcc_define_symbol(s, "__WCHAR_TYPE__", "int");
878 /* wint_t is unsigned int by default, but (signed) int on BSDs
879 and unsigned short on windows. Other OSes might have still
880 other conventions, sigh. */
881 # if defined(__FreeBSD__) || defined (__FreeBSD_kernel__) \
882 || defined(__NetBSD__) || defined(__OpenBSD__)
883 tcc_define_symbol(s, "__WINT_TYPE__", "int");
884 # ifdef __FreeBSD__
885 /* define __GNUC__ to have some useful stuff from sys/cdefs.h
886 that are unconditionally used in FreeBSDs other system headers :/ */
887 tcc_define_symbol(s, "__GNUC__", "2");
888 tcc_define_symbol(s, "__GNUC_MINOR__", "7");
889 tcc_define_symbol(s, "__builtin_alloca", "alloca");
890 # endif
891 # else
892 tcc_define_symbol(s, "__WINT_TYPE__", "unsigned int");
893 /* glibc defines */
894 tcc_define_symbol(s, "__REDIRECT(name, proto, alias)",
895 "name proto __asm__ (#alias)");
896 tcc_define_symbol(s, "__REDIRECT_NTH(name, proto, alias)",
897 "name proto __asm__ (#alias) __THROW");
898 # endif
899 #endif /* ndef TCC_TARGET_PE */
901 return s;
904 LIBTCCAPI void tcc_delete(TCCState *s1)
906 int bench = s1->do_bench;
908 tcc_cleanup();
910 /* free sections */
911 tccelf_delete(s1);
913 /* free library paths */
914 dynarray_reset(&s1->library_paths, &s1->nb_library_paths);
915 dynarray_reset(&s1->crt_paths, &s1->nb_crt_paths);
917 /* free include paths */
918 dynarray_reset(&s1->cached_includes, &s1->nb_cached_includes);
919 dynarray_reset(&s1->include_paths, &s1->nb_include_paths);
920 dynarray_reset(&s1->sysinclude_paths, &s1->nb_sysinclude_paths);
922 tcc_free(s1->tcc_lib_path);
923 tcc_free(s1->soname);
924 tcc_free(s1->rpath);
925 tcc_free(s1->init_symbol);
926 tcc_free(s1->fini_symbol);
927 tcc_free(s1->outfile);
928 tcc_free(s1->deps_outfile);
929 dynarray_reset(&s1->files, &s1->nb_files);
930 dynarray_reset(&s1->target_deps, &s1->nb_target_deps);
931 dynarray_reset(&s1->pragma_libs, &s1->nb_pragma_libs);
933 #ifdef TCC_IS_NATIVE
934 /* free runtime memory */
935 tcc_run_free(s1);
936 #endif
938 tcc_free(s1->sym_attrs);
939 tcc_free(s1);
940 tcc_memstats(bench);
943 LIBTCCAPI int tcc_set_output_type(TCCState *s, int output_type)
945 s->output_type = output_type;
947 /* always elf for objects */
948 if (output_type == TCC_OUTPUT_OBJ)
949 s->output_format = TCC_OUTPUT_FORMAT_ELF;
951 if (s->char_is_unsigned)
952 tcc_define_symbol(s, "__CHAR_UNSIGNED__", NULL);
954 if (!s->nostdinc) {
955 /* default include paths */
956 /* -isystem paths have already been handled */
957 tcc_add_sysinclude_path(s, CONFIG_TCC_SYSINCLUDEPATHS);
960 #ifdef CONFIG_TCC_BCHECK
961 if (s->do_bounds_check) {
962 /* if bound checking, then add corresponding sections */
963 tccelf_bounds_new(s);
964 /* define symbol */
965 tcc_define_symbol(s, "__BOUNDS_CHECKING_ON", NULL);
967 #endif
968 if (s->do_debug) {
969 /* add debug sections */
970 tccelf_stab_new(s);
973 tcc_add_library_path(s, CONFIG_TCC_LIBPATHS);
975 #ifdef TCC_TARGET_PE
976 # ifdef _WIN32
977 if (!s->nostdlib && output_type != TCC_OUTPUT_OBJ)
978 tcc_add_systemdir(s);
979 # endif
980 #else
981 /* paths for crt objects */
982 tcc_split_path(s, (void ***)&s->crt_paths, &s->nb_crt_paths, CONFIG_TCC_CRTPREFIX);
983 /* add libc crt1/crti objects */
984 if ((output_type == TCC_OUTPUT_EXE || output_type == TCC_OUTPUT_DLL) &&
985 !s->nostdlib) {
986 if (output_type != TCC_OUTPUT_DLL)
987 tcc_add_crt(s, "crt1.o");
988 tcc_add_crt(s, "crti.o");
990 #endif
991 return 0;
994 LIBTCCAPI int tcc_add_include_path(TCCState *s, const char *pathname)
996 tcc_split_path(s, (void ***)&s->include_paths, &s->nb_include_paths, pathname);
997 return 0;
1000 LIBTCCAPI int tcc_add_sysinclude_path(TCCState *s, const char *pathname)
1002 tcc_split_path(s, (void ***)&s->sysinclude_paths, &s->nb_sysinclude_paths, pathname);
1003 return 0;
1006 ST_FUNC int tcc_add_file_internal(TCCState *s1, const char *filename, int flags)
1008 int ret, filetype;
1010 filetype = flags & 0x0F;
1011 if (filetype == 0) {
1012 /* use a file extension to detect a filetype */
1013 const char *ext = tcc_fileextension(filename);
1014 if (ext[0]) {
1015 ext++;
1016 if (!strcmp(ext, "S"))
1017 filetype = AFF_TYPE_ASMPP;
1018 else if (!strcmp(ext, "s"))
1019 filetype = AFF_TYPE_ASM;
1020 else if (!PATHCMP(ext, "c") || !PATHCMP(ext, "i"))
1021 filetype = AFF_TYPE_C;
1022 else
1023 filetype = AFF_TYPE_BIN;
1024 } else {
1025 filetype = AFF_TYPE_C;
1029 /* open the file */
1030 ret = tcc_open(s1, filename);
1031 if (ret < 0) {
1032 if (flags & AFF_PRINT_ERROR)
1033 tcc_error_noabort("file '%s' not found", filename);
1034 return ret;
1037 /* update target deps */
1038 dynarray_add((void ***)&s1->target_deps, &s1->nb_target_deps,
1039 tcc_strdup(filename));
1041 parse_flags = 0;
1042 /* if .S file, define __ASSEMBLER__ like gcc does */
1043 if (filetype == AFF_TYPE_ASM || filetype == AFF_TYPE_ASMPP) {
1044 tcc_define_symbol(s1, "__ASSEMBLER__", NULL);
1045 parse_flags = PARSE_FLAG_ASM_FILE;
1048 if (flags & AFF_PREPROCESS) {
1049 ret = tcc_preprocess(s1);
1050 } else if (filetype == AFF_TYPE_C) {
1051 ret = tcc_compile(s1);
1052 #ifdef CONFIG_TCC_ASM
1053 } else if (filetype == AFF_TYPE_ASMPP) {
1054 /* non preprocessed assembler */
1055 ret = tcc_assemble(s1, 1);
1056 } else if (filetype == AFF_TYPE_ASM) {
1057 /* preprocessed assembler */
1058 ret = tcc_assemble(s1, 0);
1059 #endif
1060 } else {
1061 ElfW(Ehdr) ehdr;
1062 int fd, obj_type;
1064 fd = file->fd;
1065 obj_type = tcc_object_type(fd, &ehdr);
1066 lseek(fd, 0, SEEK_SET);
1068 /* do not display line number if error */
1069 file->line_num = 0;
1071 switch (obj_type) {
1072 case AFF_BINTYPE_REL:
1073 ret = tcc_load_object_file(s1, fd, 0);
1074 break;
1075 #ifndef TCC_TARGET_PE
1076 case AFF_BINTYPE_DYN:
1077 if (s1->output_type == TCC_OUTPUT_MEMORY) {
1078 ret = 0;
1079 #ifdef TCC_IS_NATIVE
1080 if (NULL == dlopen(filename, RTLD_GLOBAL | RTLD_LAZY))
1081 ret = -1;
1082 #endif
1083 } else {
1084 ret = tcc_load_dll(s1, fd, filename,
1085 (flags & AFF_REFERENCED_DLL) != 0);
1087 break;
1088 #endif
1089 case AFF_BINTYPE_AR:
1090 ret = tcc_load_archive(s1, fd);
1091 break;
1092 #ifdef TCC_TARGET_COFF
1093 case AFF_BINTYPE_C67:
1094 ret = tcc_load_coff(s1, fd);
1095 break;
1096 #endif
1097 default:
1098 #ifdef TCC_TARGET_PE
1099 ret = pe_load_file(s1, filename, fd);
1100 #else
1101 /* as GNU ld, consider it is an ld script if not recognized */
1102 ret = tcc_load_ldscript(s1);
1103 #endif
1104 if (ret < 0)
1105 tcc_error_noabort("unrecognized file type");
1106 break;
1109 tcc_close();
1110 return ret;
1113 LIBTCCAPI int tcc_add_file(TCCState *s, const char *filename)
1115 if (s->output_type == TCC_OUTPUT_PREPROCESS)
1116 return tcc_add_file_internal(s, filename, AFF_PRINT_ERROR | AFF_PREPROCESS | s->filetype);
1117 else
1118 return tcc_add_file_internal(s, filename, AFF_PRINT_ERROR | s->filetype);
1121 LIBTCCAPI int tcc_add_library_path(TCCState *s, const char *pathname)
1123 tcc_split_path(s, (void ***)&s->library_paths, &s->nb_library_paths, pathname);
1124 return 0;
1127 static int tcc_add_library_internal(TCCState *s, const char *fmt,
1128 const char *filename, int flags, char **paths, int nb_paths)
1130 char buf[1024];
1131 int i;
1133 for(i = 0; i < nb_paths; i++) {
1134 snprintf(buf, sizeof(buf), fmt, paths[i], filename);
1135 if (tcc_add_file_internal(s, buf, flags | AFF_TYPE_BIN) == 0)
1136 return 0;
1138 return -1;
1141 #ifndef TCC_TARGET_PE
1142 /* find and load a dll. Return non zero if not found */
1143 /* XXX: add '-rpath' option support ? */
1144 ST_FUNC int tcc_add_dll(TCCState *s, const char *filename, int flags)
1146 return tcc_add_library_internal(s, "%s/%s", filename, flags,
1147 s->library_paths, s->nb_library_paths);
1149 #endif
1151 ST_FUNC int tcc_add_crt(TCCState *s, const char *filename)
1153 if (-1 == tcc_add_library_internal(s, "%s/%s",
1154 filename, 0, s->crt_paths, s->nb_crt_paths))
1155 tcc_error_noabort("file '%s' not found", filename);
1156 return 0;
1159 /* the library name is the same as the argument of the '-l' option */
1160 LIBTCCAPI int tcc_add_library(TCCState *s, const char *libraryname)
1162 #ifdef TCC_TARGET_PE
1163 const char *libs[] = { "%s/%s.def", "%s/lib%s.def", "%s/%s.dll", "%s/lib%s.dll", "%s/lib%s.a", NULL };
1164 const char **pp = s->static_link ? libs + 4 : libs;
1165 #else
1166 const char *libs[] = { "%s/lib%s.so", "%s/lib%s.a", NULL };
1167 const char **pp = s->static_link ? libs + 1 : libs;
1168 #endif
1169 while (*pp) {
1170 if (0 == tcc_add_library_internal(s, *pp,
1171 libraryname, 0, s->library_paths, s->nb_library_paths))
1172 return 0;
1173 ++pp;
1175 return -1;
1178 PUB_FUNC int tcc_add_library_err(TCCState *s, const char *libname)
1180 int ret = tcc_add_library(s, libname);
1181 if (ret < 0)
1182 tcc_error_noabort("library 'lib%s' not found", libname);
1183 return ret;
1186 /* habdle #pragma comment(lib,) */
1187 ST_FUNC void tcc_add_pragma_libs(TCCState *s1)
1189 int i;
1190 for (i = 0; i < s1->nb_pragma_libs; i++)
1191 tcc_add_library_err(s1, s1->pragma_libs[i]);
1194 LIBTCCAPI int tcc_add_symbol(TCCState *s, const char *name, const void *val)
1196 #ifdef TCC_TARGET_PE
1197 /* On x86_64 'val' might not be reachable with a 32bit offset.
1198 So it is handled here as if it were in a DLL. */
1199 pe_putimport(s, 0, name, (uintptr_t)val);
1200 #else
1201 add_elf_sym(symtab_section, (uintptr_t)val, 0,
1202 ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE), 0,
1203 SHN_ABS, name);
1204 #endif
1205 return 0;
1208 LIBTCCAPI void tcc_set_lib_path(TCCState *s, const char *path)
1210 tcc_free(s->tcc_lib_path);
1211 s->tcc_lib_path = tcc_strdup(path);
1214 #define WD_ALL 0x0001 /* warning is activated when using -Wall */
1215 #define FD_INVERT 0x0002 /* invert value before storing */
1217 typedef struct FlagDef {
1218 uint16_t offset;
1219 uint16_t flags;
1220 const char *name;
1221 } FlagDef;
1223 static const FlagDef warning_defs[] = {
1224 { offsetof(TCCState, warn_unsupported), 0, "unsupported" },
1225 { offsetof(TCCState, warn_write_strings), 0, "write-strings" },
1226 { offsetof(TCCState, warn_error), 0, "error" },
1227 { offsetof(TCCState, warn_implicit_function_declaration), WD_ALL,
1228 "implicit-function-declaration" },
1231 static int no_flag(const char **pp)
1233 const char *p = *pp;
1234 if (*p != 'n' || *++p != 'o' || *++p != '-')
1235 return 0;
1236 *pp = p + 1;
1237 return 1;
1240 ST_FUNC int set_flag(TCCState *s, const FlagDef *flags, int nb_flags,
1241 const char *name, int value)
1243 int i;
1244 const FlagDef *p;
1245 const char *r;
1247 r = name;
1248 if (no_flag(&r))
1249 value = !value;
1251 for(i = 0, p = flags; i < nb_flags; i++, p++) {
1252 if (!strcmp(r, p->name))
1253 goto found;
1255 return -1;
1256 found:
1257 if (p->flags & FD_INVERT)
1258 value = !value;
1259 *(int *)((uint8_t *)s + p->offset) = value;
1260 return 0;
1263 /* set/reset a warning */
1264 static int tcc_set_warning(TCCState *s, const char *warning_name, int value)
1266 int i;
1267 const FlagDef *p;
1269 if (!strcmp(warning_name, "all")) {
1270 for(i = 0, p = warning_defs; i < countof(warning_defs); i++, p++) {
1271 if (p->flags & WD_ALL)
1272 *(int *)((uint8_t *)s + p->offset) = 1;
1274 return 0;
1275 } else {
1276 return set_flag(s, warning_defs, countof(warning_defs),
1277 warning_name, value);
1281 static const FlagDef flag_defs[] = {
1282 { offsetof(TCCState, char_is_unsigned), 0, "unsigned-char" },
1283 { offsetof(TCCState, char_is_unsigned), FD_INVERT, "signed-char" },
1284 { offsetof(TCCState, nocommon), FD_INVERT, "common" },
1285 { offsetof(TCCState, leading_underscore), 0, "leading-underscore" },
1286 { offsetof(TCCState, ms_extensions), 0, "ms-extensions" },
1287 { offsetof(TCCState, old_struct_init_code), 0, "old-struct-init-code" },
1288 { offsetof(TCCState, dollars_in_identifiers), 0, "dollars-in-identifiers" },
1291 /* set/reset a flag */
1292 static int tcc_set_flag(TCCState *s, const char *flag_name, int value)
1294 return set_flag(s, flag_defs, countof(flag_defs),
1295 flag_name, value);
1299 static int strstart(const char *val, const char **str)
1301 const char *p, *q;
1302 p = *str;
1303 q = val;
1304 while (*q) {
1305 if (*p != *q)
1306 return 0;
1307 p++;
1308 q++;
1310 *str = p;
1311 return 1;
1314 /* Like strstart, but automatically takes into account that ld options can
1316 * - start with double or single dash (e.g. '--soname' or '-soname')
1317 * - arguments can be given as separate or after '=' (e.g. '-Wl,-soname,x.so'
1318 * or '-Wl,-soname=x.so')
1320 * you provide `val` always in 'option[=]' form (no leading -)
1322 static int link_option(const char *str, const char *val, const char **ptr)
1324 const char *p, *q;
1325 int ret;
1327 /* there should be 1 or 2 dashes */
1328 if (*str++ != '-')
1329 return 0;
1330 if (*str == '-')
1331 str++;
1333 /* then str & val should match (potentialy up to '=') */
1334 p = str;
1335 q = val;
1337 ret = 1;
1338 if (q[0] == '?') {
1339 ++q;
1340 if (no_flag(&p))
1341 ret = -1;
1344 while (*q != '\0' && *q != '=') {
1345 if (*p != *q)
1346 return 0;
1347 p++;
1348 q++;
1351 /* '=' near eos means ',' or '=' is ok */
1352 if (*q == '=') {
1353 if (*p == 0)
1354 *ptr = p;
1355 if (*p != ',' && *p != '=')
1356 return 0;
1357 p++;
1359 *ptr = p;
1360 return ret;
1363 static const char *skip_linker_arg(const char **str)
1365 const char *s1 = *str;
1366 const char *s2 = strchr(s1, ',');
1367 *str = s2 ? s2++ : (s2 = s1 + strlen(s1));
1368 return s2;
1371 static char *copy_linker_arg(const char *p)
1373 const char *q = p;
1374 skip_linker_arg(&q);
1375 return pstrncpy(tcc_malloc(q - p + 1), p, q - p);
1378 /* set linker options */
1379 static int tcc_set_linker(TCCState *s, const char *option)
1381 while (*option) {
1383 const char *p = NULL;
1384 char *end = NULL;
1385 int ignoring = 0;
1386 int ret;
1388 if (link_option(option, "Bsymbolic", &p)) {
1389 s->symbolic = 1;
1390 } else if (link_option(option, "nostdlib", &p)) {
1391 s->nostdlib = 1;
1392 } else if (link_option(option, "fini=", &p)) {
1393 s->fini_symbol = copy_linker_arg(p);
1394 ignoring = 1;
1395 } else if (link_option(option, "image-base=", &p)
1396 || link_option(option, "Ttext=", &p)) {
1397 s->text_addr = strtoull(p, &end, 16);
1398 s->has_text_addr = 1;
1399 } else if (link_option(option, "init=", &p)) {
1400 s->init_symbol = copy_linker_arg(p);
1401 ignoring = 1;
1402 } else if (link_option(option, "oformat=", &p)) {
1403 #if defined(TCC_TARGET_PE)
1404 if (strstart("pe-", &p)) {
1405 #elif defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
1406 if (strstart("elf64-", &p)) {
1407 #else
1408 if (strstart("elf32-", &p)) {
1409 #endif
1410 s->output_format = TCC_OUTPUT_FORMAT_ELF;
1411 } else if (!strcmp(p, "binary")) {
1412 s->output_format = TCC_OUTPUT_FORMAT_BINARY;
1413 #ifdef TCC_TARGET_COFF
1414 } else if (!strcmp(p, "coff")) {
1415 s->output_format = TCC_OUTPUT_FORMAT_COFF;
1416 #endif
1417 } else
1418 goto err;
1420 } else if (link_option(option, "as-needed", &p)) {
1421 ignoring = 1;
1422 } else if (link_option(option, "O", &p)) {
1423 ignoring = 1;
1424 } else if (link_option(option, "rpath=", &p)) {
1425 s->rpath = copy_linker_arg(p);
1426 } else if (link_option(option, "section-alignment=", &p)) {
1427 s->section_align = strtoul(p, &end, 16);
1428 } else if (link_option(option, "soname=", &p)) {
1429 s->soname = copy_linker_arg(p);
1430 #ifdef TCC_TARGET_PE
1431 } else if (link_option(option, "file-alignment=", &p)) {
1432 s->pe_file_align = strtoul(p, &end, 16);
1433 } else if (link_option(option, "stack=", &p)) {
1434 s->pe_stack_size = strtoul(p, &end, 10);
1435 } else if (link_option(option, "subsystem=", &p)) {
1436 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
1437 if (!strcmp(p, "native")) {
1438 s->pe_subsystem = 1;
1439 } else if (!strcmp(p, "console")) {
1440 s->pe_subsystem = 3;
1441 } else if (!strcmp(p, "gui")) {
1442 s->pe_subsystem = 2;
1443 } else if (!strcmp(p, "posix")) {
1444 s->pe_subsystem = 7;
1445 } else if (!strcmp(p, "efiapp")) {
1446 s->pe_subsystem = 10;
1447 } else if (!strcmp(p, "efiboot")) {
1448 s->pe_subsystem = 11;
1449 } else if (!strcmp(p, "efiruntime")) {
1450 s->pe_subsystem = 12;
1451 } else if (!strcmp(p, "efirom")) {
1452 s->pe_subsystem = 13;
1453 #elif defined(TCC_TARGET_ARM)
1454 if (!strcmp(p, "wince")) {
1455 s->pe_subsystem = 9;
1456 #endif
1457 } else
1458 goto err;
1459 #endif
1460 } else if (ret = link_option(option, "?whole-archive", &p), ret) {
1461 s->alacarte_link = ret < 0;
1462 } else if (p) {
1463 return 0;
1464 } else {
1465 err:
1466 tcc_error("unsupported linker option '%s'", option);
1469 if (ignoring && s->warn_unsupported)
1470 tcc_warning("unsupported linker option '%s'", option);
1472 option = skip_linker_arg(&p);
1474 return 1;
1477 typedef struct TCCOption {
1478 const char *name;
1479 uint16_t index;
1480 uint16_t flags;
1481 } TCCOption;
1483 enum {
1484 TCC_OPTION_HELP,
1485 TCC_OPTION_I,
1486 TCC_OPTION_D,
1487 TCC_OPTION_U,
1488 TCC_OPTION_P,
1489 TCC_OPTION_L,
1490 TCC_OPTION_B,
1491 TCC_OPTION_l,
1492 TCC_OPTION_bench,
1493 TCC_OPTION_bt,
1494 TCC_OPTION_b,
1495 TCC_OPTION_g,
1496 TCC_OPTION_c,
1497 TCC_OPTION_dumpversion,
1498 TCC_OPTION_d,
1499 TCC_OPTION_float_abi,
1500 TCC_OPTION_static,
1501 TCC_OPTION_std,
1502 TCC_OPTION_shared,
1503 TCC_OPTION_soname,
1504 TCC_OPTION_o,
1505 TCC_OPTION_r,
1506 TCC_OPTION_s,
1507 TCC_OPTION_traditional,
1508 TCC_OPTION_Wl,
1509 TCC_OPTION_W,
1510 TCC_OPTION_O,
1511 TCC_OPTION_m,
1512 TCC_OPTION_f,
1513 TCC_OPTION_isystem,
1514 TCC_OPTION_iwithprefix,
1515 TCC_OPTION_nostdinc,
1516 TCC_OPTION_nostdlib,
1517 TCC_OPTION_print_search_dirs,
1518 TCC_OPTION_rdynamic,
1519 TCC_OPTION_pedantic,
1520 TCC_OPTION_pthread,
1521 TCC_OPTION_run,
1522 TCC_OPTION_v,
1523 TCC_OPTION_w,
1524 TCC_OPTION_pipe,
1525 TCC_OPTION_E,
1526 TCC_OPTION_MD,
1527 TCC_OPTION_MF,
1528 TCC_OPTION_x
1531 #define TCC_OPTION_HAS_ARG 0x0001
1532 #define TCC_OPTION_NOSEP 0x0002 /* cannot have space before option and arg */
1534 static const TCCOption tcc_options[] = {
1535 { "h", TCC_OPTION_HELP, 0 },
1536 { "-help", TCC_OPTION_HELP, 0 },
1537 { "?", TCC_OPTION_HELP, 0 },
1538 { "I", TCC_OPTION_I, TCC_OPTION_HAS_ARG },
1539 { "D", TCC_OPTION_D, TCC_OPTION_HAS_ARG },
1540 { "U", TCC_OPTION_U, TCC_OPTION_HAS_ARG },
1541 { "P", TCC_OPTION_P, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1542 { "L", TCC_OPTION_L, TCC_OPTION_HAS_ARG },
1543 { "B", TCC_OPTION_B, TCC_OPTION_HAS_ARG },
1544 { "l", TCC_OPTION_l, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1545 { "bench", TCC_OPTION_bench, 0 },
1546 #ifdef CONFIG_TCC_BACKTRACE
1547 { "bt", TCC_OPTION_bt, TCC_OPTION_HAS_ARG },
1548 #endif
1549 #ifdef CONFIG_TCC_BCHECK
1550 { "b", TCC_OPTION_b, 0 },
1551 #endif
1552 { "g", TCC_OPTION_g, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1553 { "c", TCC_OPTION_c, 0 },
1554 { "dumpversion", TCC_OPTION_dumpversion, 0},
1555 { "d", TCC_OPTION_d, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1556 #ifdef TCC_TARGET_ARM
1557 { "mfloat-abi", TCC_OPTION_float_abi, TCC_OPTION_HAS_ARG },
1558 #endif
1559 { "static", TCC_OPTION_static, 0 },
1560 { "std", TCC_OPTION_std, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1561 { "shared", TCC_OPTION_shared, 0 },
1562 { "soname", TCC_OPTION_soname, TCC_OPTION_HAS_ARG },
1563 { "o", TCC_OPTION_o, TCC_OPTION_HAS_ARG },
1564 { "pedantic", TCC_OPTION_pedantic, 0},
1565 { "pthread", TCC_OPTION_pthread, 0},
1566 { "run", TCC_OPTION_run, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1567 { "rdynamic", TCC_OPTION_rdynamic, 0 },
1568 { "r", TCC_OPTION_r, 0 },
1569 { "s", TCC_OPTION_s, 0 },
1570 { "traditional", TCC_OPTION_traditional, 0 },
1571 { "Wl,", TCC_OPTION_Wl, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1572 { "W", TCC_OPTION_W, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1573 { "O", TCC_OPTION_O, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1574 { "m", TCC_OPTION_m, TCC_OPTION_HAS_ARG },
1575 { "f", TCC_OPTION_f, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1576 { "isystem", TCC_OPTION_isystem, TCC_OPTION_HAS_ARG },
1577 { "iwithprefix", TCC_OPTION_iwithprefix, TCC_OPTION_HAS_ARG },
1578 { "nostdinc", TCC_OPTION_nostdinc, 0 },
1579 { "nostdlib", TCC_OPTION_nostdlib, 0 },
1580 { "print-search-dirs", TCC_OPTION_print_search_dirs, 0 },
1581 { "v", TCC_OPTION_v, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1582 { "w", TCC_OPTION_w, 0 },
1583 { "pipe", TCC_OPTION_pipe, 0},
1584 { "E", TCC_OPTION_E, 0},
1585 { "MD", TCC_OPTION_MD, 0},
1586 { "MF", TCC_OPTION_MF, TCC_OPTION_HAS_ARG },
1587 { "x", TCC_OPTION_x, TCC_OPTION_HAS_ARG },
1588 { NULL, 0, 0 },
1591 static void parse_option_D(TCCState *s1, const char *optarg)
1593 char *sym = tcc_strdup(optarg);
1594 char *value = strchr(sym, '=');
1595 if (value)
1596 *value++ = '\0';
1597 tcc_define_symbol(s1, sym, value);
1598 tcc_free(sym);
1601 static void args_parser_add_file(TCCState *s, const char* filename, int filetype)
1603 struct filespec *f = tcc_malloc(sizeof *f + strlen(filename));
1604 f->type = filetype;
1605 strcpy(f->name, filename);
1606 dynarray_add((void ***)&s->files, &s->nb_files, f);
1609 /* read list file */
1610 static void args_parser_listfile(TCCState *s, const char *filename)
1612 int fd;
1613 size_t len;
1614 char *p;
1616 fd = open(filename, O_RDONLY | O_BINARY);
1617 if (fd < 0)
1618 tcc_error("file '%s' not found", filename);
1620 len = lseek(fd, 0, SEEK_END);
1621 p = tcc_malloc(len + 1), p[len] = 0;
1622 lseek(fd, 0, SEEK_SET), read(fd, p, len), close(fd);
1623 tcc_set_options(s, p);
1624 tcc_free(p);
1627 PUB_FUNC int tcc_parse_args(TCCState *s, int argc, char **argv)
1629 const TCCOption *popt;
1630 const char *optarg, *r;
1631 int optind = 0;
1632 int run = 0;
1633 int x;
1634 CString linker_arg; /* collect -Wl options */
1635 char buf[1024];
1637 cstr_new(&linker_arg);
1639 while (optind < argc) {
1641 r = argv[optind++];
1643 if (r[0] == '@' && r[1] != '\0') {
1644 args_parser_listfile(s, r + 1);
1645 continue;
1648 if (r[0] != '-' || r[1] == '\0') {
1649 args_parser_add_file(s, r, s->filetype);
1650 if (run) {
1651 optind--;
1652 /* argv[0] will be this file */
1653 break;
1655 continue;
1658 /* find option in table */
1659 for(popt = tcc_options; ; ++popt) {
1660 const char *p1 = popt->name;
1661 const char *r1 = r + 1;
1662 if (p1 == NULL)
1663 tcc_error("invalid option -- '%s'", r);
1664 if (!strstart(p1, &r1))
1665 continue;
1666 optarg = r1;
1667 if (popt->flags & TCC_OPTION_HAS_ARG) {
1668 if (*r1 == '\0' && !(popt->flags & TCC_OPTION_NOSEP)) {
1669 if (optind >= argc)
1670 arg_err:
1671 tcc_error("argument to '%s' is missing", r);
1672 optarg = argv[optind++];
1674 } else if (*r1 != '\0')
1675 continue;
1676 break;
1679 switch(popt->index) {
1680 case TCC_OPTION_HELP:
1681 return 0;
1682 case TCC_OPTION_I:
1683 tcc_add_include_path(s, optarg);
1684 break;
1685 case TCC_OPTION_D:
1686 parse_option_D(s, optarg);
1687 break;
1688 case TCC_OPTION_U:
1689 tcc_undefine_symbol(s, optarg);
1690 break;
1691 case TCC_OPTION_L:
1692 tcc_add_library_path(s, optarg);
1693 break;
1694 case TCC_OPTION_B:
1695 /* set tcc utilities path (mainly for tcc development) */
1696 tcc_set_lib_path(s, optarg);
1697 break;
1698 case TCC_OPTION_l:
1699 args_parser_add_file(s, optarg, AFF_TYPE_LIBWH - s->alacarte_link);
1700 s->nb_libraries++;
1701 break;
1702 case TCC_OPTION_pthread:
1703 parse_option_D(s, "_REENTRANT");
1704 s->option_pthread = 1;
1705 break;
1706 case TCC_OPTION_bench:
1707 s->do_bench = 1;
1708 break;
1709 #ifdef CONFIG_TCC_BACKTRACE
1710 case TCC_OPTION_bt:
1711 tcc_set_num_callers(atoi(optarg));
1712 break;
1713 #endif
1714 #ifdef CONFIG_TCC_BCHECK
1715 case TCC_OPTION_b:
1716 s->do_bounds_check = 1;
1717 s->do_debug = 1;
1718 break;
1719 #endif
1720 case TCC_OPTION_g:
1721 s->do_debug = 1;
1722 break;
1723 case TCC_OPTION_c:
1724 x = TCC_OUTPUT_OBJ;
1725 set_output_type:
1726 if (s->output_type)
1727 tcc_warning("-%s: overriding compiler action already specified", popt->name);
1728 s->output_type = x;
1729 break;
1730 case TCC_OPTION_d:
1731 if (*optarg == 'D')
1732 s->dflag = 3;
1733 else if (*optarg == 'M')
1734 s->dflag = 7;
1735 else
1736 goto unsupported_option;
1737 break;
1738 #ifdef TCC_TARGET_ARM
1739 case TCC_OPTION_float_abi:
1740 /* tcc doesn't support soft float yet */
1741 if (!strcmp(optarg, "softfp")) {
1742 s->float_abi = ARM_SOFTFP_FLOAT;
1743 tcc_undefine_symbol(s, "__ARM_PCS_VFP");
1744 } else if (!strcmp(optarg, "hard"))
1745 s->float_abi = ARM_HARD_FLOAT;
1746 else
1747 tcc_error("unsupported float abi '%s'", optarg);
1748 break;
1749 #endif
1750 case TCC_OPTION_static:
1751 s->static_link = 1;
1752 break;
1753 case TCC_OPTION_std:
1754 /* silently ignore, a current purpose:
1755 allow to use a tcc as a reference compiler for "make test" */
1756 break;
1757 case TCC_OPTION_shared:
1758 x = TCC_OUTPUT_DLL;
1759 goto set_output_type;
1760 case TCC_OPTION_soname:
1761 s->soname = tcc_strdup(optarg);
1762 break;
1763 case TCC_OPTION_m:
1764 s->option_m = tcc_strdup(optarg);
1765 break;
1766 case TCC_OPTION_o:
1767 if (s->outfile) {
1768 tcc_warning("multiple -o option");
1769 tcc_free(s->outfile);
1771 s->outfile = tcc_strdup(optarg);
1772 break;
1773 case TCC_OPTION_r:
1774 /* generate a .o merging several output files */
1775 s->option_r = 1;
1776 x = TCC_OUTPUT_OBJ;
1777 goto set_output_type;
1778 case TCC_OPTION_isystem:
1779 tcc_add_sysinclude_path(s, optarg);
1780 break;
1781 case TCC_OPTION_iwithprefix:
1782 snprintf(buf, sizeof buf, "{B}/%s", optarg);
1783 tcc_add_sysinclude_path(s, buf);
1784 break;
1785 case TCC_OPTION_nostdinc:
1786 s->nostdinc = 1;
1787 break;
1788 case TCC_OPTION_nostdlib:
1789 s->nostdlib = 1;
1790 break;
1791 case TCC_OPTION_print_search_dirs:
1792 s->print_search_dirs = 1;
1793 break;
1794 case TCC_OPTION_run:
1795 #ifndef TCC_IS_NATIVE
1796 tcc_error("-run is not available in a cross compiler");
1797 #endif
1798 tcc_set_options(s, optarg);
1799 run = 1;
1800 x = TCC_OUTPUT_MEMORY;
1801 goto set_output_type;
1802 case TCC_OPTION_v:
1803 do ++s->verbose; while (*optarg++ == 'v');
1804 break;
1805 case TCC_OPTION_f:
1806 if (tcc_set_flag(s, optarg, 1) < 0)
1807 goto unsupported_option;
1808 break;
1809 case TCC_OPTION_W:
1810 if (tcc_set_warning(s, optarg, 1) < 0)
1811 goto unsupported_option;
1812 break;
1813 case TCC_OPTION_w:
1814 s->warn_none = 1;
1815 break;
1816 case TCC_OPTION_rdynamic:
1817 s->rdynamic = 1;
1818 break;
1819 case TCC_OPTION_Wl:
1820 if (linker_arg.size)
1821 --linker_arg.size, cstr_ccat(&linker_arg, ',');
1822 cstr_cat(&linker_arg, optarg, 0);
1823 if (tcc_set_linker(s, linker_arg.data))
1824 cstr_free(&linker_arg);
1825 break;
1826 case TCC_OPTION_E:
1827 x = TCC_OUTPUT_PREPROCESS;
1828 goto set_output_type;
1829 case TCC_OPTION_P:
1830 s->Pflag = atoi(optarg) + 1;
1831 break;
1832 case TCC_OPTION_MD:
1833 s->gen_deps = 1;
1834 break;
1835 case TCC_OPTION_MF:
1836 s->deps_outfile = tcc_strdup(optarg);
1837 break;
1838 case TCC_OPTION_dumpversion:
1839 printf ("%s\n", TCC_VERSION);
1840 exit(0);
1841 break;
1842 case TCC_OPTION_x:
1843 if (*optarg == 'c')
1844 s->filetype = AFF_TYPE_C;
1845 else if (*optarg == 'a')
1846 s->filetype = AFF_TYPE_ASMPP;
1847 else if (*optarg == 'n')
1848 s->filetype = AFF_TYPE_NONE;
1849 else
1850 tcc_warning("unsupported language '%s'", optarg);
1851 break;
1852 case TCC_OPTION_O:
1853 x = atoi(optarg);
1854 if (x > 0)
1855 tcc_define_symbol(s, "__OPTIMIZE__", NULL);
1856 break;
1857 case TCC_OPTION_traditional:
1858 case TCC_OPTION_pedantic:
1859 case TCC_OPTION_pipe:
1860 case TCC_OPTION_s:
1861 /* ignored */
1862 break;
1863 default:
1864 unsupported_option:
1865 if (s->warn_unsupported)
1866 tcc_warning("unsupported option '%s'", r);
1867 break;
1871 if (linker_arg.size) {
1872 r = linker_arg.data;
1873 goto arg_err;
1876 return optind;
1879 LIBTCCAPI int tcc_set_options(TCCState *s, const char *r)
1881 char **argv;
1882 int argc;
1883 int ret, q, c;
1884 CString str;
1886 argc = 0, argv = NULL;
1887 for(;;) {
1888 while (c = (unsigned char)*r, c && c <= ' ')
1889 ++r;
1890 if (c == 0)
1891 break;
1892 q = 0;
1893 cstr_new(&str);
1894 while (c = (unsigned char)*r, c) {
1895 ++r;
1896 if (c == '\\' && (*r == '"' || *r == '\\')) {
1897 c = *r++;
1898 } else if (c == '"') {
1899 q = !q;
1900 continue;
1901 } else if (q == 0 && c <= ' ') {
1902 break;
1904 cstr_ccat(&str, c);
1906 cstr_ccat(&str, 0);
1907 //printf("<%s>\n", str.data), fflush(stdout);
1908 dynarray_add((void ***)&argv, &argc, tcc_strdup(str.data));
1909 cstr_free(&str);
1911 ret = tcc_parse_args(s, argc, argv);
1912 dynarray_reset(&argv, &argc);
1913 return ret;
1916 PUB_FUNC void tcc_print_stats(TCCState *s, unsigned total_time)
1918 if (total_time < 1)
1919 total_time = 1;
1920 if (total_bytes < 1)
1921 total_bytes = 1;
1922 fprintf(stderr, "%d idents, %d lines, %d bytes, %0.3f s, %u lines/s, %0.1f MB/s\n",
1923 tok_ident - TOK_IDENT, total_lines, total_bytes,
1924 (double)total_time/1000,
1925 (unsigned)total_lines*1000/total_time,
1926 (double)total_bytes/1000/total_time);
1929 PUB_FUNC void tcc_set_environment(TCCState *s)
1931 char * path;
1933 path = getenv("C_INCLUDE_PATH");
1934 if(path != NULL) {
1935 tcc_add_include_path(s, path);
1937 path = getenv("CPATH");
1938 if(path != NULL) {
1939 tcc_add_include_path(s, path);
1941 path = getenv("LIBRARY_PATH");
1942 if(path != NULL) {
1943 tcc_add_library_path(s, path);