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 /* ALL_IN_ONE */
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 #ifndef CONFIG_TCC_STATIC
115 void dlclose(void *p
)
117 FreeLibrary((HMODULE
)p
);
122 BOOL WINAPI
DllMain (HANDLE hDll
, DWORD dwReason
, LPVOID lpReserved
)
124 if (DLL_PROCESS_ATTACH
== dwReason
)
131 /********************************************************/
132 /* copy a string and truncate it. */
133 PUB_FUNC
char *pstrcpy(char *buf
, int buf_size
, const char *s
)
140 q_end
= buf
+ buf_size
- 1;
152 /* strcat and truncate. */
153 PUB_FUNC
char *pstrcat(char *buf
, int buf_size
, const char *s
)
158 pstrcpy(buf
+ len
, buf_size
- len
, s
);
162 /* extract the basename of a file */
163 PUB_FUNC
char *tcc_basename(const char *name
)
165 char *p
= strchr(name
, 0);
166 while (p
> name
&& !IS_PATHSEP(p
[-1]))
171 /* extract extension part of a file
173 * (if no extension, return pointer to end-of-string)
175 PUB_FUNC
char *tcc_fileextension (const char *name
)
177 char *b
= tcc_basename(name
);
178 char *e
= strrchr(b
, '.');
179 return e
? e
: strchr(b
, 0);
182 /********************************************************/
183 /* memory management */
192 unsigned malloc_usable_size(void*);
195 PUB_FUNC
void tcc_free(void *ptr
)
198 mem_cur_size
-= malloc_usable_size(ptr
);
203 PUB_FUNC
void *tcc_malloc(unsigned long size
)
208 error("memory full");
210 mem_cur_size
+= malloc_usable_size(ptr
);
211 if (mem_cur_size
> mem_max_size
)
212 mem_max_size
= mem_cur_size
;
217 PUB_FUNC
void *tcc_mallocz(unsigned long size
)
220 ptr
= tcc_malloc(size
);
221 memset(ptr
, 0, size
);
225 PUB_FUNC
void *tcc_realloc(void *ptr
, unsigned long size
)
229 mem_cur_size
-= malloc_usable_size(ptr
);
231 ptr1
= realloc(ptr
, size
);
233 /* NOTE: count not correct if alloc error, but not critical */
234 mem_cur_size
+= malloc_usable_size(ptr1
);
235 if (mem_cur_size
> mem_max_size
)
236 mem_max_size
= mem_cur_size
;
241 PUB_FUNC
char *tcc_strdup(const char *str
)
244 ptr
= tcc_malloc(strlen(str
) + 1);
249 PUB_FUNC
void tcc_memstats(void)
252 printf("memory in use: %d\n", mem_cur_size
);
256 #define free(p) use_tcc_free(p)
257 #define malloc(s) use_tcc_malloc(s)
258 #define realloc(p, s) use_tcc_realloc(p, s)
260 /********************************************************/
263 PUB_FUNC
void dynarray_add(void ***ptab
, int *nb_ptr
, void *data
)
270 /* every power of two we double array size */
271 if ((nb
& (nb
- 1)) == 0) {
276 pp
= tcc_realloc(pp
, nb_alloc
* sizeof(void *));
278 error("memory full");
285 PUB_FUNC
void dynarray_reset(void *pp
, int *n
)
288 for (p
= *(void***)pp
; *n
; ++p
, --*n
)
291 tcc_free(*(void**)pp
);
295 /* we use our own 'finite' function to avoid potential problems with
296 non standard math libs */
297 /* XXX: endianness dependent */
298 ST_FUNC
int ieee_finite(double d
)
301 return ((unsigned)((p
[1] | 0x800fffff) + 1)) >> 31;
304 /********************************************************/
306 ST_FUNC Section
*new_section(TCCState
*s1
, const char *name
, int sh_type
, int sh_flags
)
310 sec
= tcc_mallocz(sizeof(Section
) + strlen(name
));
311 strcpy(sec
->name
, name
);
312 sec
->sh_type
= sh_type
;
313 sec
->sh_flags
= sh_flags
;
321 sec
->sh_addralign
= 4;
324 sec
->sh_addralign
= 1;
327 sec
->sh_addralign
= 32; /* default conservative alignment */
331 if (sh_flags
& SHF_PRIVATE
) {
332 dynarray_add((void ***)&s1
->priv_sections
, &s1
->nb_priv_sections
, sec
);
334 sec
->sh_num
= s1
->nb_sections
;
335 dynarray_add((void ***)&s1
->sections
, &s1
->nb_sections
, sec
);
341 static void free_section(Section
*s
)
346 /* realloc section and set its content to zero */
347 ST_FUNC
void section_realloc(Section
*sec
, unsigned long new_size
)
352 size
= sec
->data_allocated
;
355 while (size
< new_size
)
357 data
= tcc_realloc(sec
->data
, size
);
359 error("memory full");
360 memset(data
+ sec
->data_allocated
, 0, size
- sec
->data_allocated
);
362 sec
->data_allocated
= size
;
365 /* reserve at least 'size' bytes in section 'sec' from
367 ST_FUNC
void *section_ptr_add(Section
*sec
, unsigned long size
)
369 unsigned long offset
, offset1
;
371 offset
= sec
->data_offset
;
372 offset1
= offset
+ size
;
373 if (offset1
> sec
->data_allocated
)
374 section_realloc(sec
, offset1
);
375 sec
->data_offset
= offset1
;
376 return sec
->data
+ offset
;
379 /* reserve at least 'size' bytes from section start */
380 ST_FUNC
void section_reserve(Section
*sec
, unsigned long size
)
382 if (size
> sec
->data_allocated
)
383 section_realloc(sec
, size
);
384 if (size
> sec
->data_offset
)
385 sec
->data_offset
= size
;
388 /* return a reference to a section, and create it if it does not
390 ST_FUNC Section
*find_section(TCCState
*s1
, const char *name
)
394 for(i
= 1; i
< s1
->nb_sections
; i
++) {
395 sec
= s1
->sections
[i
];
396 if (!strcmp(name
, sec
->name
))
399 /* sections are created as PROGBITS */
400 return new_section(s1
, name
, SHT_PROGBITS
, SHF_ALLOC
);
403 /* update sym->c so that it points to an external symbol in section
404 'section' with value 'value' */
405 ST_FUNC
void put_extern_sym2(Sym
*sym
, Section
*section
,
406 unsigned long value
, unsigned long size
,
407 int can_add_underscore
)
409 int sym_type
, sym_bind
, sh_num
, info
, other
;
416 else if (section
== SECTION_ABS
)
419 sh_num
= section
->sh_num
;
421 if ((sym
->type
.t
& VT_BTYPE
) == VT_FUNC
) {
423 } else if ((sym
->type
.t
& VT_BTYPE
) == VT_VOID
) {
424 sym_type
= STT_NOTYPE
;
426 sym_type
= STT_OBJECT
;
429 if (sym
->type
.t
& VT_STATIC
)
430 sym_bind
= STB_LOCAL
;
432 if (sym
->type
.t
& VT_WEAK
)
435 sym_bind
= STB_GLOBAL
;
440 name
= get_tok_str(sym
->a
, NULL
);
442 name
= get_tok_str(sym
->v
, NULL
);
443 #ifdef CONFIG_TCC_BCHECK
444 if (tcc_state
->do_bounds_check
) {
447 /* XXX: avoid doing that for statics ? */
448 /* if bound checking is activated, we change some function
449 names by adding the "__bound" prefix */
452 /* XXX: we rely only on malloc hooks */
465 strcpy(buf
, "__bound_");
475 if (sym
->type
.t
& VT_EXPORT
)
477 if (sym_type
== STT_FUNC
&& sym
->type
.ref
) {
478 int attr
= sym
->type
.ref
->r
;
479 if (FUNC_EXPORT(attr
))
481 if (FUNC_CALL(attr
) == FUNC_STDCALL
&& can_add_underscore
) {
482 sprintf(buf1
, "_%s@%d", name
, FUNC_ARGS(attr
) * PTR_SIZE
);
485 can_add_underscore
= 0;
488 if (find_elf_sym(tcc_state
->dynsymtab_section
, name
))
490 if (sym
->type
.t
& VT_IMPORT
)
494 if (tcc_state
->leading_underscore
&& can_add_underscore
) {
496 pstrcpy(buf1
+ 1, sizeof(buf1
) - 1, name
);
499 info
= ELFW(ST_INFO
)(sym_bind
, sym_type
);
500 sym
->c
= add_elf_sym(symtab_section
, value
, size
, info
, other
, sh_num
, name
);
502 esym
= &((ElfW(Sym
) *)symtab_section
->data
)[sym
->c
];
503 esym
->st_value
= value
;
504 esym
->st_size
= size
;
505 esym
->st_shndx
= sh_num
;
509 ST_FUNC
void put_extern_sym(Sym
*sym
, Section
*section
,
510 unsigned long value
, unsigned long size
)
512 put_extern_sym2(sym
, section
, value
, size
, 1);
515 /* add a new relocation entry to symbol 'sym' in section 's' */
516 ST_FUNC
void greloc(Section
*s
, Sym
*sym
, unsigned long offset
, int type
)
521 put_extern_sym(sym
, NULL
, 0, 0);
524 /* now we can add ELF relocation info */
525 put_elf_reloc(symtab_section
, s
, offset
, type
, c
);
528 /********************************************************/
530 static void strcat_vprintf(char *buf
, int buf_size
, const char *fmt
, va_list ap
)
534 vsnprintf(buf
+ len
, buf_size
- len
, fmt
, ap
);
537 static void strcat_printf(char *buf
, int buf_size
, const char *fmt
, ...)
541 strcat_vprintf(buf
, buf_size
, fmt
, ap
);
545 static void error1(TCCState
*s1
, int is_warning
, const char *fmt
, va_list ap
)
552 for(f
= s1
->include_stack
; f
< s1
->include_stack_ptr
; f
++)
553 strcat_printf(buf
, sizeof(buf
), "In file included from %s:%d:\n",
554 (*f
)->filename
, (*f
)->line_num
);
555 if (file
->line_num
> 0) {
556 strcat_printf(buf
, sizeof(buf
),
557 "%s:%d: ", file
->filename
, file
->line_num
);
559 strcat_printf(buf
, sizeof(buf
),
560 "%s: ", file
->filename
);
563 strcat_printf(buf
, sizeof(buf
),
567 strcat_printf(buf
, sizeof(buf
), "warning: ");
569 strcat_printf(buf
, sizeof(buf
), "error: ");
570 strcat_vprintf(buf
, sizeof(buf
), fmt
, ap
);
572 if (!s1
->error_func
) {
573 /* default case: stderr */
574 fprintf(stderr
, "%s\n", buf
);
576 s1
->error_func(s1
->error_opaque
, buf
);
578 if (!is_warning
|| s1
->warn_error
)
582 LIBTCCAPI
void tcc_set_error_func(TCCState
*s
, void *error_opaque
,
583 void (*error_func
)(void *opaque
, const char *msg
))
585 s
->error_opaque
= error_opaque
;
586 s
->error_func
= error_func
;
589 /* error without aborting current compilation */
590 PUB_FUNC
void error_noabort(const char *fmt
, ...)
592 TCCState
*s1
= tcc_state
;
596 error1(s1
, 0, fmt
, ap
);
600 PUB_FUNC
void error(const char *fmt
, ...)
602 TCCState
*s1
= tcc_state
;
606 error1(s1
, 0, fmt
, ap
);
608 /* better than nothing: in some cases, we accept to handle errors */
609 if (s1
->error_set_jmp_enabled
) {
610 longjmp(s1
->error_jmp_buf
, 1);
612 /* XXX: eliminate this someday */
617 PUB_FUNC
void expect(const char *msg
)
619 error("%s expected", msg
);
622 PUB_FUNC
void warning(const char *fmt
, ...)
624 TCCState
*s1
= tcc_state
;
631 error1(s1
, 1, fmt
, ap
);
635 /********************************************************/
638 ST_FUNC
void tcc_open_bf(TCCState
*s1
, const char *filename
, int initlen
)
641 int buflen
= initlen
? initlen
: IO_BUF_SIZE
;
643 bf
= tcc_malloc(sizeof(BufferedFile
) + buflen
);
644 bf
->buf_ptr
= bf
->buffer
;
645 bf
->buf_end
= bf
->buffer
+ initlen
;
646 bf
->buf_end
[0] = CH_EOB
; /* put eob symbol */
647 pstrcpy(bf
->filename
, sizeof(bf
->filename
), filename
);
649 normalize_slashes(bf
->filename
);
652 bf
->ifndef_macro
= 0;
653 bf
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
659 ST_FUNC
void tcc_close(void)
661 BufferedFile
*bf
= file
;
664 total_lines
+= bf
->line_num
;
670 ST_FUNC
int tcc_open(TCCState
*s1
, const char *filename
)
673 if (strcmp(filename
, "-") == 0)
674 fd
= 0, filename
= "stdin";
676 fd
= open(filename
, O_RDONLY
| O_BINARY
);
677 if ((s1
->verbose
== 2 && fd
>= 0) || s1
->verbose
== 3)
678 printf("%s %*s%s\n", fd
< 0 ? "nf":"->",
679 (int)(s1
->include_stack_ptr
- s1
->include_stack
), "", filename
);
683 tcc_open_bf(s1
, filename
, 0);
688 /* compile the C file opened in 'file'. Return non zero if errors. */
689 static int tcc_compile(TCCState
*s1
)
693 volatile int section_sym
;
696 printf("%s: **** new file\n", file
->filename
);
700 cur_text_section
= NULL
;
702 anon_sym
= SYM_FIRST_ANOM
;
704 /* file info: full path + filename */
705 section_sym
= 0; /* avoid warning */
707 section_sym
= put_elf_sym(symtab_section
, 0, 0,
708 ELFW(ST_INFO
)(STB_LOCAL
, STT_SECTION
), 0,
709 text_section
->sh_num
, NULL
);
710 getcwd(buf
, sizeof(buf
));
712 normalize_slashes(buf
);
714 pstrcat(buf
, sizeof(buf
), "/");
715 put_stabs_r(buf
, N_SO
, 0, 0,
716 text_section
->data_offset
, text_section
, section_sym
);
717 put_stabs_r(file
->filename
, N_SO
, 0, 0,
718 text_section
->data_offset
, text_section
, section_sym
);
720 /* an elf symbol of type STT_FILE must be put so that STB_LOCAL
721 symbols can be safely used */
722 put_elf_sym(symtab_section
, 0, 0,
723 ELFW(ST_INFO
)(STB_LOCAL
, STT_FILE
), 0,
724 SHN_ABS
, file
->filename
);
726 /* define some often used types */
729 char_pointer_type
.t
= VT_BYTE
;
730 mk_pointer(&char_pointer_type
);
732 func_old_type
.t
= VT_FUNC
;
733 func_old_type
.ref
= sym_push(SYM_FIELD
, &int_type
, FUNC_CDECL
, FUNC_OLD
);
735 #if defined(TCC_ARM_EABI) && defined(TCC_ARM_VFP)
736 float_type
.t
= VT_FLOAT
;
737 double_type
.t
= VT_DOUBLE
;
739 func_float_type
.t
= VT_FUNC
;
740 func_float_type
.ref
= sym_push(SYM_FIELD
, &float_type
, FUNC_CDECL
, FUNC_OLD
);
741 func_double_type
.t
= VT_FUNC
;
742 func_double_type
.ref
= sym_push(SYM_FIELD
, &double_type
, FUNC_CDECL
, FUNC_OLD
);
746 /* define 'void *alloca(unsigned int)' builtin function */
751 sym
= sym_push(p
, mk_pointer(VT_VOID
), FUNC_CDECL
, FUNC_NEW
);
752 s1
= sym_push(SYM_FIELD
, VT_UNSIGNED
| VT_INT
, 0, 0);
755 sym_push(TOK_alloca
, VT_FUNC
| (p
<< VT_STRUCT_SHIFT
), VT_CONST
, 0);
759 define_start
= define_stack
;
762 if (setjmp(s1
->error_jmp_buf
) == 0) {
764 s1
->error_set_jmp_enabled
= 1;
766 ch
= file
->buf_ptr
[0];
767 tok_flags
= TOK_FLAG_BOL
| TOK_FLAG_BOF
;
768 parse_flags
= PARSE_FLAG_PREPROCESS
| PARSE_FLAG_TOK_NUM
;
772 expect("declaration");
774 /* end of translation unit info */
776 put_stabs_r(NULL
, N_SO
, 0, 0,
777 text_section
->data_offset
, text_section
, section_sym
);
780 s1
->error_set_jmp_enabled
= 0;
782 /* reset define stack, but leave -Dsymbols (may be incorrect if
783 they are undefined) */
784 free_defines(define_start
);
786 gen_inline_functions();
788 sym_pop(&global_stack
, NULL
);
789 sym_pop(&local_stack
, NULL
);
791 return s1
->nb_errors
!= 0 ? -1 : 0;
794 LIBTCCAPI
int tcc_compile_string(TCCState
*s
, const char *str
)
799 tcc_open_bf(s
, "<string>", len
);
800 memcpy(file
->buffer
, str
, len
);
801 ret
= tcc_compile(s
);
806 /* define a preprocessor symbol. A value can also be provided with the '=' operator */
807 LIBTCCAPI
void tcc_define_symbol(TCCState
*s1
, const char *sym
, const char *value
)
814 len2
= strlen(value
);
816 /* init file structure */
817 tcc_open_bf(s1
, "<define>", len1
+ len2
+ 1);
818 memcpy(file
->buffer
, sym
, len1
);
819 file
->buffer
[len1
] = ' ';
820 memcpy(file
->buffer
+ len1
+ 1, value
, len2
);
822 /* parse with define parser */
823 ch
= file
->buf_ptr
[0];
830 /* undefine a preprocessor symbol */
831 LIBTCCAPI
void tcc_undefine_symbol(TCCState
*s1
, const char *sym
)
835 ts
= tok_alloc(sym
, strlen(sym
));
836 s
= define_find(ts
->tok
);
837 /* undefine symbol by putting an invalid name */
842 static void tcc_cleanup(void)
846 if (NULL
== tcc_state
)
850 /* free -D defines */
854 n
= tok_ident
- TOK_IDENT
;
855 for(i
= 0; i
< n
; i
++)
856 tcc_free(table_ident
[i
]);
857 tcc_free(table_ident
);
860 dynarray_reset(&sym_pools
, &nb_sym_pools
);
863 /* reset symbol stack */
864 sym_free_first
= NULL
;
865 /* cleanup from error/setjmp */
869 LIBTCCAPI TCCState
*tcc_new(void)
877 s
= tcc_mallocz(sizeof(TCCState
));
882 tcc_set_lib_path_w32(s
);
884 tcc_set_lib_path(s
, CONFIG_TCCDIR
);
886 s
->output_type
= TCC_OUTPUT_MEMORY
;
888 s
->include_stack_ptr
= s
->include_stack
;
890 /* we add dummy defines for some special macros to speed up tests
891 and to have working defined() */
892 define_push(TOK___LINE__
, MACRO_OBJ
, NULL
, NULL
);
893 define_push(TOK___FILE__
, MACRO_OBJ
, NULL
, NULL
);
894 define_push(TOK___DATE__
, MACRO_OBJ
, NULL
, NULL
);
895 define_push(TOK___TIME__
, MACRO_OBJ
, NULL
, NULL
);
897 /* standard defines */
898 tcc_define_symbol(s
, "__STDC__", NULL
);
899 tcc_define_symbol(s
, "__STDC_VERSION__", "199901L");
900 #if defined(TCC_TARGET_I386)
901 tcc_define_symbol(s
, "__i386__", NULL
);
902 tcc_define_symbol(s
, "__i386", NULL
);
903 tcc_define_symbol(s
, "i386", NULL
);
905 #if defined(TCC_TARGET_X86_64)
906 tcc_define_symbol(s
, "__x86_64__", NULL
);
908 #if defined(TCC_TARGET_ARM)
909 tcc_define_symbol(s
, "__ARM_ARCH_4__", NULL
);
910 tcc_define_symbol(s
, "__arm_elf__", NULL
);
911 tcc_define_symbol(s
, "__arm_elf", NULL
);
912 tcc_define_symbol(s
, "arm_elf", NULL
);
913 tcc_define_symbol(s
, "__arm__", NULL
);
914 tcc_define_symbol(s
, "__arm", NULL
);
915 tcc_define_symbol(s
, "arm", NULL
);
916 tcc_define_symbol(s
, "__APCS_32__", NULL
);
919 tcc_define_symbol(s
, "_WIN32", NULL
);
920 #ifdef TCC_TARGET_X86_64
921 tcc_define_symbol(s
, "_WIN64", NULL
);
924 tcc_define_symbol(s
, "__unix__", NULL
);
925 tcc_define_symbol(s
, "__unix", NULL
);
926 tcc_define_symbol(s
, "unix", NULL
);
927 #if defined(__FreeBSD__)
929 tcc_define_symbol(s
, "__FreeBSD__", str( __FreeBSD__
));
932 #if defined(__FreeBSD_kernel__)
933 tcc_define_symbol(s
, "__FreeBSD_kernel__", NULL
);
936 tcc_define_symbol(s
, "__linux__", NULL
);
937 tcc_define_symbol(s
, "__linux", NULL
);
940 /* tiny C specific defines */
941 sscanf(TCC_VERSION
, "%d.%d.%d", &a
, &b
, &c
);
942 sprintf(buffer
, "%d", a
*10000 + b
*100 + c
);
943 tcc_define_symbol(s
, "__TINYC__", buffer
);
945 /* tiny C & gcc defines */
946 #if defined TCC_TARGET_PE && defined TCC_TARGET_X86_64
947 tcc_define_symbol(s
, "__SIZE_TYPE__", "unsigned long long");
948 tcc_define_symbol(s
, "__PTRDIFF_TYPE__", "long long");
950 tcc_define_symbol(s
, "__SIZE_TYPE__", "unsigned long");
951 tcc_define_symbol(s
, "__PTRDIFF_TYPE__", "long");
955 tcc_define_symbol(s
, "__WCHAR_TYPE__", "unsigned short");
957 tcc_define_symbol(s
, "__WCHAR_TYPE__", "int");
961 tcc_define_symbol(s
, "__REDIRECT_NTH(name, proto, alias)", "name proto __asm__ (#alias) __THROW");
963 #ifndef TCC_TARGET_PE
964 /* default library paths */
965 tcc_add_library_path(s
, CONFIG_TCC_CRT_PREFIX
);
966 tcc_add_library_path(s
, CONFIG_SYSROOT CONFIG_TCC_LDDIR
);
967 tcc_add_library_path(s
, CONFIG_SYSROOT
"/usr/local"CONFIG_TCC_LDDIR
);
970 /* no section zero */
971 dynarray_add((void ***)&s
->sections
, &s
->nb_sections
, NULL
);
973 /* create standard sections */
974 text_section
= new_section(s
, ".text", SHT_PROGBITS
, SHF_ALLOC
| SHF_EXECINSTR
);
975 data_section
= new_section(s
, ".data", SHT_PROGBITS
, SHF_ALLOC
| SHF_WRITE
);
976 bss_section
= new_section(s
, ".bss", SHT_NOBITS
, SHF_ALLOC
| SHF_WRITE
);
978 /* symbols are always generated for linking stage */
979 symtab_section
= new_symtab(s
, ".symtab", SHT_SYMTAB
, 0,
981 ".hashtab", SHF_PRIVATE
);
982 strtab_section
= symtab_section
->link
;
984 /* private symbol table for dynamic symbols */
985 s
->dynsymtab_section
= new_symtab(s
, ".dynsymtab", SHT_SYMTAB
, SHF_PRIVATE
,
987 ".dynhashtab", SHF_PRIVATE
);
988 s
->alacarte_link
= 1;
991 #ifdef CHAR_IS_UNSIGNED
992 s
->char_is_unsigned
= 1;
994 #if defined(TCC_TARGET_PE) && 0
995 /* XXX: currently the PE linker is not ready to support that */
996 s
->leading_underscore
= 1;
998 if (s
->section_align
== 0)
999 s
->section_align
= ELF_PAGE_SIZE
;
1000 #ifdef TCC_TARGET_I386
1006 LIBTCCAPI
void tcc_delete(TCCState
*s1
)
1012 /* free all sections */
1013 for(i
= 1; i
< s1
->nb_sections
; i
++)
1014 free_section(s1
->sections
[i
]);
1015 dynarray_reset(&s1
->sections
, &s1
->nb_sections
);
1017 for(i
= 0; i
< s1
->nb_priv_sections
; i
++)
1018 free_section(s1
->priv_sections
[i
]);
1019 dynarray_reset(&s1
->priv_sections
, &s1
->nb_priv_sections
);
1021 /* free any loaded DLLs */
1022 for ( i
= 0; i
< s1
->nb_loaded_dlls
; i
++) {
1023 DLLReference
*ref
= s1
->loaded_dlls
[i
];
1025 dlclose(ref
->handle
);
1028 /* free loaded dlls array */
1029 dynarray_reset(&s1
->loaded_dlls
, &s1
->nb_loaded_dlls
);
1031 /* free library paths */
1032 dynarray_reset(&s1
->library_paths
, &s1
->nb_library_paths
);
1034 /* free include paths */
1035 dynarray_reset(&s1
->cached_includes
, &s1
->nb_cached_includes
);
1036 dynarray_reset(&s1
->include_paths
, &s1
->nb_include_paths
);
1037 dynarray_reset(&s1
->sysinclude_paths
, &s1
->nb_sysinclude_paths
);
1039 tcc_free(s1
->tcc_lib_path
);
1041 dynarray_reset(&s1
->input_files
, &s1
->nb_input_files
);
1042 dynarray_reset(&s1
->input_libs
, &s1
->nb_input_libs
);
1043 dynarray_reset(&s1
->target_deps
, &s1
->nb_target_deps
);
1046 munmap (s1
->write_mem
, s1
->mem_size
);
1047 munmap (s1
->runtime_mem
, s1
->mem_size
);
1049 tcc_free(s1
->runtime_mem
);
1054 LIBTCCAPI
int tcc_add_include_path(TCCState
*s1
, const char *pathname
)
1058 pathname1
= tcc_strdup(pathname
);
1059 dynarray_add((void ***)&s1
->include_paths
, &s1
->nb_include_paths
, pathname1
);
1063 LIBTCCAPI
int tcc_add_sysinclude_path(TCCState
*s1
, const char *pathname
)
1067 pathname1
= tcc_strdup(pathname
);
1068 dynarray_add((void ***)&s1
->sysinclude_paths
, &s1
->nb_sysinclude_paths
, pathname1
);
1072 ST_FUNC
int tcc_add_file_internal(TCCState
*s1
, const char *filename
, int flags
)
1078 /* find source file type with extension */
1079 ext
= tcc_fileextension(filename
);
1084 ret
= tcc_open(s1
, filename
);
1086 if (flags
& AFF_PRINT_ERROR
)
1087 error_noabort("file '%s' not found", filename
);
1091 /* update target deps */
1092 dynarray_add((void ***)&s1
->target_deps
, &s1
->nb_target_deps
,
1093 tcc_strdup(filename
));
1095 if (flags
& AFF_PREPROCESS
) {
1096 ret
= tcc_preprocess(s1
);
1100 if (!ext
[0] || !PATHCMP(ext
, "c")) {
1101 /* C file assumed */
1102 ret
= tcc_compile(s1
);
1106 #ifdef CONFIG_TCC_ASM
1107 if (!strcmp(ext
, "S")) {
1108 /* preprocessed assembler */
1109 ret
= tcc_assemble(s1
, 1);
1113 if (!strcmp(ext
, "s")) {
1114 /* non preprocessed assembler */
1115 ret
= tcc_assemble(s1
, 0);
1121 /* assume executable format: auto guess file type */
1122 size
= read(fd
, &ehdr
, sizeof(ehdr
));
1123 lseek(fd
, 0, SEEK_SET
);
1125 error_noabort("could not read header");
1129 if (size
== sizeof(ehdr
) &&
1130 ehdr
.e_ident
[0] == ELFMAG0
&&
1131 ehdr
.e_ident
[1] == ELFMAG1
&&
1132 ehdr
.e_ident
[2] == ELFMAG2
&&
1133 ehdr
.e_ident
[3] == ELFMAG3
) {
1135 /* do not display line number if error */
1137 if (ehdr
.e_type
== ET_REL
) {
1138 ret
= tcc_load_object_file(s1
, fd
, 0);
1142 #ifndef TCC_TARGET_PE
1143 if (ehdr
.e_type
== ET_DYN
) {
1144 if (s1
->output_type
== TCC_OUTPUT_MEMORY
) {
1146 h
= dlopen(filename
, RTLD_GLOBAL
| RTLD_LAZY
);
1150 ret
= tcc_load_dll(s1
, fd
, filename
,
1151 (flags
& AFF_REFERENCED_DLL
) != 0);
1156 error_noabort("unrecognized ELF file");
1160 if (memcmp((char *)&ehdr
, ARMAG
, 8) == 0) {
1161 file
->line_num
= 0; /* do not display line number if error */
1162 ret
= tcc_load_archive(s1
, fd
);
1166 #ifdef TCC_TARGET_COFF
1167 if (*(uint16_t *)(&ehdr
) == COFF_C67_MAGIC
) {
1168 ret
= tcc_load_coff(s1
, fd
);
1173 #ifdef TCC_TARGET_PE
1174 ret
= pe_load_file(s1
, filename
, fd
);
1176 /* as GNU ld, consider it is an ld script if not recognized */
1177 ret
= tcc_load_ldscript(s1
);
1180 error_noabort("unrecognized file type");
1187 LIBTCCAPI
int tcc_add_file(TCCState
*s
, const char *filename
)
1189 dynarray_add((void ***)&s
->input_files
, &s
->nb_input_files
, tcc_strdup(filename
));
1191 if (s
->output_type
== TCC_OUTPUT_PREPROCESS
)
1192 return tcc_add_file_internal(s
, filename
, AFF_PRINT_ERROR
| AFF_PREPROCESS
);
1194 return tcc_add_file_internal(s
, filename
, AFF_PRINT_ERROR
);
1197 LIBTCCAPI
int tcc_add_library_path(TCCState
*s
, const char *pathname
)
1201 pathname1
= tcc_strdup(pathname
);
1202 dynarray_add((void ***)&s
->library_paths
, &s
->nb_library_paths
, pathname1
);
1206 /* find and load a dll. Return non zero if not found */
1207 /* XXX: add '-rpath' option support ? */
1208 ST_FUNC
int tcc_add_dll(TCCState
*s
, const char *filename
, int flags
)
1213 for(i
= 0; i
< s
->nb_library_paths
; i
++) {
1214 snprintf(buf
, sizeof(buf
), "%s/%s",
1215 s
->library_paths
[i
], filename
);
1216 if (tcc_add_file_internal(s
, buf
, flags
) == 0)
1222 /* the library name is the same as the argument of the '-l' option */
1223 LIBTCCAPI
int tcc_add_library(TCCState
*s
, const char *libraryname
)
1228 dynarray_add((void ***)&s
->input_libs
, &s
->nb_input_libs
, tcc_strdup(libraryname
));
1230 /* first we look for the dynamic library if not static linking */
1231 if (!s
->static_link
) {
1232 #ifdef TCC_TARGET_PE
1233 if (pe_add_dll(s
, libraryname
) == 0)
1236 snprintf(buf
, sizeof(buf
), "lib%s.so", libraryname
);
1237 if (tcc_add_dll(s
, buf
, 0) == 0)
1241 /* then we look for the static library */
1242 for(i
= 0; i
< s
->nb_library_paths
; i
++) {
1243 snprintf(buf
, sizeof(buf
), "%s/lib%s.a",
1244 s
->library_paths
[i
], libraryname
);
1245 if (tcc_add_file_internal(s
, buf
, 0) == 0)
1251 LIBTCCAPI
int tcc_add_symbol(TCCState
*s
, const char *name
, const void *val
)
1253 #ifdef TCC_TARGET_PE
1254 pe_putimport(s
, 0, name
, val
);
1256 add_elf_sym(symtab_section
, (uplong
)val
, 0,
1257 ELFW(ST_INFO
)(STB_GLOBAL
, STT_NOTYPE
), 0,
1263 LIBTCCAPI
int tcc_set_output_type(TCCState
*s
, int output_type
)
1267 s
->output_type
= output_type
;
1270 /* default include paths */
1271 /* XXX: reverse order needed if -isystem support */
1272 #ifndef TCC_TARGET_PE
1273 tcc_add_sysinclude_path(s
, CONFIG_SYSROOT
"/usr/local/include");
1274 tcc_add_sysinclude_path(s
, CONFIG_SYSROOT
"/usr/include");
1276 snprintf(buf
, sizeof(buf
), "%s/include", s
->tcc_lib_path
);
1277 tcc_add_sysinclude_path(s
, buf
);
1278 #ifdef TCC_TARGET_PE
1279 snprintf(buf
, sizeof(buf
), "%s/include/winapi", s
->tcc_lib_path
);
1280 tcc_add_sysinclude_path(s
, buf
);
1284 /* if bound checking, then add corresponding sections */
1285 #ifdef CONFIG_TCC_BCHECK
1286 if (s
->do_bounds_check
) {
1288 tcc_define_symbol(s
, "__BOUNDS_CHECKING_ON", NULL
);
1289 /* create bounds sections */
1290 bounds_section
= new_section(s
, ".bounds",
1291 SHT_PROGBITS
, SHF_ALLOC
);
1292 lbounds_section
= new_section(s
, ".lbounds",
1293 SHT_PROGBITS
, SHF_ALLOC
);
1297 if (s
->char_is_unsigned
) {
1298 tcc_define_symbol(s
, "__CHAR_UNSIGNED__", NULL
);
1301 /* add debug sections */
1304 stab_section
= new_section(s
, ".stab", SHT_PROGBITS
, 0);
1305 stab_section
->sh_entsize
= sizeof(Stab_Sym
);
1306 stabstr_section
= new_section(s
, ".stabstr", SHT_STRTAB
, 0);
1307 put_elf_str(stabstr_section
, "");
1308 stab_section
->link
= stabstr_section
;
1309 /* put first entry */
1310 put_stabs("", 0, 0, 0, 0);
1313 /* add libc crt1/crti objects */
1314 #ifndef TCC_TARGET_PE
1315 if ((output_type
== TCC_OUTPUT_EXE
|| output_type
== TCC_OUTPUT_DLL
) &&
1317 if (output_type
!= TCC_OUTPUT_DLL
)
1318 tcc_add_file(s
, CONFIG_TCC_CRT_PREFIX
"/crt1.o");
1319 tcc_add_file(s
, CONFIG_TCC_CRT_PREFIX
"/crti.o");
1323 #ifdef TCC_TARGET_PE
1324 #ifdef CONFIG_TCC_CROSSLIB
1325 snprintf(buf
, sizeof(buf
), "%s/" CONFIG_TCC_CROSSLIB
, s
->tcc_lib_path
);
1326 tcc_add_library_path(s
, buf
);
1328 snprintf(buf
, sizeof(buf
), "%s/lib", s
->tcc_lib_path
);
1329 tcc_add_library_path(s
, buf
);
1331 if (GetSystemDirectory(buf
, sizeof buf
))
1332 tcc_add_library_path(s
, buf
);
1339 #define WD_ALL 0x0001 /* warning is activated when using -Wall */
1340 #define FD_INVERT 0x0002 /* invert value before storing */
1342 typedef struct FlagDef
{
1348 static const FlagDef warning_defs
[] = {
1349 { offsetof(TCCState
, warn_unsupported
), 0, "unsupported" },
1350 { offsetof(TCCState
, warn_write_strings
), 0, "write-strings" },
1351 { offsetof(TCCState
, warn_error
), 0, "error" },
1352 { offsetof(TCCState
, warn_implicit_function_declaration
), WD_ALL
,
1353 "implicit-function-declaration" },
1356 ST_FUNC
int set_flag(TCCState
*s
, const FlagDef
*flags
, int nb_flags
,
1357 const char *name
, int value
)
1364 if (r
[0] == 'n' && r
[1] == 'o' && r
[2] == '-') {
1368 for(i
= 0, p
= flags
; i
< nb_flags
; i
++, p
++) {
1369 if (!strcmp(r
, p
->name
))
1374 if (p
->flags
& FD_INVERT
)
1376 *(int *)((uint8_t *)s
+ p
->offset
) = value
;
1380 /* set/reset a warning */
1381 LIBTCCAPI
int tcc_set_warning(TCCState
*s
, const char *warning_name
, int value
)
1386 if (!strcmp(warning_name
, "all")) {
1387 for(i
= 0, p
= warning_defs
; i
< countof(warning_defs
); i
++, p
++) {
1388 if (p
->flags
& WD_ALL
)
1389 *(int *)((uint8_t *)s
+ p
->offset
) = 1;
1393 return set_flag(s
, warning_defs
, countof(warning_defs
),
1394 warning_name
, value
);
1398 static const FlagDef flag_defs
[] = {
1399 { offsetof(TCCState
, char_is_unsigned
), 0, "unsigned-char" },
1400 { offsetof(TCCState
, char_is_unsigned
), FD_INVERT
, "signed-char" },
1401 { offsetof(TCCState
, nocommon
), FD_INVERT
, "common" },
1402 { offsetof(TCCState
, leading_underscore
), 0, "leading-underscore" },
1405 /* set/reset a flag */
1406 PUB_FUNC
int tcc_set_flag(TCCState
*s
, const char *flag_name
, int value
)
1408 return set_flag(s
, flag_defs
, countof(flag_defs
),
1413 static int strstart(const char *str
, const char *val
, char **ptr
)
1418 while (*q
!= '\0') {
1430 /* Like strstart, but automatically takes into account that ld options can
1432 * - start with double or single dash (e.g. '--soname' or '-soname')
1433 * - arguments can be given as separate or after '=' (e.g. '-Wl,-soname,x.so'
1434 * or '-Wl,-soname=x.so')
1436 * you provide `val` always in 'option[=]' form (no leading -)
1438 static int link_option(const char *str
, const char *val
, char **ptr
)
1442 /* there should be 1 or 2 dashes */
1448 /* then str & val should match (potentialy up to '=') */
1452 while (*q
!= '\0' && *q
!= '=') {
1459 /* '=' near eos means ',' or '=' is ok */
1461 if (*p
!= ',' && *p
!= '=')
1473 /* set linker options */
1474 PUB_FUNC
const char * tcc_set_linker(TCCState
*s
, char *option
, int multi
)
1479 while (option
&& *option
) {
1481 if (link_option(option
, "Bsymbolic", &p
)) {
1483 #ifdef TCC_TARGET_PE
1484 } else if (link_option(option
, "file-alignment=", &p
)) {
1485 s
->pe_file_align
= strtoul(p
, &end
, 16);
1487 } else if (link_option(option
, "fini=", &p
)) {
1489 if (s
->warn_unsupported
)
1490 warning("ignoring -fini %s", p
);
1492 } else if (link_option(option
, "image-base=", &p
)) {
1493 s
->text_addr
= strtoul(p
, &end
, 16);
1494 s
->has_text_addr
= 1;
1495 } else if (link_option(option
, "init=", &p
)) {
1497 if (s
->warn_unsupported
)
1498 warning("ignoring -init %s", p
);
1500 } else if (link_option(option
, "oformat=", &p
)) {
1501 #if defined(TCC_TARGET_PE)
1502 if (strstart(p
, "pe-", NULL
)) {
1504 #if defined(TCC_TARGET_X86_64)
1505 if (strstart(p
, "elf64-", NULL
)) {
1507 if (strstart(p
, "elf32-", NULL
)) {
1510 s
->output_format
= TCC_OUTPUT_FORMAT_ELF
;
1511 } else if (!strcmp(p
, "binary")) {
1512 s
->output_format
= TCC_OUTPUT_FORMAT_BINARY
;
1514 #ifdef TCC_TARGET_COFF
1515 if (!strcmp(p
, "coff")) {
1516 s
->output_format
= TCC_OUTPUT_FORMAT_COFF
;
1523 } else if (link_option(option
, "rpath=", &p
)) {
1525 } else if (link_option(option
, "section-alignment=", &p
)) {
1526 s
->section_align
= strtoul(p
, &end
, 16);
1527 } else if (link_option(option
, "soname=", &p
)) {
1530 #ifdef TCC_TARGET_PE
1531 } else if (link_option(option
, "subsystem=", &p
)) {
1532 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
1533 if (!strcmp(p
, "native")) {
1534 s
->pe_subsystem
= 1;
1535 } else if (!strcmp(p
, "console")) {
1536 s
->pe_subsystem
= 3;
1537 } else if (!strcmp(p
, "gui")) {
1538 s
->pe_subsystem
= 2;
1539 } else if (!strcmp(p
, "posix")) {
1540 s
->pe_subsystem
= 7;
1541 } else if (!strcmp(p
, "efiapp")) {
1542 s
->pe_subsystem
= 10;
1543 } else if (!strcmp(p
, "efiboot")) {
1544 s
->pe_subsystem
= 11;
1545 } else if (!strcmp(p
, "efiruntime")) {
1546 s
->pe_subsystem
= 12;
1547 } else if (!strcmp(p
, "efirom")) {
1548 s
->pe_subsystem
= 13;
1549 #elif defined(TCC_TARGET_ARM)
1550 if (!strcmp(p
, "wince")) {
1551 s
->pe_subsystem
= 9;
1558 } else if (link_option(option
, "Ttext=", &p
)) {
1559 s
->text_addr
= strtoul(p
, &end
, 16);
1560 s
->has_text_addr
= 1;
1568 p
= strchr( (end
) ? end
: p
, ',');
1570 *p
= 0; /* terminate last option */
1579 PUB_FUNC
void tcc_print_stats(TCCState
*s
, int64_t total_time
)
1582 tt
= (double)total_time
/ 1000000.0;
1585 if (total_bytes
< 1)
1587 printf("%d idents, %d lines, %d bytes, %0.3f s, %d lines/s, %0.1f MB/s\n",
1588 tok_ident
- TOK_IDENT
, total_lines
, total_bytes
,
1589 tt
, (int)(total_lines
/ tt
),
1590 total_bytes
/ tt
/ 1000000.0);
1593 /* set CONFIG_TCCDIR at runtime */
1594 LIBTCCAPI
void tcc_set_lib_path(TCCState
*s
, const char *path
)
1596 tcc_free(s
->tcc_lib_path
);
1597 s
->tcc_lib_path
= tcc_strdup(path
);
1600 PUB_FUNC
void set_num_callers(int n
)
1602 #ifdef CONFIG_TCC_BACKTRACE
1608 LIBTCCAPI
const char *tcc_default_target(TCCState
*s
)
1610 /* FIXME will break in multithreaded case */
1611 static char outfile_default
[1024];
1615 strcmp(s
->input_files
[0], "-") == 0 ? "a"
1616 : tcc_basename(s
->input_files
[0]);
1617 pstrcpy(outfile_default
, sizeof(outfile_default
), name
);
1618 ext
= tcc_fileextension(outfile_default
);
1619 #ifdef TCC_TARGET_PE
1620 if (s
->output_type
== TCC_OUTPUT_DLL
)
1621 strcpy(ext
, ".dll");
1623 if (s
->output_type
== TCC_OUTPUT_EXE
)
1624 strcpy(ext
, ".exe");
1627 if (( (s
->output_type
== TCC_OUTPUT_OBJ
&& !s
->reloc_output
) ||
1628 (s
->output_type
== TCC_OUTPUT_PREPROCESS
) )
1632 pstrcpy(outfile_default
, sizeof(outfile_default
), "a.out");
1634 return outfile_default
;
1638 LIBTCCAPI
void tcc_gen_makedeps(TCCState
*s
, const char *target
, const char *filename
)
1641 char buf
[1024], *ext
;
1645 target
= tcc_default_target(s
);
1648 /* compute filename automatically
1649 * dir/file.o -> dir/file.d */
1650 pstrcpy(buf
, sizeof(buf
), target
);
1651 ext
= tcc_fileextension(buf
);
1652 pstrcpy(ext
, sizeof(buf
) - (ext
-buf
), ".d");
1657 printf("<- %s\n", filename
);
1659 /* XXX return err codes instead of error() ? */
1660 depout
= fopen(filename
, "w");
1662 error("could not open '%s'", filename
);
1664 fprintf(depout
, "%s : \\\n", target
);
1665 for (i
=0; i
<s
->nb_target_deps
; ++i
)
1666 fprintf(depout
, "\t%s \\\n", s
->target_deps
[i
]);
1667 fprintf(depout
, "\n");