tccgen.c: cleanup debug support
[tinycc.git] / libtcc.c
blobfb52ad1995d2f5f017ef9ecb95b3c003da04e01a
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 #if !defined ONE_SOURCE || ONE_SOURCE
22 #include "tccpp.c"
23 #include "tccgen.c"
24 #include "tccelf.c"
25 #include "tccrun.c"
26 #ifdef TCC_TARGET_I386
27 #include "i386-gen.c"
28 #include "i386-link.c"
29 #include "i386-asm.c"
30 #elif defined(TCC_TARGET_ARM)
31 #include "arm-gen.c"
32 #include "arm-link.c"
33 #include "arm-asm.c"
34 #elif defined(TCC_TARGET_ARM64)
35 #include "arm64-gen.c"
36 #include "arm64-link.c"
37 #elif defined(TCC_TARGET_C67)
38 #include "c67-gen.c"
39 #include "c67-link.c"
40 #include "tcccoff.c"
41 #elif defined(TCC_TARGET_X86_64)
42 #include "x86_64-gen.c"
43 #include "x86_64-link.c"
44 #include "i386-asm.c"
45 #elif defined(TCC_TARGET_RISCV64)
46 #include "riscv64-gen.c"
47 #include "riscv64-link.c"
48 #else
49 #error unknown target
50 #endif
51 #ifdef CONFIG_TCC_ASM
52 #include "tccasm.c"
53 #endif
54 #ifdef TCC_TARGET_PE
55 #include "tccpe.c"
56 #endif
57 #endif /* ONE_SOURCE */
59 #include "tcc.h"
61 /********************************************************/
62 /* global variables */
64 /* XXX: get rid of this ASAP (or maybe not) */
65 ST_DATA struct TCCState *tcc_state;
67 #ifdef MEM_DEBUG
68 static int nb_states;
69 #endif
71 /********************************************************/
72 #ifdef _WIN32
73 ST_FUNC char *normalize_slashes(char *path)
75 char *p;
76 for (p = path; *p; ++p)
77 if (*p == '\\')
78 *p = '/';
79 return path;
82 static HMODULE tcc_module;
84 /* on win32, we suppose the lib and includes are at the location of 'tcc.exe' */
85 static void tcc_set_lib_path_w32(TCCState *s)
87 char path[1024], *p;
88 GetModuleFileNameA(tcc_module, path, sizeof path);
89 p = tcc_basename(normalize_slashes(strlwr(path)));
90 if (p > path)
91 --p;
92 *p = 0;
93 tcc_set_lib_path(s, path);
96 #ifdef TCC_TARGET_PE
97 static void tcc_add_systemdir(TCCState *s)
99 char buf[1000];
100 GetSystemDirectory(buf, sizeof buf);
101 tcc_add_library_path(s, normalize_slashes(buf));
103 #endif
105 #ifdef LIBTCC_AS_DLL
106 BOOL WINAPI DllMain (HINSTANCE hDll, DWORD dwReason, LPVOID lpReserved)
108 if (DLL_PROCESS_ATTACH == dwReason)
109 tcc_module = hDll;
110 return TRUE;
112 #endif
113 #endif
115 /********************************************************/
116 #ifndef CONFIG_TCC_SEMLOCK
117 #define WAIT_SEM()
118 #define POST_SEM()
119 #elif defined _WIN32
120 static int tcc_sem_init;
121 static CRITICAL_SECTION tcc_cr;
122 static void wait_sem(void)
124 if (!tcc_sem_init)
125 InitializeCriticalSection(&tcc_cr), tcc_sem_init = 1;
126 EnterCriticalSection(&tcc_cr);
128 #define WAIT_SEM() wait_sem()
129 #define POST_SEM() LeaveCriticalSection(&tcc_cr);
130 #else
131 #include <semaphore.h>
132 static int tcc_sem_init;
133 static sem_t tcc_sem;
134 static void wait_sem(void)
136 if (!tcc_sem_init)
137 sem_init(&tcc_sem, 0, 1), tcc_sem_init = 1;
138 while (sem_wait (&tcc_sem) < 0 && errno == EINTR);
140 #define WAIT_SEM() wait_sem()
141 #define POST_SEM() sem_post(&tcc_sem)
142 #endif
144 /********************************************************/
145 /* copy a string and truncate it. */
146 ST_FUNC char *pstrcpy(char *buf, size_t buf_size, const char *s)
148 char *q, *q_end;
149 int c;
151 if (buf_size > 0) {
152 q = buf;
153 q_end = buf + buf_size - 1;
154 while (q < q_end) {
155 c = *s++;
156 if (c == '\0')
157 break;
158 *q++ = c;
160 *q = '\0';
162 return buf;
165 /* strcat and truncate. */
166 ST_FUNC char *pstrcat(char *buf, size_t buf_size, const char *s)
168 size_t len;
169 len = strlen(buf);
170 if (len < buf_size)
171 pstrcpy(buf + len, buf_size - len, s);
172 return buf;
175 ST_FUNC char *pstrncpy(char *out, const char *in, size_t num)
177 memcpy(out, in, num);
178 out[num] = '\0';
179 return out;
182 /* extract the basename of a file */
183 PUB_FUNC char *tcc_basename(const char *name)
185 char *p = strchr(name, 0);
186 while (p > name && !IS_DIRSEP(p[-1]))
187 --p;
188 return p;
191 /* extract extension part of a file
193 * (if no extension, return pointer to end-of-string)
195 PUB_FUNC char *tcc_fileextension (const char *name)
197 char *b = tcc_basename(name);
198 char *e = strrchr(b, '.');
199 return e ? e : strchr(b, 0);
202 /********************************************************/
203 /* memory management */
205 #undef free
206 #undef malloc
207 #undef realloc
209 #ifndef MEM_DEBUG
211 PUB_FUNC void tcc_free(void *ptr)
213 free(ptr);
216 PUB_FUNC void *tcc_malloc(unsigned long size)
218 void *ptr;
219 ptr = malloc(size);
220 if (!ptr && size)
221 _tcc_error("memory full (malloc)");
222 return ptr;
225 PUB_FUNC void *tcc_mallocz(unsigned long size)
227 void *ptr;
228 ptr = tcc_malloc(size);
229 memset(ptr, 0, size);
230 return ptr;
233 PUB_FUNC void *tcc_realloc(void *ptr, unsigned long size)
235 void *ptr1;
236 ptr1 = realloc(ptr, size);
237 if (!ptr1 && size)
238 _tcc_error("memory full (realloc)");
239 return ptr1;
242 PUB_FUNC char *tcc_strdup(const char *str)
244 char *ptr;
245 ptr = tcc_malloc(strlen(str) + 1);
246 strcpy(ptr, str);
247 return ptr;
250 #else
252 #define MEM_DEBUG_MAGIC1 0xFEEDDEB1
253 #define MEM_DEBUG_MAGIC2 0xFEEDDEB2
254 #define MEM_DEBUG_MAGIC3 0xFEEDDEB3
255 #define MEM_DEBUG_FILE_LEN 40
256 #define MEM_DEBUG_CHECK3(header) \
257 ((mem_debug_header_t*)((char*)header + header->size))->magic3
258 #define MEM_USER_PTR(header) \
259 ((char *)header + offsetof(mem_debug_header_t, magic3))
260 #define MEM_HEADER_PTR(ptr) \
261 (mem_debug_header_t *)((char*)ptr - offsetof(mem_debug_header_t, magic3))
263 struct mem_debug_header {
264 unsigned magic1;
265 unsigned size;
266 struct mem_debug_header *prev;
267 struct mem_debug_header *next;
268 int line_num;
269 char file_name[MEM_DEBUG_FILE_LEN + 1];
270 unsigned magic2;
271 ALIGNED(16) unsigned magic3;
274 typedef struct mem_debug_header mem_debug_header_t;
276 static mem_debug_header_t *mem_debug_chain;
277 static unsigned mem_cur_size;
278 static unsigned mem_max_size;
280 static mem_debug_header_t *malloc_check(void *ptr, const char *msg)
282 mem_debug_header_t * header = MEM_HEADER_PTR(ptr);
283 if (header->magic1 != MEM_DEBUG_MAGIC1 ||
284 header->magic2 != MEM_DEBUG_MAGIC2 ||
285 MEM_DEBUG_CHECK3(header) != MEM_DEBUG_MAGIC3 ||
286 header->size == (unsigned)-1) {
287 fprintf(stderr, "%s check failed\n", msg);
288 if (header->magic1 == MEM_DEBUG_MAGIC1)
289 fprintf(stderr, "%s:%u: block allocated here.\n",
290 header->file_name, header->line_num);
291 exit(1);
293 return header;
296 PUB_FUNC void *tcc_malloc_debug(unsigned long size, const char *file, int line)
298 int ofs;
299 mem_debug_header_t *header;
301 header = malloc(sizeof(mem_debug_header_t) + size);
302 if (!header)
303 _tcc_error("memory full (malloc)");
305 header->magic1 = MEM_DEBUG_MAGIC1;
306 header->magic2 = MEM_DEBUG_MAGIC2;
307 header->size = size;
308 MEM_DEBUG_CHECK3(header) = MEM_DEBUG_MAGIC3;
309 header->line_num = line;
310 ofs = strlen(file) - MEM_DEBUG_FILE_LEN;
311 strncpy(header->file_name, file + (ofs > 0 ? ofs : 0), MEM_DEBUG_FILE_LEN);
312 header->file_name[MEM_DEBUG_FILE_LEN] = 0;
314 header->next = mem_debug_chain;
315 header->prev = NULL;
316 if (header->next)
317 header->next->prev = header;
318 mem_debug_chain = header;
320 mem_cur_size += size;
321 if (mem_cur_size > mem_max_size)
322 mem_max_size = mem_cur_size;
324 return MEM_USER_PTR(header);
327 PUB_FUNC void tcc_free_debug(void *ptr)
329 mem_debug_header_t *header;
330 if (!ptr)
331 return;
332 header = malloc_check(ptr, "tcc_free");
333 mem_cur_size -= header->size;
334 header->size = (unsigned)-1;
335 if (header->next)
336 header->next->prev = header->prev;
337 if (header->prev)
338 header->prev->next = header->next;
339 if (header == mem_debug_chain)
340 mem_debug_chain = header->next;
341 free(header);
344 PUB_FUNC void *tcc_mallocz_debug(unsigned long size, const char *file, int line)
346 void *ptr;
347 ptr = tcc_malloc_debug(size,file,line);
348 memset(ptr, 0, size);
349 return ptr;
352 PUB_FUNC void *tcc_realloc_debug(void *ptr, unsigned long size, const char *file, int line)
354 mem_debug_header_t *header;
355 int mem_debug_chain_update = 0;
356 if (!ptr)
357 return tcc_malloc_debug(size, file, line);
358 header = malloc_check(ptr, "tcc_realloc");
359 mem_cur_size -= header->size;
360 mem_debug_chain_update = (header == mem_debug_chain);
361 header = realloc(header, sizeof(mem_debug_header_t) + size);
362 if (!header)
363 _tcc_error("memory full (realloc)");
364 header->size = size;
365 MEM_DEBUG_CHECK3(header) = MEM_DEBUG_MAGIC3;
366 if (header->next)
367 header->next->prev = header;
368 if (header->prev)
369 header->prev->next = header;
370 if (mem_debug_chain_update)
371 mem_debug_chain = header;
372 mem_cur_size += size;
373 if (mem_cur_size > mem_max_size)
374 mem_max_size = mem_cur_size;
375 return MEM_USER_PTR(header);
378 PUB_FUNC char *tcc_strdup_debug(const char *str, const char *file, int line)
380 char *ptr;
381 ptr = tcc_malloc_debug(strlen(str) + 1, file, line);
382 strcpy(ptr, str);
383 return ptr;
386 PUB_FUNC void tcc_memcheck(void)
388 if (mem_cur_size) {
389 mem_debug_header_t *header = mem_debug_chain;
390 fprintf(stderr, "MEM_DEBUG: mem_leak= %d bytes, mem_max_size= %d bytes\n",
391 mem_cur_size, mem_max_size);
392 while (header) {
393 fprintf(stderr, "%s:%u: error: %u bytes leaked\n",
394 header->file_name, header->line_num, header->size);
395 header = header->next;
397 #if MEM_DEBUG-0 == 2
398 exit(2);
399 #endif
402 #endif /* MEM_DEBUG */
404 #define free(p) use_tcc_free(p)
405 #define malloc(s) use_tcc_malloc(s)
406 #define realloc(p, s) use_tcc_realloc(p, s)
408 /********************************************************/
409 /* dynarrays */
411 ST_FUNC void dynarray_add(void *ptab, int *nb_ptr, void *data)
413 int nb, nb_alloc;
414 void **pp;
416 nb = *nb_ptr;
417 pp = *(void ***)ptab;
418 /* every power of two we double array size */
419 if ((nb & (nb - 1)) == 0) {
420 if (!nb)
421 nb_alloc = 1;
422 else
423 nb_alloc = nb * 2;
424 pp = tcc_realloc(pp, nb_alloc * sizeof(void *));
425 *(void***)ptab = pp;
427 pp[nb++] = data;
428 *nb_ptr = nb;
431 ST_FUNC void dynarray_reset(void *pp, int *n)
433 void **p;
434 for (p = *(void***)pp; *n; ++p, --*n)
435 if (*p)
436 tcc_free(*p);
437 tcc_free(*(void**)pp);
438 *(void**)pp = NULL;
441 static void tcc_split_path(TCCState *s, void *p_ary, int *p_nb_ary, const char *in)
443 const char *p;
444 do {
445 int c;
446 CString str;
448 cstr_new(&str);
449 for (p = in; c = *p, c != '\0' && c != PATHSEP[0]; ++p) {
450 if (c == '{' && p[1] && p[2] == '}') {
451 c = p[1], p += 2;
452 if (c == 'B')
453 cstr_cat(&str, s->tcc_lib_path, -1);
454 if (c == 'f' && file) {
455 /* substitute current file's dir */
456 const char *f = file->true_filename;
457 const char *b = tcc_basename(f);
458 if (b > f)
459 cstr_cat(&str, f, b - f - 1);
460 else
461 cstr_cat(&str, ".", 1);
463 } else {
464 cstr_ccat(&str, c);
467 if (str.size) {
468 cstr_ccat(&str, '\0');
469 dynarray_add(p_ary, p_nb_ary, tcc_strdup(str.data));
471 cstr_free(&str);
472 in = p+1;
473 } while (*p);
476 /********************************************************/
478 static void strcat_vprintf(char *buf, int buf_size, const char *fmt, va_list ap)
480 int len;
481 len = strlen(buf);
482 vsnprintf(buf + len, buf_size - len, fmt, ap);
485 static void strcat_printf(char *buf, int buf_size, const char *fmt, ...)
487 va_list ap;
488 va_start(ap, fmt);
489 strcat_vprintf(buf, buf_size, fmt, ap);
490 va_end(ap);
493 #define ERROR_WARN 0
494 #define ERROR_NOABORT 1
495 #define ERROR_ERROR 2
497 PUB_FUNC void tcc_enter_state(TCCState *s1)
499 WAIT_SEM();
500 tcc_state = s1;
503 static void error1(int mode, const char *fmt, va_list ap)
505 char buf[2048];
506 BufferedFile **pf, *f;
507 TCCState *s1 = tcc_state;
509 /* 's1->error_set_jmp_enabled' means that we're called from
510 within the parser/generator and 'tcc_state' was already
511 set (i.e. not by the function above).
513 Otherwise, 's1 = NULL' means we're called because of severe
514 problems from tcc_malloc() which under normal conditions
515 should never happen. */
517 if (s1 && !s1->error_set_jmp_enabled) {
518 tcc_state = NULL;
519 POST_SEM();
522 if (mode == ERROR_WARN) {
523 if (s1->warn_none)
524 return;
525 if (s1->warn_error)
526 mode = ERROR_ERROR;
529 buf[0] = '\0';
530 /* use upper file if inline ":asm:" or token ":paste:" */
531 for (f = file; f && f->filename[0] == ':'; f = f->prev)
533 if (f) {
534 for(pf = s1->include_stack; pf < s1->include_stack_ptr; pf++)
535 strcat_printf(buf, sizeof(buf), "In file included from %s:%d:\n",
536 (*pf)->filename, (*pf)->line_num);
537 if (s1->error_set_jmp_enabled) {
538 strcat_printf(buf, sizeof(buf), "%s:%d: ",
539 f->filename, f->line_num - !!(tok_flags & TOK_FLAG_BOL));
540 } else {
541 strcat_printf(buf, sizeof(buf), "%s: ",
542 f->filename);
544 } else {
545 strcat_printf(buf, sizeof(buf), "tcc: ");
547 if (mode == ERROR_WARN)
548 strcat_printf(buf, sizeof(buf), "warning: ");
549 else
550 strcat_printf(buf, sizeof(buf), "error: ");
551 strcat_vprintf(buf, sizeof(buf), fmt, ap);
552 if (!s1 || !s1->error_func) {
553 /* default case: stderr */
554 if (s1 && s1->output_type == TCC_OUTPUT_PREPROCESS && s1->ppfp == stdout)
555 /* print a newline during tcc -E */
556 printf("\n"), fflush(stdout);
557 fflush(stdout); /* flush -v output */
558 fprintf(stderr, "%s\n", buf);
559 fflush(stderr); /* print error/warning now (win32) */
560 } else {
561 s1->error_func(s1->error_opaque, buf);
563 if (s1) {
564 if (mode != ERROR_WARN)
565 s1->nb_errors++;
566 if (mode != ERROR_ERROR)
567 return;
568 if (s1->error_set_jmp_enabled)
569 longjmp(s1->error_jmp_buf, 1);
571 exit(1);
574 LIBTCCAPI void tcc_set_error_func(TCCState *s, void *error_opaque, TCCErrorFunc error_func)
576 s->error_opaque = error_opaque;
577 s->error_func = error_func;
580 LIBTCCAPI TCCErrorFunc tcc_get_error_func(TCCState *s)
582 return s->error_func;
585 LIBTCCAPI void *tcc_get_error_opaque(TCCState *s)
587 return s->error_opaque;
590 /* error without aborting current compilation */
591 PUB_FUNC void _tcc_error_noabort(const char *fmt, ...)
593 va_list ap;
594 va_start(ap, fmt);
595 error1(ERROR_NOABORT, fmt, ap);
596 va_end(ap);
599 PUB_FUNC void _tcc_error(const char *fmt, ...)
601 va_list ap;
602 va_start(ap, fmt);
603 for (;;) error1(ERROR_ERROR, fmt, ap);
606 PUB_FUNC void _tcc_warning(const char *fmt, ...)
608 va_list ap;
609 va_start(ap, fmt);
610 error1(ERROR_WARN, fmt, ap);
611 va_end(ap);
614 /********************************************************/
615 /* I/O layer */
617 ST_FUNC void tcc_open_bf(TCCState *s1, const char *filename, int initlen)
619 BufferedFile *bf;
620 int buflen = initlen ? initlen : IO_BUF_SIZE;
622 bf = tcc_mallocz(sizeof(BufferedFile) + buflen);
623 bf->buf_ptr = bf->buffer;
624 bf->buf_end = bf->buffer + initlen;
625 bf->buf_end[0] = CH_EOB; /* put eob symbol */
626 pstrcpy(bf->filename, sizeof(bf->filename), filename);
627 #ifdef _WIN32
628 normalize_slashes(bf->filename);
629 #endif
630 bf->true_filename = bf->filename;
631 bf->line_num = 1;
632 bf->ifdef_stack_ptr = s1->ifdef_stack_ptr;
633 bf->fd = -1;
634 bf->prev = file;
635 file = bf;
636 tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
639 ST_FUNC void tcc_close(void)
641 TCCState *s1 = tcc_state;
642 BufferedFile *bf = file;
643 if (bf->fd > 0) {
644 close(bf->fd);
645 total_lines += bf->line_num;
647 if (bf->true_filename != bf->filename)
648 tcc_free(bf->true_filename);
649 file = bf->prev;
650 tcc_free(bf);
653 static int _tcc_open(TCCState *s1, const char *filename)
655 int fd;
656 if (strcmp(filename, "-") == 0)
657 fd = 0, filename = "<stdin>";
658 else
659 fd = open(filename, O_RDONLY | O_BINARY);
660 if ((s1->verbose == 2 && fd >= 0) || s1->verbose == 3)
661 printf("%s %*s%s\n", fd < 0 ? "nf":"->",
662 (int)(s1->include_stack_ptr - s1->include_stack), "", filename);
663 return fd;
666 ST_FUNC int tcc_open(TCCState *s1, const char *filename)
668 int fd = _tcc_open(s1, filename);
669 if (fd < 0)
670 return -1;
671 tcc_open_bf(s1, filename, 0);
672 file->fd = fd;
673 return 0;
676 /* compile the file opened in 'file'. Return non zero if errors. */
677 static int tcc_compile(TCCState *s1, int filetype, const char *str, int fd)
679 /* Here we enter the code section where we use the global variables for
680 parsing and code generation (tccpp.c, tccgen.c, <target>-gen.c).
681 Other threads need to wait until we're done.
683 Alternatively we could use thread local storage for those global
684 variables, which may or may not have advantages */
686 WAIT_SEM();
687 tcc_state = s1;
689 if (setjmp(s1->error_jmp_buf) == 0) {
690 int is_asm;
691 s1->error_set_jmp_enabled = 1;
692 s1->nb_errors = 0;
694 if (fd == -1) {
695 int len = strlen(str);
696 tcc_open_bf(s1, "<string>", len);
697 memcpy(file->buffer, str, len);
698 } else {
699 tcc_open_bf(s1, str, 0);
700 file->fd = fd;
703 is_asm = !!(filetype & (AFF_TYPE_ASM|AFF_TYPE_ASMPP));
704 tccelf_begin_file(s1);
705 preprocess_start(s1, is_asm);
706 tccgen_init(s1);
707 if (s1->output_type == TCC_OUTPUT_PREPROCESS) {
708 tcc_preprocess(s1);
709 } else if (is_asm) {
710 #ifdef CONFIG_TCC_ASM
711 tcc_assemble(s1, !!(filetype & AFF_TYPE_ASMPP));
712 #else
713 tcc_error_noabort("asm not supported");
714 #endif
715 } else {
716 tccgen_compile(s1);
719 s1->error_set_jmp_enabled = 0;
720 tccgen_finish(s1);
721 preprocess_end(s1);
722 tccelf_end_file(s1);
724 tcc_state = NULL;
725 POST_SEM();
726 return s1->nb_errors != 0 ? -1 : 0;
729 LIBTCCAPI int tcc_compile_string(TCCState *s, const char *str)
731 return tcc_compile(s, s->filetype, str, -1);
734 /* define a preprocessor symbol. A value can also be provided with the '=' operator */
735 LIBTCCAPI void tcc_define_symbol(TCCState *s1, const char *sym, const char *value)
737 if (!value)
738 value = "1";
739 cstr_printf(&s1->cmdline_defs, "#define %s %s\n", sym, value);
742 /* undefine a preprocessor symbol */
743 LIBTCCAPI void tcc_undefine_symbol(TCCState *s1, const char *sym)
745 cstr_printf(&s1->cmdline_defs, "#undef %s\n", sym);
749 LIBTCCAPI TCCState *tcc_new(void)
751 TCCState *s;
753 s = tcc_mallocz(sizeof(TCCState));
754 if (!s)
755 return NULL;
756 #ifdef MEM_DEBUG
757 ++nb_states;
758 #endif
760 #undef gnu_ext
762 s->gnu_ext = 1;
763 s->tcc_ext = 1;
764 s->nocommon = 1;
765 s->dollars_in_identifiers = 1; /*on by default like in gcc/clang*/
766 s->cversion = 199901; /* default unless -std=c11 is supplied */
767 s->warn_implicit_function_declaration = 1;
768 s->ms_extensions = 1;
770 #ifdef CHAR_IS_UNSIGNED
771 s->char_is_unsigned = 1;
772 #endif
773 #ifdef TCC_TARGET_I386
774 s->seg_size = 32;
775 #endif
776 /* enable this if you want symbols with leading underscore on windows: */
777 #if 0 /* def TCC_TARGET_PE */
778 s->leading_underscore = 1;
779 #endif
780 s->ppfp = stdout;
781 /* might be used in error() before preprocess_start() */
782 s->include_stack_ptr = s->include_stack;
784 tccelf_new(s);
786 #ifdef _WIN32
787 tcc_set_lib_path_w32(s);
788 #else
789 tcc_set_lib_path(s, CONFIG_TCCDIR);
790 #endif
793 /* define __TINYC__ 92X */
794 char buffer[32]; int a,b,c;
795 sscanf(TCC_VERSION, "%d.%d.%d", &a, &b, &c);
796 sprintf(buffer, "%d", a*10000 + b*100 + c);
797 tcc_define_symbol(s, "__TINYC__", buffer);
800 /* standard defines */
801 tcc_define_symbol(s, "__STDC__", NULL);
802 tcc_define_symbol(s, "__STDC_VERSION__", "199901L");
803 tcc_define_symbol(s, "__STDC_HOSTED__", NULL);
805 /* target defines */
806 #if defined(TCC_TARGET_I386)
807 tcc_define_symbol(s, "__i386__", NULL);
808 tcc_define_symbol(s, "__i386", NULL);
809 tcc_define_symbol(s, "i386", NULL);
810 #elif defined(TCC_TARGET_X86_64)
811 tcc_define_symbol(s, "__x86_64__", NULL);
812 #elif defined(TCC_TARGET_ARM)
813 tcc_define_symbol(s, "__ARM_ARCH_4__", NULL);
814 tcc_define_symbol(s, "__arm_elf__", NULL);
815 tcc_define_symbol(s, "__arm_elf", NULL);
816 tcc_define_symbol(s, "arm_elf", NULL);
817 tcc_define_symbol(s, "__arm__", NULL);
818 tcc_define_symbol(s, "__arm", NULL);
819 tcc_define_symbol(s, "arm", NULL);
820 tcc_define_symbol(s, "__APCS_32__", NULL);
821 tcc_define_symbol(s, "__ARMEL__", NULL);
822 #if defined(TCC_ARM_EABI)
823 tcc_define_symbol(s, "__ARM_EABI__", NULL);
824 #endif
825 #if defined(TCC_ARM_HARDFLOAT)
826 s->float_abi = ARM_HARD_FLOAT;
827 tcc_define_symbol(s, "__ARM_PCS_VFP", NULL);
828 #else
829 s->float_abi = ARM_SOFTFP_FLOAT;
830 #endif
831 #elif defined(TCC_TARGET_ARM64)
832 tcc_define_symbol(s, "__aarch64__", NULL);
833 #elif defined TCC_TARGET_C67
834 tcc_define_symbol(s, "__C67__", NULL);
835 #elif defined TCC_TARGET_RISCV64
836 tcc_define_symbol(s, "__riscv", NULL);
837 tcc_define_symbol(s, "__riscv_xlen", "64");
838 tcc_define_symbol(s, "__riscv_flen", "64");
839 tcc_define_symbol(s, "__riscv_div", NULL);
840 tcc_define_symbol(s, "__riscv_mul", NULL);
841 tcc_define_symbol(s, "__riscv_fdiv", NULL);
842 tcc_define_symbol(s, "__riscv_fsqrt", NULL);
843 tcc_define_symbol(s, "__riscv_float_abi_double", NULL);
844 #endif
846 #ifdef TCC_TARGET_PE
847 tcc_define_symbol(s, "_WIN32", NULL);
848 tcc_define_symbol(s, "__declspec(x)", "__attribute__((x))");
849 tcc_define_symbol(s, "__cdecl", "");
850 # ifdef TCC_TARGET_X86_64
851 tcc_define_symbol(s, "_WIN64", NULL);
852 # endif
853 #else
854 tcc_define_symbol(s, "__unix__", NULL);
855 tcc_define_symbol(s, "__unix", NULL);
856 tcc_define_symbol(s, "unix", NULL);
857 # if defined(__linux__)
858 tcc_define_symbol(s, "__linux__", NULL);
859 tcc_define_symbol(s, "__linux", NULL);
860 # endif
861 # if defined(__FreeBSD__)
862 tcc_define_symbol(s, "__FreeBSD__", "__FreeBSD__");
863 /* No 'Thread Storage Local' on FreeBSD with tcc */
864 tcc_define_symbol(s, "__NO_TLS", NULL);
865 # endif
866 # if defined(__FreeBSD_kernel__)
867 tcc_define_symbol(s, "__FreeBSD_kernel__", NULL);
868 # endif
869 # if defined(__NetBSD__)
870 tcc_define_symbol(s, "__NetBSD__", "__NetBSD__");
871 # endif
872 # if defined(__OpenBSD__)
873 tcc_define_symbol(s, "__OpenBSD__", "__OpenBSD__");
874 # endif
875 #endif
877 /* TinyCC & gcc defines */
878 #if PTR_SIZE == 4
879 /* 32bit systems. */
880 tcc_define_symbol(s, "__SIZE_TYPE__", "unsigned int");
881 tcc_define_symbol(s, "__PTRDIFF_TYPE__", "int");
882 tcc_define_symbol(s, "__ILP32__", NULL);
883 #elif LONG_SIZE == 4
884 /* 64bit Windows. */
885 tcc_define_symbol(s, "__SIZE_TYPE__", "unsigned long long");
886 tcc_define_symbol(s, "__PTRDIFF_TYPE__", "long long");
887 tcc_define_symbol(s, "__LLP64__", NULL);
888 #else
889 /* Other 64bit systems. */
890 tcc_define_symbol(s, "__SIZE_TYPE__", "unsigned long");
891 tcc_define_symbol(s, "__PTRDIFF_TYPE__", "long");
892 tcc_define_symbol(s, "__LP64__", NULL);
893 #endif
894 tcc_define_symbol(s, "__SIZEOF_POINTER__", PTR_SIZE == 4 ? "4" : "8");
896 #ifdef TCC_TARGET_PE
897 tcc_define_symbol(s, "__WCHAR_TYPE__", "unsigned short");
898 tcc_define_symbol(s, "__WINT_TYPE__", "unsigned short");
899 #else
900 tcc_define_symbol(s, "__WCHAR_TYPE__", "int");
901 /* wint_t is unsigned int by default, but (signed) int on BSDs
902 and unsigned short on windows. Other OSes might have still
903 other conventions, sigh. */
904 # if defined(__FreeBSD__) || defined (__FreeBSD_kernel__) \
905 || defined(__NetBSD__) || defined(__OpenBSD__)
906 tcc_define_symbol(s, "__WINT_TYPE__", "int");
907 # ifdef __FreeBSD__
908 /* define __GNUC__ to have some useful stuff from sys/cdefs.h
909 that are unconditionally used in FreeBSDs other system headers :/ */
910 tcc_define_symbol(s, "__GNUC__", "2");
911 tcc_define_symbol(s, "__GNUC_MINOR__", "7");
912 tcc_define_symbol(s, "__builtin_alloca", "alloca");
913 # endif
914 # else
915 tcc_define_symbol(s, "__WINT_TYPE__", "unsigned int");
916 /* glibc defines */
917 tcc_define_symbol(s, "__REDIRECT(name, proto, alias)",
918 "name proto __asm__ (#alias)");
919 tcc_define_symbol(s, "__REDIRECT_NTH(name, proto, alias)",
920 "name proto __asm__ (#alias) __THROW");
921 # endif
922 /* Some GCC builtins that are simple to express as macros. */
923 tcc_define_symbol(s, "__builtin_extract_return_addr(x)", "x");
924 #endif /* ndef TCC_TARGET_PE */
925 #ifdef TCC_TARGET_MACHO
926 /* emulate APPLE-GCC to make libc's headerfiles compile: */
927 tcc_define_symbol(s, "__APPLE__", "1");
928 tcc_define_symbol(s, "__GNUC__", "4"); /* darwin emits warning on GCC<4 */
930 /* avoids usage of GCC/clang specific builtins in libc-headerfiles: */
931 tcc_define_symbol(s, "__FINITE_MATH_ONLY__", "1");
932 tcc_define_symbol(s, "_FORTIFY_SOURCE", "0");
933 #endif /* ndef TCC_TARGET_MACHO */
934 return s;
937 LIBTCCAPI void tcc_delete(TCCState *s1)
939 /* free sections */
940 tccelf_delete(s1);
942 /* free library paths */
943 dynarray_reset(&s1->library_paths, &s1->nb_library_paths);
944 dynarray_reset(&s1->crt_paths, &s1->nb_crt_paths);
946 /* free include paths */
947 dynarray_reset(&s1->include_paths, &s1->nb_include_paths);
948 dynarray_reset(&s1->sysinclude_paths, &s1->nb_sysinclude_paths);
950 tcc_free(s1->tcc_lib_path);
951 tcc_free(s1->soname);
952 tcc_free(s1->rpath);
953 tcc_free(s1->init_symbol);
954 tcc_free(s1->fini_symbol);
955 tcc_free(s1->outfile);
956 tcc_free(s1->deps_outfile);
957 dynarray_reset(&s1->files, &s1->nb_files);
958 dynarray_reset(&s1->target_deps, &s1->nb_target_deps);
959 dynarray_reset(&s1->pragma_libs, &s1->nb_pragma_libs);
960 dynarray_reset(&s1->argv, &s1->argc);
962 cstr_free(&s1->cmdline_defs);
963 cstr_free(&s1->cmdline_incl);
964 #ifdef TCC_IS_NATIVE
965 /* free runtime memory */
966 tcc_run_free(s1);
967 #endif
969 tcc_free(s1);
970 #ifdef MEM_DEBUG
971 if (0 == --nb_states)
972 tcc_memcheck();
973 #endif
976 LIBTCCAPI int tcc_set_output_type(TCCState *s, int output_type)
978 s->output_type = output_type;
980 /* always elf for objects */
981 if (output_type == TCC_OUTPUT_OBJ)
982 s->output_format = TCC_OUTPUT_FORMAT_ELF;
984 if (s->char_is_unsigned)
985 tcc_define_symbol(s, "__CHAR_UNSIGNED__", NULL);
987 if (!s->nostdinc) {
988 /* default include paths */
989 /* -isystem paths have already been handled */
990 tcc_add_sysinclude_path(s, CONFIG_TCC_SYSINCLUDEPATHS);
993 #ifdef CONFIG_TCC_BCHECK
994 if (s->do_bounds_check) {
995 /* if bound checking, then add corresponding sections */
996 tccelf_bounds_new(s);
997 /* define symbol */
998 tcc_define_symbol(s, "__BOUNDS_CHECKING_ON", NULL);
1000 #endif
1001 if (s->do_debug) {
1002 /* add debug sections */
1003 tccelf_stab_new(s);
1006 tcc_add_library_path(s, CONFIG_TCC_LIBPATHS);
1008 #ifdef TCC_TARGET_PE
1009 # ifdef _WIN32
1010 if (!s->nostdlib && output_type != TCC_OUTPUT_OBJ)
1011 tcc_add_systemdir(s);
1012 # endif
1013 #else
1014 /* paths for crt objects */
1015 tcc_split_path(s, &s->crt_paths, &s->nb_crt_paths, CONFIG_TCC_CRTPREFIX);
1016 /* add libc crt1/crti objects */
1017 if ((output_type == TCC_OUTPUT_EXE || output_type == TCC_OUTPUT_DLL) &&
1018 !s->nostdlib) {
1019 if (output_type != TCC_OUTPUT_DLL)
1020 tcc_add_crt(s, "crt1.o");
1021 tcc_add_crt(s, "crti.o");
1023 #endif
1024 return 0;
1027 LIBTCCAPI int tcc_add_include_path(TCCState *s, const char *pathname)
1029 tcc_split_path(s, &s->include_paths, &s->nb_include_paths, pathname);
1030 return 0;
1033 LIBTCCAPI int tcc_add_sysinclude_path(TCCState *s, const char *pathname)
1035 tcc_split_path(s, &s->sysinclude_paths, &s->nb_sysinclude_paths, pathname);
1036 return 0;
1039 ST_FUNC int tcc_add_file_internal(TCCState *s1, const char *filename, int flags)
1041 int fd, ret;
1043 /* open the file */
1044 fd = _tcc_open(s1, filename);
1045 if (fd < 0) {
1046 if (flags & AFF_PRINT_ERROR)
1047 tcc_error_noabort("file '%s' not found", filename);
1048 return -1;
1051 /* update target deps */
1052 dynarray_add(&s1->target_deps, &s1->nb_target_deps,
1053 tcc_strdup(filename));
1055 if (flags & AFF_TYPE_BIN) {
1056 ElfW(Ehdr) ehdr;
1057 int obj_type;
1059 obj_type = tcc_object_type(fd, &ehdr);
1060 lseek(fd, 0, SEEK_SET);
1062 #ifdef TCC_TARGET_MACHO
1063 if (0 == obj_type && 0 == strcmp(tcc_fileextension(filename), ".dylib"))
1064 obj_type = AFF_BINTYPE_DYN;
1065 #endif
1067 switch (obj_type) {
1068 case AFF_BINTYPE_REL:
1069 ret = tcc_load_object_file(s1, fd, 0);
1070 break;
1071 #ifndef TCC_TARGET_PE
1072 case AFF_BINTYPE_DYN:
1073 if (s1->output_type == TCC_OUTPUT_MEMORY) {
1074 ret = 0;
1075 #ifdef TCC_IS_NATIVE
1076 if (NULL == dlopen(filename, RTLD_GLOBAL | RTLD_LAZY))
1077 ret = -1;
1078 #endif
1079 } else {
1080 ret = tcc_load_dll(s1, fd, filename,
1081 (flags & AFF_REFERENCED_DLL) != 0);
1083 break;
1084 #endif
1085 case AFF_BINTYPE_AR:
1086 ret = tcc_load_archive(s1, fd, !(flags & AFF_WHOLE_ARCHIVE));
1087 break;
1088 #ifdef TCC_TARGET_COFF
1089 case AFF_BINTYPE_C67:
1090 ret = tcc_load_coff(s1, fd);
1091 break;
1092 #endif
1093 default:
1094 #ifdef TCC_TARGET_PE
1095 ret = pe_load_file(s1, filename, fd);
1096 #else
1097 /* as GNU ld, consider it is an ld script if not recognized */
1098 ret = tcc_load_ldscript(s1, fd);
1099 #endif
1100 if (ret < 0)
1101 tcc_error_noabort("unrecognized file type");
1102 break;
1104 close(fd);
1105 } else {
1106 ret = tcc_compile(s1, flags, filename, fd);
1108 return ret;
1111 LIBTCCAPI int tcc_add_file(TCCState *s, const char *filename)
1113 int filetype = s->filetype;
1114 if (0 == (filetype & AFF_TYPE_MASK)) {
1115 /* use a file extension to detect a filetype */
1116 const char *ext = tcc_fileextension(filename);
1117 if (ext[0]) {
1118 ext++;
1119 if (!strcmp(ext, "S"))
1120 filetype = AFF_TYPE_ASMPP;
1121 else if (!strcmp(ext, "s"))
1122 filetype = AFF_TYPE_ASM;
1123 else if (!PATHCMP(ext, "c") || !PATHCMP(ext, "i"))
1124 filetype = AFF_TYPE_C;
1125 else
1126 filetype |= AFF_TYPE_BIN;
1127 } else {
1128 filetype = AFF_TYPE_C;
1131 return tcc_add_file_internal(s, filename, filetype | AFF_PRINT_ERROR);
1134 LIBTCCAPI int tcc_add_library_path(TCCState *s, const char *pathname)
1136 tcc_split_path(s, &s->library_paths, &s->nb_library_paths, pathname);
1137 return 0;
1140 static int tcc_add_library_internal(TCCState *s, const char *fmt,
1141 const char *filename, int flags, char **paths, int nb_paths)
1143 char buf[1024];
1144 int i;
1146 for(i = 0; i < nb_paths; i++) {
1147 snprintf(buf, sizeof(buf), fmt, paths[i], filename);
1148 if (tcc_add_file_internal(s, buf, flags | AFF_TYPE_BIN) == 0)
1149 return 0;
1151 return -1;
1154 /* find and load a dll. Return non zero if not found */
1155 /* XXX: add '-rpath' option support ? */
1156 ST_FUNC int tcc_add_dll(TCCState *s, const char *filename, int flags)
1158 return tcc_add_library_internal(s, "%s/%s", filename, flags,
1159 s->library_paths, s->nb_library_paths);
1162 #ifndef TCC_TARGET_PE
1163 ST_FUNC int tcc_add_crt(TCCState *s1, const char *filename)
1165 if (-1 == tcc_add_library_internal(s1, "%s/%s",
1166 filename, 0, s1->crt_paths, s1->nb_crt_paths))
1167 tcc_error_noabort("file '%s' not found", filename);
1168 return 0;
1170 #endif
1172 /* the library name is the same as the argument of the '-l' option */
1173 LIBTCCAPI int tcc_add_library(TCCState *s, const char *libraryname)
1175 #if defined TCC_TARGET_PE
1176 const char *libs[] = { "%s/%s.def", "%s/lib%s.def", "%s/%s.dll", "%s/lib%s.dll", "%s/lib%s.a", NULL };
1177 const char **pp = s->static_link ? libs + 4 : libs;
1178 #elif defined TCC_TARGET_MACHO
1179 const char *libs[] = { "%s/lib%s.dylib", "%s/lib%s.a", NULL };
1180 const char **pp = s->static_link ? libs + 1 : libs;
1181 #else
1182 const char *libs[] = { "%s/lib%s.so", "%s/lib%s.a", NULL };
1183 const char **pp = s->static_link ? libs + 1 : libs;
1184 #endif
1185 int flags = s->filetype & AFF_WHOLE_ARCHIVE;
1186 while (*pp) {
1187 if (0 == tcc_add_library_internal(s, *pp,
1188 libraryname, flags, s->library_paths, s->nb_library_paths))
1189 return 0;
1190 ++pp;
1192 return -1;
1195 PUB_FUNC int tcc_add_library_err(TCCState *s1, const char *libname)
1197 int ret = tcc_add_library(s1, libname);
1198 if (ret < 0)
1199 tcc_error_noabort("library '%s' not found", libname);
1200 return ret;
1203 /* handle #pragma comment(lib,) */
1204 ST_FUNC void tcc_add_pragma_libs(TCCState *s1)
1206 int i;
1207 for (i = 0; i < s1->nb_pragma_libs; i++)
1208 tcc_add_library_err(s1, s1->pragma_libs[i]);
1211 LIBTCCAPI int tcc_add_symbol(TCCState *s1, const char *name, const void *val)
1213 #ifdef TCC_TARGET_PE
1214 /* On x86_64 'val' might not be reachable with a 32bit offset.
1215 So it is handled here as if it were in a DLL. */
1216 pe_putimport(s1, 0, name, (uintptr_t)val);
1217 #else
1218 set_elf_sym(symtab_section, (uintptr_t)val, 0,
1219 ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE), 0,
1220 SHN_ABS, name);
1221 #endif
1222 return 0;
1225 LIBTCCAPI void tcc_set_lib_path(TCCState *s, const char *path)
1227 tcc_free(s->tcc_lib_path);
1228 s->tcc_lib_path = tcc_strdup(path);
1231 #define WD_ALL 0x0001 /* warning is activated when using -Wall */
1232 #define FD_INVERT 0x0002 /* invert value before storing */
1234 typedef struct FlagDef {
1235 uint16_t offset;
1236 uint16_t flags;
1237 const char *name;
1238 } FlagDef;
1240 static int no_flag(const char **pp)
1242 const char *p = *pp;
1243 if (*p != 'n' || *++p != 'o' || *++p != '-')
1244 return 0;
1245 *pp = p + 1;
1246 return 1;
1249 ST_FUNC int set_flag(TCCState *s, const FlagDef *flags, const char *name)
1251 int value, ret;
1252 const FlagDef *p;
1253 const char *r;
1255 value = 1;
1256 r = name;
1257 if (no_flag(&r))
1258 value = 0;
1260 for (ret = -1, p = flags; p->name; ++p) {
1261 if (ret) {
1262 if (strcmp(r, p->name))
1263 continue;
1264 } else {
1265 if (0 == (p->flags & WD_ALL))
1266 continue;
1268 if (p->offset) {
1269 *((unsigned char *)s + p->offset) =
1270 p->flags & FD_INVERT ? !value : value;
1271 if (ret)
1272 return 0;
1273 } else {
1274 ret = 0;
1277 return ret;
1280 static int strstart(const char *val, const char **str)
1282 const char *p, *q;
1283 p = *str;
1284 q = val;
1285 while (*q) {
1286 if (*p != *q)
1287 return 0;
1288 p++;
1289 q++;
1291 *str = p;
1292 return 1;
1295 /* Like strstart, but automatically takes into account that ld options can
1297 * - start with double or single dash (e.g. '--soname' or '-soname')
1298 * - arguments can be given as separate or after '=' (e.g. '-Wl,-soname,x.so'
1299 * or '-Wl,-soname=x.so')
1301 * you provide `val` always in 'option[=]' form (no leading -)
1303 static int link_option(const char *str, const char *val, const char **ptr)
1305 const char *p, *q;
1306 int ret;
1308 /* there should be 1 or 2 dashes */
1309 if (*str++ != '-')
1310 return 0;
1311 if (*str == '-')
1312 str++;
1314 /* then str & val should match (potentially up to '=') */
1315 p = str;
1316 q = val;
1318 ret = 1;
1319 if (q[0] == '?') {
1320 ++q;
1321 if (no_flag(&p))
1322 ret = -1;
1325 while (*q != '\0' && *q != '=') {
1326 if (*p != *q)
1327 return 0;
1328 p++;
1329 q++;
1332 /* '=' near eos means ',' or '=' is ok */
1333 if (*q == '=') {
1334 if (*p == 0)
1335 *ptr = p;
1336 if (*p != ',' && *p != '=')
1337 return 0;
1338 p++;
1339 } else if (*p) {
1340 return 0;
1342 *ptr = p;
1343 return ret;
1346 static const char *skip_linker_arg(const char **str)
1348 const char *s1 = *str;
1349 const char *s2 = strchr(s1, ',');
1350 *str = s2 ? s2++ : (s2 = s1 + strlen(s1));
1351 return s2;
1354 static void copy_linker_arg(char **pp, const char *s, int sep)
1356 const char *q = s;
1357 char *p = *pp;
1358 int l = 0;
1359 if (p && sep)
1360 p[l = strlen(p)] = sep, ++l;
1361 skip_linker_arg(&q);
1362 pstrncpy(l + (*pp = tcc_realloc(p, q - s + l + 1)), s, q - s);
1365 /* set linker options */
1366 static int tcc_set_linker(TCCState *s, const char *option)
1368 TCCState *s1 = s;
1369 while (*option) {
1371 const char *p = NULL;
1372 char *end = NULL;
1373 int ignoring = 0;
1374 int ret;
1376 if (link_option(option, "Bsymbolic", &p)) {
1377 s->symbolic = 1;
1378 } else if (link_option(option, "nostdlib", &p)) {
1379 s->nostdlib = 1;
1380 } else if (link_option(option, "fini=", &p)) {
1381 copy_linker_arg(&s->fini_symbol, p, 0);
1382 ignoring = 1;
1383 } else if (link_option(option, "image-base=", &p)
1384 || link_option(option, "Ttext=", &p)) {
1385 s->text_addr = strtoull(p, &end, 16);
1386 s->has_text_addr = 1;
1387 } else if (link_option(option, "init=", &p)) {
1388 copy_linker_arg(&s->init_symbol, p, 0);
1389 ignoring = 1;
1390 } else if (link_option(option, "oformat=", &p)) {
1391 #if defined(TCC_TARGET_PE)
1392 if (strstart("pe-", &p)) {
1393 #elif PTR_SIZE == 8
1394 if (strstart("elf64-", &p)) {
1395 #else
1396 if (strstart("elf32-", &p)) {
1397 #endif
1398 s->output_format = TCC_OUTPUT_FORMAT_ELF;
1399 } else if (!strcmp(p, "binary")) {
1400 s->output_format = TCC_OUTPUT_FORMAT_BINARY;
1401 #ifdef TCC_TARGET_COFF
1402 } else if (!strcmp(p, "coff")) {
1403 s->output_format = TCC_OUTPUT_FORMAT_COFF;
1404 #endif
1405 } else
1406 goto err;
1408 } else if (link_option(option, "as-needed", &p)) {
1409 ignoring = 1;
1410 } else if (link_option(option, "O", &p)) {
1411 ignoring = 1;
1412 } else if (link_option(option, "export-all-symbols", &p)) {
1413 s->rdynamic = 1;
1414 } else if (link_option(option, "export-dynamic", &p)) {
1415 s->rdynamic = 1;
1416 } else if (link_option(option, "rpath=", &p)) {
1417 copy_linker_arg(&s->rpath, p, ':');
1418 } else if (link_option(option, "enable-new-dtags", &p)) {
1419 s->enable_new_dtags = 1;
1420 } else if (link_option(option, "section-alignment=", &p)) {
1421 s->section_align = strtoul(p, &end, 16);
1422 } else if (link_option(option, "soname=", &p)) {
1423 copy_linker_arg(&s->soname, p, 0);
1424 #ifdef TCC_TARGET_PE
1425 } else if (link_option(option, "large-address-aware", &p)) {
1426 s->pe_characteristics |= 0x20;
1427 } else if (link_option(option, "file-alignment=", &p)) {
1428 s->pe_file_align = strtoul(p, &end, 16);
1429 } else if (link_option(option, "stack=", &p)) {
1430 s->pe_stack_size = strtoul(p, &end, 10);
1431 } else if (link_option(option, "subsystem=", &p)) {
1432 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
1433 if (!strcmp(p, "native")) {
1434 s->pe_subsystem = 1;
1435 } else if (!strcmp(p, "console")) {
1436 s->pe_subsystem = 3;
1437 } else if (!strcmp(p, "gui") || !strcmp(p, "windows")) {
1438 s->pe_subsystem = 2;
1439 } else if (!strcmp(p, "posix")) {
1440 s->pe_subsystem = 7;
1441 } else if (!strcmp(p, "efiapp")) {
1442 s->pe_subsystem = 10;
1443 } else if (!strcmp(p, "efiboot")) {
1444 s->pe_subsystem = 11;
1445 } else if (!strcmp(p, "efiruntime")) {
1446 s->pe_subsystem = 12;
1447 } else if (!strcmp(p, "efirom")) {
1448 s->pe_subsystem = 13;
1449 #elif defined(TCC_TARGET_ARM)
1450 if (!strcmp(p, "wince")) {
1451 s->pe_subsystem = 9;
1452 #endif
1453 } else
1454 goto err;
1455 #endif
1456 } else if (ret = link_option(option, "?whole-archive", &p), ret) {
1457 if (ret > 0)
1458 s->filetype |= AFF_WHOLE_ARCHIVE;
1459 else
1460 s->filetype &= ~AFF_WHOLE_ARCHIVE;
1461 } else if (p) {
1462 return 0;
1463 } else {
1464 err:
1465 tcc_error("unsupported linker option '%s'", option);
1468 if (ignoring && s->warn_unsupported)
1469 tcc_warning("unsupported linker option '%s'", option);
1471 option = skip_linker_arg(&p);
1473 return 1;
1476 typedef struct TCCOption {
1477 const char *name;
1478 uint16_t index;
1479 uint16_t flags;
1480 } TCCOption;
1482 enum {
1483 TCC_OPTION_HELP,
1484 TCC_OPTION_HELP2,
1485 TCC_OPTION_v,
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_ba,
1497 TCC_OPTION_g,
1498 TCC_OPTION_c,
1499 TCC_OPTION_dumpversion,
1500 TCC_OPTION_d,
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_Wp,
1511 TCC_OPTION_W,
1512 TCC_OPTION_O,
1513 TCC_OPTION_mfloat_abi,
1514 TCC_OPTION_m,
1515 TCC_OPTION_f,
1516 TCC_OPTION_isystem,
1517 TCC_OPTION_iwithprefix,
1518 TCC_OPTION_include,
1519 TCC_OPTION_nostdinc,
1520 TCC_OPTION_nostdlib,
1521 TCC_OPTION_print_search_dirs,
1522 TCC_OPTION_rdynamic,
1523 TCC_OPTION_param,
1524 TCC_OPTION_pedantic,
1525 TCC_OPTION_pthread,
1526 TCC_OPTION_run,
1527 TCC_OPTION_w,
1528 TCC_OPTION_pipe,
1529 TCC_OPTION_E,
1530 TCC_OPTION_MD,
1531 TCC_OPTION_MF,
1532 TCC_OPTION_x,
1533 TCC_OPTION_ar,
1534 TCC_OPTION_impdef
1537 #define TCC_OPTION_HAS_ARG 0x0001
1538 #define TCC_OPTION_NOSEP 0x0002 /* cannot have space before option and arg */
1540 static const TCCOption tcc_options[] = {
1541 { "h", TCC_OPTION_HELP, 0 },
1542 { "-help", TCC_OPTION_HELP, 0 },
1543 { "?", TCC_OPTION_HELP, 0 },
1544 { "hh", TCC_OPTION_HELP2, 0 },
1545 { "v", TCC_OPTION_v, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1546 { "-version", TCC_OPTION_v, 0 }, /* handle as verbose, also prints version*/
1547 { "I", TCC_OPTION_I, TCC_OPTION_HAS_ARG },
1548 { "D", TCC_OPTION_D, TCC_OPTION_HAS_ARG },
1549 { "U", TCC_OPTION_U, TCC_OPTION_HAS_ARG },
1550 { "P", TCC_OPTION_P, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1551 { "L", TCC_OPTION_L, TCC_OPTION_HAS_ARG },
1552 { "B", TCC_OPTION_B, TCC_OPTION_HAS_ARG },
1553 { "l", TCC_OPTION_l, TCC_OPTION_HAS_ARG },
1554 { "bench", TCC_OPTION_bench, 0 },
1555 #ifdef CONFIG_TCC_BACKTRACE
1556 { "bt", TCC_OPTION_bt, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1557 #endif
1558 #ifdef CONFIG_TCC_BCHECK
1559 { "b", TCC_OPTION_b, 0 },
1560 #endif
1561 { "g", TCC_OPTION_g, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1562 { "c", TCC_OPTION_c, 0 },
1563 { "dumpversion", TCC_OPTION_dumpversion, 0},
1564 { "d", TCC_OPTION_d, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1565 { "static", TCC_OPTION_static, 0 },
1566 { "std", TCC_OPTION_std, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1567 { "shared", TCC_OPTION_shared, 0 },
1568 { "soname", TCC_OPTION_soname, TCC_OPTION_HAS_ARG },
1569 { "o", TCC_OPTION_o, TCC_OPTION_HAS_ARG },
1570 { "-param", TCC_OPTION_param, TCC_OPTION_HAS_ARG },
1571 { "pedantic", TCC_OPTION_pedantic, 0},
1572 { "pthread", TCC_OPTION_pthread, 0},
1573 { "run", TCC_OPTION_run, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1574 { "rdynamic", TCC_OPTION_rdynamic, 0 },
1575 { "r", TCC_OPTION_r, 0 },
1576 { "s", TCC_OPTION_s, 0 },
1577 { "traditional", TCC_OPTION_traditional, 0 },
1578 { "Wl,", TCC_OPTION_Wl, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1579 { "Wp,", TCC_OPTION_Wp, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1580 { "W", TCC_OPTION_W, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1581 { "O", TCC_OPTION_O, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1582 #ifdef TCC_TARGET_ARM
1583 { "mfloat-abi", TCC_OPTION_mfloat_abi, TCC_OPTION_HAS_ARG },
1584 #endif
1585 { "m", TCC_OPTION_m, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1586 { "f", TCC_OPTION_f, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1587 { "isystem", TCC_OPTION_isystem, TCC_OPTION_HAS_ARG },
1588 { "include", TCC_OPTION_include, TCC_OPTION_HAS_ARG },
1589 { "nostdinc", TCC_OPTION_nostdinc, 0 },
1590 { "nostdlib", TCC_OPTION_nostdlib, 0 },
1591 { "print-search-dirs", TCC_OPTION_print_search_dirs, 0 },
1592 { "w", TCC_OPTION_w, 0 },
1593 { "pipe", TCC_OPTION_pipe, 0},
1594 { "E", TCC_OPTION_E, 0},
1595 { "MD", TCC_OPTION_MD, 0},
1596 { "MF", TCC_OPTION_MF, TCC_OPTION_HAS_ARG },
1597 { "x", TCC_OPTION_x, TCC_OPTION_HAS_ARG },
1598 { "ar", TCC_OPTION_ar, 0},
1599 #ifdef TCC_TARGET_PE
1600 { "impdef", TCC_OPTION_impdef, 0},
1601 #endif
1602 { NULL, 0, 0 },
1605 static const FlagDef options_W[] = {
1606 { 0, 0, "all" },
1607 { offsetof(TCCState, warn_unsupported), 0, "unsupported" },
1608 { offsetof(TCCState, warn_write_strings), 0, "write-strings" },
1609 { offsetof(TCCState, warn_error), 0, "error" },
1610 { offsetof(TCCState, warn_gcc_compat), 0, "gcc-compat" },
1611 { offsetof(TCCState, warn_implicit_function_declaration), WD_ALL,
1612 "implicit-function-declaration" },
1613 { 0, 0, NULL }
1616 static const FlagDef options_f[] = {
1617 { offsetof(TCCState, char_is_unsigned), 0, "unsigned-char" },
1618 { offsetof(TCCState, char_is_unsigned), FD_INVERT, "signed-char" },
1619 { offsetof(TCCState, nocommon), FD_INVERT, "common" },
1620 { offsetof(TCCState, leading_underscore), 0, "leading-underscore" },
1621 { offsetof(TCCState, ms_extensions), 0, "ms-extensions" },
1622 { offsetof(TCCState, dollars_in_identifiers), 0, "dollars-in-identifiers" },
1623 { 0, 0, NULL }
1626 static const FlagDef options_m[] = {
1627 { offsetof(TCCState, ms_bitfields), 0, "ms-bitfields" },
1628 #ifdef TCC_TARGET_X86_64
1629 { offsetof(TCCState, nosse), FD_INVERT, "sse" },
1630 #endif
1631 { 0, 0, NULL }
1634 static void parse_option_D(TCCState *s1, const char *optarg)
1636 char *sym = tcc_strdup(optarg);
1637 char *value = strchr(sym, '=');
1638 if (value)
1639 *value++ = '\0';
1640 tcc_define_symbol(s1, sym, value);
1641 tcc_free(sym);
1644 static void args_parser_add_file(TCCState *s, const char* filename, int filetype)
1646 struct filespec *f = tcc_malloc(sizeof *f + strlen(filename));
1647 f->type = filetype;
1648 strcpy(f->name, filename);
1649 dynarray_add(&s->files, &s->nb_files, f);
1652 static int args_parser_make_argv(const char *r, int *argc, char ***argv)
1654 int ret = 0, q, c;
1655 CString str;
1656 for(;;) {
1657 while (c = (unsigned char)*r, c && c <= ' ')
1658 ++r;
1659 if (c == 0)
1660 break;
1661 q = 0;
1662 cstr_new(&str);
1663 while (c = (unsigned char)*r, c) {
1664 ++r;
1665 if (c == '\\' && (*r == '"' || *r == '\\')) {
1666 c = *r++;
1667 } else if (c == '"') {
1668 q = !q;
1669 continue;
1670 } else if (q == 0 && c <= ' ') {
1671 break;
1673 cstr_ccat(&str, c);
1675 cstr_ccat(&str, 0);
1676 //printf("<%s>\n", str.data), fflush(stdout);
1677 dynarray_add(argv, argc, tcc_strdup(str.data));
1678 cstr_free(&str);
1679 ++ret;
1681 return ret;
1684 /* read list file */
1685 static void args_parser_listfile(TCCState *s,
1686 const char *filename, int optind, int *pargc, char ***pargv)
1688 TCCState *s1 = s;
1689 int fd, i;
1690 size_t len;
1691 char *p;
1692 int argc = 0;
1693 char **argv = NULL;
1695 fd = open(filename, O_RDONLY | O_BINARY);
1696 if (fd < 0)
1697 tcc_error("listfile '%s' not found", filename);
1699 len = lseek(fd, 0, SEEK_END);
1700 p = tcc_malloc(len + 1), p[len] = 0;
1701 lseek(fd, 0, SEEK_SET), read(fd, p, len), close(fd);
1703 for (i = 0; i < *pargc; ++i)
1704 if (i == optind)
1705 args_parser_make_argv(p, &argc, &argv);
1706 else
1707 dynarray_add(&argv, &argc, tcc_strdup((*pargv)[i]));
1709 tcc_free(p);
1710 dynarray_reset(&s->argv, &s->argc);
1711 *pargc = s->argc = argc, *pargv = s->argv = argv;
1714 PUB_FUNC int tcc_parse_args(TCCState *s, int *pargc, char ***pargv, int optind)
1716 TCCState *s1 = s;
1717 const TCCOption *popt;
1718 const char *optarg, *r;
1719 const char *run = NULL;
1720 int last_o = -1;
1721 int x;
1722 CString linker_arg; /* collect -Wl options */
1723 int tool = 0, arg_start = 0, noaction = optind;
1724 char **argv = *pargv;
1725 int argc = *pargc;
1727 cstr_new(&linker_arg);
1729 while (optind < argc) {
1730 r = argv[optind];
1731 if (r[0] == '@' && r[1] != '\0') {
1732 args_parser_listfile(s, r + 1, optind, &argc, &argv);
1733 continue;
1735 optind++;
1736 if (tool) {
1737 if (r[0] == '-' && r[1] == 'v' && r[2] == 0)
1738 ++s->verbose;
1739 continue;
1741 reparse:
1742 if (r[0] != '-' || r[1] == '\0') {
1743 if (r[0] != '@') /* allow "tcc file(s) -run @ args ..." */
1744 args_parser_add_file(s, r, s->filetype);
1745 if (run) {
1746 tcc_set_options(s, run);
1747 arg_start = optind - 1;
1748 break;
1750 continue;
1753 /* find option in table */
1754 for(popt = tcc_options; ; ++popt) {
1755 const char *p1 = popt->name;
1756 const char *r1 = r + 1;
1757 if (p1 == NULL)
1758 tcc_error("invalid option -- '%s'", r);
1759 if (!strstart(p1, &r1))
1760 continue;
1761 optarg = r1;
1762 if (popt->flags & TCC_OPTION_HAS_ARG) {
1763 if (*r1 == '\0' && !(popt->flags & TCC_OPTION_NOSEP)) {
1764 if (optind >= argc)
1765 arg_err:
1766 tcc_error("argument to '%s' is missing", r);
1767 optarg = argv[optind++];
1769 } else if (*r1 != '\0')
1770 continue;
1771 break;
1774 switch(popt->index) {
1775 case TCC_OPTION_HELP:
1776 return OPT_HELP;
1777 case TCC_OPTION_HELP2:
1778 return OPT_HELP2;
1779 case TCC_OPTION_I:
1780 tcc_add_include_path(s, optarg);
1781 break;
1782 case TCC_OPTION_D:
1783 parse_option_D(s, optarg);
1784 break;
1785 case TCC_OPTION_U:
1786 tcc_undefine_symbol(s, optarg);
1787 break;
1788 case TCC_OPTION_L:
1789 tcc_add_library_path(s, optarg);
1790 break;
1791 case TCC_OPTION_B:
1792 /* set tcc utilities path (mainly for tcc development) */
1793 tcc_set_lib_path(s, optarg);
1794 break;
1795 case TCC_OPTION_l:
1796 args_parser_add_file(s, optarg, AFF_TYPE_LIB | (s->filetype & ~AFF_TYPE_MASK));
1797 s->nb_libraries++;
1798 break;
1799 case TCC_OPTION_pthread:
1800 parse_option_D(s, "_REENTRANT");
1801 s->option_pthread = 1;
1802 break;
1803 case TCC_OPTION_bench:
1804 s->do_bench = 1;
1805 break;
1806 #ifdef CONFIG_TCC_BACKTRACE
1807 case TCC_OPTION_bt:
1808 s->rt_num_callers = atoi(optarg);
1809 s->do_backtrace = 1;
1810 s->do_debug = 1;
1811 break;
1812 #endif
1813 #ifdef CONFIG_TCC_BCHECK
1814 case TCC_OPTION_b:
1815 s->do_bounds_check = 1;
1816 s->do_backtrace = 1;
1817 s->do_debug = 1;
1818 break;
1819 #endif
1820 case TCC_OPTION_g:
1821 s->do_debug = 1;
1822 break;
1823 case TCC_OPTION_c:
1824 x = TCC_OUTPUT_OBJ;
1825 set_output_type:
1826 if (s->output_type)
1827 tcc_warning("-%s: overriding compiler action already specified", popt->name);
1828 s->output_type = x;
1829 break;
1830 case TCC_OPTION_d:
1831 if (*optarg == 'D')
1832 s->dflag = 3;
1833 else if (*optarg == 'M')
1834 s->dflag = 7;
1835 else if (*optarg == 't')
1836 s->dflag = 16;
1837 else if (isnum(*optarg))
1838 s->g_debug |= atoi(optarg);
1839 else
1840 goto unsupported_option;
1841 break;
1842 case TCC_OPTION_static:
1843 s->static_link = 1;
1844 break;
1845 case TCC_OPTION_std:
1846 if (*optarg == '=') {
1847 if (strcmp(optarg, "=c11") == 0) {
1848 tcc_undefine_symbol(s, "__STDC_VERSION__");
1849 tcc_define_symbol(s, "__STDC_VERSION__", "201112L");
1851 * The integer constant 1, intended to indicate
1852 * that the implementation does not support atomic
1853 * types (including the _Atomic type qualifier) and
1854 * the <stdatomic.h> header.
1856 tcc_define_symbol(s, "__STDC_NO_ATOMICS__", "1");
1858 * The integer constant 1, intended to indicate
1859 * that the implementation does not support complex
1860 * types or the <complex.h> header.
1862 tcc_define_symbol(s, "__STDC_NO_COMPLEX__", "1");
1864 * The integer constant 1, intended to indicate
1865 * that the implementation does not support the
1866 * <threads.h> header.
1868 tcc_define_symbol(s, "__STDC_NO_THREADS__", "1");
1870 * __STDC_NO_VLA__, tcc supports VLA.
1871 * The integer constant 1, intended to indicate
1872 * that the implementation does not support
1873 * variable length arrays or variably modified
1874 * types.
1876 #if !defined(TCC_TARGET_PE)
1878 * An integer constant of the form yyyymmL (for
1879 * example, 199712L). If this symbol is defined,
1880 * then every character in the Unicode required
1881 * set, when stored in an object of type
1882 * wchar_t, has the same value as the short
1883 * identifier of that character.
1885 #if 0
1886 /* on Linux, this conflicts with a define introduced by
1887 * /usr/include/stdc-predef.h included by glibc libs;
1888 * clang doesn't define it at all so it's probably not necessary
1890 tcc_define_symbol(s, "__STDC_ISO_10646__", "201605L");
1891 #endif
1893 * The integer constant 1, intended to indicate
1894 * that values of type char16_t are UTF−16
1895 * encoded. If some other encoding is used, the
1896 * macro shall not be defined and the actual
1897 * encoding used is implementation defined.
1899 tcc_define_symbol(s, "__STDC_UTF_16__", "1");
1901 * The integer constant 1, intended to indicate
1902 * that values of type char32_t are UTF−32
1903 * encoded. If some other encoding is used, the
1904 * macro shall not be defined and the actual
1905 * encoding used is implementationdefined.
1907 tcc_define_symbol(s, "__STDC_UTF_32__", "1");
1908 #endif /* !TCC_TARGET_PE */
1909 s->cversion = 201112;
1913 * silently ignore other values, a current purpose:
1914 * allow to use a tcc as a reference compiler for "make test"
1916 break;
1917 case TCC_OPTION_shared:
1918 x = TCC_OUTPUT_DLL;
1919 goto set_output_type;
1920 case TCC_OPTION_soname:
1921 s->soname = tcc_strdup(optarg);
1922 break;
1923 case TCC_OPTION_o:
1924 if (s->outfile) {
1925 tcc_warning("multiple -o option");
1926 tcc_free(s->outfile);
1928 s->outfile = tcc_strdup(optarg);
1929 break;
1930 case TCC_OPTION_r:
1931 /* generate a .o merging several output files */
1932 s->option_r = 1;
1933 x = TCC_OUTPUT_OBJ;
1934 goto set_output_type;
1935 case TCC_OPTION_isystem:
1936 tcc_add_sysinclude_path(s, optarg);
1937 break;
1938 case TCC_OPTION_include:
1939 cstr_printf(&s->cmdline_incl, "#include \"%s\"\n", optarg);
1940 break;
1941 case TCC_OPTION_nostdinc:
1942 s->nostdinc = 1;
1943 break;
1944 case TCC_OPTION_nostdlib:
1945 s->nostdlib = 1;
1946 break;
1947 case TCC_OPTION_run:
1948 #ifndef TCC_IS_NATIVE
1949 tcc_error("-run is not available in a cross compiler");
1950 #endif
1951 run = optarg;
1952 x = TCC_OUTPUT_MEMORY;
1953 goto set_output_type;
1954 case TCC_OPTION_v:
1955 do ++s->verbose; while (*optarg++ == 'v');
1956 ++noaction;
1957 break;
1958 case TCC_OPTION_f:
1959 if (set_flag(s, options_f, optarg) < 0)
1960 goto unsupported_option;
1961 break;
1962 #ifdef TCC_TARGET_ARM
1963 case TCC_OPTION_mfloat_abi:
1964 /* tcc doesn't support soft float yet */
1965 if (!strcmp(optarg, "softfp")) {
1966 s->float_abi = ARM_SOFTFP_FLOAT;
1967 tcc_undefine_symbol(s, "__ARM_PCS_VFP");
1968 } else if (!strcmp(optarg, "hard"))
1969 s->float_abi = ARM_HARD_FLOAT;
1970 else
1971 tcc_error("unsupported float abi '%s'", optarg);
1972 break;
1973 #endif
1974 case TCC_OPTION_m:
1975 if (set_flag(s, options_m, optarg) < 0) {
1976 if (x = atoi(optarg), x != 32 && x != 64)
1977 goto unsupported_option;
1978 if (PTR_SIZE != x/8)
1979 return x;
1980 ++noaction;
1982 break;
1983 case TCC_OPTION_W:
1984 s->warn_none = 0;
1985 if (optarg[0] && set_flag(s, options_W, optarg) < 0)
1986 goto unsupported_option;
1987 break;
1988 case TCC_OPTION_w:
1989 s->warn_none = 1;
1990 break;
1991 case TCC_OPTION_rdynamic:
1992 s->rdynamic = 1;
1993 break;
1994 case TCC_OPTION_Wl:
1995 if (linker_arg.size)
1996 --linker_arg.size, cstr_ccat(&linker_arg, ',');
1997 cstr_cat(&linker_arg, optarg, 0);
1998 if (tcc_set_linker(s, linker_arg.data))
1999 cstr_free(&linker_arg);
2000 break;
2001 case TCC_OPTION_Wp:
2002 r = optarg;
2003 goto reparse;
2004 case TCC_OPTION_E:
2005 x = TCC_OUTPUT_PREPROCESS;
2006 goto set_output_type;
2007 case TCC_OPTION_P:
2008 s->Pflag = atoi(optarg) + 1;
2009 break;
2010 case TCC_OPTION_MD:
2011 s->gen_deps = 1;
2012 break;
2013 case TCC_OPTION_MF:
2014 s->deps_outfile = tcc_strdup(optarg);
2015 break;
2016 case TCC_OPTION_dumpversion:
2017 printf ("%s\n", TCC_VERSION);
2018 exit(0);
2019 break;
2020 case TCC_OPTION_x:
2021 x = 0;
2022 if (*optarg == 'c')
2023 x = AFF_TYPE_C;
2024 else if (*optarg == 'a')
2025 x = AFF_TYPE_ASMPP;
2026 else if (*optarg == 'b')
2027 x = AFF_TYPE_BIN;
2028 else if (*optarg == 'n')
2029 x = AFF_TYPE_NONE;
2030 else
2031 tcc_warning("unsupported language '%s'", optarg);
2032 s->filetype = x | (s->filetype & ~AFF_TYPE_MASK);
2033 break;
2034 case TCC_OPTION_O:
2035 last_o = atoi(optarg);
2036 break;
2037 case TCC_OPTION_print_search_dirs:
2038 x = OPT_PRINT_DIRS;
2039 goto extra_action;
2040 case TCC_OPTION_impdef:
2041 x = OPT_IMPDEF;
2042 goto extra_action;
2043 case TCC_OPTION_ar:
2044 x = OPT_AR;
2045 extra_action:
2046 arg_start = optind - 1;
2047 if (arg_start != noaction)
2048 tcc_error("cannot parse %s here", r);
2049 tool = x;
2050 break;
2051 case TCC_OPTION_traditional:
2052 case TCC_OPTION_pedantic:
2053 case TCC_OPTION_pipe:
2054 case TCC_OPTION_s:
2055 /* ignored */
2056 break;
2057 default:
2058 unsupported_option:
2059 if (s->warn_unsupported)
2060 tcc_warning("unsupported option '%s'", r);
2061 break;
2064 if (last_o > 0)
2065 tcc_define_symbol(s, "__OPTIMIZE__", NULL);
2066 if (linker_arg.size) {
2067 r = linker_arg.data;
2068 goto arg_err;
2070 *pargc = argc - arg_start;
2071 *pargv = argv + arg_start;
2072 if (tool)
2073 return tool;
2074 if (optind != noaction)
2075 return 0;
2076 if (s->verbose == 2)
2077 return OPT_PRINT_DIRS;
2078 if (s->verbose)
2079 return OPT_V;
2080 return OPT_HELP;
2083 LIBTCCAPI void tcc_set_options(TCCState *s, const char *r)
2085 char **argv = NULL;
2086 int argc = 0;
2087 args_parser_make_argv(r, &argc, &argv);
2088 tcc_parse_args(s, &argc, &argv, 0);
2089 dynarray_reset(&argv, &argc);
2092 PUB_FUNC void tcc_print_stats(TCCState *s1, unsigned total_time)
2094 if (total_time < 1)
2095 total_time = 1;
2096 if (total_bytes < 1)
2097 total_bytes = 1;
2098 fprintf(stderr, "* %d idents, %d lines, %d bytes\n"
2099 "* %0.3f s, %u lines/s, %0.1f MB/s\n",
2100 total_idents, total_lines, total_bytes,
2101 (double)total_time/1000,
2102 (unsigned)total_lines*1000/total_time,
2103 (double)total_bytes/1000/total_time);
2104 #ifdef MEM_DEBUG
2105 fprintf(stderr, "* %d bytes memory used\n", mem_max_size);
2106 #endif