Makefile for Windows native tcc handles recent UNICODE support
[tinycc.git] / libtcc.c
blobf1bbc6cfd36a9f15dacebe3b8a4b77c14a073c5a
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 #include "tcc.h"
23 /********************************************************/
24 /* global variables */
26 /* use GNU C extensions */
27 ST_DATA int gnu_ext = 1;
29 /* use TinyCC extensions */
30 ST_DATA int tcc_ext = 1;
32 /* XXX: get rid of this ASAP */
33 ST_DATA struct TCCState *tcc_state;
35 static int nb_states;
37 /********************************************************/
39 #ifdef ONE_SOURCE
40 #include "tccpp.c"
41 #include "tccgen.c"
42 #include "tccelf.c"
43 #include "tccrun.c"
44 #ifdef TCC_TARGET_I386
45 #include "i386-gen.c"
46 #include "i386-link.c"
47 #endif
48 #ifdef TCC_TARGET_ARM
49 #include "arm-gen.c"
50 #include "arm-link.c"
51 #endif
52 #ifdef TCC_TARGET_ARM64
53 #include "arm64-gen.c"
54 #include "arm64-link.c"
55 #endif
56 #ifdef TCC_TARGET_C67
57 #include "c67-gen.c"
58 #include "c67-link.c"
59 #endif
60 #ifdef TCC_TARGET_X86_64
61 #include "x86_64-gen.c"
62 #include "x86_64-link.c"
63 #endif
64 #ifdef CONFIG_TCC_ASM
65 #include "tccasm.c"
66 #if defined TCC_TARGET_I386 || defined TCC_TARGET_X86_64
67 #include "i386-asm.c"
68 #endif
69 #endif
70 #ifdef TCC_TARGET_COFF
71 #include "tcccoff.c"
72 #endif
73 #ifdef TCC_TARGET_PE
74 #include "tccpe.c"
75 #endif
76 #endif /* ONE_SOURCE */
78 /********************************************************/
79 #ifndef CONFIG_TCC_ASM
80 ST_FUNC void asm_instr(void)
82 tcc_error("inline asm() not supported");
84 ST_FUNC void asm_global_instr(void)
86 tcc_error("inline asm() not supported");
88 #endif
90 /********************************************************/
91 #ifdef _WIN32
92 ST_FUNC char *normalize_slashes(char *path)
94 char *p;
95 for (p = path; *p; ++p)
96 if (*p == '\\')
97 *p = '/';
98 return path;
101 static HMODULE tcc_module;
103 /* on win32, we suppose the lib and includes are at the location of 'tcc.exe' */
104 static void tcc_set_lib_path_w32(TCCState *s)
106 char path[1024], *p;
107 GetModuleFileNameA(tcc_module, path, sizeof path);
108 p = tcc_basename(normalize_slashes(strlwr(path)));
109 if (p - 5 > path && 0 == strncmp(p - 5, "/bin/", 5))
110 p -= 5;
111 else if (p > path)
112 p--;
113 *p = 0;
114 tcc_set_lib_path(s, path);
117 #ifdef TCC_TARGET_PE
118 static void tcc_add_systemdir(TCCState *s)
120 char buf[1000];
121 GetSystemDirectory(buf, sizeof buf);
122 tcc_add_library_path(s, normalize_slashes(buf));
124 #endif
126 #ifdef LIBTCC_AS_DLL
127 BOOL WINAPI DllMain (HINSTANCE hDll, DWORD dwReason, LPVOID lpReserved)
129 if (DLL_PROCESS_ATTACH == dwReason)
130 tcc_module = hDll;
131 return TRUE;
133 #endif
134 #endif
136 /********************************************************/
137 /* copy a string and truncate it. */
138 ST_FUNC char *pstrcpy(char *buf, int buf_size, const char *s)
140 char *q, *q_end;
141 int c;
143 if (buf_size > 0) {
144 q = buf;
145 q_end = buf + buf_size - 1;
146 while (q < q_end) {
147 c = *s++;
148 if (c == '\0')
149 break;
150 *q++ = c;
152 *q = '\0';
154 return buf;
157 /* strcat and truncate. */
158 ST_FUNC char *pstrcat(char *buf, int buf_size, const char *s)
160 int len;
161 len = strlen(buf);
162 if (len < buf_size)
163 pstrcpy(buf + len, buf_size - len, s);
164 return buf;
167 ST_FUNC char *pstrncpy(char *out, const char *in, size_t num)
169 memcpy(out, in, num);
170 out[num] = '\0';
171 return out;
174 /* extract the basename of a file */
175 PUB_FUNC char *tcc_basename(const char *name)
177 char *p = strchr(name, 0);
178 while (p > name && !IS_DIRSEP(p[-1]))
179 --p;
180 return p;
183 /* extract extension part of a file
185 * (if no extension, return pointer to end-of-string)
187 PUB_FUNC char *tcc_fileextension (const char *name)
189 char *b = tcc_basename(name);
190 char *e = strrchr(b, '.');
191 return e ? e : strchr(b, 0);
194 /********************************************************/
195 /* memory management */
197 #undef free
198 #undef malloc
199 #undef realloc
201 #ifndef MEM_DEBUG
203 PUB_FUNC void tcc_free(void *ptr)
205 free(ptr);
208 PUB_FUNC void *tcc_malloc(unsigned long size)
210 void *ptr;
211 ptr = malloc(size);
212 if (!ptr && size)
213 tcc_error("memory full (malloc)");
214 return ptr;
217 PUB_FUNC void *tcc_mallocz(unsigned long size)
219 void *ptr;
220 ptr = tcc_malloc(size);
221 memset(ptr, 0, size);
222 return ptr;
225 PUB_FUNC void *tcc_realloc(void *ptr, unsigned long size)
227 void *ptr1;
228 ptr1 = realloc(ptr, size);
229 if (!ptr1 && size)
230 tcc_error("memory full (realloc)");
231 return ptr1;
234 PUB_FUNC char *tcc_strdup(const char *str)
236 char *ptr;
237 ptr = tcc_malloc(strlen(str) + 1);
238 strcpy(ptr, str);
239 return ptr;
242 PUB_FUNC void tcc_memstats(int bench)
246 #else
248 #define MEM_DEBUG_MAGIC1 0xFEEDDEB1
249 #define MEM_DEBUG_MAGIC2 0xFEEDDEB2
250 #define MEM_DEBUG_MAGIC3 0xFEEDDEB3
251 #define MEM_DEBUG_FILE_LEN 40
252 #define MEM_DEBUG_CHECK3(header) \
253 ((mem_debug_header_t*)((char*)header + header->size))->magic3
254 #define MEM_USER_PTR(header) \
255 ((char *)header + offsetof(mem_debug_header_t, magic3))
256 #define MEM_HEADER_PTR(ptr) \
257 (mem_debug_header_t *)((char*)ptr - offsetof(mem_debug_header_t, magic3))
259 struct mem_debug_header {
260 unsigned magic1;
261 unsigned size;
262 struct mem_debug_header *prev;
263 struct mem_debug_header *next;
264 int line_num;
265 char file_name[MEM_DEBUG_FILE_LEN + 1];
266 unsigned magic2;
267 __attribute__((aligned(16))) unsigned magic3;
270 typedef struct mem_debug_header mem_debug_header_t;
272 static mem_debug_header_t *mem_debug_chain;
273 static unsigned mem_cur_size;
274 static unsigned mem_max_size;
276 static mem_debug_header_t *malloc_check(void *ptr, const char *msg)
278 mem_debug_header_t * header = MEM_HEADER_PTR(ptr);
279 if (header->magic1 != MEM_DEBUG_MAGIC1 ||
280 header->magic2 != MEM_DEBUG_MAGIC2 ||
281 MEM_DEBUG_CHECK3(header) != MEM_DEBUG_MAGIC3 ||
282 header->size == (unsigned)-1) {
283 fprintf(stderr, "%s check failed\n", msg);
284 if (header->magic1 == MEM_DEBUG_MAGIC1)
285 fprintf(stderr, "%s:%u: block allocated here.\n",
286 header->file_name, header->line_num);
287 exit(1);
289 return header;
292 PUB_FUNC void *tcc_malloc_debug(unsigned long size, const char *file, int line)
294 int ofs;
295 mem_debug_header_t *header;
297 header = malloc(sizeof(mem_debug_header_t) + size);
298 if (!header)
299 tcc_error("memory full (malloc)");
301 header->magic1 = MEM_DEBUG_MAGIC1;
302 header->magic2 = MEM_DEBUG_MAGIC2;
303 header->size = size;
304 MEM_DEBUG_CHECK3(header) = MEM_DEBUG_MAGIC3;
305 header->line_num = line;
306 ofs = strlen(file) - MEM_DEBUG_FILE_LEN;
307 strncpy(header->file_name, file + (ofs > 0 ? ofs : 0), MEM_DEBUG_FILE_LEN);
308 header->file_name[MEM_DEBUG_FILE_LEN] = 0;
310 header->next = mem_debug_chain;
311 header->prev = NULL;
312 if (header->next)
313 header->next->prev = header;
314 mem_debug_chain = header;
316 mem_cur_size += size;
317 if (mem_cur_size > mem_max_size)
318 mem_max_size = mem_cur_size;
320 return MEM_USER_PTR(header);
323 PUB_FUNC void tcc_free_debug(void *ptr)
325 mem_debug_header_t *header;
326 if (!ptr)
327 return;
328 header = malloc_check(ptr, "tcc_free");
329 mem_cur_size -= header->size;
330 header->size = (unsigned)-1;
331 if (header->next)
332 header->next->prev = header->prev;
333 if (header->prev)
334 header->prev->next = header->next;
335 if (header == mem_debug_chain)
336 mem_debug_chain = header->next;
337 free(header);
340 PUB_FUNC void *tcc_mallocz_debug(unsigned long size, const char *file, int line)
342 void *ptr;
343 ptr = tcc_malloc_debug(size,file,line);
344 memset(ptr, 0, size);
345 return ptr;
348 PUB_FUNC void *tcc_realloc_debug(void *ptr, unsigned long size, const char *file, int line)
350 mem_debug_header_t *header;
351 int mem_debug_chain_update = 0;
352 if (!ptr)
353 return tcc_malloc_debug(size, file, line);
354 header = malloc_check(ptr, "tcc_realloc");
355 mem_cur_size -= header->size;
356 mem_debug_chain_update = (header == mem_debug_chain);
357 header = realloc(header, sizeof(mem_debug_header_t) + size);
358 if (!header)
359 tcc_error("memory full (realloc)");
360 header->size = size;
361 MEM_DEBUG_CHECK3(header) = MEM_DEBUG_MAGIC3;
362 if (header->next)
363 header->next->prev = header;
364 if (header->prev)
365 header->prev->next = header;
366 if (mem_debug_chain_update)
367 mem_debug_chain = header;
368 mem_cur_size += size;
369 if (mem_cur_size > mem_max_size)
370 mem_max_size = mem_cur_size;
371 return MEM_USER_PTR(header);
374 PUB_FUNC char *tcc_strdup_debug(const char *str, const char *file, int line)
376 char *ptr;
377 ptr = tcc_malloc_debug(strlen(str) + 1, file, line);
378 strcpy(ptr, str);
379 return ptr;
382 PUB_FUNC void tcc_memstats(int bench)
384 if (mem_cur_size) {
385 mem_debug_header_t *header = mem_debug_chain;
386 fprintf(stderr, "MEM_DEBUG: mem_leak= %d bytes, mem_max_size= %d bytes\n",
387 mem_cur_size, mem_max_size);
388 while (header) {
389 fprintf(stderr, "%s:%u: error: %u bytes leaked\n",
390 header->file_name, header->line_num, header->size);
391 header = header->next;
393 #if MEM_DEBUG-0 == 2
394 exit(2);
395 #endif
396 } else if (bench)
397 fprintf(stderr, "mem_max_size= %d bytes\n", mem_max_size);
399 #endif /* MEM_DEBUG */
401 #define free(p) use_tcc_free(p)
402 #define malloc(s) use_tcc_malloc(s)
403 #define realloc(p, s) use_tcc_realloc(p, s)
405 /********************************************************/
406 /* dynarrays */
408 ST_FUNC void dynarray_add(void *ptab, int *nb_ptr, void *data)
410 int nb, nb_alloc;
411 void **pp;
413 nb = *nb_ptr;
414 pp = *(void ***)ptab;
415 /* every power of two we double array size */
416 if ((nb & (nb - 1)) == 0) {
417 if (!nb)
418 nb_alloc = 1;
419 else
420 nb_alloc = nb * 2;
421 pp = tcc_realloc(pp, nb_alloc * sizeof(void *));
422 *(void***)ptab = pp;
424 pp[nb++] = data;
425 *nb_ptr = nb;
428 ST_FUNC void dynarray_reset(void *pp, int *n)
430 void **p;
431 for (p = *(void***)pp; *n; ++p, --*n)
432 if (*p)
433 tcc_free(*p);
434 tcc_free(*(void**)pp);
435 *(void**)pp = NULL;
438 static void tcc_split_path(TCCState *s, void ***p_ary, int *p_nb_ary, const char *in)
440 const char *p;
441 do {
442 int c;
443 CString str;
445 cstr_new(&str);
446 for (p = in; c = *p, c != '\0' && c != PATHSEP; ++p) {
447 if (c == '{' && p[1] && p[2] == '}') {
448 c = p[1], p += 2;
449 if (c == 'B')
450 cstr_cat(&str, s->tcc_lib_path, -1);
451 } else {
452 cstr_ccat(&str, c);
455 if (str.size) {
456 cstr_ccat(&str, '\0');
457 dynarray_add(p_ary, p_nb_ary, tcc_strdup(str.data));
459 cstr_free(&str);
460 in = p+1;
461 } while (*p);
464 /********************************************************/
466 static void strcat_vprintf(char *buf, int buf_size, const char *fmt, va_list ap)
468 int len;
469 len = strlen(buf);
470 vsnprintf(buf + len, buf_size - len, fmt, ap);
473 static void strcat_printf(char *buf, int buf_size, const char *fmt, ...)
475 va_list ap;
476 va_start(ap, fmt);
477 strcat_vprintf(buf, buf_size, fmt, ap);
478 va_end(ap);
481 static void error1(TCCState *s1, int is_warning, const char *fmt, va_list ap)
483 char buf[2048];
484 BufferedFile **pf, *f;
486 buf[0] = '\0';
487 /* use upper file if inline ":asm:" or token ":paste:" */
488 for (f = file; f && f->filename[0] == ':'; f = f->prev)
490 if (f) {
491 for(pf = s1->include_stack; pf < s1->include_stack_ptr; pf++)
492 strcat_printf(buf, sizeof(buf), "In file included from %s:%d:\n",
493 (*pf)->filename, (*pf)->line_num);
494 if (f->line_num > 0) {
495 strcat_printf(buf, sizeof(buf), "%s:%d: ",
496 f->filename, f->line_num - !!(tok_flags & TOK_FLAG_BOL));
497 } else {
498 strcat_printf(buf, sizeof(buf), "%s: ",
499 f->filename);
501 } else {
502 strcat_printf(buf, sizeof(buf), "tcc: ");
504 if (is_warning)
505 strcat_printf(buf, sizeof(buf), "warning: ");
506 else
507 strcat_printf(buf, sizeof(buf), "error: ");
508 strcat_vprintf(buf, sizeof(buf), fmt, ap);
510 if (!s1->error_func) {
511 /* default case: stderr */
512 if (s1->ppfp) /* print a newline during tcc -E */
513 fprintf(s1->ppfp, "\n"), fflush(s1->ppfp);
514 fflush(stdout); /* flush -v output */
515 fprintf(stderr, "%s\n", buf);
516 fflush(stderr); /* print error/warning now (win32) */
517 } else {
518 s1->error_func(s1->error_opaque, buf);
520 if (!is_warning || s1->warn_error)
521 s1->nb_errors++;
524 LIBTCCAPI void tcc_set_error_func(TCCState *s, void *error_opaque,
525 void (*error_func)(void *opaque, const char *msg))
527 s->error_opaque = error_opaque;
528 s->error_func = error_func;
531 /* error without aborting current compilation */
532 PUB_FUNC void tcc_error_noabort(const char *fmt, ...)
534 TCCState *s1 = tcc_state;
535 va_list ap;
537 va_start(ap, fmt);
538 error1(s1, 0, fmt, ap);
539 va_end(ap);
542 PUB_FUNC void tcc_error(const char *fmt, ...)
544 TCCState *s1 = tcc_state;
545 va_list ap;
547 va_start(ap, fmt);
548 error1(s1, 0, fmt, ap);
549 va_end(ap);
550 /* better than nothing: in some cases, we accept to handle errors */
551 if (s1->error_set_jmp_enabled) {
552 longjmp(s1->error_jmp_buf, 1);
553 } else {
554 /* XXX: eliminate this someday */
555 exit(1);
559 PUB_FUNC void tcc_warning(const char *fmt, ...)
561 TCCState *s1 = tcc_state;
562 va_list ap;
564 if (s1->warn_none)
565 return;
567 va_start(ap, fmt);
568 error1(s1, 1, fmt, ap);
569 va_end(ap);
572 /********************************************************/
573 /* I/O layer */
575 ST_FUNC void tcc_open_bf(TCCState *s1, const char *filename, int initlen)
577 BufferedFile *bf;
578 int buflen = initlen ? initlen : IO_BUF_SIZE;
580 bf = tcc_mallocz(sizeof(BufferedFile) + buflen);
581 bf->buf_ptr = bf->buffer;
582 bf->buf_end = bf->buffer + initlen;
583 bf->buf_end[0] = CH_EOB; /* put eob symbol */
584 pstrcpy(bf->filename, sizeof(bf->filename), filename);
585 #ifdef _WIN32
586 normalize_slashes(bf->filename);
587 #endif
588 bf->line_num = 1;
589 bf->ifdef_stack_ptr = s1->ifdef_stack_ptr;
590 bf->fd = -1;
591 bf->prev = file;
592 file = bf;
595 ST_FUNC void tcc_close(void)
597 BufferedFile *bf = file;
598 if (bf->fd > 0) {
599 close(bf->fd);
600 total_lines += bf->line_num;
602 file = bf->prev;
603 tcc_free(bf);
606 ST_FUNC int tcc_open(TCCState *s1, const char *filename)
608 int fd;
609 if (strcmp(filename, "-") == 0)
610 fd = 0, filename = "<stdin>";
611 else
612 fd = open(filename, O_RDONLY | O_BINARY);
613 if ((s1->verbose == 2 && fd >= 0) || s1->verbose == 3)
614 printf("%s %*s%s\n", fd < 0 ? "nf":"->",
615 (int)(s1->include_stack_ptr - s1->include_stack), "", filename);
616 if (fd < 0)
617 return -1;
619 tcc_open_bf(s1, filename, 0);
620 file->fd = fd;
621 return fd;
624 /* compile the C file opened in 'file'. Return non zero if errors. */
625 static int tcc_compile(TCCState *s1)
627 Sym *define_start;
629 define_start = define_stack;
630 if (setjmp(s1->error_jmp_buf) == 0) {
631 s1->nb_errors = 0;
632 s1->error_set_jmp_enabled = 1;
634 preprocess_start(s1);
635 tccgen_start(s1);
637 #ifdef INC_DEBUG
638 printf("%s: **** new file\n", file->filename);
639 #endif
641 ch = file->buf_ptr[0];
642 tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
643 parse_flags = PARSE_FLAG_PREPROCESS | PARSE_FLAG_TOK_NUM | PARSE_FLAG_TOK_STR;
644 next();
645 decl(VT_CONST);
646 if (tok != TOK_EOF)
647 expect("declaration");
648 /* free defines here already on behalf of of M.M.'s possibly existing
649 experimental preprocessor implementation. The normal call below
650 is still there to free after error-longjmp */
651 free_defines(define_start);
652 tccgen_end(s1);
654 s1->error_set_jmp_enabled = 0;
656 free_inline_functions(s1);
657 /* reset define stack, but keep -D and built-ins */
658 free_defines(define_start);
659 sym_pop(&global_stack, NULL, 0);
660 sym_pop(&local_stack, NULL, 0);
661 return s1->nb_errors != 0 ? -1 : 0;
664 LIBTCCAPI int tcc_compile_string(TCCState *s, const char *str)
666 int len, ret;
668 len = strlen(str);
669 tcc_open_bf(s, "<string>", len);
670 memcpy(file->buffer, str, len);
671 ret = tcc_compile(s);
672 tcc_close();
673 return ret;
676 /* define a preprocessor symbol. A value can also be provided with the '=' operator */
677 LIBTCCAPI void tcc_define_symbol(TCCState *s1, const char *sym, const char *value)
679 int len1, len2;
680 /* default value */
681 if (!value)
682 value = "1";
683 len1 = strlen(sym);
684 len2 = strlen(value);
686 /* init file structure */
687 tcc_open_bf(s1, "<define>", len1 + len2 + 1);
688 memcpy(file->buffer, sym, len1);
689 file->buffer[len1] = ' ';
690 memcpy(file->buffer + len1 + 1, value, len2);
692 /* parse with define parser */
693 ch = file->buf_ptr[0];
694 next_nomacro();
695 parse_define();
697 tcc_close();
700 /* undefine a preprocessor symbol */
701 LIBTCCAPI void tcc_undefine_symbol(TCCState *s1, const char *sym)
703 TokenSym *ts;
704 Sym *s;
705 ts = tok_alloc(sym, strlen(sym));
706 s = define_find(ts->tok);
707 /* undefine symbol by putting an invalid name */
708 if (s)
709 define_undef(s);
712 /* cleanup all static data used during compilation */
713 static void tcc_cleanup(void)
715 if (NULL == tcc_state)
716 return;
717 tccpp_delete(tcc_state);
718 tcc_state = NULL;
719 /* free sym_pools */
720 dynarray_reset(&sym_pools, &nb_sym_pools);
721 /* reset symbol stack */
722 sym_free_first = NULL;
725 LIBTCCAPI TCCState *tcc_new(void)
727 TCCState *s;
729 tcc_cleanup();
731 s = tcc_mallocz(sizeof(TCCState));
732 if (!s)
733 return NULL;
734 tcc_state = s;
735 ++nb_states;
737 s->alacarte_link = 1;
738 s->nocommon = 1;
739 s->warn_implicit_function_declaration = 1;
741 #ifdef CHAR_IS_UNSIGNED
742 s->char_is_unsigned = 1;
743 #endif
744 #ifdef TCC_TARGET_I386
745 s->seg_size = 32;
746 #endif
747 #ifdef TCC_IS_NATIVE
748 s->runtime_main = "main";
749 #endif
750 /* enable this if you want symbols with leading underscore on windows: */
751 #if 0 /* def TCC_TARGET_PE */
752 s->leading_underscore = 1;
753 #endif
754 #ifdef _WIN32
755 tcc_set_lib_path_w32(s);
756 #else
757 tcc_set_lib_path(s, CONFIG_TCCDIR);
758 #endif
759 tccelf_new(s);
760 tccpp_new(s);
762 /* we add dummy defines for some special macros to speed up tests
763 and to have working defined() */
764 define_push(TOK___LINE__, MACRO_OBJ, NULL, NULL);
765 define_push(TOK___FILE__, MACRO_OBJ, NULL, NULL);
766 define_push(TOK___DATE__, MACRO_OBJ, NULL, NULL);
767 define_push(TOK___TIME__, MACRO_OBJ, NULL, NULL);
769 /* define __TINYC__ 92X */
770 char buffer[32]; int a,b,c;
771 sscanf(TCC_VERSION, "%d.%d.%d", &a, &b, &c);
772 sprintf(buffer, "%d", a*10000 + b*100 + c);
773 tcc_define_symbol(s, "__TINYC__", buffer);
776 /* standard defines */
777 tcc_define_symbol(s, "__STDC__", NULL);
778 tcc_define_symbol(s, "__STDC_VERSION__", "199901L");
779 tcc_define_symbol(s, "__STDC_HOSTED__", NULL);
781 /* target defines */
782 #if defined(TCC_TARGET_I386)
783 tcc_define_symbol(s, "__i386__", NULL);
784 tcc_define_symbol(s, "__i386", NULL);
785 tcc_define_symbol(s, "i386", NULL);
786 #elif defined(TCC_TARGET_X86_64)
787 tcc_define_symbol(s, "__x86_64__", NULL);
788 #elif defined(TCC_TARGET_ARM)
789 tcc_define_symbol(s, "__ARM_ARCH_4__", NULL);
790 tcc_define_symbol(s, "__arm_elf__", NULL);
791 tcc_define_symbol(s, "__arm_elf", NULL);
792 tcc_define_symbol(s, "arm_elf", NULL);
793 tcc_define_symbol(s, "__arm__", NULL);
794 tcc_define_symbol(s, "__arm", NULL);
795 tcc_define_symbol(s, "arm", NULL);
796 tcc_define_symbol(s, "__APCS_32__", NULL);
797 tcc_define_symbol(s, "__ARMEL__", NULL);
798 #if defined(TCC_ARM_EABI)
799 tcc_define_symbol(s, "__ARM_EABI__", NULL);
800 #endif
801 #if defined(TCC_ARM_HARDFLOAT)
802 s->float_abi = ARM_HARD_FLOAT;
803 tcc_define_symbol(s, "__ARM_PCS_VFP", NULL);
804 #else
805 s->float_abi = ARM_SOFTFP_FLOAT;
806 #endif
807 #elif defined(TCC_TARGET_ARM64)
808 tcc_define_symbol(s, "__aarch64__", NULL);
809 #endif
811 #ifdef TCC_TARGET_PE
812 tcc_define_symbol(s, "_WIN32", NULL);
813 # ifdef TCC_TARGET_X86_64
814 tcc_define_symbol(s, "_WIN64", NULL);
815 # endif
816 #else
817 tcc_define_symbol(s, "__unix__", NULL);
818 tcc_define_symbol(s, "__unix", NULL);
819 tcc_define_symbol(s, "unix", NULL);
820 # if defined(__linux__)
821 tcc_define_symbol(s, "__linux__", NULL);
822 tcc_define_symbol(s, "__linux", NULL);
823 # endif
824 # if defined(__FreeBSD__)
825 tcc_define_symbol(s, "__FreeBSD__", "__FreeBSD__");
826 /* No 'Thread Storage Local' on FreeBSD with tcc */
827 tcc_define_symbol(s, "__NO_TLS", NULL);
828 # endif
829 # if defined(__FreeBSD_kernel__)
830 tcc_define_symbol(s, "__FreeBSD_kernel__", NULL);
831 # endif
832 #endif
833 # if defined(__NetBSD__)
834 tcc_define_symbol(s, "__NetBSD__", "__NetBSD__");
835 # endif
836 # if defined(__OpenBSD__)
837 tcc_define_symbol(s, "__OpenBSD__", "__OpenBSD__");
838 # endif
840 /* TinyCC & gcc defines */
841 #if defined(TCC_TARGET_PE) && defined(TCC_TARGET_X86_64)
842 /* 64bit Windows. */
843 tcc_define_symbol(s, "__SIZE_TYPE__", "unsigned long long");
844 tcc_define_symbol(s, "__PTRDIFF_TYPE__", "long long");
845 tcc_define_symbol(s, "__LLP64__", NULL);
846 #elif defined(TCC_TARGET_X86_64) || defined(TCC_TARGET_ARM64)
847 /* Other 64bit systems. */
848 tcc_define_symbol(s, "__SIZE_TYPE__", "unsigned long");
849 tcc_define_symbol(s, "__PTRDIFF_TYPE__", "long");
850 tcc_define_symbol(s, "__LP64__", NULL);
851 #else
852 /* Other 32bit systems. */
853 tcc_define_symbol(s, "__SIZE_TYPE__", "unsigned long");
854 tcc_define_symbol(s, "__PTRDIFF_TYPE__", "long");
855 tcc_define_symbol(s, "__ILP32__", NULL);
856 #endif
858 #ifdef TCC_TARGET_PE
859 tcc_define_symbol(s, "__WCHAR_TYPE__", "unsigned short");
860 tcc_define_symbol(s, "__WINT_TYPE__", "unsigned short");
861 #else
862 tcc_define_symbol(s, "__WCHAR_TYPE__", "int");
863 /* wint_t is unsigned int by default, but (signed) int on BSDs
864 and unsigned short on windows. Other OSes might have still
865 other conventions, sigh. */
866 # if defined(__FreeBSD__) || defined (__FreeBSD_kernel__) \
867 || defined(__NetBSD__) || defined(__OpenBSD__)
868 tcc_define_symbol(s, "__WINT_TYPE__", "int");
869 # ifdef __FreeBSD__
870 /* define __GNUC__ to have some useful stuff from sys/cdefs.h
871 that are unconditionally used in FreeBSDs other system headers :/ */
872 tcc_define_symbol(s, "__GNUC__", "2");
873 tcc_define_symbol(s, "__GNUC_MINOR__", "7");
874 tcc_define_symbol(s, "__builtin_alloca", "alloca");
875 # endif
876 # else
877 tcc_define_symbol(s, "__WINT_TYPE__", "unsigned int");
878 /* glibc defines */
879 tcc_define_symbol(s, "__REDIRECT(name, proto, alias)",
880 "name proto __asm__ (#alias)");
881 tcc_define_symbol(s, "__REDIRECT_NTH(name, proto, alias)",
882 "name proto __asm__ (#alias) __THROW");
883 # endif
884 #endif /* ndef TCC_TARGET_PE */
886 /* Some GCC builtins that are simple to express as macros. */
887 tcc_define_symbol(s, "__builtin_extract_return_addr(x)", "x");
889 return s;
892 LIBTCCAPI void tcc_delete(TCCState *s1)
894 int bench = s1->do_bench;
896 tcc_cleanup();
898 /* free sections */
899 tccelf_delete(s1);
901 /* free library paths */
902 dynarray_reset(&s1->library_paths, &s1->nb_library_paths);
903 dynarray_reset(&s1->crt_paths, &s1->nb_crt_paths);
905 /* free include paths */
906 dynarray_reset(&s1->cached_includes, &s1->nb_cached_includes);
907 dynarray_reset(&s1->include_paths, &s1->nb_include_paths);
908 dynarray_reset(&s1->sysinclude_paths, &s1->nb_sysinclude_paths);
909 dynarray_reset(&s1->cmd_include_files, &s1->nb_cmd_include_files);
911 tcc_free(s1->tcc_lib_path);
912 tcc_free(s1->soname);
913 tcc_free(s1->rpath);
914 tcc_free(s1->init_symbol);
915 tcc_free(s1->fini_symbol);
916 tcc_free(s1->outfile);
917 tcc_free(s1->deps_outfile);
918 dynarray_reset(&s1->files, &s1->nb_files);
919 dynarray_reset(&s1->target_deps, &s1->nb_target_deps);
920 dynarray_reset(&s1->pragma_libs, &s1->nb_pragma_libs);
922 #ifdef TCC_IS_NATIVE
923 /* free runtime memory */
924 tcc_run_free(s1);
925 #endif
927 tcc_free(s1);
928 if (0 == --nb_states)
929 tcc_memstats(bench);
932 LIBTCCAPI int tcc_set_output_type(TCCState *s, int output_type)
934 s->output_type = output_type;
936 /* always elf for objects */
937 if (output_type == TCC_OUTPUT_OBJ)
938 s->output_format = TCC_OUTPUT_FORMAT_ELF;
940 if (s->char_is_unsigned)
941 tcc_define_symbol(s, "__CHAR_UNSIGNED__", NULL);
943 if (!s->nostdinc) {
944 /* default include paths */
945 /* -isystem paths have already been handled */
946 tcc_add_sysinclude_path(s, CONFIG_TCC_SYSINCLUDEPATHS);
949 #ifdef CONFIG_TCC_BCHECK
950 if (s->do_bounds_check) {
951 /* if bound checking, then add corresponding sections */
952 tccelf_bounds_new(s);
953 /* define symbol */
954 tcc_define_symbol(s, "__BOUNDS_CHECKING_ON", NULL);
956 #endif
957 if (s->do_debug) {
958 /* add debug sections */
959 tccelf_stab_new(s);
962 tcc_add_library_path(s, CONFIG_TCC_LIBPATHS);
964 #ifdef TCC_TARGET_PE
965 # ifdef _WIN32
966 if (!s->nostdlib && output_type != TCC_OUTPUT_OBJ)
967 tcc_add_systemdir(s);
968 # endif
969 #else
970 /* paths for crt objects */
971 tcc_split_path(s, (void ***)&s->crt_paths, &s->nb_crt_paths, CONFIG_TCC_CRTPREFIX);
972 /* add libc crt1/crti objects */
973 if ((output_type == TCC_OUTPUT_EXE || output_type == TCC_OUTPUT_DLL) &&
974 !s->nostdlib) {
975 if (output_type != TCC_OUTPUT_DLL)
976 tcc_add_crt(s, "crt1.o");
977 tcc_add_crt(s, "crti.o");
979 #endif
980 return 0;
983 LIBTCCAPI int tcc_add_include_path(TCCState *s, const char *pathname)
985 tcc_split_path(s, (void ***)&s->include_paths, &s->nb_include_paths, pathname);
986 return 0;
989 LIBTCCAPI int tcc_add_sysinclude_path(TCCState *s, const char *pathname)
991 tcc_split_path(s, (void ***)&s->sysinclude_paths, &s->nb_sysinclude_paths, pathname);
992 return 0;
995 ST_FUNC int tcc_add_file_internal(TCCState *s1, const char *filename, int flags)
997 int ret, filetype;
999 filetype = flags & 0x0F;
1000 if (filetype == 0) {
1001 /* use a file extension to detect a filetype */
1002 const char *ext = tcc_fileextension(filename);
1003 if (ext[0]) {
1004 ext++;
1005 if (!strcmp(ext, "S"))
1006 filetype = AFF_TYPE_ASMPP;
1007 else if (!strcmp(ext, "s"))
1008 filetype = AFF_TYPE_ASM;
1009 else if (!PATHCMP(ext, "c") || !PATHCMP(ext, "i"))
1010 filetype = AFF_TYPE_C;
1011 else
1012 filetype = AFF_TYPE_BIN;
1013 } else {
1014 filetype = AFF_TYPE_C;
1018 /* open the file */
1019 ret = tcc_open(s1, filename);
1020 if (ret < 0) {
1021 if (flags & AFF_PRINT_ERROR)
1022 tcc_error_noabort("file '%s' not found", filename);
1023 return ret;
1026 /* update target deps */
1027 dynarray_add(&s1->target_deps, &s1->nb_target_deps,
1028 tcc_strdup(filename));
1030 parse_flags = 0;
1031 /* if .S file, define __ASSEMBLER__ like gcc does */
1032 if (filetype == AFF_TYPE_ASM || filetype == AFF_TYPE_ASMPP) {
1033 tcc_define_symbol(s1, "__ASSEMBLER__", NULL);
1034 parse_flags = PARSE_FLAG_ASM_FILE;
1037 if (flags & AFF_PREPROCESS) {
1038 ret = tcc_preprocess(s1);
1039 } else if (filetype == AFF_TYPE_C) {
1040 ret = tcc_compile(s1);
1041 #ifdef CONFIG_TCC_ASM
1042 } else if (filetype == AFF_TYPE_ASMPP) {
1043 /* non preprocessed assembler */
1044 ret = tcc_assemble(s1, 1);
1045 } else if (filetype == AFF_TYPE_ASM) {
1046 /* preprocessed assembler */
1047 ret = tcc_assemble(s1, 0);
1048 #endif
1049 } else {
1050 ElfW(Ehdr) ehdr;
1051 int fd, obj_type;
1053 fd = file->fd;
1054 obj_type = tcc_object_type(fd, &ehdr);
1055 lseek(fd, 0, SEEK_SET);
1057 /* do not display line number if error */
1058 file->line_num = 0;
1060 switch (obj_type) {
1061 case AFF_BINTYPE_REL:
1062 ret = tcc_load_object_file(s1, fd, 0);
1063 break;
1064 #ifndef TCC_TARGET_PE
1065 case AFF_BINTYPE_DYN:
1066 if (s1->output_type == TCC_OUTPUT_MEMORY) {
1067 ret = 0;
1068 #ifdef TCC_IS_NATIVE
1069 if (NULL == dlopen(filename, RTLD_GLOBAL | RTLD_LAZY))
1070 ret = -1;
1071 #endif
1072 } else {
1073 ret = tcc_load_dll(s1, fd, filename,
1074 (flags & AFF_REFERENCED_DLL) != 0);
1076 break;
1077 #endif
1078 case AFF_BINTYPE_AR:
1079 ret = tcc_load_archive(s1, fd);
1080 break;
1081 #ifdef TCC_TARGET_COFF
1082 case AFF_BINTYPE_C67:
1083 ret = tcc_load_coff(s1, fd);
1084 break;
1085 #endif
1086 default:
1087 #ifdef TCC_TARGET_PE
1088 ret = pe_load_file(s1, filename, fd);
1089 #else
1090 /* as GNU ld, consider it is an ld script if not recognized */
1091 ret = tcc_load_ldscript(s1);
1092 #endif
1093 if (ret < 0)
1094 tcc_error_noabort("unrecognized file type");
1095 break;
1098 tcc_close();
1099 return ret;
1102 LIBTCCAPI int tcc_add_file(TCCState *s, const char *filename)
1104 if (s->output_type == TCC_OUTPUT_PREPROCESS)
1105 return tcc_add_file_internal(s, filename, AFF_PRINT_ERROR | AFF_PREPROCESS | s->filetype);
1106 else
1107 return tcc_add_file_internal(s, filename, AFF_PRINT_ERROR | s->filetype);
1110 LIBTCCAPI int tcc_add_library_path(TCCState *s, const char *pathname)
1112 tcc_split_path(s, (void ***)&s->library_paths, &s->nb_library_paths, pathname);
1113 return 0;
1116 static int tcc_add_library_internal(TCCState *s, const char *fmt,
1117 const char *filename, int flags, char **paths, int nb_paths)
1119 char buf[1024];
1120 int i;
1122 for(i = 0; i < nb_paths; i++) {
1123 snprintf(buf, sizeof(buf), fmt, paths[i], filename);
1124 if (tcc_add_file_internal(s, buf, flags | AFF_TYPE_BIN) == 0)
1125 return 0;
1127 return -1;
1130 #ifndef TCC_TARGET_PE
1131 /* find and load a dll. Return non zero if not found */
1132 /* XXX: add '-rpath' option support ? */
1133 ST_FUNC int tcc_add_dll(TCCState *s, const char *filename, int flags)
1135 return tcc_add_library_internal(s, "%s/%s", filename, flags,
1136 s->library_paths, s->nb_library_paths);
1138 #endif
1140 ST_FUNC int tcc_add_crt(TCCState *s, const char *filename)
1142 if (-1 == tcc_add_library_internal(s, "%s/%s",
1143 filename, 0, s->crt_paths, s->nb_crt_paths))
1144 tcc_error_noabort("file '%s' not found", filename);
1145 return 0;
1148 /* the library name is the same as the argument of the '-l' option */
1149 LIBTCCAPI int tcc_add_library(TCCState *s, const char *libraryname)
1151 #ifdef TCC_TARGET_PE
1152 const char *libs[] = { "%s/%s.def", "%s/lib%s.def", "%s/%s.dll", "%s/lib%s.dll", "%s/lib%s.a", NULL };
1153 const char **pp = s->static_link ? libs + 4 : libs;
1154 #else
1155 const char *libs[] = { "%s/lib%s.so", "%s/lib%s.a", NULL };
1156 const char **pp = s->static_link ? libs + 1 : libs;
1157 #endif
1158 while (*pp) {
1159 if (0 == tcc_add_library_internal(s, *pp,
1160 libraryname, 0, s->library_paths, s->nb_library_paths))
1161 return 0;
1162 ++pp;
1164 return -1;
1167 PUB_FUNC int tcc_add_library_err(TCCState *s, const char *libname)
1169 int ret = tcc_add_library(s, libname);
1170 if (ret < 0)
1171 tcc_error_noabort("library '%s' not found", libname);
1172 return ret;
1175 /* habdle #pragma comment(lib,) */
1176 ST_FUNC void tcc_add_pragma_libs(TCCState *s1)
1178 int i;
1179 for (i = 0; i < s1->nb_pragma_libs; i++)
1180 tcc_add_library_err(s1, s1->pragma_libs[i]);
1183 LIBTCCAPI int tcc_add_symbol(TCCState *s, const char *name, const void *val)
1185 #ifdef TCC_TARGET_PE
1186 /* On x86_64 'val' might not be reachable with a 32bit offset.
1187 So it is handled here as if it were in a DLL. */
1188 pe_putimport(s, 0, name, (uintptr_t)val);
1189 #else
1190 set_elf_sym(symtab_section, (uintptr_t)val, 0,
1191 ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE), 0,
1192 SHN_ABS, name);
1193 #endif
1194 return 0;
1197 LIBTCCAPI void tcc_set_lib_path(TCCState *s, const char *path)
1199 tcc_free(s->tcc_lib_path);
1200 s->tcc_lib_path = tcc_strdup(path);
1203 #define WD_ALL 0x0001 /* warning is activated when using -Wall */
1204 #define FD_INVERT 0x0002 /* invert value before storing */
1206 typedef struct FlagDef {
1207 uint16_t offset;
1208 uint16_t flags;
1209 const char *name;
1210 } FlagDef;
1212 static int no_flag(const char **pp)
1214 const char *p = *pp;
1215 if (*p != 'n' || *++p != 'o' || *++p != '-')
1216 return 0;
1217 *pp = p + 1;
1218 return 1;
1221 ST_FUNC int set_flag(TCCState *s, const FlagDef *flags, const char *name)
1223 int value, ret;
1224 const FlagDef *p;
1225 const char *r;
1227 value = 1;
1228 r = name;
1229 if (no_flag(&r))
1230 value = 0;
1232 for (ret = -1, p = flags; p->name; ++p) {
1233 if (ret) {
1234 if (strcmp(r, p->name))
1235 continue;
1236 } else {
1237 if (0 == (p->flags & WD_ALL))
1238 continue;
1240 if (p->offset) {
1241 *(int*)((char *)s + p->offset) =
1242 p->flags & FD_INVERT ? !value : value;
1243 if (ret)
1244 return 0;
1245 } else {
1246 ret = 0;
1249 return ret;
1252 static int strstart(const char *val, const char **str)
1254 const char *p, *q;
1255 p = *str;
1256 q = val;
1257 while (*q) {
1258 if (*p != *q)
1259 return 0;
1260 p++;
1261 q++;
1263 *str = p;
1264 return 1;
1267 /* Like strstart, but automatically takes into account that ld options can
1269 * - start with double or single dash (e.g. '--soname' or '-soname')
1270 * - arguments can be given as separate or after '=' (e.g. '-Wl,-soname,x.so'
1271 * or '-Wl,-soname=x.so')
1273 * you provide `val` always in 'option[=]' form (no leading -)
1275 static int link_option(const char *str, const char *val, const char **ptr)
1277 const char *p, *q;
1278 int ret;
1280 /* there should be 1 or 2 dashes */
1281 if (*str++ != '-')
1282 return 0;
1283 if (*str == '-')
1284 str++;
1286 /* then str & val should match (potentialy up to '=') */
1287 p = str;
1288 q = val;
1290 ret = 1;
1291 if (q[0] == '?') {
1292 ++q;
1293 if (no_flag(&p))
1294 ret = -1;
1297 while (*q != '\0' && *q != '=') {
1298 if (*p != *q)
1299 return 0;
1300 p++;
1301 q++;
1304 /* '=' near eos means ',' or '=' is ok */
1305 if (*q == '=') {
1306 if (*p == 0)
1307 *ptr = p;
1308 if (*p != ',' && *p != '=')
1309 return 0;
1310 p++;
1312 *ptr = p;
1313 return ret;
1316 static const char *skip_linker_arg(const char **str)
1318 const char *s1 = *str;
1319 const char *s2 = strchr(s1, ',');
1320 *str = s2 ? s2++ : (s2 = s1 + strlen(s1));
1321 return s2;
1324 static void copy_linker_arg(char **pp, const char *s, int sep)
1326 const char *q = s;
1327 char *p = *pp;
1328 int l = 0;
1329 if (p && sep)
1330 p[l = strlen(p)] = sep, ++l;
1331 skip_linker_arg(&q);
1332 pstrncpy(l + (*pp = tcc_realloc(p, q - s + l + 1)), s, q - s);
1335 /* set linker options */
1336 static int tcc_set_linker(TCCState *s, const char *option)
1338 while (*option) {
1340 const char *p = NULL;
1341 char *end = NULL;
1342 int ignoring = 0;
1343 int ret;
1345 if (link_option(option, "Bsymbolic", &p)) {
1346 s->symbolic = 1;
1347 } else if (link_option(option, "nostdlib", &p)) {
1348 s->nostdlib = 1;
1349 } else if (link_option(option, "fini=", &p)) {
1350 copy_linker_arg(&s->fini_symbol, p, 0);
1351 ignoring = 1;
1352 } else if (link_option(option, "image-base=", &p)
1353 || link_option(option, "Ttext=", &p)) {
1354 s->text_addr = strtoull(p, &end, 16);
1355 s->has_text_addr = 1;
1356 } else if (link_option(option, "init=", &p)) {
1357 copy_linker_arg(&s->init_symbol, p, 0);
1358 ignoring = 1;
1359 } else if (link_option(option, "oformat=", &p)) {
1360 #if defined(TCC_TARGET_PE)
1361 if (strstart("pe-", &p)) {
1362 #elif defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
1363 if (strstart("elf64-", &p)) {
1364 #else
1365 if (strstart("elf32-", &p)) {
1366 #endif
1367 s->output_format = TCC_OUTPUT_FORMAT_ELF;
1368 } else if (!strcmp(p, "binary")) {
1369 s->output_format = TCC_OUTPUT_FORMAT_BINARY;
1370 #ifdef TCC_TARGET_COFF
1371 } else if (!strcmp(p, "coff")) {
1372 s->output_format = TCC_OUTPUT_FORMAT_COFF;
1373 #endif
1374 } else
1375 goto err;
1377 } else if (link_option(option, "as-needed", &p)) {
1378 ignoring = 1;
1379 } else if (link_option(option, "O", &p)) {
1380 ignoring = 1;
1381 } else if (link_option(option, "rpath=", &p)) {
1382 copy_linker_arg(&s->rpath, p, ':');
1383 } else if (link_option(option, "section-alignment=", &p)) {
1384 s->section_align = strtoul(p, &end, 16);
1385 } else if (link_option(option, "soname=", &p)) {
1386 copy_linker_arg(&s->soname, p, 0);
1387 #ifdef TCC_TARGET_PE
1388 } else if (link_option(option, "large-address-aware", &p)) {
1389 s->pe_characteristics |= 0x20;
1390 } else if (link_option(option, "file-alignment=", &p)) {
1391 s->pe_file_align = strtoul(p, &end, 16);
1392 } else if (link_option(option, "stack=", &p)) {
1393 s->pe_stack_size = strtoul(p, &end, 10);
1394 } else if (link_option(option, "subsystem=", &p)) {
1395 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
1396 if (!strcmp(p, "native")) {
1397 s->pe_subsystem = 1;
1398 } else if (!strcmp(p, "console")) {
1399 s->pe_subsystem = 3;
1400 } else if (!strcmp(p, "gui")) {
1401 s->pe_subsystem = 2;
1402 } else if (!strcmp(p, "posix")) {
1403 s->pe_subsystem = 7;
1404 } else if (!strcmp(p, "efiapp")) {
1405 s->pe_subsystem = 10;
1406 } else if (!strcmp(p, "efiboot")) {
1407 s->pe_subsystem = 11;
1408 } else if (!strcmp(p, "efiruntime")) {
1409 s->pe_subsystem = 12;
1410 } else if (!strcmp(p, "efirom")) {
1411 s->pe_subsystem = 13;
1412 #elif defined(TCC_TARGET_ARM)
1413 if (!strcmp(p, "wince")) {
1414 s->pe_subsystem = 9;
1415 #endif
1416 } else
1417 goto err;
1418 #endif
1419 } else if (ret = link_option(option, "?whole-archive", &p), ret) {
1420 s->alacarte_link = ret < 0;
1421 } else if (p) {
1422 return 0;
1423 } else {
1424 err:
1425 tcc_error("unsupported linker option '%s'", option);
1428 if (ignoring && s->warn_unsupported)
1429 tcc_warning("unsupported linker option '%s'", option);
1431 option = skip_linker_arg(&p);
1433 return 1;
1436 typedef struct TCCOption {
1437 const char *name;
1438 uint16_t index;
1439 uint16_t flags;
1440 } TCCOption;
1442 enum {
1443 TCC_OPTION_HELP,
1444 TCC_OPTION_I,
1445 TCC_OPTION_D,
1446 TCC_OPTION_U,
1447 TCC_OPTION_P,
1448 TCC_OPTION_L,
1449 TCC_OPTION_B,
1450 TCC_OPTION_l,
1451 TCC_OPTION_bench,
1452 TCC_OPTION_bt,
1453 TCC_OPTION_b,
1454 TCC_OPTION_g,
1455 TCC_OPTION_c,
1456 TCC_OPTION_dumpversion,
1457 TCC_OPTION_d,
1458 TCC_OPTION_static,
1459 TCC_OPTION_std,
1460 TCC_OPTION_shared,
1461 TCC_OPTION_soname,
1462 TCC_OPTION_o,
1463 TCC_OPTION_r,
1464 TCC_OPTION_s,
1465 TCC_OPTION_traditional,
1466 TCC_OPTION_Wl,
1467 TCC_OPTION_Wp,
1468 TCC_OPTION_W,
1469 TCC_OPTION_O,
1470 TCC_OPTION_mfloat_abi,
1471 TCC_OPTION_m,
1472 TCC_OPTION_f,
1473 TCC_OPTION_isystem,
1474 TCC_OPTION_iwithprefix,
1475 TCC_OPTION_include,
1476 TCC_OPTION_nostdinc,
1477 TCC_OPTION_nostdlib,
1478 TCC_OPTION_print_search_dirs,
1479 TCC_OPTION_rdynamic,
1480 TCC_OPTION_param,
1481 TCC_OPTION_pedantic,
1482 TCC_OPTION_pthread,
1483 TCC_OPTION_run,
1484 TCC_OPTION_v,
1485 TCC_OPTION_w,
1486 TCC_OPTION_pipe,
1487 TCC_OPTION_E,
1488 TCC_OPTION_MD,
1489 TCC_OPTION_MF,
1490 TCC_OPTION_x
1493 #define TCC_OPTION_HAS_ARG 0x0001
1494 #define TCC_OPTION_NOSEP 0x0002 /* cannot have space before option and arg */
1496 static const TCCOption tcc_options[] = {
1497 { "h", TCC_OPTION_HELP, 0 },
1498 { "-help", TCC_OPTION_HELP, 0 },
1499 { "?", TCC_OPTION_HELP, 0 },
1500 { "I", TCC_OPTION_I, TCC_OPTION_HAS_ARG },
1501 { "D", TCC_OPTION_D, TCC_OPTION_HAS_ARG },
1502 { "U", TCC_OPTION_U, TCC_OPTION_HAS_ARG },
1503 { "P", TCC_OPTION_P, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1504 { "L", TCC_OPTION_L, TCC_OPTION_HAS_ARG },
1505 { "B", TCC_OPTION_B, TCC_OPTION_HAS_ARG },
1506 { "l", TCC_OPTION_l, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1507 { "bench", TCC_OPTION_bench, 0 },
1508 #ifdef CONFIG_TCC_BACKTRACE
1509 { "bt", TCC_OPTION_bt, TCC_OPTION_HAS_ARG },
1510 #endif
1511 #ifdef CONFIG_TCC_BCHECK
1512 { "b", TCC_OPTION_b, 0 },
1513 #endif
1514 { "g", TCC_OPTION_g, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1515 { "c", TCC_OPTION_c, 0 },
1516 { "dumpversion", TCC_OPTION_dumpversion, 0},
1517 { "d", TCC_OPTION_d, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1518 { "static", TCC_OPTION_static, 0 },
1519 { "std", TCC_OPTION_std, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1520 { "shared", TCC_OPTION_shared, 0 },
1521 { "soname", TCC_OPTION_soname, TCC_OPTION_HAS_ARG },
1522 { "o", TCC_OPTION_o, TCC_OPTION_HAS_ARG },
1523 { "-param", TCC_OPTION_param, TCC_OPTION_HAS_ARG },
1524 { "pedantic", TCC_OPTION_pedantic, 0},
1525 { "pthread", TCC_OPTION_pthread, 0},
1526 { "run", TCC_OPTION_run, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1527 { "rdynamic", TCC_OPTION_rdynamic, 0 },
1528 { "r", TCC_OPTION_r, 0 },
1529 { "s", TCC_OPTION_s, 0 },
1530 { "traditional", TCC_OPTION_traditional, 0 },
1531 { "Wl,", TCC_OPTION_Wl, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1532 { "Wp,", TCC_OPTION_Wp, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1533 { "W", TCC_OPTION_W, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1534 { "O", TCC_OPTION_O, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1535 #ifdef TCC_TARGET_ARM
1536 { "mfloat-abi", TCC_OPTION_mfloat_abi, TCC_OPTION_HAS_ARG },
1537 #endif
1538 { "m", TCC_OPTION_m, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1539 { "f", TCC_OPTION_f, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1540 { "isystem", TCC_OPTION_isystem, TCC_OPTION_HAS_ARG },
1541 { "iwithprefix", TCC_OPTION_iwithprefix, TCC_OPTION_HAS_ARG },
1542 { "include", TCC_OPTION_include, TCC_OPTION_HAS_ARG },
1543 { "nostdinc", TCC_OPTION_nostdinc, 0 },
1544 { "nostdlib", TCC_OPTION_nostdlib, 0 },
1545 { "print-search-dirs", TCC_OPTION_print_search_dirs, 0 },
1546 { "v", TCC_OPTION_v, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1547 { "w", TCC_OPTION_w, 0 },
1548 { "pipe", TCC_OPTION_pipe, 0},
1549 { "E", TCC_OPTION_E, 0},
1550 { "MD", TCC_OPTION_MD, 0},
1551 { "MF", TCC_OPTION_MF, TCC_OPTION_HAS_ARG },
1552 { "x", TCC_OPTION_x, TCC_OPTION_HAS_ARG },
1553 { NULL, 0, 0 },
1556 static const FlagDef options_W[] = {
1557 { 0, 0, "all" },
1558 { offsetof(TCCState, warn_unsupported), 0, "unsupported" },
1559 { offsetof(TCCState, warn_write_strings), 0, "write-strings" },
1560 { offsetof(TCCState, warn_error), 0, "error" },
1561 { offsetof(TCCState, warn_implicit_function_declaration), WD_ALL,
1562 "implicit-function-declaration" },
1563 { 0, 0, NULL }
1566 static const FlagDef options_f[] = {
1567 { offsetof(TCCState, char_is_unsigned), 0, "unsigned-char" },
1568 { offsetof(TCCState, char_is_unsigned), FD_INVERT, "signed-char" },
1569 { offsetof(TCCState, nocommon), FD_INVERT, "common" },
1570 { offsetof(TCCState, leading_underscore), 0, "leading-underscore" },
1571 { offsetof(TCCState, ms_extensions), 0, "ms-extensions" },
1572 { offsetof(TCCState, old_struct_init_code), 0, "old-struct-init-code" },
1573 { offsetof(TCCState, dollars_in_identifiers), 0, "dollars-in-identifiers" },
1574 { 0, 0, NULL }
1577 static const FlagDef options_m[] = {
1578 { offsetof(TCCState, ms_bitfields), 0, "ms-bitfields" },
1579 #ifdef TCC_TARGET_X86_64
1580 { offsetof(TCCState, nosse), FD_INVERT, "sse" },
1581 #endif
1582 { 0, 0, NULL }
1585 static void parse_option_D(TCCState *s1, const char *optarg)
1587 char *sym = tcc_strdup(optarg);
1588 char *value = strchr(sym, '=');
1589 if (value)
1590 *value++ = '\0';
1591 tcc_define_symbol(s1, sym, value);
1592 tcc_free(sym);
1595 static void args_parser_add_file(TCCState *s, const char* filename, int filetype)
1597 struct filespec *f = tcc_malloc(sizeof *f + strlen(filename));
1598 f->type = filetype;
1599 strcpy(f->name, filename);
1600 dynarray_add(&s->files, &s->nb_files, f);
1603 /* read list file */
1604 static void args_parser_listfile(TCCState *s, const char *filename)
1606 int fd;
1607 size_t len;
1608 char *p;
1610 fd = open(filename, O_RDONLY | O_BINARY);
1611 if (fd < 0)
1612 tcc_error("file '%s' not found", filename);
1614 len = lseek(fd, 0, SEEK_END);
1615 p = tcc_malloc(len + 1), p[len] = 0;
1616 lseek(fd, 0, SEEK_SET), read(fd, p, len), close(fd);
1617 tcc_set_options(s, p);
1618 tcc_free(p);
1621 PUB_FUNC int tcc_parse_args(TCCState *s, int argc, char **argv)
1623 const TCCOption *popt;
1624 const char *optarg, *r;
1625 const char *run = NULL;
1626 int optind = 0;
1627 int x;
1628 int last_o = -1;
1629 CString linker_arg; /* collect -Wl options */
1630 char buf[1024];
1632 cstr_new(&linker_arg);
1634 while (optind < argc) {
1636 r = argv[optind++];
1638 reparse:
1639 if (r[0] == '@' && r[1] != '\0') {
1640 args_parser_listfile(s, r + 1);
1641 continue;
1644 if (r[0] != '-' || r[1] == '\0') {
1645 if (r[0] != '@') /* allow "tcc file(s) -run @ args ..." */
1646 args_parser_add_file(s, r, s->filetype);
1647 if (run) {
1648 tcc_set_options(s, run);
1649 optind--;
1650 /* argv[0] will be this file */
1651 break;
1653 continue;
1656 /* find option in table */
1657 for(popt = tcc_options; ; ++popt) {
1658 const char *p1 = popt->name;
1659 const char *r1 = r + 1;
1660 if (p1 == NULL)
1661 tcc_error("invalid option -- '%s'", r);
1662 if (!strstart(p1, &r1))
1663 continue;
1664 optarg = r1;
1665 if (popt->flags & TCC_OPTION_HAS_ARG) {
1666 if (*r1 == '\0' && !(popt->flags & TCC_OPTION_NOSEP)) {
1667 if (optind >= argc)
1668 arg_err:
1669 tcc_error("argument to '%s' is missing", r);
1670 optarg = argv[optind++];
1672 } else if (*r1 != '\0')
1673 continue;
1674 break;
1677 switch(popt->index) {
1678 case TCC_OPTION_HELP:
1679 return 0;
1680 case TCC_OPTION_I:
1681 tcc_add_include_path(s, optarg);
1682 break;
1683 case TCC_OPTION_D:
1684 parse_option_D(s, optarg);
1685 break;
1686 case TCC_OPTION_U:
1687 tcc_undefine_symbol(s, optarg);
1688 break;
1689 case TCC_OPTION_L:
1690 tcc_add_library_path(s, optarg);
1691 break;
1692 case TCC_OPTION_B:
1693 /* set tcc utilities path (mainly for tcc development) */
1694 tcc_set_lib_path(s, optarg);
1695 break;
1696 case TCC_OPTION_l:
1697 args_parser_add_file(s, optarg, AFF_TYPE_LIBWH - s->alacarte_link);
1698 s->nb_libraries++;
1699 break;
1700 case TCC_OPTION_pthread:
1701 parse_option_D(s, "_REENTRANT");
1702 s->option_pthread = 1;
1703 break;
1704 case TCC_OPTION_bench:
1705 s->do_bench = 1;
1706 break;
1707 #ifdef CONFIG_TCC_BACKTRACE
1708 case TCC_OPTION_bt:
1709 tcc_set_num_callers(atoi(optarg));
1710 break;
1711 #endif
1712 #ifdef CONFIG_TCC_BCHECK
1713 case TCC_OPTION_b:
1714 s->do_bounds_check = 1;
1715 s->do_debug = 1;
1716 break;
1717 #endif
1718 case TCC_OPTION_g:
1719 s->do_debug = 1;
1720 break;
1721 case TCC_OPTION_c:
1722 x = TCC_OUTPUT_OBJ;
1723 set_output_type:
1724 if (s->output_type)
1725 tcc_warning("-%s: overriding compiler action already specified", popt->name);
1726 s->output_type = x;
1727 break;
1728 case TCC_OPTION_d:
1729 if (*optarg == 'D')
1730 s->dflag = 3;
1731 else if (*optarg == 'M')
1732 s->dflag = 7;
1733 else
1734 goto unsupported_option;
1735 break;
1736 case TCC_OPTION_static:
1737 s->static_link = 1;
1738 break;
1739 case TCC_OPTION_std:
1740 /* silently ignore, a current purpose:
1741 allow to use a tcc as a reference compiler for "make test" */
1742 break;
1743 case TCC_OPTION_shared:
1744 x = TCC_OUTPUT_DLL;
1745 goto set_output_type;
1746 case TCC_OPTION_soname:
1747 s->soname = tcc_strdup(optarg);
1748 break;
1749 case TCC_OPTION_o:
1750 if (s->outfile) {
1751 tcc_warning("multiple -o option");
1752 tcc_free(s->outfile);
1754 s->outfile = tcc_strdup(optarg);
1755 break;
1756 case TCC_OPTION_r:
1757 /* generate a .o merging several output files */
1758 s->option_r = 1;
1759 x = TCC_OUTPUT_OBJ;
1760 goto set_output_type;
1761 case TCC_OPTION_isystem:
1762 tcc_add_sysinclude_path(s, optarg);
1763 break;
1764 case TCC_OPTION_iwithprefix:
1765 snprintf(buf, sizeof buf, "{B}/%s", optarg);
1766 tcc_add_sysinclude_path(s, buf);
1767 break;
1768 case TCC_OPTION_include:
1769 dynarray_add(&s->cmd_include_files,
1770 &s->nb_cmd_include_files, tcc_strdup(optarg));
1771 break;
1772 case TCC_OPTION_nostdinc:
1773 s->nostdinc = 1;
1774 break;
1775 case TCC_OPTION_nostdlib:
1776 s->nostdlib = 1;
1777 break;
1778 case TCC_OPTION_print_search_dirs:
1779 s->print_search_dirs = 1;
1780 break;
1781 case TCC_OPTION_run:
1782 #ifndef TCC_IS_NATIVE
1783 tcc_error("-run is not available in a cross compiler");
1784 #endif
1785 run = optarg;
1786 x = TCC_OUTPUT_MEMORY;
1787 goto set_output_type;
1788 case TCC_OPTION_v:
1789 do ++s->verbose; while (*optarg++ == 'v');
1790 break;
1791 case TCC_OPTION_f:
1792 if (set_flag(s, options_f, optarg) < 0)
1793 goto unsupported_option;
1794 break;
1795 #ifdef TCC_TARGET_ARM
1796 case TCC_OPTION_mfloat_abi:
1797 /* tcc doesn't support soft float yet */
1798 if (!strcmp(optarg, "softfp")) {
1799 s->float_abi = ARM_SOFTFP_FLOAT;
1800 tcc_undefine_symbol(s, "__ARM_PCS_VFP");
1801 } else if (!strcmp(optarg, "hard"))
1802 s->float_abi = ARM_HARD_FLOAT;
1803 else
1804 tcc_error("unsupported float abi '%s'", optarg);
1805 break;
1806 #endif
1807 case TCC_OPTION_m:
1808 if (set_flag(s, options_m, optarg) == 0)
1809 break;
1810 else if (x = atoi(optarg), x == 32 || x == 64)
1811 s->cross_target = x;
1812 else
1813 goto unsupported_option;
1814 break;
1815 case TCC_OPTION_W:
1816 if (set_flag(s, options_W, optarg) < 0)
1817 goto unsupported_option;
1818 break;
1819 case TCC_OPTION_w:
1820 s->warn_none = 1;
1821 break;
1822 case TCC_OPTION_rdynamic:
1823 s->rdynamic = 1;
1824 break;
1825 case TCC_OPTION_Wl:
1826 if (linker_arg.size)
1827 --linker_arg.size, cstr_ccat(&linker_arg, ',');
1828 cstr_cat(&linker_arg, optarg, 0);
1829 if (tcc_set_linker(s, linker_arg.data))
1830 cstr_free(&linker_arg);
1831 break;
1832 case TCC_OPTION_Wp:
1833 r = optarg;
1834 goto reparse;
1835 case TCC_OPTION_E:
1836 x = TCC_OUTPUT_PREPROCESS;
1837 goto set_output_type;
1838 case TCC_OPTION_P:
1839 s->Pflag = atoi(optarg) + 1;
1840 break;
1841 case TCC_OPTION_MD:
1842 s->gen_deps = 1;
1843 break;
1844 case TCC_OPTION_MF:
1845 s->deps_outfile = tcc_strdup(optarg);
1846 break;
1847 case TCC_OPTION_dumpversion:
1848 printf ("%s\n", TCC_VERSION);
1849 exit(0);
1850 break;
1851 case TCC_OPTION_x:
1852 if (*optarg == 'c')
1853 s->filetype = AFF_TYPE_C;
1854 else if (*optarg == 'a')
1855 s->filetype = AFF_TYPE_ASMPP;
1856 else if (*optarg == 'n')
1857 s->filetype = AFF_TYPE_NONE;
1858 else
1859 tcc_warning("unsupported language '%s'", optarg);
1860 break;
1861 case TCC_OPTION_O:
1862 last_o = atoi(optarg);
1863 break;
1864 case TCC_OPTION_traditional:
1865 case TCC_OPTION_pedantic:
1866 case TCC_OPTION_pipe:
1867 case TCC_OPTION_s:
1868 /* ignored */
1869 break;
1870 default:
1871 unsupported_option:
1872 if (s->warn_unsupported)
1873 tcc_warning("unsupported option '%s'", r);
1874 break;
1878 if (last_o > 0)
1879 tcc_define_symbol(s, "__OPTIMIZE__", NULL);
1881 if (linker_arg.size) {
1882 r = linker_arg.data;
1883 goto arg_err;
1886 return optind;
1889 LIBTCCAPI int tcc_set_options(TCCState *s, const char *r)
1891 char **argv;
1892 int argc;
1893 int ret, q, c;
1894 CString str;
1896 argc = 0, argv = NULL;
1897 for(;;) {
1898 while (c = (unsigned char)*r, c && c <= ' ')
1899 ++r;
1900 if (c == 0)
1901 break;
1902 q = 0;
1903 cstr_new(&str);
1904 while (c = (unsigned char)*r, c) {
1905 ++r;
1906 if (c == '\\' && (*r == '"' || *r == '\\')) {
1907 c = *r++;
1908 } else if (c == '"') {
1909 q = !q;
1910 continue;
1911 } else if (q == 0 && c <= ' ') {
1912 break;
1914 cstr_ccat(&str, c);
1916 cstr_ccat(&str, 0);
1917 //printf("<%s>\n", str.data), fflush(stdout);
1918 dynarray_add(&argv, &argc, tcc_strdup(str.data));
1919 cstr_free(&str);
1921 ret = tcc_parse_args(s, argc, argv);
1922 dynarray_reset(&argv, &argc);
1923 return ret;
1926 PUB_FUNC void tcc_print_stats(TCCState *s, unsigned total_time)
1928 if (total_time < 1)
1929 total_time = 1;
1930 if (total_bytes < 1)
1931 total_bytes = 1;
1932 fprintf(stderr, "%d idents, %d lines, %d bytes, %0.3f s, %u lines/s, %0.1f MB/s\n",
1933 tok_ident - TOK_IDENT, total_lines, total_bytes,
1934 (double)total_time/1000,
1935 (unsigned)total_lines*1000/total_time,
1936 (double)total_bytes/1000/total_time);
1939 PUB_FUNC void tcc_set_environment(TCCState *s)
1941 char * path;
1943 path = getenv("C_INCLUDE_PATH");
1944 if(path != NULL) {
1945 tcc_add_include_path(s, path);
1947 path = getenv("CPATH");
1948 if(path != NULL) {
1949 tcc_add_include_path(s, path);
1951 path = getenv("LIBRARY_PATH");
1952 if(path != NULL) {
1953 tcc_add_library_path(s, path);