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 #ifdef CONFIG_TCC_BACKTRACE
36 ST_DATA
int num_callers
= 6;
37 ST_DATA
const char **rt_bound_error_msg
;
38 ST_DATA
void *rt_prog_main
;
41 /********************************************************/
48 #ifdef TCC_TARGET_I386
57 #ifdef TCC_TARGET_X86_64
58 #include "x86_64-gen.c"
62 #if defined TCC_TARGET_I386 || defined TCC_TARGET_X86_64
66 #ifdef TCC_TARGET_COFF
72 #endif /* ONE_SOURCE */
74 /********************************************************/
75 #ifndef CONFIG_TCC_ASM
76 ST_FUNC
void asm_instr(void)
78 error("inline asm() not supported");
80 ST_FUNC
void asm_global_instr(void)
82 error("inline asm() not supported");
86 /********************************************************/
89 static char *normalize_slashes(char *path
)
92 for (p
= path
; *p
; ++p
)
98 static HMODULE tcc_module
;
100 /* on win32, we suppose the lib and includes are at the location of 'tcc.exe' */
101 static void tcc_set_lib_path_w32(TCCState
*s
)
104 GetModuleFileNameA(tcc_module
, path
, sizeof path
);
105 p
= tcc_basename(normalize_slashes(strlwr(path
)));
106 if (p
- 5 > path
&& 0 == strncmp(p
- 5, "/bin/", 5))
111 tcc_set_lib_path(s
, path
);
114 static void tcc_add_systemdir(TCCState
*s
)
117 GetSystemDirectory(buf
, sizeof buf
);
118 tcc_add_library_path(s
, buf
);
121 #ifndef CONFIG_TCC_STATIC
122 void dlclose(void *p
)
124 FreeLibrary((HMODULE
)p
);
129 BOOL WINAPI
DllMain (HANDLE hDll
, DWORD dwReason
, LPVOID lpReserved
)
131 if (DLL_PROCESS_ATTACH
== dwReason
)
138 /********************************************************/
139 /* copy a string and truncate it. */
140 PUB_FUNC
char *pstrcpy(char *buf
, int buf_size
, const char *s
)
147 q_end
= buf
+ buf_size
- 1;
159 /* strcat and truncate. */
160 PUB_FUNC
char *pstrcat(char *buf
, int buf_size
, const char *s
)
165 pstrcpy(buf
+ len
, buf_size
- len
, s
);
169 PUB_FUNC
char *pstrncpy(char *out
, const char *in
, size_t num
)
171 memcpy(out
, in
, num
);
176 /* extract the basename of a file */
177 PUB_FUNC
char *tcc_basename(const char *name
)
179 char *p
= strchr(name
, 0);
180 while (p
> name
&& !IS_DIRSEP(p
[-1]))
185 /* extract extension part of a file
187 * (if no extension, return pointer to end-of-string)
189 PUB_FUNC
char *tcc_fileextension (const char *name
)
191 char *b
= tcc_basename(name
);
192 char *e
= strrchr(b
, '.');
193 return e
? e
: strchr(b
, 0);
196 /********************************************************/
197 /* memory management */
206 unsigned malloc_usable_size(void*);
209 PUB_FUNC
void tcc_free(void *ptr
)
212 mem_cur_size
-= malloc_usable_size(ptr
);
217 PUB_FUNC
void *tcc_malloc(unsigned long size
)
222 error("memory full");
224 mem_cur_size
+= malloc_usable_size(ptr
);
225 if (mem_cur_size
> mem_max_size
)
226 mem_max_size
= mem_cur_size
;
231 PUB_FUNC
void *tcc_mallocz(unsigned long size
)
234 ptr
= tcc_malloc(size
);
235 memset(ptr
, 0, size
);
239 PUB_FUNC
void *tcc_realloc(void *ptr
, unsigned long size
)
243 mem_cur_size
-= malloc_usable_size(ptr
);
245 ptr1
= realloc(ptr
, size
);
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 *));
292 error("memory full");
299 PUB_FUNC
void dynarray_reset(void *pp
, int *n
)
302 for (p
= *(void***)pp
; *n
; ++p
, --*n
)
305 tcc_free(*(void**)pp
);
309 /* out must not point to a valid dynarray since a new one is created */
310 static void tcc_split_path(TCCState
*s
, void ***p_ary
, int *p_nb_ary
, const char *in
)
314 const char *r
= NULL
;
321 if ((c
= *r
++) == 0) {
325 } else if ((c
= *p
++) == 0) {
327 } else if (c
== PATHSEP
) {
329 } else if (c
== '\b') {
337 //printf("path: %s\n", (char*)str.data);
338 dynarray_add(p_ary
, p_nb_ary
, str
.data
);
343 /********************************************************/
345 ST_FUNC Section
*new_section(TCCState
*s1
, const char *name
, int sh_type
, int sh_flags
)
349 sec
= tcc_mallocz(sizeof(Section
) + strlen(name
));
350 strcpy(sec
->name
, name
);
351 sec
->sh_type
= sh_type
;
352 sec
->sh_flags
= sh_flags
;
360 sec
->sh_addralign
= 4;
363 sec
->sh_addralign
= 1;
366 sec
->sh_addralign
= 32; /* default conservative alignment */
370 if (sh_flags
& SHF_PRIVATE
) {
371 dynarray_add((void ***)&s1
->priv_sections
, &s1
->nb_priv_sections
, sec
);
373 sec
->sh_num
= s1
->nb_sections
;
374 dynarray_add((void ***)&s1
->sections
, &s1
->nb_sections
, sec
);
380 static void free_section(Section
*s
)
385 /* realloc section and set its content to zero */
386 ST_FUNC
void section_realloc(Section
*sec
, unsigned long new_size
)
391 size
= sec
->data_allocated
;
394 while (size
< new_size
)
396 data
= tcc_realloc(sec
->data
, size
);
398 error("memory full");
399 memset(data
+ sec
->data_allocated
, 0, size
- sec
->data_allocated
);
401 sec
->data_allocated
= size
;
404 /* reserve at least 'size' bytes in section 'sec' from
406 ST_FUNC
void *section_ptr_add(Section
*sec
, unsigned long size
)
408 unsigned long offset
, offset1
;
410 offset
= sec
->data_offset
;
411 offset1
= offset
+ size
;
412 if (offset1
> sec
->data_allocated
)
413 section_realloc(sec
, offset1
);
414 sec
->data_offset
= offset1
;
415 return sec
->data
+ offset
;
418 /* reserve at least 'size' bytes from section start */
419 ST_FUNC
void section_reserve(Section
*sec
, unsigned long size
)
421 if (size
> sec
->data_allocated
)
422 section_realloc(sec
, size
);
423 if (size
> sec
->data_offset
)
424 sec
->data_offset
= size
;
427 /* return a reference to a section, and create it if it does not
429 ST_FUNC Section
*find_section(TCCState
*s1
, const char *name
)
433 for(i
= 1; i
< s1
->nb_sections
; i
++) {
434 sec
= s1
->sections
[i
];
435 if (!strcmp(name
, sec
->name
))
438 /* sections are created as PROGBITS */
439 return new_section(s1
, name
, SHT_PROGBITS
, SHF_ALLOC
);
442 /* update sym->c so that it points to an external symbol in section
443 'section' with value 'value' */
444 ST_FUNC
void put_extern_sym2(Sym
*sym
, Section
*section
,
445 unsigned long value
, unsigned long size
,
446 int can_add_underscore
)
448 int sym_type
, sym_bind
, sh_num
, info
, other
;
455 else if (section
== SECTION_ABS
)
458 sh_num
= section
->sh_num
;
460 if ((sym
->type
.t
& VT_BTYPE
) == VT_FUNC
) {
462 } else if ((sym
->type
.t
& VT_BTYPE
) == VT_VOID
) {
463 sym_type
= STT_NOTYPE
;
465 sym_type
= STT_OBJECT
;
468 if (sym
->type
.t
& VT_STATIC
)
469 sym_bind
= STB_LOCAL
;
471 if (sym
->type
.t
& VT_WEAK
)
474 sym_bind
= STB_GLOBAL
;
478 name
= get_tok_str(sym
->v
, NULL
);
479 #ifdef CONFIG_TCC_BCHECK
480 if (tcc_state
->do_bounds_check
) {
483 /* XXX: avoid doing that for statics ? */
484 /* if bound checking is activated, we change some function
485 names by adding the "__bound" prefix */
488 /* XXX: we rely only on malloc hooks */
501 strcpy(buf
, "__bound_");
511 if (sym
->type
.t
& VT_EXPORT
)
513 if (sym_type
== STT_FUNC
&& sym
->type
.ref
) {
514 int attr
= sym
->type
.ref
->r
;
515 if (FUNC_EXPORT(attr
))
517 if (FUNC_CALL(attr
) == FUNC_STDCALL
&& can_add_underscore
) {
518 sprintf(buf1
, "_%s@%d", name
, FUNC_ARGS(attr
) * PTR_SIZE
);
521 can_add_underscore
= 0;
524 if (find_elf_sym(tcc_state
->dynsymtab_section
, name
))
526 if (sym
->type
.t
& VT_IMPORT
)
530 if (tcc_state
->leading_underscore
&& can_add_underscore
) {
532 pstrcpy(buf1
+ 1, sizeof(buf1
) - 1, name
);
535 if (sym
->asm_label
) {
536 name
= sym
->asm_label
;
538 info
= ELFW(ST_INFO
)(sym_bind
, sym_type
);
539 sym
->c
= add_elf_sym(symtab_section
, value
, size
, info
, other
, sh_num
, name
);
541 esym
= &((ElfW(Sym
) *)symtab_section
->data
)[sym
->c
];
542 esym
->st_value
= value
;
543 esym
->st_size
= size
;
544 esym
->st_shndx
= sh_num
;
548 ST_FUNC
void put_extern_sym(Sym
*sym
, Section
*section
,
549 unsigned long value
, unsigned long size
)
551 put_extern_sym2(sym
, section
, value
, size
, 1);
554 /* add a new relocation entry to symbol 'sym' in section 's' */
555 ST_FUNC
void greloc(Section
*s
, Sym
*sym
, unsigned long offset
, int type
)
560 put_extern_sym(sym
, NULL
, 0, 0);
563 /* now we can add ELF relocation info */
564 put_elf_reloc(symtab_section
, s
, offset
, type
, c
);
567 /********************************************************/
569 static void strcat_vprintf(char *buf
, int buf_size
, const char *fmt
, va_list ap
)
573 vsnprintf(buf
+ len
, buf_size
- len
, fmt
, ap
);
576 static void strcat_printf(char *buf
, int buf_size
, const char *fmt
, ...)
580 strcat_vprintf(buf
, buf_size
, fmt
, ap
);
584 static void error1(TCCState
*s1
, int is_warning
, const char *fmt
, va_list ap
)
591 for(f
= s1
->include_stack
; f
< s1
->include_stack_ptr
; f
++)
592 strcat_printf(buf
, sizeof(buf
), "In file included from %s:%d:\n",
593 (*f
)->filename
, (*f
)->line_num
);
594 if (file
->line_num
> 0) {
595 strcat_printf(buf
, sizeof(buf
),
596 "%s:%d: ", file
->filename
, file
->line_num
);
598 strcat_printf(buf
, sizeof(buf
),
599 "%s: ", file
->filename
);
602 strcat_printf(buf
, sizeof(buf
),
606 strcat_printf(buf
, sizeof(buf
), "warning: ");
608 strcat_printf(buf
, sizeof(buf
), "error: ");
609 strcat_vprintf(buf
, sizeof(buf
), fmt
, ap
);
611 if (!s1
->error_func
) {
612 /* default case: stderr */
613 fprintf(stderr
, "%s\n", buf
);
615 s1
->error_func(s1
->error_opaque
, buf
);
617 if (!is_warning
|| s1
->warn_error
)
621 LIBTCCAPI
void tcc_set_error_func(TCCState
*s
, void *error_opaque
,
622 void (*error_func
)(void *opaque
, const char *msg
))
624 s
->error_opaque
= error_opaque
;
625 s
->error_func
= error_func
;
628 /* error without aborting current compilation */
629 PUB_FUNC
void error_noabort(const char *fmt
, ...)
631 TCCState
*s1
= tcc_state
;
635 error1(s1
, 0, fmt
, ap
);
639 PUB_FUNC
void error(const char *fmt
, ...)
641 TCCState
*s1
= tcc_state
;
645 error1(s1
, 0, fmt
, ap
);
647 /* better than nothing: in some cases, we accept to handle errors */
648 if (s1
->error_set_jmp_enabled
) {
649 longjmp(s1
->error_jmp_buf
, 1);
651 /* XXX: eliminate this someday */
656 PUB_FUNC
void expect(const char *msg
)
658 error("%s expected", msg
);
661 PUB_FUNC
void warning(const char *fmt
, ...)
663 TCCState
*s1
= tcc_state
;
670 error1(s1
, 1, fmt
, ap
);
674 /********************************************************/
677 ST_FUNC
void tcc_open_bf(TCCState
*s1
, const char *filename
, int initlen
)
680 int buflen
= initlen
? initlen
: IO_BUF_SIZE
;
682 bf
= tcc_malloc(sizeof(BufferedFile
) + buflen
);
683 bf
->buf_ptr
= bf
->buffer
;
684 bf
->buf_end
= bf
->buffer
+ initlen
;
685 bf
->buf_end
[0] = CH_EOB
; /* put eob symbol */
686 pstrcpy(bf
->filename
, sizeof(bf
->filename
), filename
);
688 normalize_slashes(bf
->filename
);
691 bf
->ifndef_macro
= 0;
692 bf
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
698 ST_FUNC
void tcc_close(void)
700 BufferedFile
*bf
= file
;
703 total_lines
+= bf
->line_num
;
709 ST_FUNC
int tcc_open(TCCState
*s1
, const char *filename
)
712 if (strcmp(filename
, "-") == 0)
713 fd
= 0, filename
= "stdin";
715 fd
= open(filename
, O_RDONLY
| O_BINARY
);
716 if ((s1
->verbose
== 2 && fd
>= 0) || s1
->verbose
== 3)
717 printf("%s %*s%s\n", fd
< 0 ? "nf":"->",
718 (int)(s1
->include_stack_ptr
- s1
->include_stack
), "", filename
);
722 tcc_open_bf(s1
, filename
, 0);
727 /* compile the C file opened in 'file'. Return non zero if errors. */
728 static int tcc_compile(TCCState
*s1
)
733 volatile int section_sym
;
736 printf("%s: **** new file\n", file
->filename
);
740 cur_text_section
= NULL
;
742 anon_sym
= SYM_FIRST_ANOM
;
744 /* file info: full path + filename */
745 section_sym
= 0; /* avoid warning */
747 section_sym
= put_elf_sym(symtab_section
, 0, 0,
748 ELFW(ST_INFO
)(STB_LOCAL
, STT_SECTION
), 0,
749 text_section
->sh_num
, NULL
);
750 getcwd(buf
, sizeof(buf
));
752 normalize_slashes(buf
);
754 pstrcat(buf
, sizeof(buf
), "/");
755 put_stabs_r(buf
, N_SO
, 0, 0,
756 text_section
->data_offset
, text_section
, section_sym
);
757 put_stabs_r(file
->filename
, N_SO
, 0, 0,
758 text_section
->data_offset
, text_section
, section_sym
);
760 /* an elf symbol of type STT_FILE must be put so that STB_LOCAL
761 symbols can be safely used */
762 put_elf_sym(symtab_section
, 0, 0,
763 ELFW(ST_INFO
)(STB_LOCAL
, STT_FILE
), 0,
764 SHN_ABS
, file
->filename
);
766 /* define some often used types */
769 char_pointer_type
.t
= VT_BYTE
;
770 mk_pointer(&char_pointer_type
);
772 func_old_type
.t
= VT_FUNC
;
773 func_old_type
.ref
= sym_push(SYM_FIELD
, &int_type
, FUNC_CDECL
, FUNC_OLD
);
775 #if defined(TCC_ARM_EABI) && defined(TCC_ARM_VFP)
776 float_type
.t
= VT_FLOAT
;
777 double_type
.t
= VT_DOUBLE
;
779 func_float_type
.t
= VT_FUNC
;
780 func_float_type
.ref
= sym_push(SYM_FIELD
, &float_type
, FUNC_CDECL
, FUNC_OLD
);
781 func_double_type
.t
= VT_FUNC
;
782 func_double_type
.ref
= sym_push(SYM_FIELD
, &double_type
, FUNC_CDECL
, FUNC_OLD
);
786 /* define 'void *alloca(unsigned int)' builtin function */
791 sym
= sym_push(p
, mk_pointer(VT_VOID
), FUNC_CDECL
, FUNC_NEW
);
792 s1
= sym_push(SYM_FIELD
, VT_UNSIGNED
| VT_INT
, 0, 0);
795 sym_push(TOK_alloca
, VT_FUNC
| (p
<< VT_STRUCT_SHIFT
), VT_CONST
, 0);
799 define_start
= define_stack
;
802 if (setjmp(s1
->error_jmp_buf
) == 0) {
804 s1
->error_set_jmp_enabled
= 1;
806 ch
= file
->buf_ptr
[0];
807 tok_flags
= TOK_FLAG_BOL
| TOK_FLAG_BOF
;
808 parse_flags
= PARSE_FLAG_PREPROCESS
| PARSE_FLAG_TOK_NUM
;
813 expect("declaration");
815 warning("internal compiler error: vstack leak? (%d)", vtop
- pvtop
);
817 /* end of translation unit info */
819 put_stabs_r(NULL
, N_SO
, 0, 0,
820 text_section
->data_offset
, text_section
, section_sym
);
824 s1
->error_set_jmp_enabled
= 0;
826 /* reset define stack, but leave -Dsymbols (may be incorrect if
827 they are undefined) */
828 free_defines(define_start
);
830 gen_inline_functions();
832 sym_pop(&global_stack
, NULL
);
833 sym_pop(&local_stack
, NULL
);
835 return s1
->nb_errors
!= 0 ? -1 : 0;
838 LIBTCCAPI
int tcc_compile_string(TCCState
*s
, const char *str
)
843 tcc_open_bf(s
, "<string>", len
);
844 memcpy(file
->buffer
, str
, len
);
845 ret
= tcc_compile(s
);
850 /* define a preprocessor symbol. A value can also be provided with the '=' operator */
851 LIBTCCAPI
void tcc_define_symbol(TCCState
*s1
, const char *sym
, const char *value
)
858 len2
= strlen(value
);
860 /* init file structure */
861 tcc_open_bf(s1
, "<define>", len1
+ len2
+ 1);
862 memcpy(file
->buffer
, sym
, len1
);
863 file
->buffer
[len1
] = ' ';
864 memcpy(file
->buffer
+ len1
+ 1, value
, len2
);
866 /* parse with define parser */
867 ch
= file
->buf_ptr
[0];
874 /* undefine a preprocessor symbol */
875 LIBTCCAPI
void tcc_undefine_symbol(TCCState
*s1
, const char *sym
)
879 ts
= tok_alloc(sym
, strlen(sym
));
880 s
= define_find(ts
->tok
);
881 /* undefine symbol by putting an invalid name */
886 static void tcc_cleanup(void)
890 if (NULL
== tcc_state
)
894 /* free -D defines */
898 n
= tok_ident
- TOK_IDENT
;
899 for(i
= 0; i
< n
; i
++)
900 tcc_free(table_ident
[i
]);
901 tcc_free(table_ident
);
904 dynarray_reset(&sym_pools
, &nb_sym_pools
);
907 /* reset symbol stack */
908 sym_free_first
= NULL
;
909 /* cleanup from error/setjmp */
913 LIBTCCAPI TCCState
*tcc_new(void)
921 s
= tcc_mallocz(sizeof(TCCState
));
926 tcc_set_lib_path_w32(s
);
928 tcc_set_lib_path(s
, CONFIG_TCCDIR
);
930 s
->output_type
= TCC_OUTPUT_MEMORY
;
932 s
->include_stack_ptr
= s
->include_stack
;
934 /* we add dummy defines for some special macros to speed up tests
935 and to have working defined() */
936 define_push(TOK___LINE__
, MACRO_OBJ
, NULL
, NULL
);
937 define_push(TOK___FILE__
, MACRO_OBJ
, NULL
, NULL
);
938 define_push(TOK___DATE__
, MACRO_OBJ
, NULL
, NULL
);
939 define_push(TOK___TIME__
, MACRO_OBJ
, NULL
, NULL
);
941 /* standard defines */
942 tcc_define_symbol(s
, "__STDC__", NULL
);
943 tcc_define_symbol(s
, "__STDC_VERSION__", "199901L");
944 #if defined(TCC_TARGET_I386)
945 tcc_define_symbol(s
, "__i386__", NULL
);
946 tcc_define_symbol(s
, "__i386", NULL
);
947 tcc_define_symbol(s
, "i386", NULL
);
949 #if defined(TCC_TARGET_X86_64)
950 tcc_define_symbol(s
, "__x86_64__", NULL
);
952 #if defined(TCC_TARGET_ARM)
953 tcc_define_symbol(s
, "__ARM_ARCH_4__", NULL
);
954 tcc_define_symbol(s
, "__arm_elf__", NULL
);
955 tcc_define_symbol(s
, "__arm_elf", NULL
);
956 tcc_define_symbol(s
, "arm_elf", NULL
);
957 tcc_define_symbol(s
, "__arm__", NULL
);
958 tcc_define_symbol(s
, "__arm", NULL
);
959 tcc_define_symbol(s
, "arm", NULL
);
960 tcc_define_symbol(s
, "__APCS_32__", NULL
);
963 tcc_define_symbol(s
, "_WIN32", NULL
);
964 #ifdef TCC_TARGET_X86_64
965 tcc_define_symbol(s
, "_WIN64", NULL
);
968 tcc_define_symbol(s
, "__unix__", NULL
);
969 tcc_define_symbol(s
, "__unix", NULL
);
970 tcc_define_symbol(s
, "unix", NULL
);
971 #if defined(__FreeBSD__)
973 tcc_define_symbol(s
, "__FreeBSD__", str( __FreeBSD__
));
976 #if defined(__FreeBSD_kernel__)
977 tcc_define_symbol(s
, "__FreeBSD_kernel__", NULL
);
980 tcc_define_symbol(s
, "__linux__", NULL
);
981 tcc_define_symbol(s
, "__linux", NULL
);
984 /* tiny C specific defines */
985 sscanf(TCC_VERSION
, "%d.%d.%d", &a
, &b
, &c
);
986 sprintf(buffer
, "%d", a
*10000 + b
*100 + c
);
987 tcc_define_symbol(s
, "__TINYC__", buffer
);
989 /* tiny C & gcc defines */
990 #if defined TCC_TARGET_PE && defined TCC_TARGET_X86_64
991 tcc_define_symbol(s
, "__SIZE_TYPE__", "unsigned long long");
992 tcc_define_symbol(s
, "__PTRDIFF_TYPE__", "long long");
994 tcc_define_symbol(s
, "__SIZE_TYPE__", "unsigned long");
995 tcc_define_symbol(s
, "__PTRDIFF_TYPE__", "long");
999 tcc_define_symbol(s
, "__WCHAR_TYPE__", "unsigned short");
1001 tcc_define_symbol(s
, "__WCHAR_TYPE__", "int");
1005 tcc_define_symbol(s
, "__REDIRECT_NTH(name, proto, alias)", "name proto __asm__ (#alias) __THROW");
1007 #ifndef TCC_TARGET_PE
1008 /* default library paths */
1009 tcc_add_library_path(s
, CONFIG_TCC_LIBPATH
);
1012 /* no section zero */
1013 dynarray_add((void ***)&s
->sections
, &s
->nb_sections
, NULL
);
1015 /* create standard sections */
1016 text_section
= new_section(s
, ".text", SHT_PROGBITS
, SHF_ALLOC
| SHF_EXECINSTR
);
1017 data_section
= new_section(s
, ".data", SHT_PROGBITS
, SHF_ALLOC
| SHF_WRITE
);
1018 bss_section
= new_section(s
, ".bss", SHT_NOBITS
, SHF_ALLOC
| SHF_WRITE
);
1020 /* symbols are always generated for linking stage */
1021 symtab_section
= new_symtab(s
, ".symtab", SHT_SYMTAB
, 0,
1023 ".hashtab", SHF_PRIVATE
);
1024 strtab_section
= symtab_section
->link
;
1026 /* private symbol table for dynamic symbols */
1027 s
->dynsymtab_section
= new_symtab(s
, ".dynsymtab", SHT_SYMTAB
, SHF_PRIVATE
,
1029 ".dynhashtab", SHF_PRIVATE
);
1030 s
->alacarte_link
= 1;
1033 #ifdef CHAR_IS_UNSIGNED
1034 s
->char_is_unsigned
= 1;
1036 /* enable this if you want symbols with leading underscore on windows: */
1037 #if defined(TCC_TARGET_PE) && 0
1038 s
->leading_underscore
= 1;
1040 if (s
->section_align
== 0)
1041 s
->section_align
= ELF_PAGE_SIZE
;
1042 #ifdef TCC_TARGET_I386
1048 LIBTCCAPI
void tcc_delete(TCCState
*s1
)
1054 /* free all sections */
1055 for(i
= 1; i
< s1
->nb_sections
; i
++)
1056 free_section(s1
->sections
[i
]);
1057 dynarray_reset(&s1
->sections
, &s1
->nb_sections
);
1059 for(i
= 0; i
< s1
->nb_priv_sections
; i
++)
1060 free_section(s1
->priv_sections
[i
]);
1061 dynarray_reset(&s1
->priv_sections
, &s1
->nb_priv_sections
);
1063 /* free any loaded DLLs */
1064 for ( i
= 0; i
< s1
->nb_loaded_dlls
; i
++) {
1065 DLLReference
*ref
= s1
->loaded_dlls
[i
];
1067 dlclose(ref
->handle
);
1070 /* free loaded dlls array */
1071 dynarray_reset(&s1
->loaded_dlls
, &s1
->nb_loaded_dlls
);
1073 /* free library paths */
1074 dynarray_reset(&s1
->library_paths
, &s1
->nb_library_paths
);
1076 /* free include paths */
1077 dynarray_reset(&s1
->cached_includes
, &s1
->nb_cached_includes
);
1078 dynarray_reset(&s1
->include_paths
, &s1
->nb_include_paths
);
1079 dynarray_reset(&s1
->sysinclude_paths
, &s1
->nb_sysinclude_paths
);
1081 tcc_free(s1
->tcc_lib_path
);
1083 dynarray_reset(&s1
->input_files
, &s1
->nb_input_files
);
1084 dynarray_reset(&s1
->input_libs
, &s1
->nb_input_libs
);
1085 dynarray_reset(&s1
->target_deps
, &s1
->nb_target_deps
);
1088 munmap (s1
->write_mem
, s1
->mem_size
);
1089 munmap (s1
->runtime_mem
, s1
->mem_size
);
1091 tcc_free(s1
->runtime_mem
);
1096 LIBTCCAPI
int tcc_add_include_path(TCCState
*s
, const char *pathname
)
1098 tcc_split_path(s
, (void ***)&s
->include_paths
, &s
->nb_include_paths
, pathname
);
1102 LIBTCCAPI
int tcc_add_sysinclude_path(TCCState
*s
, const char *pathname
)
1104 tcc_split_path(s
, (void ***)&s
->sysinclude_paths
, &s
->nb_sysinclude_paths
, pathname
);
1108 ST_FUNC
int tcc_add_file_internal(TCCState
*s1
, const char *filename
, int flags
)
1114 /* find source file type with extension */
1115 ext
= tcc_fileextension(filename
);
1119 #ifdef CONFIG_TCC_ASM
1120 /* if .S file, define __ASSEMBLER__ like gcc does */
1121 if (!strcmp(ext
, "S"))
1122 tcc_define_symbol(s1
, "__ASSEMBLER__", NULL
);
1126 ret
= tcc_open(s1
, filename
);
1128 if (flags
& AFF_PRINT_ERROR
)
1129 error_noabort("file '%s' not found", filename
);
1133 /* update target deps */
1134 dynarray_add((void ***)&s1
->target_deps
, &s1
->nb_target_deps
,
1135 tcc_strdup(filename
));
1137 if (flags
& AFF_PREPROCESS
) {
1138 ret
= tcc_preprocess(s1
);
1142 if (!ext
[0] || !PATHCMP(ext
, "c")) {
1143 /* C file assumed */
1144 ret
= tcc_compile(s1
);
1148 #ifdef CONFIG_TCC_ASM
1149 if (!strcmp(ext
, "S")) {
1150 /* preprocessed assembler */
1151 ret
= tcc_assemble(s1
, 1);
1155 if (!strcmp(ext
, "s")) {
1156 /* non preprocessed assembler */
1157 ret
= tcc_assemble(s1
, 0);
1163 /* assume executable format: auto guess file type */
1164 size
= read(fd
, &ehdr
, sizeof(ehdr
));
1165 lseek(fd
, 0, SEEK_SET
);
1167 error_noabort("could not read header");
1171 if (size
== sizeof(ehdr
) &&
1172 ehdr
.e_ident
[0] == ELFMAG0
&&
1173 ehdr
.e_ident
[1] == ELFMAG1
&&
1174 ehdr
.e_ident
[2] == ELFMAG2
&&
1175 ehdr
.e_ident
[3] == ELFMAG3
) {
1177 /* do not display line number if error */
1179 if (ehdr
.e_type
== ET_REL
) {
1180 ret
= tcc_load_object_file(s1
, fd
, 0);
1184 #ifndef TCC_TARGET_PE
1185 if (ehdr
.e_type
== ET_DYN
) {
1186 if (s1
->output_type
== TCC_OUTPUT_MEMORY
) {
1188 h
= dlopen(filename
, RTLD_GLOBAL
| RTLD_LAZY
);
1192 ret
= tcc_load_dll(s1
, fd
, filename
,
1193 (flags
& AFF_REFERENCED_DLL
) != 0);
1198 error_noabort("unrecognized ELF file");
1202 if (memcmp((char *)&ehdr
, ARMAG
, 8) == 0) {
1203 file
->line_num
= 0; /* do not display line number if error */
1204 ret
= tcc_load_archive(s1
, fd
);
1208 #ifdef TCC_TARGET_COFF
1209 if (*(uint16_t *)(&ehdr
) == COFF_C67_MAGIC
) {
1210 ret
= tcc_load_coff(s1
, fd
);
1215 #ifdef TCC_TARGET_PE
1216 ret
= pe_load_file(s1
, filename
, fd
);
1218 /* as GNU ld, consider it is an ld script if not recognized */
1219 ret
= tcc_load_ldscript(s1
);
1222 error_noabort("unrecognized file type");
1229 LIBTCCAPI
int tcc_add_file(TCCState
*s
, const char *filename
)
1231 dynarray_add((void ***)&s
->input_files
, &s
->nb_input_files
, tcc_strdup(filename
));
1233 if (s
->output_type
== TCC_OUTPUT_PREPROCESS
)
1234 return tcc_add_file_internal(s
, filename
, AFF_PRINT_ERROR
| AFF_PREPROCESS
);
1236 return tcc_add_file_internal(s
, filename
, AFF_PRINT_ERROR
);
1239 LIBTCCAPI
int tcc_add_library_path(TCCState
*s
, const char *pathname
)
1241 tcc_split_path(s
, (void ***)&s
->library_paths
, &s
->nb_library_paths
, pathname
);
1245 /* find and load a dll. Return non zero if not found */
1246 /* XXX: add '-rpath' option support ? */
1247 ST_FUNC
int tcc_add_dll(TCCState
*s
, const char *filename
, int flags
)
1252 for(i
= 0; i
< s
->nb_library_paths
; i
++) {
1253 snprintf(buf
, sizeof(buf
), "%s/%s",
1254 s
->library_paths
[i
], filename
);
1255 if (tcc_add_file_internal(s
, buf
, flags
) == 0)
1261 /* the library name is the same as the argument of the '-l' option */
1262 LIBTCCAPI
int tcc_add_library(TCCState
*s
, const char *libraryname
)
1267 dynarray_add((void ***)&s
->input_libs
, &s
->nb_input_libs
, tcc_strdup(libraryname
));
1269 /* first we look for the dynamic library if not static linking */
1270 if (!s
->static_link
) {
1271 #ifdef TCC_TARGET_PE
1272 if (pe_add_dll(s
, libraryname
) == 0)
1275 snprintf(buf
, sizeof(buf
), "lib%s.so", libraryname
);
1276 if (tcc_add_dll(s
, buf
, 0) == 0)
1280 /* then we look for the static library */
1281 for(i
= 0; i
< s
->nb_library_paths
; i
++) {
1282 snprintf(buf
, sizeof(buf
), "%s/lib%s.a",
1283 s
->library_paths
[i
], libraryname
);
1284 if (tcc_add_file_internal(s
, buf
, 0) == 0)
1290 LIBTCCAPI
int tcc_add_symbol(TCCState
*s
, const char *name
, const void *val
)
1292 #ifdef TCC_TARGET_PE
1293 pe_putimport(s
, 0, name
, val
);
1295 add_elf_sym(symtab_section
, (uplong
)val
, 0,
1296 ELFW(ST_INFO
)(STB_GLOBAL
, STT_NOTYPE
), 0,
1302 LIBTCCAPI
int tcc_set_output_type(TCCState
*s
, int output_type
)
1304 s
->output_type
= output_type
;
1307 /* default include paths */
1308 /* -isystem paths have already been handled */
1309 tcc_add_sysinclude_path(s
, CONFIG_TCC_SYSINCLUDE_PATHS
);
1312 /* if bound checking, then add corresponding sections */
1313 #ifdef CONFIG_TCC_BCHECK
1314 if (s
->do_bounds_check
) {
1316 tcc_define_symbol(s
, "__BOUNDS_CHECKING_ON", NULL
);
1317 /* create bounds sections */
1318 bounds_section
= new_section(s
, ".bounds",
1319 SHT_PROGBITS
, SHF_ALLOC
);
1320 lbounds_section
= new_section(s
, ".lbounds",
1321 SHT_PROGBITS
, SHF_ALLOC
);
1325 if (s
->char_is_unsigned
) {
1326 tcc_define_symbol(s
, "__CHAR_UNSIGNED__", NULL
);
1329 /* add debug sections */
1332 stab_section
= new_section(s
, ".stab", SHT_PROGBITS
, 0);
1333 stab_section
->sh_entsize
= sizeof(Stab_Sym
);
1334 stabstr_section
= new_section(s
, ".stabstr", SHT_STRTAB
, 0);
1335 put_elf_str(stabstr_section
, "");
1336 stab_section
->link
= stabstr_section
;
1337 /* put first entry */
1338 put_stabs("", 0, 0, 0, 0);
1341 /* add libc crt1/crti objects */
1342 #ifdef TCC_TARGET_PE
1343 tcc_add_library_path(s
, CONFIG_TCC_LIBPATH
);
1345 tcc_add_systemdir(s
);
1348 if ((output_type
== TCC_OUTPUT_EXE
|| output_type
== TCC_OUTPUT_DLL
) &&
1350 if (output_type
!= TCC_OUTPUT_DLL
)
1351 tcc_add_file(s
, CONFIG_SYSROOT CONFIG_TCC_CRT_PREFIX
"/crt1.o");
1352 tcc_add_file(s
, CONFIG_SYSROOT CONFIG_TCC_CRT_PREFIX
"/crti.o");
1358 #define WD_ALL 0x0001 /* warning is activated when using -Wall */
1359 #define FD_INVERT 0x0002 /* invert value before storing */
1361 typedef struct FlagDef
{
1367 static const FlagDef warning_defs
[] = {
1368 { offsetof(TCCState
, warn_unsupported
), 0, "unsupported" },
1369 { offsetof(TCCState
, warn_write_strings
), 0, "write-strings" },
1370 { offsetof(TCCState
, warn_error
), 0, "error" },
1371 { offsetof(TCCState
, warn_implicit_function_declaration
), WD_ALL
,
1372 "implicit-function-declaration" },
1375 ST_FUNC
int set_flag(TCCState
*s
, const FlagDef
*flags
, int nb_flags
,
1376 const char *name
, int value
)
1383 if (r
[0] == 'n' && r
[1] == 'o' && r
[2] == '-') {
1387 for(i
= 0, p
= flags
; i
< nb_flags
; i
++, p
++) {
1388 if (!strcmp(r
, p
->name
))
1393 if (p
->flags
& FD_INVERT
)
1395 *(int *)((uint8_t *)s
+ p
->offset
) = value
;
1399 /* set/reset a warning */
1400 LIBTCCAPI
int tcc_set_warning(TCCState
*s
, const char *warning_name
, int value
)
1405 if (!strcmp(warning_name
, "all")) {
1406 for(i
= 0, p
= warning_defs
; i
< countof(warning_defs
); i
++, p
++) {
1407 if (p
->flags
& WD_ALL
)
1408 *(int *)((uint8_t *)s
+ p
->offset
) = 1;
1412 return set_flag(s
, warning_defs
, countof(warning_defs
),
1413 warning_name
, value
);
1417 static const FlagDef flag_defs
[] = {
1418 { offsetof(TCCState
, char_is_unsigned
), 0, "unsigned-char" },
1419 { offsetof(TCCState
, char_is_unsigned
), FD_INVERT
, "signed-char" },
1420 { offsetof(TCCState
, nocommon
), FD_INVERT
, "common" },
1421 { offsetof(TCCState
, leading_underscore
), 0, "leading-underscore" },
1424 /* set/reset a flag */
1425 PUB_FUNC
int tcc_set_flag(TCCState
*s
, const char *flag_name
, int value
)
1427 return set_flag(s
, flag_defs
, countof(flag_defs
),
1432 static int strstart(const char *str
, const char *val
, char **ptr
)
1437 while (*q
!= '\0') {
1449 /* Like strstart, but automatically takes into account that ld options can
1451 * - start with double or single dash (e.g. '--soname' or '-soname')
1452 * - arguments can be given as separate or after '=' (e.g. '-Wl,-soname,x.so'
1453 * or '-Wl,-soname=x.so')
1455 * you provide `val` always in 'option[=]' form (no leading -)
1457 static int link_option(const char *str
, const char *val
, char **ptr
)
1461 /* there should be 1 or 2 dashes */
1467 /* then str & val should match (potentialy up to '=') */
1471 while (*q
!= '\0' && *q
!= '=') {
1478 /* '=' near eos means ',' or '=' is ok */
1480 if (*p
!= ',' && *p
!= '=')
1492 /* set linker options */
1493 PUB_FUNC
const char * tcc_set_linker(TCCState
*s
, char *option
, int multi
)
1498 while (option
&& *option
) {
1500 if (link_option(option
, "Bsymbolic", &p
)) {
1502 } else if (link_option(option
, "fini=", &p
)) {
1504 if (s
->warn_unsupported
)
1505 warning("ignoring -fini %s", p
);
1506 } else if (link_option(option
, "image-base=", &p
)) {
1507 s
->text_addr
= strtoul(p
, &end
, 16);
1508 s
->has_text_addr
= 1;
1509 } else if (link_option(option
, "init=", &p
)) {
1511 if (s
->warn_unsupported
)
1512 warning("ignoring -init %s", p
);
1513 } else if (link_option(option
, "oformat=", &p
)) {
1514 #if defined(TCC_TARGET_PE)
1515 if (strstart(p
, "pe-", NULL
)) {
1517 #if defined(TCC_TARGET_X86_64)
1518 if (strstart(p
, "elf64-", NULL
)) {
1520 if (strstart(p
, "elf32-", NULL
)) {
1523 s
->output_format
= TCC_OUTPUT_FORMAT_ELF
;
1524 } else if (!strcmp(p
, "binary")) {
1525 s
->output_format
= TCC_OUTPUT_FORMAT_BINARY
;
1527 #ifdef TCC_TARGET_COFF
1528 if (!strcmp(p
, "coff")) {
1529 s
->output_format
= TCC_OUTPUT_FORMAT_COFF
;
1536 } else if (link_option(option
, "rpath=", &p
)) {
1538 } else if (link_option(option
, "section-alignment=", &p
)) {
1539 s
->section_align
= strtoul(p
, &end
, 16);
1540 } else if (link_option(option
, "soname=", &p
)) {
1543 #ifdef TCC_TARGET_PE
1544 } else if (link_option(option
, "file-alignment=", &p
)) {
1545 s
->pe_file_align
= strtoul(p
, &end
, 16);
1546 } else if (link_option(option
, "stack=", &p
)) {
1547 s
->pe_stack_size
= strtoul(p
, &end
, 10);
1548 } else if (link_option(option
, "subsystem=", &p
)) {
1549 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
1550 if (!strcmp(p
, "native")) {
1551 s
->pe_subsystem
= 1;
1552 } else if (!strcmp(p
, "console")) {
1553 s
->pe_subsystem
= 3;
1554 } else if (!strcmp(p
, "gui")) {
1555 s
->pe_subsystem
= 2;
1556 } else if (!strcmp(p
, "posix")) {
1557 s
->pe_subsystem
= 7;
1558 } else if (!strcmp(p
, "efiapp")) {
1559 s
->pe_subsystem
= 10;
1560 } else if (!strcmp(p
, "efiboot")) {
1561 s
->pe_subsystem
= 11;
1562 } else if (!strcmp(p
, "efiruntime")) {
1563 s
->pe_subsystem
= 12;
1564 } else if (!strcmp(p
, "efirom")) {
1565 s
->pe_subsystem
= 13;
1566 #elif defined(TCC_TARGET_ARM)
1567 if (!strcmp(p
, "wince")) {
1568 s
->pe_subsystem
= 9;
1575 } else if (link_option(option
, "Ttext=", &p
)) {
1576 s
->text_addr
= strtoul(p
, &end
, 16);
1577 s
->has_text_addr
= 1;
1585 p
= strchr( (end
) ? end
: p
, ',');
1587 *p
= 0; /* terminate last option */
1596 PUB_FUNC
void tcc_print_stats(TCCState
*s
, int64_t total_time
)
1599 tt
= (double)total_time
/ 1000000.0;
1602 if (total_bytes
< 1)
1604 printf("%d idents, %d lines, %d bytes, %0.3f s, %d lines/s, %0.1f MB/s\n",
1605 tok_ident
- TOK_IDENT
, total_lines
, total_bytes
,
1606 tt
, (int)(total_lines
/ tt
),
1607 total_bytes
/ tt
/ 1000000.0);
1610 /* set CONFIG_TCCDIR at runtime */
1611 LIBTCCAPI
void tcc_set_lib_path(TCCState
*s
, const char *path
)
1613 tcc_free(s
->tcc_lib_path
);
1614 s
->tcc_lib_path
= tcc_strdup(path
);
1617 PUB_FUNC
void set_num_callers(int n
)
1619 #ifdef CONFIG_TCC_BACKTRACE
1625 LIBTCCAPI
const char *tcc_default_target(TCCState
*s
)
1627 /* FIXME will break in multithreaded case */
1628 static char outfile_default
[1024];
1632 strcmp(s
->input_files
[0], "-") == 0 ? "a"
1633 : tcc_basename(s
->input_files
[0]);
1634 pstrcpy(outfile_default
, sizeof(outfile_default
), name
);
1635 ext
= tcc_fileextension(outfile_default
);
1636 #ifdef TCC_TARGET_PE
1637 if (s
->output_type
== TCC_OUTPUT_DLL
)
1638 strcpy(ext
, ".dll");
1640 if (s
->output_type
== TCC_OUTPUT_EXE
)
1641 strcpy(ext
, ".exe");
1644 if (( (s
->output_type
== TCC_OUTPUT_OBJ
&& !s
->reloc_output
) ||
1645 (s
->output_type
== TCC_OUTPUT_PREPROCESS
) )
1649 pstrcpy(outfile_default
, sizeof(outfile_default
), "a.out");
1651 return outfile_default
;
1655 LIBTCCAPI
void tcc_gen_makedeps(TCCState
*s
, const char *target
, const char *filename
)
1658 char buf
[1024], *ext
;
1662 target
= tcc_default_target(s
);
1665 /* compute filename automatically
1666 * dir/file.o -> dir/file.d */
1667 pstrcpy(buf
, sizeof(buf
), target
);
1668 ext
= tcc_fileextension(buf
);
1669 pstrcpy(ext
, sizeof(buf
) - (ext
-buf
), ".d");
1674 printf("<- %s\n", filename
);
1676 /* XXX return err codes instead of error() ? */
1677 depout
= fopen(filename
, "w");
1679 error("could not open '%s'", filename
);
1681 fprintf(depout
, "%s : \\\n", target
);
1682 for (i
=0; i
<s
->nb_target_deps
; ++i
)
1683 fprintf(depout
, "\t%s \\\n", s
->target_deps
[i
]);
1684 fprintf(depout
, "\n");