Update ChangeLog
[tinycc.git] / libtcc.c
blobbbaf17f97da17cec29c9d3304becdd40380543ba
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_memcheck(void)
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_memcheck(void)
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
398 #endif /* MEM_DEBUG */
400 #define free(p) use_tcc_free(p)
401 #define malloc(s) use_tcc_malloc(s)
402 #define realloc(p, s) use_tcc_realloc(p, s)
404 /********************************************************/
405 /* dynarrays */
407 ST_FUNC void dynarray_add(void *ptab, int *nb_ptr, void *data)
409 int nb, nb_alloc;
410 void **pp;
412 nb = *nb_ptr;
413 pp = *(void ***)ptab;
414 /* every power of two we double array size */
415 if ((nb & (nb - 1)) == 0) {
416 if (!nb)
417 nb_alloc = 1;
418 else
419 nb_alloc = nb * 2;
420 pp = tcc_realloc(pp, nb_alloc * sizeof(void *));
421 *(void***)ptab = pp;
423 pp[nb++] = data;
424 *nb_ptr = nb;
427 ST_FUNC void dynarray_reset(void *pp, int *n)
429 void **p;
430 for (p = *(void***)pp; *n; ++p, --*n)
431 if (*p)
432 tcc_free(*p);
433 tcc_free(*(void**)pp);
434 *(void**)pp = NULL;
437 static void tcc_split_path(TCCState *s, void *p_ary, int *p_nb_ary, const char *in)
439 const char *p;
440 do {
441 int c;
442 CString str;
444 cstr_new(&str);
445 for (p = in; c = *p, c != '\0' && c != PATHSEP; ++p) {
446 if (c == '{' && p[1] && p[2] == '}') {
447 c = p[1], p += 2;
448 if (c == 'B')
449 cstr_cat(&str, s->tcc_lib_path, -1);
450 } else {
451 cstr_ccat(&str, c);
454 if (str.size) {
455 cstr_ccat(&str, '\0');
456 dynarray_add(p_ary, p_nb_ary, tcc_strdup(str.data));
458 cstr_free(&str);
459 in = p+1;
460 } while (*p);
463 /********************************************************/
465 static void strcat_vprintf(char *buf, int buf_size, const char *fmt, va_list ap)
467 int len;
468 len = strlen(buf);
469 vsnprintf(buf + len, buf_size - len, fmt, ap);
472 static void strcat_printf(char *buf, int buf_size, const char *fmt, ...)
474 va_list ap;
475 va_start(ap, fmt);
476 strcat_vprintf(buf, buf_size, fmt, ap);
477 va_end(ap);
480 static void error1(TCCState *s1, int is_warning, const char *fmt, va_list ap)
482 char buf[2048];
483 BufferedFile **pf, *f;
485 buf[0] = '\0';
486 /* use upper file if inline ":asm:" or token ":paste:" */
487 for (f = file; f && f->filename[0] == ':'; f = f->prev)
489 if (f) {
490 for(pf = s1->include_stack; pf < s1->include_stack_ptr; pf++)
491 strcat_printf(buf, sizeof(buf), "In file included from %s:%d:\n",
492 (*pf)->filename, (*pf)->line_num);
493 if (f->line_num > 0) {
494 strcat_printf(buf, sizeof(buf), "%s:%d: ",
495 f->filename, f->line_num - !!(tok_flags & TOK_FLAG_BOL));
496 } else {
497 strcat_printf(buf, sizeof(buf), "%s: ",
498 f->filename);
500 } else {
501 strcat_printf(buf, sizeof(buf), "tcc: ");
503 if (is_warning)
504 strcat_printf(buf, sizeof(buf), "warning: ");
505 else
506 strcat_printf(buf, sizeof(buf), "error: ");
507 strcat_vprintf(buf, sizeof(buf), fmt, ap);
509 if (!s1->error_func) {
510 /* default case: stderr */
511 if (s1->ppfp) /* print a newline during tcc -E */
512 fprintf(s1->ppfp, "\n"), fflush(s1->ppfp);
513 fflush(stdout); /* flush -v output */
514 fprintf(stderr, "%s\n", buf);
515 fflush(stderr); /* print error/warning now (win32) */
516 } else {
517 s1->error_func(s1->error_opaque, buf);
519 if (!is_warning || s1->warn_error)
520 s1->nb_errors++;
523 LIBTCCAPI void tcc_set_error_func(TCCState *s, void *error_opaque,
524 void (*error_func)(void *opaque, const char *msg))
526 s->error_opaque = error_opaque;
527 s->error_func = error_func;
530 /* error without aborting current compilation */
531 PUB_FUNC void tcc_error_noabort(const char *fmt, ...)
533 TCCState *s1 = tcc_state;
534 va_list ap;
536 va_start(ap, fmt);
537 error1(s1, 0, fmt, ap);
538 va_end(ap);
541 PUB_FUNC void tcc_error(const char *fmt, ...)
543 TCCState *s1 = tcc_state;
544 va_list ap;
546 va_start(ap, fmt);
547 error1(s1, 0, fmt, ap);
548 va_end(ap);
549 /* better than nothing: in some cases, we accept to handle errors */
550 if (s1->error_set_jmp_enabled) {
551 longjmp(s1->error_jmp_buf, 1);
552 } else {
553 /* XXX: eliminate this someday */
554 exit(1);
558 PUB_FUNC void tcc_warning(const char *fmt, ...)
560 TCCState *s1 = tcc_state;
561 va_list ap;
563 if (s1->warn_none)
564 return;
566 va_start(ap, fmt);
567 error1(s1, 1, fmt, ap);
568 va_end(ap);
571 /********************************************************/
572 /* I/O layer */
574 ST_FUNC void tcc_open_bf(TCCState *s1, const char *filename, int initlen)
576 BufferedFile *bf;
577 int buflen = initlen ? initlen : IO_BUF_SIZE;
579 bf = tcc_mallocz(sizeof(BufferedFile) + buflen);
580 bf->buf_ptr = bf->buffer;
581 bf->buf_end = bf->buffer + initlen;
582 bf->buf_end[0] = CH_EOB; /* put eob symbol */
583 pstrcpy(bf->filename, sizeof(bf->filename), filename);
584 #ifdef _WIN32
585 normalize_slashes(bf->filename);
586 #endif
587 bf->line_num = 1;
588 bf->ifdef_stack_ptr = s1->ifdef_stack_ptr;
589 bf->fd = -1;
590 bf->prev = file;
591 file = bf;
594 ST_FUNC void tcc_close(void)
596 BufferedFile *bf = file;
597 if (bf->fd > 0) {
598 close(bf->fd);
599 total_lines += bf->line_num;
601 file = bf->prev;
602 tcc_free(bf);
605 ST_FUNC int tcc_open(TCCState *s1, const char *filename)
607 int fd;
608 if (strcmp(filename, "-") == 0)
609 fd = 0, filename = "<stdin>";
610 else
611 fd = open(filename, O_RDONLY | O_BINARY);
612 if ((s1->verbose == 2 && fd >= 0) || s1->verbose == 3)
613 printf("%s %*s%s\n", fd < 0 ? "nf":"->",
614 (int)(s1->include_stack_ptr - s1->include_stack), "", filename);
615 if (fd < 0)
616 return -1;
618 tcc_open_bf(s1, filename, 0);
619 file->fd = fd;
620 return fd;
623 /* compile the C file opened in 'file'. Return non zero if errors. */
624 static int tcc_compile(TCCState *s1)
626 Sym *define_start;
628 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 preprocess_start(s1);
634 tccgen_start(s1);
636 #ifdef INC_DEBUG
637 printf("%s: **** new file\n", file->filename);
638 #endif
640 ch = file->buf_ptr[0];
641 tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
642 parse_flags = PARSE_FLAG_PREPROCESS | PARSE_FLAG_TOK_NUM | PARSE_FLAG_TOK_STR;
643 next();
644 decl(VT_CONST);
645 if (tok != TOK_EOF)
646 expect("declaration");
647 /* free defines here already on behalf of of M.M.'s possibly existing
648 experimental preprocessor implementation. The normal call below
649 is still there to free after error-longjmp */
650 free_defines(define_start);
651 tccgen_end(s1);
653 s1->error_set_jmp_enabled = 0;
655 free_inline_functions(s1);
656 /* reset define stack, but keep -D and built-ins */
657 free_defines(define_start);
658 sym_pop(&global_stack, NULL, 0);
659 sym_pop(&local_stack, NULL, 0);
660 return s1->nb_errors != 0 ? -1 : 0;
663 LIBTCCAPI int tcc_compile_string(TCCState *s, const char *str)
665 int len, ret;
667 len = strlen(str);
668 tcc_open_bf(s, "<string>", len);
669 memcpy(file->buffer, str, len);
670 ret = tcc_compile(s);
671 tcc_close();
672 return ret;
675 /* define a preprocessor symbol. A value can also be provided with the '=' operator */
676 LIBTCCAPI void tcc_define_symbol(TCCState *s1, const char *sym, const char *value)
678 int len1, len2;
679 /* default value */
680 if (!value)
681 value = "1";
682 len1 = strlen(sym);
683 len2 = strlen(value);
685 /* init file structure */
686 tcc_open_bf(s1, "<define>", len1 + len2 + 1);
687 memcpy(file->buffer, sym, len1);
688 file->buffer[len1] = ' ';
689 memcpy(file->buffer + len1 + 1, value, len2);
691 /* parse with define parser */
692 ch = file->buf_ptr[0];
693 next_nomacro();
694 parse_define();
696 tcc_close();
699 /* undefine a preprocessor symbol */
700 LIBTCCAPI void tcc_undefine_symbol(TCCState *s1, const char *sym)
702 TokenSym *ts;
703 Sym *s;
704 ts = tok_alloc(sym, strlen(sym));
705 s = define_find(ts->tok);
706 /* undefine symbol by putting an invalid name */
707 if (s)
708 define_undef(s);
711 /* cleanup all static data used during compilation */
712 static void tcc_cleanup(void)
714 if (NULL == tcc_state)
715 return;
716 tccpp_delete(tcc_state);
717 tcc_state = NULL;
718 /* free sym_pools */
719 dynarray_reset(&sym_pools, &nb_sym_pools);
720 /* reset symbol stack */
721 sym_free_first = NULL;
724 LIBTCCAPI TCCState *tcc_new(void)
726 TCCState *s;
728 tcc_cleanup();
730 s = tcc_mallocz(sizeof(TCCState));
731 if (!s)
732 return NULL;
733 tcc_state = s;
734 ++nb_states;
736 s->alacarte_link = 1;
737 s->nocommon = 1;
738 s->warn_implicit_function_declaration = 1;
740 #ifdef CHAR_IS_UNSIGNED
741 s->char_is_unsigned = 1;
742 #endif
743 #ifdef TCC_TARGET_I386
744 s->seg_size = 32;
745 #endif
746 /* enable this if you want symbols with leading underscore on windows: */
747 #if 0 /* def TCC_TARGET_PE */
748 s->leading_underscore = 1;
749 #endif
750 #ifdef _WIN32
751 tcc_set_lib_path_w32(s);
752 #else
753 tcc_set_lib_path(s, CONFIG_TCCDIR);
754 #endif
755 tccelf_new(s);
756 tccpp_new(s);
758 /* we add dummy defines for some special macros to speed up tests
759 and to have working defined() */
760 define_push(TOK___LINE__, MACRO_OBJ, NULL, NULL);
761 define_push(TOK___FILE__, MACRO_OBJ, NULL, NULL);
762 define_push(TOK___DATE__, MACRO_OBJ, NULL, NULL);
763 define_push(TOK___TIME__, MACRO_OBJ, NULL, NULL);
765 /* define __TINYC__ 92X */
766 char buffer[32]; int a,b,c;
767 sscanf(TCC_VERSION, "%d.%d.%d", &a, &b, &c);
768 sprintf(buffer, "%d", a*10000 + b*100 + c);
769 tcc_define_symbol(s, "__TINYC__", buffer);
772 /* standard defines */
773 tcc_define_symbol(s, "__STDC__", NULL);
774 tcc_define_symbol(s, "__STDC_VERSION__", "199901L");
775 tcc_define_symbol(s, "__STDC_HOSTED__", NULL);
777 /* target defines */
778 #if defined(TCC_TARGET_I386)
779 tcc_define_symbol(s, "__i386__", NULL);
780 tcc_define_symbol(s, "__i386", NULL);
781 tcc_define_symbol(s, "i386", NULL);
782 #elif defined(TCC_TARGET_X86_64)
783 tcc_define_symbol(s, "__x86_64__", NULL);
784 #elif defined(TCC_TARGET_ARM)
785 tcc_define_symbol(s, "__ARM_ARCH_4__", NULL);
786 tcc_define_symbol(s, "__arm_elf__", NULL);
787 tcc_define_symbol(s, "__arm_elf", NULL);
788 tcc_define_symbol(s, "arm_elf", NULL);
789 tcc_define_symbol(s, "__arm__", NULL);
790 tcc_define_symbol(s, "__arm", NULL);
791 tcc_define_symbol(s, "arm", NULL);
792 tcc_define_symbol(s, "__APCS_32__", NULL);
793 tcc_define_symbol(s, "__ARMEL__", NULL);
794 #if defined(TCC_ARM_EABI)
795 tcc_define_symbol(s, "__ARM_EABI__", NULL);
796 #endif
797 #if defined(TCC_ARM_HARDFLOAT)
798 s->float_abi = ARM_HARD_FLOAT;
799 tcc_define_symbol(s, "__ARM_PCS_VFP", NULL);
800 #else
801 s->float_abi = ARM_SOFTFP_FLOAT;
802 #endif
803 #elif defined(TCC_TARGET_ARM64)
804 tcc_define_symbol(s, "__aarch64__", NULL);
805 #endif
807 #ifdef TCC_TARGET_PE
808 tcc_define_symbol(s, "_WIN32", NULL);
809 # ifdef TCC_TARGET_X86_64
810 tcc_define_symbol(s, "_WIN64", NULL);
811 # endif
812 #else
813 tcc_define_symbol(s, "__unix__", NULL);
814 tcc_define_symbol(s, "__unix", NULL);
815 tcc_define_symbol(s, "unix", NULL);
816 # if defined(__linux__)
817 tcc_define_symbol(s, "__linux__", NULL);
818 tcc_define_symbol(s, "__linux", NULL);
819 # endif
820 # if defined(__FreeBSD__)
821 tcc_define_symbol(s, "__FreeBSD__", "__FreeBSD__");
822 /* No 'Thread Storage Local' on FreeBSD with tcc */
823 tcc_define_symbol(s, "__NO_TLS", NULL);
824 # endif
825 # if defined(__FreeBSD_kernel__)
826 tcc_define_symbol(s, "__FreeBSD_kernel__", NULL);
827 # endif
828 #endif
829 # if defined(__NetBSD__)
830 tcc_define_symbol(s, "__NetBSD__", "__NetBSD__");
831 # endif
832 # if defined(__OpenBSD__)
833 tcc_define_symbol(s, "__OpenBSD__", "__OpenBSD__");
834 # endif
836 /* TinyCC & gcc defines */
837 #if defined(TCC_TARGET_PE) && defined(TCC_TARGET_X86_64)
838 /* 64bit Windows. */
839 tcc_define_symbol(s, "__SIZE_TYPE__", "unsigned long long");
840 tcc_define_symbol(s, "__PTRDIFF_TYPE__", "long long");
841 tcc_define_symbol(s, "__LLP64__", NULL);
842 #elif defined(TCC_TARGET_X86_64) || defined(TCC_TARGET_ARM64)
843 /* Other 64bit systems. */
844 tcc_define_symbol(s, "__SIZE_TYPE__", "unsigned long");
845 tcc_define_symbol(s, "__PTRDIFF_TYPE__", "long");
846 tcc_define_symbol(s, "__LP64__", NULL);
847 #else
848 /* Other 32bit systems. */
849 tcc_define_symbol(s, "__SIZE_TYPE__", "unsigned long");
850 tcc_define_symbol(s, "__PTRDIFF_TYPE__", "long");
851 tcc_define_symbol(s, "__ILP32__", NULL);
852 #endif
854 #ifdef TCC_TARGET_PE
855 tcc_define_symbol(s, "__WCHAR_TYPE__", "unsigned short");
856 tcc_define_symbol(s, "__WINT_TYPE__", "unsigned short");
857 #else
858 tcc_define_symbol(s, "__WCHAR_TYPE__", "int");
859 /* wint_t is unsigned int by default, but (signed) int on BSDs
860 and unsigned short on windows. Other OSes might have still
861 other conventions, sigh. */
862 # if defined(__FreeBSD__) || defined (__FreeBSD_kernel__) \
863 || defined(__NetBSD__) || defined(__OpenBSD__)
864 tcc_define_symbol(s, "__WINT_TYPE__", "int");
865 # ifdef __FreeBSD__
866 /* define __GNUC__ to have some useful stuff from sys/cdefs.h
867 that are unconditionally used in FreeBSDs other system headers :/ */
868 tcc_define_symbol(s, "__GNUC__", "2");
869 tcc_define_symbol(s, "__GNUC_MINOR__", "7");
870 tcc_define_symbol(s, "__builtin_alloca", "alloca");
871 # endif
872 # else
873 tcc_define_symbol(s, "__WINT_TYPE__", "unsigned int");
874 /* glibc defines */
875 tcc_define_symbol(s, "__REDIRECT(name, proto, alias)",
876 "name proto __asm__ (#alias)");
877 tcc_define_symbol(s, "__REDIRECT_NTH(name, proto, alias)",
878 "name proto __asm__ (#alias) __THROW");
879 # endif
880 /* Some GCC builtins that are simple to express as macros. */
881 tcc_define_symbol(s, "__builtin_extract_return_addr(x)", "x");
882 #endif /* ndef TCC_TARGET_PE */
883 return s;
886 LIBTCCAPI void tcc_delete(TCCState *s1)
888 tcc_cleanup();
890 /* free sections */
891 tccelf_delete(s1);
893 /* free library paths */
894 dynarray_reset(&s1->library_paths, &s1->nb_library_paths);
895 dynarray_reset(&s1->crt_paths, &s1->nb_crt_paths);
897 /* free include paths */
898 dynarray_reset(&s1->cached_includes, &s1->nb_cached_includes);
899 dynarray_reset(&s1->include_paths, &s1->nb_include_paths);
900 dynarray_reset(&s1->sysinclude_paths, &s1->nb_sysinclude_paths);
901 dynarray_reset(&s1->cmd_include_files, &s1->nb_cmd_include_files);
903 tcc_free(s1->tcc_lib_path);
904 tcc_free(s1->soname);
905 tcc_free(s1->rpath);
906 tcc_free(s1->init_symbol);
907 tcc_free(s1->fini_symbol);
908 tcc_free(s1->outfile);
909 tcc_free(s1->deps_outfile);
910 dynarray_reset(&s1->files, &s1->nb_files);
911 dynarray_reset(&s1->target_deps, &s1->nb_target_deps);
912 dynarray_reset(&s1->pragma_libs, &s1->nb_pragma_libs);
913 dynarray_reset(&s1->argv, &s1->argc);
915 #ifdef TCC_IS_NATIVE
916 /* free runtime memory */
917 tcc_run_free(s1);
918 #endif
920 tcc_free(s1);
921 if (0 == --nb_states)
922 tcc_memcheck();
925 LIBTCCAPI int tcc_set_output_type(TCCState *s, int output_type)
927 s->output_type = output_type;
929 /* always elf for objects */
930 if (output_type == TCC_OUTPUT_OBJ)
931 s->output_format = TCC_OUTPUT_FORMAT_ELF;
933 if (s->char_is_unsigned)
934 tcc_define_symbol(s, "__CHAR_UNSIGNED__", NULL);
936 if (!s->nostdinc) {
937 /* default include paths */
938 /* -isystem paths have already been handled */
939 tcc_add_sysinclude_path(s, CONFIG_TCC_SYSINCLUDEPATHS);
942 #ifdef CONFIG_TCC_BCHECK
943 if (s->do_bounds_check) {
944 /* if bound checking, then add corresponding sections */
945 tccelf_bounds_new(s);
946 /* define symbol */
947 tcc_define_symbol(s, "__BOUNDS_CHECKING_ON", NULL);
949 #endif
950 if (s->do_debug) {
951 /* add debug sections */
952 tccelf_stab_new(s);
955 tcc_add_library_path(s, CONFIG_TCC_LIBPATHS);
957 #ifdef TCC_TARGET_PE
958 # ifdef _WIN32
959 if (!s->nostdlib && output_type != TCC_OUTPUT_OBJ)
960 tcc_add_systemdir(s);
961 # endif
962 #else
963 /* paths for crt objects */
964 tcc_split_path(s, &s->crt_paths, &s->nb_crt_paths, CONFIG_TCC_CRTPREFIX);
965 /* add libc crt1/crti objects */
966 if ((output_type == TCC_OUTPUT_EXE || output_type == TCC_OUTPUT_DLL) &&
967 !s->nostdlib) {
968 if (output_type != TCC_OUTPUT_DLL)
969 tcc_add_crt(s, "crt1.o");
970 tcc_add_crt(s, "crti.o");
972 #endif
973 return 0;
976 LIBTCCAPI int tcc_add_include_path(TCCState *s, const char *pathname)
978 tcc_split_path(s, &s->include_paths, &s->nb_include_paths, pathname);
979 return 0;
982 LIBTCCAPI int tcc_add_sysinclude_path(TCCState *s, const char *pathname)
984 tcc_split_path(s, &s->sysinclude_paths, &s->nb_sysinclude_paths, pathname);
985 return 0;
988 ST_FUNC int tcc_add_file_internal(TCCState *s1, const char *filename, int flags)
990 int ret, filetype;
992 filetype = flags & 0x0F;
993 if (filetype == 0) {
994 /* use a file extension to detect a filetype */
995 const char *ext = tcc_fileextension(filename);
996 if (ext[0]) {
997 ext++;
998 if (!strcmp(ext, "S"))
999 filetype = AFF_TYPE_ASMPP;
1000 else if (!strcmp(ext, "s"))
1001 filetype = AFF_TYPE_ASM;
1002 else if (!PATHCMP(ext, "c") || !PATHCMP(ext, "i"))
1003 filetype = AFF_TYPE_C;
1004 else
1005 filetype = AFF_TYPE_BIN;
1006 } else {
1007 filetype = AFF_TYPE_C;
1011 /* open the file */
1012 ret = tcc_open(s1, filename);
1013 if (ret < 0) {
1014 if (flags & AFF_PRINT_ERROR)
1015 tcc_error_noabort("file '%s' not found", filename);
1016 return ret;
1019 /* update target deps */
1020 dynarray_add(&s1->target_deps, &s1->nb_target_deps,
1021 tcc_strdup(filename));
1023 parse_flags = 0;
1024 /* if .S file, define __ASSEMBLER__ like gcc does */
1025 if (filetype == AFF_TYPE_ASM || filetype == AFF_TYPE_ASMPP) {
1026 tcc_define_symbol(s1, "__ASSEMBLER__", NULL);
1027 parse_flags = PARSE_FLAG_ASM_FILE;
1030 if (flags & AFF_PREPROCESS) {
1031 ret = tcc_preprocess(s1);
1032 } else if (filetype == AFF_TYPE_C) {
1033 ret = tcc_compile(s1);
1034 #ifdef CONFIG_TCC_ASM
1035 } else if (filetype == AFF_TYPE_ASMPP) {
1036 /* non preprocessed assembler */
1037 ret = tcc_assemble(s1, 1);
1038 } else if (filetype == AFF_TYPE_ASM) {
1039 /* preprocessed assembler */
1040 ret = tcc_assemble(s1, 0);
1041 #endif
1042 } else {
1043 ElfW(Ehdr) ehdr;
1044 int fd, obj_type;
1046 fd = file->fd;
1047 obj_type = tcc_object_type(fd, &ehdr);
1048 lseek(fd, 0, SEEK_SET);
1050 /* do not display line number if error */
1051 file->line_num = 0;
1053 switch (obj_type) {
1054 case AFF_BINTYPE_REL:
1055 ret = tcc_load_object_file(s1, fd, 0);
1056 break;
1057 #ifndef TCC_TARGET_PE
1058 case AFF_BINTYPE_DYN:
1059 if (s1->output_type == TCC_OUTPUT_MEMORY) {
1060 ret = 0;
1061 #ifdef TCC_IS_NATIVE
1062 if (NULL == dlopen(filename, RTLD_GLOBAL | RTLD_LAZY))
1063 ret = -1;
1064 #endif
1065 } else {
1066 ret = tcc_load_dll(s1, fd, filename,
1067 (flags & AFF_REFERENCED_DLL) != 0);
1069 break;
1070 #endif
1071 case AFF_BINTYPE_AR:
1072 ret = tcc_load_archive(s1, fd);
1073 break;
1074 #ifdef TCC_TARGET_COFF
1075 case AFF_BINTYPE_C67:
1076 ret = tcc_load_coff(s1, fd);
1077 break;
1078 #endif
1079 default:
1080 #ifdef TCC_TARGET_PE
1081 ret = pe_load_file(s1, filename, fd);
1082 #else
1083 /* as GNU ld, consider it is an ld script if not recognized */
1084 ret = tcc_load_ldscript(s1);
1085 #endif
1086 if (ret < 0)
1087 tcc_error_noabort("unrecognized file type");
1088 break;
1091 tcc_close();
1092 return ret;
1095 LIBTCCAPI int tcc_add_file(TCCState *s, const char *filename)
1097 if (s->output_type == TCC_OUTPUT_PREPROCESS)
1098 return tcc_add_file_internal(s, filename, AFF_PRINT_ERROR | AFF_PREPROCESS | s->filetype);
1099 else
1100 return tcc_add_file_internal(s, filename, AFF_PRINT_ERROR | s->filetype);
1103 LIBTCCAPI int tcc_add_library_path(TCCState *s, const char *pathname)
1105 tcc_split_path(s, &s->library_paths, &s->nb_library_paths, pathname);
1106 return 0;
1109 static int tcc_add_library_internal(TCCState *s, const char *fmt,
1110 const char *filename, int flags, char **paths, int nb_paths)
1112 char buf[1024];
1113 int i;
1115 for(i = 0; i < nb_paths; i++) {
1116 snprintf(buf, sizeof(buf), fmt, paths[i], filename);
1117 if (tcc_add_file_internal(s, buf, flags | AFF_TYPE_BIN) == 0)
1118 return 0;
1120 return -1;
1123 #ifndef TCC_TARGET_PE
1124 /* find and load a dll. Return non zero if not found */
1125 /* XXX: add '-rpath' option support ? */
1126 ST_FUNC int tcc_add_dll(TCCState *s, const char *filename, int flags)
1128 return tcc_add_library_internal(s, "%s/%s", filename, flags,
1129 s->library_paths, s->nb_library_paths);
1131 #endif
1133 ST_FUNC int tcc_add_crt(TCCState *s, const char *filename)
1135 if (-1 == tcc_add_library_internal(s, "%s/%s",
1136 filename, 0, s->crt_paths, s->nb_crt_paths))
1137 tcc_error_noabort("file '%s' not found", filename);
1138 return 0;
1141 /* the library name is the same as the argument of the '-l' option */
1142 LIBTCCAPI int tcc_add_library(TCCState *s, const char *libraryname)
1144 #ifdef TCC_TARGET_PE
1145 const char *libs[] = { "%s/%s.def", "%s/lib%s.def", "%s/%s.dll", "%s/lib%s.dll", "%s/lib%s.a", NULL };
1146 const char **pp = s->static_link ? libs + 4 : libs;
1147 #else
1148 const char *libs[] = { "%s/lib%s.so", "%s/lib%s.a", NULL };
1149 const char **pp = s->static_link ? libs + 1 : libs;
1150 #endif
1151 while (*pp) {
1152 if (0 == tcc_add_library_internal(s, *pp,
1153 libraryname, 0, s->library_paths, s->nb_library_paths))
1154 return 0;
1155 ++pp;
1157 return -1;
1160 PUB_FUNC int tcc_add_library_err(TCCState *s, const char *libname)
1162 int ret = tcc_add_library(s, libname);
1163 if (ret < 0)
1164 tcc_error_noabort("library '%s' not found", libname);
1165 return ret;
1168 /* habdle #pragma comment(lib,) */
1169 ST_FUNC void tcc_add_pragma_libs(TCCState *s1)
1171 int i;
1172 for (i = 0; i < s1->nb_pragma_libs; i++)
1173 tcc_add_library_err(s1, s1->pragma_libs[i]);
1176 LIBTCCAPI int tcc_add_symbol(TCCState *s, const char *name, const void *val)
1178 #ifdef TCC_TARGET_PE
1179 /* On x86_64 'val' might not be reachable with a 32bit offset.
1180 So it is handled here as if it were in a DLL. */
1181 pe_putimport(s, 0, name, (uintptr_t)val);
1182 #else
1183 set_elf_sym(symtab_section, (uintptr_t)val, 0,
1184 ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE), 0,
1185 SHN_ABS, name);
1186 #endif
1187 return 0;
1190 LIBTCCAPI void tcc_set_lib_path(TCCState *s, const char *path)
1192 tcc_free(s->tcc_lib_path);
1193 s->tcc_lib_path = tcc_strdup(path);
1196 #define WD_ALL 0x0001 /* warning is activated when using -Wall */
1197 #define FD_INVERT 0x0002 /* invert value before storing */
1199 typedef struct FlagDef {
1200 uint16_t offset;
1201 uint16_t flags;
1202 const char *name;
1203 } FlagDef;
1205 static int no_flag(const char **pp)
1207 const char *p = *pp;
1208 if (*p != 'n' || *++p != 'o' || *++p != '-')
1209 return 0;
1210 *pp = p + 1;
1211 return 1;
1214 ST_FUNC int set_flag(TCCState *s, const FlagDef *flags, const char *name)
1216 int value, ret;
1217 const FlagDef *p;
1218 const char *r;
1220 value = 1;
1221 r = name;
1222 if (no_flag(&r))
1223 value = 0;
1225 for (ret = -1, p = flags; p->name; ++p) {
1226 if (ret) {
1227 if (strcmp(r, p->name))
1228 continue;
1229 } else {
1230 if (0 == (p->flags & WD_ALL))
1231 continue;
1233 if (p->offset) {
1234 *(int*)((char *)s + p->offset) =
1235 p->flags & FD_INVERT ? !value : value;
1236 if (ret)
1237 return 0;
1238 } else {
1239 ret = 0;
1242 return ret;
1245 static int strstart(const char *val, const char **str)
1247 const char *p, *q;
1248 p = *str;
1249 q = val;
1250 while (*q) {
1251 if (*p != *q)
1252 return 0;
1253 p++;
1254 q++;
1256 *str = p;
1257 return 1;
1260 /* Like strstart, but automatically takes into account that ld options can
1262 * - start with double or single dash (e.g. '--soname' or '-soname')
1263 * - arguments can be given as separate or after '=' (e.g. '-Wl,-soname,x.so'
1264 * or '-Wl,-soname=x.so')
1266 * you provide `val` always in 'option[=]' form (no leading -)
1268 static int link_option(const char *str, const char *val, const char **ptr)
1270 const char *p, *q;
1271 int ret;
1273 /* there should be 1 or 2 dashes */
1274 if (*str++ != '-')
1275 return 0;
1276 if (*str == '-')
1277 str++;
1279 /* then str & val should match (potentialy up to '=') */
1280 p = str;
1281 q = val;
1283 ret = 1;
1284 if (q[0] == '?') {
1285 ++q;
1286 if (no_flag(&p))
1287 ret = -1;
1290 while (*q != '\0' && *q != '=') {
1291 if (*p != *q)
1292 return 0;
1293 p++;
1294 q++;
1297 /* '=' near eos means ',' or '=' is ok */
1298 if (*q == '=') {
1299 if (*p == 0)
1300 *ptr = p;
1301 if (*p != ',' && *p != '=')
1302 return 0;
1303 p++;
1305 *ptr = p;
1306 return ret;
1309 static const char *skip_linker_arg(const char **str)
1311 const char *s1 = *str;
1312 const char *s2 = strchr(s1, ',');
1313 *str = s2 ? s2++ : (s2 = s1 + strlen(s1));
1314 return s2;
1317 static void copy_linker_arg(char **pp, const char *s, int sep)
1319 const char *q = s;
1320 char *p = *pp;
1321 int l = 0;
1322 if (p && sep)
1323 p[l = strlen(p)] = sep, ++l;
1324 skip_linker_arg(&q);
1325 pstrncpy(l + (*pp = tcc_realloc(p, q - s + l + 1)), s, q - s);
1328 /* set linker options */
1329 static int tcc_set_linker(TCCState *s, const char *option)
1331 while (*option) {
1333 const char *p = NULL;
1334 char *end = NULL;
1335 int ignoring = 0;
1336 int ret;
1338 if (link_option(option, "Bsymbolic", &p)) {
1339 s->symbolic = 1;
1340 } else if (link_option(option, "nostdlib", &p)) {
1341 s->nostdlib = 1;
1342 } else if (link_option(option, "fini=", &p)) {
1343 copy_linker_arg(&s->fini_symbol, p, 0);
1344 ignoring = 1;
1345 } else if (link_option(option, "image-base=", &p)
1346 || link_option(option, "Ttext=", &p)) {
1347 s->text_addr = strtoull(p, &end, 16);
1348 s->has_text_addr = 1;
1349 } else if (link_option(option, "init=", &p)) {
1350 copy_linker_arg(&s->init_symbol, p, 0);
1351 ignoring = 1;
1352 } else if (link_option(option, "oformat=", &p)) {
1353 #if defined(TCC_TARGET_PE)
1354 if (strstart("pe-", &p)) {
1355 #elif defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
1356 if (strstart("elf64-", &p)) {
1357 #else
1358 if (strstart("elf32-", &p)) {
1359 #endif
1360 s->output_format = TCC_OUTPUT_FORMAT_ELF;
1361 } else if (!strcmp(p, "binary")) {
1362 s->output_format = TCC_OUTPUT_FORMAT_BINARY;
1363 #ifdef TCC_TARGET_COFF
1364 } else if (!strcmp(p, "coff")) {
1365 s->output_format = TCC_OUTPUT_FORMAT_COFF;
1366 #endif
1367 } else
1368 goto err;
1370 } else if (link_option(option, "as-needed", &p)) {
1371 ignoring = 1;
1372 } else if (link_option(option, "O", &p)) {
1373 ignoring = 1;
1374 } else if (link_option(option, "rpath=", &p)) {
1375 copy_linker_arg(&s->rpath, p, ':');
1376 } else if (link_option(option, "enable-new-dtags", &p)) {
1377 s->enable_new_dtags = 1;
1378 } else if (link_option(option, "section-alignment=", &p)) {
1379 s->section_align = strtoul(p, &end, 16);
1380 } else if (link_option(option, "soname=", &p)) {
1381 copy_linker_arg(&s->soname, p, 0);
1382 #ifdef TCC_TARGET_PE
1383 } else if (link_option(option, "large-address-aware", &p)) {
1384 s->pe_characteristics |= 0x20;
1385 } else if (link_option(option, "file-alignment=", &p)) {
1386 s->pe_file_align = strtoul(p, &end, 16);
1387 } else if (link_option(option, "stack=", &p)) {
1388 s->pe_stack_size = strtoul(p, &end, 10);
1389 } else if (link_option(option, "subsystem=", &p)) {
1390 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
1391 if (!strcmp(p, "native")) {
1392 s->pe_subsystem = 1;
1393 } else if (!strcmp(p, "console")) {
1394 s->pe_subsystem = 3;
1395 } else if (!strcmp(p, "gui")) {
1396 s->pe_subsystem = 2;
1397 } else if (!strcmp(p, "posix")) {
1398 s->pe_subsystem = 7;
1399 } else if (!strcmp(p, "efiapp")) {
1400 s->pe_subsystem = 10;
1401 } else if (!strcmp(p, "efiboot")) {
1402 s->pe_subsystem = 11;
1403 } else if (!strcmp(p, "efiruntime")) {
1404 s->pe_subsystem = 12;
1405 } else if (!strcmp(p, "efirom")) {
1406 s->pe_subsystem = 13;
1407 #elif defined(TCC_TARGET_ARM)
1408 if (!strcmp(p, "wince")) {
1409 s->pe_subsystem = 9;
1410 #endif
1411 } else
1412 goto err;
1413 #endif
1414 } else if (ret = link_option(option, "?whole-archive", &p), ret) {
1415 s->alacarte_link = ret < 0;
1416 } else if (p) {
1417 return 0;
1418 } else {
1419 err:
1420 tcc_error("unsupported linker option '%s'", option);
1423 if (ignoring && s->warn_unsupported)
1424 tcc_warning("unsupported linker option '%s'", option);
1426 option = skip_linker_arg(&p);
1428 return 1;
1431 typedef struct TCCOption {
1432 const char *name;
1433 uint16_t index;
1434 uint16_t flags;
1435 } TCCOption;
1437 enum {
1438 TCC_OPTION_HELP,
1439 TCC_OPTION_HELP2,
1440 TCC_OPTION_v,
1441 TCC_OPTION_I,
1442 TCC_OPTION_D,
1443 TCC_OPTION_U,
1444 TCC_OPTION_P,
1445 TCC_OPTION_L,
1446 TCC_OPTION_B,
1447 TCC_OPTION_l,
1448 TCC_OPTION_bench,
1449 TCC_OPTION_bt,
1450 TCC_OPTION_b,
1451 TCC_OPTION_g,
1452 TCC_OPTION_c,
1453 TCC_OPTION_dumpversion,
1454 TCC_OPTION_d,
1455 TCC_OPTION_static,
1456 TCC_OPTION_std,
1457 TCC_OPTION_shared,
1458 TCC_OPTION_soname,
1459 TCC_OPTION_o,
1460 TCC_OPTION_r,
1461 TCC_OPTION_s,
1462 TCC_OPTION_traditional,
1463 TCC_OPTION_Wl,
1464 TCC_OPTION_Wp,
1465 TCC_OPTION_W,
1466 TCC_OPTION_O,
1467 TCC_OPTION_mfloat_abi,
1468 TCC_OPTION_m,
1469 TCC_OPTION_f,
1470 TCC_OPTION_isystem,
1471 TCC_OPTION_iwithprefix,
1472 TCC_OPTION_include,
1473 TCC_OPTION_nostdinc,
1474 TCC_OPTION_nostdlib,
1475 TCC_OPTION_print_search_dirs,
1476 TCC_OPTION_rdynamic,
1477 TCC_OPTION_param,
1478 TCC_OPTION_pedantic,
1479 TCC_OPTION_pthread,
1480 TCC_OPTION_run,
1481 TCC_OPTION_w,
1482 TCC_OPTION_pipe,
1483 TCC_OPTION_E,
1484 TCC_OPTION_MD,
1485 TCC_OPTION_MF,
1486 TCC_OPTION_x,
1487 TCC_OPTION_ar,
1488 TCC_OPTION_impdef
1491 #define TCC_OPTION_HAS_ARG 0x0001
1492 #define TCC_OPTION_NOSEP 0x0002 /* cannot have space before option and arg */
1494 static const TCCOption tcc_options[] = {
1495 { "h", TCC_OPTION_HELP, 0 },
1496 { "-help", TCC_OPTION_HELP, 0 },
1497 { "?", TCC_OPTION_HELP, 0 },
1498 { "hh", TCC_OPTION_HELP2, 0 },
1499 { "v", TCC_OPTION_v, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
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 { "w", TCC_OPTION_w, 0 },
1547 { "pipe", TCC_OPTION_pipe, 0},
1548 { "E", TCC_OPTION_E, 0},
1549 { "MD", TCC_OPTION_MD, 0},
1550 { "MF", TCC_OPTION_MF, TCC_OPTION_HAS_ARG },
1551 { "x", TCC_OPTION_x, TCC_OPTION_HAS_ARG },
1552 { "ar", TCC_OPTION_ar, 0},
1553 #ifdef TCC_TARGET_PE
1554 { "impdef", TCC_OPTION_impdef, 0},
1555 #endif
1556 { NULL, 0, 0 },
1559 static const FlagDef options_W[] = {
1560 { 0, 0, "all" },
1561 { offsetof(TCCState, warn_unsupported), 0, "unsupported" },
1562 { offsetof(TCCState, warn_write_strings), 0, "write-strings" },
1563 { offsetof(TCCState, warn_error), 0, "error" },
1564 { offsetof(TCCState, warn_implicit_function_declaration), WD_ALL,
1565 "implicit-function-declaration" },
1566 { 0, 0, NULL }
1569 static const FlagDef options_f[] = {
1570 { offsetof(TCCState, char_is_unsigned), 0, "unsigned-char" },
1571 { offsetof(TCCState, char_is_unsigned), FD_INVERT, "signed-char" },
1572 { offsetof(TCCState, nocommon), FD_INVERT, "common" },
1573 { offsetof(TCCState, leading_underscore), 0, "leading-underscore" },
1574 { offsetof(TCCState, ms_extensions), 0, "ms-extensions" },
1575 { offsetof(TCCState, dollars_in_identifiers), 0, "dollars-in-identifiers" },
1576 { 0, 0, NULL }
1579 static const FlagDef options_m[] = {
1580 { offsetof(TCCState, ms_bitfields), 0, "ms-bitfields" },
1581 #ifdef TCC_TARGET_X86_64
1582 { offsetof(TCCState, nosse), FD_INVERT, "sse" },
1583 #endif
1584 { 0, 0, NULL }
1587 static void parse_option_D(TCCState *s1, const char *optarg)
1589 char *sym = tcc_strdup(optarg);
1590 char *value = strchr(sym, '=');
1591 if (value)
1592 *value++ = '\0';
1593 tcc_define_symbol(s1, sym, value);
1594 tcc_free(sym);
1597 static void args_parser_add_file(TCCState *s, const char* filename, int filetype)
1599 struct filespec *f = tcc_malloc(sizeof *f + strlen(filename));
1600 f->type = filetype;
1601 f->alacarte = s->alacarte_link;
1602 strcpy(f->name, filename);
1603 dynarray_add(&s->files, &s->nb_files, f);
1606 static int args_parser_make_argv(const char *r, int *argc, char ***argv)
1608 int ret = 0, q, c;
1609 CString str;
1610 for(;;) {
1611 while (c = (unsigned char)*r, c && c <= ' ')
1612 ++r;
1613 if (c == 0)
1614 break;
1615 q = 0;
1616 cstr_new(&str);
1617 while (c = (unsigned char)*r, c) {
1618 ++r;
1619 if (c == '\\' && (*r == '"' || *r == '\\')) {
1620 c = *r++;
1621 } else if (c == '"') {
1622 q = !q;
1623 continue;
1624 } else if (q == 0 && c <= ' ') {
1625 break;
1627 cstr_ccat(&str, c);
1629 cstr_ccat(&str, 0);
1630 //printf("<%s>\n", str.data), fflush(stdout);
1631 dynarray_add(argv, argc, tcc_strdup(str.data));
1632 cstr_free(&str);
1633 ++ret;
1635 return ret;
1638 /* read list file */
1639 static void args_parser_listfile(TCCState *s,
1640 const char *filename, int optind, int *pargc, char ***pargv)
1642 int fd, i;
1643 size_t len;
1644 char *p;
1645 int argc = 0;
1646 char **argv = NULL;
1648 fd = open(filename, O_RDONLY | O_BINARY);
1649 if (fd < 0)
1650 tcc_error("listfile '%s' not found", filename);
1652 len = lseek(fd, 0, SEEK_END);
1653 p = tcc_malloc(len + 1), p[len] = 0;
1654 lseek(fd, 0, SEEK_SET), read(fd, p, len), close(fd);
1656 for (i = 0; i < *pargc; ++i)
1657 if (i == optind)
1658 args_parser_make_argv(p, &argc, &argv);
1659 else
1660 dynarray_add(&argv, &argc, tcc_strdup((*pargv)[i]));
1662 tcc_free(p);
1663 dynarray_reset(&s->argv, &s->argc);
1664 *pargc = s->argc = argc, *pargv = s->argv = argv;
1667 PUB_FUNC int tcc_parse_args(TCCState *s, int *pargc, char ***pargv, int optind)
1669 const TCCOption *popt;
1670 const char *optarg, *r;
1671 const char *run = NULL;
1672 int last_o = -1;
1673 int x;
1674 CString linker_arg; /* collect -Wl options */
1675 char buf[1024];
1676 int tool = 0, arg_start = 0, noaction = optind;
1677 char **argv = *pargv;
1678 int argc = *pargc;
1680 cstr_new(&linker_arg);
1682 while (optind < argc) {
1683 r = argv[optind];
1684 if (r[0] == '@' && r[1] != '\0') {
1685 args_parser_listfile(s, r + 1, optind, &argc, &argv);
1686 continue;
1688 optind++;
1689 if (tool) {
1690 if (r[0] == '-' && r[1] == 'v' && r[2] == 0)
1691 ++s->verbose;
1692 continue;
1694 reparse:
1695 if (r[0] != '-' || r[1] == '\0') {
1696 if (r[0] != '@') /* allow "tcc file(s) -run @ args ..." */
1697 args_parser_add_file(s, r, s->filetype);
1698 if (run) {
1699 tcc_set_options(s, run);
1700 arg_start = optind - 1;
1701 break;
1703 continue;
1706 /* find option in table */
1707 for(popt = tcc_options; ; ++popt) {
1708 const char *p1 = popt->name;
1709 const char *r1 = r + 1;
1710 if (p1 == NULL)
1711 tcc_error("invalid option -- '%s'", r);
1712 if (!strstart(p1, &r1))
1713 continue;
1714 optarg = r1;
1715 if (popt->flags & TCC_OPTION_HAS_ARG) {
1716 if (*r1 == '\0' && !(popt->flags & TCC_OPTION_NOSEP)) {
1717 if (optind >= argc)
1718 arg_err:
1719 tcc_error("argument to '%s' is missing", r);
1720 optarg = argv[optind++];
1722 } else if (*r1 != '\0')
1723 continue;
1724 break;
1727 switch(popt->index) {
1728 case TCC_OPTION_HELP:
1729 return OPT_HELP;
1730 case TCC_OPTION_HELP2:
1731 return OPT_HELP2;
1732 case TCC_OPTION_I:
1733 tcc_add_include_path(s, optarg);
1734 break;
1735 case TCC_OPTION_D:
1736 parse_option_D(s, optarg);
1737 break;
1738 case TCC_OPTION_U:
1739 tcc_undefine_symbol(s, optarg);
1740 break;
1741 case TCC_OPTION_L:
1742 tcc_add_library_path(s, optarg);
1743 break;
1744 case TCC_OPTION_B:
1745 /* set tcc utilities path (mainly for tcc development) */
1746 tcc_set_lib_path(s, optarg);
1747 break;
1748 case TCC_OPTION_l:
1749 args_parser_add_file(s, optarg, AFF_TYPE_LIB);
1750 s->nb_libraries++;
1751 break;
1752 case TCC_OPTION_pthread:
1753 parse_option_D(s, "_REENTRANT");
1754 s->option_pthread = 1;
1755 break;
1756 case TCC_OPTION_bench:
1757 s->do_bench = 1;
1758 break;
1759 #ifdef CONFIG_TCC_BACKTRACE
1760 case TCC_OPTION_bt:
1761 tcc_set_num_callers(atoi(optarg));
1762 break;
1763 #endif
1764 #ifdef CONFIG_TCC_BCHECK
1765 case TCC_OPTION_b:
1766 s->do_bounds_check = 1;
1767 s->do_debug = 1;
1768 break;
1769 #endif
1770 case TCC_OPTION_g:
1771 s->do_debug = 1;
1772 break;
1773 case TCC_OPTION_c:
1774 x = TCC_OUTPUT_OBJ;
1775 set_output_type:
1776 if (s->output_type)
1777 tcc_warning("-%s: overriding compiler action already specified", popt->name);
1778 s->output_type = x;
1779 break;
1780 case TCC_OPTION_d:
1781 if (*optarg == 'D')
1782 s->dflag = 3;
1783 else if (*optarg == 'M')
1784 s->dflag = 7;
1785 else
1786 goto unsupported_option;
1787 break;
1788 case TCC_OPTION_static:
1789 s->static_link = 1;
1790 break;
1791 case TCC_OPTION_std:
1792 /* silently ignore, a current purpose:
1793 allow to use a tcc as a reference compiler for "make test" */
1794 break;
1795 case TCC_OPTION_shared:
1796 x = TCC_OUTPUT_DLL;
1797 goto set_output_type;
1798 case TCC_OPTION_soname:
1799 s->soname = tcc_strdup(optarg);
1800 break;
1801 case TCC_OPTION_o:
1802 if (s->outfile) {
1803 tcc_warning("multiple -o option");
1804 tcc_free(s->outfile);
1806 s->outfile = tcc_strdup(optarg);
1807 break;
1808 case TCC_OPTION_r:
1809 /* generate a .o merging several output files */
1810 s->option_r = 1;
1811 x = TCC_OUTPUT_OBJ;
1812 goto set_output_type;
1813 case TCC_OPTION_isystem:
1814 tcc_add_sysinclude_path(s, optarg);
1815 break;
1816 case TCC_OPTION_iwithprefix:
1817 snprintf(buf, sizeof buf, "{B}/%s", optarg);
1818 tcc_add_sysinclude_path(s, buf);
1819 break;
1820 case TCC_OPTION_include:
1821 dynarray_add(&s->cmd_include_files,
1822 &s->nb_cmd_include_files, tcc_strdup(optarg));
1823 break;
1824 case TCC_OPTION_nostdinc:
1825 s->nostdinc = 1;
1826 break;
1827 case TCC_OPTION_nostdlib:
1828 s->nostdlib = 1;
1829 break;
1830 case TCC_OPTION_run:
1831 #ifndef TCC_IS_NATIVE
1832 tcc_error("-run is not available in a cross compiler");
1833 #endif
1834 run = optarg;
1835 x = TCC_OUTPUT_MEMORY;
1836 goto set_output_type;
1837 case TCC_OPTION_v:
1838 do ++s->verbose; while (*optarg++ == 'v');
1839 ++noaction;
1840 break;
1841 case TCC_OPTION_f:
1842 if (set_flag(s, options_f, optarg) < 0)
1843 goto unsupported_option;
1844 break;
1845 #ifdef TCC_TARGET_ARM
1846 case TCC_OPTION_mfloat_abi:
1847 /* tcc doesn't support soft float yet */
1848 if (!strcmp(optarg, "softfp")) {
1849 s->float_abi = ARM_SOFTFP_FLOAT;
1850 tcc_undefine_symbol(s, "__ARM_PCS_VFP");
1851 } else if (!strcmp(optarg, "hard"))
1852 s->float_abi = ARM_HARD_FLOAT;
1853 else
1854 tcc_error("unsupported float abi '%s'", optarg);
1855 break;
1856 #endif
1857 case TCC_OPTION_m:
1858 if (set_flag(s, options_m, optarg) < 0) {
1859 if (x = atoi(optarg), x != 32 && x != 64)
1860 goto unsupported_option;
1861 if (PTR_SIZE != x/8)
1862 return x;
1863 ++noaction;
1865 break;
1866 case TCC_OPTION_W:
1867 if (set_flag(s, options_W, optarg) < 0)
1868 goto unsupported_option;
1869 break;
1870 case TCC_OPTION_w:
1871 s->warn_none = 1;
1872 break;
1873 case TCC_OPTION_rdynamic:
1874 s->rdynamic = 1;
1875 break;
1876 case TCC_OPTION_Wl:
1877 if (linker_arg.size)
1878 --linker_arg.size, cstr_ccat(&linker_arg, ',');
1879 cstr_cat(&linker_arg, optarg, 0);
1880 if (tcc_set_linker(s, linker_arg.data))
1881 cstr_free(&linker_arg);
1882 break;
1883 case TCC_OPTION_Wp:
1884 r = optarg;
1885 goto reparse;
1886 case TCC_OPTION_E:
1887 x = TCC_OUTPUT_PREPROCESS;
1888 goto set_output_type;
1889 case TCC_OPTION_P:
1890 s->Pflag = atoi(optarg) + 1;
1891 break;
1892 case TCC_OPTION_MD:
1893 s->gen_deps = 1;
1894 break;
1895 case TCC_OPTION_MF:
1896 s->deps_outfile = tcc_strdup(optarg);
1897 break;
1898 case TCC_OPTION_dumpversion:
1899 printf ("%s\n", TCC_VERSION);
1900 exit(0);
1901 break;
1902 case TCC_OPTION_x:
1903 if (*optarg == 'c')
1904 s->filetype = AFF_TYPE_C;
1905 else if (*optarg == 'a')
1906 s->filetype = AFF_TYPE_ASMPP;
1907 else if (*optarg == 'n')
1908 s->filetype = AFF_TYPE_NONE;
1909 else
1910 tcc_warning("unsupported language '%s'", optarg);
1911 break;
1912 case TCC_OPTION_O:
1913 last_o = atoi(optarg);
1914 break;
1915 case TCC_OPTION_print_search_dirs:
1916 x = OPT_PRINT_DIRS;
1917 goto extra_action;
1918 case TCC_OPTION_impdef:
1919 x = OPT_IMPDEF;
1920 goto extra_action;
1921 case TCC_OPTION_ar:
1922 x = OPT_AR;
1923 extra_action:
1924 arg_start = optind - 1;
1925 if (arg_start != noaction)
1926 tcc_error("cannot parse %s here", r);
1927 tool = x;
1928 break;
1929 case TCC_OPTION_traditional:
1930 case TCC_OPTION_pedantic:
1931 case TCC_OPTION_pipe:
1932 case TCC_OPTION_s:
1933 /* ignored */
1934 break;
1935 default:
1936 unsupported_option:
1937 if (s->warn_unsupported)
1938 tcc_warning("unsupported option '%s'", r);
1939 break;
1942 if (last_o > 0)
1943 tcc_define_symbol(s, "__OPTIMIZE__", NULL);
1944 if (linker_arg.size) {
1945 r = linker_arg.data;
1946 goto arg_err;
1948 *pargc = argc - arg_start;
1949 *pargv = argv + arg_start;
1950 if (tool)
1951 return tool;
1952 if (optind != noaction)
1953 return 0;
1954 if (s->verbose == 2)
1955 return OPT_PRINT_DIRS;
1956 if (s->verbose)
1957 return OPT_V;
1958 return OPT_HELP;
1961 LIBTCCAPI void tcc_set_options(TCCState *s, const char *r)
1963 char **argv = NULL;
1964 int argc = 0;
1965 args_parser_make_argv(r, &argc, &argv);
1966 tcc_parse_args(s, &argc, &argv, 0);
1967 dynarray_reset(&argv, &argc);
1970 PUB_FUNC void tcc_print_stats(TCCState *s, unsigned total_time)
1972 if (total_time < 1)
1973 total_time = 1;
1974 if (total_bytes < 1)
1975 total_bytes = 1;
1976 fprintf(stderr, "* %d idents, %d lines, %d bytes\n"
1977 "* %0.3f s, %u lines/s, %0.1f MB/s\n",
1978 tok_ident - TOK_IDENT, total_lines, total_bytes,
1979 (double)total_time/1000,
1980 (unsigned)total_lines*1000/total_time,
1981 (double)total_bytes/1000/total_time);
1982 #ifdef MEM_DEBUG
1983 fprintf(stderr, "* %d bytes memory used\n", mem_max_size);
1984 #endif