fixup! riscv: Implement large addend for global address
[tinycc.git] / libtcc.c
blob9d4fdac04bdef319fe031f069e985a4b08a1ef87
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 GetModuleFileNameA(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 GetSystemDirectoryA(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 #ifdef MEM_DEBUG
805 tcc_memcheck(1);
806 #endif
808 #undef gnu_ext
809 s->gnu_ext = 1;
810 s->tcc_ext = 1;
811 s->nocommon = 1;
812 s->dollars_in_identifiers = 1; /*on by default like in gcc/clang*/
813 s->cversion = 199901; /* default unless -std=c11 is supplied */
814 s->warn_implicit_function_declaration = 1;
815 s->warn_discarded_qualifiers = 1;
816 s->ms_extensions = 1;
818 #ifdef CHAR_IS_UNSIGNED
819 s->char_is_unsigned = 1;
820 #endif
821 #ifdef TCC_TARGET_I386
822 s->seg_size = 32;
823 #endif
824 /* enable this if you want symbols with leading underscore on windows: */
825 #if defined TCC_TARGET_MACHO /* || defined TCC_TARGET_PE */
826 s->leading_underscore = 1;
827 #endif
828 #ifdef TCC_TARGET_ARM
829 s->float_abi = ARM_FLOAT_ABI;
830 #endif
831 #ifdef CONFIG_NEW_DTAGS
832 s->enable_new_dtags = 1;
833 #endif
834 s->ppfp = stdout;
835 /* might be used in error() before preprocess_start() */
836 s->include_stack_ptr = s->include_stack;
838 tcc_set_lib_path(s, CONFIG_TCCDIR);
839 return s;
842 LIBTCCAPI void tcc_delete(TCCState *s1)
844 /* free sections */
845 tccelf_delete(s1);
847 /* free library paths */
848 dynarray_reset(&s1->library_paths, &s1->nb_library_paths);
849 dynarray_reset(&s1->crt_paths, &s1->nb_crt_paths);
851 /* free include paths */
852 dynarray_reset(&s1->include_paths, &s1->nb_include_paths);
853 dynarray_reset(&s1->sysinclude_paths, &s1->nb_sysinclude_paths);
855 tcc_free(s1->tcc_lib_path);
856 tcc_free(s1->soname);
857 tcc_free(s1->rpath);
858 tcc_free(s1->elf_entryname);
859 tcc_free(s1->init_symbol);
860 tcc_free(s1->fini_symbol);
861 tcc_free(s1->mapfile);
862 tcc_free(s1->outfile);
863 tcc_free(s1->deps_outfile);
864 #if defined TCC_TARGET_MACHO
865 tcc_free(s1->install_name);
866 #endif
867 dynarray_reset(&s1->files, &s1->nb_files);
868 dynarray_reset(&s1->target_deps, &s1->nb_target_deps);
869 dynarray_reset(&s1->pragma_libs, &s1->nb_pragma_libs);
870 dynarray_reset(&s1->argv, &s1->argc);
871 cstr_free(&s1->cmdline_defs);
872 cstr_free(&s1->cmdline_incl);
873 cstr_free(&s1->linker_arg);
874 tcc_free(s1->dState);
875 #ifdef TCC_IS_NATIVE
876 /* free runtime memory */
877 tcc_run_free(s1);
878 #endif
879 /* free loaded dlls array */
880 dynarray_reset(&s1->loaded_dlls, &s1->nb_loaded_dlls);
881 tcc_free(s1);
882 #ifdef MEM_DEBUG
883 tcc_memcheck(-1);
884 #endif
887 LIBTCCAPI int tcc_set_output_type(TCCState *s, int output_type)
889 #ifdef CONFIG_TCC_PIE
890 if (output_type == TCC_OUTPUT_EXE)
891 output_type |= TCC_OUTPUT_DYN;
892 #endif
893 s->output_type = output_type;
895 if (!s->nostdinc) {
896 /* default include paths */
897 /* -isystem paths have already been handled */
898 tcc_add_sysinclude_path(s, CONFIG_TCC_SYSINCLUDEPATHS);
901 if (output_type == TCC_OUTPUT_PREPROCESS) {
902 s->do_debug = 0;
903 return 0;
906 /* add sections */
907 tccelf_new(s);
909 if (output_type == TCC_OUTPUT_OBJ) {
910 /* always elf for objects */
911 s->output_format = TCC_OUTPUT_FORMAT_ELF;
912 return 0;
915 tcc_add_library_path(s, CONFIG_TCC_LIBPATHS);
917 #ifdef TCC_TARGET_PE
918 # ifdef TCC_IS_NATIVE
919 /* allow linking with system dll's directly */
920 tcc_add_systemdir(s);
921 # endif
922 #elif defined TCC_TARGET_MACHO
923 # ifdef TCC_IS_NATIVE
924 tcc_add_macos_sdkpath(s);
925 # endif
926 #else
927 /* paths for crt objects */
928 tcc_split_path(s, &s->crt_paths, &s->nb_crt_paths, CONFIG_TCC_CRTPREFIX);
929 if (output_type != TCC_OUTPUT_MEMORY && !s->nostdlib)
930 tccelf_add_crtbegin(s);
931 #endif
932 return 0;
935 LIBTCCAPI int tcc_add_include_path(TCCState *s, const char *pathname)
937 tcc_split_path(s, &s->include_paths, &s->nb_include_paths, pathname);
938 return 0;
941 LIBTCCAPI int tcc_add_sysinclude_path(TCCState *s, const char *pathname)
943 tcc_split_path(s, &s->sysinclude_paths, &s->nb_sysinclude_paths, pathname);
944 return 0;
947 /* add/update a 'DLLReference', Just find if level == -1 */
948 ST_FUNC DLLReference *tcc_add_dllref(TCCState *s1, const char *dllname, int level)
950 DLLReference *ref = NULL;
951 int i;
952 for (i = 0; i < s1->nb_loaded_dlls; i++)
953 if (0 == strcmp(s1->loaded_dlls[i]->name, dllname)) {
954 ref = s1->loaded_dlls[i];
955 break;
957 if (level == -1)
958 return ref;
959 if (ref) {
960 if (level < ref->level)
961 ref->level = level;
962 ref->found = 1;
963 return ref;
965 ref = tcc_mallocz(sizeof(DLLReference) + strlen(dllname));
966 strcpy(ref->name, dllname);
967 dynarray_add(&s1->loaded_dlls, &s1->nb_loaded_dlls, ref);
968 ref->level = level;
969 ref->index = s1->nb_loaded_dlls;
970 return ref;
973 /* OpenBSD: choose latest from libxxx.so.x.y versions */
974 #if defined TARGETOS_OpenBSD && !defined _WIN32
975 #include <glob.h>
976 static int tcc_glob_so(TCCState *s1, const char *pattern, char *buf, int size)
978 const char *star;
979 glob_t g;
980 char *p;
981 int i, v, v1, v2, v3;
983 star = strchr(pattern, '*');
984 if (!star || glob(pattern, 0, NULL, &g))
985 return -1;
986 for (v = -1, i = 0; i < g.gl_pathc; ++i) {
987 p = g.gl_pathv[i];
988 if (2 != sscanf(p + (star - pattern), "%d.%d.%d", &v1, &v2, &v3))
989 continue;
990 if ((v1 = v1 * 1000 + v2) > v)
991 v = v1, pstrcpy(buf, size, p);
993 globfree(&g);
994 return v;
996 #endif
998 ST_FUNC int tcc_add_file_internal(TCCState *s1, const char *filename, int flags)
1000 int fd, ret = -1;
1002 #if defined TARGETOS_OpenBSD && !defined _WIN32
1003 char buf[1024];
1004 if (tcc_glob_so(s1, filename, buf, sizeof buf) >= 0)
1005 filename = buf;
1006 #endif
1008 /* ignore binary files with -E */
1009 if (s1->output_type == TCC_OUTPUT_PREPROCESS
1010 && (flags & AFF_TYPE_BIN))
1011 return 0;
1013 /* open the file */
1014 fd = _tcc_open(s1, filename);
1015 if (fd < 0) {
1016 if (flags & AFF_PRINT_ERROR)
1017 tcc_error_noabort("file '%s' not found", filename);
1018 return FILE_NOT_FOUND;
1021 s1->current_filename = filename;
1022 if (flags & AFF_TYPE_BIN) {
1023 ElfW(Ehdr) ehdr;
1024 int obj_type;
1026 obj_type = tcc_object_type(fd, &ehdr);
1027 lseek(fd, 0, SEEK_SET);
1029 switch (obj_type) {
1031 case AFF_BINTYPE_REL:
1032 ret = tcc_load_object_file(s1, fd, 0);
1033 break;
1035 case AFF_BINTYPE_AR:
1036 ret = tcc_load_archive(s1, fd, !(flags & AFF_WHOLE_ARCHIVE));
1037 break;
1039 #ifdef TCC_TARGET_PE
1040 default:
1041 ret = pe_load_file(s1, fd, filename);
1042 goto check_success;
1044 #elif defined TCC_TARGET_MACHO
1045 case AFF_BINTYPE_DYN:
1046 case_dyn_or_tbd:
1047 if (s1->output_type == TCC_OUTPUT_MEMORY) {
1048 #ifdef TCC_IS_NATIVE
1049 void* dl;
1050 const char* soname = filename;
1051 if (obj_type != AFF_BINTYPE_DYN)
1052 soname = macho_tbd_soname(filename);
1053 dl = dlopen(soname, RTLD_GLOBAL | RTLD_LAZY);
1054 if (dl)
1055 tcc_add_dllref(s1, soname, 0)->handle = dl, ret = 0;
1056 if (filename != soname)
1057 tcc_free((void *)soname);
1058 #endif
1059 } else if (obj_type == AFF_BINTYPE_DYN) {
1060 ret = macho_load_dll(s1, fd, filename, (flags & AFF_REFERENCED_DLL) != 0);
1061 } else {
1062 ret = macho_load_tbd(s1, fd, filename, (flags & AFF_REFERENCED_DLL) != 0);
1064 goto check_success;
1065 default:
1067 const char *ext = tcc_fileextension(filename);
1068 if (!strcmp(ext, ".tbd"))
1069 goto case_dyn_or_tbd;
1070 if (!strcmp(ext, ".dylib")) {
1071 obj_type = AFF_BINTYPE_DYN;
1072 goto case_dyn_or_tbd;
1074 goto check_success;
1077 #else /* unix */
1078 case AFF_BINTYPE_DYN:
1079 if (s1->output_type == TCC_OUTPUT_MEMORY) {
1080 #ifdef TCC_IS_NATIVE
1081 void* dl = dlopen(filename, RTLD_GLOBAL | RTLD_LAZY);
1082 if (dl)
1083 tcc_add_dllref(s1, filename, 0)->handle = dl, ret = 0;
1084 #endif
1085 } else
1086 ret = tcc_load_dll(s1, fd, filename, (flags & AFF_REFERENCED_DLL) != 0);
1087 break;
1089 default:
1090 /* as GNU ld, consider it is an ld script if not recognized */
1091 ret = tcc_load_ldscript(s1, fd);
1092 goto check_success;
1094 #endif /* pe / macos / unix */
1096 check_success:
1097 if (ret < 0)
1098 tcc_error_noabort("%s: unrecognized file type", filename);
1099 break;
1101 #ifdef TCC_TARGET_COFF
1102 case AFF_BINTYPE_C67:
1103 ret = tcc_load_coff(s1, fd);
1104 break;
1105 #endif
1107 close(fd);
1108 } else {
1109 /* update target deps */
1110 dynarray_add(&s1->target_deps, &s1->nb_target_deps, tcc_strdup(filename));
1111 ret = tcc_compile(s1, flags, filename, fd);
1113 s1->current_filename = NULL;
1114 return ret;
1117 LIBTCCAPI int tcc_add_file(TCCState *s, const char *filename)
1119 int filetype = s->filetype;
1120 if (0 == (filetype & AFF_TYPE_MASK)) {
1121 /* use a file extension to detect a filetype */
1122 const char *ext = tcc_fileextension(filename);
1123 if (ext[0]) {
1124 ext++;
1125 if (!strcmp(ext, "S"))
1126 filetype = AFF_TYPE_ASMPP;
1127 else if (!strcmp(ext, "s"))
1128 filetype = AFF_TYPE_ASM;
1129 else if (!PATHCMP(ext, "c")
1130 || !PATHCMP(ext, "h")
1131 || !PATHCMP(ext, "i"))
1132 filetype = AFF_TYPE_C;
1133 else
1134 filetype |= AFF_TYPE_BIN;
1135 } else {
1136 filetype = AFF_TYPE_C;
1139 return tcc_add_file_internal(s, filename, filetype | AFF_PRINT_ERROR);
1142 LIBTCCAPI int tcc_add_library_path(TCCState *s, const char *pathname)
1144 tcc_split_path(s, &s->library_paths, &s->nb_library_paths, pathname);
1145 return 0;
1148 static int tcc_add_library_internal(TCCState *s1, const char *fmt,
1149 const char *filename, int flags, char **paths, int nb_paths)
1151 char buf[1024];
1152 int i, ret;
1154 for(i = 0; i < nb_paths; i++) {
1155 snprintf(buf, sizeof(buf), fmt, paths[i], filename);
1156 ret = tcc_add_file_internal(s1, buf, (flags & ~AFF_PRINT_ERROR) | AFF_TYPE_BIN);
1157 if (ret != FILE_NOT_FOUND)
1158 return ret;
1160 if (flags & AFF_PRINT_ERROR)
1161 tcc_error_noabort("file '%s' not found", filename);
1162 return FILE_NOT_FOUND;
1165 /* find and load a dll. Return non zero if not found */
1166 ST_FUNC int tcc_add_dll(TCCState *s, const char *filename, int flags)
1168 return tcc_add_library_internal(s, "%s/%s", filename, flags,
1169 s->library_paths, s->nb_library_paths);
1172 /* find [cross-]libtcc1.a and tcc helper objects in library path */
1173 ST_FUNC void tcc_add_support(TCCState *s1, const char *filename)
1175 char buf[100];
1176 if (CONFIG_TCC_CROSSPREFIX[0])
1177 filename = strcat(strcpy(buf, CONFIG_TCC_CROSSPREFIX), filename);
1178 tcc_add_dll(s1, filename, AFF_PRINT_ERROR);
1181 #if !defined TCC_TARGET_PE && !defined TCC_TARGET_MACHO
1182 ST_FUNC int tcc_add_crt(TCCState *s1, const char *filename)
1184 return tcc_add_library_internal(s1, "%s/%s",
1185 filename, AFF_PRINT_ERROR, s1->crt_paths, s1->nb_crt_paths);
1187 #endif
1189 /* the library name is the same as the argument of the '-l' option */
1190 LIBTCCAPI int tcc_add_library(TCCState *s, const char *libraryname)
1192 #if defined TCC_TARGET_PE
1193 static const char * const libs[] = { "%s/%s.def", "%s/lib%s.def", "%s/%s.dll", "%s/lib%s.dll", "%s/lib%s.a", NULL };
1194 const char * const *pp = s->static_link ? libs + 4 : libs;
1195 #elif defined TCC_TARGET_MACHO
1196 static const char * const libs[] = { "%s/lib%s.dylib", "%s/lib%s.tbd", "%s/lib%s.a", NULL };
1197 const char * const *pp = s->static_link ? libs + 2 : libs;
1198 #elif defined TARGETOS_OpenBSD
1199 static const char * const libs[] = { "%s/lib%s.so.*", "%s/lib%s.a", NULL };
1200 const char * const *pp = s->static_link ? libs + 1 : libs;
1201 #else
1202 static const char * const libs[] = { "%s/lib%s.so", "%s/lib%s.a", NULL };
1203 const char * const *pp = s->static_link ? libs + 1 : libs;
1204 #endif
1205 int flags = s->filetype & AFF_WHOLE_ARCHIVE;
1206 while (*pp) {
1207 int ret = tcc_add_library_internal(s, *pp,
1208 libraryname, flags, s->library_paths, s->nb_library_paths);
1209 if (ret != FILE_NOT_FOUND)
1210 return ret;
1211 ++pp;
1213 return FILE_NOT_FOUND;
1216 PUB_FUNC int tcc_add_library_err(TCCState *s1, const char *libname)
1218 int ret = tcc_add_library(s1, libname);
1219 if (ret == FILE_NOT_FOUND)
1220 tcc_error_noabort("library '%s' not found", libname);
1221 return ret;
1224 /* handle #pragma comment(lib,) */
1225 ST_FUNC void tcc_add_pragma_libs(TCCState *s1)
1227 int i;
1228 for (i = 0; i < s1->nb_pragma_libs; i++)
1229 tcc_add_library_err(s1, s1->pragma_libs[i]);
1232 LIBTCCAPI int tcc_add_symbol(TCCState *s1, const char *name, const void *val)
1234 #ifdef TCC_TARGET_PE
1235 /* On x86_64 'val' might not be reachable with a 32bit offset.
1236 So it is handled here as if it were in a DLL. */
1237 pe_putimport(s1, 0, name, (uintptr_t)val);
1238 #else
1239 char buf[256];
1240 if (s1->leading_underscore) {
1241 buf[0] = '_';
1242 pstrcpy(buf + 1, sizeof(buf) - 1, name);
1243 name = buf;
1245 set_global_sym(s1, name, NULL, (addr_t)(uintptr_t)val); /* NULL: SHN_ABS */
1246 #endif
1247 return 0;
1250 LIBTCCAPI void tcc_set_lib_path(TCCState *s, const char *path)
1252 tcc_free(s->tcc_lib_path);
1253 s->tcc_lib_path = tcc_strdup(path);
1256 /********************************************************/
1257 /* options parser */
1259 static int strstart(const char *val, const char **str)
1261 const char *p, *q;
1262 p = *str;
1263 q = val;
1264 while (*q) {
1265 if (*p != *q)
1266 return 0;
1267 p++;
1268 q++;
1270 *str = p;
1271 return 1;
1274 /* Like strstart, but automatically takes into account that ld options can
1276 * - start with double or single dash (e.g. '--soname' or '-soname')
1277 * - arguments can be given as separate or after '=' (e.g. '-Wl,-soname,x.so'
1278 * or '-Wl,-soname=x.so')
1280 * you provide `val` always in 'option[=]' form (no leading -)
1282 static int link_option(const char *str, const char *val, const char **ptr)
1284 const char *p, *q;
1285 int ret;
1287 /* there should be 1 or 2 dashes */
1288 if (*str++ != '-')
1289 return 0;
1290 if (*str == '-')
1291 str++;
1293 /* then str & val should match (potentially up to '=') */
1294 p = str;
1295 q = val;
1297 ret = 1;
1298 if (q[0] == '?') {
1299 ++q;
1300 if (strstart("no-", &p))
1301 ret = -1;
1304 while (*q != '\0' && *q != '=') {
1305 if (*p != *q)
1306 return 0;
1307 p++;
1308 q++;
1311 /* '=' near eos means ',' or '=' is ok */
1312 if (*q == '=') {
1313 if (*p == 0)
1314 *ptr = p;
1315 if (*p != ',' && *p != '=')
1316 return 0;
1317 p++;
1318 } else if (*p) {
1319 return 0;
1321 *ptr = p;
1322 return ret;
1325 static const char *skip_linker_arg(const char **str)
1327 const char *s1 = *str;
1328 const char *s2 = strchr(s1, ',');
1329 *str = s2 ? s2++ : (s2 = s1 + strlen(s1));
1330 return s2;
1333 static void copy_linker_arg(char **pp, const char *s, int sep)
1335 const char *q = s;
1336 char *p = *pp;
1337 int l = 0;
1338 if (p && sep)
1339 p[l = strlen(p)] = sep, ++l;
1340 skip_linker_arg(&q);
1341 pstrncpy(l + (*pp = tcc_realloc(p, q - s + l + 1)), s, q - s);
1344 static void args_parser_add_file(TCCState *s, const char* filename, int filetype)
1346 struct filespec *f = tcc_malloc(sizeof *f + strlen(filename));
1347 f->type = filetype;
1348 strcpy(f->name, filename);
1349 dynarray_add(&s->files, &s->nb_files, f);
1352 /* set linker options */
1353 static int tcc_set_linker(TCCState *s, const char *option)
1355 TCCState *s1 = s;
1356 while (*option) {
1358 const char *p = NULL;
1359 char *end = NULL;
1360 int ignoring = 0;
1361 int ret;
1363 if (link_option(option, "Bsymbolic", &p)) {
1364 s->symbolic = 1;
1365 } else if (link_option(option, "nostdlib", &p)) {
1366 s->nostdlib = 1;
1367 } else if (link_option(option, "e=", &p)
1368 || link_option(option, "entry=", &p)) {
1369 copy_linker_arg(&s->elf_entryname, p, 0);
1370 } else if (link_option(option, "fini=", &p)) {
1371 copy_linker_arg(&s->fini_symbol, p, 0);
1372 ignoring = 1;
1373 } else if (link_option(option, "image-base=", &p)
1374 || link_option(option, "Ttext=", &p)) {
1375 s->text_addr = strtoull(p, &end, 16);
1376 s->has_text_addr = 1;
1377 } else if (link_option(option, "init=", &p)) {
1378 copy_linker_arg(&s->init_symbol, p, 0);
1379 ignoring = 1;
1380 } else if (link_option(option, "Map=", &p)) {
1381 copy_linker_arg(&s->mapfile, p, 0);
1382 ignoring = 1;
1383 } else if (link_option(option, "oformat=", &p)) {
1384 #if defined(TCC_TARGET_PE)
1385 if (strstart("pe-", &p)) {
1386 #elif PTR_SIZE == 8
1387 if (strstart("elf64-", &p)) {
1388 #else
1389 if (strstart("elf32-", &p)) {
1390 #endif
1391 s->output_format = TCC_OUTPUT_FORMAT_ELF;
1392 } else if (!strcmp(p, "binary")) {
1393 s->output_format = TCC_OUTPUT_FORMAT_BINARY;
1394 #ifdef TCC_TARGET_COFF
1395 } else if (!strcmp(p, "coff")) {
1396 s->output_format = TCC_OUTPUT_FORMAT_COFF;
1397 #endif
1398 } else
1399 goto err;
1401 } else if (link_option(option, "as-needed", &p)) {
1402 ignoring = 1;
1403 } else if (link_option(option, "O", &p)) {
1404 ignoring = 1;
1405 } else if (link_option(option, "export-all-symbols", &p)) {
1406 s->rdynamic = 1;
1407 } else if (link_option(option, "export-dynamic", &p)) {
1408 s->rdynamic = 1;
1409 } else if (link_option(option, "rpath=", &p)) {
1410 copy_linker_arg(&s->rpath, p, ':');
1411 } else if (link_option(option, "enable-new-dtags", &p)) {
1412 s->enable_new_dtags = 1;
1413 } else if (link_option(option, "section-alignment=", &p)) {
1414 s->section_align = strtoul(p, &end, 16);
1415 } else if (link_option(option, "soname=", &p)) {
1416 copy_linker_arg(&s->soname, p, 0);
1417 } else if (link_option(option, "install_name=", &p)) {
1418 copy_linker_arg(&s->soname, p, 0);
1419 #ifdef TCC_TARGET_PE
1420 } else if (link_option(option, "large-address-aware", &p)) {
1421 s->pe_characteristics |= 0x20;
1422 } else if (link_option(option, "file-alignment=", &p)) {
1423 s->pe_file_align = strtoul(p, &end, 16);
1424 } else if (link_option(option, "stack=", &p)) {
1425 s->pe_stack_size = strtoul(p, &end, 10);
1426 } else if (link_option(option, "subsystem=", &p)) {
1427 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
1428 if (!strcmp(p, "native")) {
1429 s->pe_subsystem = 1;
1430 } else if (!strcmp(p, "console")) {
1431 s->pe_subsystem = 3;
1432 } else if (!strcmp(p, "gui") || !strcmp(p, "windows")) {
1433 s->pe_subsystem = 2;
1434 } else if (!strcmp(p, "posix")) {
1435 s->pe_subsystem = 7;
1436 } else if (!strcmp(p, "efiapp")) {
1437 s->pe_subsystem = 10;
1438 } else if (!strcmp(p, "efiboot")) {
1439 s->pe_subsystem = 11;
1440 } else if (!strcmp(p, "efiruntime")) {
1441 s->pe_subsystem = 12;
1442 } else if (!strcmp(p, "efirom")) {
1443 s->pe_subsystem = 13;
1444 #elif defined(TCC_TARGET_ARM)
1445 if (!strcmp(p, "wince")) {
1446 s->pe_subsystem = 9;
1447 #endif
1448 } else
1449 goto err;
1450 #endif
1451 #ifdef TCC_TARGET_MACHO
1452 } else if (link_option(option, "all_load", &p)) {
1453 s->filetype |= AFF_WHOLE_ARCHIVE;
1454 } else if (link_option(option, "force_load", &p)) {
1455 s->filetype |= AFF_WHOLE_ARCHIVE;
1456 args_parser_add_file(s, p, AFF_TYPE_LIB | (s->filetype & ~AFF_TYPE_MASK));
1457 s->nb_libraries++;
1458 } else if (link_option(option, "single_module", &p)) {
1459 ignoring = 1;
1460 #endif
1461 } else if (ret = link_option(option, "?whole-archive", &p), ret) {
1462 if (ret > 0)
1463 s->filetype |= AFF_WHOLE_ARCHIVE;
1464 else
1465 s->filetype &= ~AFF_WHOLE_ARCHIVE;
1466 } else if (link_option(option, "z=", &p)) {
1467 ignoring = 1;
1468 } else if (p) {
1469 return 0;
1470 } else {
1471 err:
1472 return tcc_error_noabort("unsupported linker option '%s'", option);
1474 if (ignoring)
1475 tcc_warning_c(warn_unsupported)("unsupported linker option '%s'", option);
1476 option = skip_linker_arg(&p);
1478 return 1;
1481 typedef struct TCCOption {
1482 const char *name;
1483 uint16_t index;
1484 uint16_t flags;
1485 } TCCOption;
1487 enum {
1488 TCC_OPTION_ignored = 0,
1489 TCC_OPTION_HELP,
1490 TCC_OPTION_HELP2,
1491 TCC_OPTION_v,
1492 TCC_OPTION_I,
1493 TCC_OPTION_D,
1494 TCC_OPTION_U,
1495 TCC_OPTION_P,
1496 TCC_OPTION_L,
1497 TCC_OPTION_B,
1498 TCC_OPTION_l,
1499 TCC_OPTION_bench,
1500 TCC_OPTION_bt,
1501 TCC_OPTION_b,
1502 TCC_OPTION_ba,
1503 TCC_OPTION_g,
1504 TCC_OPTION_c,
1505 TCC_OPTION_dumpmachine,
1506 TCC_OPTION_dumpversion,
1507 TCC_OPTION_d,
1508 TCC_OPTION_static,
1509 TCC_OPTION_std,
1510 TCC_OPTION_shared,
1511 TCC_OPTION_soname,
1512 TCC_OPTION_o,
1513 TCC_OPTION_r,
1514 TCC_OPTION_Wl,
1515 TCC_OPTION_Wp,
1516 TCC_OPTION_W,
1517 TCC_OPTION_O,
1518 TCC_OPTION_mfloat_abi,
1519 TCC_OPTION_m,
1520 TCC_OPTION_f,
1521 TCC_OPTION_isystem,
1522 TCC_OPTION_iwithprefix,
1523 TCC_OPTION_include,
1524 TCC_OPTION_nostdinc,
1525 TCC_OPTION_nostdlib,
1526 TCC_OPTION_print_search_dirs,
1527 TCC_OPTION_rdynamic,
1528 TCC_OPTION_pthread,
1529 TCC_OPTION_run,
1530 TCC_OPTION_w,
1531 TCC_OPTION_E,
1532 TCC_OPTION_M,
1533 TCC_OPTION_MD,
1534 TCC_OPTION_MF,
1535 TCC_OPTION_MM,
1536 TCC_OPTION_MMD,
1537 TCC_OPTION_MP,
1538 TCC_OPTION_x,
1539 TCC_OPTION_ar,
1540 TCC_OPTION_impdef,
1541 TCC_OPTION_dynamiclib,
1542 TCC_OPTION_flat_namespace,
1543 TCC_OPTION_two_levelnamespace,
1544 TCC_OPTION_undefined,
1545 TCC_OPTION_install_name,
1546 TCC_OPTION_compatibility_version ,
1547 TCC_OPTION_current_version,
1550 #define TCC_OPTION_HAS_ARG 0x0001
1551 #define TCC_OPTION_NOSEP 0x0002 /* cannot have space before option and arg */
1553 static const TCCOption tcc_options[] = {
1554 { "h", TCC_OPTION_HELP, 0 },
1555 { "-help", TCC_OPTION_HELP, 0 },
1556 { "?", TCC_OPTION_HELP, 0 },
1557 { "hh", TCC_OPTION_HELP2, 0 },
1558 { "v", TCC_OPTION_v, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1559 { "-version", TCC_OPTION_v, 0 }, /* handle as verbose, also prints version*/
1560 { "I", TCC_OPTION_I, TCC_OPTION_HAS_ARG },
1561 { "D", TCC_OPTION_D, TCC_OPTION_HAS_ARG },
1562 { "U", TCC_OPTION_U, TCC_OPTION_HAS_ARG },
1563 { "P", TCC_OPTION_P, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1564 { "L", TCC_OPTION_L, TCC_OPTION_HAS_ARG },
1565 { "B", TCC_OPTION_B, TCC_OPTION_HAS_ARG },
1566 { "l", TCC_OPTION_l, TCC_OPTION_HAS_ARG },
1567 { "bench", TCC_OPTION_bench, 0 },
1568 #ifdef CONFIG_TCC_BACKTRACE
1569 { "bt", TCC_OPTION_bt, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1570 #endif
1571 #ifdef CONFIG_TCC_BCHECK
1572 { "b", TCC_OPTION_b, 0 },
1573 #endif
1574 { "g", TCC_OPTION_g, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1575 #ifdef TCC_TARGET_MACHO
1576 { "compatibility_version", TCC_OPTION_compatibility_version, TCC_OPTION_HAS_ARG },
1577 { "current_version", TCC_OPTION_current_version, TCC_OPTION_HAS_ARG },
1578 #endif
1579 { "c", TCC_OPTION_c, 0 },
1580 #ifdef TCC_TARGET_MACHO
1581 { "dynamiclib", TCC_OPTION_dynamiclib, 0 },
1582 #endif
1583 { "dumpmachine", TCC_OPTION_dumpmachine, 0},
1584 { "dumpversion", TCC_OPTION_dumpversion, 0},
1585 { "d", TCC_OPTION_d, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1586 { "static", TCC_OPTION_static, 0 },
1587 { "std", TCC_OPTION_std, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1588 { "shared", TCC_OPTION_shared, 0 },
1589 { "soname", TCC_OPTION_soname, TCC_OPTION_HAS_ARG },
1590 { "o", TCC_OPTION_o, TCC_OPTION_HAS_ARG },
1591 { "pthread", TCC_OPTION_pthread, 0},
1592 { "run", TCC_OPTION_run, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1593 { "rdynamic", TCC_OPTION_rdynamic, 0 },
1594 { "r", TCC_OPTION_r, 0 },
1595 { "Wl,", TCC_OPTION_Wl, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1596 { "Wp,", TCC_OPTION_Wp, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1597 { "W", TCC_OPTION_W, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1598 { "O", TCC_OPTION_O, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1599 #ifdef TCC_TARGET_ARM
1600 { "mfloat-abi", TCC_OPTION_mfloat_abi, TCC_OPTION_HAS_ARG },
1601 #endif
1602 { "m", TCC_OPTION_m, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1603 #ifdef TCC_TARGET_MACHO
1604 { "flat_namespace", TCC_OPTION_flat_namespace, 0 },
1605 #endif
1606 { "f", TCC_OPTION_f, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1607 { "isystem", TCC_OPTION_isystem, TCC_OPTION_HAS_ARG },
1608 { "include", TCC_OPTION_include, TCC_OPTION_HAS_ARG },
1609 { "nostdinc", TCC_OPTION_nostdinc, 0 },
1610 { "nostdlib", TCC_OPTION_nostdlib, 0 },
1611 { "print-search-dirs", TCC_OPTION_print_search_dirs, 0 },
1612 { "w", TCC_OPTION_w, 0 },
1613 { "E", TCC_OPTION_E, 0},
1614 { "M", TCC_OPTION_M, 0},
1615 { "MD", TCC_OPTION_MD, 0},
1616 { "MF", TCC_OPTION_MF, TCC_OPTION_HAS_ARG },
1617 { "MM", TCC_OPTION_MM, 0},
1618 { "MMD", TCC_OPTION_MMD, 0},
1619 { "MP", TCC_OPTION_MP, 0},
1620 { "x", TCC_OPTION_x, TCC_OPTION_HAS_ARG },
1621 { "ar", TCC_OPTION_ar, 0},
1622 #ifdef TCC_TARGET_PE
1623 { "impdef", TCC_OPTION_impdef, 0},
1624 #endif
1625 #ifdef TCC_TARGET_MACHO
1626 { "install_name", TCC_OPTION_install_name, TCC_OPTION_HAS_ARG },
1627 { "two_levelnamespace", TCC_OPTION_two_levelnamespace, 0 },
1628 { "undefined", TCC_OPTION_undefined, TCC_OPTION_HAS_ARG },
1629 #endif
1630 /* ignored (silently, except after -Wunsupported) */
1631 { "arch", 0, TCC_OPTION_HAS_ARG},
1632 { "C", 0, 0 },
1633 { "-param", 0, TCC_OPTION_HAS_ARG },
1634 { "pedantic", 0, 0 },
1635 { "pipe", 0, 0 },
1636 { "s", 0, 0 },
1637 { "traditional", 0, 0 },
1638 { NULL, 0, 0 },
1641 typedef struct FlagDef {
1642 uint16_t offset;
1643 uint16_t flags;
1644 const char *name;
1645 } FlagDef;
1647 #define WD_ALL 0x0001 /* warning is activated when using -Wall */
1648 #define FD_INVERT 0x0002 /* invert value before storing */
1650 static const FlagDef options_W[] = {
1651 { offsetof(TCCState, warn_all), WD_ALL, "all" },
1652 { offsetof(TCCState, warn_error), 0, "error" },
1653 { offsetof(TCCState, warn_write_strings), 0, "write-strings" },
1654 { offsetof(TCCState, warn_unsupported), 0, "unsupported" },
1655 { offsetof(TCCState, warn_implicit_function_declaration), WD_ALL, "implicit-function-declaration" },
1656 { offsetof(TCCState, warn_discarded_qualifiers), WD_ALL, "discarded-qualifiers" },
1657 { 0, 0, NULL }
1660 static const FlagDef options_f[] = {
1661 { offsetof(TCCState, char_is_unsigned), 0, "unsigned-char" },
1662 { offsetof(TCCState, char_is_unsigned), FD_INVERT, "signed-char" },
1663 { offsetof(TCCState, nocommon), FD_INVERT, "common" },
1664 { offsetof(TCCState, leading_underscore), 0, "leading-underscore" },
1665 { offsetof(TCCState, ms_extensions), 0, "ms-extensions" },
1666 { offsetof(TCCState, dollars_in_identifiers), 0, "dollars-in-identifiers" },
1667 { offsetof(TCCState, test_coverage), 0, "test-coverage" },
1668 { 0, 0, NULL }
1671 static const FlagDef options_m[] = {
1672 { offsetof(TCCState, ms_bitfields), 0, "ms-bitfields" },
1673 #ifdef TCC_TARGET_X86_64
1674 { offsetof(TCCState, nosse), FD_INVERT, "sse" },
1675 #endif
1676 { 0, 0, NULL }
1679 static int set_flag(TCCState *s, const FlagDef *flags, const char *name)
1681 int value, mask, ret;
1682 const FlagDef *p;
1683 const char *r;
1684 unsigned char *f;
1686 r = name, value = !strstart("no-", &r), mask = 0;
1688 /* when called with options_W, look for -W[no-]error=<option> */
1689 if ((flags->flags & WD_ALL) && strstart("error=", &r))
1690 value = value ? WARN_ON|WARN_ERR : WARN_NOE, mask = WARN_ON;
1692 for (ret = -1, p = flags; p->name; ++p) {
1693 if (ret) {
1694 if (strcmp(r, p->name))
1695 continue;
1696 } else {
1697 if (0 == (p->flags & WD_ALL))
1698 continue;
1701 f = (unsigned char *)s + p->offset;
1702 *f = (*f & mask) | (value ^ !!(p->flags & FD_INVERT));
1704 if (ret) {
1705 ret = 0;
1706 if (strcmp(r, "all"))
1707 break;
1710 return ret;
1713 static const char dumpmachine_str[] =
1714 /* this is a best guess, please refine as necessary */
1715 #ifdef TCC_TARGET_I386
1716 "i386-pc"
1717 #elif defined TCC_TARGET_X86_64
1718 "x86_64-pc"
1719 #elif defined TCC_TARGET_C67
1720 "c67"
1721 #elif defined TCC_TARGET_ARM
1722 "arm"
1723 #elif defined TCC_TARGET_ARM64
1724 "aarch64"
1725 #elif defined TCC_TARGET_RISCV64
1726 "riscv64"
1727 #endif
1729 #ifdef TCC_TARGET_PE
1730 "mingw32"
1731 #elif defined(TCC_TARGET_MACHO)
1732 "apple-darwin"
1733 #elif TARGETOS_FreeBSD || TARGETOS_FreeBSD_kernel
1734 "freebsd"
1735 #elif TARGETOS_OpenBSD
1736 "openbsd"
1737 #elif TARGETOS_NetBSD
1738 "netbsd"
1739 #else
1740 "linux-gnu"
1741 #endif
1744 static int args_parser_make_argv(const char *r, int *argc, char ***argv)
1746 int ret = 0, q, c;
1747 CString str;
1748 for(;;) {
1749 while (c = (unsigned char)*r, c && c <= ' ')
1750 ++r;
1751 if (c == 0)
1752 break;
1753 q = 0;
1754 cstr_new(&str);
1755 while (c = (unsigned char)*r, c) {
1756 ++r;
1757 if (c == '\\' && (*r == '"' || *r == '\\')) {
1758 c = *r++;
1759 } else if (c == '"') {
1760 q = !q;
1761 continue;
1762 } else if (q == 0 && c <= ' ') {
1763 break;
1765 cstr_ccat(&str, c);
1767 cstr_ccat(&str, 0);
1768 //printf("<%s>\n", str.data), fflush(stdout);
1769 dynarray_add(argv, argc, tcc_strdup(str.data));
1770 cstr_free(&str);
1771 ++ret;
1773 return ret;
1776 /* read list file */
1777 static int args_parser_listfile(TCCState *s,
1778 const char *filename, int optind, int *pargc, char ***pargv)
1780 TCCState *s1 = s;
1781 int fd, i;
1782 char *p;
1783 int argc = 0;
1784 char **argv = NULL;
1786 fd = open(filename, O_RDONLY | O_BINARY);
1787 if (fd < 0)
1788 return tcc_error_noabort("listfile '%s' not found", filename);
1790 p = tcc_load_text(fd);
1791 for (i = 0; i < *pargc; ++i)
1792 if (i == optind)
1793 args_parser_make_argv(p, &argc, &argv);
1794 else
1795 dynarray_add(&argv, &argc, tcc_strdup((*pargv)[i]));
1797 tcc_free(p);
1798 dynarray_reset(&s->argv, &s->argc);
1799 *pargc = s->argc = argc, *pargv = s->argv = argv;
1800 return 0;
1803 #if defined TCC_TARGET_MACHO
1804 static uint32_t parse_version(TCCState *s1, const char *version)
1806 uint32_t a = 0;
1807 uint32_t b = 0;
1808 uint32_t c = 0;
1809 char* last;
1811 a = strtoul(version, &last, 10);
1812 if (*last == '.') {
1813 b = strtoul(&last[1], &last, 10);
1814 if (*last == '.')
1815 c = strtoul(&last[1], &last, 10);
1817 if (*last || a > 0xffff || b > 0xff || c > 0xff)
1818 tcc_error_noabort("version a.b.c not correct: %s", version);
1819 return (a << 16) | (b << 8) | c;
1821 #endif
1823 PUB_FUNC int tcc_parse_args(TCCState *s, int *pargc, char ***pargv, int optind)
1825 TCCState *s1 = s;
1826 const TCCOption *popt;
1827 const char *optarg, *r;
1828 const char *run = NULL;
1829 int x;
1830 int tool = 0, arg_start = 0, noaction = optind;
1831 char **argv = *pargv;
1832 int argc = *pargc;
1834 cstr_reset(&s->linker_arg);
1836 while (optind < argc) {
1837 r = argv[optind];
1838 if (r[0] == '@' && r[1] != '\0') {
1839 if (args_parser_listfile(s, r + 1, optind, &argc, &argv))
1840 return -1;
1841 continue;
1843 optind++;
1844 if (tool) {
1845 if (r[0] == '-' && r[1] == 'v' && r[2] == 0)
1846 ++s->verbose;
1847 continue;
1849 reparse:
1850 if (r[0] != '-' || r[1] == '\0') {
1851 args_parser_add_file(s, r, s->filetype);
1852 if (run) {
1853 dorun:
1854 if (tcc_set_options(s, run))
1855 return -1;
1856 arg_start = optind - 1;
1857 break;
1859 continue;
1862 /* allow "tcc files... -run -- args ..." */
1863 if (r[1] == '-' && r[2] == '\0' && run)
1864 goto dorun;
1866 /* find option in table */
1867 for(popt = tcc_options; ; ++popt) {
1868 const char *p1 = popt->name;
1869 const char *r1 = r + 1;
1870 if (p1 == NULL)
1871 return tcc_error_noabort("invalid option -- '%s'", r);
1872 if (!strstart(p1, &r1))
1873 continue;
1874 optarg = r1;
1875 if (popt->flags & TCC_OPTION_HAS_ARG) {
1876 if (*r1 == '\0' && !(popt->flags & TCC_OPTION_NOSEP)) {
1877 if (optind >= argc)
1878 arg_err:
1879 return tcc_error_noabort("argument to '%s' is missing", r);
1880 optarg = argv[optind++];
1882 } else if (*r1 != '\0')
1883 continue;
1884 break;
1887 switch(popt->index) {
1888 case TCC_OPTION_HELP:
1889 x = OPT_HELP;
1890 goto extra_action;
1891 case TCC_OPTION_HELP2:
1892 x = OPT_HELP2;
1893 goto extra_action;
1894 case TCC_OPTION_I:
1895 tcc_add_include_path(s, optarg);
1896 break;
1897 case TCC_OPTION_D:
1898 tcc_define_symbol(s, optarg, NULL);
1899 break;
1900 case TCC_OPTION_U:
1901 tcc_undefine_symbol(s, optarg);
1902 break;
1903 case TCC_OPTION_L:
1904 tcc_add_library_path(s, optarg);
1905 break;
1906 case TCC_OPTION_B:
1907 /* set tcc utilities path (mainly for tcc development) */
1908 tcc_set_lib_path(s, optarg);
1909 ++noaction;
1910 break;
1911 case TCC_OPTION_l:
1912 args_parser_add_file(s, optarg, AFF_TYPE_LIB | (s->filetype & ~AFF_TYPE_MASK));
1913 s->nb_libraries++;
1914 break;
1915 case TCC_OPTION_pthread:
1916 s->option_pthread = 1;
1917 break;
1918 case TCC_OPTION_bench:
1919 s->do_bench = 1;
1920 break;
1921 #ifdef CONFIG_TCC_BACKTRACE
1922 case TCC_OPTION_bt:
1923 s->rt_num_callers = atoi(optarg); /* zero = default (6) */
1924 goto enable_backtrace;
1925 enable_backtrace:
1926 s->do_backtrace = 1;
1927 s->do_debug = s->do_debug ? s->do_debug : 1;
1928 s->dwarf = DWARF_VERSION;
1929 break;
1930 #ifdef CONFIG_TCC_BCHECK
1931 case TCC_OPTION_b:
1932 s->do_bounds_check = 1;
1933 goto enable_backtrace;
1934 #endif
1935 #endif
1936 case TCC_OPTION_g:
1937 s->do_debug = 2;
1938 s->dwarf = DWARF_VERSION;
1939 if (strstart("dwarf", &optarg)) {
1940 s->dwarf = (*optarg) ? (0 - atoi(optarg)) : DEFAULT_DWARF_VERSION;
1941 } else if (isnum(*optarg)) {
1942 x = *optarg - '0';
1943 /* -g0 = no info, -g1 = lines/functions only, -g2 = full info */
1944 s->do_debug = x > 2 ? 2 : x == 0 && s->do_backtrace ? 1 : x;
1945 #ifdef TCC_TARGET_PE
1946 } else if (0 == strcmp(".pdb", optarg)) {
1947 s->dwarf = 5, s->do_debug |= 16;
1948 #endif
1950 break;
1951 case TCC_OPTION_c:
1952 x = TCC_OUTPUT_OBJ;
1953 set_output_type:
1954 if (s->output_type)
1955 tcc_warning("-%s: overriding compiler action already specified", popt->name);
1956 s->output_type = x;
1957 break;
1958 case TCC_OPTION_d:
1959 if (*optarg == 'D')
1960 s->dflag = 3;
1961 else if (*optarg == 'M')
1962 s->dflag = 7;
1963 else if (*optarg == 't')
1964 s->dflag = 16;
1965 else if (isnum(*optarg))
1966 s->g_debug |= atoi(optarg);
1967 else
1968 goto unsupported_option;
1969 break;
1970 case TCC_OPTION_static:
1971 s->static_link = 1;
1972 break;
1973 case TCC_OPTION_std:
1974 if (strcmp(optarg, "=c11") == 0)
1975 s->cversion = 201112;
1976 break;
1977 case TCC_OPTION_shared:
1978 x = TCC_OUTPUT_DLL;
1979 goto set_output_type;
1980 case TCC_OPTION_soname:
1981 s->soname = tcc_strdup(optarg);
1982 break;
1983 case TCC_OPTION_o:
1984 if (s->outfile) {
1985 tcc_warning("multiple -o option");
1986 tcc_free(s->outfile);
1988 s->outfile = tcc_strdup(optarg);
1989 break;
1990 case TCC_OPTION_r:
1991 /* generate a .o merging several output files */
1992 s->option_r = 1;
1993 x = TCC_OUTPUT_OBJ;
1994 goto set_output_type;
1995 case TCC_OPTION_isystem:
1996 tcc_add_sysinclude_path(s, optarg);
1997 break;
1998 case TCC_OPTION_include:
1999 cstr_printf(&s->cmdline_incl, "#include \"%s\"\n", optarg);
2000 break;
2001 case TCC_OPTION_nostdinc:
2002 s->nostdinc = 1;
2003 break;
2004 case TCC_OPTION_nostdlib:
2005 s->nostdlib = 1;
2006 break;
2007 case TCC_OPTION_run:
2008 #ifndef TCC_IS_NATIVE
2009 return tcc_error_noabort("-run is not available in a cross compiler");
2010 #else
2011 run = optarg;
2012 x = TCC_OUTPUT_MEMORY;
2013 goto set_output_type;
2014 #endif
2015 case TCC_OPTION_v:
2016 do ++s->verbose; while (*optarg++ == 'v');
2017 ++noaction;
2018 break;
2019 case TCC_OPTION_f:
2020 if (set_flag(s, options_f, optarg) < 0)
2021 goto unsupported_option;
2022 break;
2023 #ifdef TCC_TARGET_ARM
2024 case TCC_OPTION_mfloat_abi:
2025 /* tcc doesn't support soft float yet */
2026 if (!strcmp(optarg, "softfp")) {
2027 s->float_abi = ARM_SOFTFP_FLOAT;
2028 } else if (!strcmp(optarg, "hard"))
2029 s->float_abi = ARM_HARD_FLOAT;
2030 else
2031 return tcc_error_noabort("unsupported float abi '%s'", optarg);
2032 break;
2033 #endif
2034 case TCC_OPTION_m:
2035 if (set_flag(s, options_m, optarg) < 0) {
2036 if (x = atoi(optarg), x != 32 && x != 64)
2037 goto unsupported_option;
2038 if (PTR_SIZE != x/8)
2039 return x;
2040 ++noaction;
2042 break;
2043 case TCC_OPTION_W:
2044 s->warn_none = 0;
2045 if (optarg[0] && set_flag(s, options_W, optarg) < 0)
2046 goto unsupported_option;
2047 break;
2048 case TCC_OPTION_w:
2049 s->warn_none = 1;
2050 break;
2051 case TCC_OPTION_rdynamic:
2052 s->rdynamic = 1;
2053 break;
2054 case TCC_OPTION_Wl:
2055 if (s->linker_arg.size)
2056 ((char*)s->linker_arg.data)[s->linker_arg.size - 1] = ',';
2057 cstr_cat(&s->linker_arg, optarg, 0);
2058 x = tcc_set_linker(s, s->linker_arg.data);
2059 if (x)
2060 cstr_reset(&s->linker_arg);
2061 if (x < 0)
2062 return -1;
2063 break;
2064 case TCC_OPTION_Wp:
2065 r = optarg;
2066 goto reparse;
2067 case TCC_OPTION_E:
2068 x = TCC_OUTPUT_PREPROCESS;
2069 goto set_output_type;
2070 case TCC_OPTION_P:
2071 s->Pflag = atoi(optarg) + 1;
2072 break;
2073 case TCC_OPTION_M:
2074 s->include_sys_deps = 1;
2075 // fall through
2076 case TCC_OPTION_MM:
2077 s->just_deps = 1;
2078 if(!s->deps_outfile)
2079 s->deps_outfile = tcc_strdup("-");
2080 // fall through
2081 case TCC_OPTION_MMD:
2082 s->gen_deps = 1;
2083 break;
2084 case TCC_OPTION_MD:
2085 s->gen_deps = 1;
2086 s->include_sys_deps = 1;
2087 break;
2088 case TCC_OPTION_MF:
2089 s->deps_outfile = tcc_strdup(optarg);
2090 break;
2091 case TCC_OPTION_MP:
2092 s->gen_phony_deps = 1;
2093 break;
2094 case TCC_OPTION_dumpmachine:
2095 printf("%s\n", dumpmachine_str);
2096 exit(0);
2097 case TCC_OPTION_dumpversion:
2098 printf ("%s\n", TCC_VERSION);
2099 exit(0);
2100 case TCC_OPTION_x:
2101 x = 0;
2102 if (*optarg == 'c')
2103 x = AFF_TYPE_C;
2104 else if (*optarg == 'a')
2105 x = AFF_TYPE_ASMPP;
2106 else if (*optarg == 'b')
2107 x = AFF_TYPE_BIN;
2108 else if (*optarg == 'n')
2109 x = AFF_TYPE_NONE;
2110 else
2111 tcc_warning("unsupported language '%s'", optarg);
2112 s->filetype = x | (s->filetype & ~AFF_TYPE_MASK);
2113 break;
2114 case TCC_OPTION_O:
2115 s->optimize = atoi(optarg);
2116 break;
2117 case TCC_OPTION_print_search_dirs:
2118 x = OPT_PRINT_DIRS;
2119 goto extra_action;
2120 case TCC_OPTION_impdef:
2121 x = OPT_IMPDEF;
2122 goto extra_action;
2123 #if defined TCC_TARGET_MACHO
2124 case TCC_OPTION_dynamiclib:
2125 x = TCC_OUTPUT_DLL;
2126 goto set_output_type;
2127 case TCC_OPTION_flat_namespace:
2128 break;
2129 case TCC_OPTION_two_levelnamespace:
2130 break;
2131 case TCC_OPTION_undefined:
2132 break;
2133 case TCC_OPTION_install_name:
2134 s->install_name = tcc_strdup(optarg);
2135 break;
2136 case TCC_OPTION_compatibility_version:
2137 s->compatibility_version = parse_version(s, optarg);
2138 break;
2139 case TCC_OPTION_current_version:
2140 s->current_version = parse_version(s, optarg);;
2141 break;
2142 #endif
2143 case TCC_OPTION_ar:
2144 x = OPT_AR;
2145 extra_action:
2146 arg_start = optind - 1;
2147 if (arg_start != noaction)
2148 return tcc_error_noabort("cannot parse %s here", r);
2149 tool = x;
2150 break;
2151 default:
2152 unsupported_option:
2153 tcc_warning_c(warn_unsupported)("unsupported option '%s'", r);
2154 break;
2157 if (s->linker_arg.size) {
2158 r = s->linker_arg.data;
2159 goto arg_err;
2161 *pargc = argc - arg_start;
2162 *pargv = argv + arg_start;
2163 if (tool)
2164 return tool;
2165 if (optind != noaction)
2166 return 0;
2167 if (s->verbose == 2)
2168 return OPT_PRINT_DIRS;
2169 if (s->verbose)
2170 return OPT_V;
2171 return OPT_HELP;
2174 LIBTCCAPI int tcc_set_options(TCCState *s, const char *r)
2176 char **argv = NULL;
2177 int argc = 0, ret;
2178 args_parser_make_argv(r, &argc, &argv);
2179 ret = tcc_parse_args(s, &argc, &argv, 0);
2180 dynarray_reset(&argv, &argc);
2181 return ret < 0 ? ret : 0;
2184 PUB_FUNC void tcc_print_stats(TCCState *s1, unsigned total_time)
2186 if (!total_time)
2187 total_time = 1;
2188 fprintf(stderr, "# %d idents, %d lines, %u bytes\n"
2189 "# %0.3f s, %u lines/s, %0.1f MB/s\n",
2190 total_idents, total_lines, total_bytes,
2191 (double)total_time/1000,
2192 (unsigned)total_lines*1000/total_time,
2193 (double)total_bytes/1000/total_time);
2194 fprintf(stderr, "# text %u, data.rw %u, data.ro %u, bss %u bytes\n",
2195 s1->total_output[0],
2196 s1->total_output[1],
2197 s1->total_output[2],
2198 s1->total_output[3]
2200 #ifdef MEM_DEBUG
2201 fprintf(stderr, "# memory usage");
2202 #ifdef TCC_IS_NATIVE
2203 if (s1->run_size) {
2204 Section *s = s1->symtab;
2205 unsigned ms = s->data_offset + s->link->data_offset + s->hash->data_offset;
2206 unsigned rs = s1->run_size;
2207 fprintf(stderr, ": %d to run, %d symbols, %d other,",
2208 rs, ms, mem_cur_size - rs - ms);
2210 #endif
2211 fprintf(stderr, " %d max (bytes)\n", mem_max_size);
2212 #endif