called function should pop the arguments when using fastcall
[tinycc.git] / libtcc.c
blob6a5e45273c304121e029f522567dc7e934d8b7f2
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 static int nb_states;
37 /********************************************************/
39 #if ONE_SOURCE
40 #include "tccpp.c"
41 #include "tccgen.c"
42 #include "tccelf.c"
43 #include "tccrun.c"
44 #ifdef TCC_TARGET_I386
45 #include "i386-gen.c"
46 #include "i386-link.c"
47 #include "i386-asm.c"
48 #endif
49 #ifdef TCC_TARGET_ARM
50 #include "arm-gen.c"
51 #include "arm-link.c"
52 #include "arm-asm.c"
53 #endif
54 #ifdef TCC_TARGET_ARM64
55 #include "arm64-gen.c"
56 #include "arm64-link.c"
57 #endif
58 #ifdef TCC_TARGET_C67
59 #include "c67-gen.c"
60 #include "c67-link.c"
61 #include "tcccoff.c"
62 #endif
63 #ifdef TCC_TARGET_X86_64
64 #include "x86_64-gen.c"
65 #include "x86_64-link.c"
66 #include "i386-asm.c"
67 #endif
68 #ifdef CONFIG_TCC_ASM
69 #include "tccasm.c"
70 #endif
71 #ifdef TCC_TARGET_PE
72 #include "tccpe.c"
73 #endif
74 #endif /* ONE_SOURCE */
76 /********************************************************/
77 #ifndef CONFIG_TCC_ASM
78 ST_FUNC void asm_instr(void)
80 tcc_error("inline asm() not supported");
82 ST_FUNC void asm_global_instr(void)
84 tcc_error("inline asm() not supported");
86 #endif
88 /********************************************************/
89 #ifdef _WIN32
90 ST_FUNC char *normalize_slashes(char *path)
92 char *p;
93 for (p = path; *p; ++p)
94 if (*p == '\\')
95 *p = '/';
96 return path;
99 static HMODULE tcc_module;
101 /* on win32, we suppose the lib and includes are at the location of 'tcc.exe' */
102 static void tcc_set_lib_path_w32(TCCState *s)
104 char path[1024], *p;
105 GetModuleFileNameA(tcc_module, path, sizeof path);
106 p = tcc_basename(normalize_slashes(strlwr(path)));
107 if (p - 5 > path && 0 == strncmp(p - 5, "/bin/", 5))
108 p -= 5;
109 else if (p > path)
110 p--;
111 *p = 0;
112 tcc_set_lib_path(s, path);
115 #ifdef TCC_TARGET_PE
116 static void tcc_add_systemdir(TCCState *s)
118 char buf[1000];
119 GetSystemDirectory(buf, sizeof buf);
120 tcc_add_library_path(s, normalize_slashes(buf));
122 #endif
124 #ifdef LIBTCC_AS_DLL
125 BOOL WINAPI DllMain (HINSTANCE hDll, DWORD dwReason, LPVOID lpReserved)
127 if (DLL_PROCESS_ATTACH == dwReason)
128 tcc_module = hDll;
129 return TRUE;
131 #endif
132 #endif
134 /********************************************************/
135 /* copy a string and truncate it. */
136 ST_FUNC char *pstrcpy(char *buf, int buf_size, const char *s)
138 char *q, *q_end;
139 int c;
141 if (buf_size > 0) {
142 q = buf;
143 q_end = buf + buf_size - 1;
144 while (q < q_end) {
145 c = *s++;
146 if (c == '\0')
147 break;
148 *q++ = c;
150 *q = '\0';
152 return buf;
155 /* strcat and truncate. */
156 ST_FUNC char *pstrcat(char *buf, int buf_size, const char *s)
158 int len;
159 len = strlen(buf);
160 if (len < buf_size)
161 pstrcpy(buf + len, buf_size - len, s);
162 return buf;
165 ST_FUNC char *pstrncpy(char *out, const char *in, size_t num)
167 memcpy(out, in, num);
168 out[num] = '\0';
169 return out;
172 /* extract the basename of a file */
173 PUB_FUNC char *tcc_basename(const char *name)
175 char *p = strchr(name, 0);
176 while (p > name && !IS_DIRSEP(p[-1]))
177 --p;
178 return p;
181 /* extract extension part of a file
183 * (if no extension, return pointer to end-of-string)
185 PUB_FUNC char *tcc_fileextension (const char *name)
187 char *b = tcc_basename(name);
188 char *e = strrchr(b, '.');
189 return e ? e : strchr(b, 0);
192 /********************************************************/
193 /* memory management */
195 #undef free
196 #undef malloc
197 #undef realloc
199 #ifndef MEM_DEBUG
201 PUB_FUNC void tcc_free(void *ptr)
203 free(ptr);
206 PUB_FUNC void *tcc_malloc(unsigned long size)
208 void *ptr;
209 ptr = malloc(size);
210 if (!ptr && size)
211 tcc_error("memory full (malloc)");
212 return ptr;
215 PUB_FUNC void *tcc_mallocz(unsigned long size)
217 void *ptr;
218 ptr = tcc_malloc(size);
219 memset(ptr, 0, size);
220 return ptr;
223 PUB_FUNC void *tcc_realloc(void *ptr, unsigned long size)
225 void *ptr1;
226 ptr1 = realloc(ptr, size);
227 if (!ptr1 && size)
228 tcc_error("memory full (realloc)");
229 return ptr1;
232 PUB_FUNC char *tcc_strdup(const char *str)
234 char *ptr;
235 ptr = tcc_malloc(strlen(str) + 1);
236 strcpy(ptr, str);
237 return ptr;
240 PUB_FUNC void tcc_memcheck(void)
244 #else
246 #define MEM_DEBUG_MAGIC1 0xFEEDDEB1
247 #define MEM_DEBUG_MAGIC2 0xFEEDDEB2
248 #define MEM_DEBUG_MAGIC3 0xFEEDDEB3
249 #define MEM_DEBUG_FILE_LEN 40
250 #define MEM_DEBUG_CHECK3(header) \
251 ((mem_debug_header_t*)((char*)header + header->size))->magic3
252 #define MEM_USER_PTR(header) \
253 ((char *)header + offsetof(mem_debug_header_t, magic3))
254 #define MEM_HEADER_PTR(ptr) \
255 (mem_debug_header_t *)((char*)ptr - offsetof(mem_debug_header_t, magic3))
257 struct mem_debug_header {
258 unsigned magic1;
259 unsigned size;
260 struct mem_debug_header *prev;
261 struct mem_debug_header *next;
262 int line_num;
263 char file_name[MEM_DEBUG_FILE_LEN + 1];
264 unsigned magic2;
265 ALIGNED(16) unsigned magic3;
268 typedef struct mem_debug_header mem_debug_header_t;
270 static mem_debug_header_t *mem_debug_chain;
271 static unsigned mem_cur_size;
272 static unsigned mem_max_size;
274 static mem_debug_header_t *malloc_check(void *ptr, const char *msg)
276 mem_debug_header_t * header = MEM_HEADER_PTR(ptr);
277 if (header->magic1 != MEM_DEBUG_MAGIC1 ||
278 header->magic2 != MEM_DEBUG_MAGIC2 ||
279 MEM_DEBUG_CHECK3(header) != MEM_DEBUG_MAGIC3 ||
280 header->size == (unsigned)-1) {
281 fprintf(stderr, "%s check failed\n", msg);
282 if (header->magic1 == MEM_DEBUG_MAGIC1)
283 fprintf(stderr, "%s:%u: block allocated here.\n",
284 header->file_name, header->line_num);
285 exit(1);
287 return header;
290 PUB_FUNC void *tcc_malloc_debug(unsigned long size, const char *file, int line)
292 int ofs;
293 mem_debug_header_t *header;
295 header = malloc(sizeof(mem_debug_header_t) + size);
296 if (!header)
297 tcc_error("memory full (malloc)");
299 header->magic1 = MEM_DEBUG_MAGIC1;
300 header->magic2 = MEM_DEBUG_MAGIC2;
301 header->size = size;
302 MEM_DEBUG_CHECK3(header) = MEM_DEBUG_MAGIC3;
303 header->line_num = line;
304 ofs = strlen(file) - MEM_DEBUG_FILE_LEN;
305 strncpy(header->file_name, file + (ofs > 0 ? ofs : 0), MEM_DEBUG_FILE_LEN);
306 header->file_name[MEM_DEBUG_FILE_LEN] = 0;
308 header->next = mem_debug_chain;
309 header->prev = NULL;
310 if (header->next)
311 header->next->prev = header;
312 mem_debug_chain = header;
314 mem_cur_size += size;
315 if (mem_cur_size > mem_max_size)
316 mem_max_size = mem_cur_size;
318 return MEM_USER_PTR(header);
321 PUB_FUNC void tcc_free_debug(void *ptr)
323 mem_debug_header_t *header;
324 if (!ptr)
325 return;
326 header = malloc_check(ptr, "tcc_free");
327 mem_cur_size -= header->size;
328 header->size = (unsigned)-1;
329 if (header->next)
330 header->next->prev = header->prev;
331 if (header->prev)
332 header->prev->next = header->next;
333 if (header == mem_debug_chain)
334 mem_debug_chain = header->next;
335 free(header);
338 PUB_FUNC void *tcc_mallocz_debug(unsigned long size, const char *file, int line)
340 void *ptr;
341 ptr = tcc_malloc_debug(size,file,line);
342 memset(ptr, 0, size);
343 return ptr;
346 PUB_FUNC void *tcc_realloc_debug(void *ptr, unsigned long size, const char *file, int line)
348 mem_debug_header_t *header;
349 int mem_debug_chain_update = 0;
350 if (!ptr)
351 return tcc_malloc_debug(size, file, line);
352 header = malloc_check(ptr, "tcc_realloc");
353 mem_cur_size -= header->size;
354 mem_debug_chain_update = (header == mem_debug_chain);
355 header = realloc(header, sizeof(mem_debug_header_t) + size);
356 if (!header)
357 tcc_error("memory full (realloc)");
358 header->size = size;
359 MEM_DEBUG_CHECK3(header) = MEM_DEBUG_MAGIC3;
360 if (header->next)
361 header->next->prev = header;
362 if (header->prev)
363 header->prev->next = header;
364 if (mem_debug_chain_update)
365 mem_debug_chain = header;
366 mem_cur_size += size;
367 if (mem_cur_size > mem_max_size)
368 mem_max_size = mem_cur_size;
369 return MEM_USER_PTR(header);
372 PUB_FUNC char *tcc_strdup_debug(const char *str, const char *file, int line)
374 char *ptr;
375 ptr = tcc_malloc_debug(strlen(str) + 1, file, line);
376 strcpy(ptr, str);
377 return ptr;
380 PUB_FUNC void tcc_memcheck(void)
382 if (mem_cur_size) {
383 mem_debug_header_t *header = mem_debug_chain;
384 fprintf(stderr, "MEM_DEBUG: mem_leak= %d bytes, mem_max_size= %d bytes\n",
385 mem_cur_size, mem_max_size);
386 while (header) {
387 fprintf(stderr, "%s:%u: error: %u bytes leaked\n",
388 header->file_name, header->line_num, header->size);
389 header = header->next;
391 #if MEM_DEBUG-0 == 2
392 exit(2);
393 #endif
396 #endif /* MEM_DEBUG */
398 #define free(p) use_tcc_free(p)
399 #define malloc(s) use_tcc_malloc(s)
400 #define realloc(p, s) use_tcc_realloc(p, s)
402 /********************************************************/
403 /* dynarrays */
405 ST_FUNC void dynarray_add(void *ptab, int *nb_ptr, void *data)
407 int nb, nb_alloc;
408 void **pp;
410 nb = *nb_ptr;
411 pp = *(void ***)ptab;
412 /* every power of two we double array size */
413 if ((nb & (nb - 1)) == 0) {
414 if (!nb)
415 nb_alloc = 1;
416 else
417 nb_alloc = nb * 2;
418 pp = tcc_realloc(pp, nb_alloc * sizeof(void *));
419 *(void***)ptab = pp;
421 pp[nb++] = data;
422 *nb_ptr = nb;
425 ST_FUNC void dynarray_reset(void *pp, int *n)
427 void **p;
428 for (p = *(void***)pp; *n; ++p, --*n)
429 if (*p)
430 tcc_free(*p);
431 tcc_free(*(void**)pp);
432 *(void**)pp = NULL;
435 static void tcc_split_path(TCCState *s, void *p_ary, int *p_nb_ary, const char *in)
437 const char *p;
438 do {
439 int c;
440 CString str;
442 cstr_new(&str);
443 for (p = in; c = *p, c != '\0' && c != PATHSEP; ++p) {
444 if (c == '{' && p[1] && p[2] == '}') {
445 c = p[1], p += 2;
446 if (c == 'B')
447 cstr_cat(&str, s->tcc_lib_path, -1);
448 } else {
449 cstr_ccat(&str, c);
452 if (str.size) {
453 cstr_ccat(&str, '\0');
454 dynarray_add(p_ary, p_nb_ary, tcc_strdup(str.data));
456 cstr_free(&str);
457 in = p+1;
458 } while (*p);
461 /********************************************************/
463 static void strcat_vprintf(char *buf, int buf_size, const char *fmt, va_list ap)
465 int len;
466 len = strlen(buf);
467 vsnprintf(buf + len, buf_size - len, fmt, ap);
470 static void strcat_printf(char *buf, int buf_size, const char *fmt, ...)
472 va_list ap;
473 va_start(ap, fmt);
474 strcat_vprintf(buf, buf_size, fmt, ap);
475 va_end(ap);
478 static void error1(TCCState *s1, int is_warning, const char *fmt, va_list ap)
480 char buf[2048];
481 BufferedFile **pf, *f;
483 buf[0] = '\0';
484 /* use upper file if inline ":asm:" or token ":paste:" */
485 for (f = file; f && f->filename[0] == ':'; f = f->prev)
487 if (f) {
488 for(pf = s1->include_stack; pf < s1->include_stack_ptr; pf++)
489 strcat_printf(buf, sizeof(buf), "In file included from %s:%d:\n",
490 (*pf)->filename, (*pf)->line_num);
491 if (f->line_num > 0) {
492 strcat_printf(buf, sizeof(buf), "%s:%d: ",
493 f->filename, f->line_num - !!(tok_flags & TOK_FLAG_BOL));
494 } else {
495 strcat_printf(buf, sizeof(buf), "%s: ",
496 f->filename);
498 } else {
499 strcat_printf(buf, sizeof(buf), "tcc: ");
501 if (is_warning)
502 strcat_printf(buf, sizeof(buf), "warning: ");
503 else
504 strcat_printf(buf, sizeof(buf), "error: ");
505 strcat_vprintf(buf, sizeof(buf), fmt, ap);
507 if (!s1->error_func) {
508 /* default case: stderr */
509 if (s1->output_type == TCC_OUTPUT_PREPROCESS && s1->ppfp == stdout)
510 /* print a newline during tcc -E */
511 printf("\n"), fflush(stdout);
512 fflush(stdout); /* flush -v output */
513 fprintf(stderr, "%s\n", buf);
514 fflush(stderr); /* print error/warning now (win32) */
515 } else {
516 s1->error_func(s1->error_opaque, buf);
518 if (!is_warning || s1->warn_error)
519 s1->nb_errors++;
522 LIBTCCAPI void tcc_set_error_func(TCCState *s, void *error_opaque,
523 void (*error_func)(void *opaque, const char *msg))
525 s->error_opaque = error_opaque;
526 s->error_func = error_func;
529 /* error without aborting current compilation */
530 PUB_FUNC void tcc_error_noabort(const char *fmt, ...)
532 TCCState *s1 = tcc_state;
533 va_list ap;
535 va_start(ap, fmt);
536 error1(s1, 0, fmt, ap);
537 va_end(ap);
540 PUB_FUNC void tcc_error(const char *fmt, ...)
542 TCCState *s1 = tcc_state;
543 va_list ap;
545 va_start(ap, fmt);
546 error1(s1, 0, fmt, ap);
547 va_end(ap);
548 /* better than nothing: in some cases, we accept to handle errors */
549 if (s1->error_set_jmp_enabled) {
550 longjmp(s1->error_jmp_buf, 1);
551 } else {
552 /* XXX: eliminate this someday */
553 exit(1);
557 PUB_FUNC void tcc_warning(const char *fmt, ...)
559 TCCState *s1 = tcc_state;
560 va_list ap;
562 if (s1->warn_none)
563 return;
565 va_start(ap, fmt);
566 error1(s1, 1, fmt, ap);
567 va_end(ap);
570 /********************************************************/
571 /* I/O layer */
573 ST_FUNC void tcc_open_bf(TCCState *s1, const char *filename, int initlen)
575 BufferedFile *bf;
576 int buflen = initlen ? initlen : IO_BUF_SIZE;
578 bf = tcc_mallocz(sizeof(BufferedFile) + buflen);
579 bf->buf_ptr = bf->buffer;
580 bf->buf_end = bf->buffer + initlen;
581 bf->buf_end[0] = CH_EOB; /* put eob symbol */
582 pstrcpy(bf->filename, sizeof(bf->filename), filename);
583 bf->true_filename = bf->filename;
584 bf->line_num = 1;
585 bf->ifdef_stack_ptr = s1->ifdef_stack_ptr;
586 bf->fd = -1;
587 bf->prev = file;
588 file = bf;
589 tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
592 ST_FUNC void tcc_close(void)
594 BufferedFile *bf = file;
595 if (bf->fd > 0) {
596 close(bf->fd);
597 total_lines += bf->line_num;
599 if (bf->true_filename != bf->filename)
600 tcc_free(bf->true_filename);
601 file = bf->prev;
602 tcc_free(bf);
605 ST_FUNC int tcc_open(TCCState *s1, const char *filename)
607 int fd;
608 if (strcmp(filename, "-") == 0)
609 fd = 0, filename = "<stdin>";
610 else
611 fd = open(filename, O_RDONLY | O_BINARY);
612 if ((s1->verbose == 2 && fd >= 0) || s1->verbose == 3)
613 printf("%s %*s%s\n", fd < 0 ? "nf":"->",
614 (int)(s1->include_stack_ptr - s1->include_stack), "", filename);
615 if (fd < 0)
616 return -1;
617 tcc_open_bf(s1, filename, 0);
618 #ifdef _WIN32
619 normalize_slashes(file->filename);
620 #endif
621 file->fd = fd;
622 return fd;
625 /* compile the file opened in 'file'. Return non zero if errors. */
626 static int tcc_compile(TCCState *s1)
628 Sym *define_start;
629 int filetype, is_asm;
631 define_start = define_stack;
632 filetype = s1->filetype;
633 is_asm = filetype == AFF_TYPE_ASM || filetype == AFF_TYPE_ASMPP;
635 if (setjmp(s1->error_jmp_buf) == 0) {
636 s1->nb_errors = 0;
637 s1->error_set_jmp_enabled = 1;
639 preprocess_start(s1, is_asm);
640 if (s1->output_type == TCC_OUTPUT_PREPROCESS) {
641 tcc_preprocess(s1);
642 } else if (is_asm) {
643 #ifdef CONFIG_TCC_ASM
644 tcc_assemble(s1, filetype == AFF_TYPE_ASMPP);
645 #else
646 tcc_error_noabort("asm not supported");
647 #endif
648 } else {
649 tccgen_compile(s1);
652 s1->error_set_jmp_enabled = 0;
654 preprocess_end(s1);
655 free_inline_functions(s1);
656 /* reset define stack, but keep -D and built-ins */
657 free_defines(define_start);
658 sym_pop(&global_stack, NULL, 0);
659 sym_pop(&local_stack, NULL, 0);
660 return s1->nb_errors != 0 ? -1 : 0;
663 LIBTCCAPI int tcc_compile_string(TCCState *s, const char *str)
665 int len, ret;
667 len = strlen(str);
668 tcc_open_bf(s, "<string>", len);
669 memcpy(file->buffer, str, len);
670 ret = tcc_compile(s);
671 tcc_close();
672 return ret;
675 /* define a preprocessor symbol. A value can also be provided with the '=' operator */
676 LIBTCCAPI void tcc_define_symbol(TCCState *s1, const char *sym, const char *value)
678 int len1, len2;
679 /* default value */
680 if (!value)
681 value = "1";
682 len1 = strlen(sym);
683 len2 = strlen(value);
685 /* init file structure */
686 tcc_open_bf(s1, "<define>", len1 + len2 + 1);
687 memcpy(file->buffer, sym, len1);
688 file->buffer[len1] = ' ';
689 memcpy(file->buffer + len1 + 1, value, len2);
691 /* parse with define parser */
692 next_nomacro();
693 parse_define();
694 tcc_close();
697 /* undefine a preprocessor symbol */
698 LIBTCCAPI void tcc_undefine_symbol(TCCState *s1, const char *sym)
700 TokenSym *ts;
701 Sym *s;
702 ts = tok_alloc(sym, strlen(sym));
703 s = define_find(ts->tok);
704 /* undefine symbol by putting an invalid name */
705 if (s)
706 define_undef(s);
709 /* cleanup all static data used during compilation */
710 static void tcc_cleanup(void)
712 if (NULL == tcc_state)
713 return;
714 while (file)
715 tcc_close();
716 tccpp_delete(tcc_state);
717 tcc_state = NULL;
718 /* free sym_pools */
719 dynarray_reset(&sym_pools, &nb_sym_pools);
720 /* reset symbol stack */
721 sym_free_first = NULL;
724 LIBTCCAPI TCCState *tcc_new(void)
726 TCCState *s;
728 tcc_cleanup();
730 s = tcc_mallocz(sizeof(TCCState));
731 if (!s)
732 return NULL;
733 tcc_state = s;
734 ++nb_states;
736 s->alacarte_link = 1;
737 s->nocommon = 1;
738 s->warn_implicit_function_declaration = 1;
739 s->ms_extensions = 1;
741 #ifdef CHAR_IS_UNSIGNED
742 s->char_is_unsigned = 1;
743 #endif
744 #ifdef TCC_TARGET_I386
745 s->seg_size = 32;
746 #endif
747 /* enable this if you want symbols with leading underscore on windows: */
748 #if 0 /* def TCC_TARGET_PE */
749 s->leading_underscore = 1;
750 #endif
751 #ifdef _WIN32
752 tcc_set_lib_path_w32(s);
753 #else
754 tcc_set_lib_path(s, CONFIG_TCCDIR);
755 #endif
756 tccelf_new(s);
757 tccpp_new(s);
759 /* we add dummy defines for some special macros to speed up tests
760 and to have working defined() */
761 define_push(TOK___LINE__, MACRO_OBJ, NULL, NULL);
762 define_push(TOK___FILE__, MACRO_OBJ, NULL, NULL);
763 define_push(TOK___DATE__, MACRO_OBJ, NULL, NULL);
764 define_push(TOK___TIME__, MACRO_OBJ, NULL, NULL);
765 define_push(TOK___COUNTER__, MACRO_OBJ, NULL, NULL);
767 /* define __TINYC__ 92X */
768 char buffer[32]; int a,b,c;
769 sscanf(TCC_VERSION, "%d.%d.%d", &a, &b, &c);
770 sprintf(buffer, "%d", a*10000 + b*100 + c);
771 tcc_define_symbol(s, "__TINYC__", buffer);
774 /* standard defines */
775 tcc_define_symbol(s, "__STDC__", NULL);
776 tcc_define_symbol(s, "__STDC_VERSION__", "199901L");
777 tcc_define_symbol(s, "__STDC_HOSTED__", NULL);
779 /* target defines */
780 #if defined(TCC_TARGET_I386)
781 tcc_define_symbol(s, "__i386__", NULL);
782 tcc_define_symbol(s, "__i386", NULL);
783 tcc_define_symbol(s, "i386", NULL);
784 #elif defined(TCC_TARGET_X86_64)
785 tcc_define_symbol(s, "__x86_64__", NULL);
786 #elif defined(TCC_TARGET_ARM)
787 tcc_define_symbol(s, "__ARM_ARCH_4__", NULL);
788 tcc_define_symbol(s, "__arm_elf__", NULL);
789 tcc_define_symbol(s, "__arm_elf", NULL);
790 tcc_define_symbol(s, "arm_elf", NULL);
791 tcc_define_symbol(s, "__arm__", NULL);
792 tcc_define_symbol(s, "__arm", NULL);
793 tcc_define_symbol(s, "arm", NULL);
794 tcc_define_symbol(s, "__APCS_32__", NULL);
795 tcc_define_symbol(s, "__ARMEL__", NULL);
796 #if defined(TCC_ARM_EABI)
797 tcc_define_symbol(s, "__ARM_EABI__", NULL);
798 #endif
799 #if defined(TCC_ARM_HARDFLOAT)
800 s->float_abi = ARM_HARD_FLOAT;
801 tcc_define_symbol(s, "__ARM_PCS_VFP", NULL);
802 #else
803 s->float_abi = ARM_SOFTFP_FLOAT;
804 #endif
805 #elif defined(TCC_TARGET_ARM64)
806 tcc_define_symbol(s, "__aarch64__", NULL);
807 #endif
809 #ifdef TCC_TARGET_PE
810 tcc_define_symbol(s, "_WIN32", NULL);
811 # ifdef TCC_TARGET_X86_64
812 tcc_define_symbol(s, "_WIN64", NULL);
813 # endif
814 #else
815 tcc_define_symbol(s, "__unix__", NULL);
816 tcc_define_symbol(s, "__unix", NULL);
817 tcc_define_symbol(s, "unix", NULL);
818 # if defined(__linux__)
819 tcc_define_symbol(s, "__linux__", NULL);
820 tcc_define_symbol(s, "__linux", NULL);
821 # endif
822 # if defined(__FreeBSD__)
823 tcc_define_symbol(s, "__FreeBSD__", "__FreeBSD__");
824 /* No 'Thread Storage Local' on FreeBSD with tcc */
825 tcc_define_symbol(s, "__NO_TLS", NULL);
826 # endif
827 # if defined(__FreeBSD_kernel__)
828 tcc_define_symbol(s, "__FreeBSD_kernel__", NULL);
829 # endif
830 #endif
831 # if defined(__NetBSD__)
832 tcc_define_symbol(s, "__NetBSD__", "__NetBSD__");
833 # endif
834 # if defined(__OpenBSD__)
835 tcc_define_symbol(s, "__OpenBSD__", "__OpenBSD__");
836 # endif
838 /* TinyCC & gcc defines */
839 #if defined(TCC_TARGET_PE) && PTR_SIZE == 8
840 /* 64bit Windows. */
841 tcc_define_symbol(s, "__SIZE_TYPE__", "unsigned long long");
842 tcc_define_symbol(s, "__PTRDIFF_TYPE__", "long long");
843 tcc_define_symbol(s, "__LLP64__", NULL);
844 #elif PTR_SIZE == 8
845 /* Other 64bit systems. */
846 tcc_define_symbol(s, "__SIZE_TYPE__", "unsigned long");
847 tcc_define_symbol(s, "__PTRDIFF_TYPE__", "long");
848 tcc_define_symbol(s, "__LP64__", NULL);
849 #else
850 /* Other 32bit systems. */
851 tcc_define_symbol(s, "__SIZE_TYPE__", "unsigned int");
852 tcc_define_symbol(s, "__PTRDIFF_TYPE__", "int");
853 tcc_define_symbol(s, "__ILP32__", NULL);
854 #endif
856 #if defined(TCC_MUSL)
857 tcc_define_symbol(s, "__builtin_va_list", "void *");
858 #endif /* TCC_MUSL */
860 #ifdef TCC_TARGET_PE
861 tcc_define_symbol(s, "__WCHAR_TYPE__", "unsigned short");
862 tcc_define_symbol(s, "__WINT_TYPE__", "unsigned short");
863 #else
864 tcc_define_symbol(s, "__WCHAR_TYPE__", "int");
865 /* wint_t is unsigned int by default, but (signed) int on BSDs
866 and unsigned short on windows. Other OSes might have still
867 other conventions, sigh. */
868 # if defined(__FreeBSD__) || defined (__FreeBSD_kernel__) \
869 || defined(__NetBSD__) || defined(__OpenBSD__)
870 tcc_define_symbol(s, "__WINT_TYPE__", "int");
871 # ifdef __FreeBSD__
872 /* define __GNUC__ to have some useful stuff from sys/cdefs.h
873 that are unconditionally used in FreeBSDs other system headers :/ */
874 tcc_define_symbol(s, "__GNUC__", "2");
875 tcc_define_symbol(s, "__GNUC_MINOR__", "7");
876 tcc_define_symbol(s, "__builtin_alloca", "alloca");
877 # endif
878 # else
879 tcc_define_symbol(s, "__WINT_TYPE__", "unsigned int");
880 /* glibc defines */
881 tcc_define_symbol(s, "__REDIRECT(name, proto, alias)",
882 "name proto __asm__ (#alias)");
883 tcc_define_symbol(s, "__REDIRECT_NTH(name, proto, alias)",
884 "name proto __asm__ (#alias) __THROW");
885 # endif
886 /* Some GCC builtins that are simple to express as macros. */
887 tcc_define_symbol(s, "__builtin_extract_return_addr(x)", "x");
888 #endif /* ndef TCC_TARGET_PE */
889 return s;
892 LIBTCCAPI void tcc_delete(TCCState *s1)
894 tcc_cleanup();
896 /* free sections */
897 tccelf_delete(s1);
899 /* free library paths */
900 dynarray_reset(&s1->library_paths, &s1->nb_library_paths);
901 dynarray_reset(&s1->crt_paths, &s1->nb_crt_paths);
903 /* free include paths */
904 dynarray_reset(&s1->cached_includes, &s1->nb_cached_includes);
905 dynarray_reset(&s1->include_paths, &s1->nb_include_paths);
906 dynarray_reset(&s1->sysinclude_paths, &s1->nb_sysinclude_paths);
907 dynarray_reset(&s1->cmd_include_files, &s1->nb_cmd_include_files);
909 tcc_free(s1->tcc_lib_path);
910 tcc_free(s1->soname);
911 tcc_free(s1->rpath);
912 tcc_free(s1->init_symbol);
913 tcc_free(s1->fini_symbol);
914 tcc_free(s1->outfile);
915 tcc_free(s1->deps_outfile);
916 dynarray_reset(&s1->files, &s1->nb_files);
917 dynarray_reset(&s1->target_deps, &s1->nb_target_deps);
918 dynarray_reset(&s1->pragma_libs, &s1->nb_pragma_libs);
919 dynarray_reset(&s1->argv, &s1->argc);
921 #ifdef TCC_IS_NATIVE
922 /* free runtime memory */
923 tcc_run_free(s1);
924 #endif
926 tcc_free(s1);
927 if (0 == --nb_states)
928 tcc_memcheck();
931 LIBTCCAPI int tcc_set_output_type(TCCState *s, int output_type)
933 s->output_type = output_type;
935 /* always elf for objects */
936 if (output_type == TCC_OUTPUT_OBJ)
937 s->output_format = TCC_OUTPUT_FORMAT_ELF;
939 if (s->char_is_unsigned)
940 tcc_define_symbol(s, "__CHAR_UNSIGNED__", NULL);
942 if (!s->nostdinc) {
943 /* default include paths */
944 /* -isystem paths have already been handled */
945 tcc_add_sysinclude_path(s, CONFIG_TCC_SYSINCLUDEPATHS);
948 #ifdef CONFIG_TCC_BCHECK
949 if (s->do_bounds_check) {
950 /* if bound checking, then add corresponding sections */
951 tccelf_bounds_new(s);
952 /* define symbol */
953 tcc_define_symbol(s, "__BOUNDS_CHECKING_ON", NULL);
955 #endif
956 if (s->do_debug) {
957 /* add debug sections */
958 tccelf_stab_new(s);
961 tcc_add_library_path(s, CONFIG_TCC_LIBPATHS);
963 #ifdef TCC_TARGET_PE
964 # ifdef _WIN32
965 if (!s->nostdlib && output_type != TCC_OUTPUT_OBJ)
966 tcc_add_systemdir(s);
967 # endif
968 #else
969 /* paths for crt objects */
970 tcc_split_path(s, &s->crt_paths, &s->nb_crt_paths, CONFIG_TCC_CRTPREFIX);
971 /* add libc crt1/crti objects */
972 if ((output_type == TCC_OUTPUT_EXE || output_type == TCC_OUTPUT_DLL) &&
973 !s->nostdlib) {
974 if (output_type != TCC_OUTPUT_DLL)
975 tcc_add_crt(s, "crt1.o");
976 tcc_add_crt(s, "crti.o");
978 #endif
979 return 0;
982 LIBTCCAPI int tcc_add_include_path(TCCState *s, const char *pathname)
984 tcc_split_path(s, &s->include_paths, &s->nb_include_paths, pathname);
985 return 0;
988 LIBTCCAPI int tcc_add_sysinclude_path(TCCState *s, const char *pathname)
990 tcc_split_path(s, &s->sysinclude_paths, &s->nb_sysinclude_paths, pathname);
991 return 0;
994 ST_FUNC int tcc_add_file_internal(TCCState *s1, const char *filename, int flags)
996 int ret;
998 /* open the file */
999 ret = tcc_open(s1, filename);
1000 if (ret < 0) {
1001 if (flags & AFF_PRINT_ERROR)
1002 tcc_error_noabort("file '%s' not found", filename);
1003 return ret;
1006 /* update target deps */
1007 dynarray_add(&s1->target_deps, &s1->nb_target_deps,
1008 tcc_strdup(filename));
1010 if (flags & AFF_TYPE_BIN) {
1011 ElfW(Ehdr) ehdr;
1012 int fd, obj_type;
1014 fd = file->fd;
1015 obj_type = tcc_object_type(fd, &ehdr);
1016 lseek(fd, 0, SEEK_SET);
1018 /* do not display line number if error */
1019 file->line_num = 0;
1021 #ifdef TCC_TARGET_MACHO
1022 if (0 == obj_type && 0 == strcmp(tcc_fileextension(filename), "dylib"))
1023 obj_type = AFF_BINTYPE_DYN;
1024 #endif
1026 switch (obj_type) {
1027 case AFF_BINTYPE_REL:
1028 ret = tcc_load_object_file(s1, fd, 0);
1029 break;
1030 #ifndef TCC_TARGET_PE
1031 case AFF_BINTYPE_DYN:
1032 if (s1->output_type == TCC_OUTPUT_MEMORY) {
1033 ret = 0;
1034 #ifdef TCC_IS_NATIVE
1035 if (NULL == dlopen(filename, RTLD_GLOBAL | RTLD_LAZY))
1036 ret = -1;
1037 #endif
1038 } else {
1039 ret = tcc_load_dll(s1, fd, filename,
1040 (flags & AFF_REFERENCED_DLL) != 0);
1042 break;
1043 #endif
1044 case AFF_BINTYPE_AR:
1045 ret = tcc_load_archive(s1, fd);
1046 break;
1047 #ifdef TCC_TARGET_COFF
1048 case AFF_BINTYPE_C67:
1049 ret = tcc_load_coff(s1, fd);
1050 break;
1051 #endif
1052 default:
1053 #ifdef TCC_TARGET_PE
1054 ret = pe_load_file(s1, filename, fd);
1055 #else
1056 /* as GNU ld, consider it is an ld script if not recognized */
1057 ret = tcc_load_ldscript(s1);
1058 #endif
1059 if (ret < 0)
1060 tcc_error_noabort("unrecognized file type");
1061 break;
1063 } else {
1064 ret = tcc_compile(s1);
1066 tcc_close();
1067 return ret;
1070 LIBTCCAPI int tcc_add_file(TCCState *s, const char *filename)
1072 int filetype = s->filetype;
1073 int flags = AFF_PRINT_ERROR;
1074 if (filetype == 0) {
1075 /* use a file extension to detect a filetype */
1076 const char *ext = tcc_fileextension(filename);
1077 if (ext[0]) {
1078 ext++;
1079 if (!strcmp(ext, "S"))
1080 filetype = AFF_TYPE_ASMPP;
1081 else if (!strcmp(ext, "s"))
1082 filetype = AFF_TYPE_ASM;
1083 else if (!PATHCMP(ext, "c") || !PATHCMP(ext, "i"))
1084 filetype = AFF_TYPE_C;
1085 else
1086 flags |= AFF_TYPE_BIN;
1087 } else {
1088 filetype = AFF_TYPE_C;
1090 s->filetype = filetype;
1092 return tcc_add_file_internal(s, filename, flags);
1095 LIBTCCAPI int tcc_add_library_path(TCCState *s, const char *pathname)
1097 tcc_split_path(s, &s->library_paths, &s->nb_library_paths, pathname);
1098 return 0;
1101 static int tcc_add_library_internal(TCCState *s, const char *fmt,
1102 const char *filename, int flags, char **paths, int nb_paths)
1104 char buf[1024];
1105 int i;
1107 for(i = 0; i < nb_paths; i++) {
1108 snprintf(buf, sizeof(buf), fmt, paths[i], filename);
1109 if (tcc_add_file_internal(s, buf, flags | AFF_TYPE_BIN) == 0)
1110 return 0;
1112 return -1;
1115 /* find and load a dll. Return non zero if not found */
1116 /* XXX: add '-rpath' option support ? */
1117 ST_FUNC int tcc_add_dll(TCCState *s, const char *filename, int flags)
1119 return tcc_add_library_internal(s, "%s/%s", filename, flags,
1120 s->library_paths, s->nb_library_paths);
1123 ST_FUNC int tcc_add_crt(TCCState *s, const char *filename)
1125 if (-1 == tcc_add_library_internal(s, "%s/%s",
1126 filename, 0, s->crt_paths, s->nb_crt_paths))
1127 tcc_error_noabort("file '%s' not found", filename);
1128 return 0;
1131 /* the library name is the same as the argument of the '-l' option */
1132 LIBTCCAPI int tcc_add_library(TCCState *s, const char *libraryname)
1134 #if defined TCC_TARGET_PE
1135 const char *libs[] = { "%s/%s.def", "%s/lib%s.def", "%s/%s.dll", "%s/lib%s.dll", "%s/lib%s.a", NULL };
1136 const char **pp = s->static_link ? libs + 4 : libs;
1137 #elif defined TCC_TARGET_MACHO
1138 const char *libs[] = { "%s/lib%s.dylib", "%s/lib%s.a", NULL };
1139 const char **pp = s->static_link ? libs + 1 : libs;
1140 #else
1141 const char *libs[] = { "%s/lib%s.so", "%s/lib%s.a", NULL };
1142 const char **pp = s->static_link ? libs + 1 : libs;
1143 #endif
1144 while (*pp) {
1145 if (0 == tcc_add_library_internal(s, *pp,
1146 libraryname, 0, s->library_paths, s->nb_library_paths))
1147 return 0;
1148 ++pp;
1150 return -1;
1153 PUB_FUNC int tcc_add_library_err(TCCState *s, const char *libname)
1155 int ret = tcc_add_library(s, libname);
1156 if (ret < 0)
1157 tcc_error_noabort("library '%s' not found", libname);
1158 return ret;
1161 /* handle #pragma comment(lib,) */
1162 ST_FUNC void tcc_add_pragma_libs(TCCState *s1)
1164 int i;
1165 for (i = 0; i < s1->nb_pragma_libs; i++)
1166 tcc_add_library_err(s1, s1->pragma_libs[i]);
1169 LIBTCCAPI int tcc_add_symbol(TCCState *s, const char *name, const void *val)
1171 #ifdef TCC_TARGET_PE
1172 /* On x86_64 'val' might not be reachable with a 32bit offset.
1173 So it is handled here as if it were in a DLL. */
1174 pe_putimport(s, 0, name, (uintptr_t)val);
1175 #else
1176 set_elf_sym(symtab_section, (uintptr_t)val, 0,
1177 ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE), 0,
1178 SHN_ABS, name);
1179 #endif
1180 return 0;
1183 LIBTCCAPI void tcc_set_lib_path(TCCState *s, const char *path)
1185 tcc_free(s->tcc_lib_path);
1186 s->tcc_lib_path = tcc_strdup(path);
1189 #define WD_ALL 0x0001 /* warning is activated when using -Wall */
1190 #define FD_INVERT 0x0002 /* invert value before storing */
1192 typedef struct FlagDef {
1193 uint16_t offset;
1194 uint16_t flags;
1195 const char *name;
1196 } FlagDef;
1198 static int no_flag(const char **pp)
1200 const char *p = *pp;
1201 if (*p != 'n' || *++p != 'o' || *++p != '-')
1202 return 0;
1203 *pp = p + 1;
1204 return 1;
1207 ST_FUNC int set_flag(TCCState *s, const FlagDef *flags, const char *name)
1209 int value, ret;
1210 const FlagDef *p;
1211 const char *r;
1213 value = 1;
1214 r = name;
1215 if (no_flag(&r))
1216 value = 0;
1218 for (ret = -1, p = flags; p->name; ++p) {
1219 if (ret) {
1220 if (strcmp(r, p->name))
1221 continue;
1222 } else {
1223 if (0 == (p->flags & WD_ALL))
1224 continue;
1226 if (p->offset) {
1227 *(int*)((char *)s + p->offset) =
1228 p->flags & FD_INVERT ? !value : value;
1229 if (ret)
1230 return 0;
1231 } else {
1232 ret = 0;
1235 return ret;
1238 static int strstart(const char *val, const char **str)
1240 const char *p, *q;
1241 p = *str;
1242 q = val;
1243 while (*q) {
1244 if (*p != *q)
1245 return 0;
1246 p++;
1247 q++;
1249 *str = p;
1250 return 1;
1253 /* Like strstart, but automatically takes into account that ld options can
1255 * - start with double or single dash (e.g. '--soname' or '-soname')
1256 * - arguments can be given as separate or after '=' (e.g. '-Wl,-soname,x.so'
1257 * or '-Wl,-soname=x.so')
1259 * you provide `val` always in 'option[=]' form (no leading -)
1261 static int link_option(const char *str, const char *val, const char **ptr)
1263 const char *p, *q;
1264 int ret;
1266 /* there should be 1 or 2 dashes */
1267 if (*str++ != '-')
1268 return 0;
1269 if (*str == '-')
1270 str++;
1272 /* then str & val should match (potentially up to '=') */
1273 p = str;
1274 q = val;
1276 ret = 1;
1277 if (q[0] == '?') {
1278 ++q;
1279 if (no_flag(&p))
1280 ret = -1;
1283 while (*q != '\0' && *q != '=') {
1284 if (*p != *q)
1285 return 0;
1286 p++;
1287 q++;
1290 /* '=' near eos means ',' or '=' is ok */
1291 if (*q == '=') {
1292 if (*p == 0)
1293 *ptr = p;
1294 if (*p != ',' && *p != '=')
1295 return 0;
1296 p++;
1297 } else if (*p) {
1298 return 0;
1300 *ptr = p;
1301 return ret;
1304 static const char *skip_linker_arg(const char **str)
1306 const char *s1 = *str;
1307 const char *s2 = strchr(s1, ',');
1308 *str = s2 ? s2++ : (s2 = s1 + strlen(s1));
1309 return s2;
1312 static void copy_linker_arg(char **pp, const char *s, int sep)
1314 const char *q = s;
1315 char *p = *pp;
1316 int l = 0;
1317 if (p && sep)
1318 p[l = strlen(p)] = sep, ++l;
1319 skip_linker_arg(&q);
1320 pstrncpy(l + (*pp = tcc_realloc(p, q - s + l + 1)), s, q - s);
1323 /* set linker options */
1324 static int tcc_set_linker(TCCState *s, const char *option)
1326 while (*option) {
1328 const char *p = NULL;
1329 char *end = NULL;
1330 int ignoring = 0;
1331 int ret;
1333 if (link_option(option, "Bsymbolic", &p)) {
1334 s->symbolic = 1;
1335 } else if (link_option(option, "nostdlib", &p)) {
1336 s->nostdlib = 1;
1337 } else if (link_option(option, "fini=", &p)) {
1338 copy_linker_arg(&s->fini_symbol, p, 0);
1339 ignoring = 1;
1340 } else if (link_option(option, "image-base=", &p)
1341 || link_option(option, "Ttext=", &p)) {
1342 s->text_addr = strtoull(p, &end, 16);
1343 s->has_text_addr = 1;
1344 } else if (link_option(option, "init=", &p)) {
1345 copy_linker_arg(&s->init_symbol, p, 0);
1346 ignoring = 1;
1347 } else if (link_option(option, "oformat=", &p)) {
1348 #if defined(TCC_TARGET_PE)
1349 if (strstart("pe-", &p)) {
1350 #elif PTR_SIZE == 8
1351 if (strstart("elf64-", &p)) {
1352 #else
1353 if (strstart("elf32-", &p)) {
1354 #endif
1355 s->output_format = TCC_OUTPUT_FORMAT_ELF;
1356 } else if (!strcmp(p, "binary")) {
1357 s->output_format = TCC_OUTPUT_FORMAT_BINARY;
1358 #ifdef TCC_TARGET_COFF
1359 } else if (!strcmp(p, "coff")) {
1360 s->output_format = TCC_OUTPUT_FORMAT_COFF;
1361 #endif
1362 } else
1363 goto err;
1365 } else if (link_option(option, "as-needed", &p)) {
1366 ignoring = 1;
1367 } else if (link_option(option, "O", &p)) {
1368 ignoring = 1;
1369 } else if (link_option(option, "export-all-symbols", &p)) {
1370 s->rdynamic = 1;
1371 } else if (link_option(option, "rpath=", &p)) {
1372 copy_linker_arg(&s->rpath, p, ':');
1373 } else if (link_option(option, "enable-new-dtags", &p)) {
1374 s->enable_new_dtags = 1;
1375 } else if (link_option(option, "section-alignment=", &p)) {
1376 s->section_align = strtoul(p, &end, 16);
1377 } else if (link_option(option, "soname=", &p)) {
1378 copy_linker_arg(&s->soname, p, 0);
1379 #ifdef TCC_TARGET_PE
1380 } else if (link_option(option, "large-address-aware", &p)) {
1381 s->pe_characteristics |= 0x20;
1382 } else if (link_option(option, "file-alignment=", &p)) {
1383 s->pe_file_align = strtoul(p, &end, 16);
1384 } else if (link_option(option, "stack=", &p)) {
1385 s->pe_stack_size = strtoul(p, &end, 10);
1386 } else if (link_option(option, "subsystem=", &p)) {
1387 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
1388 if (!strcmp(p, "native")) {
1389 s->pe_subsystem = 1;
1390 } else if (!strcmp(p, "console")) {
1391 s->pe_subsystem = 3;
1392 } else if (!strcmp(p, "gui") || !strcmp(p, "windows")) {
1393 s->pe_subsystem = 2;
1394 } else if (!strcmp(p, "posix")) {
1395 s->pe_subsystem = 7;
1396 } else if (!strcmp(p, "efiapp")) {
1397 s->pe_subsystem = 10;
1398 } else if (!strcmp(p, "efiboot")) {
1399 s->pe_subsystem = 11;
1400 } else if (!strcmp(p, "efiruntime")) {
1401 s->pe_subsystem = 12;
1402 } else if (!strcmp(p, "efirom")) {
1403 s->pe_subsystem = 13;
1404 #elif defined(TCC_TARGET_ARM)
1405 if (!strcmp(p, "wince")) {
1406 s->pe_subsystem = 9;
1407 #endif
1408 } else
1409 goto err;
1410 #endif
1411 } else if (ret = link_option(option, "?whole-archive", &p), ret) {
1412 s->alacarte_link = ret < 0;
1413 } else if (p) {
1414 return 0;
1415 } else {
1416 err:
1417 tcc_error("unsupported linker option '%s'", option);
1420 if (ignoring && s->warn_unsupported)
1421 tcc_warning("unsupported linker option '%s'", option);
1423 option = skip_linker_arg(&p);
1425 return 1;
1428 typedef struct TCCOption {
1429 const char *name;
1430 uint16_t index;
1431 uint16_t flags;
1432 } TCCOption;
1434 enum {
1435 TCC_OPTION_HELP,
1436 TCC_OPTION_HELP2,
1437 TCC_OPTION_v,
1438 TCC_OPTION_I,
1439 TCC_OPTION_D,
1440 TCC_OPTION_U,
1441 TCC_OPTION_P,
1442 TCC_OPTION_L,
1443 TCC_OPTION_B,
1444 TCC_OPTION_l,
1445 TCC_OPTION_bench,
1446 TCC_OPTION_bt,
1447 TCC_OPTION_b,
1448 TCC_OPTION_g,
1449 TCC_OPTION_c,
1450 TCC_OPTION_dumpversion,
1451 TCC_OPTION_d,
1452 TCC_OPTION_static,
1453 TCC_OPTION_std,
1454 TCC_OPTION_shared,
1455 TCC_OPTION_soname,
1456 TCC_OPTION_o,
1457 TCC_OPTION_r,
1458 TCC_OPTION_s,
1459 TCC_OPTION_traditional,
1460 TCC_OPTION_Wl,
1461 TCC_OPTION_Wp,
1462 TCC_OPTION_W,
1463 TCC_OPTION_O,
1464 TCC_OPTION_mfloat_abi,
1465 TCC_OPTION_m,
1466 TCC_OPTION_f,
1467 TCC_OPTION_isystem,
1468 TCC_OPTION_iwithprefix,
1469 TCC_OPTION_include,
1470 TCC_OPTION_nostdinc,
1471 TCC_OPTION_nostdlib,
1472 TCC_OPTION_print_search_dirs,
1473 TCC_OPTION_rdynamic,
1474 TCC_OPTION_param,
1475 TCC_OPTION_pedantic,
1476 TCC_OPTION_pthread,
1477 TCC_OPTION_run,
1478 TCC_OPTION_w,
1479 TCC_OPTION_pipe,
1480 TCC_OPTION_E,
1481 TCC_OPTION_MD,
1482 TCC_OPTION_MF,
1483 TCC_OPTION_x,
1484 TCC_OPTION_ar,
1485 TCC_OPTION_impdef
1488 #define TCC_OPTION_HAS_ARG 0x0001
1489 #define TCC_OPTION_NOSEP 0x0002 /* cannot have space before option and arg */
1491 static const TCCOption tcc_options[] = {
1492 { "h", TCC_OPTION_HELP, 0 },
1493 { "-help", TCC_OPTION_HELP, 0 },
1494 { "?", TCC_OPTION_HELP, 0 },
1495 { "hh", TCC_OPTION_HELP2, 0 },
1496 { "v", TCC_OPTION_v, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1497 { "I", TCC_OPTION_I, TCC_OPTION_HAS_ARG },
1498 { "D", TCC_OPTION_D, TCC_OPTION_HAS_ARG },
1499 { "U", TCC_OPTION_U, TCC_OPTION_HAS_ARG },
1500 { "P", TCC_OPTION_P, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1501 { "L", TCC_OPTION_L, TCC_OPTION_HAS_ARG },
1502 { "B", TCC_OPTION_B, TCC_OPTION_HAS_ARG },
1503 { "l", TCC_OPTION_l, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1504 { "bench", TCC_OPTION_bench, 0 },
1505 #ifdef CONFIG_TCC_BACKTRACE
1506 { "bt", TCC_OPTION_bt, TCC_OPTION_HAS_ARG },
1507 #endif
1508 #ifdef CONFIG_TCC_BCHECK
1509 { "b", TCC_OPTION_b, 0 },
1510 #endif
1511 { "g", TCC_OPTION_g, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1512 { "c", TCC_OPTION_c, 0 },
1513 { "dumpversion", TCC_OPTION_dumpversion, 0},
1514 { "d", TCC_OPTION_d, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1515 { "static", TCC_OPTION_static, 0 },
1516 { "std", TCC_OPTION_std, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1517 { "shared", TCC_OPTION_shared, 0 },
1518 { "soname", TCC_OPTION_soname, TCC_OPTION_HAS_ARG },
1519 { "o", TCC_OPTION_o, TCC_OPTION_HAS_ARG },
1520 { "-param", TCC_OPTION_param, TCC_OPTION_HAS_ARG },
1521 { "pedantic", TCC_OPTION_pedantic, 0},
1522 { "pthread", TCC_OPTION_pthread, 0},
1523 { "run", TCC_OPTION_run, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1524 { "rdynamic", TCC_OPTION_rdynamic, 0 },
1525 { "r", TCC_OPTION_r, 0 },
1526 { "s", TCC_OPTION_s, 0 },
1527 { "traditional", TCC_OPTION_traditional, 0 },
1528 { "Wl,", TCC_OPTION_Wl, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1529 { "Wp,", TCC_OPTION_Wp, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1530 { "W", TCC_OPTION_W, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1531 { "O", TCC_OPTION_O, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1532 #ifdef TCC_TARGET_ARM
1533 { "mfloat-abi", TCC_OPTION_mfloat_abi, TCC_OPTION_HAS_ARG },
1534 #endif
1535 { "m", TCC_OPTION_m, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1536 { "f", TCC_OPTION_f, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1537 { "isystem", TCC_OPTION_isystem, TCC_OPTION_HAS_ARG },
1538 { "iwithprefix", TCC_OPTION_iwithprefix, TCC_OPTION_HAS_ARG },
1539 { "include", TCC_OPTION_include, TCC_OPTION_HAS_ARG },
1540 { "nostdinc", TCC_OPTION_nostdinc, 0 },
1541 { "nostdlib", TCC_OPTION_nostdlib, 0 },
1542 { "print-search-dirs", TCC_OPTION_print_search_dirs, 0 },
1543 { "w", TCC_OPTION_w, 0 },
1544 { "pipe", TCC_OPTION_pipe, 0},
1545 { "E", TCC_OPTION_E, 0},
1546 { "MD", TCC_OPTION_MD, 0},
1547 { "MF", TCC_OPTION_MF, TCC_OPTION_HAS_ARG },
1548 { "x", TCC_OPTION_x, TCC_OPTION_HAS_ARG },
1549 { "ar", TCC_OPTION_ar, 0},
1550 #ifdef TCC_TARGET_PE
1551 { "impdef", TCC_OPTION_impdef, 0},
1552 #endif
1553 { NULL, 0, 0 },
1556 static const FlagDef options_W[] = {
1557 { 0, 0, "all" },
1558 { offsetof(TCCState, warn_unsupported), 0, "unsupported" },
1559 { offsetof(TCCState, warn_write_strings), 0, "write-strings" },
1560 { offsetof(TCCState, warn_error), 0, "error" },
1561 { offsetof(TCCState, warn_gcc_compat), 0, "gcc-compat" },
1562 { offsetof(TCCState, warn_implicit_function_declaration), WD_ALL,
1563 "implicit-function-declaration" },
1564 { 0, 0, NULL }
1567 static const FlagDef options_f[] = {
1568 { offsetof(TCCState, char_is_unsigned), 0, "unsigned-char" },
1569 { offsetof(TCCState, char_is_unsigned), FD_INVERT, "signed-char" },
1570 { offsetof(TCCState, nocommon), FD_INVERT, "common" },
1571 { offsetof(TCCState, leading_underscore), 0, "leading-underscore" },
1572 { offsetof(TCCState, ms_extensions), 0, "ms-extensions" },
1573 { offsetof(TCCState, dollars_in_identifiers), 0, "dollars-in-identifiers" },
1574 { 0, 0, NULL }
1577 static const FlagDef options_m[] = {
1578 { offsetof(TCCState, ms_bitfields), 0, "ms-bitfields" },
1579 #ifdef TCC_TARGET_X86_64
1580 { offsetof(TCCState, nosse), FD_INVERT, "sse" },
1581 #endif
1582 { 0, 0, NULL }
1585 static void parse_option_D(TCCState *s1, const char *optarg)
1587 char *sym = tcc_strdup(optarg);
1588 char *value = strchr(sym, '=');
1589 if (value)
1590 *value++ = '\0';
1591 tcc_define_symbol(s1, sym, value);
1592 tcc_free(sym);
1595 static void args_parser_add_file(TCCState *s, const char* filename, int filetype)
1597 struct filespec *f = tcc_malloc(sizeof *f + strlen(filename));
1598 f->type = filetype;
1599 f->alacarte = s->alacarte_link;
1600 strcpy(f->name, filename);
1601 dynarray_add(&s->files, &s->nb_files, f);
1604 static int args_parser_make_argv(const char *r, int *argc, char ***argv)
1606 int ret = 0, q, c;
1607 CString str;
1608 for(;;) {
1609 while (c = (unsigned char)*r, c && c <= ' ')
1610 ++r;
1611 if (c == 0)
1612 break;
1613 q = 0;
1614 cstr_new(&str);
1615 while (c = (unsigned char)*r, c) {
1616 ++r;
1617 if (c == '\\' && (*r == '"' || *r == '\\')) {
1618 c = *r++;
1619 } else if (c == '"') {
1620 q = !q;
1621 continue;
1622 } else if (q == 0 && c <= ' ') {
1623 break;
1625 cstr_ccat(&str, c);
1627 cstr_ccat(&str, 0);
1628 //printf("<%s>\n", str.data), fflush(stdout);
1629 dynarray_add(argv, argc, tcc_strdup(str.data));
1630 cstr_free(&str);
1631 ++ret;
1633 return ret;
1636 /* read list file */
1637 static void args_parser_listfile(TCCState *s,
1638 const char *filename, int optind, int *pargc, char ***pargv)
1640 int fd, i;
1641 size_t len;
1642 char *p;
1643 int argc = 0;
1644 char **argv = NULL;
1646 fd = open(filename, O_RDONLY | O_BINARY);
1647 if (fd < 0)
1648 tcc_error("listfile '%s' not found", filename);
1650 len = lseek(fd, 0, SEEK_END);
1651 p = tcc_malloc(len + 1), p[len] = 0;
1652 lseek(fd, 0, SEEK_SET), read(fd, p, len), close(fd);
1654 for (i = 0; i < *pargc; ++i)
1655 if (i == optind)
1656 args_parser_make_argv(p, &argc, &argv);
1657 else
1658 dynarray_add(&argv, &argc, tcc_strdup((*pargv)[i]));
1660 tcc_free(p);
1661 dynarray_reset(&s->argv, &s->argc);
1662 *pargc = s->argc = argc, *pargv = s->argv = argv;
1665 PUB_FUNC int tcc_parse_args(TCCState *s, int *pargc, char ***pargv, int optind)
1667 const TCCOption *popt;
1668 const char *optarg, *r;
1669 const char *run = NULL;
1670 int last_o = -1;
1671 int x;
1672 CString linker_arg; /* collect -Wl options */
1673 char buf[1024];
1674 int tool = 0, arg_start = 0, noaction = optind;
1675 char **argv = *pargv;
1676 int argc = *pargc;
1678 cstr_new(&linker_arg);
1680 while (optind < argc) {
1681 r = argv[optind];
1682 if (r[0] == '@' && r[1] != '\0') {
1683 args_parser_listfile(s, r + 1, optind, &argc, &argv);
1684 continue;
1686 optind++;
1687 if (tool) {
1688 if (r[0] == '-' && r[1] == 'v' && r[2] == 0)
1689 ++s->verbose;
1690 continue;
1692 reparse:
1693 if (r[0] != '-' || r[1] == '\0') {
1694 if (r[0] != '@') /* allow "tcc file(s) -run @ args ..." */
1695 args_parser_add_file(s, r, s->filetype);
1696 if (run) {
1697 tcc_set_options(s, run);
1698 arg_start = optind - 1;
1699 break;
1701 continue;
1704 /* find option in table */
1705 for(popt = tcc_options; ; ++popt) {
1706 const char *p1 = popt->name;
1707 const char *r1 = r + 1;
1708 if (p1 == NULL)
1709 tcc_error("invalid option -- '%s'", r);
1710 if (!strstart(p1, &r1))
1711 continue;
1712 optarg = r1;
1713 if (popt->flags & TCC_OPTION_HAS_ARG) {
1714 if (*r1 == '\0' && !(popt->flags & TCC_OPTION_NOSEP)) {
1715 if (optind >= argc)
1716 arg_err:
1717 tcc_error("argument to '%s' is missing", r);
1718 optarg = argv[optind++];
1720 } else if (*r1 != '\0')
1721 continue;
1722 break;
1725 switch(popt->index) {
1726 case TCC_OPTION_HELP:
1727 return OPT_HELP;
1728 case TCC_OPTION_HELP2:
1729 return OPT_HELP2;
1730 case TCC_OPTION_I:
1731 tcc_add_include_path(s, optarg);
1732 break;
1733 case TCC_OPTION_D:
1734 parse_option_D(s, optarg);
1735 break;
1736 case TCC_OPTION_U:
1737 tcc_undefine_symbol(s, optarg);
1738 break;
1739 case TCC_OPTION_L:
1740 tcc_add_library_path(s, optarg);
1741 break;
1742 case TCC_OPTION_B:
1743 /* set tcc utilities path (mainly for tcc development) */
1744 tcc_set_lib_path(s, optarg);
1745 break;
1746 case TCC_OPTION_l:
1747 args_parser_add_file(s, optarg, AFF_TYPE_LIB);
1748 s->nb_libraries++;
1749 break;
1750 case TCC_OPTION_pthread:
1751 parse_option_D(s, "_REENTRANT");
1752 s->option_pthread = 1;
1753 break;
1754 case TCC_OPTION_bench:
1755 s->do_bench = 1;
1756 break;
1757 #ifdef CONFIG_TCC_BACKTRACE
1758 case TCC_OPTION_bt:
1759 tcc_set_num_callers(atoi(optarg));
1760 break;
1761 #endif
1762 #ifdef CONFIG_TCC_BCHECK
1763 case TCC_OPTION_b:
1764 s->do_bounds_check = 1;
1765 s->do_debug = 1;
1766 break;
1767 #endif
1768 case TCC_OPTION_g:
1769 s->do_debug = 1;
1770 break;
1771 case TCC_OPTION_c:
1772 x = TCC_OUTPUT_OBJ;
1773 set_output_type:
1774 if (s->output_type)
1775 tcc_warning("-%s: overriding compiler action already specified", popt->name);
1776 s->output_type = x;
1777 break;
1778 case TCC_OPTION_d:
1779 if (*optarg == 'D')
1780 s->dflag = 3;
1781 else if (*optarg == 'M')
1782 s->dflag = 7;
1783 else if (*optarg == 't')
1784 s->dflag = 16;
1785 else if (isnum(*optarg))
1786 g_debug = atoi(optarg);
1787 else
1788 goto unsupported_option;
1789 break;
1790 case TCC_OPTION_static:
1791 s->static_link = 1;
1792 break;
1793 case TCC_OPTION_std:
1794 /* silently ignore, a current purpose:
1795 allow to use a tcc as a reference compiler for "make test" */
1796 break;
1797 case TCC_OPTION_shared:
1798 x = TCC_OUTPUT_DLL;
1799 goto set_output_type;
1800 case TCC_OPTION_soname:
1801 s->soname = tcc_strdup(optarg);
1802 break;
1803 case TCC_OPTION_o:
1804 if (s->outfile) {
1805 tcc_warning("multiple -o option");
1806 tcc_free(s->outfile);
1808 s->outfile = tcc_strdup(optarg);
1809 break;
1810 case TCC_OPTION_r:
1811 /* generate a .o merging several output files */
1812 s->option_r = 1;
1813 x = TCC_OUTPUT_OBJ;
1814 goto set_output_type;
1815 case TCC_OPTION_isystem:
1816 tcc_add_sysinclude_path(s, optarg);
1817 break;
1818 case TCC_OPTION_iwithprefix:
1819 snprintf(buf, sizeof buf, "{B}/%s", optarg);
1820 tcc_add_sysinclude_path(s, buf);
1821 break;
1822 case TCC_OPTION_include:
1823 dynarray_add(&s->cmd_include_files,
1824 &s->nb_cmd_include_files, tcc_strdup(optarg));
1825 break;
1826 case TCC_OPTION_nostdinc:
1827 s->nostdinc = 1;
1828 break;
1829 case TCC_OPTION_nostdlib:
1830 s->nostdlib = 1;
1831 break;
1832 case TCC_OPTION_run:
1833 #ifndef TCC_IS_NATIVE
1834 tcc_error("-run is not available in a cross compiler");
1835 #endif
1836 run = optarg;
1837 x = TCC_OUTPUT_MEMORY;
1838 goto set_output_type;
1839 case TCC_OPTION_v:
1840 do ++s->verbose; while (*optarg++ == 'v');
1841 ++noaction;
1842 break;
1843 case TCC_OPTION_f:
1844 if (set_flag(s, options_f, optarg) < 0)
1845 goto unsupported_option;
1846 break;
1847 #ifdef TCC_TARGET_ARM
1848 case TCC_OPTION_mfloat_abi:
1849 /* tcc doesn't support soft float yet */
1850 if (!strcmp(optarg, "softfp")) {
1851 s->float_abi = ARM_SOFTFP_FLOAT;
1852 tcc_undefine_symbol(s, "__ARM_PCS_VFP");
1853 } else if (!strcmp(optarg, "hard"))
1854 s->float_abi = ARM_HARD_FLOAT;
1855 else
1856 tcc_error("unsupported float abi '%s'", optarg);
1857 break;
1858 #endif
1859 case TCC_OPTION_m:
1860 if (set_flag(s, options_m, optarg) < 0) {
1861 if (x = atoi(optarg), x != 32 && x != 64)
1862 goto unsupported_option;
1863 if (PTR_SIZE != x/8)
1864 return x;
1865 ++noaction;
1867 break;
1868 case TCC_OPTION_W:
1869 if (set_flag(s, options_W, optarg) < 0)
1870 goto unsupported_option;
1871 break;
1872 case TCC_OPTION_w:
1873 s->warn_none = 1;
1874 break;
1875 case TCC_OPTION_rdynamic:
1876 s->rdynamic = 1;
1877 break;
1878 case TCC_OPTION_Wl:
1879 if (linker_arg.size)
1880 --linker_arg.size, cstr_ccat(&linker_arg, ',');
1881 cstr_cat(&linker_arg, optarg, 0);
1882 if (tcc_set_linker(s, linker_arg.data))
1883 cstr_free(&linker_arg);
1884 break;
1885 case TCC_OPTION_Wp:
1886 r = optarg;
1887 goto reparse;
1888 case TCC_OPTION_E:
1889 x = TCC_OUTPUT_PREPROCESS;
1890 goto set_output_type;
1891 case TCC_OPTION_P:
1892 s->Pflag = atoi(optarg) + 1;
1893 break;
1894 case TCC_OPTION_MD:
1895 s->gen_deps = 1;
1896 break;
1897 case TCC_OPTION_MF:
1898 s->deps_outfile = tcc_strdup(optarg);
1899 break;
1900 case TCC_OPTION_dumpversion:
1901 printf ("%s\n", TCC_VERSION);
1902 exit(0);
1903 break;
1904 case TCC_OPTION_x:
1905 if (*optarg == 'c')
1906 s->filetype = AFF_TYPE_C;
1907 else if (*optarg == 'a')
1908 s->filetype = AFF_TYPE_ASMPP;
1909 else if (*optarg == 'n')
1910 s->filetype = AFF_TYPE_NONE;
1911 else
1912 tcc_warning("unsupported language '%s'", optarg);
1913 break;
1914 case TCC_OPTION_O:
1915 last_o = atoi(optarg);
1916 break;
1917 case TCC_OPTION_print_search_dirs:
1918 x = OPT_PRINT_DIRS;
1919 goto extra_action;
1920 case TCC_OPTION_impdef:
1921 x = OPT_IMPDEF;
1922 goto extra_action;
1923 case TCC_OPTION_ar:
1924 x = OPT_AR;
1925 extra_action:
1926 arg_start = optind - 1;
1927 if (arg_start != noaction)
1928 tcc_error("cannot parse %s here", r);
1929 tool = x;
1930 break;
1931 case TCC_OPTION_traditional:
1932 case TCC_OPTION_pedantic:
1933 case TCC_OPTION_pipe:
1934 case TCC_OPTION_s:
1935 /* ignored */
1936 break;
1937 default:
1938 unsupported_option:
1939 if (s->warn_unsupported)
1940 tcc_warning("unsupported option '%s'", r);
1941 break;
1944 if (last_o > 0)
1945 tcc_define_symbol(s, "__OPTIMIZE__", NULL);
1946 if (linker_arg.size) {
1947 r = linker_arg.data;
1948 goto arg_err;
1950 *pargc = argc - arg_start;
1951 *pargv = argv + arg_start;
1952 if (tool)
1953 return tool;
1954 if (optind != noaction)
1955 return 0;
1956 if (s->verbose == 2)
1957 return OPT_PRINT_DIRS;
1958 if (s->verbose)
1959 return OPT_V;
1960 return OPT_HELP;
1963 LIBTCCAPI void tcc_set_options(TCCState *s, const char *r)
1965 char **argv = NULL;
1966 int argc = 0;
1967 args_parser_make_argv(r, &argc, &argv);
1968 tcc_parse_args(s, &argc, &argv, 0);
1969 dynarray_reset(&argv, &argc);
1972 PUB_FUNC void tcc_print_stats(TCCState *s, unsigned total_time)
1974 if (total_time < 1)
1975 total_time = 1;
1976 if (total_bytes < 1)
1977 total_bytes = 1;
1978 fprintf(stderr, "* %d idents, %d lines, %d bytes\n"
1979 "* %0.3f s, %u lines/s, %0.1f MB/s\n",
1980 tok_ident - TOK_IDENT, total_lines, total_bytes,
1981 (double)total_time/1000,
1982 (unsigned)total_lines*1000/total_time,
1983 (double)total_bytes/1000/total_time);
1984 #ifdef MEM_DEBUG
1985 fprintf(stderr, "* %d bytes memory used\n", mem_max_size);
1986 #endif