SECTION_ALIGNMENT -> RUN_SECTION_ALIGNMENT, and tweaks
[tinycc.git] / libtcc.c
blob11a7cf6ffe19286660cb26bf8f3f6546647e5ba6
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 /********************************************************/
37 #ifdef ONE_SOURCE
38 #include "tccpp.c"
39 #include "tccgen.c"
40 #include "tccelf.c"
41 #include "tccrun.c"
42 #ifdef TCC_TARGET_I386
43 #include "i386-gen.c"
44 #include "i386-link.c"
45 #endif
46 #ifdef TCC_TARGET_ARM
47 #include "arm-gen.c"
48 #include "arm-link.c"
49 #endif
50 #ifdef TCC_TARGET_ARM64
51 #include "arm64-gen.c"
52 #include "arm64-link.c"
53 #endif
54 #ifdef TCC_TARGET_C67
55 #include "c67-gen.c"
56 #include "c67-link.c"
57 #endif
58 #ifdef TCC_TARGET_X86_64
59 #include "x86_64-gen.c"
60 #include "x86_64-link.c"
61 #endif
62 #ifdef CONFIG_TCC_ASM
63 #include "tccasm.c"
64 #if defined TCC_TARGET_I386 || defined TCC_TARGET_X86_64
65 #include "i386-asm.c"
66 #endif
67 #endif
68 #ifdef TCC_TARGET_COFF
69 #include "tcccoff.c"
70 #endif
71 #ifdef TCC_TARGET_PE
72 #include "tccpe.c"
73 #endif
74 #endif /* ONE_SOURCE */
76 /********************************************************/
77 #ifndef CONFIG_TCC_ASM
78 ST_FUNC void asm_instr(void)
80 tcc_error("inline asm() not supported");
82 ST_FUNC void asm_global_instr(void)
84 tcc_error("inline asm() not supported");
86 #endif
88 /********************************************************/
89 #ifdef _WIN32
90 ST_FUNC char *normalize_slashes(char *path)
92 char *p;
93 for (p = path; *p; ++p)
94 if (*p == '\\')
95 *p = '/';
96 return path;
99 static HMODULE tcc_module;
101 /* on win32, we suppose the lib and includes are at the location of 'tcc.exe' */
102 static void tcc_set_lib_path_w32(TCCState *s)
104 char path[1024], *p;
105 GetModuleFileNameA(tcc_module, path, sizeof path);
106 p = tcc_basename(normalize_slashes(strlwr(path)));
107 if (p - 5 > path && 0 == strncmp(p - 5, "/bin/", 5))
108 p -= 5;
109 else if (p > path)
110 p--;
111 *p = 0;
112 tcc_set_lib_path(s, path);
115 #ifdef TCC_TARGET_PE
116 static void tcc_add_systemdir(TCCState *s)
118 char buf[1000];
119 GetSystemDirectory(buf, sizeof buf);
120 tcc_add_library_path(s, normalize_slashes(buf));
122 #endif
124 #ifdef LIBTCC_AS_DLL
125 BOOL WINAPI DllMain (HINSTANCE hDll, DWORD dwReason, LPVOID lpReserved)
127 if (DLL_PROCESS_ATTACH == dwReason)
128 tcc_module = hDll;
129 return TRUE;
131 #endif
132 #endif
134 /********************************************************/
135 /* copy a string and truncate it. */
136 PUB_FUNC char *pstrcpy(char *buf, int buf_size, const char *s)
138 char *q, *q_end;
139 int c;
141 if (buf_size > 0) {
142 q = buf;
143 q_end = buf + buf_size - 1;
144 while (q < q_end) {
145 c = *s++;
146 if (c == '\0')
147 break;
148 *q++ = c;
150 *q = '\0';
152 return buf;
155 /* strcat and truncate. */
156 PUB_FUNC char *pstrcat(char *buf, int buf_size, const char *s)
158 int len;
159 len = strlen(buf);
160 if (len < buf_size)
161 pstrcpy(buf + len, buf_size - len, s);
162 return buf;
165 PUB_FUNC char *pstrncpy(char *out, const char *in, size_t num)
167 memcpy(out, in, num);
168 out[num] = '\0';
169 return out;
172 /* extract the basename of a file */
173 PUB_FUNC char *tcc_basename(const char *name)
175 char *p = strchr(name, 0);
176 while (p > name && !IS_DIRSEP(p[-1]))
177 --p;
178 return p;
181 /* extract extension part of a file
183 * (if no extension, return pointer to end-of-string)
185 PUB_FUNC char *tcc_fileextension (const char *name)
187 char *b = tcc_basename(name);
188 char *e = strrchr(b, '.');
189 return e ? e : strchr(b, 0);
192 /********************************************************/
193 /* memory management */
195 #undef free
196 #undef malloc
197 #undef realloc
199 #ifndef MEM_DEBUG
201 PUB_FUNC void tcc_free(void *ptr)
203 free(ptr);
206 PUB_FUNC void *tcc_malloc(unsigned long size)
208 void *ptr;
209 ptr = malloc(size);
210 if (!ptr && size)
211 tcc_error("memory full (malloc)");
212 return ptr;
215 PUB_FUNC void *tcc_mallocz(unsigned long size)
217 void *ptr;
218 ptr = tcc_malloc(size);
219 memset(ptr, 0, size);
220 return ptr;
223 PUB_FUNC void *tcc_realloc(void *ptr, unsigned long size)
225 void *ptr1;
226 ptr1 = realloc(ptr, size);
227 if (!ptr1 && size)
228 tcc_error("memory full (realloc)");
229 return ptr1;
232 PUB_FUNC char *tcc_strdup(const char *str)
234 char *ptr;
235 ptr = tcc_malloc(strlen(str) + 1);
236 strcpy(ptr, str);
237 return ptr;
240 PUB_FUNC void tcc_memstats(int bench)
244 #else
246 #define MEM_DEBUG_MAGIC1 0xFEEDDEB1
247 #define MEM_DEBUG_MAGIC2 0xFEEDDEB2
248 #define MEM_DEBUG_MAGIC3 0xFEEDDEB3
249 #define MEM_DEBUG_FILE_LEN 40
250 #define MEM_DEBUG_CHECK3(header) \
251 ((mem_debug_header_t*)((char*)header + header->size))->magic3
252 #define MEM_USER_PTR(header) \
253 ((char *)header + offsetof(mem_debug_header_t, magic3))
254 #define MEM_HEADER_PTR(ptr) \
255 (mem_debug_header_t *)((char*)ptr - offsetof(mem_debug_header_t, magic3))
257 struct mem_debug_header {
258 unsigned magic1;
259 unsigned size;
260 struct mem_debug_header *prev;
261 struct mem_debug_header *next;
262 int line_num;
263 char file_name[MEM_DEBUG_FILE_LEN + 1];
264 unsigned magic2;
265 __attribute__((aligned(16))) unsigned magic3;
268 typedef struct mem_debug_header mem_debug_header_t;
270 static mem_debug_header_t *mem_debug_chain;
271 static unsigned mem_cur_size;
272 static unsigned mem_max_size;
274 static mem_debug_header_t *malloc_check(void *ptr, const char *msg)
276 mem_debug_header_t * header = MEM_HEADER_PTR(ptr);
277 if (header->magic1 != MEM_DEBUG_MAGIC1 ||
278 header->magic2 != MEM_DEBUG_MAGIC2 ||
279 MEM_DEBUG_CHECK3(header) != MEM_DEBUG_MAGIC3 ||
280 header->size == (unsigned)-1) {
281 fprintf(stderr, "%s check failed\n", msg);
282 if (header->magic1 == MEM_DEBUG_MAGIC1)
283 fprintf(stderr, "%s:%u: block allocated here.\n",
284 header->file_name, header->line_num);
285 exit(1);
287 return header;
290 PUB_FUNC void *tcc_malloc_debug(unsigned long size, const char *file, int line)
292 int ofs;
293 mem_debug_header_t *header;
295 header = malloc(sizeof(mem_debug_header_t) + size);
296 if (!header)
297 tcc_error("memory full (malloc)");
299 header->magic1 = MEM_DEBUG_MAGIC1;
300 header->magic2 = MEM_DEBUG_MAGIC2;
301 header->size = size;
302 MEM_DEBUG_CHECK3(header) = MEM_DEBUG_MAGIC3;
303 header->line_num = line;
304 ofs = strlen(file) - MEM_DEBUG_FILE_LEN;
305 strncpy(header->file_name, file + (ofs > 0 ? ofs : 0), MEM_DEBUG_FILE_LEN);
306 header->file_name[MEM_DEBUG_FILE_LEN] = 0;
308 header->next = mem_debug_chain;
309 header->prev = NULL;
310 if (header->next)
311 header->next->prev = header;
312 mem_debug_chain = header;
314 mem_cur_size += size;
315 if (mem_cur_size > mem_max_size)
316 mem_max_size = mem_cur_size;
318 return MEM_USER_PTR(header);
321 PUB_FUNC void tcc_free_debug(void *ptr)
323 mem_debug_header_t *header;
324 if (!ptr)
325 return;
326 header = malloc_check(ptr, "tcc_free");
327 mem_cur_size -= header->size;
328 header->size = (unsigned)-1;
329 if (header->next)
330 header->next->prev = header->prev;
331 if (header->prev)
332 header->prev->next = header->next;
333 if (header == mem_debug_chain)
334 mem_debug_chain = header->next;
335 free(header);
338 PUB_FUNC void *tcc_mallocz_debug(unsigned long size, const char *file, int line)
340 void *ptr;
341 ptr = tcc_malloc_debug(size,file,line);
342 memset(ptr, 0, size);
343 return ptr;
346 PUB_FUNC void *tcc_realloc_debug(void *ptr, unsigned long size, const char *file, int line)
348 mem_debug_header_t *header;
349 int mem_debug_chain_update = 0;
350 if (!ptr)
351 return tcc_malloc_debug(size, file, line);
352 header = malloc_check(ptr, "tcc_realloc");
353 mem_cur_size -= header->size;
354 mem_debug_chain_update = (header == mem_debug_chain);
355 header = realloc(header, sizeof(mem_debug_header_t) + size);
356 if (!header)
357 tcc_error("memory full (realloc)");
358 header->size = size;
359 MEM_DEBUG_CHECK3(header) = MEM_DEBUG_MAGIC3;
360 if (header->next)
361 header->next->prev = header;
362 if (header->prev)
363 header->prev->next = header;
364 if (mem_debug_chain_update)
365 mem_debug_chain = header;
366 mem_cur_size += size;
367 if (mem_cur_size > mem_max_size)
368 mem_max_size = mem_cur_size;
369 return MEM_USER_PTR(header);
372 PUB_FUNC char *tcc_strdup_debug(const char *str, const char *file, int line)
374 char *ptr;
375 ptr = tcc_malloc_debug(strlen(str) + 1, file, line);
376 strcpy(ptr, str);
377 return ptr;
380 PUB_FUNC void tcc_memstats(int bench)
382 if (mem_cur_size) {
383 mem_debug_header_t *header = mem_debug_chain;
384 fprintf(stderr, "MEM_DEBUG: mem_leak= %d bytes, mem_max_size= %d bytes\n",
385 mem_cur_size, mem_max_size);
386 while (header) {
387 fprintf(stderr, "%s:%u: error: %u bytes leaked\n",
388 header->file_name, header->line_num, header->size);
389 header = header->next;
391 #if MEM_DEBUG-0 == 2
392 exit(2);
393 #endif
394 } else if (bench)
395 fprintf(stderr, "mem_max_size= %d bytes\n", mem_max_size);
397 #endif /* MEM_DEBUG */
399 #define free(p) use_tcc_free(p)
400 #define malloc(s) use_tcc_malloc(s)
401 #define realloc(p, s) use_tcc_realloc(p, s)
403 /********************************************************/
404 /* dynarrays */
406 ST_FUNC void dynarray_add(void ***ptab, int *nb_ptr, void *data)
408 int nb, nb_alloc;
409 void **pp;
411 nb = *nb_ptr;
412 pp = *ptab;
413 /* every power of two we double array size */
414 if ((nb & (nb - 1)) == 0) {
415 if (!nb)
416 nb_alloc = 1;
417 else
418 nb_alloc = nb * 2;
419 pp = tcc_realloc(pp, nb_alloc * sizeof(void *));
420 *ptab = pp;
422 pp[nb++] = data;
423 *nb_ptr = nb;
426 ST_FUNC void dynarray_reset(void *pp, int *n)
428 void **p;
429 for (p = *(void***)pp; *n; ++p, --*n)
430 if (*p)
431 tcc_free(*p);
432 tcc_free(*(void**)pp);
433 *(void**)pp = NULL;
436 static void tcc_split_path(TCCState *s, void ***p_ary, int *p_nb_ary, const char *in)
438 const char *p;
439 do {
440 int c;
441 CString str;
443 cstr_new(&str);
444 for (p = in; c = *p, c != '\0' && c != PATHSEP; ++p) {
445 if (c == '{' && p[1] && p[2] == '}') {
446 c = p[1], p += 2;
447 if (c == 'B')
448 cstr_cat(&str, s->tcc_lib_path, -1);
449 } else {
450 cstr_ccat(&str, c);
453 if (str.size) {
454 cstr_ccat(&str, '\0');
455 dynarray_add(p_ary, p_nb_ary, tcc_strdup(str.data));
457 cstr_free(&str);
458 in = p+1;
459 } while (*p);
462 /********************************************************/
464 static void strcat_vprintf(char *buf, int buf_size, const char *fmt, va_list ap)
466 int len;
467 len = strlen(buf);
468 vsnprintf(buf + len, buf_size - len, fmt, ap);
471 static void strcat_printf(char *buf, int buf_size, const char *fmt, ...)
473 va_list ap;
474 va_start(ap, fmt);
475 strcat_vprintf(buf, buf_size, fmt, ap);
476 va_end(ap);
479 static void error1(TCCState *s1, int is_warning, const char *fmt, va_list ap)
481 char buf[2048];
482 BufferedFile **pf, *f;
484 buf[0] = '\0';
485 /* use upper file if inline ":asm:" or token ":paste:" */
486 for (f = file; f && f->filename[0] == ':'; f = f->prev)
488 if (f) {
489 for(pf = s1->include_stack; pf < s1->include_stack_ptr; pf++)
490 strcat_printf(buf, sizeof(buf), "In file included from %s:%d:\n",
491 (*pf)->filename, (*pf)->line_num);
492 if (f->line_num > 0) {
493 strcat_printf(buf, sizeof(buf), "%s:%d: ",
494 f->filename, f->line_num - !!(tok_flags & TOK_FLAG_BOL));
495 } else {
496 strcat_printf(buf, sizeof(buf), "%s: ",
497 f->filename);
499 } else {
500 strcat_printf(buf, sizeof(buf), "tcc: ");
502 if (is_warning)
503 strcat_printf(buf, sizeof(buf), "warning: ");
504 else
505 strcat_printf(buf, sizeof(buf), "error: ");
506 strcat_vprintf(buf, sizeof(buf), fmt, ap);
508 if (!s1->error_func) {
509 /* default case: stderr */
510 if (s1->ppfp) /* print a newline during tcc -E */
511 fprintf(s1->ppfp, "\n"), fflush(s1->ppfp);
512 fprintf(stderr, "%s\n", buf);
513 fflush(stderr); /* print error/warning now (win32) */
514 } else {
515 s1->error_func(s1->error_opaque, buf);
517 if (!is_warning || s1->warn_error)
518 s1->nb_errors++;
521 LIBTCCAPI void tcc_set_error_func(TCCState *s, void *error_opaque,
522 void (*error_func)(void *opaque, const char *msg))
524 s->error_opaque = error_opaque;
525 s->error_func = error_func;
528 /* error without aborting current compilation */
529 PUB_FUNC void tcc_error_noabort(const char *fmt, ...)
531 TCCState *s1 = tcc_state;
532 va_list ap;
534 va_start(ap, fmt);
535 error1(s1, 0, fmt, ap);
536 va_end(ap);
539 PUB_FUNC void tcc_error(const char *fmt, ...)
541 TCCState *s1 = tcc_state;
542 va_list ap;
544 va_start(ap, fmt);
545 error1(s1, 0, fmt, ap);
546 va_end(ap);
547 /* better than nothing: in some cases, we accept to handle errors */
548 if (s1->error_set_jmp_enabled) {
549 longjmp(s1->error_jmp_buf, 1);
550 } else {
551 /* XXX: eliminate this someday */
552 exit(1);
556 PUB_FUNC void tcc_warning(const char *fmt, ...)
558 TCCState *s1 = tcc_state;
559 va_list ap;
561 if (s1->warn_none)
562 return;
564 va_start(ap, fmt);
565 error1(s1, 1, fmt, ap);
566 va_end(ap);
569 /********************************************************/
570 /* I/O layer */
572 ST_FUNC void tcc_open_bf(TCCState *s1, const char *filename, int initlen)
574 BufferedFile *bf;
575 int buflen = initlen ? initlen : IO_BUF_SIZE;
577 bf = tcc_mallocz(sizeof(BufferedFile) + buflen);
578 bf->buf_ptr = bf->buffer;
579 bf->buf_end = bf->buffer + initlen;
580 bf->buf_end[0] = CH_EOB; /* put eob symbol */
581 pstrcpy(bf->filename, sizeof(bf->filename), filename);
582 #ifdef _WIN32
583 normalize_slashes(bf->filename);
584 #endif
585 bf->line_num = 1;
586 bf->ifdef_stack_ptr = s1->ifdef_stack_ptr;
587 bf->fd = -1;
588 bf->prev = file;
589 file = bf;
592 ST_FUNC void tcc_close(void)
594 BufferedFile *bf = file;
595 if (bf->fd > 0) {
596 close(bf->fd);
597 total_lines += bf->line_num;
599 file = bf->prev;
600 tcc_free(bf);
603 ST_FUNC int tcc_open(TCCState *s1, const char *filename)
605 int fd;
606 if (strcmp(filename, "-") == 0)
607 fd = 0, filename = "<stdin>";
608 else
609 fd = open(filename, O_RDONLY | O_BINARY);
610 if ((s1->verbose == 2 && fd >= 0) || s1->verbose == 3)
611 printf("%s %*s%s\n", fd < 0 ? "nf":"->",
612 (int)(s1->include_stack_ptr - s1->include_stack), "", filename);
613 if (fd < 0)
614 return -1;
616 tcc_open_bf(s1, filename, 0);
617 file->fd = fd;
618 return fd;
621 /* compile the C file opened in 'file'. Return non zero if errors. */
622 static int tcc_compile(TCCState *s1)
624 Sym *define_start;
626 preprocess_start(s1);
627 define_start = define_stack;
629 if (setjmp(s1->error_jmp_buf) == 0) {
630 s1->nb_errors = 0;
631 s1->error_set_jmp_enabled = 1;
633 tccgen_start(s1);
634 #ifdef INC_DEBUG
635 printf("%s: **** new file\n", file->filename);
636 #endif
637 ch = file->buf_ptr[0];
638 tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
639 parse_flags = PARSE_FLAG_PREPROCESS | PARSE_FLAG_TOK_NUM | PARSE_FLAG_TOK_STR;
640 next();
641 decl(VT_CONST);
642 if (tok != TOK_EOF)
643 expect("declaration");
644 /* reset define stack, but keep -D and built-ins */
645 free_defines(define_start);
646 tccgen_end(s1);
648 s1->error_set_jmp_enabled = 0;
650 free_inline_functions(s1);
651 sym_pop(&global_stack, NULL, 0);
652 sym_pop(&local_stack, NULL, 0);
653 return s1->nb_errors != 0 ? -1 : 0;
656 LIBTCCAPI int tcc_compile_string(TCCState *s, const char *str)
658 int len, ret;
660 len = strlen(str);
661 tcc_open_bf(s, "<string>", len);
662 memcpy(file->buffer, str, len);
663 ret = tcc_compile(s);
664 tcc_close();
665 return ret;
668 /* define a preprocessor symbol. A value can also be provided with the '=' operator */
669 LIBTCCAPI void tcc_define_symbol(TCCState *s1, const char *sym, const char *value)
671 int len1, len2;
672 /* default value */
673 if (!value)
674 value = "1";
675 len1 = strlen(sym);
676 len2 = strlen(value);
678 /* init file structure */
679 tcc_open_bf(s1, "<define>", len1 + len2 + 1);
680 memcpy(file->buffer, sym, len1);
681 file->buffer[len1] = ' ';
682 memcpy(file->buffer + len1 + 1, value, len2);
684 /* parse with define parser */
685 ch = file->buf_ptr[0];
686 next_nomacro();
687 parse_define();
689 tcc_close();
692 /* undefine a preprocessor symbol */
693 LIBTCCAPI void tcc_undefine_symbol(TCCState *s1, const char *sym)
695 TokenSym *ts;
696 Sym *s;
697 ts = tok_alloc(sym, strlen(sym));
698 s = define_find(ts->tok);
699 /* undefine symbol by putting an invalid name */
700 if (s)
701 define_undef(s);
704 /* cleanup all static data used during compilation */
705 static void tcc_cleanup(void)
707 if (NULL == tcc_state)
708 return;
709 tccpp_delete(tcc_state);
710 tcc_state = NULL;
711 /* free sym_pools */
712 dynarray_reset(&sym_pools, &nb_sym_pools);
713 /* reset symbol stack */
714 sym_free_first = NULL;
717 LIBTCCAPI TCCState *tcc_new(void)
719 TCCState *s;
721 tcc_cleanup();
723 s = tcc_mallocz(sizeof(TCCState));
724 if (!s)
725 return NULL;
726 tcc_state = s;
728 s->alacarte_link = 1;
729 s->nocommon = 1;
730 s->warn_implicit_function_declaration = 1;
732 #ifdef CHAR_IS_UNSIGNED
733 s->char_is_unsigned = 1;
734 #endif
735 #ifdef TCC_TARGET_I386
736 s->seg_size = 32;
737 #endif
738 #ifdef TCC_IS_NATIVE
739 s->runtime_main = "main";
740 #endif
741 /* enable this if you want symbols with leading underscore on windows: */
742 #if 0 /* def TCC_TARGET_PE */
743 s->leading_underscore = 1;
744 #endif
745 #ifdef _WIN32
746 tcc_set_lib_path_w32(s);
747 #else
748 tcc_set_lib_path(s, CONFIG_TCCDIR);
749 #endif
750 tccelf_new(s);
751 tccpp_new(s);
753 /* we add dummy defines for some special macros to speed up tests
754 and to have working defined() */
755 define_push(TOK___LINE__, MACRO_OBJ, NULL, NULL);
756 define_push(TOK___FILE__, MACRO_OBJ, NULL, NULL);
757 define_push(TOK___DATE__, MACRO_OBJ, NULL, NULL);
758 define_push(TOK___TIME__, MACRO_OBJ, NULL, NULL);
760 /* define __TINYC__ 92X */
761 char buffer[32]; int a,b,c;
762 sscanf(TCC_VERSION, "%d.%d.%d", &a, &b, &c);
763 sprintf(buffer, "%d", a*10000 + b*100 + c);
764 tcc_define_symbol(s, "__TINYC__", buffer);
767 /* standard defines */
768 tcc_define_symbol(s, "__STDC__", NULL);
769 tcc_define_symbol(s, "__STDC_VERSION__", "199901L");
770 tcc_define_symbol(s, "__STDC_HOSTED__", NULL);
772 /* target defines */
773 #if defined(TCC_TARGET_I386)
774 tcc_define_symbol(s, "__i386__", NULL);
775 tcc_define_symbol(s, "__i386", NULL);
776 tcc_define_symbol(s, "i386", NULL);
777 #elif defined(TCC_TARGET_X86_64)
778 tcc_define_symbol(s, "__x86_64__", NULL);
779 #elif defined(TCC_TARGET_ARM)
780 tcc_define_symbol(s, "__ARM_ARCH_4__", NULL);
781 tcc_define_symbol(s, "__arm_elf__", NULL);
782 tcc_define_symbol(s, "__arm_elf", NULL);
783 tcc_define_symbol(s, "arm_elf", NULL);
784 tcc_define_symbol(s, "__arm__", NULL);
785 tcc_define_symbol(s, "__arm", NULL);
786 tcc_define_symbol(s, "arm", NULL);
787 tcc_define_symbol(s, "__APCS_32__", NULL);
788 tcc_define_symbol(s, "__ARMEL__", NULL);
789 #if defined(TCC_ARM_EABI)
790 tcc_define_symbol(s, "__ARM_EABI__", NULL);
791 #endif
792 #if defined(TCC_ARM_HARDFLOAT)
793 s->float_abi = ARM_HARD_FLOAT;
794 tcc_define_symbol(s, "__ARM_PCS_VFP", NULL);
795 #else
796 s->float_abi = ARM_SOFTFP_FLOAT;
797 #endif
798 #elif defined(TCC_TARGET_ARM64)
799 tcc_define_symbol(s, "__aarch64__", NULL);
800 #endif
802 #ifdef TCC_TARGET_PE
803 tcc_define_symbol(s, "_WIN32", NULL);
804 # ifdef TCC_TARGET_X86_64
805 tcc_define_symbol(s, "_WIN64", NULL);
806 # endif
807 #else
808 tcc_define_symbol(s, "__unix__", NULL);
809 tcc_define_symbol(s, "__unix", NULL);
810 tcc_define_symbol(s, "unix", NULL);
811 # if defined(__linux__)
812 tcc_define_symbol(s, "__linux__", NULL);
813 tcc_define_symbol(s, "__linux", NULL);
814 # endif
815 # if defined(__FreeBSD__)
816 tcc_define_symbol(s, "__FreeBSD__", "__FreeBSD__");
817 /* No 'Thread Storage Local' on FreeBSD with tcc */
818 tcc_define_symbol(s, "__NO_TLS", NULL);
819 # endif
820 # if defined(__FreeBSD_kernel__)
821 tcc_define_symbol(s, "__FreeBSD_kernel__", NULL);
822 # endif
823 #endif
824 # if defined(__NetBSD__)
825 tcc_define_symbol(s, "__NetBSD__", "__NetBSD__");
826 # endif
827 # if defined(__OpenBSD__)
828 tcc_define_symbol(s, "__OpenBSD__", "__OpenBSD__");
829 # endif
831 /* TinyCC & gcc defines */
832 #if defined(TCC_TARGET_PE) && defined(TCC_TARGET_X86_64)
833 /* 64bit Windows. */
834 tcc_define_symbol(s, "__SIZE_TYPE__", "unsigned long long");
835 tcc_define_symbol(s, "__PTRDIFF_TYPE__", "long long");
836 tcc_define_symbol(s, "__LLP64__", NULL);
837 #elif defined(TCC_TARGET_X86_64) || defined(TCC_TARGET_ARM64)
838 /* Other 64bit systems. */
839 tcc_define_symbol(s, "__SIZE_TYPE__", "unsigned long");
840 tcc_define_symbol(s, "__PTRDIFF_TYPE__", "long");
841 tcc_define_symbol(s, "__LP64__", NULL);
842 #else
843 /* Other 32bit systems. */
844 tcc_define_symbol(s, "__SIZE_TYPE__", "unsigned long");
845 tcc_define_symbol(s, "__PTRDIFF_TYPE__", "long");
846 tcc_define_symbol(s, "__ILP32__", NULL);
847 #endif
849 #ifdef TCC_TARGET_PE
850 tcc_define_symbol(s, "__WCHAR_TYPE__", "unsigned short");
851 tcc_define_symbol(s, "__WINT_TYPE__", "unsigned short");
852 #else
853 tcc_define_symbol(s, "__WCHAR_TYPE__", "int");
854 /* wint_t is unsigned int by default, but (signed) int on BSDs
855 and unsigned short on windows. Other OSes might have still
856 other conventions, sigh. */
857 # if defined(__FreeBSD__) || defined (__FreeBSD_kernel__) \
858 || defined(__NetBSD__) || defined(__OpenBSD__)
859 tcc_define_symbol(s, "__WINT_TYPE__", "int");
860 # ifdef __FreeBSD__
861 /* define __GNUC__ to have some useful stuff from sys/cdefs.h
862 that are unconditionally used in FreeBSDs other system headers :/ */
863 tcc_define_symbol(s, "__GNUC__", "2");
864 tcc_define_symbol(s, "__GNUC_MINOR__", "7");
865 tcc_define_symbol(s, "__builtin_alloca", "alloca");
866 # endif
867 # else
868 tcc_define_symbol(s, "__WINT_TYPE__", "unsigned int");
869 /* glibc defines */
870 tcc_define_symbol(s, "__REDIRECT(name, proto, alias)",
871 "name proto __asm__ (#alias)");
872 tcc_define_symbol(s, "__REDIRECT_NTH(name, proto, alias)",
873 "name proto __asm__ (#alias) __THROW");
874 # endif
875 #endif /* ndef TCC_TARGET_PE */
877 /* Some GCC builtins that are simple to express as macros. */
878 tcc_define_symbol(s, "__builtin_extract_return_addr(x)", "x");
880 return s;
883 LIBTCCAPI void tcc_delete(TCCState *s1)
885 int bench = s1->do_bench;
887 tcc_cleanup();
889 /* free sections */
890 tccelf_delete(s1);
892 /* free library paths */
893 dynarray_reset(&s1->library_paths, &s1->nb_library_paths);
894 dynarray_reset(&s1->crt_paths, &s1->nb_crt_paths);
896 /* free include paths */
897 dynarray_reset(&s1->cached_includes, &s1->nb_cached_includes);
898 dynarray_reset(&s1->include_paths, &s1->nb_include_paths);
899 dynarray_reset(&s1->sysinclude_paths, &s1->nb_sysinclude_paths);
901 tcc_free(s1->tcc_lib_path);
902 tcc_free(s1->soname);
903 tcc_free(s1->rpath);
904 tcc_free(s1->init_symbol);
905 tcc_free(s1->fini_symbol);
906 tcc_free(s1->outfile);
907 tcc_free(s1->deps_outfile);
908 dynarray_reset(&s1->files, &s1->nb_files);
909 dynarray_reset(&s1->target_deps, &s1->nb_target_deps);
910 dynarray_reset(&s1->pragma_libs, &s1->nb_pragma_libs);
912 #ifdef TCC_IS_NATIVE
913 /* free runtime memory */
914 tcc_run_free(s1);
915 #endif
917 tcc_free(s1);
918 tcc_memstats(bench);
921 LIBTCCAPI int tcc_set_output_type(TCCState *s, int output_type)
923 s->output_type = output_type;
925 /* always elf for objects */
926 if (output_type == TCC_OUTPUT_OBJ)
927 s->output_format = TCC_OUTPUT_FORMAT_ELF;
929 if (s->char_is_unsigned)
930 tcc_define_symbol(s, "__CHAR_UNSIGNED__", NULL);
932 if (!s->nostdinc) {
933 /* default include paths */
934 /* -isystem paths have already been handled */
935 tcc_add_sysinclude_path(s, CONFIG_TCC_SYSINCLUDEPATHS);
938 #ifdef CONFIG_TCC_BCHECK
939 if (s->do_bounds_check) {
940 /* if bound checking, then add corresponding sections */
941 tccelf_bounds_new(s);
942 /* define symbol */
943 tcc_define_symbol(s, "__BOUNDS_CHECKING_ON", NULL);
945 #endif
946 if (s->do_debug) {
947 /* add debug sections */
948 tccelf_stab_new(s);
951 tcc_add_library_path(s, CONFIG_TCC_LIBPATHS);
953 #ifdef TCC_TARGET_PE
954 # ifdef _WIN32
955 if (!s->nostdlib && output_type != TCC_OUTPUT_OBJ)
956 tcc_add_systemdir(s);
957 # endif
958 #else
959 /* paths for crt objects */
960 tcc_split_path(s, (void ***)&s->crt_paths, &s->nb_crt_paths, CONFIG_TCC_CRTPREFIX);
961 /* add libc crt1/crti objects */
962 if ((output_type == TCC_OUTPUT_EXE || output_type == TCC_OUTPUT_DLL) &&
963 !s->nostdlib) {
964 if (output_type != TCC_OUTPUT_DLL)
965 tcc_add_crt(s, "crt1.o");
966 tcc_add_crt(s, "crti.o");
968 #endif
969 return 0;
972 LIBTCCAPI int tcc_add_include_path(TCCState *s, const char *pathname)
974 tcc_split_path(s, (void ***)&s->include_paths, &s->nb_include_paths, pathname);
975 return 0;
978 LIBTCCAPI int tcc_add_sysinclude_path(TCCState *s, const char *pathname)
980 tcc_split_path(s, (void ***)&s->sysinclude_paths, &s->nb_sysinclude_paths, pathname);
981 return 0;
984 ST_FUNC int tcc_add_file_internal(TCCState *s1, const char *filename, int flags)
986 int ret, filetype;
988 filetype = flags & 0x0F;
989 if (filetype == 0) {
990 /* use a file extension to detect a filetype */
991 const char *ext = tcc_fileextension(filename);
992 if (ext[0]) {
993 ext++;
994 if (!strcmp(ext, "S"))
995 filetype = AFF_TYPE_ASMPP;
996 else if (!strcmp(ext, "s"))
997 filetype = AFF_TYPE_ASM;
998 else if (!PATHCMP(ext, "c") || !PATHCMP(ext, "i"))
999 filetype = AFF_TYPE_C;
1000 else
1001 filetype = AFF_TYPE_BIN;
1002 } else {
1003 filetype = AFF_TYPE_C;
1007 /* open the file */
1008 ret = tcc_open(s1, filename);
1009 if (ret < 0) {
1010 if (flags & AFF_PRINT_ERROR)
1011 tcc_error_noabort("file '%s' not found", filename);
1012 return ret;
1015 /* update target deps */
1016 dynarray_add((void ***)&s1->target_deps, &s1->nb_target_deps,
1017 tcc_strdup(filename));
1019 parse_flags = 0;
1020 /* if .S file, define __ASSEMBLER__ like gcc does */
1021 if (filetype == AFF_TYPE_ASM || filetype == AFF_TYPE_ASMPP) {
1022 tcc_define_symbol(s1, "__ASSEMBLER__", NULL);
1023 parse_flags = PARSE_FLAG_ASM_FILE;
1026 if (flags & AFF_PREPROCESS) {
1027 ret = tcc_preprocess(s1);
1028 } else if (filetype == AFF_TYPE_C) {
1029 ret = tcc_compile(s1);
1030 #ifdef CONFIG_TCC_ASM
1031 } else if (filetype == AFF_TYPE_ASMPP) {
1032 /* non preprocessed assembler */
1033 ret = tcc_assemble(s1, 1);
1034 } else if (filetype == AFF_TYPE_ASM) {
1035 /* preprocessed assembler */
1036 ret = tcc_assemble(s1, 0);
1037 #endif
1038 } else {
1039 ElfW(Ehdr) ehdr;
1040 int fd, obj_type;
1042 fd = file->fd;
1043 obj_type = tcc_object_type(fd, &ehdr);
1044 lseek(fd, 0, SEEK_SET);
1046 /* do not display line number if error */
1047 file->line_num = 0;
1049 switch (obj_type) {
1050 case AFF_BINTYPE_REL:
1051 ret = tcc_load_object_file(s1, fd, 0);
1052 break;
1053 #ifndef TCC_TARGET_PE
1054 case AFF_BINTYPE_DYN:
1055 if (s1->output_type == TCC_OUTPUT_MEMORY) {
1056 ret = 0;
1057 #ifdef TCC_IS_NATIVE
1058 if (NULL == dlopen(filename, RTLD_GLOBAL | RTLD_LAZY))
1059 ret = -1;
1060 #endif
1061 } else {
1062 ret = tcc_load_dll(s1, fd, filename,
1063 (flags & AFF_REFERENCED_DLL) != 0);
1065 break;
1066 #endif
1067 case AFF_BINTYPE_AR:
1068 ret = tcc_load_archive(s1, fd);
1069 break;
1070 #ifdef TCC_TARGET_COFF
1071 case AFF_BINTYPE_C67:
1072 ret = tcc_load_coff(s1, fd);
1073 break;
1074 #endif
1075 default:
1076 #ifdef TCC_TARGET_PE
1077 ret = pe_load_file(s1, filename, fd);
1078 #else
1079 /* as GNU ld, consider it is an ld script if not recognized */
1080 ret = tcc_load_ldscript(s1);
1081 #endif
1082 if (ret < 0)
1083 tcc_error_noabort("unrecognized file type");
1084 break;
1087 tcc_close();
1088 return ret;
1091 LIBTCCAPI int tcc_add_file(TCCState *s, const char *filename)
1093 if (s->output_type == TCC_OUTPUT_PREPROCESS)
1094 return tcc_add_file_internal(s, filename, AFF_PRINT_ERROR | AFF_PREPROCESS | s->filetype);
1095 else
1096 return tcc_add_file_internal(s, filename, AFF_PRINT_ERROR | s->filetype);
1099 LIBTCCAPI int tcc_add_library_path(TCCState *s, const char *pathname)
1101 tcc_split_path(s, (void ***)&s->library_paths, &s->nb_library_paths, pathname);
1102 return 0;
1105 static int tcc_add_library_internal(TCCState *s, const char *fmt,
1106 const char *filename, int flags, char **paths, int nb_paths)
1108 char buf[1024];
1109 int i;
1111 for(i = 0; i < nb_paths; i++) {
1112 snprintf(buf, sizeof(buf), fmt, paths[i], filename);
1113 if (tcc_add_file_internal(s, buf, flags | AFF_TYPE_BIN) == 0)
1114 return 0;
1116 return -1;
1119 #ifndef TCC_TARGET_PE
1120 /* find and load a dll. Return non zero if not found */
1121 /* XXX: add '-rpath' option support ? */
1122 ST_FUNC int tcc_add_dll(TCCState *s, const char *filename, int flags)
1124 return tcc_add_library_internal(s, "%s/%s", filename, flags,
1125 s->library_paths, s->nb_library_paths);
1127 #endif
1129 ST_FUNC int tcc_add_crt(TCCState *s, const char *filename)
1131 if (-1 == tcc_add_library_internal(s, "%s/%s",
1132 filename, 0, s->crt_paths, s->nb_crt_paths))
1133 tcc_error_noabort("file '%s' not found", filename);
1134 return 0;
1137 /* the library name is the same as the argument of the '-l' option */
1138 LIBTCCAPI int tcc_add_library(TCCState *s, const char *libraryname)
1140 #ifdef TCC_TARGET_PE
1141 const char *libs[] = { "%s/%s.def", "%s/lib%s.def", "%s/%s.dll", "%s/lib%s.dll", "%s/lib%s.a", NULL };
1142 const char **pp = s->static_link ? libs + 4 : libs;
1143 #else
1144 const char *libs[] = { "%s/lib%s.so", "%s/lib%s.a", NULL };
1145 const char **pp = s->static_link ? libs + 1 : libs;
1146 #endif
1147 while (*pp) {
1148 if (0 == tcc_add_library_internal(s, *pp,
1149 libraryname, 0, s->library_paths, s->nb_library_paths))
1150 return 0;
1151 ++pp;
1153 return -1;
1156 PUB_FUNC int tcc_add_library_err(TCCState *s, const char *libname)
1158 int ret = tcc_add_library(s, libname);
1159 if (ret < 0)
1160 tcc_error_noabort("library 'lib%s' not found", libname);
1161 return ret;
1164 /* habdle #pragma comment(lib,) */
1165 ST_FUNC void tcc_add_pragma_libs(TCCState *s1)
1167 int i;
1168 for (i = 0; i < s1->nb_pragma_libs; i++)
1169 tcc_add_library_err(s1, s1->pragma_libs[i]);
1172 LIBTCCAPI int tcc_add_symbol(TCCState *s, const char *name, const void *val)
1174 #ifdef TCC_TARGET_PE
1175 /* On x86_64 'val' might not be reachable with a 32bit offset.
1176 So it is handled here as if it were in a DLL. */
1177 pe_putimport(s, 0, name, (uintptr_t)val);
1178 #else
1179 set_elf_sym(symtab_section, (uintptr_t)val, 0,
1180 ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE), 0,
1181 SHN_ABS, name);
1182 #endif
1183 return 0;
1186 LIBTCCAPI void tcc_set_lib_path(TCCState *s, const char *path)
1188 tcc_free(s->tcc_lib_path);
1189 s->tcc_lib_path = tcc_strdup(path);
1192 #define WD_ALL 0x0001 /* warning is activated when using -Wall */
1193 #define FD_INVERT 0x0002 /* invert value before storing */
1195 typedef struct FlagDef {
1196 uint16_t offset;
1197 uint16_t flags;
1198 const char *name;
1199 } FlagDef;
1201 static int no_flag(const char **pp)
1203 const char *p = *pp;
1204 if (*p != 'n' || *++p != 'o' || *++p != '-')
1205 return 0;
1206 *pp = p + 1;
1207 return 1;
1210 ST_FUNC int set_flag(TCCState *s, const FlagDef *flags, const char *name)
1212 int value, ret;
1213 const FlagDef *p;
1214 const char *r;
1216 value = 1;
1217 r = name;
1218 if (no_flag(&r))
1219 value = 0;
1221 for (ret = -1, p = flags; p->name; ++p) {
1222 if (ret) {
1223 if (strcmp(r, p->name))
1224 continue;
1225 } else {
1226 if (0 == (p->flags & WD_ALL))
1227 continue;
1229 if (p->offset) {
1230 *(int*)((char *)s + p->offset) =
1231 p->flags & FD_INVERT ? !value : value;
1232 if (ret)
1233 return 0;
1234 } else {
1235 ret = 0;
1238 return ret;
1241 static int strstart(const char *val, const char **str)
1243 const char *p, *q;
1244 p = *str;
1245 q = val;
1246 while (*q) {
1247 if (*p != *q)
1248 return 0;
1249 p++;
1250 q++;
1252 *str = p;
1253 return 1;
1256 /* Like strstart, but automatically takes into account that ld options can
1258 * - start with double or single dash (e.g. '--soname' or '-soname')
1259 * - arguments can be given as separate or after '=' (e.g. '-Wl,-soname,x.so'
1260 * or '-Wl,-soname=x.so')
1262 * you provide `val` always in 'option[=]' form (no leading -)
1264 static int link_option(const char *str, const char *val, const char **ptr)
1266 const char *p, *q;
1267 int ret;
1269 /* there should be 1 or 2 dashes */
1270 if (*str++ != '-')
1271 return 0;
1272 if (*str == '-')
1273 str++;
1275 /* then str & val should match (potentialy up to '=') */
1276 p = str;
1277 q = val;
1279 ret = 1;
1280 if (q[0] == '?') {
1281 ++q;
1282 if (no_flag(&p))
1283 ret = -1;
1286 while (*q != '\0' && *q != '=') {
1287 if (*p != *q)
1288 return 0;
1289 p++;
1290 q++;
1293 /* '=' near eos means ',' or '=' is ok */
1294 if (*q == '=') {
1295 if (*p == 0)
1296 *ptr = p;
1297 if (*p != ',' && *p != '=')
1298 return 0;
1299 p++;
1301 *ptr = p;
1302 return ret;
1305 static const char *skip_linker_arg(const char **str)
1307 const char *s1 = *str;
1308 const char *s2 = strchr(s1, ',');
1309 *str = s2 ? s2++ : (s2 = s1 + strlen(s1));
1310 return s2;
1313 static char *copy_linker_arg(const char *p)
1315 const char *q = p;
1316 skip_linker_arg(&q);
1317 return pstrncpy(tcc_malloc(q - p + 1), p, q - p);
1320 /* set linker options */
1321 static int tcc_set_linker(TCCState *s, const char *option)
1323 while (*option) {
1325 const char *p = NULL;
1326 char *end = NULL;
1327 int ignoring = 0;
1328 int ret;
1330 if (link_option(option, "Bsymbolic", &p)) {
1331 s->symbolic = 1;
1332 } else if (link_option(option, "nostdlib", &p)) {
1333 s->nostdlib = 1;
1334 } else if (link_option(option, "fini=", &p)) {
1335 s->fini_symbol = copy_linker_arg(p);
1336 ignoring = 1;
1337 } else if (link_option(option, "image-base=", &p)
1338 || link_option(option, "Ttext=", &p)) {
1339 s->text_addr = strtoull(p, &end, 16);
1340 s->has_text_addr = 1;
1341 } else if (link_option(option, "init=", &p)) {
1342 s->init_symbol = copy_linker_arg(p);
1343 ignoring = 1;
1344 } else if (link_option(option, "oformat=", &p)) {
1345 #if defined(TCC_TARGET_PE)
1346 if (strstart("pe-", &p)) {
1347 #elif defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
1348 if (strstart("elf64-", &p)) {
1349 #else
1350 if (strstart("elf32-", &p)) {
1351 #endif
1352 s->output_format = TCC_OUTPUT_FORMAT_ELF;
1353 } else if (!strcmp(p, "binary")) {
1354 s->output_format = TCC_OUTPUT_FORMAT_BINARY;
1355 #ifdef TCC_TARGET_COFF
1356 } else if (!strcmp(p, "coff")) {
1357 s->output_format = TCC_OUTPUT_FORMAT_COFF;
1358 #endif
1359 } else
1360 goto err;
1362 } else if (link_option(option, "as-needed", &p)) {
1363 ignoring = 1;
1364 } else if (link_option(option, "O", &p)) {
1365 ignoring = 1;
1366 } else if (link_option(option, "rpath=", &p)) {
1367 s->rpath = copy_linker_arg(p);
1368 } else if (link_option(option, "section-alignment=", &p)) {
1369 s->section_align = strtoul(p, &end, 16);
1370 } else if (link_option(option, "soname=", &p)) {
1371 s->soname = copy_linker_arg(p);
1372 #ifdef TCC_TARGET_PE
1373 } else if (link_option(option, "large-address-aware", &p)) {
1374 s->pe_characteristics |= 0x20;
1375 } else if (link_option(option, "file-alignment=", &p)) {
1376 s->pe_file_align = strtoul(p, &end, 16);
1377 } else if (link_option(option, "stack=", &p)) {
1378 s->pe_stack_size = strtoul(p, &end, 10);
1379 } else if (link_option(option, "subsystem=", &p)) {
1380 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
1381 if (!strcmp(p, "native")) {
1382 s->pe_subsystem = 1;
1383 } else if (!strcmp(p, "console")) {
1384 s->pe_subsystem = 3;
1385 } else if (!strcmp(p, "gui")) {
1386 s->pe_subsystem = 2;
1387 } else if (!strcmp(p, "posix")) {
1388 s->pe_subsystem = 7;
1389 } else if (!strcmp(p, "efiapp")) {
1390 s->pe_subsystem = 10;
1391 } else if (!strcmp(p, "efiboot")) {
1392 s->pe_subsystem = 11;
1393 } else if (!strcmp(p, "efiruntime")) {
1394 s->pe_subsystem = 12;
1395 } else if (!strcmp(p, "efirom")) {
1396 s->pe_subsystem = 13;
1397 #elif defined(TCC_TARGET_ARM)
1398 if (!strcmp(p, "wince")) {
1399 s->pe_subsystem = 9;
1400 #endif
1401 } else
1402 goto err;
1403 #endif
1404 } else if (ret = link_option(option, "?whole-archive", &p), ret) {
1405 s->alacarte_link = ret < 0;
1406 } else if (p) {
1407 return 0;
1408 } else {
1409 err:
1410 tcc_error("unsupported linker option '%s'", option);
1413 if (ignoring && s->warn_unsupported)
1414 tcc_warning("unsupported linker option '%s'", option);
1416 option = skip_linker_arg(&p);
1418 return 1;
1421 typedef struct TCCOption {
1422 const char *name;
1423 uint16_t index;
1424 uint16_t flags;
1425 } TCCOption;
1427 enum {
1428 TCC_OPTION_HELP,
1429 TCC_OPTION_I,
1430 TCC_OPTION_D,
1431 TCC_OPTION_U,
1432 TCC_OPTION_P,
1433 TCC_OPTION_L,
1434 TCC_OPTION_B,
1435 TCC_OPTION_l,
1436 TCC_OPTION_bench,
1437 TCC_OPTION_bt,
1438 TCC_OPTION_b,
1439 TCC_OPTION_g,
1440 TCC_OPTION_c,
1441 TCC_OPTION_dumpversion,
1442 TCC_OPTION_d,
1443 TCC_OPTION_static,
1444 TCC_OPTION_std,
1445 TCC_OPTION_shared,
1446 TCC_OPTION_soname,
1447 TCC_OPTION_o,
1448 TCC_OPTION_r,
1449 TCC_OPTION_s,
1450 TCC_OPTION_traditional,
1451 TCC_OPTION_Wl,
1452 TCC_OPTION_Wp,
1453 TCC_OPTION_W,
1454 TCC_OPTION_O,
1455 TCC_OPTION_mfloat_abi,
1456 TCC_OPTION_m,
1457 TCC_OPTION_f,
1458 TCC_OPTION_isystem,
1459 TCC_OPTION_iwithprefix,
1460 TCC_OPTION_include,
1461 TCC_OPTION_nostdinc,
1462 TCC_OPTION_nostdlib,
1463 TCC_OPTION_print_search_dirs,
1464 TCC_OPTION_rdynamic,
1465 TCC_OPTION_param,
1466 TCC_OPTION_pedantic,
1467 TCC_OPTION_pthread,
1468 TCC_OPTION_run,
1469 TCC_OPTION_v,
1470 TCC_OPTION_w,
1471 TCC_OPTION_pipe,
1472 TCC_OPTION_E,
1473 TCC_OPTION_MD,
1474 TCC_OPTION_MF,
1475 TCC_OPTION_x
1478 #define TCC_OPTION_HAS_ARG 0x0001
1479 #define TCC_OPTION_NOSEP 0x0002 /* cannot have space before option and arg */
1481 static const TCCOption tcc_options[] = {
1482 { "h", TCC_OPTION_HELP, 0 },
1483 { "-help", TCC_OPTION_HELP, 0 },
1484 { "?", TCC_OPTION_HELP, 0 },
1485 { "I", TCC_OPTION_I, TCC_OPTION_HAS_ARG },
1486 { "D", TCC_OPTION_D, TCC_OPTION_HAS_ARG },
1487 { "U", TCC_OPTION_U, TCC_OPTION_HAS_ARG },
1488 { "P", TCC_OPTION_P, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1489 { "L", TCC_OPTION_L, TCC_OPTION_HAS_ARG },
1490 { "B", TCC_OPTION_B, TCC_OPTION_HAS_ARG },
1491 { "l", TCC_OPTION_l, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1492 { "bench", TCC_OPTION_bench, 0 },
1493 #ifdef CONFIG_TCC_BACKTRACE
1494 { "bt", TCC_OPTION_bt, TCC_OPTION_HAS_ARG },
1495 #endif
1496 #ifdef CONFIG_TCC_BCHECK
1497 { "b", TCC_OPTION_b, 0 },
1498 #endif
1499 { "g", TCC_OPTION_g, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1500 { "c", TCC_OPTION_c, 0 },
1501 { "dumpversion", TCC_OPTION_dumpversion, 0},
1502 { "d", TCC_OPTION_d, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1503 { "static", TCC_OPTION_static, 0 },
1504 { "std", TCC_OPTION_std, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1505 { "shared", TCC_OPTION_shared, 0 },
1506 { "soname", TCC_OPTION_soname, TCC_OPTION_HAS_ARG },
1507 { "o", TCC_OPTION_o, TCC_OPTION_HAS_ARG },
1508 { "-param", TCC_OPTION_param, TCC_OPTION_HAS_ARG },
1509 { "pedantic", TCC_OPTION_pedantic, 0},
1510 { "pthread", TCC_OPTION_pthread, 0},
1511 { "run", TCC_OPTION_run, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1512 { "rdynamic", TCC_OPTION_rdynamic, 0 },
1513 { "r", TCC_OPTION_r, 0 },
1514 { "s", TCC_OPTION_s, 0 },
1515 { "traditional", TCC_OPTION_traditional, 0 },
1516 { "Wl,", TCC_OPTION_Wl, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1517 { "Wp,", TCC_OPTION_Wp, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1518 { "W", TCC_OPTION_W, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1519 { "O", TCC_OPTION_O, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1520 #ifdef TCC_TARGET_ARM
1521 { "mfloat-abi", TCC_OPTION_mfloat_abi, TCC_OPTION_HAS_ARG },
1522 #endif
1523 { "m", TCC_OPTION_m, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1524 { "f", TCC_OPTION_f, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1525 { "isystem", TCC_OPTION_isystem, TCC_OPTION_HAS_ARG },
1526 { "iwithprefix", TCC_OPTION_iwithprefix, TCC_OPTION_HAS_ARG },
1527 { "include", TCC_OPTION_include, TCC_OPTION_HAS_ARG },
1528 { "nostdinc", TCC_OPTION_nostdinc, 0 },
1529 { "nostdlib", TCC_OPTION_nostdlib, 0 },
1530 { "print-search-dirs", TCC_OPTION_print_search_dirs, 0 },
1531 { "v", TCC_OPTION_v, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
1532 { "w", TCC_OPTION_w, 0 },
1533 { "pipe", TCC_OPTION_pipe, 0},
1534 { "E", TCC_OPTION_E, 0},
1535 { "MD", TCC_OPTION_MD, 0},
1536 { "MF", TCC_OPTION_MF, TCC_OPTION_HAS_ARG },
1537 { "x", TCC_OPTION_x, TCC_OPTION_HAS_ARG },
1538 { NULL, 0, 0 },
1541 static const FlagDef options_W[] = {
1542 { 0, 0, "all" },
1543 { offsetof(TCCState, warn_unsupported), 0, "unsupported" },
1544 { offsetof(TCCState, warn_write_strings), 0, "write-strings" },
1545 { offsetof(TCCState, warn_error), 0, "error" },
1546 { offsetof(TCCState, warn_implicit_function_declaration), WD_ALL,
1547 "implicit-function-declaration" },
1548 { 0, 0, NULL }
1551 static const FlagDef options_f[] = {
1552 { offsetof(TCCState, char_is_unsigned), 0, "unsigned-char" },
1553 { offsetof(TCCState, char_is_unsigned), FD_INVERT, "signed-char" },
1554 { offsetof(TCCState, nocommon), FD_INVERT, "common" },
1555 { offsetof(TCCState, leading_underscore), 0, "leading-underscore" },
1556 { offsetof(TCCState, ms_extensions), 0, "ms-extensions" },
1557 { offsetof(TCCState, old_struct_init_code), 0, "old-struct-init-code" },
1558 { offsetof(TCCState, dollars_in_identifiers), 0, "dollars-in-identifiers" },
1559 { 0, 0, NULL }
1562 static const FlagDef options_m[] = {
1563 { offsetof(TCCState, ms_bitfields), 0, "ms-bitfields" },
1564 #ifdef TCC_TARGET_X86_64
1565 { offsetof(TCCState, nosse), FD_INVERT, "sse" },
1566 #endif
1567 { 0, 0, NULL }
1570 static void parse_option_D(TCCState *s1, const char *optarg)
1572 char *sym = tcc_strdup(optarg);
1573 char *value = strchr(sym, '=');
1574 if (value)
1575 *value++ = '\0';
1576 tcc_define_symbol(s1, sym, value);
1577 tcc_free(sym);
1580 static void args_parser_add_file(TCCState *s, const char* filename, int filetype)
1582 struct filespec *f = tcc_malloc(sizeof *f + strlen(filename));
1583 f->type = filetype;
1584 strcpy(f->name, filename);
1585 dynarray_add((void ***)&s->files, &s->nb_files, f);
1588 /* read list file */
1589 static void args_parser_listfile(TCCState *s, const char *filename)
1591 int fd;
1592 size_t len;
1593 char *p;
1595 fd = open(filename, O_RDONLY | O_BINARY);
1596 if (fd < 0)
1597 tcc_error("file '%s' not found", filename);
1599 len = lseek(fd, 0, SEEK_END);
1600 p = tcc_malloc(len + 1), p[len] = 0;
1601 lseek(fd, 0, SEEK_SET), read(fd, p, len), close(fd);
1602 tcc_set_options(s, p);
1603 tcc_free(p);
1606 PUB_FUNC int tcc_parse_args(TCCState *s, int argc, char **argv)
1608 const TCCOption *popt;
1609 const char *optarg, *r;
1610 int optind = 0;
1611 int run = 0;
1612 int x;
1613 int last_o = -1;
1614 CString linker_arg; /* collect -Wl options */
1615 char buf[1024];
1617 cstr_new(&linker_arg);
1619 while (optind < argc) {
1621 r = argv[optind++];
1623 reparse:
1624 if (r[0] == '@' && r[1] != '\0') {
1625 args_parser_listfile(s, r + 1);
1626 continue;
1629 if (r[0] != '-' || r[1] == '\0') {
1630 args_parser_add_file(s, r, s->filetype);
1631 if (run) {
1632 optind--;
1633 /* argv[0] will be this file */
1634 break;
1636 continue;
1639 /* find option in table */
1640 for(popt = tcc_options; ; ++popt) {
1641 const char *p1 = popt->name;
1642 const char *r1 = r + 1;
1643 if (p1 == NULL)
1644 tcc_error("invalid option -- '%s'", r);
1645 if (!strstart(p1, &r1))
1646 continue;
1647 optarg = r1;
1648 if (popt->flags & TCC_OPTION_HAS_ARG) {
1649 if (*r1 == '\0' && !(popt->flags & TCC_OPTION_NOSEP)) {
1650 if (optind >= argc)
1651 arg_err:
1652 tcc_error("argument to '%s' is missing", r);
1653 optarg = argv[optind++];
1655 } else if (*r1 != '\0')
1656 continue;
1657 break;
1660 switch(popt->index) {
1661 case TCC_OPTION_HELP:
1662 return 0;
1663 case TCC_OPTION_I:
1664 tcc_add_include_path(s, optarg);
1665 break;
1666 case TCC_OPTION_D:
1667 parse_option_D(s, optarg);
1668 break;
1669 case TCC_OPTION_U:
1670 tcc_undefine_symbol(s, optarg);
1671 break;
1672 case TCC_OPTION_L:
1673 tcc_add_library_path(s, optarg);
1674 break;
1675 case TCC_OPTION_B:
1676 /* set tcc utilities path (mainly for tcc development) */
1677 tcc_set_lib_path(s, optarg);
1678 break;
1679 case TCC_OPTION_l:
1680 args_parser_add_file(s, optarg, AFF_TYPE_LIBWH - s->alacarte_link);
1681 s->nb_libraries++;
1682 break;
1683 case TCC_OPTION_pthread:
1684 parse_option_D(s, "_REENTRANT");
1685 s->option_pthread = 1;
1686 break;
1687 case TCC_OPTION_bench:
1688 s->do_bench = 1;
1689 break;
1690 #ifdef CONFIG_TCC_BACKTRACE
1691 case TCC_OPTION_bt:
1692 tcc_set_num_callers(atoi(optarg));
1693 break;
1694 #endif
1695 #ifdef CONFIG_TCC_BCHECK
1696 case TCC_OPTION_b:
1697 s->do_bounds_check = 1;
1698 s->do_debug = 1;
1699 break;
1700 #endif
1701 case TCC_OPTION_g:
1702 s->do_debug = 1;
1703 break;
1704 case TCC_OPTION_c:
1705 x = TCC_OUTPUT_OBJ;
1706 set_output_type:
1707 if (s->output_type)
1708 tcc_warning("-%s: overriding compiler action already specified", popt->name);
1709 s->output_type = x;
1710 break;
1711 case TCC_OPTION_d:
1712 if (*optarg == 'D')
1713 s->dflag = 3;
1714 else if (*optarg == 'M')
1715 s->dflag = 7;
1716 else
1717 goto unsupported_option;
1718 break;
1719 case TCC_OPTION_static:
1720 s->static_link = 1;
1721 break;
1722 case TCC_OPTION_std:
1723 /* silently ignore, a current purpose:
1724 allow to use a tcc as a reference compiler for "make test" */
1725 break;
1726 case TCC_OPTION_shared:
1727 x = TCC_OUTPUT_DLL;
1728 goto set_output_type;
1729 case TCC_OPTION_soname:
1730 s->soname = tcc_strdup(optarg);
1731 break;
1732 case TCC_OPTION_o:
1733 if (s->outfile) {
1734 tcc_warning("multiple -o option");
1735 tcc_free(s->outfile);
1737 s->outfile = tcc_strdup(optarg);
1738 break;
1739 case TCC_OPTION_r:
1740 /* generate a .o merging several output files */
1741 s->option_r = 1;
1742 x = TCC_OUTPUT_OBJ;
1743 goto set_output_type;
1744 case TCC_OPTION_isystem:
1745 tcc_add_sysinclude_path(s, optarg);
1746 break;
1747 case TCC_OPTION_iwithprefix:
1748 snprintf(buf, sizeof buf, "{B}/%s", optarg);
1749 tcc_add_sysinclude_path(s, buf);
1750 break;
1751 case TCC_OPTION_include:
1752 dynarray_add((void ***)&s->cmd_include_files,
1753 &s->nb_cmd_include_files, tcc_strdup(optarg));
1754 break;
1755 case TCC_OPTION_nostdinc:
1756 s->nostdinc = 1;
1757 break;
1758 case TCC_OPTION_nostdlib:
1759 s->nostdlib = 1;
1760 break;
1761 case TCC_OPTION_print_search_dirs:
1762 s->print_search_dirs = 1;
1763 break;
1764 case TCC_OPTION_run:
1765 #ifndef TCC_IS_NATIVE
1766 tcc_error("-run is not available in a cross compiler");
1767 #endif
1768 tcc_set_options(s, optarg);
1769 run = 1;
1770 x = TCC_OUTPUT_MEMORY;
1771 goto set_output_type;
1772 case TCC_OPTION_v:
1773 do ++s->verbose; while (*optarg++ == 'v');
1774 break;
1775 case TCC_OPTION_f:
1776 if (set_flag(s, options_f, optarg) < 0)
1777 goto unsupported_option;
1778 break;
1779 #ifdef TCC_TARGET_ARM
1780 case TCC_OPTION_mfloat_abi:
1781 /* tcc doesn't support soft float yet */
1782 if (!strcmp(optarg, "softfp")) {
1783 s->float_abi = ARM_SOFTFP_FLOAT;
1784 tcc_undefine_symbol(s, "__ARM_PCS_VFP");
1785 } else if (!strcmp(optarg, "hard"))
1786 s->float_abi = ARM_HARD_FLOAT;
1787 else
1788 tcc_error("unsupported float abi '%s'", optarg);
1789 break;
1790 #endif
1791 case TCC_OPTION_m:
1792 if (set_flag(s, options_m, optarg) == 0)
1793 break;
1794 else if (x = atoi(optarg), x == 32 || x == 64)
1795 s->cross_target = x;
1796 else
1797 goto unsupported_option;
1798 break;
1799 case TCC_OPTION_W:
1800 if (set_flag(s, options_W, optarg) < 0)
1801 goto unsupported_option;
1802 break;
1803 case TCC_OPTION_w:
1804 s->warn_none = 1;
1805 break;
1806 case TCC_OPTION_rdynamic:
1807 s->rdynamic = 1;
1808 break;
1809 case TCC_OPTION_Wl:
1810 if (linker_arg.size)
1811 --linker_arg.size, cstr_ccat(&linker_arg, ',');
1812 cstr_cat(&linker_arg, optarg, 0);
1813 if (tcc_set_linker(s, linker_arg.data))
1814 cstr_free(&linker_arg);
1815 break;
1816 case TCC_OPTION_Wp:
1817 r = optarg;
1818 goto reparse;
1819 case TCC_OPTION_E:
1820 x = TCC_OUTPUT_PREPROCESS;
1821 goto set_output_type;
1822 case TCC_OPTION_P:
1823 s->Pflag = atoi(optarg) + 1;
1824 break;
1825 case TCC_OPTION_MD:
1826 s->gen_deps = 1;
1827 break;
1828 case TCC_OPTION_MF:
1829 s->deps_outfile = tcc_strdup(optarg);
1830 break;
1831 case TCC_OPTION_dumpversion:
1832 printf ("%s\n", TCC_VERSION);
1833 exit(0);
1834 break;
1835 case TCC_OPTION_x:
1836 if (*optarg == 'c')
1837 s->filetype = AFF_TYPE_C;
1838 else if (*optarg == 'a')
1839 s->filetype = AFF_TYPE_ASMPP;
1840 else if (*optarg == 'n')
1841 s->filetype = AFF_TYPE_NONE;
1842 else
1843 tcc_warning("unsupported language '%s'", optarg);
1844 break;
1845 case TCC_OPTION_O:
1846 last_o = atoi(optarg);
1847 break;
1848 case TCC_OPTION_traditional:
1849 case TCC_OPTION_pedantic:
1850 case TCC_OPTION_pipe:
1851 case TCC_OPTION_s:
1852 /* ignored */
1853 break;
1854 default:
1855 unsupported_option:
1856 if (s->warn_unsupported)
1857 tcc_warning("unsupported option '%s'", r);
1858 break;
1862 if (last_o > 0)
1863 tcc_define_symbol(s, "__OPTIMIZE__", NULL);
1865 if (linker_arg.size) {
1866 r = linker_arg.data;
1867 goto arg_err;
1870 return optind;
1873 LIBTCCAPI int tcc_set_options(TCCState *s, const char *r)
1875 char **argv;
1876 int argc;
1877 int ret, q, c;
1878 CString str;
1880 argc = 0, argv = NULL;
1881 for(;;) {
1882 while (c = (unsigned char)*r, c && c <= ' ')
1883 ++r;
1884 if (c == 0)
1885 break;
1886 q = 0;
1887 cstr_new(&str);
1888 while (c = (unsigned char)*r, c) {
1889 ++r;
1890 if (c == '\\' && (*r == '"' || *r == '\\')) {
1891 c = *r++;
1892 } else if (c == '"') {
1893 q = !q;
1894 continue;
1895 } else if (q == 0 && c <= ' ') {
1896 break;
1898 cstr_ccat(&str, c);
1900 cstr_ccat(&str, 0);
1901 //printf("<%s>\n", str.data), fflush(stdout);
1902 dynarray_add((void ***)&argv, &argc, tcc_strdup(str.data));
1903 cstr_free(&str);
1905 ret = tcc_parse_args(s, argc, argv);
1906 dynarray_reset(&argv, &argc);
1907 return ret;
1910 PUB_FUNC void tcc_print_stats(TCCState *s, unsigned total_time)
1912 if (total_time < 1)
1913 total_time = 1;
1914 if (total_bytes < 1)
1915 total_bytes = 1;
1916 fprintf(stderr, "%d idents, %d lines, %d bytes, %0.3f s, %u lines/s, %0.1f MB/s\n",
1917 tok_ident - TOK_IDENT, total_lines, total_bytes,
1918 (double)total_time/1000,
1919 (unsigned)total_lines*1000/total_time,
1920 (double)total_bytes/1000/total_time);
1923 PUB_FUNC void tcc_set_environment(TCCState *s)
1925 char * path;
1927 path = getenv("C_INCLUDE_PATH");
1928 if(path != NULL) {
1929 tcc_add_include_path(s, path);
1931 path = getenv("CPATH");
1932 if(path != NULL) {
1933 tcc_add_include_path(s, path);
1935 path = getenv("LIBRARY_PATH");
1936 if(path != NULL) {
1937 tcc_add_library_path(s, path);