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
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 /********************************************************/
46 #ifdef TCC_TARGET_I386
55 #ifdef TCC_TARGET_X86_64
56 #include "x86_64-gen.c"
60 #if defined TCC_TARGET_I386 || defined TCC_TARGET_X86_64
64 #ifdef TCC_TARGET_COFF
70 #endif /* ONE_SOURCE */
72 /********************************************************/
73 #ifndef CONFIG_TCC_ASM
74 ST_FUNC
void asm_instr(void)
76 tcc_error("inline asm() not supported");
78 ST_FUNC
void asm_global_instr(void)
80 tcc_error("inline asm() not supported");
84 /********************************************************/
87 static char *normalize_slashes(char *path
)
90 for (p
= path
; *p
; ++p
)
96 static HMODULE tcc_module
;
98 /* on win32, we suppose the lib and includes are at the location of 'tcc.exe' */
99 static void tcc_set_lib_path_w32(TCCState
*s
)
102 GetModuleFileNameA(tcc_module
, path
, sizeof path
);
103 p
= tcc_basename(normalize_slashes(strlwr(path
)));
104 if (p
- 5 > path
&& 0 == strncmp(p
- 5, "/bin/", 5))
109 tcc_set_lib_path(s
, path
);
112 static void tcc_add_systemdir(TCCState
*s
)
115 GetSystemDirectory(buf
, sizeof buf
);
116 tcc_add_library_path(s
, normalize_slashes(buf
));
119 #ifndef CONFIG_TCC_STATIC
120 void dlclose(void *p
)
122 FreeLibrary((HMODULE
)p
);
127 BOOL WINAPI
DllMain (HANDLE hDll
, DWORD dwReason
, LPVOID lpReserved
)
129 if (DLL_PROCESS_ATTACH
== dwReason
)
136 /********************************************************/
137 /* copy a string and truncate it. */
138 PUB_FUNC
char *pstrcpy(char *buf
, int buf_size
, const char *s
)
145 q_end
= buf
+ buf_size
- 1;
157 /* strcat and truncate. */
158 PUB_FUNC
char *pstrcat(char *buf
, int buf_size
, const char *s
)
163 pstrcpy(buf
+ len
, buf_size
- len
, s
);
167 PUB_FUNC
char *pstrncpy(char *out
, const char *in
, size_t num
)
169 memcpy(out
, in
, num
);
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]))
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 */
204 unsigned malloc_usable_size(void*);
207 PUB_FUNC
void tcc_free(void *ptr
)
210 mem_cur_size
-= malloc_usable_size(ptr
);
215 PUB_FUNC
void *tcc_malloc(unsigned long size
)
220 tcc_error("memory full");
222 mem_cur_size
+= malloc_usable_size(ptr
);
223 if (mem_cur_size
> mem_max_size
)
224 mem_max_size
= mem_cur_size
;
229 PUB_FUNC
void *tcc_mallocz(unsigned long size
)
232 ptr
= tcc_malloc(size
);
233 memset(ptr
, 0, size
);
237 PUB_FUNC
void *tcc_realloc(void *ptr
, unsigned long size
)
241 mem_cur_size
-= malloc_usable_size(ptr
);
243 ptr1
= realloc(ptr
, size
);
245 tcc_error("memory full");
247 /* NOTE: count not correct if alloc error, but not critical */
248 mem_cur_size
+= malloc_usable_size(ptr1
);
249 if (mem_cur_size
> mem_max_size
)
250 mem_max_size
= mem_cur_size
;
255 PUB_FUNC
char *tcc_strdup(const char *str
)
258 ptr
= tcc_malloc(strlen(str
) + 1);
263 PUB_FUNC
void tcc_memstats(void)
266 printf("memory in use: %d\n", mem_cur_size
);
270 #define free(p) use_tcc_free(p)
271 #define malloc(s) use_tcc_malloc(s)
272 #define realloc(p, s) use_tcc_realloc(p, s)
274 /********************************************************/
277 PUB_FUNC
void dynarray_add(void ***ptab
, int *nb_ptr
, void *data
)
284 /* every power of two we double array size */
285 if ((nb
& (nb
- 1)) == 0) {
290 pp
= tcc_realloc(pp
, nb_alloc
* sizeof(void *));
297 PUB_FUNC
void dynarray_reset(void *pp
, int *n
)
300 for (p
= *(void***)pp
; *n
; ++p
, --*n
)
303 tcc_free(*(void**)pp
);
307 static void tcc_split_path(TCCState
*s
, void ***p_ary
, int *p_nb_ary
, const char *in
)
315 for (p
= in
; c
= *p
, c
!= '\0' && c
!= PATHSEP
; ++p
) {
316 if (c
== '{' && p
[1] && p
[2] == '}') {
319 cstr_cat(&str
, s
->tcc_lib_path
);
324 cstr_ccat(&str
, '\0');
330 if (realpath(str
.data
, tmp
)) {
333 cstr_ccat(&str
, '\0');
337 for (i
= 0; i
< *p_nb_ary
&& do_include
; i
++) {
338 do_include
= do_include
&&
339 strcmp((char*)str
.data
, (char*)(*p_ary
)[i
]);
343 dynarray_add(p_ary
, p_nb_ary
, str
.data
);
347 dynarray_add(p_ary
, p_nb_ary
, str
.data
);
353 /********************************************************/
355 ST_FUNC Section
*new_section(TCCState
*s1
, const char *name
, int sh_type
, int sh_flags
)
359 sec
= tcc_mallocz(sizeof(Section
) + strlen(name
));
360 strcpy(sec
->name
, name
);
361 sec
->sh_type
= sh_type
;
362 sec
->sh_flags
= sh_flags
;
370 sec
->sh_addralign
= 4;
373 sec
->sh_addralign
= 1;
376 sec
->sh_addralign
= 32; /* default conservative alignment */
380 if (sh_flags
& SHF_PRIVATE
) {
381 dynarray_add((void ***)&s1
->priv_sections
, &s1
->nb_priv_sections
, sec
);
383 sec
->sh_num
= s1
->nb_sections
;
384 dynarray_add((void ***)&s1
->sections
, &s1
->nb_sections
, sec
);
390 static void free_section(Section
*s
)
395 /* realloc section and set its content to zero */
396 ST_FUNC
void section_realloc(Section
*sec
, unsigned long new_size
)
401 size
= sec
->data_allocated
;
404 while (size
< new_size
)
406 data
= tcc_realloc(sec
->data
, size
);
407 memset(data
+ sec
->data_allocated
, 0, size
- sec
->data_allocated
);
409 sec
->data_allocated
= size
;
412 /* reserve at least 'size' bytes in section 'sec' from
414 ST_FUNC
void *section_ptr_add(Section
*sec
, unsigned long size
)
416 unsigned long offset
, offset1
;
418 offset
= sec
->data_offset
;
419 offset1
= offset
+ size
;
420 if (offset1
> sec
->data_allocated
)
421 section_realloc(sec
, offset1
);
422 sec
->data_offset
= offset1
;
423 return sec
->data
+ offset
;
426 /* reserve at least 'size' bytes from section start */
427 ST_FUNC
void section_reserve(Section
*sec
, unsigned long size
)
429 if (size
> sec
->data_allocated
)
430 section_realloc(sec
, size
);
431 if (size
> sec
->data_offset
)
432 sec
->data_offset
= size
;
435 /* return a reference to a section, and create it if it does not
437 ST_FUNC Section
*find_section(TCCState
*s1
, const char *name
)
441 for(i
= 1; i
< s1
->nb_sections
; i
++) {
442 sec
= s1
->sections
[i
];
443 if (!strcmp(name
, sec
->name
))
446 /* sections are created as PROGBITS */
447 return new_section(s1
, name
, SHT_PROGBITS
, SHF_ALLOC
);
450 /* update sym->c so that it points to an external symbol in section
451 'section' with value 'value' */
452 ST_FUNC
void put_extern_sym2(Sym
*sym
, Section
*section
,
453 uplong value
, unsigned long size
,
454 int can_add_underscore
)
456 int sym_type
, sym_bind
, sh_num
, info
, other
;
463 else if (section
== SECTION_ABS
)
466 sh_num
= section
->sh_num
;
468 if ((sym
->type
.t
& VT_BTYPE
) == VT_FUNC
) {
470 } else if ((sym
->type
.t
& VT_BTYPE
) == VT_VOID
) {
471 sym_type
= STT_NOTYPE
;
473 sym_type
= STT_OBJECT
;
476 if (sym
->type
.t
& VT_STATIC
)
477 sym_bind
= STB_LOCAL
;
479 if (sym
->type
.t
& VT_WEAK
)
482 sym_bind
= STB_GLOBAL
;
486 name
= get_tok_str(sym
->v
, NULL
);
487 #ifdef CONFIG_TCC_BCHECK
488 if (tcc_state
->do_bounds_check
) {
491 /* XXX: avoid doing that for statics ? */
492 /* if bound checking is activated, we change some function
493 names by adding the "__bound" prefix */
496 /* XXX: we rely only on malloc hooks */
509 strcpy(buf
, "__bound_");
519 if (sym
->type
.t
& VT_EXPORT
)
521 if (sym_type
== STT_FUNC
&& sym
->type
.ref
) {
522 int attr
= sym
->type
.ref
->r
;
523 if (FUNC_EXPORT(attr
))
525 if (FUNC_CALL(attr
) == FUNC_STDCALL
&& can_add_underscore
) {
526 sprintf(buf1
, "_%s@%d", name
, FUNC_ARGS(attr
) * PTR_SIZE
);
529 can_add_underscore
= 0;
532 if (find_elf_sym(tcc_state
->dynsymtab_section
, name
))
534 if (sym
->type
.t
& VT_IMPORT
)
538 if (tcc_state
->leading_underscore
&& can_add_underscore
) {
540 pstrcpy(buf1
+ 1, sizeof(buf1
) - 1, name
);
543 if (sym
->asm_label
) {
544 name
= sym
->asm_label
;
546 info
= ELFW(ST_INFO
)(sym_bind
, sym_type
);
547 sym
->c
= add_elf_sym(symtab_section
, value
, size
, info
, other
, sh_num
, name
);
549 esym
= &((ElfW(Sym
) *)symtab_section
->data
)[sym
->c
];
550 esym
->st_value
= value
;
551 esym
->st_size
= size
;
552 esym
->st_shndx
= sh_num
;
556 ST_FUNC
void put_extern_sym(Sym
*sym
, Section
*section
,
557 uplong value
, unsigned long size
)
559 put_extern_sym2(sym
, section
, value
, size
, 1);
562 /* add a new relocation entry to symbol 'sym' in section 's' */
563 ST_FUNC
void greloc(Section
*s
, Sym
*sym
, unsigned long offset
, int type
)
568 put_extern_sym(sym
, NULL
, 0, 0);
571 /* now we can add ELF relocation info */
572 put_elf_reloc(symtab_section
, s
, offset
, type
, c
);
575 /********************************************************/
577 static void strcat_vprintf(char *buf
, int buf_size
, const char *fmt
, va_list ap
)
581 vsnprintf(buf
+ len
, buf_size
- len
, fmt
, ap
);
584 static void strcat_printf(char *buf
, int buf_size
, const char *fmt
, ...)
588 strcat_vprintf(buf
, buf_size
, fmt
, ap
);
592 static void error1(TCCState
*s1
, int is_warning
, const char *fmt
, va_list ap
)
599 for(f
= s1
->include_stack
; f
< s1
->include_stack_ptr
; f
++)
600 strcat_printf(buf
, sizeof(buf
), "In file included from %s:%d:\n",
601 (*f
)->filename
, (*f
)->line_num
);
602 if (file
->line_num
> 0) {
603 strcat_printf(buf
, sizeof(buf
),
604 "%s:%d: ", file
->filename
, file
->line_num
);
606 strcat_printf(buf
, sizeof(buf
),
607 "%s: ", file
->filename
);
610 strcat_printf(buf
, sizeof(buf
),
614 strcat_printf(buf
, sizeof(buf
), "warning: ");
616 strcat_printf(buf
, sizeof(buf
), "error: ");
617 strcat_vprintf(buf
, sizeof(buf
), fmt
, ap
);
619 if (!s1
->error_func
) {
620 /* default case: stderr */
621 fprintf(stderr
, "%s\n", buf
);
623 s1
->error_func(s1
->error_opaque
, buf
);
625 if (!is_warning
|| s1
->warn_error
)
629 LIBTCCAPI
void tcc_set_error_func(TCCState
*s
, void *error_opaque
,
630 void (*error_func
)(void *opaque
, const char *msg
))
632 s
->error_opaque
= error_opaque
;
633 s
->error_func
= error_func
;
636 /* error without aborting current compilation */
637 PUB_FUNC
void tcc_error_noabort(const char *fmt
, ...)
639 TCCState
*s1
= tcc_state
;
643 error1(s1
, 0, fmt
, ap
);
647 PUB_FUNC
void tcc_error(const char *fmt
, ...)
649 TCCState
*s1
= tcc_state
;
653 error1(s1
, 0, fmt
, ap
);
655 /* better than nothing: in some cases, we accept to handle errors */
656 if (s1
->error_set_jmp_enabled
) {
657 longjmp(s1
->error_jmp_buf
, 1);
659 /* XXX: eliminate this someday */
664 PUB_FUNC
void tcc_warning(const char *fmt
, ...)
666 TCCState
*s1
= tcc_state
;
673 error1(s1
, 1, fmt
, ap
);
677 /********************************************************/
680 ST_FUNC
void tcc_open_bf(TCCState
*s1
, const char *filename
, int initlen
)
683 int buflen
= initlen
? initlen
: IO_BUF_SIZE
;
685 bf
= tcc_malloc(sizeof(BufferedFile
) + buflen
);
686 bf
->buf_ptr
= bf
->buffer
;
687 bf
->buf_end
= bf
->buffer
+ initlen
;
688 bf
->buf_end
[0] = CH_EOB
; /* put eob symbol */
689 pstrcpy(bf
->filename
, sizeof(bf
->filename
), filename
);
691 normalize_slashes(bf
->filename
);
694 bf
->ifndef_macro
= 0;
695 bf
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
701 ST_FUNC
void tcc_close(void)
703 BufferedFile
*bf
= file
;
706 total_lines
+= bf
->line_num
;
712 ST_FUNC
int tcc_open(TCCState
*s1
, const char *filename
)
715 if (strcmp(filename
, "-") == 0)
716 fd
= 0, filename
= "stdin";
718 fd
= open(filename
, O_RDONLY
| O_BINARY
);
719 if ((s1
->verbose
== 2 && fd
>= 0) || s1
->verbose
== 3)
720 printf("%s %*s%s\n", fd
< 0 ? "nf":"->",
721 (int)(s1
->include_stack_ptr
- s1
->include_stack
), "", filename
);
725 tcc_open_bf(s1
, filename
, 0);
730 /* compile the C file opened in 'file'. Return non zero if errors. */
731 static int tcc_compile(TCCState
*s1
)
736 volatile int section_sym
;
739 printf("%s: **** new file\n", file
->filename
);
743 cur_text_section
= NULL
;
745 anon_sym
= SYM_FIRST_ANOM
;
747 /* file info: full path + filename */
748 section_sym
= 0; /* avoid warning */
750 section_sym
= put_elf_sym(symtab_section
, 0, 0,
751 ELFW(ST_INFO
)(STB_LOCAL
, STT_SECTION
), 0,
752 text_section
->sh_num
, NULL
);
753 getcwd(buf
, sizeof(buf
));
755 normalize_slashes(buf
);
757 pstrcat(buf
, sizeof(buf
), "/");
758 put_stabs_r(buf
, N_SO
, 0, 0,
759 text_section
->data_offset
, text_section
, section_sym
);
760 put_stabs_r(file
->filename
, N_SO
, 0, 0,
761 text_section
->data_offset
, text_section
, section_sym
);
763 /* an elf symbol of type STT_FILE must be put so that STB_LOCAL
764 symbols can be safely used */
765 put_elf_sym(symtab_section
, 0, 0,
766 ELFW(ST_INFO
)(STB_LOCAL
, STT_FILE
), 0,
767 SHN_ABS
, file
->filename
);
769 /* define some often used types */
772 char_pointer_type
.t
= VT_BYTE
;
773 mk_pointer(&char_pointer_type
);
776 size_type
.t
= VT_INT
;
778 size_type
.t
= VT_LLONG
;
781 func_old_type
.t
= VT_FUNC
;
782 func_old_type
.ref
= sym_push(SYM_FIELD
, &int_type
, FUNC_CDECL
, FUNC_OLD
);
784 #if defined(TCC_ARM_EABI) && defined(TCC_ARM_VFP)
785 float_type
.t
= VT_FLOAT
;
786 double_type
.t
= VT_DOUBLE
;
788 func_float_type
.t
= VT_FUNC
;
789 func_float_type
.ref
= sym_push(SYM_FIELD
, &float_type
, FUNC_CDECL
, FUNC_OLD
);
790 func_double_type
.t
= VT_FUNC
;
791 func_double_type
.ref
= sym_push(SYM_FIELD
, &double_type
, FUNC_CDECL
, FUNC_OLD
);
795 /* define 'void *alloca(unsigned int)' builtin function */
800 sym
= sym_push(p
, mk_pointer(VT_VOID
), FUNC_CDECL
, FUNC_NEW
);
801 s1
= sym_push(SYM_FIELD
, VT_UNSIGNED
| VT_INT
, 0, 0);
804 sym_push(TOK_alloca
, VT_FUNC
| (p
<< VT_STRUCT_SHIFT
), VT_CONST
, 0);
808 define_start
= define_stack
;
811 if (setjmp(s1
->error_jmp_buf
) == 0) {
813 s1
->error_set_jmp_enabled
= 1;
815 ch
= file
->buf_ptr
[0];
816 tok_flags
= TOK_FLAG_BOL
| TOK_FLAG_BOF
;
817 parse_flags
= PARSE_FLAG_PREPROCESS
| PARSE_FLAG_TOK_NUM
;
822 expect("declaration");
824 tcc_warning("internal compiler error: vstack leak? (%d)", vtop
- pvtop
);
826 /* end of translation unit info */
828 put_stabs_r(NULL
, N_SO
, 0, 0,
829 text_section
->data_offset
, text_section
, section_sym
);
833 s1
->error_set_jmp_enabled
= 0;
835 /* reset define stack, but leave -Dsymbols (may be incorrect if
836 they are undefined) */
837 free_defines(define_start
);
839 gen_inline_functions();
841 sym_pop(&global_stack
, NULL
);
842 sym_pop(&local_stack
, NULL
);
844 return s1
->nb_errors
!= 0 ? -1 : 0;
847 LIBTCCAPI
int tcc_compile_string(TCCState
*s
, const char *str
)
852 tcc_open_bf(s
, "<string>", len
);
853 memcpy(file
->buffer
, str
, len
);
854 ret
= tcc_compile(s
);
859 /* define a preprocessor symbol. A value can also be provided with the '=' operator */
860 LIBTCCAPI
void tcc_define_symbol(TCCState
*s1
, const char *sym
, const char *value
)
867 len2
= strlen(value
);
869 /* init file structure */
870 tcc_open_bf(s1
, "<define>", len1
+ len2
+ 1);
871 memcpy(file
->buffer
, sym
, len1
);
872 file
->buffer
[len1
] = ' ';
873 memcpy(file
->buffer
+ len1
+ 1, value
, len2
);
875 /* parse with define parser */
876 ch
= file
->buf_ptr
[0];
883 /* undefine a preprocessor symbol */
884 LIBTCCAPI
void tcc_undefine_symbol(TCCState
*s1
, const char *sym
)
888 ts
= tok_alloc(sym
, strlen(sym
));
889 s
= define_find(ts
->tok
);
890 /* undefine symbol by putting an invalid name */
895 static void tcc_cleanup(void)
899 if (NULL
== tcc_state
)
903 /* free -D defines */
907 n
= tok_ident
- TOK_IDENT
;
908 for(i
= 0; i
< n
; i
++)
909 tcc_free(table_ident
[i
]);
910 tcc_free(table_ident
);
913 dynarray_reset(&sym_pools
, &nb_sym_pools
);
916 /* reset symbol stack */
917 sym_free_first
= NULL
;
918 /* cleanup from error/setjmp */
922 LIBTCCAPI TCCState
*tcc_new(void)
930 s
= tcc_mallocz(sizeof(TCCState
));
935 tcc_set_lib_path_w32(s
);
937 tcc_set_lib_path(s
, CONFIG_TCCDIR
);
939 s
->output_type
= TCC_OUTPUT_MEMORY
;
941 s
->include_stack_ptr
= s
->include_stack
;
943 /* we add dummy defines for some special macros to speed up tests
944 and to have working defined() */
945 define_push(TOK___LINE__
, MACRO_OBJ
, NULL
, NULL
);
946 define_push(TOK___FILE__
, MACRO_OBJ
, NULL
, NULL
);
947 define_push(TOK___DATE__
, MACRO_OBJ
, NULL
, NULL
);
948 define_push(TOK___TIME__
, MACRO_OBJ
, NULL
, NULL
);
950 /* standard defines */
951 tcc_define_symbol(s
, "__STDC__", NULL
);
952 tcc_define_symbol(s
, "__STDC_VERSION__", "199901L");
953 #if defined(TCC_TARGET_I386)
954 tcc_define_symbol(s
, "__i386__", NULL
);
955 tcc_define_symbol(s
, "__i386", NULL
);
956 tcc_define_symbol(s
, "i386", NULL
);
958 #if defined(TCC_TARGET_X86_64)
959 tcc_define_symbol(s
, "__x86_64__", NULL
);
961 #if defined(TCC_TARGET_ARM)
962 tcc_define_symbol(s
, "__ARM_ARCH_4__", NULL
);
963 tcc_define_symbol(s
, "__arm_elf__", NULL
);
964 tcc_define_symbol(s
, "__arm_elf", NULL
);
965 tcc_define_symbol(s
, "arm_elf", NULL
);
966 tcc_define_symbol(s
, "__arm__", NULL
);
967 tcc_define_symbol(s
, "__arm", NULL
);
968 tcc_define_symbol(s
, "arm", NULL
);
969 tcc_define_symbol(s
, "__APCS_32__", NULL
);
972 tcc_define_symbol(s
, "_WIN32", NULL
);
973 #ifdef TCC_TARGET_X86_64
974 tcc_define_symbol(s
, "_WIN64", NULL
);
977 tcc_define_symbol(s
, "__unix__", NULL
);
978 tcc_define_symbol(s
, "__unix", NULL
);
979 tcc_define_symbol(s
, "unix", NULL
);
980 #if defined(__FreeBSD__)
982 tcc_define_symbol(s
, "__FreeBSD__", str( __FreeBSD__
));
985 #if defined(__FreeBSD_kernel__)
986 tcc_define_symbol(s
, "__FreeBSD_kernel__", NULL
);
989 tcc_define_symbol(s
, "__linux__", NULL
);
990 tcc_define_symbol(s
, "__linux", NULL
);
993 /* tiny C specific defines */
994 sscanf(TCC_VERSION
, "%d.%d.%d", &a
, &b
, &c
);
995 sprintf(buffer
, "%d", a
*10000 + b
*100 + c
);
996 tcc_define_symbol(s
, "__TINYC__", buffer
);
998 /* tiny C & gcc defines */
999 #if defined TCC_TARGET_PE && defined TCC_TARGET_X86_64
1000 tcc_define_symbol(s
, "__SIZE_TYPE__", "unsigned long long");
1001 tcc_define_symbol(s
, "__PTRDIFF_TYPE__", "long long");
1003 tcc_define_symbol(s
, "__SIZE_TYPE__", "unsigned long");
1004 tcc_define_symbol(s
, "__PTRDIFF_TYPE__", "long");
1007 #ifdef TCC_TARGET_PE
1008 tcc_define_symbol(s
, "__WCHAR_TYPE__", "unsigned short");
1010 tcc_define_symbol(s
, "__WCHAR_TYPE__", "int");
1014 tcc_define_symbol(s
, "__REDIRECT(name, proto, alias)", "name proto __asm__ (#alias)");
1015 tcc_define_symbol(s
, "__REDIRECT_NTH(name, proto, alias)", "name proto __asm__ (#alias) __THROW");
1017 #ifndef TCC_TARGET_PE
1018 /* default library paths */
1019 tcc_add_library_path(s
, CONFIG_TCC_LIBPATHS
);
1020 /* paths for crt objects */
1021 tcc_split_path(s
, (void ***)&s
->crt_paths
, &s
->nb_crt_paths
, CONFIG_TCC_CRTPREFIX
);
1024 /* no section zero */
1025 dynarray_add((void ***)&s
->sections
, &s
->nb_sections
, NULL
);
1027 /* create standard sections */
1028 text_section
= new_section(s
, ".text", SHT_PROGBITS
, SHF_ALLOC
| SHF_EXECINSTR
);
1029 data_section
= new_section(s
, ".data", SHT_PROGBITS
, SHF_ALLOC
| SHF_WRITE
);
1030 bss_section
= new_section(s
, ".bss", SHT_NOBITS
, SHF_ALLOC
| SHF_WRITE
);
1032 /* symbols are always generated for linking stage */
1033 symtab_section
= new_symtab(s
, ".symtab", SHT_SYMTAB
, 0,
1035 ".hashtab", SHF_PRIVATE
);
1036 strtab_section
= symtab_section
->link
;
1037 s
->symtab
= symtab_section
;
1039 /* private symbol table for dynamic symbols */
1040 s
->dynsymtab_section
= new_symtab(s
, ".dynsymtab", SHT_SYMTAB
, SHF_PRIVATE
,
1042 ".dynhashtab", SHF_PRIVATE
);
1043 s
->alacarte_link
= 1;
1046 #ifdef CHAR_IS_UNSIGNED
1047 s
->char_is_unsigned
= 1;
1049 /* enable this if you want symbols with leading underscore on windows: */
1050 #if defined(TCC_TARGET_PE) && 0
1051 s
->leading_underscore
= 1;
1053 if (s
->section_align
== 0)
1054 s
->section_align
= ELF_PAGE_SIZE
;
1055 #ifdef TCC_TARGET_I386
1061 LIBTCCAPI
void tcc_delete(TCCState
*s1
)
1067 /* free all sections */
1068 for(i
= 1; i
< s1
->nb_sections
; i
++)
1069 free_section(s1
->sections
[i
]);
1070 dynarray_reset(&s1
->sections
, &s1
->nb_sections
);
1072 for(i
= 0; i
< s1
->nb_priv_sections
; i
++)
1073 free_section(s1
->priv_sections
[i
]);
1074 dynarray_reset(&s1
->priv_sections
, &s1
->nb_priv_sections
);
1076 /* free any loaded DLLs */
1077 for ( i
= 0; i
< s1
->nb_loaded_dlls
; i
++) {
1078 DLLReference
*ref
= s1
->loaded_dlls
[i
];
1080 dlclose(ref
->handle
);
1083 /* free loaded dlls array */
1084 dynarray_reset(&s1
->loaded_dlls
, &s1
->nb_loaded_dlls
);
1086 /* free library paths */
1087 dynarray_reset(&s1
->library_paths
, &s1
->nb_library_paths
);
1088 dynarray_reset(&s1
->crt_paths
, &s1
->nb_crt_paths
);
1090 /* free include paths */
1091 dynarray_reset(&s1
->cached_includes
, &s1
->nb_cached_includes
);
1092 dynarray_reset(&s1
->include_paths
, &s1
->nb_include_paths
);
1093 dynarray_reset(&s1
->sysinclude_paths
, &s1
->nb_sysinclude_paths
);
1095 dynarray_reset(&s1
->target_deps
, &s1
->nb_target_deps
);
1097 tcc_free(s1
->tcc_lib_path
);
1100 munmap (s1
->write_mem
, s1
->mem_size
);
1101 munmap (s1
->runtime_mem
, s1
->mem_size
);
1103 tcc_free(s1
->runtime_mem
);
1108 LIBTCCAPI
int tcc_add_include_path(TCCState
*s
, const char *pathname
)
1110 tcc_split_path(s
, (void ***)&s
->include_paths
, &s
->nb_include_paths
, pathname
);
1114 LIBTCCAPI
int tcc_add_sysinclude_path(TCCState
*s
, const char *pathname
)
1116 tcc_split_path(s
, (void ***)&s
->sysinclude_paths
, &s
->nb_sysinclude_paths
, pathname
);
1120 ST_FUNC
int tcc_add_file_internal(TCCState
*s1
, const char *filename
, int flags
)
1126 /* find source file type with extension */
1127 ext
= tcc_fileextension(filename
);
1131 #ifdef CONFIG_TCC_ASM
1132 /* if .S file, define __ASSEMBLER__ like gcc does */
1133 if (!strcmp(ext
, "S"))
1134 tcc_define_symbol(s1
, "__ASSEMBLER__", NULL
);
1138 ret
= tcc_open(s1
, filename
);
1140 if (flags
& AFF_PRINT_ERROR
)
1141 tcc_error_noabort("file '%s' not found", filename
);
1145 /* update target deps */
1146 dynarray_add((void ***)&s1
->target_deps
, &s1
->nb_target_deps
,
1147 tcc_strdup(filename
));
1149 if (flags
& AFF_PREPROCESS
) {
1150 ret
= tcc_preprocess(s1
);
1154 if (!ext
[0] || !PATHCMP(ext
, "c")) {
1155 /* C file assumed */
1156 ret
= tcc_compile(s1
);
1160 #ifdef CONFIG_TCC_ASM
1161 if (!strcmp(ext
, "S")) {
1162 /* preprocessed assembler */
1163 ret
= tcc_assemble(s1
, 1);
1167 if (!strcmp(ext
, "s")) {
1168 /* non preprocessed assembler */
1169 ret
= tcc_assemble(s1
, 0);
1175 /* assume executable format: auto guess file type */
1176 size
= read(fd
, &ehdr
, sizeof(ehdr
));
1177 lseek(fd
, 0, SEEK_SET
);
1179 tcc_error_noabort("could not read header");
1183 if (size
== sizeof(ehdr
) &&
1184 ehdr
.e_ident
[0] == ELFMAG0
&&
1185 ehdr
.e_ident
[1] == ELFMAG1
&&
1186 ehdr
.e_ident
[2] == ELFMAG2
&&
1187 ehdr
.e_ident
[3] == ELFMAG3
) {
1189 /* do not display line number if error */
1191 if (ehdr
.e_type
== ET_REL
) {
1192 ret
= tcc_load_object_file(s1
, fd
, 0);
1196 #ifndef TCC_TARGET_PE
1197 if (ehdr
.e_type
== ET_DYN
) {
1198 if (s1
->output_type
== TCC_OUTPUT_MEMORY
) {
1200 h
= dlopen(filename
, RTLD_GLOBAL
| RTLD_LAZY
);
1204 ret
= tcc_load_dll(s1
, fd
, filename
,
1205 (flags
& AFF_REFERENCED_DLL
) != 0);
1210 tcc_error_noabort("unrecognized ELF file");
1214 if (memcmp((char *)&ehdr
, ARMAG
, 8) == 0) {
1215 file
->line_num
= 0; /* do not display line number if error */
1216 ret
= tcc_load_archive(s1
, fd
);
1220 #ifdef TCC_TARGET_COFF
1221 if (*(uint16_t *)(&ehdr
) == COFF_C67_MAGIC
) {
1222 ret
= tcc_load_coff(s1
, fd
);
1227 #ifdef TCC_TARGET_PE
1228 ret
= pe_load_file(s1
, filename
, fd
);
1230 /* as GNU ld, consider it is an ld script if not recognized */
1231 ret
= tcc_load_ldscript(s1
);
1234 tcc_error_noabort("unrecognized file type");
1241 LIBTCCAPI
int tcc_add_file(TCCState
*s
, const char *filename
)
1243 if (s
->output_type
== TCC_OUTPUT_PREPROCESS
)
1244 return tcc_add_file_internal(s
, filename
, AFF_PRINT_ERROR
| AFF_PREPROCESS
);
1246 return tcc_add_file_internal(s
, filename
, AFF_PRINT_ERROR
);
1249 LIBTCCAPI
int tcc_add_library_path(TCCState
*s
, const char *pathname
)
1251 tcc_split_path(s
, (void ***)&s
->library_paths
, &s
->nb_library_paths
, pathname
);
1255 static int tcc_add_library_internal(TCCState
*s
, const char *fmt
,
1256 const char *filename
, int flags
, char **paths
, int nb_paths
)
1261 for(i
= 0; i
< nb_paths
; i
++) {
1262 snprintf(buf
, sizeof(buf
), fmt
, paths
[i
], filename
);
1263 if (tcc_add_file_internal(s
, buf
, flags
) == 0)
1269 #ifndef TCC_TARGET_PE
1270 /* find and load a dll. Return non zero if not found */
1271 /* XXX: add '-rpath' option support ? */
1272 ST_FUNC
int tcc_add_dll(TCCState
*s
, const char *filename
, int flags
)
1274 return tcc_add_library_internal(s
, "%s/%s", filename
, flags
,
1275 s
->library_paths
, s
->nb_library_paths
);
1279 ST_FUNC
int tcc_add_crt(TCCState
*s
, const char *filename
)
1281 if (-1 == tcc_add_library_internal(s
, "%s/%s",
1282 filename
, 0, s
->crt_paths
, s
->nb_crt_paths
))
1283 tcc_error_noabort("file '%s' not found", filename
);
1287 /* the library name is the same as the argument of the '-l' option */
1288 LIBTCCAPI
int tcc_add_library(TCCState
*s
, const char *libraryname
)
1290 #ifdef TCC_TARGET_PE
1291 const char *libs
[] = { "%s/%s.def", "%s/lib%s.def", "%s/%s.dll", "%s/lib%s.dll", "%s/lib%s.a", NULL
};
1292 const char **pp
= s
->static_link
? libs
+ 4 : libs
;
1294 const char *libs
[] = { "%s/lib%s.so", "%s/lib%s.a", NULL
};
1295 const char **pp
= s
->static_link
? libs
+ 1 : libs
;
1298 if (0 == tcc_add_library_internal(s
, *pp
,
1299 libraryname
, 0, s
->library_paths
, s
->nb_library_paths
))
1306 LIBTCCAPI
int tcc_add_symbol(TCCState
*s
, const char *name
, const void *val
)
1308 #ifdef TCC_TARGET_PE
1309 pe_putimport(s
, 0, name
, val
);
1311 add_elf_sym(symtab_section
, (uplong
)val
, 0,
1312 ELFW(ST_INFO
)(STB_GLOBAL
, STT_NOTYPE
), 0,
1318 LIBTCCAPI
int tcc_set_output_type(TCCState
*s
, int output_type
)
1320 s
->output_type
= output_type
;
1323 /* default include paths */
1324 /* -isystem paths have already been handled */
1325 tcc_add_sysinclude_path(s
, CONFIG_TCC_SYSINCLUDEPATHS
);
1328 /* if bound checking, then add corresponding sections */
1329 #ifdef CONFIG_TCC_BCHECK
1330 if (s
->do_bounds_check
) {
1332 tcc_define_symbol(s
, "__BOUNDS_CHECKING_ON", NULL
);
1333 /* create bounds sections */
1334 bounds_section
= new_section(s
, ".bounds",
1335 SHT_PROGBITS
, SHF_ALLOC
);
1336 lbounds_section
= new_section(s
, ".lbounds",
1337 SHT_PROGBITS
, SHF_ALLOC
);
1341 if (s
->char_is_unsigned
) {
1342 tcc_define_symbol(s
, "__CHAR_UNSIGNED__", NULL
);
1345 /* add debug sections */
1348 stab_section
= new_section(s
, ".stab", SHT_PROGBITS
, 0);
1349 stab_section
->sh_entsize
= sizeof(Stab_Sym
);
1350 stabstr_section
= new_section(s
, ".stabstr", SHT_STRTAB
, 0);
1351 put_elf_str(stabstr_section
, "");
1352 stab_section
->link
= stabstr_section
;
1353 /* put first entry */
1354 put_stabs("", 0, 0, 0, 0);
1357 #ifdef TCC_TARGET_PE
1358 tcc_add_library_path(s
, CONFIG_TCC_LIBPATHS
);
1360 tcc_add_systemdir(s
);
1363 /* add libc crt1/crti objects */
1364 if ((output_type
== TCC_OUTPUT_EXE
|| output_type
== TCC_OUTPUT_DLL
) &&
1366 if (output_type
!= TCC_OUTPUT_DLL
)
1367 tcc_add_crt(s
, "crt1.o");
1368 tcc_add_crt(s
, "crti.o");
1374 #define WD_ALL 0x0001 /* warning is activated when using -Wall */
1375 #define FD_INVERT 0x0002 /* invert value before storing */
1377 typedef struct FlagDef
{
1383 static const FlagDef warning_defs
[] = {
1384 { offsetof(TCCState
, warn_unsupported
), 0, "unsupported" },
1385 { offsetof(TCCState
, warn_write_strings
), 0, "write-strings" },
1386 { offsetof(TCCState
, warn_error
), 0, "error" },
1387 { offsetof(TCCState
, warn_implicit_function_declaration
), WD_ALL
,
1388 "implicit-function-declaration" },
1391 ST_FUNC
int set_flag(TCCState
*s
, const FlagDef
*flags
, int nb_flags
,
1392 const char *name
, int value
)
1399 if (r
[0] == 'n' && r
[1] == 'o' && r
[2] == '-') {
1403 for(i
= 0, p
= flags
; i
< nb_flags
; i
++, p
++) {
1404 if (!strcmp(r
, p
->name
))
1409 if (p
->flags
& FD_INVERT
)
1411 *(int *)((uint8_t *)s
+ p
->offset
) = value
;
1416 LIBTCCAPI
void tcc_enable_debug(TCCState
*s
)
1421 /* set/reset a warning */
1422 LIBTCCAPI
int tcc_set_warning(TCCState
*s
, const char *warning_name
, int value
)
1427 if (!strcmp(warning_name
, "all")) {
1428 for(i
= 0, p
= warning_defs
; i
< countof(warning_defs
); i
++, p
++) {
1429 if (p
->flags
& WD_ALL
)
1430 *(int *)((uint8_t *)s
+ p
->offset
) = 1;
1434 return set_flag(s
, warning_defs
, countof(warning_defs
),
1435 warning_name
, value
);
1439 static const FlagDef flag_defs
[] = {
1440 { offsetof(TCCState
, char_is_unsigned
), 0, "unsigned-char" },
1441 { offsetof(TCCState
, char_is_unsigned
), FD_INVERT
, "signed-char" },
1442 { offsetof(TCCState
, nocommon
), FD_INVERT
, "common" },
1443 { offsetof(TCCState
, leading_underscore
), 0, "leading-underscore" },
1446 /* set/reset a flag */
1447 PUB_FUNC
int tcc_set_flag(TCCState
*s
, const char *flag_name
, int value
)
1449 return set_flag(s
, flag_defs
, countof(flag_defs
),
1454 static int strstart(const char *str
, const char *val
, char **ptr
)
1459 while (*q
!= '\0') {
1471 /* Like strstart, but automatically takes into account that ld options can
1473 * - start with double or single dash (e.g. '--soname' or '-soname')
1474 * - arguments can be given as separate or after '=' (e.g. '-Wl,-soname,x.so'
1475 * or '-Wl,-soname=x.so')
1477 * you provide `val` always in 'option[=]' form (no leading -)
1479 static int link_option(const char *str
, const char *val
, char **ptr
)
1483 /* there should be 1 or 2 dashes */
1489 /* then str & val should match (potentialy up to '=') */
1493 while (*q
!= '\0' && *q
!= '=') {
1500 /* '=' near eos means ',' or '=' is ok */
1502 if (*p
!= ',' && *p
!= '=')
1514 /* set linker options */
1515 PUB_FUNC
const char * tcc_set_linker(TCCState
*s
, char *option
, int multi
)
1520 while (option
&& *option
) {
1522 if (link_option(option
, "Bsymbolic", &p
)) {
1524 } else if (link_option(option
, "nostdlib", &p
)) {
1526 } else if (link_option(option
, "fini=", &p
)) {
1528 if (s
->warn_unsupported
)
1529 tcc_warning("ignoring -fini %s", p
);
1530 } else if (link_option(option
, "image-base=", &p
)) {
1531 s
->text_addr
= strtoull(p
, &end
, 16);
1532 s
->has_text_addr
= 1;
1533 } else if (link_option(option
, "init=", &p
)) {
1535 if (s
->warn_unsupported
)
1536 tcc_warning("ignoring -init %s", p
);
1537 } else if (link_option(option
, "oformat=", &p
)) {
1538 #if defined(TCC_TARGET_PE)
1539 if (strstart(p
, "pe-", NULL
)) {
1541 #if defined(TCC_TARGET_X86_64)
1542 if (strstart(p
, "elf64-", NULL
)) {
1544 if (strstart(p
, "elf32-", NULL
)) {
1547 s
->output_format
= TCC_OUTPUT_FORMAT_ELF
;
1548 } else if (!strcmp(p
, "binary")) {
1549 s
->output_format
= TCC_OUTPUT_FORMAT_BINARY
;
1551 #ifdef TCC_TARGET_COFF
1552 if (!strcmp(p
, "coff")) {
1553 s
->output_format
= TCC_OUTPUT_FORMAT_COFF
;
1560 } else if (link_option(option
, "rpath=", &p
)) {
1562 } else if (link_option(option
, "section-alignment=", &p
)) {
1563 s
->section_align
= strtoul(p
, &end
, 16);
1564 } else if (link_option(option
, "soname=", &p
)) {
1567 #ifdef TCC_TARGET_PE
1568 } else if (link_option(option
, "file-alignment=", &p
)) {
1569 s
->pe_file_align
= strtoul(p
, &end
, 16);
1570 } else if (link_option(option
, "stack=", &p
)) {
1571 s
->pe_stack_size
= strtoul(p
, &end
, 10);
1572 } else if (link_option(option
, "subsystem=", &p
)) {
1573 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
1574 if (!strcmp(p
, "native")) {
1575 s
->pe_subsystem
= 1;
1576 } else if (!strcmp(p
, "console")) {
1577 s
->pe_subsystem
= 3;
1578 } else if (!strcmp(p
, "gui")) {
1579 s
->pe_subsystem
= 2;
1580 } else if (!strcmp(p
, "posix")) {
1581 s
->pe_subsystem
= 7;
1582 } else if (!strcmp(p
, "efiapp")) {
1583 s
->pe_subsystem
= 10;
1584 } else if (!strcmp(p
, "efiboot")) {
1585 s
->pe_subsystem
= 11;
1586 } else if (!strcmp(p
, "efiruntime")) {
1587 s
->pe_subsystem
= 12;
1588 } else if (!strcmp(p
, "efirom")) {
1589 s
->pe_subsystem
= 13;
1590 #elif defined(TCC_TARGET_ARM)
1591 if (!strcmp(p
, "wince")) {
1592 s
->pe_subsystem
= 9;
1599 } else if (link_option(option
, "Ttext=", &p
)) {
1600 s
->text_addr
= strtoull(p
, &end
, 16);
1601 s
->has_text_addr
= 1;
1603 char *comma_ptr
= strchr(option
, ',');
1611 p
= strchr( (end
) ? end
: p
, ',');
1613 *p
= 0; /* terminate last option */
1622 PUB_FUNC
void tcc_print_stats(TCCState
*s
, int64_t total_time
)
1625 tt
= (double)total_time
/ 1000000.0;
1628 if (total_bytes
< 1)
1630 printf("%d idents, %d lines, %d bytes, %0.3f s, %d lines/s, %0.1f MB/s\n",
1631 tok_ident
- TOK_IDENT
, total_lines
, total_bytes
,
1632 tt
, (int)(total_lines
/ tt
),
1633 total_bytes
/ tt
/ 1000000.0);
1636 /* set CONFIG_TCCDIR at runtime */
1637 LIBTCCAPI
void tcc_set_lib_path(TCCState
*s
, const char *path
)
1639 tcc_free(s
->tcc_lib_path
);
1640 s
->tcc_lib_path
= tcc_strdup(path
);
1643 PUB_FUNC
char *tcc_default_target(TCCState
*s
, const char *default_file
)
1647 const char *name
= "a";
1649 if (default_file
&& strcmp(default_file
, "-"))
1650 name
= tcc_basename(default_file
);
1651 pstrcpy(buf
, sizeof(buf
), name
);
1652 ext
= tcc_fileextension(buf
);
1653 #ifdef TCC_TARGET_PE
1654 if (s
->output_type
== TCC_OUTPUT_DLL
)
1655 strcpy(ext
, ".dll");
1657 if (s
->output_type
== TCC_OUTPUT_EXE
)
1658 strcpy(ext
, ".exe");
1661 if (( (s
->output_type
== TCC_OUTPUT_OBJ
&& !s
->reloc_output
) ||
1662 (s
->output_type
== TCC_OUTPUT_PREPROCESS
) )
1666 pstrcpy(buf
, sizeof(buf
), "a.out");
1668 return tcc_strdup(buf
);
1672 PUB_FUNC
void tcc_gen_makedeps(TCCState
*s
, const char *target
, const char *filename
)
1675 char buf
[1024], *ext
;
1679 /* compute filename automatically
1680 * dir/file.o -> dir/file.d */
1681 pstrcpy(buf
, sizeof(buf
), target
);
1682 ext
= tcc_fileextension(buf
);
1683 pstrcpy(ext
, sizeof(buf
) - (ext
-buf
), ".d");
1688 printf("<- %s\n", filename
);
1690 /* XXX return err codes instead of error() ? */
1691 depout
= fopen(filename
, "w");
1693 tcc_error("could not open '%s'", filename
);
1695 fprintf(depout
, "%s : \\\n", target
);
1696 for (i
=0; i
<s
->nb_target_deps
; ++i
)
1697 fprintf(depout
, " %s \\\n", s
->target_deps
[i
]);
1698 fprintf(depout
, "\n");