NetBSD: define __amd64__ which is sometimes used in headers.
[tinycc/self_contained.git] / libtcc.c
blobd13371f8420b2628f6503ae03683be5b21f6bba7
1 /*
2 * TCC - Tiny C Compiler
4 * Copyright (c) 2001-2004 Fabrice Bellard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 #if !defined ONE_SOURCE || ONE_SOURCE
22 #include "tccpp.c"
23 #include "tccgen.c"
24 #include "tccelf.c"
25 #include "tccrun.c"
26 #ifdef TCC_TARGET_I386
27 #include "i386-gen.c"
28 #include "i386-link.c"
29 #include "i386-asm.c"
30 #elif defined(TCC_TARGET_ARM)
31 #include "arm-gen.c"
32 #include "arm-link.c"
33 #include "arm-asm.c"
34 #elif defined(TCC_TARGET_ARM64)
35 #include "arm64-gen.c"
36 #include "arm64-link.c"
37 #include "arm-asm.c"
38 #elif defined(TCC_TARGET_C67)
39 #include "c67-gen.c"
40 #include "c67-link.c"
41 #include "tcccoff.c"
42 #elif defined(TCC_TARGET_X86_64)
43 #include "x86_64-gen.c"
44 #include "x86_64-link.c"
45 #include "i386-asm.c"
46 #elif defined(TCC_TARGET_RISCV64)
47 #include "riscv64-gen.c"
48 #include "riscv64-link.c"
49 #include "riscv64-asm.c"
50 #else
51 #error unknown target
52 #endif
53 #ifdef CONFIG_TCC_ASM
54 #include "tccasm.c"
55 #endif
56 #ifdef TCC_TARGET_PE
57 #include "tccpe.c"
58 #endif
59 #ifdef TCC_TARGET_MACHO
60 #include "tccmacho.c"
61 #endif
62 #endif /* ONE_SOURCE */
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;
72 #ifdef MEM_DEBUG
73 static int nb_states;
74 #endif
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 static HMODULE tcc_module;
89 /* on win32, we suppose the lib and includes are at the location of 'tcc.exe' */
90 static void tcc_set_lib_path_w32(TCCState *s)
92 char path[1024], *p;
93 GetModuleFileNameA(tcc_module, path, sizeof path);
94 p = tcc_basename(normalize_slashes(strlwr(path)));
95 if (p > path)
96 --p;
97 *p = 0;
98 tcc_set_lib_path(s, path);
101 #ifdef TCC_TARGET_PE
102 static void tcc_add_systemdir(TCCState *s)
104 char buf[1000];
105 GetSystemDirectory(buf, sizeof buf);
106 tcc_add_library_path(s, normalize_slashes(buf));
108 #endif
110 #ifdef LIBTCC_AS_DLL
111 BOOL WINAPI DllMain (HINSTANCE hDll, DWORD dwReason, LPVOID lpReserved)
113 if (DLL_PROCESS_ATTACH == dwReason)
114 tcc_module = hDll;
115 return TRUE;
117 #endif
118 #endif
120 /********************************************************/
121 #ifndef CONFIG_TCC_SEMLOCK
122 #define WAIT_SEM()
123 #define POST_SEM()
124 #elif defined _WIN32
125 static int tcc_sem_init;
126 static CRITICAL_SECTION tcc_cr;
127 static void wait_sem(void)
129 if (!tcc_sem_init)
130 InitializeCriticalSection(&tcc_cr), tcc_sem_init = 1;
131 EnterCriticalSection(&tcc_cr);
133 #define WAIT_SEM() wait_sem()
134 #define POST_SEM() LeaveCriticalSection(&tcc_cr);
135 #elif defined __APPLE__
136 /* Half-compatible MacOS doesn't have non-shared (process local)
137 semaphores. Use the dispatch framework for lightweight locks. */
138 #include <dispatch/dispatch.h>
139 static int tcc_sem_init;
140 static dispatch_semaphore_t tcc_sem;
141 static void wait_sem(void)
143 if (!tcc_sem_init)
144 tcc_sem = dispatch_semaphore_create(1), tcc_sem_init = 1;
145 dispatch_semaphore_wait(tcc_sem, DISPATCH_TIME_FOREVER);
147 #define WAIT_SEM() wait_sem()
148 #define POST_SEM() dispatch_semaphore_signal(tcc_sem)
149 #else
150 #include <semaphore.h>
151 static int tcc_sem_init;
152 static sem_t tcc_sem;
153 static void wait_sem(void)
155 if (!tcc_sem_init)
156 sem_init(&tcc_sem, 0, 1), tcc_sem_init = 1;
157 while (sem_wait (&tcc_sem) < 0 && errno == EINTR);
159 #define WAIT_SEM() wait_sem()
160 #define POST_SEM() sem_post(&tcc_sem)
161 #endif
163 /********************************************************/
164 /* copy a string and truncate it. */
165 ST_FUNC char *pstrcpy(char *buf, size_t buf_size, const char *s)
167 char *q, *q_end;
168 int c;
170 if (buf_size > 0) {
171 q = buf;
172 q_end = buf + buf_size - 1;
173 while (q < q_end) {
174 c = *s++;
175 if (c == '\0')
176 break;
177 *q++ = c;
179 *q = '\0';
181 return buf;
184 /* strcat and truncate. */
185 ST_FUNC char *pstrcat(char *buf, size_t buf_size, const char *s)
187 size_t len;
188 len = strlen(buf);
189 if (len < buf_size)
190 pstrcpy(buf + len, buf_size - len, s);
191 return buf;
194 ST_FUNC char *pstrncpy(char *out, const char *in, size_t num)
196 memcpy(out, in, num);
197 out[num] = '\0';
198 return out;
201 /* extract the basename of a file */
202 PUB_FUNC char *tcc_basename(const char *name)
204 char *p = strchr(name, 0);
205 while (p > name && !IS_DIRSEP(p[-1]))
206 --p;
207 return p;
210 /* extract extension part of a file
212 * (if no extension, return pointer to end-of-string)
214 PUB_FUNC char *tcc_fileextension (const char *name)
216 char *b = tcc_basename(name);
217 char *e = strrchr(b, '.');
218 return e ? e : strchr(b, 0);
221 /********************************************************/
222 /* memory management */
224 #undef free
225 #undef malloc
226 #undef realloc
228 #ifndef MEM_DEBUG
230 PUB_FUNC void tcc_free(void *ptr)
232 free(ptr);
235 PUB_FUNC void *tcc_malloc(unsigned long size)
237 void *ptr;
238 ptr = malloc(size);
239 if (!ptr && size)
240 _tcc_error("memory full (malloc)");
241 return ptr;
244 PUB_FUNC void *tcc_mallocz(unsigned long size)
246 void *ptr;
247 ptr = tcc_malloc(size);
248 if (size)
249 memset(ptr, 0, size);
250 return ptr;
253 PUB_FUNC void *tcc_realloc(void *ptr, unsigned long size)
255 void *ptr1;
256 ptr1 = realloc(ptr, size);
257 if (!ptr1 && size)
258 _tcc_error("memory full (realloc)");
259 return ptr1;
262 PUB_FUNC char *tcc_strdup(const char *str)
264 char *ptr;
265 ptr = tcc_malloc(strlen(str) + 1);
266 strcpy(ptr, str);
267 return ptr;
270 #else
272 #define MEM_DEBUG_MAGIC1 0xFEEDDEB1
273 #define MEM_DEBUG_MAGIC2 0xFEEDDEB2
274 #define MEM_DEBUG_MAGIC3 0xFEEDDEB3
275 #define MEM_DEBUG_FILE_LEN 40
276 #define MEM_DEBUG_CHECK3(header) \
277 ((mem_debug_header_t*)((char*)header + header->size))->magic3
278 #define MEM_USER_PTR(header) \
279 ((char *)header + offsetof(mem_debug_header_t, magic3))
280 #define MEM_HEADER_PTR(ptr) \
281 (mem_debug_header_t *)((char*)ptr - offsetof(mem_debug_header_t, magic3))
283 struct mem_debug_header {
284 unsigned magic1;
285 unsigned size;
286 struct mem_debug_header *prev;
287 struct mem_debug_header *next;
288 int line_num;
289 char file_name[MEM_DEBUG_FILE_LEN + 1];
290 unsigned magic2;
291 ALIGNED(16) unsigned magic3;
294 typedef struct mem_debug_header mem_debug_header_t;
296 static mem_debug_header_t *mem_debug_chain;
297 static unsigned mem_cur_size;
298 static unsigned mem_max_size;
300 static mem_debug_header_t *malloc_check(void *ptr, const char *msg)
302 mem_debug_header_t * header = MEM_HEADER_PTR(ptr);
303 if (header->magic1 != MEM_DEBUG_MAGIC1 ||
304 header->magic2 != MEM_DEBUG_MAGIC2 ||
305 MEM_DEBUG_CHECK3(header) != MEM_DEBUG_MAGIC3 ||
306 header->size == (unsigned)-1) {
307 fprintf(stderr, "%s check failed\n", msg);
308 if (header->magic1 == MEM_DEBUG_MAGIC1)
309 fprintf(stderr, "%s:%u: block allocated here.\n",
310 header->file_name, header->line_num);
311 exit(1);
313 return header;
316 PUB_FUNC void *tcc_malloc_debug(unsigned long size, const char *file, int line)
318 int ofs;
319 mem_debug_header_t *header;
321 header = malloc(sizeof(mem_debug_header_t) + size);
322 if (!header)
323 _tcc_error("memory full (malloc)");
325 header->magic1 = MEM_DEBUG_MAGIC1;
326 header->magic2 = MEM_DEBUG_MAGIC2;
327 header->size = size;
328 MEM_DEBUG_CHECK3(header) = MEM_DEBUG_MAGIC3;
329 header->line_num = line;
330 ofs = strlen(file) - MEM_DEBUG_FILE_LEN;
331 strncpy(header->file_name, file + (ofs > 0 ? ofs : 0), MEM_DEBUG_FILE_LEN);
332 header->file_name[MEM_DEBUG_FILE_LEN] = 0;
334 header->next = mem_debug_chain;
335 header->prev = NULL;
336 if (header->next)
337 header->next->prev = header;
338 mem_debug_chain = header;
340 mem_cur_size += size;
341 if (mem_cur_size > mem_max_size)
342 mem_max_size = mem_cur_size;
344 return MEM_USER_PTR(header);
347 PUB_FUNC void tcc_free_debug(void *ptr)
349 mem_debug_header_t *header;
350 if (!ptr)
351 return;
352 header = malloc_check(ptr, "tcc_free");
353 mem_cur_size -= header->size;
354 header->size = (unsigned)-1;
355 if (header->next)
356 header->next->prev = header->prev;
357 if (header->prev)
358 header->prev->next = header->next;
359 if (header == mem_debug_chain)
360 mem_debug_chain = header->next;
361 free(header);
364 PUB_FUNC void *tcc_mallocz_debug(unsigned long size, const char *file, int line)
366 void *ptr;
367 ptr = tcc_malloc_debug(size,file,line);
368 memset(ptr, 0, size);
369 return ptr;
372 PUB_FUNC void *tcc_realloc_debug(void *ptr, unsigned long size, const char *file, int line)
374 mem_debug_header_t *header;
375 int mem_debug_chain_update = 0;
376 if (!ptr)
377 return tcc_malloc_debug(size, file, line);
378 header = malloc_check(ptr, "tcc_realloc");
379 mem_cur_size -= header->size;
380 mem_debug_chain_update = (header == mem_debug_chain);
381 header = realloc(header, sizeof(mem_debug_header_t) + size);
382 if (!header)
383 _tcc_error("memory full (realloc)");
384 header->size = size;
385 MEM_DEBUG_CHECK3(header) = MEM_DEBUG_MAGIC3;
386 if (header->next)
387 header->next->prev = header;
388 if (header->prev)
389 header->prev->next = header;
390 if (mem_debug_chain_update)
391 mem_debug_chain = header;
392 mem_cur_size += size;
393 if (mem_cur_size > mem_max_size)
394 mem_max_size = mem_cur_size;
395 return MEM_USER_PTR(header);
398 PUB_FUNC char *tcc_strdup_debug(const char *str, const char *file, int line)
400 char *ptr;
401 ptr = tcc_malloc_debug(strlen(str) + 1, file, line);
402 strcpy(ptr, str);
403 return ptr;
406 PUB_FUNC void tcc_memcheck(void)
408 if (mem_cur_size) {
409 mem_debug_header_t *header = mem_debug_chain;
410 fprintf(stderr, "MEM_DEBUG: mem_leak= %d bytes, mem_max_size= %d bytes\n",
411 mem_cur_size, mem_max_size);
412 while (header) {
413 fprintf(stderr, "%s:%u: error: %u bytes leaked\n",
414 header->file_name, header->line_num, header->size);
415 header = header->next;
417 #if MEM_DEBUG-0 == 2
418 exit(2);
419 #endif
422 #endif /* MEM_DEBUG */
424 #define free(p) use_tcc_free(p)
425 #define malloc(s) use_tcc_malloc(s)
426 #define realloc(p, s) use_tcc_realloc(p, s)
428 /********************************************************/
429 /* dynarrays */
431 ST_FUNC void dynarray_add(void *ptab, int *nb_ptr, void *data)
433 int nb, nb_alloc;
434 void **pp;
436 nb = *nb_ptr;
437 pp = *(void ***)ptab;
438 /* every power of two we double array size */
439 if ((nb & (nb - 1)) == 0) {
440 if (!nb)
441 nb_alloc = 1;
442 else
443 nb_alloc = nb * 2;
444 pp = tcc_realloc(pp, nb_alloc * sizeof(void *));
445 *(void***)ptab = pp;
447 pp[nb++] = data;
448 *nb_ptr = nb;
451 ST_FUNC void dynarray_reset(void *pp, int *n)
453 void **p;
454 for (p = *(void***)pp; *n; ++p, --*n)
455 if (*p)
456 tcc_free(*p);
457 tcc_free(*(void**)pp);
458 *(void**)pp = NULL;
461 static void tcc_split_path(TCCState *s, void *p_ary, int *p_nb_ary, const char *in)
463 const char *p;
464 do {
465 int c;
466 CString str;
468 cstr_new(&str);
469 for (p = in; c = *p, c != '\0' && c != PATHSEP[0]; ++p) {
470 if (c == '{' && p[1] && p[2] == '}') {
471 c = p[1], p += 2;
472 if (c == 'B')
473 cstr_cat(&str, s->tcc_lib_path, -1);
474 if (c == 'f' && file) {
475 /* substitute current file's dir */
476 const char *f = file->true_filename;
477 const char *b = tcc_basename(f);
478 if (b > f)
479 cstr_cat(&str, f, b - f - 1);
480 else
481 cstr_cat(&str, ".", 1);
483 } else {
484 cstr_ccat(&str, c);
487 if (str.size) {
488 cstr_ccat(&str, '\0');
489 dynarray_add(p_ary, p_nb_ary, tcc_strdup(str.data));
491 cstr_free(&str);
492 in = p+1;
493 } while (*p);
496 /********************************************************/
498 static void strcat_vprintf(char *buf, int buf_size, const char *fmt, va_list ap)
500 int len;
501 len = strlen(buf);
502 vsnprintf(buf + len, buf_size - len, fmt, ap);
505 static void strcat_printf(char *buf, int buf_size, const char *fmt, ...)
507 va_list ap;
508 va_start(ap, fmt);
509 strcat_vprintf(buf, buf_size, fmt, ap);
510 va_end(ap);
513 #define ERROR_WARN 0
514 #define ERROR_NOABORT 1
515 #define ERROR_ERROR 2
517 PUB_FUNC void tcc_enter_state(TCCState *s1)
519 WAIT_SEM();
520 tcc_state = s1;
523 PUB_FUNC void tcc_exit_state(void)
525 tcc_state = NULL;
526 POST_SEM();
529 static void error1(int mode, const char *fmt, va_list ap)
531 char buf[2048];
532 BufferedFile **pf, *f;
533 TCCState *s1 = tcc_state;
535 buf[0] = '\0';
536 if (s1 == NULL)
537 /* can happen only if called from tcc_malloc(): 'out of memory' */
538 goto no_file;
540 if (s1 && !s1->error_set_jmp_enabled)
541 /* tcc_state just was set by tcc_enter_state() */
542 tcc_exit_state();
544 if (mode == ERROR_WARN) {
545 if (s1->warn_none)
546 return;
547 if (s1->warn_error)
548 mode = ERROR_ERROR;
551 f = NULL;
552 if (s1->error_set_jmp_enabled) { /* we're called while parsing a file */
553 /* use upper file if inline ":asm:" or token ":paste:" */
554 for (f = file; f && f->filename[0] == ':'; f = f->prev)
557 if (f) {
558 for(pf = s1->include_stack; pf < s1->include_stack_ptr; pf++)
559 strcat_printf(buf, sizeof(buf), "In file included from %s:%d:\n",
560 (*pf)->filename, (*pf)->line_num);
561 strcat_printf(buf, sizeof(buf), "%s:%d: ",
562 f->filename, f->line_num - !!(tok_flags & TOK_FLAG_BOL));
563 } else if (s1->current_filename) {
564 strcat_printf(buf, sizeof(buf), "%s: ", s1->current_filename);
567 no_file:
568 if (0 == buf[0])
569 strcat_printf(buf, sizeof(buf), "tcc: ");
570 if (mode == ERROR_WARN)
571 strcat_printf(buf, sizeof(buf), "warning: ");
572 else
573 strcat_printf(buf, sizeof(buf), "error: ");
574 strcat_vprintf(buf, sizeof(buf), fmt, ap);
575 if (!s1 || !s1->error_func) {
576 /* default case: stderr */
577 if (s1 && s1->output_type == TCC_OUTPUT_PREPROCESS && s1->ppfp == stdout)
578 /* print a newline during tcc -E */
579 printf("\n"), fflush(stdout);
580 fflush(stdout); /* flush -v output */
581 fprintf(stderr, "%s\n", buf);
582 fflush(stderr); /* print error/warning now (win32) */
583 } else {
584 s1->error_func(s1->error_opaque, buf);
586 if (s1) {
587 if (mode != ERROR_WARN)
588 s1->nb_errors++;
589 if (mode != ERROR_ERROR)
590 return;
591 if (s1->error_set_jmp_enabled)
592 longjmp(s1->error_jmp_buf, 1);
594 exit(1);
597 LIBTCCAPI void tcc_set_error_func(TCCState *s, void *error_opaque, TCCErrorFunc error_func)
599 s->error_opaque = error_opaque;
600 s->error_func = error_func;
603 LIBTCCAPI TCCErrorFunc tcc_get_error_func(TCCState *s)
605 return s->error_func;
608 LIBTCCAPI void *tcc_get_error_opaque(TCCState *s)
610 return s->error_opaque;
613 /* error without aborting current compilation */
614 PUB_FUNC void _tcc_error_noabort(const char *fmt, ...)
616 va_list ap;
617 va_start(ap, fmt);
618 error1(ERROR_NOABORT, fmt, ap);
619 va_end(ap);
622 PUB_FUNC void _tcc_error(const char *fmt, ...)
624 va_list ap;
625 va_start(ap, fmt);
626 for (;;) error1(ERROR_ERROR, fmt, ap);
629 PUB_FUNC void _tcc_warning(const char *fmt, ...)
631 va_list ap;
632 va_start(ap, fmt);
633 error1(ERROR_WARN, fmt, ap);
634 va_end(ap);
637 /********************************************************/
638 /* I/O layer */
640 ST_FUNC void tcc_open_bf(TCCState *s1, const char *filename, int initlen)
642 BufferedFile *bf;
643 int buflen = initlen ? initlen : IO_BUF_SIZE;
645 bf = tcc_mallocz(sizeof(BufferedFile) + buflen);
646 bf->buf_ptr = bf->buffer;
647 bf->buf_end = bf->buffer + initlen;
648 bf->buf_end[0] = CH_EOB; /* put eob symbol */
649 pstrcpy(bf->filename, sizeof(bf->filename), filename);
650 #ifdef _WIN32
651 normalize_slashes(bf->filename);
652 #endif
653 bf->true_filename = bf->filename;
654 bf->line_num = 1;
655 bf->ifdef_stack_ptr = s1->ifdef_stack_ptr;
656 bf->fd = -1;
657 bf->prev = file;
658 file = bf;
659 tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
662 ST_FUNC void tcc_close(void)
664 TCCState *s1 = tcc_state;
665 BufferedFile *bf = file;
666 if (bf->fd > 0) {
667 close(bf->fd);
668 total_lines += bf->line_num;
670 if (bf->true_filename != bf->filename)
671 tcc_free(bf->true_filename);
672 file = bf->prev;
673 tcc_free(bf);
676 static int _tcc_open(TCCState *s1, const char *filename)
678 int fd;
679 if (strcmp(filename, "-") == 0)
680 fd = 0, filename = "<stdin>";
681 else
682 fd = open(filename, O_RDONLY | O_BINARY);
683 if ((s1->verbose == 2 && fd >= 0) || s1->verbose == 3)
684 printf("%s %*s%s\n", fd < 0 ? "nf":"->",
685 (int)(s1->include_stack_ptr - s1->include_stack), "", filename);
686 return fd;
689 ST_FUNC int tcc_open(TCCState *s1, const char *filename)
691 int fd = _tcc_open(s1, filename);
692 if (fd < 0)
693 return -1;
694 tcc_open_bf(s1, filename, 0);
695 file->fd = fd;
696 return 0;
699 /* compile the file opened in 'file'. Return non zero if errors. */
700 static int tcc_compile(TCCState *s1, int filetype, const char *str, int fd)
702 /* Here we enter the code section where we use the global variables for
703 parsing and code generation (tccpp.c, tccgen.c, <target>-gen.c).
704 Other threads need to wait until we're done.
706 Alternatively we could use thread local storage for those global
707 variables, which may or may not have advantages */
709 tcc_enter_state(s1);
711 if (setjmp(s1->error_jmp_buf) == 0) {
712 s1->error_set_jmp_enabled = 1;
713 s1->nb_errors = 0;
715 if (fd == -1) {
716 int len = strlen(str);
717 tcc_open_bf(s1, "<string>", len);
718 memcpy(file->buffer, str, len);
719 } else {
720 tcc_open_bf(s1, str, 0);
721 file->fd = fd;
724 tccelf_begin_file(s1);
725 preprocess_start(s1, filetype);
726 tccgen_init(s1);
727 if (s1->output_type == TCC_OUTPUT_PREPROCESS) {
728 tcc_preprocess(s1);
729 } else if (filetype & (AFF_TYPE_ASM | AFF_TYPE_ASMPP)) {
730 #ifdef CONFIG_TCC_ASM
731 tcc_assemble(s1, !!(filetype & AFF_TYPE_ASMPP));
732 #else
733 tcc_error_noabort("asm not supported");
734 #endif
735 } else {
736 tccgen_compile(s1);
739 s1->error_set_jmp_enabled = 0;
740 tccgen_finish(s1);
741 preprocess_end(s1);
742 tcc_exit_state();
744 tccelf_end_file(s1);
745 return s1->nb_errors != 0 ? -1 : 0;
748 LIBTCCAPI int tcc_compile_string(TCCState *s, const char *str)
750 return tcc_compile(s, s->filetype, str, -1);
753 /* define a preprocessor symbol. value can be NULL, sym can be "sym=val" */
754 LIBTCCAPI void tcc_define_symbol(TCCState *s1, const char *sym, const char *value)
756 const char *eq;
757 if (NULL == (eq = strchr(sym, '=')))
758 eq = strchr(sym, 0);
759 if (NULL == value)
760 value = *eq ? eq + 1 : "1";
761 cstr_printf(&s1->cmdline_defs, "#define %.*s %s\n", (int)(eq-sym), sym, value);
764 /* undefine a preprocessor symbol */
765 LIBTCCAPI void tcc_undefine_symbol(TCCState *s1, const char *sym)
767 cstr_printf(&s1->cmdline_defs, "#undef %s\n", sym);
771 LIBTCCAPI TCCState *tcc_new(void)
773 TCCState *s;
775 s = tcc_mallocz(sizeof(TCCState));
776 if (!s)
777 return NULL;
778 #ifdef MEM_DEBUG
779 ++nb_states;
780 #endif
782 #undef gnu_ext
784 s->gnu_ext = 1;
785 s->tcc_ext = 1;
786 s->nocommon = 1;
787 s->dollars_in_identifiers = 1; /*on by default like in gcc/clang*/
788 s->cversion = 199901; /* default unless -std=c11 is supplied */
789 s->warn_implicit_function_declaration = 1;
790 s->ms_extensions = 1;
792 #ifdef CHAR_IS_UNSIGNED
793 s->char_is_unsigned = 1;
794 #endif
795 #ifdef TCC_TARGET_I386
796 s->seg_size = 32;
797 #endif
798 /* enable this if you want symbols with leading underscore on windows: */
799 #if defined TCC_TARGET_MACHO /* || defined TCC_TARGET_PE */
800 s->leading_underscore = 1;
801 #endif
802 s->ppfp = stdout;
803 /* might be used in error() before preprocess_start() */
804 s->include_stack_ptr = s->include_stack;
806 tccelf_new(s);
808 #ifdef _WIN32
809 tcc_set_lib_path_w32(s);
810 #else
811 tcc_set_lib_path(s, CONFIG_TCCDIR);
812 #endif
815 /* define __TINYC__ 92X */
816 char buffer[32]; int a,b,c;
817 sscanf(TCC_VERSION, "%d.%d.%d", &a, &b, &c);
818 sprintf(buffer, "%d", a*10000 + b*100 + c);
819 tcc_define_symbol(s, "__TINYC__", buffer);
822 /* standard defines */
823 tcc_define_symbol(s, "__STDC__", NULL);
824 tcc_define_symbol(s, "__STDC_VERSION__", "199901L");
825 tcc_define_symbol(s, "__STDC_HOSTED__", NULL);
827 /* target defines */
828 #if defined(TCC_TARGET_I386)
829 tcc_define_symbol(s, "__i386__", NULL);
830 tcc_define_symbol(s, "__i386", NULL);
831 tcc_define_symbol(s, "i386", NULL);
832 #elif defined(TCC_TARGET_X86_64)
833 tcc_define_symbol(s, "__x86_64__", NULL);
834 #elif defined(TCC_TARGET_ARM)
835 tcc_define_symbol(s, "__ARM_ARCH_4__", NULL);
836 tcc_define_symbol(s, "__arm_elf__", NULL);
837 tcc_define_symbol(s, "__arm_elf", NULL);
838 tcc_define_symbol(s, "arm_elf", NULL);
839 tcc_define_symbol(s, "__arm__", NULL);
840 tcc_define_symbol(s, "__arm", NULL);
841 tcc_define_symbol(s, "arm", NULL);
842 tcc_define_symbol(s, "__APCS_32__", NULL);
843 tcc_define_symbol(s, "__ARMEL__", NULL);
844 #if defined(TCC_ARM_EABI)
845 tcc_define_symbol(s, "__ARM_EABI__", NULL);
846 #endif
847 #if defined(TCC_ARM_HARDFLOAT)
848 s->float_abi = ARM_HARD_FLOAT;
849 tcc_define_symbol(s, "__ARM_PCS_VFP", NULL);
850 #else
851 s->float_abi = ARM_SOFTFP_FLOAT;
852 #endif
853 #elif defined(TCC_TARGET_ARM64)
854 tcc_define_symbol(s, "__aarch64__", NULL);
855 #elif defined TCC_TARGET_C67
856 tcc_define_symbol(s, "__C67__", NULL);
857 #elif defined TCC_TARGET_RISCV64
858 tcc_define_symbol(s, "__riscv", NULL);
859 tcc_define_symbol(s, "__riscv_xlen", "64");
860 tcc_define_symbol(s, "__riscv_flen", "64");
861 tcc_define_symbol(s, "__riscv_div", NULL);
862 tcc_define_symbol(s, "__riscv_mul", NULL);
863 tcc_define_symbol(s, "__riscv_fdiv", NULL);
864 tcc_define_symbol(s, "__riscv_fsqrt", NULL);
865 tcc_define_symbol(s, "__riscv_float_abi_double", NULL);
866 #endif
868 #ifdef TCC_TARGET_PE
869 tcc_define_symbol(s, "_WIN32", NULL);
870 tcc_define_symbol(s, "__declspec(x)", "__attribute__((x))");
871 tcc_define_symbol(s, "__cdecl", "");
872 # ifdef TCC_TARGET_X86_64
873 tcc_define_symbol(s, "_WIN64", NULL);
874 # endif
875 #else
876 tcc_define_symbol(s, "__unix__", NULL);
877 tcc_define_symbol(s, "__unix", NULL);
878 tcc_define_symbol(s, "unix", NULL);
879 # if defined(__linux__)
880 tcc_define_symbol(s, "__linux__", NULL);
881 tcc_define_symbol(s, "__linux", NULL);
882 # endif
883 # if TARGETOS_FreeBSD
884 tcc_define_symbol(s, "__FreeBSD__", "12");
885 /* No 'Thread Storage Local' on FreeBSD with tcc */
886 tcc_define_symbol(s, "__NO_TLS", NULL);
887 tcc_define_symbol(s, "__builtin_huge_val()", "1e500");
888 tcc_define_symbol(s, "__builtin_huge_valf()", "1e50f");
889 tcc_define_symbol(s, "__builtin_huge_vall()", "1e5000L");
890 tcc_define_symbol(s, "__builtin_nanf(ignored_string)", "(0.0F/0.0F)");
891 # if defined(__aarch64__)
892 /* FIXME, __int128_t is used by setjump */
893 tcc_define_symbol(s, "__int128_t", "struct { unsigned char _dummy[16]; }");
894 # endif
895 # endif
896 # if TARGETOS_FreeBSD_kernel
897 tcc_define_symbol(s, "__FreeBSD_kernel__", NULL);
898 # endif
899 # if TARGETOS_NetBSD
900 tcc_define_symbol(s, "__NetBSD__", "1");
901 tcc_define_symbol(s, "__GNUC__", "4");
902 tcc_define_symbol(s, "__GNUC_MINOR__", "0");
903 tcc_define_symbol(s, "__GNUC_PATCHLEVEL__", "0");
904 tcc_define_symbol(s, "_Pragma(x)", "");
905 tcc_define_symbol(s, "__ELF__", "1");
906 tcc_define_symbol(s, "__amd64__", "1");
907 tcc_define_symbol(s, "__builtin_huge_val()", "1e500");
908 tcc_define_symbol(s, "__builtin_huge_valf()", "1e50f");
909 tcc_define_symbol(s, "__builtin_huge_vall()", "1e5000L");
910 tcc_define_symbol(s, "__builtin_nanf(ignored_string)", "(0.0F/0.0F)");
911 # endif
912 # if TARGETOS_OpenBSD
913 tcc_define_symbol(s, "__OpenBSD__", "1");
914 tcc_define_symbol(s, "_ANSI_LIBRARY", "1");
915 tcc_define_symbol(s, "__GNUC__", "4");
916 /* used by math.h */
917 tcc_define_symbol(s, "__builtin_huge_val()", "1e500");
918 tcc_define_symbol(s, "__builtin_huge_valf()", "1e50f");
919 tcc_define_symbol(s, "__builtin_huge_vall()", "1e5000L");
920 tcc_define_symbol(s, "__builtin_nanf(ignored_string)", "(0.0F/0.0F)");
921 # endif
922 #endif
924 /* TinyCC & gcc defines */
925 #if PTR_SIZE == 4
926 /* 32bit systems. */
927 tcc_define_symbol(s, "__SIZE_TYPE__", "unsigned int");
928 tcc_define_symbol(s, "__PTRDIFF_TYPE__", "int");
929 tcc_define_symbol(s, "__ILP32__", NULL);
930 #elif LONG_SIZE == 4
931 /* 64bit Windows. */
932 tcc_define_symbol(s, "__SIZE_TYPE__", "unsigned long long");
933 tcc_define_symbol(s, "__PTRDIFF_TYPE__", "long long");
934 tcc_define_symbol(s, "__LLP64__", NULL);
935 #else
936 /* Other 64bit systems. */
937 tcc_define_symbol(s, "__SIZE_TYPE__", "unsigned long");
938 tcc_define_symbol(s, "__PTRDIFF_TYPE__", "long");
939 tcc_define_symbol(s, "__LP64__", NULL);
940 #endif
941 tcc_define_symbol(s, "__SIZEOF_POINTER__", PTR_SIZE == 4 ? "4" : "8");
943 #ifdef TCC_TARGET_PE
944 tcc_define_symbol(s, "__WCHAR_TYPE__", "unsigned short");
945 tcc_define_symbol(s, "__WINT_TYPE__", "unsigned short");
946 #else
947 tcc_define_symbol(s, "__WCHAR_TYPE__", "int");
948 /* wint_t is unsigned int by default, but (signed) int on BSDs
949 and unsigned short on windows. Other OSes might have still
950 other conventions, sigh. */
951 # if TARGETOS_FreeBSD || TARGETOS_FreeBSD_kernel || TARGETOS_NetBSD || TARGETOS_OpenBSD
952 tcc_define_symbol(s, "__WINT_TYPE__", "int");
953 # if TARGETOS_FreeBSD
954 /* define __GNUC__ to have some useful stuff from sys/cdefs.h
955 that are unconditionally used in FreeBSDs other system headers :/ */
956 tcc_define_symbol(s, "__GNUC__", "9");
957 tcc_define_symbol(s, "__GNUC_MINOR__", "3");
958 tcc_define_symbol(s, "__GNUC_PATCHLEVEL__", "0");
959 tcc_define_symbol(s, "__GNUC_STDC_INLINE__", "1");
960 tcc_define_symbol(s, "__amd64__", "1");
961 # endif
962 # else
963 tcc_define_symbol(s, "__WINT_TYPE__", "unsigned int");
964 /* glibc defines */
965 tcc_define_symbol(s, "__REDIRECT(name, proto, alias)",
966 "name proto __asm__ (#alias)");
967 tcc_define_symbol(s, "__REDIRECT_NTH(name, proto, alias)",
968 "name proto __asm__ (#alias) __THROW");
969 # endif
970 /* Some GCC builtins that are simple to express as macros. */
971 tcc_define_symbol(s, "__builtin_extract_return_addr(x)", "x");
972 #endif /* ndef TCC_TARGET_PE */
973 #ifdef TCC_TARGET_MACHO
974 /* emulate APPLE-GCC to make libc's headerfiles compile: */
975 tcc_define_symbol(s, "__APPLE__", "1");
976 tcc_define_symbol(s, "__GNUC__", "4"); /* darwin emits warning on GCC<4 */
977 tcc_define_symbol(s, "__APPLE_CC__", "1"); /* for <TargetConditionals.h> */
978 tcc_define_symbol(s, "_DONT_USE_CTYPE_INLINE_", "1");
979 /* used by math.h */
980 tcc_define_symbol(s, "__builtin_huge_val()", "1e500");
981 tcc_define_symbol(s, "__builtin_huge_valf()", "1e50f");
982 tcc_define_symbol(s, "__builtin_huge_vall()", "1e5000L");
983 tcc_define_symbol(s, "__builtin_nanf(ignored_string)", "__nan()");
984 /* used by _fd_def.h */
985 tcc_define_symbol(s, "__builtin_bzero(p, ignored_size)", "bzero(p, sizeof(*(p)))");
986 /* used by floats.h to implement FLT_ROUNDS C99 macro. 1 == to nearest */
987 tcc_define_symbol(s, "__builtin_flt_rounds()", "1");
989 /* avoids usage of GCC/clang specific builtins in libc-headerfiles: */
990 tcc_define_symbol(s, "__FINITE_MATH_ONLY__", "1");
991 tcc_define_symbol(s, "_FORTIFY_SOURCE", "0");
992 #endif /* ndef TCC_TARGET_MACHO */
994 #if LONG_SIZE == 4
995 tcc_define_symbol(s, "__SIZEOF_LONG__", "4");
996 tcc_define_symbol(s, "__LONG_MAX__", "0x7fffffffL");
997 #else
998 tcc_define_symbol(s, "__SIZEOF_LONG__", "8");
999 tcc_define_symbol(s, "__LONG_MAX__", "0x7fffffffffffffffL");
1000 #endif
1001 tcc_define_symbol(s, "__SIZEOF_INT__", "4");
1002 tcc_define_symbol(s, "__SIZEOF_LONG_LONG__", "8");
1003 tcc_define_symbol(s, "__CHAR_BIT__", "8");
1004 tcc_define_symbol(s, "__ORDER_LITTLE_ENDIAN__", "1234");
1005 tcc_define_symbol(s, "__ORDER_BIG_ENDIAN__", "4321");
1006 tcc_define_symbol(s, "__BYTE_ORDER__", "__ORDER_LITTLE_ENDIAN__");
1007 tcc_define_symbol(s, "__INT_MAX__", "0x7fffffff");
1008 tcc_define_symbol(s, "__LONG_LONG_MAX__", "0x7fffffffffffffffLL");
1009 tcc_define_symbol(s, "__builtin_offsetof(type,field)", "((__SIZE_TYPE__) &((type *)0)->field)");
1010 return s;
1013 LIBTCCAPI void tcc_delete(TCCState *s1)
1015 /* free sections */
1016 tccelf_delete(s1);
1018 /* free library paths */
1019 dynarray_reset(&s1->library_paths, &s1->nb_library_paths);
1020 dynarray_reset(&s1->crt_paths, &s1->nb_crt_paths);
1022 /* free include paths */
1023 dynarray_reset(&s1->include_paths, &s1->nb_include_paths);
1024 dynarray_reset(&s1->sysinclude_paths, &s1->nb_sysinclude_paths);
1026 tcc_free(s1->tcc_lib_path);
1027 tcc_free(s1->soname);
1028 tcc_free(s1->rpath);
1029 tcc_free(s1->init_symbol);
1030 tcc_free(s1->fini_symbol);
1031 tcc_free(s1->outfile);
1032 tcc_free(s1->deps_outfile);
1033 dynarray_reset(&s1->files, &s1->nb_files);
1034 dynarray_reset(&s1->target_deps, &s1->nb_target_deps);
1035 dynarray_reset(&s1->pragma_libs, &s1->nb_pragma_libs);
1036 dynarray_reset(&s1->argv, &s1->argc);
1037 cstr_free(&s1->cmdline_defs);
1038 cstr_free(&s1->cmdline_incl);
1039 #ifdef TCC_IS_NATIVE
1040 /* free runtime memory */
1041 tcc_run_free(s1);
1042 #endif
1044 tcc_free(s1);
1045 #ifdef MEM_DEBUG
1046 if (0 == --nb_states)
1047 tcc_memcheck();
1048 #endif
1051 LIBTCCAPI int tcc_set_output_type(TCCState *s, int output_type)
1053 s->output_type = output_type;
1055 /* always elf for objects */
1056 if (output_type == TCC_OUTPUT_OBJ)
1057 s->output_format = TCC_OUTPUT_FORMAT_ELF;
1059 if (s->char_is_unsigned)
1060 tcc_define_symbol(s, "__CHAR_UNSIGNED__", NULL);
1062 if (s->cversion == 201112) {
1063 tcc_undefine_symbol(s, "__STDC_VERSION__");
1064 tcc_define_symbol(s, "__STDC_VERSION__", "201112L");
1065 tcc_define_symbol(s, "__STDC_NO_ATOMICS__", NULL);
1066 tcc_define_symbol(s, "__STDC_NO_COMPLEX__", NULL);
1067 tcc_define_symbol(s, "__STDC_NO_THREADS__", NULL);
1068 #ifndef TCC_TARGET_PE
1069 /* on Linux, this conflicts with a define introduced by
1070 /usr/include/stdc-predef.h included by glibc libs
1071 tcc_define_symbol(s, "__STDC_ISO_10646__", "201605L"); */
1072 tcc_define_symbol(s, "__STDC_UTF_16__", NULL);
1073 tcc_define_symbol(s, "__STDC_UTF_32__", NULL);
1074 #endif
1077 if (s->optimize > 0)
1078 tcc_define_symbol(s, "__OPTIMIZE__", NULL);
1080 if (s->option_pthread)
1081 tcc_define_symbol(s, "_REENTRANT", NULL);
1083 if (s->leading_underscore)
1084 tcc_define_symbol(s, "__leading_underscore", NULL);
1086 if (!s->nostdinc) {
1087 /* default include paths */
1088 /* -isystem paths have already been handled */
1089 tcc_add_sysinclude_path(s, CONFIG_TCC_SYSINCLUDEPATHS);
1092 #ifdef CONFIG_TCC_BCHECK
1093 if (s->do_bounds_check) {
1094 /* if bound checking, then add corresponding sections */
1095 tccelf_bounds_new(s);
1096 /* define symbol */
1097 tcc_define_symbol(s, "__BOUNDS_CHECKING_ON", NULL);
1099 #endif
1100 if (s->do_debug) {
1101 /* add debug sections */
1102 tccelf_stab_new(s);
1105 tcc_add_library_path(s, CONFIG_TCC_LIBPATHS);
1107 #ifdef TCC_TARGET_PE
1108 # ifdef _WIN32
1109 if (!s->nostdlib && output_type != TCC_OUTPUT_OBJ)
1110 tcc_add_systemdir(s);
1111 # endif
1112 #else
1113 /* paths for crt objects */
1114 tcc_split_path(s, &s->crt_paths, &s->nb_crt_paths, CONFIG_TCC_CRTPREFIX);
1115 /* add libc crt1/crti objects */
1116 if ((output_type == TCC_OUTPUT_EXE || output_type == TCC_OUTPUT_DLL) &&
1117 !s->nostdlib) {
1118 #if TARGETOS_OpenBSD || TARGETOS_FreeBSD || TARGETOS_NetBSD
1119 #if TARGETOS_OpenBSD
1120 if (output_type != TCC_OUTPUT_DLL)
1121 tcc_add_crt(s, "crt0.o");
1122 #elif TARGETOS_FreeBSD
1123 if (output_type != TCC_OUTPUT_DLL)
1124 tcc_add_crt(s, "crt1.o");
1125 tcc_add_crt(s, "crti.o");
1126 #elif TARGETOS_NetBSD
1127 if (output_type != TCC_OUTPUT_DLL)
1128 tcc_add_crt(s, "crt0.o");
1129 tcc_add_crt(s, "crti.o");
1130 #endif
1131 if (s->static_link)
1132 tcc_add_crt(s, "crtbeginT.o");
1133 else if (output_type == TCC_OUTPUT_DLL)
1134 tcc_add_crt(s, "crtbeginS.o");
1135 else
1136 tcc_add_crt(s, "crtbegin.o");
1137 #elif !TCC_TARGET_MACHO
1138 /* Mach-O with LC_MAIN doesn't need any crt startup code. */
1139 if (output_type != TCC_OUTPUT_DLL)
1140 tcc_add_crt(s, "crt1.o");
1141 tcc_add_crt(s, "crti.o");
1142 #endif
1144 #endif
1145 return 0;
1148 LIBTCCAPI int tcc_add_include_path(TCCState *s, const char *pathname)
1150 tcc_split_path(s, &s->include_paths, &s->nb_include_paths, pathname);
1151 return 0;
1154 LIBTCCAPI int tcc_add_sysinclude_path(TCCState *s, const char *pathname)
1156 tcc_split_path(s, &s->sysinclude_paths, &s->nb_sysinclude_paths, pathname);
1157 return 0;
1160 #if !defined TCC_TARGET_MACHO || defined TCC_IS_NATIVE
1161 ST_FUNC DLLReference *tcc_add_dllref(TCCState *s1, const char *dllname)
1163 DLLReference *ref = tcc_mallocz(sizeof(DLLReference) + strlen(dllname));
1164 strcpy(ref->name, dllname);
1165 dynarray_add(&s1->loaded_dlls, &s1->nb_loaded_dlls, ref);
1166 return ref;
1168 #endif
1170 ST_FUNC int tcc_add_file_internal(TCCState *s1, const char *filename, int flags)
1172 int fd, ret = -1;
1174 /* open the file */
1175 fd = _tcc_open(s1, filename);
1176 if (fd < 0) {
1177 if (flags & AFF_PRINT_ERROR)
1178 tcc_error_noabort("file '%s' not found", filename);
1179 return ret;
1182 s1->current_filename = filename;
1183 if (flags & AFF_TYPE_BIN) {
1184 ElfW(Ehdr) ehdr;
1185 int obj_type;
1187 obj_type = tcc_object_type(fd, &ehdr);
1188 lseek(fd, 0, SEEK_SET);
1190 #ifdef TCC_TARGET_MACHO
1191 if (0 == obj_type && 0 == strcmp(tcc_fileextension(filename), ".dylib"))
1192 obj_type = AFF_BINTYPE_DYN;
1193 #endif
1195 switch (obj_type) {
1197 case AFF_BINTYPE_REL:
1198 ret = tcc_load_object_file(s1, fd, 0);
1199 break;
1201 case AFF_BINTYPE_AR:
1202 ret = tcc_load_archive(s1, fd, !(flags & AFF_WHOLE_ARCHIVE));
1203 break;
1205 #ifdef TCC_TARGET_PE
1206 default:
1207 ret = pe_load_file(s1, fd, filename);
1208 #else
1209 case AFF_BINTYPE_DYN:
1210 if (s1->output_type == TCC_OUTPUT_MEMORY) {
1211 #ifdef TCC_IS_NATIVE
1212 void *dl = dlopen(filename, RTLD_GLOBAL | RTLD_LAZY);
1213 if (dl) {
1214 tcc_add_dllref(s1, filename)->handle = dl;
1215 ret = 0;
1217 #endif
1218 break;
1220 #ifdef TCC_TARGET_MACHO
1221 ret = macho_load_dll(s1, fd, filename,
1222 (flags & AFF_REFERENCED_DLL) != 0);
1223 #else
1224 ret = tcc_load_dll(s1, fd, filename,
1225 (flags & AFF_REFERENCED_DLL) != 0);
1226 #endif
1227 break;
1229 #ifdef TCC_TARGET_COFF
1230 case AFF_BINTYPE_C67:
1231 ret = tcc_load_coff(s1, fd);
1232 break;
1233 #endif
1234 default:
1235 #ifndef TCC_TARGET_MACHO
1236 /* as GNU ld, consider it is an ld script if not recognized */
1237 ret = tcc_load_ldscript(s1, fd);
1238 #endif
1240 #endif /* !TCC_TARGET_PE */
1241 if (ret < 0)
1242 tcc_error_noabort("%s: unrecognized file type", filename);
1243 break;
1245 close(fd);
1246 } else {
1247 /* update target deps */
1248 dynarray_add(&s1->target_deps, &s1->nb_target_deps, tcc_strdup(filename));
1249 ret = tcc_compile(s1, flags, filename, fd);
1251 s1->current_filename = NULL;
1252 return ret;
1255 LIBTCCAPI int tcc_add_file(TCCState *s, const char *filename)
1257 int filetype = s->filetype;
1258 if (0 == (filetype & AFF_TYPE_MASK)) {
1259 /* use a file extension to detect a filetype */
1260 const char *ext = tcc_fileextension(filename);
1261 if (ext[0]) {
1262 ext++;
1263 if (!strcmp(ext, "S"))
1264 filetype = AFF_TYPE_ASMPP;
1265 else if (!strcmp(ext, "s"))
1266 filetype = AFF_TYPE_ASM;
1267 else if (!PATHCMP(ext, "c") || !PATHCMP(ext, "i"))
1268 filetype = AFF_TYPE_C;
1269 else
1270 filetype |= AFF_TYPE_BIN;
1271 } else {
1272 filetype = AFF_TYPE_C;
1275 return tcc_add_file_internal(s, filename, filetype | AFF_PRINT_ERROR);
1278 LIBTCCAPI int tcc_add_library_path(TCCState *s, const char *pathname)
1280 tcc_split_path(s, &s->library_paths, &s->nb_library_paths, pathname);
1281 return 0;
1284 static int tcc_add_library_internal(TCCState *s, const char *fmt,
1285 const char *filename, int flags, char **paths, int nb_paths)
1287 char buf[1024];
1288 int i;
1290 for(i = 0; i < nb_paths; i++) {
1291 snprintf(buf, sizeof(buf), fmt, paths[i], filename);
1292 if (tcc_add_file_internal(s, buf, flags | AFF_TYPE_BIN) == 0)
1293 return 0;
1295 return -1;
1298 #ifndef TCC_TARGET_MACHO
1299 /* find and load a dll. Return non zero if not found */
1300 /* XXX: add '-rpath' option support ? */
1301 ST_FUNC int tcc_add_dll(TCCState *s, const char *filename, int flags)
1303 return tcc_add_library_internal(s, "%s/%s", filename, flags,
1304 s->library_paths, s->nb_library_paths);
1306 #endif
1308 #if !defined TCC_TARGET_PE && !defined TCC_TARGET_MACHO
1309 ST_FUNC int tcc_add_crt(TCCState *s1, const char *filename)
1311 if (-1 == tcc_add_library_internal(s1, "%s/%s",
1312 filename, 0, s1->crt_paths, s1->nb_crt_paths))
1313 tcc_error_noabort("file '%s' not found", filename);
1314 return 0;
1316 #endif
1318 /* the library name is the same as the argument of the '-l' option */
1319 LIBTCCAPI int tcc_add_library(TCCState *s, const char *libraryname)
1321 #if defined TCC_TARGET_PE
1322 const char *libs[] = { "%s/%s.def", "%s/lib%s.def", "%s/%s.dll", "%s/lib%s.dll", "%s/lib%s.a", NULL };
1323 const char **pp = s->static_link ? libs + 4 : libs;
1324 #elif defined TCC_TARGET_MACHO
1325 const char *libs[] = { "%s/lib%s.dylib", "%s/lib%s.a", NULL };
1326 const char **pp = s->static_link ? libs + 1 : libs;
1327 #else
1328 const char *libs[] = { "%s/lib%s.so", "%s/lib%s.a", NULL };
1329 const char **pp = s->static_link ? libs + 1 : libs;
1330 #endif
1331 int flags = s->filetype & AFF_WHOLE_ARCHIVE;
1332 while (*pp) {
1333 if (0 == tcc_add_library_internal(s, *pp,
1334 libraryname, flags, s->library_paths, s->nb_library_paths))
1335 return 0;
1336 ++pp;
1338 return -1;
1341 PUB_FUNC int tcc_add_library_err(TCCState *s1, const char *libname)
1343 int ret = tcc_add_library(s1, libname);
1344 if (ret < 0)
1345 tcc_error_noabort("library '%s' not found", libname);
1346 return ret;
1349 /* handle #pragma comment(lib,) */
1350 ST_FUNC void tcc_add_pragma_libs(TCCState *s1)
1352 int i;
1353 for (i = 0; i < s1->nb_pragma_libs; i++)
1354 tcc_add_library_err(s1, s1->pragma_libs[i]);
1357 LIBTCCAPI int tcc_add_symbol(TCCState *s1, const char *name, const void *val)
1359 #ifdef TCC_TARGET_PE
1360 /* On x86_64 'val' might not be reachable with a 32bit offset.
1361 So it is handled here as if it were in a DLL. */
1362 pe_putimport(s1, 0, name, (uintptr_t)val);
1363 #else
1364 char buf[256];
1365 if (s1->leading_underscore) {
1366 buf[0] = '_';
1367 pstrcpy(buf + 1, sizeof(buf) - 1, name);
1368 name = buf;
1370 set_global_sym(s1, name, NULL, (addr_t)(uintptr_t)val); /* NULL: SHN_ABS */
1371 #endif
1372 return 0;
1375 LIBTCCAPI void tcc_set_lib_path(TCCState *s, const char *path)
1377 tcc_free(s->tcc_lib_path);
1378 s->tcc_lib_path = tcc_strdup(path);
1381 #define WD_ALL 0x0001 /* warning is activated when using -Wall */
1382 #define FD_INVERT 0x0002 /* invert value before storing */
1384 typedef struct FlagDef {
1385 uint16_t offset;
1386 uint16_t flags;
1387 const char *name;
1388 } FlagDef;
1390 static int no_flag(const char **pp)
1392 const char *p = *pp;
1393 if (*p != 'n' || *++p != 'o' || *++p != '-')
1394 return 0;
1395 *pp = p + 1;
1396 return 1;
1399 ST_FUNC int set_flag(TCCState *s, const FlagDef *flags, const char *name)
1401 int value, ret;
1402 const FlagDef *p;
1403 const char *r;
1405 value = 1;
1406 r = name;
1407 if (no_flag(&r))
1408 value = 0;
1410 for (ret = -1, p = flags; p->name; ++p) {
1411 if (ret) {
1412 if (strcmp(r, p->name))
1413 continue;
1414 } else {
1415 if (0 == (p->flags & WD_ALL))
1416 continue;
1418 if (p->offset) {
1419 *((unsigned char *)s + p->offset) =
1420 p->flags & FD_INVERT ? !value : value;
1421 if (ret)
1422 return 0;
1423 } else {
1424 ret = 0;
1427 return ret;
1430 static int strstart(const char *val, const char **str)
1432 const char *p, *q;
1433 p = *str;
1434 q = val;
1435 while (*q) {
1436 if (*p != *q)
1437 return 0;
1438 p++;
1439 q++;
1441 *str = p;
1442 return 1;
1445 /* Like strstart, but automatically takes into account that ld options can
1447 * - start with double or single dash (e.g. '--soname' or '-soname')
1448 * - arguments can be given as separate or after '=' (e.g. '-Wl,-soname,x.so'
1449 * or '-Wl,-soname=x.so')
1451 * you provide `val` always in 'option[=]' form (no leading -)
1453 static int link_option(const char *str, const char *val, const char **ptr)
1455 const char *p, *q;
1456 int ret;
1458 /* there should be 1 or 2 dashes */
1459 if (*str++ != '-')
1460 return 0;
1461 if (*str == '-')
1462 str++;
1464 /* then str & val should match (potentially up to '=') */
1465 p = str;
1466 q = val;
1468 ret = 1;
1469 if (q[0] == '?') {
1470 ++q;
1471 if (no_flag(&p))
1472 ret = -1;
1475 while (*q != '\0' && *q != '=') {
1476 if (*p != *q)
1477 return 0;
1478 p++;
1479 q++;
1482 /* '=' near eos means ',' or '=' is ok */
1483 if (*q == '=') {
1484 if (*p == 0)
1485 *ptr = p;
1486 if (*p != ',' && *p != '=')
1487 return 0;
1488 p++;
1489 } else if (*p) {
1490 return 0;
1492 *ptr = p;
1493 return ret;
1496 static const char *skip_linker_arg(const char **str)
1498 const char *s1 = *str;
1499 const char *s2 = strchr(s1, ',');
1500 *str = s2 ? s2++ : (s2 = s1 + strlen(s1));
1501 return s2;
1504 static void copy_linker_arg(char **pp, const char *s, int sep)
1506 const char *q = s;
1507 char *p = *pp;
1508 int l = 0;
1509 if (p && sep)
1510 p[l = strlen(p)] = sep, ++l;
1511 skip_linker_arg(&q);
1512 pstrncpy(l + (*pp = tcc_realloc(p, q - s + l + 1)), s, q - s);
1515 /* set linker options */
1516 static int tcc_set_linker(TCCState *s, const char *option)
1518 TCCState *s1 = s;
1519 while (*option) {
1521 const char *p = NULL;
1522 char *end = NULL;
1523 int ignoring = 0;
1524 int ret;
1526 if (link_option(option, "Bsymbolic", &p)) {
1527 s->symbolic = 1;
1528 } else if (link_option(option, "nostdlib", &p)) {
1529 s->nostdlib = 1;
1530 } else if (link_option(option, "fini=", &p)) {
1531 copy_linker_arg(&s->fini_symbol, p, 0);
1532 ignoring = 1;
1533 } else if (link_option(option, "image-base=", &p)
1534 || link_option(option, "Ttext=", &p)) {
1535 s->text_addr = strtoull(p, &end, 16);
1536 s->has_text_addr = 1;
1537 } else if (link_option(option, "init=", &p)) {
1538 copy_linker_arg(&s->init_symbol, p, 0);
1539 ignoring = 1;
1540 } else if (link_option(option, "oformat=", &p)) {
1541 #if defined(TCC_TARGET_PE)
1542 if (strstart("pe-", &p)) {
1543 #elif PTR_SIZE == 8
1544 if (strstart("elf64-", &p)) {
1545 #else
1546 if (strstart("elf32-", &p)) {
1547 #endif
1548 s->output_format = TCC_OUTPUT_FORMAT_ELF;
1549 } else if (!strcmp(p, "binary")) {
1550 s->output_format = TCC_OUTPUT_FORMAT_BINARY;
1551 #ifdef TCC_TARGET_COFF
1552 } else if (!strcmp(p, "coff")) {
1553 s->output_format = TCC_OUTPUT_FORMAT_COFF;
1554 #endif
1555 } else
1556 goto err;
1558 } else if (link_option(option, "as-needed", &p)) {
1559 ignoring = 1;
1560 } else if (link_option(option, "O", &p)) {
1561 ignoring = 1;
1562 } else if (link_option(option, "export-all-symbols", &p)) {
1563 s->rdynamic = 1;
1564 } else if (link_option(option, "export-dynamic", &p)) {
1565 s->rdynamic = 1;
1566 } else if (link_option(option, "rpath=", &p)) {
1567 copy_linker_arg(&s->rpath, p, ':');
1568 } else if (link_option(option, "enable-new-dtags", &p)) {
1569 s->enable_new_dtags = 1;
1570 } else if (link_option(option, "section-alignment=", &p)) {
1571 s->section_align = strtoul(p, &end, 16);
1572 } else if (link_option(option, "soname=", &p)) {
1573 copy_linker_arg(&s->soname, p, 0);
1574 #ifdef TCC_TARGET_PE
1575 } else if (link_option(option, "large-address-aware", &p)) {
1576 s->pe_characteristics |= 0x20;
1577 } else if (link_option(option, "file-alignment=", &p)) {
1578 s->pe_file_align = strtoul(p, &end, 16);
1579 } else if (link_option(option, "stack=", &p)) {
1580 s->pe_stack_size = strtoul(p, &end, 10);
1581 } else if (link_option(option, "subsystem=", &p)) {
1582 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
1583 if (!strcmp(p, "native")) {
1584 s->pe_subsystem = 1;
1585 } else if (!strcmp(p, "console")) {
1586 s->pe_subsystem = 3;
1587 } else if (!strcmp(p, "gui") || !strcmp(p, "windows")) {
1588 s->pe_subsystem = 2;
1589 } else if (!strcmp(p, "posix")) {
1590 s->pe_subsystem = 7;
1591 } else if (!strcmp(p, "efiapp")) {
1592 s->pe_subsystem = 10;
1593 } else if (!strcmp(p, "efiboot")) {
1594 s->pe_subsystem = 11;
1595 } else if (!strcmp(p, "efiruntime")) {
1596 s->pe_subsystem = 12;
1597 } else if (!strcmp(p, "efirom")) {
1598 s->pe_subsystem = 13;
1599 #elif defined(TCC_TARGET_ARM)
1600 if (!strcmp(p, "wince")) {
1601 s->pe_subsystem = 9;
1602 #endif
1603 } else
1604 goto err;
1605 #endif
1606 } else if (ret = link_option(option, "?whole-archive", &p), ret) {
1607 if (ret > 0)
1608 s->filetype |= AFF_WHOLE_ARCHIVE;
1609 else
1610 s->filetype &= ~AFF_WHOLE_ARCHIVE;
1611 } else if (p) {
1612 return 0;
1613 } else {
1614 err:
1615 tcc_error("unsupported linker option '%s'", option);
1618 if (ignoring && s->warn_unsupported)
1619 tcc_warning("unsupported linker option '%s'", option);
1621 option = skip_linker_arg(&p);
1623 return 1;
1626 typedef struct TCCOption {
1627 const char *name;
1628 uint16_t index;
1629 uint16_t flags;
1630 } TCCOption;
1632 enum {
1633 TCC_OPTION_HELP,
1634 TCC_OPTION_HELP2,
1635 TCC_OPTION_v,
1636 TCC_OPTION_I,
1637 TCC_OPTION_D,
1638 TCC_OPTION_U,
1639 TCC_OPTION_P,
1640 TCC_OPTION_L,
1641 TCC_OPTION_B,
1642 TCC_OPTION_l,
1643 TCC_OPTION_bench,
1644 TCC_OPTION_bt,
1645 TCC_OPTION_b,
1646 TCC_OPTION_ba,
1647 TCC_OPTION_g,
1648 TCC_OPTION_c,
1649 TCC_OPTION_dumpversion,
1650 TCC_OPTION_d,
1651 TCC_OPTION_static,
1652 TCC_OPTION_std,
1653 TCC_OPTION_shared,
1654 TCC_OPTION_soname,
1655 TCC_OPTION_o,
1656 TCC_OPTION_r,
1657 TCC_OPTION_s,
1658 TCC_OPTION_traditional,
1659 TCC_OPTION_Wl,
1660 TCC_OPTION_Wp,
1661 TCC_OPTION_W,
1662 TCC_OPTION_O,
1663 TCC_OPTION_mfloat_abi,
1664 TCC_OPTION_m,
1665 TCC_OPTION_f,
1666 TCC_OPTION_isystem,
1667 TCC_OPTION_iwithprefix,
1668 TCC_OPTION_include,
1669 TCC_OPTION_nostdinc,
1670 TCC_OPTION_nostdlib,
1671 TCC_OPTION_print_search_dirs,
1672 TCC_OPTION_rdynamic,
1673 TCC_OPTION_param,
1674 TCC_OPTION_pedantic,
1675 TCC_OPTION_pthread,
1676 TCC_OPTION_run,
1677 TCC_OPTION_w,
1678 TCC_OPTION_pipe,
1679 TCC_OPTION_E,
1680 TCC_OPTION_MD,
1681 TCC_OPTION_MF,
1682 TCC_OPTION_x,
1683 TCC_OPTION_ar,
1684 TCC_OPTION_impdef,
1685 TCC_OPTION_C
1688 #define TCC_OPTION_HAS_ARG 0x0001
1689 #define TCC_OPTION_NOSEP 0x0002 /* cannot have space before option and arg */
1691 static const TCCOption tcc_options[] = {
1692 { "h", TCC_OPTION_HELP, 0 },
1693 { "-help", TCC_OPTION_HELP, 0 },
1694 { "?", TCC_OPTION_HELP, 0 },
1695 { "hh", TCC_OPTION_HELP2, 0 },
1696 { "v", TCC_OPTION_v, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1697 { "-version", TCC_OPTION_v, 0 }, /* handle as verbose, also prints version*/
1698 { "I", TCC_OPTION_I, TCC_OPTION_HAS_ARG },
1699 { "D", TCC_OPTION_D, TCC_OPTION_HAS_ARG },
1700 { "U", TCC_OPTION_U, TCC_OPTION_HAS_ARG },
1701 { "P", TCC_OPTION_P, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1702 { "L", TCC_OPTION_L, TCC_OPTION_HAS_ARG },
1703 { "B", TCC_OPTION_B, TCC_OPTION_HAS_ARG },
1704 { "l", TCC_OPTION_l, TCC_OPTION_HAS_ARG },
1705 { "bench", TCC_OPTION_bench, 0 },
1706 #ifdef CONFIG_TCC_BACKTRACE
1707 { "bt", TCC_OPTION_bt, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1708 #endif
1709 #ifdef CONFIG_TCC_BCHECK
1710 { "b", TCC_OPTION_b, 0 },
1711 #endif
1712 { "g", TCC_OPTION_g, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1713 { "c", TCC_OPTION_c, 0 },
1714 { "dumpversion", TCC_OPTION_dumpversion, 0},
1715 { "d", TCC_OPTION_d, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1716 { "static", TCC_OPTION_static, 0 },
1717 { "std", TCC_OPTION_std, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1718 { "shared", TCC_OPTION_shared, 0 },
1719 { "soname", TCC_OPTION_soname, TCC_OPTION_HAS_ARG },
1720 { "o", TCC_OPTION_o, TCC_OPTION_HAS_ARG },
1721 { "-param", TCC_OPTION_param, TCC_OPTION_HAS_ARG },
1722 { "pedantic", TCC_OPTION_pedantic, 0},
1723 { "pthread", TCC_OPTION_pthread, 0},
1724 { "run", TCC_OPTION_run, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1725 { "rdynamic", TCC_OPTION_rdynamic, 0 },
1726 { "r", TCC_OPTION_r, 0 },
1727 { "s", TCC_OPTION_s, 0 },
1728 { "traditional", TCC_OPTION_traditional, 0 },
1729 { "Wl,", TCC_OPTION_Wl, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1730 { "Wp,", TCC_OPTION_Wp, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1731 { "W", TCC_OPTION_W, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1732 { "O", TCC_OPTION_O, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1733 #ifdef TCC_TARGET_ARM
1734 { "mfloat-abi", TCC_OPTION_mfloat_abi, TCC_OPTION_HAS_ARG },
1735 #endif
1736 { "m", TCC_OPTION_m, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1737 { "f", TCC_OPTION_f, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1738 { "isystem", TCC_OPTION_isystem, TCC_OPTION_HAS_ARG },
1739 { "include", TCC_OPTION_include, TCC_OPTION_HAS_ARG },
1740 { "nostdinc", TCC_OPTION_nostdinc, 0 },
1741 { "nostdlib", TCC_OPTION_nostdlib, 0 },
1742 { "print-search-dirs", TCC_OPTION_print_search_dirs, 0 },
1743 { "w", TCC_OPTION_w, 0 },
1744 { "pipe", TCC_OPTION_pipe, 0},
1745 { "E", TCC_OPTION_E, 0},
1746 { "MD", TCC_OPTION_MD, 0},
1747 { "MF", TCC_OPTION_MF, TCC_OPTION_HAS_ARG },
1748 { "x", TCC_OPTION_x, TCC_OPTION_HAS_ARG },
1749 { "ar", TCC_OPTION_ar, 0},
1750 #ifdef TCC_TARGET_PE
1751 { "impdef", TCC_OPTION_impdef, 0},
1752 #endif
1753 { "C", TCC_OPTION_C, 0},
1754 { NULL, 0, 0 },
1757 static const FlagDef options_W[] = {
1758 { 0, 0, "all" },
1759 { offsetof(TCCState, warn_unsupported), 0, "unsupported" },
1760 { offsetof(TCCState, warn_write_strings), 0, "write-strings" },
1761 { offsetof(TCCState, warn_error), 0, "error" },
1762 { offsetof(TCCState, warn_gcc_compat), 0, "gcc-compat" },
1763 { offsetof(TCCState, warn_implicit_function_declaration), WD_ALL,
1764 "implicit-function-declaration" },
1765 { 0, 0, NULL }
1768 static const FlagDef options_f[] = {
1769 { offsetof(TCCState, char_is_unsigned), 0, "unsigned-char" },
1770 { offsetof(TCCState, char_is_unsigned), FD_INVERT, "signed-char" },
1771 { offsetof(TCCState, nocommon), FD_INVERT, "common" },
1772 { offsetof(TCCState, leading_underscore), 0, "leading-underscore" },
1773 { offsetof(TCCState, ms_extensions), 0, "ms-extensions" },
1774 { offsetof(TCCState, dollars_in_identifiers), 0, "dollars-in-identifiers" },
1775 { 0, 0, NULL }
1778 static const FlagDef options_m[] = {
1779 { offsetof(TCCState, ms_bitfields), 0, "ms-bitfields" },
1780 #ifdef TCC_TARGET_X86_64
1781 { offsetof(TCCState, nosse), FD_INVERT, "sse" },
1782 #endif
1783 { 0, 0, NULL }
1786 static void args_parser_add_file(TCCState *s, const char* filename, int filetype)
1788 struct filespec *f = tcc_malloc(sizeof *f + strlen(filename));
1789 f->type = filetype;
1790 strcpy(f->name, filename);
1791 dynarray_add(&s->files, &s->nb_files, f);
1794 static int args_parser_make_argv(const char *r, int *argc, char ***argv)
1796 int ret = 0, q, c;
1797 CString str;
1798 for(;;) {
1799 while (c = (unsigned char)*r, c && c <= ' ')
1800 ++r;
1801 if (c == 0)
1802 break;
1803 q = 0;
1804 cstr_new(&str);
1805 while (c = (unsigned char)*r, c) {
1806 ++r;
1807 if (c == '\\' && (*r == '"' || *r == '\\')) {
1808 c = *r++;
1809 } else if (c == '"') {
1810 q = !q;
1811 continue;
1812 } else if (q == 0 && c <= ' ') {
1813 break;
1815 cstr_ccat(&str, c);
1817 cstr_ccat(&str, 0);
1818 //printf("<%s>\n", str.data), fflush(stdout);
1819 dynarray_add(argv, argc, tcc_strdup(str.data));
1820 cstr_free(&str);
1821 ++ret;
1823 return ret;
1826 /* read list file */
1827 static void args_parser_listfile(TCCState *s,
1828 const char *filename, int optind, int *pargc, char ***pargv)
1830 TCCState *s1 = s;
1831 int fd, i;
1832 size_t len;
1833 char *p;
1834 int argc = 0;
1835 char **argv = NULL;
1837 fd = open(filename, O_RDONLY | O_BINARY);
1838 if (fd < 0)
1839 tcc_error("listfile '%s' not found", filename);
1841 len = lseek(fd, 0, SEEK_END);
1842 p = tcc_malloc(len + 1), p[len] = 0;
1843 lseek(fd, 0, SEEK_SET), read(fd, p, len), close(fd);
1845 for (i = 0; i < *pargc; ++i)
1846 if (i == optind)
1847 args_parser_make_argv(p, &argc, &argv);
1848 else
1849 dynarray_add(&argv, &argc, tcc_strdup((*pargv)[i]));
1851 tcc_free(p);
1852 dynarray_reset(&s->argv, &s->argc);
1853 *pargc = s->argc = argc, *pargv = s->argv = argv;
1856 PUB_FUNC int tcc_parse_args(TCCState *s, int *pargc, char ***pargv, int optind)
1858 TCCState *s1 = s;
1859 const TCCOption *popt;
1860 const char *optarg, *r;
1861 const char *run = NULL;
1862 int x;
1863 CString linker_arg; /* collect -Wl options */
1864 int tool = 0, arg_start = 0, noaction = optind;
1865 char **argv = *pargv;
1866 int argc = *pargc;
1868 cstr_new(&linker_arg);
1870 while (optind < argc) {
1871 r = argv[optind];
1872 if (r[0] == '@' && r[1] != '\0') {
1873 args_parser_listfile(s, r + 1, optind, &argc, &argv);
1874 continue;
1876 optind++;
1877 if (tool) {
1878 if (r[0] == '-' && r[1] == 'v' && r[2] == 0)
1879 ++s->verbose;
1880 continue;
1882 reparse:
1883 if (r[0] != '-' || r[1] == '\0') {
1884 if (r[0] != '@') /* allow "tcc file(s) -run @ args ..." */
1885 args_parser_add_file(s, r, s->filetype);
1886 if (run) {
1887 tcc_set_options(s, run);
1888 arg_start = optind - 1;
1889 break;
1891 continue;
1894 /* find option in table */
1895 for(popt = tcc_options; ; ++popt) {
1896 const char *p1 = popt->name;
1897 const char *r1 = r + 1;
1898 if (p1 == NULL)
1899 tcc_error("invalid option -- '%s'", r);
1900 if (!strstart(p1, &r1))
1901 continue;
1902 optarg = r1;
1903 if (popt->flags & TCC_OPTION_HAS_ARG) {
1904 if (*r1 == '\0' && !(popt->flags & TCC_OPTION_NOSEP)) {
1905 if (optind >= argc)
1906 arg_err:
1907 tcc_error("argument to '%s' is missing", r);
1908 optarg = argv[optind++];
1910 } else if (*r1 != '\0')
1911 continue;
1912 break;
1915 switch(popt->index) {
1916 case TCC_OPTION_HELP:
1917 x = OPT_HELP;
1918 goto extra_action;
1919 case TCC_OPTION_HELP2:
1920 x = OPT_HELP2;
1921 goto extra_action;
1922 case TCC_OPTION_I:
1923 tcc_add_include_path(s, optarg);
1924 break;
1925 case TCC_OPTION_D:
1926 tcc_define_symbol(s, optarg, NULL);
1927 break;
1928 case TCC_OPTION_U:
1929 tcc_undefine_symbol(s, optarg);
1930 break;
1931 case TCC_OPTION_L:
1932 tcc_add_library_path(s, optarg);
1933 break;
1934 case TCC_OPTION_B:
1935 /* set tcc utilities path (mainly for tcc development) */
1936 tcc_set_lib_path(s, optarg);
1937 break;
1938 case TCC_OPTION_l:
1939 args_parser_add_file(s, optarg, AFF_TYPE_LIB | (s->filetype & ~AFF_TYPE_MASK));
1940 s->nb_libraries++;
1941 break;
1942 case TCC_OPTION_pthread:
1943 s->option_pthread = 1;
1944 break;
1945 case TCC_OPTION_bench:
1946 s->do_bench = 1;
1947 break;
1948 #ifdef CONFIG_TCC_BACKTRACE
1949 case TCC_OPTION_bt:
1950 s->rt_num_callers = atoi(optarg);
1951 s->do_backtrace = 1;
1952 s->do_debug = 1;
1953 break;
1954 #endif
1955 #ifdef CONFIG_TCC_BCHECK
1956 case TCC_OPTION_b:
1957 s->do_bounds_check = 1;
1958 s->do_backtrace = 1;
1959 s->do_debug = 1;
1960 break;
1961 #endif
1962 case TCC_OPTION_g:
1963 s->do_debug = 1;
1964 break;
1965 case TCC_OPTION_c:
1966 x = TCC_OUTPUT_OBJ;
1967 set_output_type:
1968 if (s->output_type)
1969 tcc_warning("-%s: overriding compiler action already specified", popt->name);
1970 s->output_type = x;
1971 break;
1972 case TCC_OPTION_d:
1973 if (*optarg == 'D')
1974 s->dflag = 3;
1975 else if (*optarg == 'M')
1976 s->dflag = 7;
1977 else if (*optarg == 't')
1978 s->dflag = 16;
1979 else if (isnum(*optarg))
1980 s->g_debug |= atoi(optarg);
1981 else
1982 goto unsupported_option;
1983 break;
1984 case TCC_OPTION_static:
1985 s->static_link = 1;
1986 break;
1987 case TCC_OPTION_std:
1988 if (strcmp(optarg, "=c11") == 0)
1989 s->cversion = 201112;
1990 break;
1991 case TCC_OPTION_shared:
1992 x = TCC_OUTPUT_DLL;
1993 goto set_output_type;
1994 case TCC_OPTION_soname:
1995 s->soname = tcc_strdup(optarg);
1996 break;
1997 case TCC_OPTION_o:
1998 if (s->outfile) {
1999 tcc_warning("multiple -o option");
2000 tcc_free(s->outfile);
2002 s->outfile = tcc_strdup(optarg);
2003 break;
2004 case TCC_OPTION_r:
2005 /* generate a .o merging several output files */
2006 s->option_r = 1;
2007 x = TCC_OUTPUT_OBJ;
2008 goto set_output_type;
2009 case TCC_OPTION_isystem:
2010 tcc_add_sysinclude_path(s, optarg);
2011 break;
2012 case TCC_OPTION_include:
2013 cstr_printf(&s->cmdline_incl, "#include \"%s\"\n", optarg);
2014 break;
2015 case TCC_OPTION_nostdinc:
2016 s->nostdinc = 1;
2017 break;
2018 case TCC_OPTION_nostdlib:
2019 s->nostdlib = 1;
2020 break;
2021 case TCC_OPTION_run:
2022 #ifndef TCC_IS_NATIVE
2023 tcc_error("-run is not available in a cross compiler");
2024 #endif
2025 run = optarg;
2026 x = TCC_OUTPUT_MEMORY;
2027 goto set_output_type;
2028 case TCC_OPTION_v:
2029 do ++s->verbose; while (*optarg++ == 'v');
2030 ++noaction;
2031 break;
2032 case TCC_OPTION_f:
2033 if (set_flag(s, options_f, optarg) < 0)
2034 goto unsupported_option;
2035 break;
2036 #ifdef TCC_TARGET_ARM
2037 case TCC_OPTION_mfloat_abi:
2038 /* tcc doesn't support soft float yet */
2039 if (!strcmp(optarg, "softfp")) {
2040 s->float_abi = ARM_SOFTFP_FLOAT;
2041 tcc_undefine_symbol(s, "__ARM_PCS_VFP");
2042 } else if (!strcmp(optarg, "hard"))
2043 s->float_abi = ARM_HARD_FLOAT;
2044 else
2045 tcc_error("unsupported float abi '%s'", optarg);
2046 break;
2047 #endif
2048 case TCC_OPTION_m:
2049 if (set_flag(s, options_m, optarg) < 0) {
2050 if (x = atoi(optarg), x != 32 && x != 64)
2051 goto unsupported_option;
2052 if (PTR_SIZE != x/8)
2053 return x;
2054 ++noaction;
2056 break;
2057 case TCC_OPTION_W:
2058 s->warn_none = 0;
2059 if (optarg[0] && set_flag(s, options_W, optarg) < 0)
2060 goto unsupported_option;
2061 break;
2062 case TCC_OPTION_w:
2063 s->warn_none = 1;
2064 break;
2065 case TCC_OPTION_rdynamic:
2066 s->rdynamic = 1;
2067 break;
2068 case TCC_OPTION_Wl:
2069 if (linker_arg.size)
2070 --linker_arg.size, cstr_ccat(&linker_arg, ',');
2071 cstr_cat(&linker_arg, optarg, 0);
2072 if (tcc_set_linker(s, linker_arg.data))
2073 cstr_free(&linker_arg);
2074 break;
2075 case TCC_OPTION_Wp:
2076 r = optarg;
2077 goto reparse;
2078 case TCC_OPTION_E:
2079 x = TCC_OUTPUT_PREPROCESS;
2080 goto set_output_type;
2081 case TCC_OPTION_P:
2082 s->Pflag = atoi(optarg) + 1;
2083 break;
2084 case TCC_OPTION_MD:
2085 s->gen_deps = 1;
2086 break;
2087 case TCC_OPTION_MF:
2088 s->deps_outfile = tcc_strdup(optarg);
2089 break;
2090 case TCC_OPTION_dumpversion:
2091 printf ("%s\n", TCC_VERSION);
2092 exit(0);
2093 break;
2094 case TCC_OPTION_x:
2095 x = 0;
2096 if (*optarg == 'c')
2097 x = AFF_TYPE_C;
2098 else if (*optarg == 'a')
2099 x = AFF_TYPE_ASMPP;
2100 else if (*optarg == 'b')
2101 x = AFF_TYPE_BIN;
2102 else if (*optarg == 'n')
2103 x = AFF_TYPE_NONE;
2104 else
2105 tcc_warning("unsupported language '%s'", optarg);
2106 s->filetype = x | (s->filetype & ~AFF_TYPE_MASK);
2107 break;
2108 case TCC_OPTION_O:
2109 s->optimize = atoi(optarg);
2110 break;
2111 case TCC_OPTION_print_search_dirs:
2112 x = OPT_PRINT_DIRS;
2113 goto extra_action;
2114 case TCC_OPTION_impdef:
2115 x = OPT_IMPDEF;
2116 goto extra_action;
2117 case TCC_OPTION_ar:
2118 x = OPT_AR;
2119 extra_action:
2120 arg_start = optind - 1;
2121 if (arg_start != noaction)
2122 tcc_error("cannot parse %s here", r);
2123 tool = x;
2124 break;
2125 case TCC_OPTION_traditional:
2126 case TCC_OPTION_pedantic:
2127 case TCC_OPTION_pipe:
2128 case TCC_OPTION_s:
2129 case TCC_OPTION_C:
2130 /* ignored */
2131 break;
2132 default:
2133 unsupported_option:
2134 if (s->warn_unsupported)
2135 tcc_warning("unsupported option '%s'", r);
2136 break;
2139 if (linker_arg.size) {
2140 r = linker_arg.data;
2141 goto arg_err;
2143 *pargc = argc - arg_start;
2144 *pargv = argv + arg_start;
2145 if (tool)
2146 return tool;
2147 if (optind != noaction)
2148 return 0;
2149 if (s->verbose == 2)
2150 return OPT_PRINT_DIRS;
2151 if (s->verbose)
2152 return OPT_V;
2153 return OPT_HELP;
2156 LIBTCCAPI void tcc_set_options(TCCState *s, const char *r)
2158 char **argv = NULL;
2159 int argc = 0;
2160 args_parser_make_argv(r, &argc, &argv);
2161 tcc_parse_args(s, &argc, &argv, 0);
2162 dynarray_reset(&argv, &argc);
2165 PUB_FUNC void tcc_print_stats(TCCState *s1, unsigned total_time)
2167 if (total_time < 1)
2168 total_time = 1;
2169 if (total_bytes < 1)
2170 total_bytes = 1;
2171 fprintf(stderr, "* %d idents, %d lines, %d bytes\n"
2172 "* %0.3f s, %u lines/s, %0.1f MB/s\n",
2173 total_idents, total_lines, total_bytes,
2174 (double)total_time/1000,
2175 (unsigned)total_lines*1000/total_time,
2176 (double)total_bytes/1000/total_time);
2177 fprintf(stderr, "* text %d, data %d, bss %d bytes\n",
2178 s1->total_output[0], s1->total_output[1], s1->total_output[2]);
2179 #ifdef MEM_DEBUG
2180 fprintf(stderr, "* %d bytes memory used\n", mem_max_size);
2181 #endif