tccrun: resign from "advanced" system calls (memaligh/gettid)
[tinycc.git] / libtcc.c
blob6d720e7463a88f0ffdf18de8c1cd50839d6444ae
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 #define TCC_SEM_IMPL 1
64 #include "tcc.h"
66 /********************************************************/
67 /* global variables */
69 /* XXX: get rid of this ASAP (or maybe not) */
70 ST_DATA struct TCCState *tcc_state;
71 TCC_SEM(static tcc_compile_sem);
72 /* an array of pointers to memory to be free'd after errors */
73 ST_DATA void** stk_data;
74 ST_DATA int nb_stk_data;
76 /********************************************************/
77 #ifdef _WIN32
78 ST_FUNC char *normalize_slashes(char *path)
80 char *p;
81 for (p = path; *p; ++p)
82 if (*p == '\\')
83 *p = '/';
84 return path;
87 #if defined LIBTCC_AS_DLL && !defined CONFIG_TCCDIR
88 static HMODULE tcc_module;
89 BOOL WINAPI DllMain (HINSTANCE hDll, DWORD dwReason, LPVOID lpReserved)
91 if (DLL_PROCESS_ATTACH == dwReason)
92 tcc_module = hDll;
93 return TRUE;
95 #else
96 #define tcc_module NULL /* NULL means executable itself */
97 #endif
99 #ifndef CONFIG_TCCDIR
100 /* on win32, we suppose the lib and includes are at the location of 'tcc.exe' */
101 static inline char *config_tccdir_w32(char *path)
103 char *p;
104 GetModuleFileName(tcc_module, path, MAX_PATH);
105 p = tcc_basename(normalize_slashes(strlwr(path)));
106 if (p > path)
107 --p;
108 *p = 0;
109 return path;
111 #define CONFIG_TCCDIR config_tccdir_w32(alloca(MAX_PATH))
112 #endif
114 #ifdef TCC_IS_NATIVE
115 static void tcc_add_systemdir(TCCState *s)
117 char buf[1000];
118 GetSystemDirectory(buf, sizeof buf);
119 tcc_add_library_path(s, normalize_slashes(buf));
121 #endif
122 #endif
124 /********************************************************/
126 PUB_FUNC void tcc_enter_state(TCCState *s1)
128 if (s1->error_set_jmp_enabled)
129 return;
130 WAIT_SEM(&tcc_compile_sem);
131 tcc_state = s1;
134 PUB_FUNC void tcc_exit_state(TCCState *s1)
136 if (s1->error_set_jmp_enabled)
137 return;
138 tcc_state = NULL;
139 POST_SEM(&tcc_compile_sem);
142 /********************************************************/
143 /* copy a string and truncate it. */
144 ST_FUNC char *pstrcpy(char *buf, size_t buf_size, const char *s)
146 char *q, *q_end;
147 int c;
149 if (buf_size > 0) {
150 q = buf;
151 q_end = buf + buf_size - 1;
152 while (q < q_end) {
153 c = *s++;
154 if (c == '\0')
155 break;
156 *q++ = c;
158 *q = '\0';
160 return buf;
163 /* strcat and truncate. */
164 ST_FUNC char *pstrcat(char *buf, size_t buf_size, const char *s)
166 size_t len;
167 len = strlen(buf);
168 if (len < buf_size)
169 pstrcpy(buf + len, buf_size - len, s);
170 return buf;
173 ST_FUNC char *pstrncpy(char *out, const char *in, size_t num)
175 memcpy(out, in, num);
176 out[num] = '\0';
177 return out;
180 /* extract the basename of a file */
181 PUB_FUNC char *tcc_basename(const char *name)
183 char *p = strchr(name, 0);
184 while (p > name && !IS_DIRSEP(p[-1]))
185 --p;
186 return p;
189 /* extract extension part of a file
191 * (if no extension, return pointer to end-of-string)
193 PUB_FUNC char *tcc_fileextension (const char *name)
195 char *b = tcc_basename(name);
196 char *e = strrchr(b, '.');
197 return e ? e : strchr(b, 0);
200 ST_FUNC char *tcc_load_text(int fd)
202 int len = lseek(fd, 0, SEEK_END);
203 char *buf = load_data(fd, 0, len + 1);
204 buf[len] = 0;
205 return buf;
208 /********************************************************/
209 /* memory management */
211 /* we'll need the actual versions for a minute */
212 #undef free
213 #undef realloc
215 static void *default_reallocator(void *ptr, unsigned long size)
217 void *ptr1;
218 if (size == 0) {
219 free(ptr);
220 ptr1 = NULL;
222 else {
223 ptr1 = realloc(ptr, size);
224 if (!ptr1) {
225 fprintf(stderr, "memory full\n");
226 exit (1);
229 return ptr1;
232 ST_FUNC void libc_free(void *ptr)
234 free(ptr);
237 #define free(p) use_tcc_free(p)
238 #define realloc(p, s) use_tcc_realloc(p, s)
240 /* global so that every tcc_alloc()/tcc_free() call doesn't need to be changed */
241 static void *(*reallocator)(void*, unsigned long) = default_reallocator;
243 LIBTCCAPI void tcc_set_realloc(TCCReallocFunc *realloc)
245 reallocator = realloc ? realloc : default_reallocator;
248 /* in case MEM_DEBUG is #defined */
249 #undef tcc_free
250 #undef tcc_malloc
251 #undef tcc_realloc
252 #undef tcc_mallocz
253 #undef tcc_strdup
255 PUB_FUNC void tcc_free(void *ptr)
257 reallocator(ptr, 0);
260 PUB_FUNC void *tcc_malloc(unsigned long size)
262 return reallocator(0, size);
265 PUB_FUNC void *tcc_realloc(void *ptr, unsigned long size)
267 return reallocator(ptr, size);
270 PUB_FUNC void *tcc_mallocz(unsigned long size)
272 void *ptr;
273 ptr = tcc_malloc(size);
274 if (size)
275 memset(ptr, 0, size);
276 return ptr;
279 PUB_FUNC char *tcc_strdup(const char *str)
281 char *ptr;
282 ptr = tcc_malloc(strlen(str) + 1);
283 strcpy(ptr, str);
284 return ptr;
287 #ifdef MEM_DEBUG
289 #define MEM_DEBUG_MAGIC1 0xFEEDDEB1
290 #define MEM_DEBUG_MAGIC2 0xFEEDDEB2
291 #define MEM_DEBUG_MAGIC3 0xFEEDDEB3
292 #define MEM_DEBUG_FILE_LEN 40
293 #define MEM_DEBUG_CHECK3(header) \
294 ((mem_debug_header_t*)((char*)header + header->size))->magic3
295 #define MEM_USER_PTR(header) \
296 ((char *)header + offsetof(mem_debug_header_t, magic3))
297 #define MEM_HEADER_PTR(ptr) \
298 (mem_debug_header_t *)((char*)ptr - offsetof(mem_debug_header_t, magic3))
300 struct mem_debug_header {
301 unsigned magic1;
302 unsigned size;
303 struct mem_debug_header *prev;
304 struct mem_debug_header *next;
305 int line_num;
306 char file_name[MEM_DEBUG_FILE_LEN + 1];
307 unsigned magic2;
308 ALIGNED(16) unsigned char magic3[4];
311 typedef struct mem_debug_header mem_debug_header_t;
313 TCC_SEM(static mem_sem);
314 static mem_debug_header_t *mem_debug_chain;
315 static unsigned mem_cur_size;
316 static unsigned mem_max_size;
317 static int nb_states;
319 static mem_debug_header_t *malloc_check(void *ptr, const char *msg)
321 mem_debug_header_t * header = MEM_HEADER_PTR(ptr);
322 if (header->magic1 != MEM_DEBUG_MAGIC1 ||
323 header->magic2 != MEM_DEBUG_MAGIC2 ||
324 read32le(MEM_DEBUG_CHECK3(header)) != MEM_DEBUG_MAGIC3 ||
325 header->size == (unsigned)-1) {
326 fprintf(stderr, "%s check failed\n", msg);
327 if (header->magic1 == MEM_DEBUG_MAGIC1)
328 fprintf(stderr, "%s:%u: block allocated here.\n",
329 header->file_name, header->line_num);
330 exit(1);
332 return header;
335 PUB_FUNC void *tcc_malloc_debug(unsigned long size, const char *file, int line)
337 int ofs;
338 mem_debug_header_t *header;
340 header = tcc_malloc(sizeof(mem_debug_header_t) + size);
341 header->magic1 = MEM_DEBUG_MAGIC1;
342 header->magic2 = MEM_DEBUG_MAGIC2;
343 header->size = size;
344 write32le(MEM_DEBUG_CHECK3(header), MEM_DEBUG_MAGIC3);
345 header->line_num = line;
346 ofs = strlen(file) - MEM_DEBUG_FILE_LEN;
347 strncpy(header->file_name, file + (ofs > 0 ? ofs : 0), MEM_DEBUG_FILE_LEN);
348 header->file_name[MEM_DEBUG_FILE_LEN] = 0;
350 WAIT_SEM(&mem_sem);
351 header->next = mem_debug_chain;
352 header->prev = NULL;
353 if (header->next)
354 header->next->prev = header;
355 mem_debug_chain = header;
356 mem_cur_size += size;
357 if (mem_cur_size > mem_max_size)
358 mem_max_size = mem_cur_size;
359 POST_SEM(&mem_sem);
361 return MEM_USER_PTR(header);
364 PUB_FUNC void tcc_free_debug(void *ptr)
366 mem_debug_header_t *header;
367 if (!ptr)
368 return;
369 header = malloc_check(ptr, "tcc_free");
371 WAIT_SEM(&mem_sem);
372 mem_cur_size -= header->size;
373 header->size = (unsigned)-1;
374 if (header->next)
375 header->next->prev = header->prev;
376 if (header->prev)
377 header->prev->next = header->next;
378 if (header == mem_debug_chain)
379 mem_debug_chain = header->next;
380 POST_SEM(&mem_sem);
381 tcc_free(header);
384 PUB_FUNC void *tcc_mallocz_debug(unsigned long size, const char *file, int line)
386 void *ptr;
387 ptr = tcc_malloc_debug(size,file,line);
388 memset(ptr, 0, size);
389 return ptr;
392 PUB_FUNC void *tcc_realloc_debug(void *ptr, unsigned long size, const char *file, int line)
394 mem_debug_header_t *header;
395 int mem_debug_chain_update = 0;
396 if (!ptr)
397 return tcc_malloc_debug(size, file, line);
398 header = malloc_check(ptr, "tcc_realloc");
400 WAIT_SEM(&mem_sem);
401 mem_cur_size -= header->size;
402 mem_debug_chain_update = (header == mem_debug_chain);
403 header = tcc_realloc(header, sizeof(mem_debug_header_t) + size);
404 header->size = size;
405 write32le(MEM_DEBUG_CHECK3(header), MEM_DEBUG_MAGIC3);
406 if (header->next)
407 header->next->prev = header;
408 if (header->prev)
409 header->prev->next = header;
410 if (mem_debug_chain_update)
411 mem_debug_chain = header;
412 mem_cur_size += size;
413 if (mem_cur_size > mem_max_size)
414 mem_max_size = mem_cur_size;
415 POST_SEM(&mem_sem);
417 return MEM_USER_PTR(header);
420 PUB_FUNC char *tcc_strdup_debug(const char *str, const char *file, int line)
422 char *ptr;
423 ptr = tcc_malloc_debug(strlen(str) + 1, file, line);
424 strcpy(ptr, str);
425 return ptr;
428 PUB_FUNC void tcc_memcheck(int d)
430 WAIT_SEM(&mem_sem);
431 nb_states += d;
432 if (0 == nb_states && mem_cur_size) {
433 mem_debug_header_t *header = mem_debug_chain;
434 fflush(stdout);
435 fprintf(stderr, "MEM_DEBUG: mem_leak= %d bytes, mem_max_size= %d bytes\n",
436 mem_cur_size, mem_max_size);
437 while (header) {
438 fprintf(stderr, "%s:%u: error: %u bytes leaked\n",
439 header->file_name, header->line_num, header->size);
440 header = header->next;
442 fflush(stderr);
443 mem_cur_size = 0;
444 mem_debug_chain = NULL;
445 #if MEM_DEBUG-0 == 2
446 exit(2);
447 #endif
449 POST_SEM(&mem_sem);
452 /* restore the debug versions */
453 #define tcc_free(ptr) tcc_free_debug(ptr)
454 #define tcc_malloc(size) tcc_malloc_debug(size, __FILE__, __LINE__)
455 #define tcc_mallocz(size) tcc_mallocz_debug(size, __FILE__, __LINE__)
456 #define tcc_realloc(ptr,size) tcc_realloc_debug(ptr, size, __FILE__, __LINE__)
457 #define tcc_strdup(str) tcc_strdup_debug(str, __FILE__, __LINE__)
459 #endif /* MEM_DEBUG */
461 #ifdef _WIN32
462 # define realpath(file, buf) _fullpath(buf, file, 260)
463 #endif
465 /* for #pragma once */
466 ST_FUNC int normalized_PATHCMP(const char *f1, const char *f2)
468 char *p1, *p2;
469 int ret = 1;
470 if (!!(p1 = realpath(f1, NULL))) {
471 if (!!(p2 = realpath(f2, NULL))) {
472 ret = PATHCMP(p1, p2);
473 libc_free(p2); /* realpath() requirement */
475 libc_free(p1);
477 return ret;
480 /********************************************************/
481 /* dynarrays */
483 ST_FUNC void dynarray_add(void *ptab, int *nb_ptr, void *data)
485 int nb, nb_alloc;
486 void **pp;
488 nb = *nb_ptr;
489 pp = *(void ***)ptab;
490 /* every power of two we double array size */
491 if ((nb & (nb - 1)) == 0) {
492 if (!nb)
493 nb_alloc = 1;
494 else
495 nb_alloc = nb * 2;
496 pp = tcc_realloc(pp, nb_alloc * sizeof(void *));
497 *(void***)ptab = pp;
499 pp[nb++] = data;
500 *nb_ptr = nb;
503 ST_FUNC void dynarray_reset(void *pp, int *n)
505 void **p;
506 for (p = *(void***)pp; *n; ++p, --*n)
507 if (*p)
508 tcc_free(*p);
509 tcc_free(*(void**)pp);
510 *(void**)pp = NULL;
513 static void tcc_split_path(TCCState *s, void *p_ary, int *p_nb_ary, const char *in)
515 const char *p;
516 do {
517 int c;
518 CString str;
520 cstr_new(&str);
521 for (p = in; c = *p, c != '\0' && c != PATHSEP[0]; ++p) {
522 if (c == '{' && p[1] && p[2] == '}') {
523 c = p[1], p += 2;
524 if (c == 'B')
525 cstr_cat(&str, s->tcc_lib_path, -1);
526 if (c == 'R')
527 cstr_cat(&str, CONFIG_SYSROOT, -1);
528 if (c == 'f' && file) {
529 /* substitute current file's dir */
530 const char *f = file->true_filename;
531 const char *b = tcc_basename(f);
532 if (b > f)
533 cstr_cat(&str, f, b - f - 1);
534 else
535 cstr_cat(&str, ".", 1);
537 } else {
538 cstr_ccat(&str, c);
541 if (str.size) {
542 cstr_ccat(&str, '\0');
543 dynarray_add(p_ary, p_nb_ary, tcc_strdup(str.data));
545 cstr_free(&str);
546 in = p+1;
547 } while (*p);
550 /********************************************************/
551 /* warning / error */
553 /* warn_... option bits */
554 #define WARN_ON 1 /* warning is on (-Woption) */
555 #define WARN_ERR 2 /* warning is an error (-Werror=option) */
556 #define WARN_NOE 4 /* warning is not an error (-Wno-error=option) */
558 /* error1() modes */
559 enum { ERROR_WARN, ERROR_NOABORT, ERROR_ERROR };
561 static void error1(int mode, const char *fmt, va_list ap)
563 BufferedFile **pf, *f;
564 TCCState *s1 = tcc_state;
565 CString cs;
567 tcc_exit_state(s1);
569 if (mode == ERROR_WARN) {
570 if (s1->warn_error)
571 mode = ERROR_ERROR;
572 if (s1->warn_num) {
573 /* handle tcc_warning_c(warn_option)(fmt, ...) */
574 int wopt = *(&s1->warn_none + s1->warn_num);
575 s1->warn_num = 0;
576 if (0 == (wopt & WARN_ON))
577 return;
578 if (wopt & WARN_ERR)
579 mode = ERROR_ERROR;
580 if (wopt & WARN_NOE)
581 mode = ERROR_WARN;
583 if (s1->warn_none)
584 return;
587 cstr_new(&cs);
588 f = NULL;
589 if (s1->error_set_jmp_enabled) { /* we're called while parsing a file */
590 /* use upper file if inline ":asm:" or token ":paste:" */
591 for (f = file; f && f->filename[0] == ':'; f = f->prev)
594 if (f) {
595 for(pf = s1->include_stack; pf < s1->include_stack_ptr; pf++)
596 cstr_printf(&cs, "In file included from %s:%d:\n",
597 (*pf)->filename, (*pf)->line_num - 1);
598 cstr_printf(&cs, "%s:%d: ",
599 f->filename, f->line_num - ((tok_flags & TOK_FLAG_BOL) && !macro_ptr));
600 } else if (s1->current_filename) {
601 cstr_printf(&cs, "%s: ", s1->current_filename);
602 } else {
603 cstr_printf(&cs, "tcc: ");
605 cstr_printf(&cs, mode == ERROR_WARN ? "warning: " : "error: ");
606 if (pp_expr > 1)
607 pp_error(&cs); /* special handler for preprocessor expression errors */
608 else
609 cstr_vprintf(&cs, fmt, ap);
610 if (!s1->error_func) {
611 /* default case: stderr */
612 if (s1 && s1->output_type == TCC_OUTPUT_PREPROCESS && s1->ppfp == stdout)
613 printf("\n"); /* print a newline during tcc -E */
614 fflush(stdout); /* flush -v output */
615 fprintf(stderr, "%s\n", (char*)cs.data);
616 fflush(stderr); /* print error/warning now (win32) */
617 } else {
618 s1->error_func(s1->error_opaque, (char*)cs.data);
620 cstr_free(&cs);
621 if (mode != ERROR_WARN)
622 s1->nb_errors++;
623 if (mode == ERROR_ERROR && s1->error_set_jmp_enabled) {
624 while (nb_stk_data)
625 tcc_free(*(void**)stk_data[--nb_stk_data]);
626 longjmp(s1->error_jmp_buf, 1);
630 LIBTCCAPI void tcc_set_error_func(TCCState *s, void *error_opaque, TCCErrorFunc *error_func)
632 s->error_opaque = error_opaque;
633 s->error_func = error_func;
636 /* error without aborting current compilation */
637 PUB_FUNC int _tcc_error_noabort(const char *fmt, ...)
639 va_list ap;
640 va_start(ap, fmt);
641 error1(ERROR_NOABORT, fmt, ap);
642 va_end(ap);
643 return -1;
646 #undef _tcc_error
647 PUB_FUNC void _tcc_error(const char *fmt, ...)
649 va_list ap;
650 va_start(ap, fmt);
651 error1(ERROR_ERROR, fmt, ap);
652 exit(1);
654 #define _tcc_error use_tcc_error_noabort
656 PUB_FUNC void _tcc_warning(const char *fmt, ...)
658 va_list ap;
659 va_start(ap, fmt);
660 error1(ERROR_WARN, fmt, ap);
661 va_end(ap);
665 /********************************************************/
666 /* I/O layer */
668 ST_FUNC void tcc_open_bf(TCCState *s1, const char *filename, int initlen)
670 BufferedFile *bf;
671 int buflen = initlen ? initlen : IO_BUF_SIZE;
673 bf = tcc_mallocz(sizeof(BufferedFile) + buflen);
674 bf->buf_ptr = bf->buffer;
675 bf->buf_end = bf->buffer + initlen;
676 bf->buf_end[0] = CH_EOB; /* put eob symbol */
677 pstrcpy(bf->filename, sizeof(bf->filename), filename);
678 #ifdef _WIN32
679 normalize_slashes(bf->filename);
680 #endif
681 bf->true_filename = bf->filename;
682 bf->line_num = 1;
683 bf->ifdef_stack_ptr = s1->ifdef_stack_ptr;
684 bf->fd = -1;
685 bf->prev = file;
686 bf->prev_tok_flags = tok_flags;
687 file = bf;
688 tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
691 ST_FUNC void tcc_close(void)
693 TCCState *s1 = tcc_state;
694 BufferedFile *bf = file;
695 if (bf->fd > 0) {
696 close(bf->fd);
697 total_lines += bf->line_num - 1;
699 if (bf->true_filename != bf->filename)
700 tcc_free(bf->true_filename);
701 file = bf->prev;
702 tok_flags = bf->prev_tok_flags;
703 tcc_free(bf);
706 static int _tcc_open(TCCState *s1, const char *filename)
708 int fd;
709 if (strcmp(filename, "-") == 0)
710 fd = 0, filename = "<stdin>";
711 else
712 fd = open(filename, O_RDONLY | O_BINARY);
713 if ((s1->verbose == 2 && fd >= 0) || s1->verbose == 3)
714 printf("%s %*s%s\n", fd < 0 ? "nf":"->",
715 (int)(s1->include_stack_ptr - s1->include_stack), "", filename);
716 return fd;
719 ST_FUNC int tcc_open(TCCState *s1, const char *filename)
721 int fd = _tcc_open(s1, filename);
722 if (fd < 0)
723 return -1;
724 tcc_open_bf(s1, filename, 0);
725 file->fd = fd;
726 return 0;
729 /* compile the file opened in 'file'. Return non zero if errors. */
730 static int tcc_compile(TCCState *s1, int filetype, const char *str, int fd)
732 /* Here we enter the code section where we use the global variables for
733 parsing and code generation (tccpp.c, tccgen.c, <target>-gen.c).
734 Other threads need to wait until we're done.
736 Alternatively we could use thread local storage for those global
737 variables, which may or may not have advantages */
739 tcc_enter_state(s1);
740 s1->error_set_jmp_enabled = 1;
742 if (setjmp(s1->error_jmp_buf) == 0) {
743 s1->nb_errors = 0;
745 if (fd == -1) {
746 int len = strlen(str);
747 tcc_open_bf(s1, "<string>", len);
748 memcpy(file->buffer, str, len);
749 } else {
750 tcc_open_bf(s1, str, 0);
751 file->fd = fd;
754 preprocess_start(s1, filetype);
755 tccgen_init(s1);
757 if (s1->output_type == TCC_OUTPUT_PREPROCESS) {
758 tcc_preprocess(s1);
759 } else {
760 tccelf_begin_file(s1);
761 if (filetype & (AFF_TYPE_ASM | AFF_TYPE_ASMPP)) {
762 tcc_assemble(s1, !!(filetype & AFF_TYPE_ASMPP));
763 } else {
764 tccgen_compile(s1);
766 tccelf_end_file(s1);
769 tccgen_finish(s1);
770 preprocess_end(s1);
771 s1->error_set_jmp_enabled = 0;
772 tcc_exit_state(s1);
773 return s1->nb_errors != 0 ? -1 : 0;
776 LIBTCCAPI int tcc_compile_string(TCCState *s, const char *str)
778 return tcc_compile(s, s->filetype, str, -1);
781 /* define a preprocessor symbol. value can be NULL, sym can be "sym=val" */
782 LIBTCCAPI void tcc_define_symbol(TCCState *s1, const char *sym, const char *value)
784 const char *eq;
785 if (NULL == (eq = strchr(sym, '=')))
786 eq = strchr(sym, 0);
787 if (NULL == value)
788 value = *eq ? eq + 1 : "1";
789 cstr_printf(&s1->cmdline_defs, "#define %.*s %s\n", (int)(eq-sym), sym, value);
792 /* undefine a preprocessor symbol */
793 LIBTCCAPI void tcc_undefine_symbol(TCCState *s1, const char *sym)
795 cstr_printf(&s1->cmdline_defs, "#undef %s\n", sym);
799 LIBTCCAPI TCCState *tcc_new(void)
801 TCCState *s;
803 s = tcc_mallocz(sizeof(TCCState));
804 if (!s)
805 return NULL;
806 #ifdef MEM_DEBUG
807 tcc_memcheck(1);
808 #endif
810 #undef gnu_ext
812 s->gnu_ext = 1;
813 s->tcc_ext = 1;
814 s->nocommon = 1;
815 s->dollars_in_identifiers = 1; /*on by default like in gcc/clang*/
816 s->cversion = 199901; /* default unless -std=c11 is supplied */
817 s->warn_implicit_function_declaration = 1;
818 s->warn_discarded_qualifiers = 1;
819 s->ms_extensions = 1;
821 #ifdef CHAR_IS_UNSIGNED
822 s->char_is_unsigned = 1;
823 #endif
824 #ifdef TCC_TARGET_I386
825 s->seg_size = 32;
826 #endif
827 /* enable this if you want symbols with leading underscore on windows: */
828 #if defined TCC_TARGET_MACHO /* || defined TCC_TARGET_PE */
829 s->leading_underscore = 1;
830 #endif
831 #ifdef TCC_TARGET_ARM
832 s->float_abi = ARM_FLOAT_ABI;
833 #endif
834 #ifdef CONFIG_NEW_DTAGS
835 s->enable_new_dtags = 1;
836 #endif
837 s->ppfp = stdout;
838 /* might be used in error() before preprocess_start() */
839 s->include_stack_ptr = s->include_stack;
841 tcc_set_lib_path(s, CONFIG_TCCDIR);
842 return s;
845 LIBTCCAPI void tcc_delete(TCCState *s1)
847 /* free sections */
848 tccelf_delete(s1);
850 /* free library paths */
851 dynarray_reset(&s1->library_paths, &s1->nb_library_paths);
852 dynarray_reset(&s1->crt_paths, &s1->nb_crt_paths);
854 /* free include paths */
855 dynarray_reset(&s1->include_paths, &s1->nb_include_paths);
856 dynarray_reset(&s1->sysinclude_paths, &s1->nb_sysinclude_paths);
858 tcc_free(s1->tcc_lib_path);
859 tcc_free(s1->soname);
860 tcc_free(s1->rpath);
861 tcc_free(s1->elf_entryname);
862 tcc_free(s1->init_symbol);
863 tcc_free(s1->fini_symbol);
864 tcc_free(s1->mapfile);
865 tcc_free(s1->outfile);
866 tcc_free(s1->deps_outfile);
867 #if defined TCC_TARGET_MACHO
868 tcc_free(s1->install_name);
869 #endif
870 dynarray_reset(&s1->files, &s1->nb_files);
871 dynarray_reset(&s1->target_deps, &s1->nb_target_deps);
872 dynarray_reset(&s1->pragma_libs, &s1->nb_pragma_libs);
873 dynarray_reset(&s1->argv, &s1->argc);
874 cstr_free(&s1->cmdline_defs);
875 cstr_free(&s1->cmdline_incl);
876 cstr_free(&s1->linker_arg);
877 #ifdef TCC_IS_NATIVE
878 /* free runtime memory */
879 tcc_run_free(s1);
880 #endif
881 tcc_free(s1->dState);
882 tcc_free(s1);
883 #ifdef MEM_DEBUG
884 tcc_memcheck(-1);
885 #endif
888 LIBTCCAPI int tcc_set_output_type(TCCState *s, int output_type)
890 #ifdef CONFIG_TCC_PIE
891 if (output_type == TCC_OUTPUT_EXE)
892 output_type |= TCC_OUTPUT_DYN;
893 #endif
894 s->output_type = output_type;
896 if (!s->nostdinc) {
897 /* default include paths */
898 /* -isystem paths have already been handled */
899 tcc_add_sysinclude_path(s, CONFIG_TCC_SYSINCLUDEPATHS);
902 if (output_type == TCC_OUTPUT_PREPROCESS) {
903 s->do_debug = 0;
904 return 0;
907 /* add sections */
908 tccelf_new(s);
910 if (output_type == TCC_OUTPUT_OBJ) {
911 /* always elf for objects */
912 s->output_format = TCC_OUTPUT_FORMAT_ELF;
913 return 0;
916 tcc_add_library_path(s, CONFIG_TCC_LIBPATHS);
918 #ifdef TCC_TARGET_PE
919 # ifdef TCC_IS_NATIVE
920 /* allow linking with system dll's directly */
921 tcc_add_systemdir(s);
922 # endif
923 #elif defined TCC_TARGET_MACHO
924 # ifdef TCC_IS_NATIVE
925 tcc_add_macos_sdkpath(s);
926 # endif
927 #else
928 /* paths for crt objects */
929 tcc_split_path(s, &s->crt_paths, &s->nb_crt_paths, CONFIG_TCC_CRTPREFIX);
930 if (output_type != TCC_OUTPUT_MEMORY && !s->nostdlib)
931 tccelf_add_crtbegin(s);
932 #endif
933 return 0;
936 LIBTCCAPI int tcc_add_include_path(TCCState *s, const char *pathname)
938 tcc_split_path(s, &s->include_paths, &s->nb_include_paths, pathname);
939 return 0;
942 LIBTCCAPI int tcc_add_sysinclude_path(TCCState *s, const char *pathname)
944 tcc_split_path(s, &s->sysinclude_paths, &s->nb_sysinclude_paths, pathname);
945 return 0;
948 /* add/update a 'DLLReference', Just find if level == -1 */
949 ST_FUNC DLLReference *tcc_add_dllref(TCCState *s1, const char *dllname, int level)
951 DLLReference *ref = NULL;
952 int i;
953 for (i = 0; i < s1->nb_loaded_dlls; i++)
954 if (0 == strcmp(s1->loaded_dlls[i]->name, dllname)) {
955 ref = s1->loaded_dlls[i];
956 break;
958 if (level == -1)
959 return ref;
960 if (ref) {
961 if (level < ref->level)
962 ref->level = level;
963 ref->found = 1;
964 return ref;
966 ref = tcc_mallocz(sizeof(DLLReference) + strlen(dllname));
967 strcpy(ref->name, dllname);
968 dynarray_add(&s1->loaded_dlls, &s1->nb_loaded_dlls, ref);
969 ref->level = level;
970 ref->index = s1->nb_loaded_dlls;
971 return ref;
974 /* OpenBSD: choose latest from libxxx.so.x.y versions */
975 #if defined TARGETOS_OpenBSD && !defined _WIN32
976 #include <glob.h>
977 static int tcc_glob_so(TCCState *s1, const char *pattern, char *buf, int size)
979 const char *star;
980 glob_t g;
981 char *p;
982 int i, v, v1, v2, v3;
984 star = strchr(pattern, '*');
985 if (!star || glob(pattern, 0, NULL, &g))
986 return -1;
987 for (v = -1, i = 0; i < g.gl_pathc; ++i) {
988 p = g.gl_pathv[i];
989 if (2 != sscanf(p + (star - pattern), "%d.%d.%d", &v1, &v2, &v3))
990 continue;
991 if ((v1 = v1 * 1000 + v2) > v)
992 v = v1, pstrcpy(buf, size, p);
994 globfree(&g);
995 return v;
997 #endif
999 ST_FUNC int tcc_add_file_internal(TCCState *s1, const char *filename, int flags)
1001 int fd, ret = -1;
1003 #if defined TARGETOS_OpenBSD && !defined _WIN32
1004 char buf[1024];
1005 if (tcc_glob_so(s1, filename, buf, sizeof buf) >= 0)
1006 filename = buf;
1007 #endif
1009 /* ignore binary files with -E */
1010 if (s1->output_type == TCC_OUTPUT_PREPROCESS
1011 && (flags & AFF_TYPE_BIN))
1012 return 0;
1014 /* open the file */
1015 fd = _tcc_open(s1, filename);
1016 if (fd < 0) {
1017 if (flags & AFF_PRINT_ERROR)
1018 tcc_error_noabort("file '%s' not found", filename);
1019 return FILE_NOT_FOUND;
1022 s1->current_filename = filename;
1023 if (flags & AFF_TYPE_BIN) {
1024 ElfW(Ehdr) ehdr;
1025 int obj_type;
1027 obj_type = tcc_object_type(fd, &ehdr);
1028 lseek(fd, 0, SEEK_SET);
1030 switch (obj_type) {
1032 case AFF_BINTYPE_REL:
1033 ret = tcc_load_object_file(s1, fd, 0);
1034 break;
1036 case AFF_BINTYPE_AR:
1037 ret = tcc_load_archive(s1, fd, !(flags & AFF_WHOLE_ARCHIVE));
1038 break;
1040 #ifdef TCC_TARGET_PE
1041 default:
1042 ret = pe_load_file(s1, fd, filename);
1043 goto check_success;
1045 #elif defined TCC_TARGET_MACHO
1046 case AFF_BINTYPE_DYN:
1047 case_dyn_or_tbd:
1048 if (s1->output_type == TCC_OUTPUT_MEMORY) {
1049 #ifdef TCC_IS_NATIVE
1050 void* dl;
1051 const char* soname = filename;
1052 if (obj_type != AFF_BINTYPE_DYN)
1053 soname = macho_tbd_soname(filename);
1054 dl = dlopen(soname, RTLD_GLOBAL | RTLD_LAZY);
1055 if (dl)
1056 tcc_add_dllref(s1, soname, 0)->handle = dl, ret = 0;
1057 if (filename != soname)
1058 tcc_free((void *)soname);
1059 #endif
1060 } else if (obj_type == AFF_BINTYPE_DYN) {
1061 ret = macho_load_dll(s1, fd, filename, (flags & AFF_REFERENCED_DLL) != 0);
1062 } else {
1063 ret = macho_load_tbd(s1, fd, filename, (flags & AFF_REFERENCED_DLL) != 0);
1065 goto check_success;
1066 default:
1068 const char *ext = tcc_fileextension(filename);
1069 if (!strcmp(ext, ".tbd"))
1070 goto case_dyn_or_tbd;
1071 if (!strcmp(ext, ".dylib")) {
1072 obj_type = AFF_BINTYPE_DYN;
1073 goto case_dyn_or_tbd;
1075 goto check_success;
1078 #else /* unix */
1079 case AFF_BINTYPE_DYN:
1080 if (s1->output_type == TCC_OUTPUT_MEMORY) {
1081 #ifdef TCC_IS_NATIVE
1082 void* dl = dlopen(filename, RTLD_GLOBAL | RTLD_LAZY);
1083 if (dl)
1084 tcc_add_dllref(s1, filename, 0)->handle = dl, ret = 0;
1085 #endif
1086 } else
1087 ret = tcc_load_dll(s1, fd, filename, (flags & AFF_REFERENCED_DLL) != 0);
1088 break;
1090 default:
1091 /* as GNU ld, consider it is an ld script if not recognized */
1092 ret = tcc_load_ldscript(s1, fd);
1093 goto check_success;
1095 #endif /* pe / macos / unix */
1097 check_success:
1098 if (ret < 0)
1099 tcc_error_noabort("%s: unrecognized file type", filename);
1100 break;
1102 #ifdef TCC_TARGET_COFF
1103 case AFF_BINTYPE_C67:
1104 ret = tcc_load_coff(s1, fd);
1105 break;
1106 #endif
1108 close(fd);
1109 } else {
1110 /* update target deps */
1111 dynarray_add(&s1->target_deps, &s1->nb_target_deps, tcc_strdup(filename));
1112 ret = tcc_compile(s1, flags, filename, fd);
1114 s1->current_filename = NULL;
1115 return ret;
1118 LIBTCCAPI int tcc_add_file(TCCState *s, const char *filename)
1120 int filetype = s->filetype;
1121 if (0 == (filetype & AFF_TYPE_MASK)) {
1122 /* use a file extension to detect a filetype */
1123 const char *ext = tcc_fileextension(filename);
1124 if (ext[0]) {
1125 ext++;
1126 if (!strcmp(ext, "S"))
1127 filetype = AFF_TYPE_ASMPP;
1128 else if (!strcmp(ext, "s"))
1129 filetype = AFF_TYPE_ASM;
1130 else if (!PATHCMP(ext, "c")
1131 || !PATHCMP(ext, "h")
1132 || !PATHCMP(ext, "i"))
1133 filetype = AFF_TYPE_C;
1134 else
1135 filetype |= AFF_TYPE_BIN;
1136 } else {
1137 filetype = AFF_TYPE_C;
1140 return tcc_add_file_internal(s, filename, filetype | AFF_PRINT_ERROR);
1143 LIBTCCAPI int tcc_add_library_path(TCCState *s, const char *pathname)
1145 tcc_split_path(s, &s->library_paths, &s->nb_library_paths, pathname);
1146 return 0;
1149 static int tcc_add_library_internal(TCCState *s1, const char *fmt,
1150 const char *filename, int flags, char **paths, int nb_paths)
1152 char buf[1024];
1153 int i, ret;
1155 for(i = 0; i < nb_paths; i++) {
1156 snprintf(buf, sizeof(buf), fmt, paths[i], filename);
1157 ret = tcc_add_file_internal(s1, buf, (flags & ~AFF_PRINT_ERROR) | AFF_TYPE_BIN);
1158 if (ret != FILE_NOT_FOUND)
1159 return ret;
1161 if (flags & AFF_PRINT_ERROR)
1162 tcc_error_noabort("file '%s' not found", filename);
1163 return FILE_NOT_FOUND;
1166 /* find and load a dll. Return non zero if not found */
1167 ST_FUNC int tcc_add_dll(TCCState *s, const char *filename, int flags)
1169 return tcc_add_library_internal(s, "%s/%s", filename, flags,
1170 s->library_paths, s->nb_library_paths);
1173 /* find [cross-]libtcc1.a and tcc helper objects in library path */
1174 ST_FUNC void tcc_add_support(TCCState *s1, const char *filename)
1176 char buf[100];
1177 if (CONFIG_TCC_CROSSPREFIX[0])
1178 filename = strcat(strcpy(buf, CONFIG_TCC_CROSSPREFIX), filename);
1179 tcc_add_dll(s1, filename, AFF_PRINT_ERROR);
1182 #if !defined TCC_TARGET_PE && !defined TCC_TARGET_MACHO
1183 ST_FUNC int tcc_add_crt(TCCState *s1, const char *filename)
1185 return tcc_add_library_internal(s1, "%s/%s",
1186 filename, AFF_PRINT_ERROR, s1->crt_paths, s1->nb_crt_paths);
1188 #endif
1190 /* the library name is the same as the argument of the '-l' option */
1191 LIBTCCAPI int tcc_add_library(TCCState *s, const char *libraryname)
1193 #if defined TCC_TARGET_PE
1194 static const char * const libs[] = { "%s/%s.def", "%s/lib%s.def", "%s/%s.dll", "%s/lib%s.dll", "%s/lib%s.a", NULL };
1195 const char * const *pp = s->static_link ? libs + 4 : libs;
1196 #elif defined TCC_TARGET_MACHO
1197 static const char * const libs[] = { "%s/lib%s.dylib", "%s/lib%s.tbd", "%s/lib%s.a", NULL };
1198 const char * const *pp = s->static_link ? libs + 2 : libs;
1199 #elif defined TARGETOS_OpenBSD
1200 static const char * const libs[] = { "%s/lib%s.so.*", "%s/lib%s.a", NULL };
1201 const char * const *pp = s->static_link ? libs + 1 : libs;
1202 #else
1203 static const char * const libs[] = { "%s/lib%s.so", "%s/lib%s.a", NULL };
1204 const char * const *pp = s->static_link ? libs + 1 : libs;
1205 #endif
1206 int flags = s->filetype & AFF_WHOLE_ARCHIVE;
1207 while (*pp) {
1208 int ret = tcc_add_library_internal(s, *pp,
1209 libraryname, flags, s->library_paths, s->nb_library_paths);
1210 if (ret != FILE_NOT_FOUND)
1211 return ret;
1212 ++pp;
1214 return FILE_NOT_FOUND;
1217 PUB_FUNC int tcc_add_library_err(TCCState *s1, const char *libname)
1219 int ret = tcc_add_library(s1, libname);
1220 if (ret == FILE_NOT_FOUND)
1221 tcc_error_noabort("library '%s' not found", libname);
1222 return ret;
1225 /* handle #pragma comment(lib,) */
1226 ST_FUNC void tcc_add_pragma_libs(TCCState *s1)
1228 int i;
1229 for (i = 0; i < s1->nb_pragma_libs; i++)
1230 tcc_add_library_err(s1, s1->pragma_libs[i]);
1233 LIBTCCAPI int tcc_add_symbol(TCCState *s1, const char *name, const void *val)
1235 #ifdef TCC_TARGET_PE
1236 /* On x86_64 'val' might not be reachable with a 32bit offset.
1237 So it is handled here as if it were in a DLL. */
1238 pe_putimport(s1, 0, name, (uintptr_t)val);
1239 #else
1240 char buf[256];
1241 if (s1->leading_underscore) {
1242 buf[0] = '_';
1243 pstrcpy(buf + 1, sizeof(buf) - 1, name);
1244 name = buf;
1246 set_global_sym(s1, name, NULL, (addr_t)(uintptr_t)val); /* NULL: SHN_ABS */
1247 #endif
1248 return 0;
1251 LIBTCCAPI void tcc_set_lib_path(TCCState *s, const char *path)
1253 tcc_free(s->tcc_lib_path);
1254 s->tcc_lib_path = tcc_strdup(path);
1257 /********************************************************/
1258 /* options parser */
1260 static int strstart(const char *val, const char **str)
1262 const char *p, *q;
1263 p = *str;
1264 q = val;
1265 while (*q) {
1266 if (*p != *q)
1267 return 0;
1268 p++;
1269 q++;
1271 *str = p;
1272 return 1;
1275 /* Like strstart, but automatically takes into account that ld options can
1277 * - start with double or single dash (e.g. '--soname' or '-soname')
1278 * - arguments can be given as separate or after '=' (e.g. '-Wl,-soname,x.so'
1279 * or '-Wl,-soname=x.so')
1281 * you provide `val` always in 'option[=]' form (no leading -)
1283 static int link_option(const char *str, const char *val, const char **ptr)
1285 const char *p, *q;
1286 int ret;
1288 /* there should be 1 or 2 dashes */
1289 if (*str++ != '-')
1290 return 0;
1291 if (*str == '-')
1292 str++;
1294 /* then str & val should match (potentially up to '=') */
1295 p = str;
1296 q = val;
1298 ret = 1;
1299 if (q[0] == '?') {
1300 ++q;
1301 if (strstart("no-", &p))
1302 ret = -1;
1305 while (*q != '\0' && *q != '=') {
1306 if (*p != *q)
1307 return 0;
1308 p++;
1309 q++;
1312 /* '=' near eos means ',' or '=' is ok */
1313 if (*q == '=') {
1314 if (*p == 0)
1315 *ptr = p;
1316 if (*p != ',' && *p != '=')
1317 return 0;
1318 p++;
1319 } else if (*p) {
1320 return 0;
1322 *ptr = p;
1323 return ret;
1326 static const char *skip_linker_arg(const char **str)
1328 const char *s1 = *str;
1329 const char *s2 = strchr(s1, ',');
1330 *str = s2 ? s2++ : (s2 = s1 + strlen(s1));
1331 return s2;
1334 static void copy_linker_arg(char **pp, const char *s, int sep)
1336 const char *q = s;
1337 char *p = *pp;
1338 int l = 0;
1339 if (p && sep)
1340 p[l = strlen(p)] = sep, ++l;
1341 skip_linker_arg(&q);
1342 pstrncpy(l + (*pp = tcc_realloc(p, q - s + l + 1)), s, q - s);
1345 static void args_parser_add_file(TCCState *s, const char* filename, int filetype)
1347 struct filespec *f = tcc_malloc(sizeof *f + strlen(filename));
1348 f->type = filetype;
1349 strcpy(f->name, filename);
1350 dynarray_add(&s->files, &s->nb_files, f);
1353 /* set linker options */
1354 static int tcc_set_linker(TCCState *s, const char *option)
1356 TCCState *s1 = s;
1357 while (*option) {
1359 const char *p = NULL;
1360 char *end = NULL;
1361 int ignoring = 0;
1362 int ret;
1364 if (link_option(option, "Bsymbolic", &p)) {
1365 s->symbolic = 1;
1366 } else if (link_option(option, "nostdlib", &p)) {
1367 s->nostdlib = 1;
1368 } else if (link_option(option, "e=", &p)
1369 || link_option(option, "entry=", &p)) {
1370 copy_linker_arg(&s->elf_entryname, p, 0);
1371 } else if (link_option(option, "fini=", &p)) {
1372 copy_linker_arg(&s->fini_symbol, p, 0);
1373 ignoring = 1;
1374 } else if (link_option(option, "image-base=", &p)
1375 || link_option(option, "Ttext=", &p)) {
1376 s->text_addr = strtoull(p, &end, 16);
1377 s->has_text_addr = 1;
1378 } else if (link_option(option, "init=", &p)) {
1379 copy_linker_arg(&s->init_symbol, p, 0);
1380 ignoring = 1;
1381 } else if (link_option(option, "Map=", &p)) {
1382 copy_linker_arg(&s->mapfile, p, 0);
1383 ignoring = 1;
1384 } else if (link_option(option, "oformat=", &p)) {
1385 #if defined(TCC_TARGET_PE)
1386 if (strstart("pe-", &p)) {
1387 #elif PTR_SIZE == 8
1388 if (strstart("elf64-", &p)) {
1389 #else
1390 if (strstart("elf32-", &p)) {
1391 #endif
1392 s->output_format = TCC_OUTPUT_FORMAT_ELF;
1393 } else if (!strcmp(p, "binary")) {
1394 s->output_format = TCC_OUTPUT_FORMAT_BINARY;
1395 #ifdef TCC_TARGET_COFF
1396 } else if (!strcmp(p, "coff")) {
1397 s->output_format = TCC_OUTPUT_FORMAT_COFF;
1398 #endif
1399 } else
1400 goto err;
1402 } else if (link_option(option, "as-needed", &p)) {
1403 ignoring = 1;
1404 } else if (link_option(option, "O", &p)) {
1405 ignoring = 1;
1406 } else if (link_option(option, "export-all-symbols", &p)) {
1407 s->rdynamic = 1;
1408 } else if (link_option(option, "export-dynamic", &p)) {
1409 s->rdynamic = 1;
1410 } else if (link_option(option, "rpath=", &p)) {
1411 copy_linker_arg(&s->rpath, p, ':');
1412 } else if (link_option(option, "enable-new-dtags", &p)) {
1413 s->enable_new_dtags = 1;
1414 } else if (link_option(option, "section-alignment=", &p)) {
1415 s->section_align = strtoul(p, &end, 16);
1416 } else if (link_option(option, "soname=", &p)) {
1417 copy_linker_arg(&s->soname, p, 0);
1418 } else if (link_option(option, "install_name=", &p)) {
1419 copy_linker_arg(&s->soname, p, 0);
1420 #ifdef TCC_TARGET_PE
1421 } else if (link_option(option, "large-address-aware", &p)) {
1422 s->pe_characteristics |= 0x20;
1423 } else if (link_option(option, "file-alignment=", &p)) {
1424 s->pe_file_align = strtoul(p, &end, 16);
1425 } else if (link_option(option, "stack=", &p)) {
1426 s->pe_stack_size = strtoul(p, &end, 10);
1427 } else if (link_option(option, "subsystem=", &p)) {
1428 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
1429 if (!strcmp(p, "native")) {
1430 s->pe_subsystem = 1;
1431 } else if (!strcmp(p, "console")) {
1432 s->pe_subsystem = 3;
1433 } else if (!strcmp(p, "gui") || !strcmp(p, "windows")) {
1434 s->pe_subsystem = 2;
1435 } else if (!strcmp(p, "posix")) {
1436 s->pe_subsystem = 7;
1437 } else if (!strcmp(p, "efiapp")) {
1438 s->pe_subsystem = 10;
1439 } else if (!strcmp(p, "efiboot")) {
1440 s->pe_subsystem = 11;
1441 } else if (!strcmp(p, "efiruntime")) {
1442 s->pe_subsystem = 12;
1443 } else if (!strcmp(p, "efirom")) {
1444 s->pe_subsystem = 13;
1445 #elif defined(TCC_TARGET_ARM)
1446 if (!strcmp(p, "wince")) {
1447 s->pe_subsystem = 9;
1448 #endif
1449 } else
1450 goto err;
1451 #endif
1452 #ifdef TCC_TARGET_MACHO
1453 } else if (link_option(option, "all_load", &p)) {
1454 s->filetype |= AFF_WHOLE_ARCHIVE;
1455 } else if (link_option(option, "force_load", &p)) {
1456 s->filetype |= AFF_WHOLE_ARCHIVE;
1457 args_parser_add_file(s, p, AFF_TYPE_LIB | (s->filetype & ~AFF_TYPE_MASK));
1458 s->nb_libraries++;
1459 } else if (link_option(option, "single_module", &p)) {
1460 ignoring = 1;
1461 #endif
1462 } else if (ret = link_option(option, "?whole-archive", &p), ret) {
1463 if (ret > 0)
1464 s->filetype |= AFF_WHOLE_ARCHIVE;
1465 else
1466 s->filetype &= ~AFF_WHOLE_ARCHIVE;
1467 } else if (link_option(option, "z=", &p)) {
1468 ignoring = 1;
1469 } else if (p) {
1470 return 0;
1471 } else {
1472 err:
1473 return tcc_error_noabort("unsupported linker option '%s'", option);
1475 if (ignoring)
1476 tcc_warning_c(warn_unsupported)("unsupported linker option '%s'", option);
1477 option = skip_linker_arg(&p);
1479 return 1;
1482 typedef struct TCCOption {
1483 const char *name;
1484 uint16_t index;
1485 uint16_t flags;
1486 } TCCOption;
1488 enum {
1489 TCC_OPTION_ignored = 0,
1490 TCC_OPTION_HELP,
1491 TCC_OPTION_HELP2,
1492 TCC_OPTION_v,
1493 TCC_OPTION_I,
1494 TCC_OPTION_D,
1495 TCC_OPTION_U,
1496 TCC_OPTION_P,
1497 TCC_OPTION_L,
1498 TCC_OPTION_B,
1499 TCC_OPTION_l,
1500 TCC_OPTION_bench,
1501 TCC_OPTION_bt,
1502 TCC_OPTION_b,
1503 TCC_OPTION_ba,
1504 TCC_OPTION_g,
1505 TCC_OPTION_c,
1506 TCC_OPTION_dumpmachine,
1507 TCC_OPTION_dumpversion,
1508 TCC_OPTION_d,
1509 TCC_OPTION_static,
1510 TCC_OPTION_std,
1511 TCC_OPTION_shared,
1512 TCC_OPTION_soname,
1513 TCC_OPTION_o,
1514 TCC_OPTION_r,
1515 TCC_OPTION_Wl,
1516 TCC_OPTION_Wp,
1517 TCC_OPTION_W,
1518 TCC_OPTION_O,
1519 TCC_OPTION_mfloat_abi,
1520 TCC_OPTION_m,
1521 TCC_OPTION_f,
1522 TCC_OPTION_isystem,
1523 TCC_OPTION_iwithprefix,
1524 TCC_OPTION_include,
1525 TCC_OPTION_nostdinc,
1526 TCC_OPTION_nostdlib,
1527 TCC_OPTION_print_search_dirs,
1528 TCC_OPTION_rdynamic,
1529 TCC_OPTION_pthread,
1530 TCC_OPTION_run,
1531 TCC_OPTION_w,
1532 TCC_OPTION_E,
1533 TCC_OPTION_M,
1534 TCC_OPTION_MD,
1535 TCC_OPTION_MF,
1536 TCC_OPTION_MM,
1537 TCC_OPTION_MMD,
1538 TCC_OPTION_MP,
1539 TCC_OPTION_x,
1540 TCC_OPTION_ar,
1541 TCC_OPTION_impdef,
1542 TCC_OPTION_dynamiclib,
1543 TCC_OPTION_flat_namespace,
1544 TCC_OPTION_two_levelnamespace,
1545 TCC_OPTION_undefined,
1546 TCC_OPTION_install_name,
1547 TCC_OPTION_compatibility_version ,
1548 TCC_OPTION_current_version,
1551 #define TCC_OPTION_HAS_ARG 0x0001
1552 #define TCC_OPTION_NOSEP 0x0002 /* cannot have space before option and arg */
1554 static const TCCOption tcc_options[] = {
1555 { "h", TCC_OPTION_HELP, 0 },
1556 { "-help", TCC_OPTION_HELP, 0 },
1557 { "?", TCC_OPTION_HELP, 0 },
1558 { "hh", TCC_OPTION_HELP2, 0 },
1559 { "v", TCC_OPTION_v, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1560 { "-version", TCC_OPTION_v, 0 }, /* handle as verbose, also prints version*/
1561 { "I", TCC_OPTION_I, TCC_OPTION_HAS_ARG },
1562 { "D", TCC_OPTION_D, TCC_OPTION_HAS_ARG },
1563 { "U", TCC_OPTION_U, TCC_OPTION_HAS_ARG },
1564 { "P", TCC_OPTION_P, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1565 { "L", TCC_OPTION_L, TCC_OPTION_HAS_ARG },
1566 { "B", TCC_OPTION_B, TCC_OPTION_HAS_ARG },
1567 { "l", TCC_OPTION_l, TCC_OPTION_HAS_ARG },
1568 { "bench", TCC_OPTION_bench, 0 },
1569 #ifdef CONFIG_TCC_BACKTRACE
1570 { "bt", TCC_OPTION_bt, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1571 #endif
1572 #ifdef CONFIG_TCC_BCHECK
1573 { "b", TCC_OPTION_b, 0 },
1574 #endif
1575 { "g", TCC_OPTION_g, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1576 #ifdef TCC_TARGET_MACHO
1577 { "compatibility_version", TCC_OPTION_compatibility_version, TCC_OPTION_HAS_ARG },
1578 { "current_version", TCC_OPTION_current_version, TCC_OPTION_HAS_ARG },
1579 #endif
1580 { "c", TCC_OPTION_c, 0 },
1581 #ifdef TCC_TARGET_MACHO
1582 { "dynamiclib", TCC_OPTION_dynamiclib, 0 },
1583 #endif
1584 { "dumpmachine", TCC_OPTION_dumpmachine, 0},
1585 { "dumpversion", TCC_OPTION_dumpversion, 0},
1586 { "d", TCC_OPTION_d, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1587 { "static", TCC_OPTION_static, 0 },
1588 { "std", TCC_OPTION_std, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1589 { "shared", TCC_OPTION_shared, 0 },
1590 { "soname", TCC_OPTION_soname, TCC_OPTION_HAS_ARG },
1591 { "o", TCC_OPTION_o, TCC_OPTION_HAS_ARG },
1592 { "pthread", TCC_OPTION_pthread, 0},
1593 { "run", TCC_OPTION_run, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1594 { "rdynamic", TCC_OPTION_rdynamic, 0 },
1595 { "r", TCC_OPTION_r, 0 },
1596 { "Wl,", TCC_OPTION_Wl, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1597 { "Wp,", TCC_OPTION_Wp, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1598 { "W", TCC_OPTION_W, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1599 { "O", TCC_OPTION_O, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1600 #ifdef TCC_TARGET_ARM
1601 { "mfloat-abi", TCC_OPTION_mfloat_abi, TCC_OPTION_HAS_ARG },
1602 #endif
1603 { "m", TCC_OPTION_m, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1604 #ifdef TCC_TARGET_MACHO
1605 { "flat_namespace", TCC_OPTION_flat_namespace, 0 },
1606 #endif
1607 { "f", TCC_OPTION_f, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1608 { "isystem", TCC_OPTION_isystem, TCC_OPTION_HAS_ARG },
1609 { "include", TCC_OPTION_include, TCC_OPTION_HAS_ARG },
1610 { "nostdinc", TCC_OPTION_nostdinc, 0 },
1611 { "nostdlib", TCC_OPTION_nostdlib, 0 },
1612 { "print-search-dirs", TCC_OPTION_print_search_dirs, 0 },
1613 { "w", TCC_OPTION_w, 0 },
1614 { "E", TCC_OPTION_E, 0},
1615 { "M", TCC_OPTION_M, 0},
1616 { "MD", TCC_OPTION_MD, 0},
1617 { "MF", TCC_OPTION_MF, TCC_OPTION_HAS_ARG },
1618 { "MM", TCC_OPTION_MM, 0},
1619 { "MMD", TCC_OPTION_MMD, 0},
1620 { "MP", TCC_OPTION_MP, 0},
1621 { "x", TCC_OPTION_x, TCC_OPTION_HAS_ARG },
1622 { "ar", TCC_OPTION_ar, 0},
1623 #ifdef TCC_TARGET_PE
1624 { "impdef", TCC_OPTION_impdef, 0},
1625 #endif
1626 #ifdef TCC_TARGET_MACHO
1627 { "install_name", TCC_OPTION_install_name, TCC_OPTION_HAS_ARG },
1628 { "two_levelnamespace", TCC_OPTION_two_levelnamespace, 0 },
1629 { "undefined", TCC_OPTION_undefined, TCC_OPTION_HAS_ARG },
1630 #endif
1631 /* ignored (silently, except after -Wunsupported) */
1632 { "arch", 0, TCC_OPTION_HAS_ARG},
1633 { "C", 0, 0 },
1634 { "-param", 0, TCC_OPTION_HAS_ARG },
1635 { "pedantic", 0, 0 },
1636 { "pipe", 0, 0 },
1637 { "s", 0, 0 },
1638 { "traditional", 0, 0 },
1639 { NULL, 0, 0 },
1642 typedef struct FlagDef {
1643 uint16_t offset;
1644 uint16_t flags;
1645 const char *name;
1646 } FlagDef;
1648 #define WD_ALL 0x0001 /* warning is activated when using -Wall */
1649 #define FD_INVERT 0x0002 /* invert value before storing */
1651 static const FlagDef options_W[] = {
1652 { offsetof(TCCState, warn_all), WD_ALL, "all" },
1653 { offsetof(TCCState, warn_error), 0, "error" },
1654 { offsetof(TCCState, warn_write_strings), 0, "write-strings" },
1655 { offsetof(TCCState, warn_unsupported), 0, "unsupported" },
1656 { offsetof(TCCState, warn_implicit_function_declaration), WD_ALL, "implicit-function-declaration" },
1657 { offsetof(TCCState, warn_discarded_qualifiers), WD_ALL, "discarded-qualifiers" },
1658 { 0, 0, NULL }
1661 static const FlagDef options_f[] = {
1662 { offsetof(TCCState, char_is_unsigned), 0, "unsigned-char" },
1663 { offsetof(TCCState, char_is_unsigned), FD_INVERT, "signed-char" },
1664 { offsetof(TCCState, nocommon), FD_INVERT, "common" },
1665 { offsetof(TCCState, leading_underscore), 0, "leading-underscore" },
1666 { offsetof(TCCState, ms_extensions), 0, "ms-extensions" },
1667 { offsetof(TCCState, dollars_in_identifiers), 0, "dollars-in-identifiers" },
1668 { offsetof(TCCState, test_coverage), 0, "test-coverage" },
1669 { 0, 0, NULL }
1672 static const FlagDef options_m[] = {
1673 { offsetof(TCCState, ms_bitfields), 0, "ms-bitfields" },
1674 #ifdef TCC_TARGET_X86_64
1675 { offsetof(TCCState, nosse), FD_INVERT, "sse" },
1676 #endif
1677 { 0, 0, NULL }
1680 static int set_flag(TCCState *s, const FlagDef *flags, const char *name)
1682 int value, mask, ret;
1683 const FlagDef *p;
1684 const char *r;
1685 unsigned char *f;
1687 r = name, value = !strstart("no-", &r), mask = 0;
1689 /* when called with options_W, look for -W[no-]error=<option> */
1690 if ((flags->flags & WD_ALL) && strstart("error=", &r))
1691 value = value ? WARN_ON|WARN_ERR : WARN_NOE, mask = WARN_ON;
1693 for (ret = -1, p = flags; p->name; ++p) {
1694 if (ret) {
1695 if (strcmp(r, p->name))
1696 continue;
1697 } else {
1698 if (0 == (p->flags & WD_ALL))
1699 continue;
1702 f = (unsigned char *)s + p->offset;
1703 *f = (*f & mask) | (value ^ !!(p->flags & FD_INVERT));
1705 if (ret) {
1706 ret = 0;
1707 if (strcmp(r, "all"))
1708 break;
1711 return ret;
1714 static const char dumpmachine_str[] =
1715 /* this is a best guess, please refine as necessary */
1716 #ifdef TCC_TARGET_I386
1717 "i386-pc"
1718 #elif defined TCC_TARGET_X86_64
1719 "x86_64-pc"
1720 #elif defined TCC_TARGET_C67
1721 "c67"
1722 #elif defined TCC_TARGET_ARM
1723 "arm"
1724 #elif defined TCC_TARGET_ARM64
1725 "aarch64"
1726 #elif defined TCC_TARGET_RISCV64
1727 "riscv64"
1728 #endif
1730 #ifdef TCC_TARGET_PE
1731 "mingw32"
1732 #elif defined(TCC_TARGET_MACHO)
1733 "apple-darwin"
1734 #elif TARGETOS_FreeBSD || TARGETOS_FreeBSD_kernel
1735 "freebsd"
1736 #elif TARGETOS_OpenBSD
1737 "openbsd"
1738 #elif TARGETOS_NetBSD
1739 "netbsd"
1740 #else
1741 "linux-gnu"
1742 #endif
1745 static int args_parser_make_argv(const char *r, int *argc, char ***argv)
1747 int ret = 0, q, c;
1748 CString str;
1749 for(;;) {
1750 while (c = (unsigned char)*r, c && c <= ' ')
1751 ++r;
1752 if (c == 0)
1753 break;
1754 q = 0;
1755 cstr_new(&str);
1756 while (c = (unsigned char)*r, c) {
1757 ++r;
1758 if (c == '\\' && (*r == '"' || *r == '\\')) {
1759 c = *r++;
1760 } else if (c == '"') {
1761 q = !q;
1762 continue;
1763 } else if (q == 0 && c <= ' ') {
1764 break;
1766 cstr_ccat(&str, c);
1768 cstr_ccat(&str, 0);
1769 //printf("<%s>\n", str.data), fflush(stdout);
1770 dynarray_add(argv, argc, tcc_strdup(str.data));
1771 cstr_free(&str);
1772 ++ret;
1774 return ret;
1777 /* read list file */
1778 static int args_parser_listfile(TCCState *s,
1779 const char *filename, int optind, int *pargc, char ***pargv)
1781 TCCState *s1 = s;
1782 int fd, i;
1783 char *p;
1784 int argc = 0;
1785 char **argv = NULL;
1787 fd = open(filename, O_RDONLY | O_BINARY);
1788 if (fd < 0)
1789 return tcc_error_noabort("listfile '%s' not found", filename);
1791 p = tcc_load_text(fd);
1792 for (i = 0; i < *pargc; ++i)
1793 if (i == optind)
1794 args_parser_make_argv(p, &argc, &argv);
1795 else
1796 dynarray_add(&argv, &argc, tcc_strdup((*pargv)[i]));
1798 tcc_free(p);
1799 dynarray_reset(&s->argv, &s->argc);
1800 *pargc = s->argc = argc, *pargv = s->argv = argv;
1801 return 0;
1804 #if defined TCC_TARGET_MACHO
1805 static uint32_t parse_version(TCCState *s1, const char *version)
1807 uint32_t a = 0;
1808 uint32_t b = 0;
1809 uint32_t c = 0;
1810 char* last;
1812 a = strtoul(version, &last, 10);
1813 if (*last == '.') {
1814 b = strtoul(&last[1], &last, 10);
1815 if (*last == '.')
1816 c = strtoul(&last[1], &last, 10);
1818 if (*last || a > 0xffff || b > 0xff || c > 0xff)
1819 tcc_error_noabort("version a.b.c not correct: %s", version);
1820 return (a << 16) | (b << 8) | c;
1822 #endif
1824 PUB_FUNC int tcc_parse_args(TCCState *s, int *pargc, char ***pargv, int optind)
1826 TCCState *s1 = s;
1827 const TCCOption *popt;
1828 const char *optarg, *r;
1829 const char *run = NULL;
1830 int x;
1831 int tool = 0, arg_start = 0, noaction = optind;
1832 char **argv = *pargv;
1833 int argc = *pargc;
1835 cstr_reset(&s->linker_arg);
1837 while (optind < argc) {
1838 r = argv[optind];
1839 if (r[0] == '@' && r[1] != '\0') {
1840 if (args_parser_listfile(s, r + 1, optind, &argc, &argv))
1841 return -1;
1842 continue;
1844 optind++;
1845 if (tool) {
1846 if (r[0] == '-' && r[1] == 'v' && r[2] == 0)
1847 ++s->verbose;
1848 continue;
1850 reparse:
1851 if (r[0] != '-' || r[1] == '\0') {
1852 args_parser_add_file(s, r, s->filetype);
1853 if (run) {
1854 dorun:
1855 if (tcc_set_options(s, run))
1856 return -1;
1857 arg_start = optind - 1;
1858 break;
1860 continue;
1863 /* allow "tcc files... -run -- args ..." */
1864 if (r[1] == '-' && r[2] == '\0' && run)
1865 goto dorun;
1867 /* find option in table */
1868 for(popt = tcc_options; ; ++popt) {
1869 const char *p1 = popt->name;
1870 const char *r1 = r + 1;
1871 if (p1 == NULL)
1872 return tcc_error_noabort("invalid option -- '%s'", r);
1873 if (!strstart(p1, &r1))
1874 continue;
1875 optarg = r1;
1876 if (popt->flags & TCC_OPTION_HAS_ARG) {
1877 if (*r1 == '\0' && !(popt->flags & TCC_OPTION_NOSEP)) {
1878 if (optind >= argc)
1879 arg_err:
1880 return tcc_error_noabort("argument to '%s' is missing", r);
1881 optarg = argv[optind++];
1883 } else if (*r1 != '\0')
1884 continue;
1885 break;
1888 switch(popt->index) {
1889 case TCC_OPTION_HELP:
1890 x = OPT_HELP;
1891 goto extra_action;
1892 case TCC_OPTION_HELP2:
1893 x = OPT_HELP2;
1894 goto extra_action;
1895 case TCC_OPTION_I:
1896 tcc_add_include_path(s, optarg);
1897 break;
1898 case TCC_OPTION_D:
1899 tcc_define_symbol(s, optarg, NULL);
1900 break;
1901 case TCC_OPTION_U:
1902 tcc_undefine_symbol(s, optarg);
1903 break;
1904 case TCC_OPTION_L:
1905 tcc_add_library_path(s, optarg);
1906 break;
1907 case TCC_OPTION_B:
1908 /* set tcc utilities path (mainly for tcc development) */
1909 tcc_set_lib_path(s, optarg);
1910 ++noaction;
1911 break;
1912 case TCC_OPTION_l:
1913 args_parser_add_file(s, optarg, AFF_TYPE_LIB | (s->filetype & ~AFF_TYPE_MASK));
1914 s->nb_libraries++;
1915 break;
1916 case TCC_OPTION_pthread:
1917 s->option_pthread = 1;
1918 break;
1919 case TCC_OPTION_bench:
1920 s->do_bench = 1;
1921 break;
1922 #ifdef CONFIG_TCC_BACKTRACE
1923 case TCC_OPTION_bt:
1924 s->rt_num_callers = atoi(optarg); /* zero = default (6) */
1925 goto enable_backtrace;
1926 enable_backtrace:
1927 s->do_backtrace = 1;
1928 s->do_debug = s->do_debug ? s->do_debug : 1;
1929 s->dwarf = DWARF_VERSION;
1930 break;
1931 #ifdef CONFIG_TCC_BCHECK
1932 case TCC_OPTION_b:
1933 s->do_bounds_check = 1;
1934 goto enable_backtrace;
1935 #endif
1936 #endif
1937 case TCC_OPTION_g:
1938 s->do_debug = 2;
1939 s->dwarf = DWARF_VERSION;
1940 if (strstart("dwarf", &optarg)) {
1941 s->dwarf = (*optarg) ? (0 - atoi(optarg)) : DEFAULT_DWARF_VERSION;
1942 } else if (isnum(*optarg)) {
1943 x = *optarg - '0';
1944 /* -g0 = no info, -g1 = lines/functions only, -g2 = full info */
1945 s->do_debug = x > 2 ? 2 : x == 0 && s->do_backtrace ? 1 : x;
1946 #ifdef TCC_TARGET_PE
1947 } else if (0 == strcmp(".pdb", optarg)) {
1948 s->dwarf = 5, s->do_debug |= 16;
1949 #endif
1951 break;
1952 case TCC_OPTION_c:
1953 x = TCC_OUTPUT_OBJ;
1954 set_output_type:
1955 if (s->output_type)
1956 tcc_warning("-%s: overriding compiler action already specified", popt->name);
1957 s->output_type = x;
1958 break;
1959 case TCC_OPTION_d:
1960 if (*optarg == 'D')
1961 s->dflag = 3;
1962 else if (*optarg == 'M')
1963 s->dflag = 7;
1964 else if (*optarg == 't')
1965 s->dflag = 16;
1966 else if (isnum(*optarg))
1967 s->g_debug |= atoi(optarg);
1968 else
1969 goto unsupported_option;
1970 break;
1971 case TCC_OPTION_static:
1972 s->static_link = 1;
1973 break;
1974 case TCC_OPTION_std:
1975 if (strcmp(optarg, "=c11") == 0)
1976 s->cversion = 201112;
1977 break;
1978 case TCC_OPTION_shared:
1979 x = TCC_OUTPUT_DLL;
1980 goto set_output_type;
1981 case TCC_OPTION_soname:
1982 s->soname = tcc_strdup(optarg);
1983 break;
1984 case TCC_OPTION_o:
1985 if (s->outfile) {
1986 tcc_warning("multiple -o option");
1987 tcc_free(s->outfile);
1989 s->outfile = tcc_strdup(optarg);
1990 break;
1991 case TCC_OPTION_r:
1992 /* generate a .o merging several output files */
1993 s->option_r = 1;
1994 x = TCC_OUTPUT_OBJ;
1995 goto set_output_type;
1996 case TCC_OPTION_isystem:
1997 tcc_add_sysinclude_path(s, optarg);
1998 break;
1999 case TCC_OPTION_include:
2000 cstr_printf(&s->cmdline_incl, "#include \"%s\"\n", optarg);
2001 break;
2002 case TCC_OPTION_nostdinc:
2003 s->nostdinc = 1;
2004 break;
2005 case TCC_OPTION_nostdlib:
2006 s->nostdlib = 1;
2007 break;
2008 case TCC_OPTION_run:
2009 #ifndef TCC_IS_NATIVE
2010 return tcc_error_noabort("-run is not available in a cross compiler");
2011 #else
2012 run = optarg;
2013 x = TCC_OUTPUT_MEMORY;
2014 goto set_output_type;
2015 #endif
2016 case TCC_OPTION_v:
2017 do ++s->verbose; while (*optarg++ == 'v');
2018 ++noaction;
2019 break;
2020 case TCC_OPTION_f:
2021 if (set_flag(s, options_f, optarg) < 0)
2022 goto unsupported_option;
2023 break;
2024 #ifdef TCC_TARGET_ARM
2025 case TCC_OPTION_mfloat_abi:
2026 /* tcc doesn't support soft float yet */
2027 if (!strcmp(optarg, "softfp")) {
2028 s->float_abi = ARM_SOFTFP_FLOAT;
2029 } else if (!strcmp(optarg, "hard"))
2030 s->float_abi = ARM_HARD_FLOAT;
2031 else
2032 return tcc_error_noabort("unsupported float abi '%s'", optarg);
2033 break;
2034 #endif
2035 case TCC_OPTION_m:
2036 if (set_flag(s, options_m, optarg) < 0) {
2037 if (x = atoi(optarg), x != 32 && x != 64)
2038 goto unsupported_option;
2039 if (PTR_SIZE != x/8)
2040 return x;
2041 ++noaction;
2043 break;
2044 case TCC_OPTION_W:
2045 s->warn_none = 0;
2046 if (optarg[0] && set_flag(s, options_W, optarg) < 0)
2047 goto unsupported_option;
2048 break;
2049 case TCC_OPTION_w:
2050 s->warn_none = 1;
2051 break;
2052 case TCC_OPTION_rdynamic:
2053 s->rdynamic = 1;
2054 break;
2055 case TCC_OPTION_Wl:
2056 if (s->linker_arg.size)
2057 ((char*)s->linker_arg.data)[s->linker_arg.size - 1] = ',';
2058 cstr_cat(&s->linker_arg, optarg, 0);
2059 x = tcc_set_linker(s, s->linker_arg.data);
2060 if (x)
2061 cstr_reset(&s->linker_arg);
2062 if (x < 0)
2063 return -1;
2064 break;
2065 case TCC_OPTION_Wp:
2066 r = optarg;
2067 goto reparse;
2068 case TCC_OPTION_E:
2069 x = TCC_OUTPUT_PREPROCESS;
2070 goto set_output_type;
2071 case TCC_OPTION_P:
2072 s->Pflag = atoi(optarg) + 1;
2073 break;
2074 case TCC_OPTION_M:
2075 s->include_sys_deps = 1;
2076 // fall through
2077 case TCC_OPTION_MM:
2078 s->just_deps = 1;
2079 if(!s->deps_outfile)
2080 s->deps_outfile = tcc_strdup("-");
2081 // fall through
2082 case TCC_OPTION_MMD:
2083 s->gen_deps = 1;
2084 break;
2085 case TCC_OPTION_MD:
2086 s->gen_deps = 1;
2087 s->include_sys_deps = 1;
2088 break;
2089 case TCC_OPTION_MF:
2090 s->deps_outfile = tcc_strdup(optarg);
2091 break;
2092 case TCC_OPTION_MP:
2093 s->gen_phony_deps = 1;
2094 break;
2095 case TCC_OPTION_dumpmachine:
2096 printf("%s\n", dumpmachine_str);
2097 exit(0);
2098 case TCC_OPTION_dumpversion:
2099 printf ("%s\n", TCC_VERSION);
2100 exit(0);
2101 case TCC_OPTION_x:
2102 x = 0;
2103 if (*optarg == 'c')
2104 x = AFF_TYPE_C;
2105 else if (*optarg == 'a')
2106 x = AFF_TYPE_ASMPP;
2107 else if (*optarg == 'b')
2108 x = AFF_TYPE_BIN;
2109 else if (*optarg == 'n')
2110 x = AFF_TYPE_NONE;
2111 else
2112 tcc_warning("unsupported language '%s'", optarg);
2113 s->filetype = x | (s->filetype & ~AFF_TYPE_MASK);
2114 break;
2115 case TCC_OPTION_O:
2116 s->optimize = atoi(optarg);
2117 break;
2118 case TCC_OPTION_print_search_dirs:
2119 x = OPT_PRINT_DIRS;
2120 goto extra_action;
2121 case TCC_OPTION_impdef:
2122 x = OPT_IMPDEF;
2123 goto extra_action;
2124 #if defined TCC_TARGET_MACHO
2125 case TCC_OPTION_dynamiclib:
2126 x = TCC_OUTPUT_DLL;
2127 goto set_output_type;
2128 case TCC_OPTION_flat_namespace:
2129 break;
2130 case TCC_OPTION_two_levelnamespace:
2131 break;
2132 case TCC_OPTION_undefined:
2133 break;
2134 case TCC_OPTION_install_name:
2135 s->install_name = tcc_strdup(optarg);
2136 break;
2137 case TCC_OPTION_compatibility_version:
2138 s->compatibility_version = parse_version(s, optarg);
2139 break;
2140 case TCC_OPTION_current_version:
2141 s->current_version = parse_version(s, optarg);;
2142 break;
2143 #endif
2144 case TCC_OPTION_ar:
2145 x = OPT_AR;
2146 extra_action:
2147 arg_start = optind - 1;
2148 if (arg_start != noaction)
2149 return tcc_error_noabort("cannot parse %s here", r);
2150 tool = x;
2151 break;
2152 default:
2153 unsupported_option:
2154 tcc_warning_c(warn_unsupported)("unsupported option '%s'", r);
2155 break;
2158 if (s->linker_arg.size) {
2159 r = s->linker_arg.data;
2160 goto arg_err;
2162 *pargc = argc - arg_start;
2163 *pargv = argv + arg_start;
2164 if (tool)
2165 return tool;
2166 if (optind != noaction)
2167 return 0;
2168 if (s->verbose == 2)
2169 return OPT_PRINT_DIRS;
2170 if (s->verbose)
2171 return OPT_V;
2172 return OPT_HELP;
2175 LIBTCCAPI int tcc_set_options(TCCState *s, const char *r)
2177 char **argv = NULL;
2178 int argc = 0, ret;
2179 args_parser_make_argv(r, &argc, &argv);
2180 ret = tcc_parse_args(s, &argc, &argv, 0);
2181 dynarray_reset(&argv, &argc);
2182 return ret < 0 ? ret : 0;
2185 PUB_FUNC void tcc_print_stats(TCCState *s1, unsigned total_time)
2187 if (!total_time)
2188 total_time = 1;
2189 fprintf(stderr, "# %d idents, %d lines, %u bytes\n"
2190 "# %0.3f s, %u lines/s, %0.1f MB/s\n",
2191 total_idents, total_lines, total_bytes,
2192 (double)total_time/1000,
2193 (unsigned)total_lines*1000/total_time,
2194 (double)total_bytes/1000/total_time);
2195 fprintf(stderr, "# text %u, data.rw %u, data.ro %u, bss %u bytes\n",
2196 s1->total_output[0],
2197 s1->total_output[1],
2198 s1->total_output[2],
2199 s1->total_output[3]
2201 #ifdef MEM_DEBUG
2202 fprintf(stderr, "# memory usage");
2203 #ifdef TCC_IS_NATIVE
2204 if (s1->run_size) {
2205 Section *s = s1->symtab;
2206 int ms = s->data_offset + s->link->data_offset + s->hash->data_offset;
2207 fprintf(stderr, ": %d to run, %d symbols, %d other,",
2208 s1->run_size, ms, mem_cur_size - s1->run_size - ms);
2210 #endif
2211 fprintf(stderr, " %d max (bytes)\n", mem_max_size);
2212 #endif