Add tcov support in Makefile
[tinycc.git] / libtcc.c
blobd5ca6d46ed3e8c93ca0996f92f13d784066533c8
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 "tccdbg.c"
25 #include "tccasm.c"
26 #include "tccelf.c"
27 #include "tccrun.c"
28 #ifdef TCC_TARGET_I386
29 #include "i386-gen.c"
30 #include "i386-link.c"
31 #include "i386-asm.c"
32 #elif defined(TCC_TARGET_ARM)
33 #include "arm-gen.c"
34 #include "arm-link.c"
35 #include "arm-asm.c"
36 #elif defined(TCC_TARGET_ARM64)
37 #include "arm64-gen.c"
38 #include "arm64-link.c"
39 #include "arm-asm.c"
40 #elif defined(TCC_TARGET_C67)
41 #include "c67-gen.c"
42 #include "c67-link.c"
43 #include "tcccoff.c"
44 #elif defined(TCC_TARGET_X86_64)
45 #include "x86_64-gen.c"
46 #include "x86_64-link.c"
47 #include "i386-asm.c"
48 #elif defined(TCC_TARGET_RISCV64)
49 #include "riscv64-gen.c"
50 #include "riscv64-link.c"
51 #include "riscv64-asm.c"
52 #else
53 #error unknown target
54 #endif
55 #ifdef TCC_TARGET_PE
56 #include "tccpe.c"
57 #endif
58 #ifdef TCC_TARGET_MACHO
59 #include "tccmacho.c"
60 #endif
61 #endif /* ONE_SOURCE */
63 #include "tcc.h"
65 /********************************************************/
66 /* global variables */
68 /* XXX: get rid of this ASAP (or maybe not) */
69 ST_DATA struct TCCState *tcc_state;
70 TCC_SEM(static tcc_compile_sem);
71 /* an array of pointers to memory to be free'd after errors */
72 ST_DATA void** stk_data;
73 ST_DATA int nb_stk_data;
75 /********************************************************/
76 #ifdef _WIN32
77 ST_FUNC char *normalize_slashes(char *path)
79 char *p;
80 for (p = path; *p; ++p)
81 if (*p == '\\')
82 *p = '/';
83 return path;
86 #if defined LIBTCC_AS_DLL && !defined CONFIG_TCCDIR
87 static HMODULE tcc_module;
88 BOOL WINAPI DllMain (HINSTANCE hDll, DWORD dwReason, LPVOID lpReserved)
90 if (DLL_PROCESS_ATTACH == dwReason)
91 tcc_module = hDll;
92 return TRUE;
94 #else
95 #define tcc_module NULL /* NULL means executable itself */
96 #endif
98 #ifndef CONFIG_TCCDIR
99 /* on win32, we suppose the lib and includes are at the location of 'tcc.exe' */
100 static inline char *config_tccdir_w32(char *path)
102 char temp[1024];
103 char try[1024];
104 char *p;
105 int c;
106 GetModuleFileName(tcc_module, path, MAX_PATH);
107 p = tcc_basename(normalize_slashes(strlwr(path)));
108 if (p > path)
109 --p;
111 *p = 0;
114 * See if we are perhaps in a "bin/" subfolder of the
115 * installation path, in which case the real root of
116 * the installation is one level up. We can test this
117 * by looking for the 'include' folder.
119 strncpy(temp, path, sizeof(temp)-1);
120 strcat(temp, "/include");
122 if (_access(temp, 0) != 0) {
123 /* No 'include' folder found, so go up one level. */
124 strncpy(temp, path, sizeof(temp)-1);
126 /* Try this for several "levels" up. */
127 for (c = 0; c < 4; c++) {
128 p = tcc_basename(temp);
129 if (p > temp) {
130 --p;
131 *p = '\0';
134 strncpy(try, temp, sizeof(try)-1);
135 strcat(try, "/include");
137 if (_access(try, 0) == 0) {
138 if (p != NULL)
139 p = '\0';
140 strcpy(path, temp);
141 break;
146 return path;
148 #define CONFIG_TCCDIR config_tccdir_w32(alloca(MAX_PATH))
149 #endif
151 #ifdef TCC_TARGET_PE
152 static void tcc_add_systemdir(TCCState *s)
154 char buf[1000];
155 GetSystemDirectory(buf, sizeof buf);
156 tcc_add_library_path(s, normalize_slashes(buf));
158 #endif
159 #endif
161 /********************************************************/
162 #if CONFIG_TCC_SEMLOCK
163 #if defined _WIN32
164 ST_FUNC void wait_sem(TCCSem *p)
166 if (!p->init)
167 InitializeCriticalSection(&p->cr), p->init = 1;
168 EnterCriticalSection(&p->cr);
170 ST_FUNC void post_sem(TCCSem *p)
172 LeaveCriticalSection(&p->cr);
174 #elif defined __APPLE__
175 /* Half-compatible MacOS doesn't have non-shared (process local)
176 semaphores. Use the dispatch framework for lightweight locks. */
177 ST_FUNC void wait_sem(TCCSem *p)
179 if (!p->init)
180 p->sem = dispatch_semaphore_create(1), p->init = 1;
181 dispatch_semaphore_wait(p->sem, DISPATCH_TIME_FOREVER);
183 ST_FUNC void post_sem(TCCSem *p)
185 dispatch_semaphore_signal(p->sem);
187 #else
188 ST_FUNC void wait_sem(TCCSem *p)
190 if (!p->init)
191 sem_init(&p->sem, 0, 1), p->init = 1;
192 while (sem_wait(&p->sem) < 0 && errno == EINTR);
194 ST_FUNC void post_sem(TCCSem *p)
196 sem_post(&p->sem);
198 #endif
199 #endif
201 PUB_FUNC void tcc_enter_state(TCCState *s1)
203 if (s1->error_set_jmp_enabled)
204 return;
205 WAIT_SEM(&tcc_compile_sem);
206 tcc_state = s1;
209 PUB_FUNC void tcc_exit_state(TCCState *s1)
211 if (s1->error_set_jmp_enabled)
212 return;
213 tcc_state = NULL;
214 POST_SEM(&tcc_compile_sem);
217 /********************************************************/
218 /* copy a string and truncate it. */
219 ST_FUNC char *pstrcpy(char *buf, size_t buf_size, const char *s)
221 char *q, *q_end;
222 int c;
224 if (buf_size > 0) {
225 q = buf;
226 q_end = buf + buf_size - 1;
227 while (q < q_end) {
228 c = *s++;
229 if (c == '\0')
230 break;
231 *q++ = c;
233 *q = '\0';
235 return buf;
238 /* strcat and truncate. */
239 ST_FUNC char *pstrcat(char *buf, size_t buf_size, const char *s)
241 size_t len;
242 len = strlen(buf);
243 if (len < buf_size)
244 pstrcpy(buf + len, buf_size - len, s);
245 return buf;
248 ST_FUNC char *pstrncpy(char *out, const char *in, size_t num)
250 memcpy(out, in, num);
251 out[num] = '\0';
252 return out;
255 /* extract the basename of a file */
256 PUB_FUNC char *tcc_basename(const char *name)
258 char *p = strchr(name, 0);
259 while (p > name && !IS_DIRSEP(p[-1]))
260 --p;
261 return p;
264 /* extract extension part of a file
266 * (if no extension, return pointer to end-of-string)
268 PUB_FUNC char *tcc_fileextension (const char *name)
270 char *b = tcc_basename(name);
271 char *e = strrchr(b, '.');
272 return e ? e : strchr(b, 0);
275 ST_FUNC char *tcc_load_text(int fd)
277 int len = lseek(fd, 0, SEEK_END);
278 char *buf = load_data(fd, 0, len + 1);
279 buf[len] = 0;
280 return buf;
283 /********************************************************/
284 /* memory management */
286 #undef free
287 #undef malloc
288 #undef realloc
290 void mem_error(const char *msg)
292 fprintf(stderr, "%s\n", msg);
293 exit (1);
296 #ifndef MEM_DEBUG
298 PUB_FUNC void tcc_free(void *ptr)
300 free(ptr);
303 PUB_FUNC void *tcc_malloc(unsigned long size)
305 void *ptr;
306 ptr = malloc(size);
307 if (!ptr && size)
308 mem_error("memory full (malloc)");
309 return ptr;
312 PUB_FUNC void *tcc_mallocz(unsigned long size)
314 void *ptr;
315 ptr = tcc_malloc(size);
316 if (size)
317 memset(ptr, 0, size);
318 return ptr;
321 PUB_FUNC void *tcc_realloc(void *ptr, unsigned long size)
323 void *ptr1;
324 ptr1 = realloc(ptr, size);
325 if (!ptr1 && size)
326 mem_error("memory full (realloc)");
327 return ptr1;
330 PUB_FUNC char *tcc_strdup(const char *str)
332 char *ptr;
333 ptr = tcc_malloc(strlen(str) + 1);
334 strcpy(ptr, str);
335 return ptr;
338 #else
340 #define MEM_DEBUG_MAGIC1 0xFEEDDEB1
341 #define MEM_DEBUG_MAGIC2 0xFEEDDEB2
342 #define MEM_DEBUG_MAGIC3 0xFEEDDEB3
343 #define MEM_DEBUG_FILE_LEN 40
344 #define MEM_DEBUG_CHECK3(header) \
345 ((mem_debug_header_t*)((char*)header + header->size))->magic3
346 #define MEM_USER_PTR(header) \
347 ((char *)header + offsetof(mem_debug_header_t, magic3))
348 #define MEM_HEADER_PTR(ptr) \
349 (mem_debug_header_t *)((char*)ptr - offsetof(mem_debug_header_t, magic3))
351 struct mem_debug_header {
352 unsigned magic1;
353 unsigned size;
354 struct mem_debug_header *prev;
355 struct mem_debug_header *next;
356 int line_num;
357 char file_name[MEM_DEBUG_FILE_LEN + 1];
358 unsigned magic2;
359 ALIGNED(16) unsigned char magic3[4];
362 typedef struct mem_debug_header mem_debug_header_t;
364 TCC_SEM(static mem_sem);
365 static mem_debug_header_t *mem_debug_chain;
366 static unsigned mem_cur_size;
367 static unsigned mem_max_size;
368 static int nb_states;
370 static mem_debug_header_t *malloc_check(void *ptr, const char *msg)
372 mem_debug_header_t * header = MEM_HEADER_PTR(ptr);
373 if (header->magic1 != MEM_DEBUG_MAGIC1 ||
374 header->magic2 != MEM_DEBUG_MAGIC2 ||
375 read32le(MEM_DEBUG_CHECK3(header)) != MEM_DEBUG_MAGIC3 ||
376 header->size == (unsigned)-1) {
377 fprintf(stderr, "%s check failed\n", msg);
378 if (header->magic1 == MEM_DEBUG_MAGIC1)
379 fprintf(stderr, "%s:%u: block allocated here.\n",
380 header->file_name, header->line_num);
381 exit(1);
383 return header;
386 PUB_FUNC void *tcc_malloc_debug(unsigned long size, const char *file, int line)
388 int ofs;
389 mem_debug_header_t *header;
391 header = malloc(sizeof(mem_debug_header_t) + size);
392 if (!header)
393 mem_error("memory full (malloc)");
395 header->magic1 = MEM_DEBUG_MAGIC1;
396 header->magic2 = MEM_DEBUG_MAGIC2;
397 header->size = size;
398 write32le(MEM_DEBUG_CHECK3(header), MEM_DEBUG_MAGIC3);
399 header->line_num = line;
400 ofs = strlen(file) - MEM_DEBUG_FILE_LEN;
401 strncpy(header->file_name, file + (ofs > 0 ? ofs : 0), MEM_DEBUG_FILE_LEN);
402 header->file_name[MEM_DEBUG_FILE_LEN] = 0;
404 WAIT_SEM(&mem_sem);
405 header->next = mem_debug_chain;
406 header->prev = NULL;
407 if (header->next)
408 header->next->prev = header;
409 mem_debug_chain = header;
410 mem_cur_size += size;
411 if (mem_cur_size > mem_max_size)
412 mem_max_size = mem_cur_size;
413 POST_SEM(&mem_sem);
415 return MEM_USER_PTR(header);
418 PUB_FUNC void tcc_free_debug(void *ptr)
420 mem_debug_header_t *header;
421 if (!ptr)
422 return;
423 header = malloc_check(ptr, "tcc_free");
425 WAIT_SEM(&mem_sem);
426 mem_cur_size -= header->size;
427 header->size = (unsigned)-1;
428 if (header->next)
429 header->next->prev = header->prev;
430 if (header->prev)
431 header->prev->next = header->next;
432 if (header == mem_debug_chain)
433 mem_debug_chain = header->next;
434 POST_SEM(&mem_sem);
435 free(header);
438 PUB_FUNC void *tcc_mallocz_debug(unsigned long size, const char *file, int line)
440 void *ptr;
441 ptr = tcc_malloc_debug(size,file,line);
442 memset(ptr, 0, size);
443 return ptr;
446 PUB_FUNC void *tcc_realloc_debug(void *ptr, unsigned long size, const char *file, int line)
448 mem_debug_header_t *header;
449 int mem_debug_chain_update = 0;
450 if (!ptr)
451 return tcc_malloc_debug(size, file, line);
452 header = malloc_check(ptr, "tcc_realloc");
454 WAIT_SEM(&mem_sem);
455 mem_cur_size -= header->size;
456 mem_debug_chain_update = (header == mem_debug_chain);
457 header = realloc(header, sizeof(mem_debug_header_t) + size);
458 if (!header)
459 mem_error("memory full (realloc)");
460 header->size = size;
461 write32le(MEM_DEBUG_CHECK3(header), MEM_DEBUG_MAGIC3);
462 if (header->next)
463 header->next->prev = header;
464 if (header->prev)
465 header->prev->next = header;
466 if (mem_debug_chain_update)
467 mem_debug_chain = header;
468 mem_cur_size += size;
469 if (mem_cur_size > mem_max_size)
470 mem_max_size = mem_cur_size;
471 POST_SEM(&mem_sem);
473 return MEM_USER_PTR(header);
476 PUB_FUNC char *tcc_strdup_debug(const char *str, const char *file, int line)
478 char *ptr;
479 ptr = tcc_malloc_debug(strlen(str) + 1, file, line);
480 strcpy(ptr, str);
481 return ptr;
484 PUB_FUNC void tcc_memcheck(int d)
486 WAIT_SEM(&mem_sem);
487 nb_states += d;
488 if (0 == nb_states && mem_cur_size) {
489 mem_debug_header_t *header = mem_debug_chain;
490 fflush(stdout);
491 fprintf(stderr, "MEM_DEBUG: mem_leak= %d bytes, mem_max_size= %d bytes\n",
492 mem_cur_size, mem_max_size);
493 while (header) {
494 fprintf(stderr, "%s:%u: error: %u bytes leaked\n",
495 header->file_name, header->line_num, header->size);
496 header = header->next;
498 fflush(stderr);
499 mem_cur_size = 0;
500 mem_debug_chain = NULL;
501 #if MEM_DEBUG-0 == 2
502 exit(2);
503 #endif
505 POST_SEM(&mem_sem);
508 #endif /* MEM_DEBUG */
510 #ifdef _WIN32
511 # define realpath(file, buf) _fullpath(buf, file, 260)
512 #endif
514 /* for #pragma once */
515 ST_FUNC int normalized_PATHCMP(const char *f1, const char *f2)
517 char *p1, *p2;
518 int ret = 1;
519 if (!!(p1 = realpath(f1, NULL))) {
520 if (!!(p2 = realpath(f2, NULL))) {
521 ret = PATHCMP(p1, p2);
522 free(p2); /* using original free */
524 free(p1);
526 return ret;
529 #define free(p) use_tcc_free(p)
530 #define malloc(s) use_tcc_malloc(s)
531 #define realloc(p, s) use_tcc_realloc(p, s)
533 /********************************************************/
534 /* dynarrays */
536 ST_FUNC void dynarray_add(void *ptab, int *nb_ptr, void *data)
538 int nb, nb_alloc;
539 void **pp;
541 nb = *nb_ptr;
542 pp = *(void ***)ptab;
543 /* every power of two we double array size */
544 if ((nb & (nb - 1)) == 0) {
545 if (!nb)
546 nb_alloc = 1;
547 else
548 nb_alloc = nb * 2;
549 pp = tcc_realloc(pp, nb_alloc * sizeof(void *));
550 *(void***)ptab = pp;
552 pp[nb++] = data;
553 *nb_ptr = nb;
556 ST_FUNC void dynarray_reset(void *pp, int *n)
558 void **p;
559 for (p = *(void***)pp; *n; ++p, --*n)
560 if (*p)
561 tcc_free(*p);
562 tcc_free(*(void**)pp);
563 *(void**)pp = NULL;
566 static void tcc_split_path(TCCState *s, void *p_ary, int *p_nb_ary, const char *in)
568 const char *p;
569 do {
570 int c;
571 CString str;
573 cstr_new(&str);
574 for (p = in; c = *p, c != '\0' && c != PATHSEP[0]; ++p) {
575 if (c == '{' && p[1] && p[2] == '}') {
576 c = p[1], p += 2;
577 if (c == 'B')
578 cstr_cat(&str, s->tcc_lib_path, -1);
579 if (c == 'R')
580 cstr_cat(&str, CONFIG_SYSROOT, -1);
581 if (c == 'f' && file) {
582 /* substitute current file's dir */
583 const char *f = file->true_filename;
584 const char *b = tcc_basename(f);
585 if (b > f)
586 cstr_cat(&str, f, b - f - 1);
587 else
588 cstr_cat(&str, ".", 1);
590 } else {
591 cstr_ccat(&str, c);
594 if (str.size) {
595 cstr_ccat(&str, '\0');
596 dynarray_add(p_ary, p_nb_ary, tcc_strdup(str.data));
598 cstr_free(&str);
599 in = p+1;
600 } while (*p);
603 /********************************************************/
604 /* warning / error */
606 /* warn_... option bits */
607 #define WARN_ON 1 /* warning is on (-Woption) */
608 #define WARN_ERR 2 /* warning is an error (-Werror=option) */
609 #define WARN_NOE 4 /* warning is not an error (-Wno-error=option) */
611 /* error1() modes */
612 enum { ERROR_WARN, ERROR_NOABORT, ERROR_ERROR };
614 static void error1(int mode, const char *fmt, va_list ap)
616 BufferedFile **pf, *f;
617 TCCState *s1 = tcc_state;
618 CString cs;
620 tcc_exit_state(s1);
622 if (mode == ERROR_WARN) {
623 if (s1->warn_error)
624 mode = ERROR_ERROR;
625 if (s1->warn_num) {
626 /* handle tcc_warning_c(warn_option)(fmt, ...) */
627 int wopt = *(&s1->warn_none + s1->warn_num);
628 s1->warn_num = 0;
629 if (0 == (wopt & WARN_ON))
630 return;
631 if (wopt & WARN_ERR)
632 mode = ERROR_ERROR;
633 if (wopt & WARN_NOE)
634 mode = ERROR_WARN;
636 if (s1->warn_none)
637 return;
640 cstr_new(&cs);
641 f = NULL;
642 if (s1->error_set_jmp_enabled) { /* we're called while parsing a file */
643 /* use upper file if inline ":asm:" or token ":paste:" */
644 for (f = file; f && f->filename[0] == ':'; f = f->prev)
647 if (f) {
648 for(pf = s1->include_stack; pf < s1->include_stack_ptr; pf++)
649 cstr_printf(&cs, "In file included from %s:%d:\n",
650 (*pf)->filename, (*pf)->line_num - 1);
651 cstr_printf(&cs, "%s:%d: ",
652 f->filename, f->line_num - !!(tok_flags & TOK_FLAG_BOL));
653 } else if (s1->current_filename) {
654 cstr_printf(&cs, "%s: ", s1->current_filename);
656 if (0 == cs.size)
657 cstr_printf(&cs, "tcc: ");
658 cstr_printf(&cs, mode == ERROR_WARN ? "warning: " : "error: ");
659 cstr_vprintf(&cs, fmt, ap);
660 if (!s1 || !s1->error_func) {
661 /* default case: stderr */
662 if (s1 && s1->output_type == TCC_OUTPUT_PREPROCESS && s1->ppfp == stdout)
663 printf("\n"); /* print a newline during tcc -E */
664 fflush(stdout); /* flush -v output */
665 fprintf(stderr, "%s\n", (char*)cs.data);
666 fflush(stderr); /* print error/warning now (win32) */
667 } else {
668 s1->error_func(s1->error_opaque, (char*)cs.data);
670 cstr_free(&cs);
671 if (mode != ERROR_WARN)
672 s1->nb_errors++;
673 if (mode == ERROR_ERROR && s1->error_set_jmp_enabled) {
674 while (nb_stk_data)
675 tcc_free(*(void**)stk_data[--nb_stk_data]);
676 longjmp(s1->error_jmp_buf, 1);
680 LIBTCCAPI void tcc_set_error_func(TCCState *s, void *error_opaque, TCCErrorFunc error_func)
682 s->error_opaque = error_opaque;
683 s->error_func = error_func;
686 LIBTCCAPI TCCErrorFunc tcc_get_error_func(TCCState *s)
688 return s->error_func;
691 LIBTCCAPI void *tcc_get_error_opaque(TCCState *s)
693 return s->error_opaque;
696 /* error without aborting current compilation */
697 PUB_FUNC int _tcc_error_noabort(const char *fmt, ...)
699 va_list ap;
700 va_start(ap, fmt);
701 error1(ERROR_NOABORT, fmt, ap);
702 va_end(ap);
703 return -1;
706 #undef _tcc_error
707 PUB_FUNC void _tcc_error(const char *fmt, ...)
709 va_list ap;
710 va_start(ap, fmt);
711 error1(ERROR_ERROR, fmt, ap);
712 exit(1);
714 #define _tcc_error use_tcc_error_noabort
716 PUB_FUNC void _tcc_warning(const char *fmt, ...)
718 va_list ap;
719 va_start(ap, fmt);
720 error1(ERROR_WARN, fmt, ap);
721 va_end(ap);
725 /********************************************************/
726 /* I/O layer */
728 ST_FUNC void tcc_open_bf(TCCState *s1, const char *filename, int initlen)
730 BufferedFile *bf;
731 int buflen = initlen ? initlen : IO_BUF_SIZE;
733 bf = tcc_mallocz(sizeof(BufferedFile) + buflen);
734 bf->buf_ptr = bf->buffer;
735 bf->buf_end = bf->buffer + initlen;
736 bf->buf_end[0] = CH_EOB; /* put eob symbol */
737 pstrcpy(bf->filename, sizeof(bf->filename), filename);
738 #ifdef _WIN32
739 normalize_slashes(bf->filename);
740 #endif
741 bf->true_filename = bf->filename;
742 bf->line_num = 1;
743 bf->ifdef_stack_ptr = s1->ifdef_stack_ptr;
744 bf->fd = -1;
745 bf->prev = file;
746 file = bf;
747 tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
750 ST_FUNC void tcc_close(void)
752 TCCState *s1 = tcc_state;
753 BufferedFile *bf = file;
754 if (bf->fd > 0) {
755 close(bf->fd);
756 total_lines += bf->line_num - 1;
758 if (bf->true_filename != bf->filename)
759 tcc_free(bf->true_filename);
760 file = bf->prev;
761 tcc_free(bf);
764 static int _tcc_open(TCCState *s1, const char *filename)
766 int fd;
767 if (strcmp(filename, "-") == 0)
768 fd = 0, filename = "<stdin>";
769 else
770 fd = open(filename, O_RDONLY | O_BINARY);
771 if ((s1->verbose == 2 && fd >= 0) || s1->verbose == 3)
772 printf("%s %*s%s\n", fd < 0 ? "nf":"->",
773 (int)(s1->include_stack_ptr - s1->include_stack), "", filename);
774 return fd;
777 ST_FUNC int tcc_open(TCCState *s1, const char *filename)
779 int fd = _tcc_open(s1, filename);
780 if (fd < 0)
781 return -1;
782 tcc_open_bf(s1, filename, 0);
783 file->fd = fd;
784 return 0;
787 /* compile the file opened in 'file'. Return non zero if errors. */
788 static int tcc_compile(TCCState *s1, int filetype, const char *str, int fd)
790 /* Here we enter the code section where we use the global variables for
791 parsing and code generation (tccpp.c, tccgen.c, <target>-gen.c).
792 Other threads need to wait until we're done.
794 Alternatively we could use thread local storage for those global
795 variables, which may or may not have advantages */
797 tcc_enter_state(s1);
798 s1->error_set_jmp_enabled = 1;
800 if (setjmp(s1->error_jmp_buf) == 0) {
801 s1->nb_errors = 0;
803 if (fd == -1) {
804 int len = strlen(str);
805 tcc_open_bf(s1, "<string>", len);
806 memcpy(file->buffer, str, len);
807 } else {
808 tcc_open_bf(s1, str, 0);
809 file->fd = fd;
812 preprocess_start(s1, filetype);
813 tccgen_init(s1);
815 if (s1->output_type == TCC_OUTPUT_PREPROCESS) {
816 tcc_preprocess(s1);
817 } else {
818 tccelf_begin_file(s1);
819 if (filetype & (AFF_TYPE_ASM | AFF_TYPE_ASMPP)) {
820 tcc_assemble(s1, !!(filetype & AFF_TYPE_ASMPP));
821 } else {
822 tccgen_compile(s1);
824 tccelf_end_file(s1);
827 tccgen_finish(s1);
828 preprocess_end(s1);
829 s1->error_set_jmp_enabled = 0;
830 tcc_exit_state(s1);
831 return s1->nb_errors != 0 ? -1 : 0;
834 LIBTCCAPI int tcc_compile_string(TCCState *s, const char *str)
836 return tcc_compile(s, s->filetype, str, -1);
839 /* define a preprocessor symbol. value can be NULL, sym can be "sym=val" */
840 LIBTCCAPI void tcc_define_symbol(TCCState *s1, const char *sym, const char *value)
842 const char *eq;
843 if (NULL == (eq = strchr(sym, '=')))
844 eq = strchr(sym, 0);
845 if (NULL == value)
846 value = *eq ? eq + 1 : "1";
847 cstr_printf(&s1->cmdline_defs, "#define %.*s %s\n", (int)(eq-sym), sym, value);
850 /* undefine a preprocessor symbol */
851 LIBTCCAPI void tcc_undefine_symbol(TCCState *s1, const char *sym)
853 cstr_printf(&s1->cmdline_defs, "#undef %s\n", sym);
857 LIBTCCAPI TCCState *tcc_new(void)
859 TCCState *s;
861 s = tcc_mallocz(sizeof(TCCState));
862 if (!s)
863 return NULL;
864 #ifdef MEM_DEBUG
865 tcc_memcheck(1);
866 #endif
868 #undef gnu_ext
870 s->gnu_ext = 1;
871 s->tcc_ext = 1;
872 s->nocommon = 1;
873 s->dollars_in_identifiers = 1; /*on by default like in gcc/clang*/
874 s->cversion = 199901; /* default unless -std=c11 is supplied */
875 s->warn_implicit_function_declaration = 1;
876 s->warn_discarded_qualifiers = 1;
877 s->ms_extensions = 1;
879 #ifdef CHAR_IS_UNSIGNED
880 s->char_is_unsigned = 1;
881 #endif
882 #ifdef TCC_TARGET_I386
883 s->seg_size = 32;
884 #endif
885 /* enable this if you want symbols with leading underscore on windows: */
886 #if defined TCC_TARGET_MACHO /* || defined TCC_TARGET_PE */
887 s->leading_underscore = 1;
888 #endif
889 #ifdef TCC_TARGET_ARM
890 s->float_abi = ARM_FLOAT_ABI;
891 #endif
892 #ifdef CONFIG_NEW_DTAGS
893 s->enable_new_dtags = 1;
894 #endif
895 s->ppfp = stdout;
896 /* might be used in error() before preprocess_start() */
897 s->include_stack_ptr = s->include_stack;
899 tcc_set_lib_path(s, CONFIG_TCCDIR);
900 return s;
903 LIBTCCAPI void tcc_delete(TCCState *s1)
905 /* free sections */
906 tccelf_delete(s1);
908 /* free library paths */
909 dynarray_reset(&s1->library_paths, &s1->nb_library_paths);
910 dynarray_reset(&s1->crt_paths, &s1->nb_crt_paths);
912 /* free include paths */
913 dynarray_reset(&s1->include_paths, &s1->nb_include_paths);
914 dynarray_reset(&s1->sysinclude_paths, &s1->nb_sysinclude_paths);
916 tcc_free(s1->tcc_lib_path);
917 tcc_free(s1->soname);
918 tcc_free(s1->rpath);
919 tcc_free(s1->elf_entryname);
920 tcc_free(s1->init_symbol);
921 tcc_free(s1->fini_symbol);
922 tcc_free(s1->mapfile);
923 tcc_free(s1->outfile);
924 tcc_free(s1->deps_outfile);
925 #if defined TCC_TARGET_MACHO
926 tcc_free(s1->install_name);
927 #endif
928 dynarray_reset(&s1->files, &s1->nb_files);
929 dynarray_reset(&s1->target_deps, &s1->nb_target_deps);
930 dynarray_reset(&s1->pragma_libs, &s1->nb_pragma_libs);
931 dynarray_reset(&s1->argv, &s1->argc);
932 cstr_free(&s1->cmdline_defs);
933 cstr_free(&s1->cmdline_incl);
934 cstr_free(&s1->linker_arg);
935 #ifdef TCC_IS_NATIVE
936 /* free runtime memory */
937 tcc_run_free(s1);
938 #endif
939 tcc_free(s1->dState);
940 tcc_free(s1);
941 #ifdef MEM_DEBUG
942 tcc_memcheck(-1);
943 #endif
946 LIBTCCAPI int tcc_set_output_type(TCCState *s, int output_type)
948 #ifdef CONFIG_TCC_PIE
949 if (output_type == TCC_OUTPUT_EXE)
950 output_type |= TCC_OUTPUT_DYN;
951 #endif
952 s->output_type = output_type;
954 if (!s->nostdinc) {
955 /* default include paths */
956 /* -isystem paths have already been handled */
957 tcc_add_sysinclude_path(s, CONFIG_TCC_SYSINCLUDEPATHS);
960 if (output_type == TCC_OUTPUT_PREPROCESS) {
961 s->do_debug = 0;
962 return 0;
965 tccelf_new(s);
966 if (s->do_debug) {
967 /* add debug sections */
968 tcc_debug_new(s);
970 #ifdef CONFIG_TCC_BCHECK
971 if (s->do_bounds_check) {
972 /* if bound checking, then add corresponding sections */
973 tccelf_bounds_new(s);
975 #endif
977 if (output_type == TCC_OUTPUT_OBJ) {
978 /* always elf for objects */
979 s->output_format = TCC_OUTPUT_FORMAT_ELF;
980 return 0;
983 tcc_add_library_path(s, CONFIG_TCC_LIBPATHS);
985 #ifdef TCC_TARGET_PE
986 # ifdef _WIN32
987 /* allow linking with system dll's directly */
988 tcc_add_systemdir(s);
989 # endif
990 /* target PE has its own startup code in libtcc1.a */
991 return 0;
993 #elif defined TCC_TARGET_MACHO
994 # ifdef TCC_IS_NATIVE
995 tcc_add_macos_sdkpath(s);
996 # endif
997 /* Mach-O with LC_MAIN doesn't need any crt startup code. */
998 return 0;
1000 #else
1001 /* paths for crt objects */
1002 tcc_split_path(s, &s->crt_paths, &s->nb_crt_paths, CONFIG_TCC_CRTPREFIX);
1004 /* add libc crt1/crti objects */
1005 if (output_type != TCC_OUTPUT_MEMORY && !s->nostdlib) {
1006 #if TARGETOS_OpenBSD
1007 if (output_type != TCC_OUTPUT_DLL)
1008 tcc_add_crt(s, "crt0.o");
1009 if (output_type == TCC_OUTPUT_DLL)
1010 tcc_add_crt(s, "crtbeginS.o");
1011 else
1012 tcc_add_crt(s, "crtbegin.o");
1013 #elif TARGETOS_FreeBSD
1014 if (output_type != TCC_OUTPUT_DLL)
1015 tcc_add_crt(s, "crt1.o");
1016 tcc_add_crt(s, "crti.o");
1017 if (s->static_link)
1018 tcc_add_crt(s, "crtbeginT.o");
1019 else if (output_type & TCC_OUTPUT_DYN)
1020 tcc_add_crt(s, "crtbeginS.o");
1021 else
1022 tcc_add_crt(s, "crtbegin.o");
1023 #elif TARGETOS_NetBSD
1024 if (output_type != TCC_OUTPUT_DLL)
1025 tcc_add_crt(s, "crt0.o");
1026 tcc_add_crt(s, "crti.o");
1027 if (s->static_link)
1028 tcc_add_crt(s, "crtbeginT.o");
1029 else if (output_type & TCC_OUTPUT_DYN)
1030 tcc_add_crt(s, "crtbeginS.o");
1031 else
1032 tcc_add_crt(s, "crtbegin.o");
1033 #elif defined TARGETOS_ANDROID
1034 if (output_type != TCC_OUTPUT_DLL)
1035 tcc_add_crt(s, "crtbegin_dynamic.o");
1036 else
1037 tcc_add_crt(s, "crtbegin_so.o");
1038 #else
1039 if (output_type != TCC_OUTPUT_DLL)
1040 tcc_add_crt(s, "crt1.o");
1041 tcc_add_crt(s, "crti.o");
1042 #endif
1044 return 0;
1045 #endif
1048 LIBTCCAPI int tcc_add_include_path(TCCState *s, const char *pathname)
1050 tcc_split_path(s, &s->include_paths, &s->nb_include_paths, pathname);
1051 return 0;
1054 LIBTCCAPI int tcc_add_sysinclude_path(TCCState *s, const char *pathname)
1056 tcc_split_path(s, &s->sysinclude_paths, &s->nb_sysinclude_paths, pathname);
1057 return 0;
1060 /* add/update a 'DLLReference', Just find if level == -1 */
1061 ST_FUNC DLLReference *tcc_add_dllref(TCCState *s1, const char *dllname, int level)
1063 DLLReference *ref = NULL;
1064 int i;
1065 for (i = 0; i < s1->nb_loaded_dlls; i++)
1066 if (0 == strcmp(s1->loaded_dlls[i]->name, dllname)) {
1067 ref = s1->loaded_dlls[i];
1068 break;
1070 if (level == -1)
1071 return ref;
1072 if (ref) {
1073 if (level < ref->level)
1074 ref->level = level;
1075 ref->found = 1;
1076 return ref;
1078 ref = tcc_mallocz(sizeof(DLLReference) + strlen(dllname));
1079 strcpy(ref->name, dllname);
1080 dynarray_add(&s1->loaded_dlls, &s1->nb_loaded_dlls, ref);
1081 ref->level = level;
1082 ref->index = s1->nb_loaded_dlls;
1083 return ref;
1086 /* OpenBSD: choose latest from libxxx.so.x.y versions */
1087 #if defined TARGETOS_OpenBSD && !defined _WIN32
1088 #include <glob.h>
1089 static int tcc_glob_so(TCCState *s1, const char *pattern, char *buf, int size)
1091 const char *star;
1092 glob_t g;
1093 char *p;
1094 int i, v, v1, v2, v3;
1096 star = strchr(pattern, '*');
1097 if (!star || glob(pattern, 0, NULL, &g))
1098 return -1;
1099 for (v = -1, i = 0; i < g.gl_pathc; ++i) {
1100 p = g.gl_pathv[i];
1101 if (2 != sscanf(p + (star - pattern), "%d.%d.%d", &v1, &v2, &v3))
1102 continue;
1103 if ((v1 = v1 * 1000 + v2) > v)
1104 v = v1, pstrcpy(buf, size, p);
1106 globfree(&g);
1107 return v;
1109 #endif
1111 ST_FUNC int tcc_add_file_internal(TCCState *s1, const char *filename, int flags)
1113 int fd, ret = -1;
1115 #if defined TARGETOS_OpenBSD && !defined _WIN32
1116 char buf[1024];
1117 if (tcc_glob_so(s1, filename, buf, sizeof buf) >= 0)
1118 filename = buf;
1119 #endif
1121 /* ignore binary files with -E */
1122 if (s1->output_type == TCC_OUTPUT_PREPROCESS
1123 && (flags & AFF_TYPE_BIN))
1124 return 0;
1126 /* open the file */
1127 fd = _tcc_open(s1, filename);
1128 if (fd < 0) {
1129 if (flags & AFF_PRINT_ERROR)
1130 tcc_error_noabort("file '%s' not found", filename);
1131 return ret;
1134 s1->current_filename = filename;
1135 if (flags & AFF_TYPE_BIN) {
1136 ElfW(Ehdr) ehdr;
1137 int obj_type;
1139 obj_type = tcc_object_type(fd, &ehdr);
1140 lseek(fd, 0, SEEK_SET);
1142 switch (obj_type) {
1144 case AFF_BINTYPE_REL:
1145 ret = tcc_load_object_file(s1, fd, 0);
1146 break;
1148 case AFF_BINTYPE_AR:
1149 ret = tcc_load_archive(s1, fd, !(flags & AFF_WHOLE_ARCHIVE));
1150 break;
1152 #ifdef TCC_TARGET_PE
1153 default:
1154 ret = pe_load_file(s1, fd, filename);
1155 goto check_success;
1157 #elif defined TCC_TARGET_MACHO
1158 case AFF_BINTYPE_DYN:
1159 case_dyn_or_tbd:
1160 if (s1->output_type == TCC_OUTPUT_MEMORY) {
1161 #ifdef TCC_IS_NATIVE
1162 void* dl;
1163 const char* soname = filename;
1164 if (obj_type != AFF_BINTYPE_DYN)
1165 soname = macho_tbd_soname(filename);
1166 dl = dlopen(soname, RTLD_GLOBAL | RTLD_LAZY);
1167 if (dl)
1168 tcc_add_dllref(s1, soname, 0)->handle = dl, ret = 0;
1169 if (filename != soname)
1170 tcc_free((void *)soname);
1171 #endif
1172 } else if (obj_type == AFF_BINTYPE_DYN) {
1173 ret = macho_load_dll(s1, fd, filename, (flags & AFF_REFERENCED_DLL) != 0);
1174 } else {
1175 ret = macho_load_tbd(s1, fd, filename, (flags & AFF_REFERENCED_DLL) != 0);
1177 break;
1178 default:
1180 const char *ext = tcc_fileextension(filename);
1181 if (!strcmp(ext, ".tbd"))
1182 goto case_dyn_or_tbd;
1183 if (!strcmp(ext, ".dylib")) {
1184 obj_type = AFF_BINTYPE_DYN;
1185 goto case_dyn_or_tbd;
1187 goto check_success;
1190 #else /* unix */
1191 case AFF_BINTYPE_DYN:
1192 if (s1->output_type == TCC_OUTPUT_MEMORY) {
1193 #ifdef TCC_IS_NATIVE
1194 void* dl = dlopen(filename, RTLD_GLOBAL | RTLD_LAZY);
1195 if (dl)
1196 tcc_add_dllref(s1, filename, 0)->handle = dl, ret = 0;
1197 #endif
1198 } else
1199 ret = tcc_load_dll(s1, fd, filename, (flags & AFF_REFERENCED_DLL) != 0);
1200 break;
1202 default:
1203 /* as GNU ld, consider it is an ld script if not recognized */
1204 ret = tcc_load_ldscript(s1, fd);
1205 goto check_success;
1207 #endif /* pe / macos / unix */
1209 check_success:
1210 if (ret < 0)
1211 tcc_error_noabort("%s: unrecognized file type", filename);
1212 break;
1214 #ifdef TCC_TARGET_COFF
1215 case AFF_BINTYPE_C67:
1216 ret = tcc_load_coff(s1, fd);
1217 break;
1218 #endif
1220 close(fd);
1221 } else {
1222 /* update target deps */
1223 dynarray_add(&s1->target_deps, &s1->nb_target_deps, tcc_strdup(filename));
1224 ret = tcc_compile(s1, flags, filename, fd);
1226 s1->current_filename = NULL;
1227 return ret;
1230 LIBTCCAPI int tcc_add_file(TCCState *s, const char *filename)
1232 int filetype = s->filetype;
1233 if (0 == (filetype & AFF_TYPE_MASK)) {
1234 /* use a file extension to detect a filetype */
1235 const char *ext = tcc_fileextension(filename);
1236 if (ext[0]) {
1237 ext++;
1238 if (!strcmp(ext, "S"))
1239 filetype = AFF_TYPE_ASMPP;
1240 else if (!strcmp(ext, "s"))
1241 filetype = AFF_TYPE_ASM;
1242 else if (!PATHCMP(ext, "c")
1243 || !PATHCMP(ext, "h")
1244 || !PATHCMP(ext, "i"))
1245 filetype = AFF_TYPE_C;
1246 else
1247 filetype |= AFF_TYPE_BIN;
1248 } else {
1249 filetype = AFF_TYPE_C;
1252 return tcc_add_file_internal(s, filename, filetype | AFF_PRINT_ERROR);
1255 LIBTCCAPI int tcc_add_library_path(TCCState *s, const char *pathname)
1257 tcc_split_path(s, &s->library_paths, &s->nb_library_paths, pathname);
1258 return 0;
1261 static int tcc_add_library_internal(TCCState *s, const char *fmt,
1262 const char *filename, int flags, char **paths, int nb_paths)
1264 char buf[1024];
1265 int i;
1267 for(i = 0; i < nb_paths; i++) {
1268 snprintf(buf, sizeof(buf), fmt, paths[i], filename);
1269 if (tcc_add_file_internal(s, buf, flags | AFF_TYPE_BIN) == 0)
1270 return 0;
1272 return -1;
1275 /* find and load a dll. Return non zero if not found */
1276 ST_FUNC int tcc_add_dll(TCCState *s, const char *filename, int flags)
1278 return tcc_add_library_internal(s, "%s/%s", filename, flags,
1279 s->library_paths, s->nb_library_paths);
1282 /* find [cross-]libtcc1.a and tcc helper objects in library path */
1283 ST_FUNC void tcc_add_support(TCCState *s1, const char *filename)
1285 char buf[100];
1286 if (CONFIG_TCC_CROSSPREFIX[0])
1287 filename = strcat(strcpy(buf, CONFIG_TCC_CROSSPREFIX), filename);
1288 if (tcc_add_dll(s1, filename, 0) < 0)
1289 tcc_error_noabort("%s not found", filename);
1292 #if !defined TCC_TARGET_PE && !defined TCC_TARGET_MACHO
1293 ST_FUNC int tcc_add_crt(TCCState *s1, const char *filename)
1295 if (-1 == tcc_add_library_internal(s1, "%s/%s",
1296 filename, 0, s1->crt_paths, s1->nb_crt_paths))
1297 return tcc_error_noabort("file '%s' not found", filename);
1298 return 0;
1300 #endif
1302 /* the library name is the same as the argument of the '-l' option */
1303 LIBTCCAPI int tcc_add_library(TCCState *s, const char *libraryname)
1305 #if defined TCC_TARGET_PE
1306 static const char * const libs[] = { "%s/%s.def", "%s/lib%s.def", "%s/%s.dll", "%s/lib%s.dll", "%s/lib%s.a", NULL };
1307 const char * const *pp = s->static_link ? libs + 4 : libs;
1308 #elif defined TCC_TARGET_MACHO
1309 static const char * const libs[] = { "%s/lib%s.dylib", "%s/lib%s.tbd", "%s/lib%s.a", NULL };
1310 const char * const *pp = s->static_link ? libs + 2 : libs;
1311 #elif defined TARGETOS_OpenBSD
1312 static const char * const libs[] = { "%s/lib%s.so.*", "%s/lib%s.a", NULL };
1313 const char * const *pp = s->static_link ? libs + 1 : libs;
1314 #else
1315 static const char * const libs[] = { "%s/lib%s.so", "%s/lib%s.a", NULL };
1316 const char * const *pp = s->static_link ? libs + 1 : libs;
1317 #endif
1318 int flags = s->filetype & AFF_WHOLE_ARCHIVE;
1319 while (*pp) {
1320 if (0 == tcc_add_library_internal(s, *pp,
1321 libraryname, flags, s->library_paths, s->nb_library_paths))
1322 return 0;
1323 ++pp;
1325 return -1;
1328 PUB_FUNC int tcc_add_library_err(TCCState *s1, const char *libname)
1330 int ret = tcc_add_library(s1, libname);
1331 if (ret < 0)
1332 tcc_error_noabort("library '%s' not found", libname);
1333 return ret;
1336 /* handle #pragma comment(lib,) */
1337 ST_FUNC void tcc_add_pragma_libs(TCCState *s1)
1339 int i;
1340 for (i = 0; i < s1->nb_pragma_libs; i++)
1341 tcc_add_library_err(s1, s1->pragma_libs[i]);
1344 LIBTCCAPI int tcc_add_symbol(TCCState *s1, const char *name, const void *val)
1346 #ifdef TCC_TARGET_PE
1347 /* On x86_64 'val' might not be reachable with a 32bit offset.
1348 So it is handled here as if it were in a DLL. */
1349 pe_putimport(s1, 0, name, (uintptr_t)val);
1350 #else
1351 char buf[256];
1352 if (s1->leading_underscore) {
1353 buf[0] = '_';
1354 pstrcpy(buf + 1, sizeof(buf) - 1, name);
1355 name = buf;
1357 set_global_sym(s1, name, NULL, (addr_t)(uintptr_t)val); /* NULL: SHN_ABS */
1358 #endif
1359 return 0;
1362 LIBTCCAPI void tcc_set_lib_path(TCCState *s, const char *path)
1364 tcc_free(s->tcc_lib_path);
1365 s->tcc_lib_path = tcc_strdup(path);
1368 /********************************************************/
1369 /* options parser */
1371 static int strstart(const char *val, const char **str)
1373 const char *p, *q;
1374 p = *str;
1375 q = val;
1376 while (*q) {
1377 if (*p != *q)
1378 return 0;
1379 p++;
1380 q++;
1382 *str = p;
1383 return 1;
1386 /* Like strstart, but automatically takes into account that ld options can
1388 * - start with double or single dash (e.g. '--soname' or '-soname')
1389 * - arguments can be given as separate or after '=' (e.g. '-Wl,-soname,x.so'
1390 * or '-Wl,-soname=x.so')
1392 * you provide `val` always in 'option[=]' form (no leading -)
1394 static int link_option(const char *str, const char *val, const char **ptr)
1396 const char *p, *q;
1397 int ret;
1399 /* there should be 1 or 2 dashes */
1400 if (*str++ != '-')
1401 return 0;
1402 if (*str == '-')
1403 str++;
1405 /* then str & val should match (potentially up to '=') */
1406 p = str;
1407 q = val;
1409 ret = 1;
1410 if (q[0] == '?') {
1411 ++q;
1412 if (strstart("no-", &p))
1413 ret = -1;
1416 while (*q != '\0' && *q != '=') {
1417 if (*p != *q)
1418 return 0;
1419 p++;
1420 q++;
1423 /* '=' near eos means ',' or '=' is ok */
1424 if (*q == '=') {
1425 if (*p == 0)
1426 *ptr = p;
1427 if (*p != ',' && *p != '=')
1428 return 0;
1429 p++;
1430 } else if (*p) {
1431 return 0;
1433 *ptr = p;
1434 return ret;
1437 static const char *skip_linker_arg(const char **str)
1439 const char *s1 = *str;
1440 const char *s2 = strchr(s1, ',');
1441 *str = s2 ? s2++ : (s2 = s1 + strlen(s1));
1442 return s2;
1445 static void copy_linker_arg(char **pp, const char *s, int sep)
1447 const char *q = s;
1448 char *p = *pp;
1449 int l = 0;
1450 if (p && sep)
1451 p[l = strlen(p)] = sep, ++l;
1452 skip_linker_arg(&q);
1453 pstrncpy(l + (*pp = tcc_realloc(p, q - s + l + 1)), s, q - s);
1456 static void args_parser_add_file(TCCState *s, const char* filename, int filetype)
1458 struct filespec *f = tcc_malloc(sizeof *f + strlen(filename));
1459 f->type = filetype;
1460 strcpy(f->name, filename);
1461 dynarray_add(&s->files, &s->nb_files, f);
1464 /* set linker options */
1465 static int tcc_set_linker(TCCState *s, const char *option)
1467 TCCState *s1 = s;
1468 while (*option) {
1470 const char *p = NULL;
1471 char *end = NULL;
1472 int ignoring = 0;
1473 int ret;
1475 if (link_option(option, "Bsymbolic", &p)) {
1476 s->symbolic = 1;
1477 } else if (link_option(option, "nostdlib", &p)) {
1478 s->nostdlib = 1;
1479 } else if (link_option(option, "e=", &p)
1480 || link_option(option, "entry=", &p)) {
1481 copy_linker_arg(&s->elf_entryname, p, 0);
1482 } else if (link_option(option, "fini=", &p)) {
1483 copy_linker_arg(&s->fini_symbol, p, 0);
1484 ignoring = 1;
1485 } else if (link_option(option, "image-base=", &p)
1486 || link_option(option, "Ttext=", &p)) {
1487 s->text_addr = strtoull(p, &end, 16);
1488 s->has_text_addr = 1;
1489 } else if (link_option(option, "init=", &p)) {
1490 copy_linker_arg(&s->init_symbol, p, 0);
1491 ignoring = 1;
1492 } else if (link_option(option, "Map=", &p)) {
1493 copy_linker_arg(&s->mapfile, p, 0);
1494 ignoring = 1;
1495 } else if (link_option(option, "oformat=", &p)) {
1496 #if defined(TCC_TARGET_PE)
1497 if (strstart("pe-", &p)) {
1498 #elif PTR_SIZE == 8
1499 if (strstart("elf64-", &p)) {
1500 #else
1501 if (strstart("elf32-", &p)) {
1502 #endif
1503 s->output_format = TCC_OUTPUT_FORMAT_ELF;
1504 } else if (!strcmp(p, "binary")) {
1505 s->output_format = TCC_OUTPUT_FORMAT_BINARY;
1506 #ifdef TCC_TARGET_COFF
1507 } else if (!strcmp(p, "coff")) {
1508 s->output_format = TCC_OUTPUT_FORMAT_COFF;
1509 #endif
1510 } else
1511 goto err;
1513 } else if (link_option(option, "as-needed", &p)) {
1514 ignoring = 1;
1515 } else if (link_option(option, "O", &p)) {
1516 ignoring = 1;
1517 } else if (link_option(option, "export-all-symbols", &p)) {
1518 s->rdynamic = 1;
1519 } else if (link_option(option, "export-dynamic", &p)) {
1520 s->rdynamic = 1;
1521 } else if (link_option(option, "rpath=", &p)) {
1522 copy_linker_arg(&s->rpath, p, ':');
1523 } else if (link_option(option, "enable-new-dtags", &p)) {
1524 s->enable_new_dtags = 1;
1525 } else if (link_option(option, "section-alignment=", &p)) {
1526 s->section_align = strtoul(p, &end, 16);
1527 } else if (link_option(option, "soname=", &p)) {
1528 copy_linker_arg(&s->soname, p, 0);
1529 } else if (link_option(option, "install_name=", &p)) {
1530 copy_linker_arg(&s->soname, p, 0);
1531 #ifdef TCC_TARGET_PE
1532 } else if (link_option(option, "large-address-aware", &p)) {
1533 s->pe_characteristics |= 0x20;
1534 } else if (link_option(option, "file-alignment=", &p)) {
1535 s->pe_file_align = strtoul(p, &end, 16);
1536 } else if (link_option(option, "stack=", &p)) {
1537 s->pe_stack_size = strtoul(p, &end, 10);
1538 } else if (link_option(option, "subsystem=", &p)) {
1539 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
1540 if (!strcmp(p, "native")) {
1541 s->pe_subsystem = 1;
1542 } else if (!strcmp(p, "console")) {
1543 s->pe_subsystem = 3;
1544 } else if (!strcmp(p, "gui") || !strcmp(p, "windows")) {
1545 s->pe_subsystem = 2;
1546 } else if (!strcmp(p, "posix")) {
1547 s->pe_subsystem = 7;
1548 } else if (!strcmp(p, "efiapp")) {
1549 s->pe_subsystem = 10;
1550 } else if (!strcmp(p, "efiboot")) {
1551 s->pe_subsystem = 11;
1552 } else if (!strcmp(p, "efiruntime")) {
1553 s->pe_subsystem = 12;
1554 } else if (!strcmp(p, "efirom")) {
1555 s->pe_subsystem = 13;
1556 #elif defined(TCC_TARGET_ARM)
1557 if (!strcmp(p, "wince")) {
1558 s->pe_subsystem = 9;
1559 #endif
1560 } else
1561 goto err;
1562 #endif
1563 #ifdef TCC_TARGET_MACHO
1564 } else if (link_option(option, "all_load", &p)) {
1565 s->filetype |= AFF_WHOLE_ARCHIVE;
1566 } else if (link_option(option, "force_load", &p)) {
1567 s->filetype |= AFF_WHOLE_ARCHIVE;
1568 args_parser_add_file(s, p, AFF_TYPE_LIB | (s->filetype & ~AFF_TYPE_MASK));
1569 s->nb_libraries++;
1570 } else if (link_option(option, "single_module", &p)) {
1571 ignoring = 1;
1572 #endif
1573 } else if (ret = link_option(option, "?whole-archive", &p), ret) {
1574 if (ret > 0)
1575 s->filetype |= AFF_WHOLE_ARCHIVE;
1576 else
1577 s->filetype &= ~AFF_WHOLE_ARCHIVE;
1578 } else if (link_option(option, "z=", &p)) {
1579 ignoring = 1;
1580 } else if (p) {
1581 return 0;
1582 } else {
1583 err:
1584 return tcc_error_noabort("unsupported linker option '%s'", option);
1586 if (ignoring)
1587 tcc_warning_c(warn_unsupported)("unsupported linker option '%s'", option);
1588 option = skip_linker_arg(&p);
1590 return 1;
1593 typedef struct TCCOption {
1594 const char *name;
1595 uint16_t index;
1596 uint16_t flags;
1597 } TCCOption;
1599 enum {
1600 TCC_OPTION_ignored = 0,
1601 TCC_OPTION_HELP,
1602 TCC_OPTION_HELP2,
1603 TCC_OPTION_v,
1604 TCC_OPTION_I,
1605 TCC_OPTION_D,
1606 TCC_OPTION_U,
1607 TCC_OPTION_P,
1608 TCC_OPTION_L,
1609 TCC_OPTION_B,
1610 TCC_OPTION_l,
1611 TCC_OPTION_bench,
1612 TCC_OPTION_bt,
1613 TCC_OPTION_b,
1614 TCC_OPTION_ba,
1615 TCC_OPTION_g,
1616 TCC_OPTION_c,
1617 TCC_OPTION_dumpversion,
1618 TCC_OPTION_d,
1619 TCC_OPTION_static,
1620 TCC_OPTION_std,
1621 TCC_OPTION_shared,
1622 TCC_OPTION_soname,
1623 TCC_OPTION_o,
1624 TCC_OPTION_r,
1625 TCC_OPTION_Wl,
1626 TCC_OPTION_Wp,
1627 TCC_OPTION_W,
1628 TCC_OPTION_O,
1629 TCC_OPTION_mfloat_abi,
1630 TCC_OPTION_m,
1631 TCC_OPTION_f,
1632 TCC_OPTION_isystem,
1633 TCC_OPTION_iwithprefix,
1634 TCC_OPTION_include,
1635 TCC_OPTION_nostdinc,
1636 TCC_OPTION_nostdlib,
1637 TCC_OPTION_print_search_dirs,
1638 TCC_OPTION_rdynamic,
1639 TCC_OPTION_pthread,
1640 TCC_OPTION_run,
1641 TCC_OPTION_w,
1642 TCC_OPTION_E,
1643 TCC_OPTION_M,
1644 TCC_OPTION_MD,
1645 TCC_OPTION_MF,
1646 TCC_OPTION_MM,
1647 TCC_OPTION_MMD,
1648 TCC_OPTION_x,
1649 TCC_OPTION_ar,
1650 TCC_OPTION_impdef,
1651 TCC_OPTION_dynamiclib,
1652 TCC_OPTION_flat_namespace,
1653 TCC_OPTION_two_levelnamespace,
1654 TCC_OPTION_undefined,
1655 TCC_OPTION_install_name,
1656 TCC_OPTION_compatibility_version ,
1657 TCC_OPTION_current_version,
1660 #define TCC_OPTION_HAS_ARG 0x0001
1661 #define TCC_OPTION_NOSEP 0x0002 /* cannot have space before option and arg */
1663 static const TCCOption tcc_options[] = {
1664 { "h", TCC_OPTION_HELP, 0 },
1665 { "-help", TCC_OPTION_HELP, 0 },
1666 { "?", TCC_OPTION_HELP, 0 },
1667 { "hh", TCC_OPTION_HELP2, 0 },
1668 { "v", TCC_OPTION_v, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1669 { "-version", TCC_OPTION_v, 0 }, /* handle as verbose, also prints version*/
1670 { "I", TCC_OPTION_I, TCC_OPTION_HAS_ARG },
1671 { "D", TCC_OPTION_D, TCC_OPTION_HAS_ARG },
1672 { "U", TCC_OPTION_U, TCC_OPTION_HAS_ARG },
1673 { "P", TCC_OPTION_P, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1674 { "L", TCC_OPTION_L, TCC_OPTION_HAS_ARG },
1675 { "B", TCC_OPTION_B, TCC_OPTION_HAS_ARG },
1676 { "l", TCC_OPTION_l, TCC_OPTION_HAS_ARG },
1677 { "bench", TCC_OPTION_bench, 0 },
1678 #ifdef CONFIG_TCC_BACKTRACE
1679 { "bt", TCC_OPTION_bt, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1680 #endif
1681 #ifdef CONFIG_TCC_BCHECK
1682 { "b", TCC_OPTION_b, 0 },
1683 #endif
1684 { "g", TCC_OPTION_g, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1685 #ifdef TCC_TARGET_MACHO
1686 { "compatibility_version", TCC_OPTION_compatibility_version, TCC_OPTION_HAS_ARG },
1687 { "current_version", TCC_OPTION_current_version, TCC_OPTION_HAS_ARG },
1688 #endif
1689 { "c", TCC_OPTION_c, 0 },
1690 #ifdef TCC_TARGET_MACHO
1691 { "dynamiclib", TCC_OPTION_dynamiclib, 0 },
1692 #endif
1693 { "dumpversion", TCC_OPTION_dumpversion, 0},
1694 { "d", TCC_OPTION_d, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1695 { "static", TCC_OPTION_static, 0 },
1696 { "std", TCC_OPTION_std, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1697 { "shared", TCC_OPTION_shared, 0 },
1698 { "soname", TCC_OPTION_soname, TCC_OPTION_HAS_ARG },
1699 { "o", TCC_OPTION_o, TCC_OPTION_HAS_ARG },
1700 { "pthread", TCC_OPTION_pthread, 0},
1701 { "run", TCC_OPTION_run, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1702 { "rdynamic", TCC_OPTION_rdynamic, 0 },
1703 { "r", TCC_OPTION_r, 0 },
1704 { "Wl,", TCC_OPTION_Wl, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1705 { "Wp,", TCC_OPTION_Wp, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1706 { "W", TCC_OPTION_W, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1707 { "O", TCC_OPTION_O, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1708 #ifdef TCC_TARGET_ARM
1709 { "mfloat-abi", TCC_OPTION_mfloat_abi, TCC_OPTION_HAS_ARG },
1710 #endif
1711 { "m", TCC_OPTION_m, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1712 #ifdef TCC_TARGET_MACHO
1713 { "flat_namespace", TCC_OPTION_flat_namespace, 0 },
1714 #endif
1715 { "f", TCC_OPTION_f, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1716 { "isystem", TCC_OPTION_isystem, TCC_OPTION_HAS_ARG },
1717 { "include", TCC_OPTION_include, TCC_OPTION_HAS_ARG },
1718 { "nostdinc", TCC_OPTION_nostdinc, 0 },
1719 { "nostdlib", TCC_OPTION_nostdlib, 0 },
1720 { "print-search-dirs", TCC_OPTION_print_search_dirs, 0 },
1721 { "w", TCC_OPTION_w, 0 },
1722 { "E", TCC_OPTION_E, 0},
1723 { "M", TCC_OPTION_M, 0},
1724 { "MD", TCC_OPTION_MD, 0},
1725 { "MF", TCC_OPTION_MF, TCC_OPTION_HAS_ARG },
1726 { "MM", TCC_OPTION_MM, 0},
1727 { "MMD", TCC_OPTION_MMD, 0},
1728 { "x", TCC_OPTION_x, TCC_OPTION_HAS_ARG },
1729 { "ar", TCC_OPTION_ar, 0},
1730 #ifdef TCC_TARGET_PE
1731 { "impdef", TCC_OPTION_impdef, 0},
1732 #endif
1733 #ifdef TCC_TARGET_MACHO
1734 { "install_name", TCC_OPTION_install_name, TCC_OPTION_HAS_ARG },
1735 { "two_levelnamespace", TCC_OPTION_two_levelnamespace, 0 },
1736 { "undefined", TCC_OPTION_undefined, TCC_OPTION_HAS_ARG },
1737 #endif
1738 /* ignored (silently, except after -Wunsupported) */
1739 { "arch", 0, TCC_OPTION_HAS_ARG},
1740 { "C", 0, 0 },
1741 { "-param", 0, TCC_OPTION_HAS_ARG },
1742 { "pedantic", 0, 0 },
1743 { "pipe", 0, 0 },
1744 { "s", 0, 0 },
1745 { "traditional", 0, 0 },
1746 { NULL, 0, 0 },
1749 typedef struct FlagDef {
1750 uint16_t offset;
1751 uint16_t flags;
1752 const char *name;
1753 } FlagDef;
1755 #define WD_ALL 0x0001 /* warning is activated when using -Wall */
1756 #define FD_INVERT 0x0002 /* invert value before storing */
1758 static const FlagDef options_W[] = {
1759 { offsetof(TCCState, warn_all), WD_ALL, "all" },
1760 { offsetof(TCCState, warn_error), 0, "error" },
1761 { offsetof(TCCState, warn_write_strings), 0, "write-strings" },
1762 { offsetof(TCCState, warn_unsupported), 0, "unsupported" },
1763 { offsetof(TCCState, warn_implicit_function_declaration), WD_ALL, "implicit-function-declaration" },
1764 { offsetof(TCCState, warn_discarded_qualifiers), WD_ALL, "discarded-qualifiers" },
1765 { 0, 0, NULL }
1768 static const FlagDef options_f[] = {
1769 { offsetof(TCCState, char_is_unsigned), 0, "unsigned-char" },
1770 { offsetof(TCCState, char_is_unsigned), FD_INVERT, "signed-char" },
1771 { offsetof(TCCState, nocommon), FD_INVERT, "common" },
1772 { offsetof(TCCState, leading_underscore), 0, "leading-underscore" },
1773 { offsetof(TCCState, ms_extensions), 0, "ms-extensions" },
1774 { offsetof(TCCState, dollars_in_identifiers), 0, "dollars-in-identifiers" },
1775 { offsetof(TCCState, test_coverage), 0, "test-coverage" },
1776 { 0, 0, NULL }
1779 static const FlagDef options_m[] = {
1780 { offsetof(TCCState, ms_bitfields), 0, "ms-bitfields" },
1781 #ifdef TCC_TARGET_X86_64
1782 { offsetof(TCCState, nosse), FD_INVERT, "sse" },
1783 #endif
1784 { 0, 0, NULL }
1787 static int set_flag(TCCState *s, const FlagDef *flags, const char *name)
1789 int value, mask, ret;
1790 const FlagDef *p;
1791 const char *r;
1792 unsigned char *f;
1794 r = name, value = !strstart("no-", &r), mask = 0;
1796 /* when called with options_W, look for -W[no-]error=<option> */
1797 if ((flags->flags & WD_ALL) && strstart("error=", &r))
1798 value = value ? WARN_ON|WARN_ERR : WARN_NOE, mask = WARN_ON;
1800 for (ret = -1, p = flags; p->name; ++p) {
1801 if (ret) {
1802 if (strcmp(r, p->name))
1803 continue;
1804 } else {
1805 if (0 == (p->flags & WD_ALL))
1806 continue;
1809 f = (unsigned char *)s + p->offset;
1810 *f = (*f & mask) | (value ^ !!(p->flags & FD_INVERT));
1812 if (ret) {
1813 ret = 0;
1814 if (strcmp(r, "all"))
1815 break;
1818 return ret;
1821 static int args_parser_make_argv(const char *r, int *argc, char ***argv)
1823 int ret = 0, q, c;
1824 CString str;
1825 for(;;) {
1826 while (c = (unsigned char)*r, c && c <= ' ')
1827 ++r;
1828 if (c == 0)
1829 break;
1830 q = 0;
1831 cstr_new(&str);
1832 while (c = (unsigned char)*r, c) {
1833 ++r;
1834 if (c == '\\' && (*r == '"' || *r == '\\')) {
1835 c = *r++;
1836 } else if (c == '"') {
1837 q = !q;
1838 continue;
1839 } else if (q == 0 && c <= ' ') {
1840 break;
1842 cstr_ccat(&str, c);
1844 cstr_ccat(&str, 0);
1845 //printf("<%s>\n", str.data), fflush(stdout);
1846 dynarray_add(argv, argc, tcc_strdup(str.data));
1847 cstr_free(&str);
1848 ++ret;
1850 return ret;
1853 /* read list file */
1854 static int args_parser_listfile(TCCState *s,
1855 const char *filename, int optind, int *pargc, char ***pargv)
1857 TCCState *s1 = s;
1858 int fd, i;
1859 char *p;
1860 int argc = 0;
1861 char **argv = NULL;
1863 fd = open(filename, O_RDONLY | O_BINARY);
1864 if (fd < 0)
1865 return tcc_error_noabort("listfile '%s' not found", filename);
1867 p = tcc_load_text(fd);
1868 for (i = 0; i < *pargc; ++i)
1869 if (i == optind)
1870 args_parser_make_argv(p, &argc, &argv);
1871 else
1872 dynarray_add(&argv, &argc, tcc_strdup((*pargv)[i]));
1874 tcc_free(p);
1875 dynarray_reset(&s->argv, &s->argc);
1876 *pargc = s->argc = argc, *pargv = s->argv = argv;
1877 return 0;
1880 #if defined TCC_TARGET_MACHO
1881 static uint32_t parse_version(TCCState *s1, const char *version)
1883 uint32_t a = 0;
1884 uint32_t b = 0;
1885 uint32_t c = 0;
1886 char* last;
1888 a = strtoul(version, &last, 10);
1889 if (*last == '.') {
1890 b = strtoul(&last[1], &last, 10);
1891 if (*last == '.')
1892 c = strtoul(&last[1], &last, 10);
1894 if (*last || a > 0xffff || b > 0xff || c > 0xff)
1895 tcc_error_noabort("version a.b.c not correct: %s", version);
1896 return (a << 16) | (b << 8) | c;
1898 #endif
1900 PUB_FUNC int tcc_parse_args(TCCState *s, int *pargc, char ***pargv, int optind)
1902 TCCState *s1 = s;
1903 const TCCOption *popt;
1904 const char *optarg, *r;
1905 const char *run = NULL;
1906 int x;
1907 int tool = 0, arg_start = 0, noaction = optind;
1908 char **argv = *pargv;
1909 int argc = *pargc;
1911 cstr_reset(&s->linker_arg);
1913 while (optind < argc) {
1914 r = argv[optind];
1915 if (r[0] == '@' && r[1] != '\0') {
1916 if (args_parser_listfile(s, r + 1, optind, &argc, &argv))
1917 return -1;
1918 continue;
1920 optind++;
1921 if (tool) {
1922 if (r[0] == '-' && r[1] == 'v' && r[2] == 0)
1923 ++s->verbose;
1924 continue;
1926 reparse:
1927 if (r[0] != '-' || r[1] == '\0') {
1928 args_parser_add_file(s, r, s->filetype);
1929 if (run) {
1930 dorun:
1931 if (tcc_set_options(s, run))
1932 return -1;
1933 arg_start = optind - 1;
1934 break;
1936 continue;
1939 /* allow "tcc files... -run -- args ..." */
1940 if (r[1] == '-' && r[2] == '\0' && run)
1941 goto dorun;
1943 /* find option in table */
1944 for(popt = tcc_options; ; ++popt) {
1945 const char *p1 = popt->name;
1946 const char *r1 = r + 1;
1947 if (p1 == NULL)
1948 return tcc_error_noabort("invalid option -- '%s'", r);
1949 if (!strstart(p1, &r1))
1950 continue;
1951 optarg = r1;
1952 if (popt->flags & TCC_OPTION_HAS_ARG) {
1953 if (*r1 == '\0' && !(popt->flags & TCC_OPTION_NOSEP)) {
1954 if (optind >= argc)
1955 arg_err:
1956 return tcc_error_noabort("argument to '%s' is missing", r);
1957 optarg = argv[optind++];
1959 } else if (*r1 != '\0')
1960 continue;
1961 break;
1964 switch(popt->index) {
1965 case TCC_OPTION_HELP:
1966 x = OPT_HELP;
1967 goto extra_action;
1968 case TCC_OPTION_HELP2:
1969 x = OPT_HELP2;
1970 goto extra_action;
1971 case TCC_OPTION_I:
1972 tcc_add_include_path(s, optarg);
1973 break;
1974 case TCC_OPTION_D:
1975 tcc_define_symbol(s, optarg, NULL);
1976 break;
1977 case TCC_OPTION_U:
1978 tcc_undefine_symbol(s, optarg);
1979 break;
1980 case TCC_OPTION_L:
1981 tcc_add_library_path(s, optarg);
1982 break;
1983 case TCC_OPTION_B:
1984 /* set tcc utilities path (mainly for tcc development) */
1985 tcc_set_lib_path(s, optarg);
1986 ++noaction;
1987 break;
1988 case TCC_OPTION_l:
1989 args_parser_add_file(s, optarg, AFF_TYPE_LIB | (s->filetype & ~AFF_TYPE_MASK));
1990 s->nb_libraries++;
1991 break;
1992 case TCC_OPTION_pthread:
1993 s->option_pthread = 1;
1994 break;
1995 case TCC_OPTION_bench:
1996 s->do_bench = 1;
1997 break;
1998 #ifdef CONFIG_TCC_BACKTRACE
1999 case TCC_OPTION_bt:
2000 s->rt_num_callers = atoi(optarg);
2001 s->do_backtrace = 1;
2002 s->do_debug = 1;
2003 s->dwarf = DWARF_VERSION;
2004 break;
2005 #endif
2006 #ifdef CONFIG_TCC_BCHECK
2007 case TCC_OPTION_b:
2008 s->do_bounds_check = 1;
2009 s->do_backtrace = 1;
2010 s->do_debug = 1;
2011 s->dwarf = DWARF_VERSION;
2012 break;
2013 #endif
2014 case TCC_OPTION_g:
2015 s->do_debug = 1;
2016 s->dwarf = DWARF_VERSION;
2018 if (strstart("dwarf", &optarg))
2019 s->dwarf = (*optarg) ? (0 - atoi(optarg)) : DEFAULT_DWARF_VERSION;
2020 break;
2021 case TCC_OPTION_c:
2022 x = TCC_OUTPUT_OBJ;
2023 set_output_type:
2024 if (s->output_type)
2025 tcc_warning("-%s: overriding compiler action already specified", popt->name);
2026 s->output_type = x;
2027 break;
2028 case TCC_OPTION_d:
2029 if (*optarg == 'D')
2030 s->dflag = 3;
2031 else if (*optarg == 'M')
2032 s->dflag = 7;
2033 else if (*optarg == 't')
2034 s->dflag = 16;
2035 else if (isnum(*optarg))
2036 s->g_debug |= atoi(optarg);
2037 else
2038 goto unsupported_option;
2039 break;
2040 case TCC_OPTION_static:
2041 s->static_link = 1;
2042 break;
2043 case TCC_OPTION_std:
2044 if (strcmp(optarg, "=c11") == 0)
2045 s->cversion = 201112;
2046 break;
2047 case TCC_OPTION_shared:
2048 x = TCC_OUTPUT_DLL;
2049 goto set_output_type;
2050 case TCC_OPTION_soname:
2051 s->soname = tcc_strdup(optarg);
2052 break;
2053 case TCC_OPTION_o:
2054 if (s->outfile) {
2055 tcc_warning("multiple -o option");
2056 tcc_free(s->outfile);
2058 s->outfile = tcc_strdup(optarg);
2059 break;
2060 case TCC_OPTION_r:
2061 /* generate a .o merging several output files */
2062 s->option_r = 1;
2063 x = TCC_OUTPUT_OBJ;
2064 goto set_output_type;
2065 case TCC_OPTION_isystem:
2066 tcc_add_sysinclude_path(s, optarg);
2067 break;
2068 case TCC_OPTION_include:
2069 cstr_printf(&s->cmdline_incl, "#include \"%s\"\n", optarg);
2070 break;
2071 case TCC_OPTION_nostdinc:
2072 s->nostdinc = 1;
2073 break;
2074 case TCC_OPTION_nostdlib:
2075 s->nostdlib = 1;
2076 break;
2077 case TCC_OPTION_run:
2078 #ifndef TCC_IS_NATIVE
2079 return tcc_error_noabort("-run is not available in a cross compiler");
2080 #else
2081 run = optarg;
2082 x = TCC_OUTPUT_MEMORY;
2083 goto set_output_type;
2084 #endif
2085 case TCC_OPTION_v:
2086 do ++s->verbose; while (*optarg++ == 'v');
2087 ++noaction;
2088 break;
2089 case TCC_OPTION_f:
2090 if (set_flag(s, options_f, optarg) < 0)
2091 goto unsupported_option;
2092 break;
2093 #ifdef TCC_TARGET_ARM
2094 case TCC_OPTION_mfloat_abi:
2095 /* tcc doesn't support soft float yet */
2096 if (!strcmp(optarg, "softfp")) {
2097 s->float_abi = ARM_SOFTFP_FLOAT;
2098 } else if (!strcmp(optarg, "hard"))
2099 s->float_abi = ARM_HARD_FLOAT;
2100 else
2101 return tcc_error_noabort("unsupported float abi '%s'", optarg);
2102 break;
2103 #endif
2104 case TCC_OPTION_m:
2105 if (set_flag(s, options_m, optarg) < 0) {
2106 if (x = atoi(optarg), x != 32 && x != 64)
2107 goto unsupported_option;
2108 if (PTR_SIZE != x/8)
2109 return x;
2110 ++noaction;
2112 break;
2113 case TCC_OPTION_W:
2114 s->warn_none = 0;
2115 if (optarg[0] && set_flag(s, options_W, optarg) < 0)
2116 goto unsupported_option;
2117 break;
2118 case TCC_OPTION_w:
2119 s->warn_none = 1;
2120 break;
2121 case TCC_OPTION_rdynamic:
2122 s->rdynamic = 1;
2123 break;
2124 case TCC_OPTION_Wl:
2125 if (s->linker_arg.size)
2126 ((char*)s->linker_arg.data)[s->linker_arg.size - 1] = ',';
2127 cstr_cat(&s->linker_arg, optarg, 0);
2128 x = tcc_set_linker(s, s->linker_arg.data);
2129 if (x)
2130 cstr_reset(&s->linker_arg);
2131 if (x < 0)
2132 return -1;
2133 break;
2134 case TCC_OPTION_Wp:
2135 r = optarg;
2136 goto reparse;
2137 case TCC_OPTION_E:
2138 x = TCC_OUTPUT_PREPROCESS;
2139 goto set_output_type;
2140 case TCC_OPTION_P:
2141 s->Pflag = atoi(optarg) + 1;
2142 break;
2143 case TCC_OPTION_M:
2144 s->include_sys_deps = 1;
2145 // fall through
2146 case TCC_OPTION_MM:
2147 s->just_deps = 1;
2148 if(!s->deps_outfile)
2149 s->deps_outfile = tcc_strdup("-");
2150 // fall through
2151 case TCC_OPTION_MMD:
2152 s->gen_deps = 1;
2153 break;
2154 case TCC_OPTION_MD:
2155 s->gen_deps = 1;
2156 s->include_sys_deps = 1;
2157 break;
2158 case TCC_OPTION_MF:
2159 s->deps_outfile = tcc_strdup(optarg);
2160 break;
2161 case TCC_OPTION_dumpversion:
2162 printf ("%s\n", TCC_VERSION);
2163 exit(0);
2164 break;
2165 case TCC_OPTION_x:
2166 x = 0;
2167 if (*optarg == 'c')
2168 x = AFF_TYPE_C;
2169 else if (*optarg == 'a')
2170 x = AFF_TYPE_ASMPP;
2171 else if (*optarg == 'b')
2172 x = AFF_TYPE_BIN;
2173 else if (*optarg == 'n')
2174 x = AFF_TYPE_NONE;
2175 else
2176 tcc_warning("unsupported language '%s'", optarg);
2177 s->filetype = x | (s->filetype & ~AFF_TYPE_MASK);
2178 break;
2179 case TCC_OPTION_O:
2180 s->optimize = atoi(optarg);
2181 break;
2182 case TCC_OPTION_print_search_dirs:
2183 x = OPT_PRINT_DIRS;
2184 goto extra_action;
2185 case TCC_OPTION_impdef:
2186 x = OPT_IMPDEF;
2187 goto extra_action;
2188 #if defined TCC_TARGET_MACHO
2189 case TCC_OPTION_dynamiclib:
2190 x = TCC_OUTPUT_DLL;
2191 goto set_output_type;
2192 case TCC_OPTION_flat_namespace:
2193 break;
2194 case TCC_OPTION_two_levelnamespace:
2195 break;
2196 case TCC_OPTION_undefined:
2197 break;
2198 case TCC_OPTION_install_name:
2199 s->install_name = tcc_strdup(optarg);
2200 break;
2201 case TCC_OPTION_compatibility_version:
2202 s->compatibility_version = parse_version(s, optarg);
2203 break;
2204 case TCC_OPTION_current_version:
2205 s->current_version = parse_version(s, optarg);;
2206 break;
2207 #endif
2208 case TCC_OPTION_ar:
2209 x = OPT_AR;
2210 extra_action:
2211 arg_start = optind - 1;
2212 if (arg_start != noaction)
2213 return tcc_error_noabort("cannot parse %s here", r);
2214 tool = x;
2215 break;
2216 default:
2217 unsupported_option:
2218 tcc_warning_c(warn_unsupported)("unsupported option '%s'", r);
2219 break;
2222 if (s->linker_arg.size) {
2223 r = s->linker_arg.data;
2224 goto arg_err;
2226 *pargc = argc - arg_start;
2227 *pargv = argv + arg_start;
2228 if (tool)
2229 return tool;
2230 if (optind != noaction)
2231 return 0;
2232 if (s->verbose == 2)
2233 return OPT_PRINT_DIRS;
2234 if (s->verbose)
2235 return OPT_V;
2236 return OPT_HELP;
2239 LIBTCCAPI int tcc_set_options(TCCState *s, const char *r)
2241 char **argv = NULL;
2242 int argc = 0, ret;
2243 args_parser_make_argv(r, &argc, &argv);
2244 ret = tcc_parse_args(s, &argc, &argv, 0);
2245 dynarray_reset(&argv, &argc);
2246 return ret < 0 ? ret : 0;
2249 PUB_FUNC void tcc_print_stats(TCCState *s1, unsigned total_time)
2251 if (!total_time)
2252 total_time = 1;
2253 fprintf(stderr, "# %d idents, %d lines, %u bytes\n"
2254 "# %0.3f s, %u lines/s, %0.1f MB/s\n",
2255 total_idents, total_lines, total_bytes,
2256 (double)total_time/1000,
2257 (unsigned)total_lines*1000/total_time,
2258 (double)total_bytes/1000/total_time);
2259 fprintf(stderr, "# text %u, data.rw %u, data.ro %u, bss %u bytes\n",
2260 s1->total_output[0],
2261 s1->total_output[1],
2262 s1->total_output[2],
2263 s1->total_output[3]
2265 #ifdef MEM_DEBUG
2266 fprintf(stderr, "# %d bytes memory used\n", mem_max_size);
2267 #endif