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