2 * TCC - Tiny C Compiler
4 * Copyright (c) 2001-2004 Fabrice Bellard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 #define NEED_FLOAT_TYPES
24 /********************************************************/
25 /* global variables */
27 /* use GNU C extensions */
28 ST_DATA
int gnu_ext
= 1;
30 /* use TinyCC extensions */
31 ST_DATA
int tcc_ext
= 1;
33 /* XXX: get rid of this ASAP */
34 ST_DATA
struct TCCState
*tcc_state
;
36 #ifdef CONFIG_TCC_BACKTRACE
37 ST_DATA
int num_callers
= 6;
38 ST_DATA
const char **rt_bound_error_msg
;
39 ST_DATA
void *rt_prog_main
;
42 /********************************************************/
49 #ifdef TCC_TARGET_I386
58 #ifdef TCC_TARGET_X86_64
59 #include "x86_64-gen.c"
63 #if defined TCC_TARGET_I386 || defined TCC_TARGET_X86_64
67 #ifdef TCC_TARGET_COFF
73 #endif /* ALL_IN_ONE */
75 /********************************************************/
76 #ifndef CONFIG_TCC_ASM
77 ST_FUNC
void asm_instr(void)
79 error("inline asm() not supported");
81 ST_FUNC
void asm_global_instr(void)
83 error("inline asm() not supported");
87 /********************************************************/
90 static char *normalize_slashes(char *path
)
93 for (p
= path
; *p
; ++p
)
99 static HMODULE tcc_module
;
101 /* on win32, we suppose the lib and includes are at the location of 'tcc.exe' */
102 static void tcc_set_lib_path_w32(TCCState
*s
)
105 GetModuleFileNameA(tcc_module
, path
, sizeof path
);
106 p
= tcc_basename(normalize_slashes(strlwr(path
)));
107 if (p
- 5 > path
&& 0 == strncmp(p
- 5, "/bin/", 5))
112 tcc_set_lib_path(s
, path
);
115 #ifndef CONFIG_TCC_STATIC
116 void dlclose(void *p
)
118 FreeLibrary((HMODULE
)p
);
123 BOOL WINAPI
DllMain (HANDLE hDll
, DWORD dwReason
, LPVOID lpReserved
)
125 if (DLL_PROCESS_ATTACH
== dwReason
)
132 /********************************************************/
133 /* copy a string and truncate it. */
134 PUB_FUNC
char *pstrcpy(char *buf
, int buf_size
, const char *s
)
141 q_end
= buf
+ buf_size
- 1;
153 /* strcat and truncate. */
154 PUB_FUNC
char *pstrcat(char *buf
, int buf_size
, const char *s
)
159 pstrcpy(buf
+ len
, buf_size
- len
, s
);
163 /* extract the basename of a file */
164 PUB_FUNC
char *tcc_basename(const char *name
)
166 char *p
= strchr(name
, 0);
167 while (p
> name
&& !IS_PATHSEP(p
[-1]))
172 /* extract extension part of a file
174 * (if no extension, return pointer to end-of-string)
176 PUB_FUNC
char *tcc_fileextension (const char *name
)
178 char *b
= tcc_basename(name
);
179 char *e
= strrchr(b
, '.');
180 return e
? e
: strchr(b
, 0);
183 /********************************************************/
184 /* memory management */
193 unsigned malloc_usable_size(void*);
196 PUB_FUNC
void tcc_free(void *ptr
)
199 mem_cur_size
-= malloc_usable_size(ptr
);
204 PUB_FUNC
void *tcc_malloc(unsigned long size
)
209 error("memory full");
211 mem_cur_size
+= malloc_usable_size(ptr
);
212 if (mem_cur_size
> mem_max_size
)
213 mem_max_size
= mem_cur_size
;
218 PUB_FUNC
void *tcc_mallocz(unsigned long size
)
221 ptr
= tcc_malloc(size
);
222 memset(ptr
, 0, size
);
226 PUB_FUNC
void *tcc_realloc(void *ptr
, unsigned long size
)
230 mem_cur_size
-= malloc_usable_size(ptr
);
232 ptr1
= realloc(ptr
, size
);
234 /* NOTE: count not correct if alloc error, but not critical */
235 mem_cur_size
+= malloc_usable_size(ptr1
);
236 if (mem_cur_size
> mem_max_size
)
237 mem_max_size
= mem_cur_size
;
242 PUB_FUNC
char *tcc_strdup(const char *str
)
245 ptr
= tcc_malloc(strlen(str
) + 1);
250 PUB_FUNC
void tcc_memstats(void)
253 printf("memory in use: %d\n", mem_cur_size
);
257 #define free(p) use_tcc_free(p)
258 #define malloc(s) use_tcc_malloc(s)
259 #define realloc(p, s) use_tcc_realloc(p, s)
261 /********************************************************/
264 PUB_FUNC
void dynarray_add(void ***ptab
, int *nb_ptr
, void *data
)
271 /* every power of two we double array size */
272 if ((nb
& (nb
- 1)) == 0) {
277 pp
= tcc_realloc(pp
, nb_alloc
* sizeof(void *));
279 error("memory full");
286 PUB_FUNC
void dynarray_reset(void *pp
, int *n
)
289 for (p
= *(void***)pp
; *n
; ++p
, --*n
)
292 tcc_free(*(void**)pp
);
296 /* we use our own 'finite' function to avoid potential problems with
297 non standard math libs */
298 /* XXX: endianness dependent */
299 ST_FUNC
int ieee_finite(double d
)
302 return ((unsigned)((p
[1] | 0x800fffff) + 1)) >> 31;
305 /********************************************************/
307 ST_FUNC Section
*new_section(TCCState
*s1
, const char *name
, int sh_type
, int sh_flags
)
311 sec
= tcc_mallocz(sizeof(Section
) + strlen(name
));
312 strcpy(sec
->name
, name
);
313 sec
->sh_type
= sh_type
;
314 sec
->sh_flags
= sh_flags
;
322 sec
->sh_addralign
= 4;
325 sec
->sh_addralign
= 1;
328 sec
->sh_addralign
= 32; /* default conservative alignment */
332 if (sh_flags
& SHF_PRIVATE
) {
333 dynarray_add((void ***)&s1
->priv_sections
, &s1
->nb_priv_sections
, sec
);
335 sec
->sh_num
= s1
->nb_sections
;
336 dynarray_add((void ***)&s1
->sections
, &s1
->nb_sections
, sec
);
342 static void free_section(Section
*s
)
347 /* realloc section and set its content to zero */
348 ST_FUNC
void section_realloc(Section
*sec
, unsigned long new_size
)
353 size
= sec
->data_allocated
;
356 while (size
< new_size
)
358 data
= tcc_realloc(sec
->data
, size
);
360 error("memory full");
361 memset(data
+ sec
->data_allocated
, 0, size
- sec
->data_allocated
);
363 sec
->data_allocated
= size
;
366 /* reserve at least 'size' bytes in section 'sec' from
368 ST_FUNC
void *section_ptr_add(Section
*sec
, unsigned long size
)
370 unsigned long offset
, offset1
;
372 offset
= sec
->data_offset
;
373 offset1
= offset
+ size
;
374 if (offset1
> sec
->data_allocated
)
375 section_realloc(sec
, offset1
);
376 sec
->data_offset
= offset1
;
377 return sec
->data
+ offset
;
380 /* reserve at least 'size' bytes from section start */
381 ST_FUNC
void section_reserve(Section
*sec
, unsigned long size
)
383 if (size
> sec
->data_allocated
)
384 section_realloc(sec
, size
);
385 if (size
> sec
->data_offset
)
386 sec
->data_offset
= size
;
389 /* return a reference to a section, and create it if it does not
391 ST_FUNC Section
*find_section(TCCState
*s1
, const char *name
)
395 for(i
= 1; i
< s1
->nb_sections
; i
++) {
396 sec
= s1
->sections
[i
];
397 if (!strcmp(name
, sec
->name
))
400 /* sections are created as PROGBITS */
401 return new_section(s1
, name
, SHT_PROGBITS
, SHF_ALLOC
);
404 /* update sym->c so that it points to an external symbol in section
405 'section' with value 'value' */
406 ST_FUNC
void put_extern_sym2(Sym
*sym
, Section
*section
,
407 unsigned long value
, unsigned long size
,
408 int can_add_underscore
)
410 int sym_type
, sym_bind
, sh_num
, info
, other
;
417 else if (section
== SECTION_ABS
)
420 sh_num
= section
->sh_num
;
422 if ((sym
->type
.t
& VT_BTYPE
) == VT_FUNC
) {
424 } else if ((sym
->type
.t
& VT_BTYPE
) == VT_VOID
) {
425 sym_type
= STT_NOTYPE
;
427 sym_type
= STT_OBJECT
;
430 if (sym
->type
.t
& VT_STATIC
)
431 sym_bind
= STB_LOCAL
;
433 if (sym
->type
.t
& VT_WEAK
)
436 sym_bind
= STB_GLOBAL
;
440 name
= get_tok_str(sym
->v
, NULL
);
441 #ifdef CONFIG_TCC_BCHECK
442 if (tcc_state
->do_bounds_check
) {
445 /* XXX: avoid doing that for statics ? */
446 /* if bound checking is activated, we change some function
447 names by adding the "__bound" prefix */
450 /* XXX: we rely only on malloc hooks */
463 strcpy(buf
, "__bound_");
473 if (sym
->type
.t
& VT_EXPORT
)
475 if (sym_type
== STT_FUNC
&& sym
->type
.ref
) {
476 int attr
= sym
->type
.ref
->r
;
477 if (FUNC_EXPORT(attr
))
479 if (FUNC_CALL(attr
) == FUNC_STDCALL
&& can_add_underscore
) {
480 sprintf(buf1
, "_%s@%d", name
, FUNC_ARGS(attr
) * PTR_SIZE
);
483 can_add_underscore
= 0;
486 if (find_elf_sym(tcc_state
->dynsymtab_section
, name
))
488 if (sym
->type
.t
& VT_IMPORT
)
492 if (tcc_state
->leading_underscore
&& can_add_underscore
) {
494 pstrcpy(buf1
+ 1, sizeof(buf1
) - 1, name
);
497 if (sym
->asm_label
) {
498 name
= sym
->asm_label
;
500 info
= ELFW(ST_INFO
)(sym_bind
, sym_type
);
501 sym
->c
= add_elf_sym(symtab_section
, value
, size
, info
, other
, sh_num
, name
);
503 esym
= &((ElfW(Sym
) *)symtab_section
->data
)[sym
->c
];
504 esym
->st_value
= value
;
505 esym
->st_size
= size
;
506 esym
->st_shndx
= sh_num
;
510 ST_FUNC
void put_extern_sym(Sym
*sym
, Section
*section
,
511 unsigned long value
, unsigned long size
)
513 put_extern_sym2(sym
, section
, value
, size
, 1);
516 /* add a new relocation entry to symbol 'sym' in section 's' */
517 ST_FUNC
void greloc(Section
*s
, Sym
*sym
, unsigned long offset
, int type
)
522 put_extern_sym(sym
, NULL
, 0, 0);
525 /* now we can add ELF relocation info */
526 put_elf_reloc(symtab_section
, s
, offset
, type
, c
);
529 /********************************************************/
531 static void strcat_vprintf(char *buf
, int buf_size
, const char *fmt
, va_list ap
)
535 vsnprintf(buf
+ len
, buf_size
- len
, fmt
, ap
);
538 static void strcat_printf(char *buf
, int buf_size
, const char *fmt
, ...)
542 strcat_vprintf(buf
, buf_size
, fmt
, ap
);
546 static void error1(TCCState
*s1
, int is_warning
, const char *fmt
, va_list ap
)
553 for(f
= s1
->include_stack
; f
< s1
->include_stack_ptr
; f
++)
554 strcat_printf(buf
, sizeof(buf
), "In file included from %s:%d:\n",
555 (*f
)->filename
, (*f
)->line_num
);
556 if (file
->line_num
> 0) {
557 strcat_printf(buf
, sizeof(buf
),
558 "%s:%d: ", file
->filename
, file
->line_num
);
560 strcat_printf(buf
, sizeof(buf
),
561 "%s: ", file
->filename
);
564 strcat_printf(buf
, sizeof(buf
),
568 strcat_printf(buf
, sizeof(buf
), "warning: ");
570 strcat_printf(buf
, sizeof(buf
), "error: ");
571 strcat_vprintf(buf
, sizeof(buf
), fmt
, ap
);
573 if (!s1
->error_func
) {
574 /* default case: stderr */
575 fprintf(stderr
, "%s\n", buf
);
577 s1
->error_func(s1
->error_opaque
, buf
);
579 if (!is_warning
|| s1
->warn_error
)
583 LIBTCCAPI
void tcc_set_error_func(TCCState
*s
, void *error_opaque
,
584 void (*error_func
)(void *opaque
, const char *msg
))
586 s
->error_opaque
= error_opaque
;
587 s
->error_func
= error_func
;
590 /* error without aborting current compilation */
591 PUB_FUNC
void error_noabort(const char *fmt
, ...)
593 TCCState
*s1
= tcc_state
;
597 error1(s1
, 0, fmt
, ap
);
601 PUB_FUNC
void error(const char *fmt
, ...)
603 TCCState
*s1
= tcc_state
;
607 error1(s1
, 0, fmt
, ap
);
609 /* better than nothing: in some cases, we accept to handle errors */
610 if (s1
->error_set_jmp_enabled
) {
611 longjmp(s1
->error_jmp_buf
, 1);
613 /* XXX: eliminate this someday */
618 PUB_FUNC
void expect(const char *msg
)
620 error("%s expected", msg
);
623 PUB_FUNC
void warning(const char *fmt
, ...)
625 TCCState
*s1
= tcc_state
;
632 error1(s1
, 1, fmt
, ap
);
636 /********************************************************/
639 ST_FUNC
void tcc_open_bf(TCCState
*s1
, const char *filename
, int initlen
)
642 int buflen
= initlen
? initlen
: IO_BUF_SIZE
;
644 bf
= tcc_malloc(sizeof(BufferedFile
) + buflen
);
645 bf
->buf_ptr
= bf
->buffer
;
646 bf
->buf_end
= bf
->buffer
+ initlen
;
647 bf
->buf_end
[0] = CH_EOB
; /* put eob symbol */
648 pstrcpy(bf
->filename
, sizeof(bf
->filename
), filename
);
650 normalize_slashes(bf
->filename
);
653 bf
->ifndef_macro
= 0;
654 bf
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
660 ST_FUNC
void tcc_close(void)
662 BufferedFile
*bf
= file
;
665 total_lines
+= bf
->line_num
;
671 ST_FUNC
int tcc_open(TCCState
*s1
, const char *filename
)
674 if (strcmp(filename
, "-") == 0)
675 fd
= 0, filename
= "stdin";
677 fd
= open(filename
, O_RDONLY
| O_BINARY
);
678 if ((s1
->verbose
== 2 && fd
>= 0) || s1
->verbose
== 3)
679 printf("%s %*s%s\n", fd
< 0 ? "nf":"->",
680 (int)(s1
->include_stack_ptr
- s1
->include_stack
), "", filename
);
684 tcc_open_bf(s1
, filename
, 0);
689 /* compile the C file opened in 'file'. Return non zero if errors. */
690 static int tcc_compile(TCCState
*s1
)
695 volatile int section_sym
;
698 printf("%s: **** new file\n", file
->filename
);
702 cur_text_section
= NULL
;
704 anon_sym
= SYM_FIRST_ANOM
;
706 /* file info: full path + filename */
707 section_sym
= 0; /* avoid warning */
709 section_sym
= put_elf_sym(symtab_section
, 0, 0,
710 ELFW(ST_INFO
)(STB_LOCAL
, STT_SECTION
), 0,
711 text_section
->sh_num
, NULL
);
712 getcwd(buf
, sizeof(buf
));
714 normalize_slashes(buf
);
716 pstrcat(buf
, sizeof(buf
), "/");
717 put_stabs_r(buf
, N_SO
, 0, 0,
718 text_section
->data_offset
, text_section
, section_sym
);
719 put_stabs_r(file
->filename
, N_SO
, 0, 0,
720 text_section
->data_offset
, text_section
, section_sym
);
722 /* an elf symbol of type STT_FILE must be put so that STB_LOCAL
723 symbols can be safely used */
724 put_elf_sym(symtab_section
, 0, 0,
725 ELFW(ST_INFO
)(STB_LOCAL
, STT_FILE
), 0,
726 SHN_ABS
, file
->filename
);
728 /* define some often used types */
731 char_pointer_type
.t
= VT_BYTE
;
732 mk_pointer(&char_pointer_type
);
734 func_old_type
.t
= VT_FUNC
;
735 func_old_type
.ref
= sym_push(SYM_FIELD
, &int_type
, FUNC_CDECL
, FUNC_OLD
);
737 #if defined(TCC_ARM_EABI) && defined(TCC_ARM_VFP)
738 float_type
.t
= VT_FLOAT
;
739 double_type
.t
= VT_DOUBLE
;
741 func_float_type
.t
= VT_FUNC
;
742 func_float_type
.ref
= sym_push(SYM_FIELD
, &float_type
, FUNC_CDECL
, FUNC_OLD
);
743 func_double_type
.t
= VT_FUNC
;
744 func_double_type
.ref
= sym_push(SYM_FIELD
, &double_type
, FUNC_CDECL
, FUNC_OLD
);
748 /* define 'void *alloca(unsigned int)' builtin function */
753 sym
= sym_push(p
, mk_pointer(VT_VOID
), FUNC_CDECL
, FUNC_NEW
);
754 s1
= sym_push(SYM_FIELD
, VT_UNSIGNED
| VT_INT
, 0, 0);
757 sym_push(TOK_alloca
, VT_FUNC
| (p
<< VT_STRUCT_SHIFT
), VT_CONST
, 0);
761 define_start
= define_stack
;
764 if (setjmp(s1
->error_jmp_buf
) == 0) {
766 s1
->error_set_jmp_enabled
= 1;
768 ch
= file
->buf_ptr
[0];
769 tok_flags
= TOK_FLAG_BOL
| TOK_FLAG_BOF
;
770 parse_flags
= PARSE_FLAG_PREPROCESS
| PARSE_FLAG_TOK_NUM
;
775 expect("declaration");
777 warning("internal compiler error: vstack leak? (%d)", vtop
- pvtop
);
779 /* end of translation unit info */
781 put_stabs_r(NULL
, N_SO
, 0, 0,
782 text_section
->data_offset
, text_section
, section_sym
);
786 s1
->error_set_jmp_enabled
= 0;
788 /* reset define stack, but leave -Dsymbols (may be incorrect if
789 they are undefined) */
790 free_defines(define_start
);
792 gen_inline_functions();
794 sym_pop(&global_stack
, NULL
);
795 sym_pop(&local_stack
, NULL
);
797 return s1
->nb_errors
!= 0 ? -1 : 0;
800 LIBTCCAPI
int tcc_compile_string(TCCState
*s
, const char *str
)
805 tcc_open_bf(s
, "<string>", len
);
806 memcpy(file
->buffer
, str
, len
);
807 ret
= tcc_compile(s
);
812 /* define a preprocessor symbol. A value can also be provided with the '=' operator */
813 LIBTCCAPI
void tcc_define_symbol(TCCState
*s1
, const char *sym
, const char *value
)
820 len2
= strlen(value
);
822 /* init file structure */
823 tcc_open_bf(s1
, "<define>", len1
+ len2
+ 1);
824 memcpy(file
->buffer
, sym
, len1
);
825 file
->buffer
[len1
] = ' ';
826 memcpy(file
->buffer
+ len1
+ 1, value
, len2
);
828 /* parse with define parser */
829 ch
= file
->buf_ptr
[0];
836 /* undefine a preprocessor symbol */
837 LIBTCCAPI
void tcc_undefine_symbol(TCCState
*s1
, const char *sym
)
841 ts
= tok_alloc(sym
, strlen(sym
));
842 s
= define_find(ts
->tok
);
843 /* undefine symbol by putting an invalid name */
848 static void tcc_cleanup(void)
852 if (NULL
== tcc_state
)
856 /* free -D defines */
860 n
= tok_ident
- TOK_IDENT
;
861 for(i
= 0; i
< n
; i
++)
862 tcc_free(table_ident
[i
]);
863 tcc_free(table_ident
);
866 dynarray_reset(&sym_pools
, &nb_sym_pools
);
869 /* reset symbol stack */
870 sym_free_first
= NULL
;
871 /* cleanup from error/setjmp */
875 LIBTCCAPI TCCState
*tcc_new(void)
883 s
= tcc_mallocz(sizeof(TCCState
));
888 tcc_set_lib_path_w32(s
);
890 tcc_set_lib_path(s
, CONFIG_TCCDIR
);
892 s
->output_type
= TCC_OUTPUT_MEMORY
;
894 s
->include_stack_ptr
= s
->include_stack
;
896 /* we add dummy defines for some special macros to speed up tests
897 and to have working defined() */
898 define_push(TOK___LINE__
, MACRO_OBJ
, NULL
, NULL
);
899 define_push(TOK___FILE__
, MACRO_OBJ
, NULL
, NULL
);
900 define_push(TOK___DATE__
, MACRO_OBJ
, NULL
, NULL
);
901 define_push(TOK___TIME__
, MACRO_OBJ
, NULL
, NULL
);
903 /* standard defines */
904 tcc_define_symbol(s
, "__STDC__", NULL
);
905 tcc_define_symbol(s
, "__STDC_VERSION__", "199901L");
906 #if defined(TCC_TARGET_I386)
907 tcc_define_symbol(s
, "__i386__", NULL
);
908 tcc_define_symbol(s
, "__i386", NULL
);
909 tcc_define_symbol(s
, "i386", NULL
);
911 #if defined(TCC_TARGET_X86_64)
912 tcc_define_symbol(s
, "__x86_64__", NULL
);
914 #if defined(TCC_TARGET_ARM)
915 tcc_define_symbol(s
, "__ARM_ARCH_4__", NULL
);
916 tcc_define_symbol(s
, "__arm_elf__", NULL
);
917 tcc_define_symbol(s
, "__arm_elf", NULL
);
918 tcc_define_symbol(s
, "arm_elf", NULL
);
919 tcc_define_symbol(s
, "__arm__", NULL
);
920 tcc_define_symbol(s
, "__arm", NULL
);
921 tcc_define_symbol(s
, "arm", NULL
);
922 tcc_define_symbol(s
, "__APCS_32__", NULL
);
925 tcc_define_symbol(s
, "_WIN32", NULL
);
926 #ifdef TCC_TARGET_X86_64
927 tcc_define_symbol(s
, "_WIN64", NULL
);
930 tcc_define_symbol(s
, "__unix__", NULL
);
931 tcc_define_symbol(s
, "__unix", NULL
);
932 tcc_define_symbol(s
, "unix", NULL
);
933 #if defined(__FreeBSD__)
935 tcc_define_symbol(s
, "__FreeBSD__", str( __FreeBSD__
));
938 #if defined(__FreeBSD_kernel__)
939 tcc_define_symbol(s
, "__FreeBSD_kernel__", NULL
);
942 tcc_define_symbol(s
, "__linux__", NULL
);
943 tcc_define_symbol(s
, "__linux", NULL
);
946 /* tiny C specific defines */
947 sscanf(TCC_VERSION
, "%d.%d.%d", &a
, &b
, &c
);
948 sprintf(buffer
, "%d", a
*10000 + b
*100 + c
);
949 tcc_define_symbol(s
, "__TINYC__", buffer
);
951 /* tiny C & gcc defines */
952 #if defined TCC_TARGET_PE && defined TCC_TARGET_X86_64
953 tcc_define_symbol(s
, "__SIZE_TYPE__", "unsigned long long");
954 tcc_define_symbol(s
, "__PTRDIFF_TYPE__", "long long");
956 tcc_define_symbol(s
, "__SIZE_TYPE__", "unsigned long");
957 tcc_define_symbol(s
, "__PTRDIFF_TYPE__", "long");
961 tcc_define_symbol(s
, "__WCHAR_TYPE__", "unsigned short");
963 tcc_define_symbol(s
, "__WCHAR_TYPE__", "int");
967 tcc_define_symbol(s
, "__REDIRECT_NTH(name, proto, alias)", "name proto __asm__ (#alias) __THROW");
969 #ifndef TCC_TARGET_PE
970 /* default library paths */
971 tcc_add_library_path(s
, CONFIG_TCC_CRT_PREFIX
);
972 tcc_add_library_path(s
, CONFIG_SYSROOT CONFIG_TCC_LDDIR
);
973 tcc_add_library_path(s
, CONFIG_SYSROOT
"/usr/local"CONFIG_TCC_LDDIR
);
974 #ifdef CONFIG_TCC_EXTRA_LDDIR
976 const char delim
[] = ":";
977 char *tok
, *tok_extra_libdir
= NULL
, *tok_save_ptr
, *extra_libdir_str
;
978 size_t toklen
= 0, old_toklen
= 0;
980 extra_libdir_str
= tcc_strdup(CONFIG_TCC_EXTRA_LDDIR
);
981 tok
= strtok_r(extra_libdir_str
, delim
, &tok_save_ptr
);
984 toklen
= strlen(CONFIG_SYSROOT
"/usr/local") + strlen(tok
);
985 if (toklen
> old_toklen
)
986 tok_extra_libdir
= tcc_realloc(tok_extra_libdir
,
987 toklen
* sizeof(char));
988 /* No need for snprintf: value in tok comes from tcc compilation */
989 sprintf(tok_extra_libdir
, CONFIG_SYSROOT
"%s", tok
);
990 tcc_add_library_path(s
, tok_extra_libdir
);
991 sprintf(tok_extra_libdir
, CONFIG_SYSROOT
"/usr/local%s", tok
);
992 tcc_add_library_path(s
, tok_extra_libdir
);
993 tok
= strtok_r(NULL
, delim
, &tok_save_ptr
);
995 tcc_free(tok_extra_libdir
);
1000 /* no section zero */
1001 dynarray_add((void ***)&s
->sections
, &s
->nb_sections
, NULL
);
1003 /* create standard sections */
1004 text_section
= new_section(s
, ".text", SHT_PROGBITS
, SHF_ALLOC
| SHF_EXECINSTR
);
1005 data_section
= new_section(s
, ".data", SHT_PROGBITS
, SHF_ALLOC
| SHF_WRITE
);
1006 bss_section
= new_section(s
, ".bss", SHT_NOBITS
, SHF_ALLOC
| SHF_WRITE
);
1008 /* symbols are always generated for linking stage */
1009 symtab_section
= new_symtab(s
, ".symtab", SHT_SYMTAB
, 0,
1011 ".hashtab", SHF_PRIVATE
);
1012 strtab_section
= symtab_section
->link
;
1014 /* private symbol table for dynamic symbols */
1015 s
->dynsymtab_section
= new_symtab(s
, ".dynsymtab", SHT_SYMTAB
, SHF_PRIVATE
,
1017 ".dynhashtab", SHF_PRIVATE
);
1018 s
->alacarte_link
= 1;
1021 #ifdef CHAR_IS_UNSIGNED
1022 s
->char_is_unsigned
= 1;
1024 /* enable this if you want symbols with leading underscore on windows: */
1025 #if defined(TCC_TARGET_PE) && 0
1026 s
->leading_underscore
= 1;
1028 if (s
->section_align
== 0)
1029 s
->section_align
= ELF_PAGE_SIZE
;
1030 #ifdef TCC_TARGET_I386
1036 LIBTCCAPI
void tcc_delete(TCCState
*s1
)
1042 /* free all sections */
1043 for(i
= 1; i
< s1
->nb_sections
; i
++)
1044 free_section(s1
->sections
[i
]);
1045 dynarray_reset(&s1
->sections
, &s1
->nb_sections
);
1047 for(i
= 0; i
< s1
->nb_priv_sections
; i
++)
1048 free_section(s1
->priv_sections
[i
]);
1049 dynarray_reset(&s1
->priv_sections
, &s1
->nb_priv_sections
);
1051 /* free any loaded DLLs */
1052 for ( i
= 0; i
< s1
->nb_loaded_dlls
; i
++) {
1053 DLLReference
*ref
= s1
->loaded_dlls
[i
];
1055 dlclose(ref
->handle
);
1058 /* free loaded dlls array */
1059 dynarray_reset(&s1
->loaded_dlls
, &s1
->nb_loaded_dlls
);
1061 /* free library paths */
1062 dynarray_reset(&s1
->library_paths
, &s1
->nb_library_paths
);
1064 /* free include paths */
1065 dynarray_reset(&s1
->cached_includes
, &s1
->nb_cached_includes
);
1066 dynarray_reset(&s1
->include_paths
, &s1
->nb_include_paths
);
1067 dynarray_reset(&s1
->sysinclude_paths
, &s1
->nb_sysinclude_paths
);
1069 tcc_free(s1
->tcc_lib_path
);
1071 dynarray_reset(&s1
->input_files
, &s1
->nb_input_files
);
1072 dynarray_reset(&s1
->input_libs
, &s1
->nb_input_libs
);
1073 dynarray_reset(&s1
->target_deps
, &s1
->nb_target_deps
);
1076 munmap (s1
->write_mem
, s1
->mem_size
);
1077 munmap (s1
->runtime_mem
, s1
->mem_size
);
1079 tcc_free(s1
->runtime_mem
);
1084 LIBTCCAPI
int tcc_add_include_path(TCCState
*s1
, const char *pathname
)
1088 pathname1
= tcc_strdup(pathname
);
1089 dynarray_add((void ***)&s1
->include_paths
, &s1
->nb_include_paths
, pathname1
);
1093 LIBTCCAPI
int tcc_add_sysinclude_path(TCCState
*s1
, const char *pathname
)
1097 pathname1
= tcc_strdup(pathname
);
1098 dynarray_add((void ***)&s1
->sysinclude_paths
, &s1
->nb_sysinclude_paths
, pathname1
);
1102 ST_FUNC
int tcc_add_file_internal(TCCState
*s1
, const char *filename
, int flags
)
1108 /* find source file type with extension */
1109 ext
= tcc_fileextension(filename
);
1113 #ifdef CONFIG_TCC_ASM
1114 /* if .S file, define __ASSEMBLER__ like gcc does */
1115 if (!strcmp(ext
, "S"))
1116 tcc_define_symbol(s1
, "__ASSEMBLER__", NULL
);
1120 ret
= tcc_open(s1
, filename
);
1122 if (flags
& AFF_PRINT_ERROR
)
1123 error_noabort("file '%s' not found", filename
);
1127 /* update target deps */
1128 dynarray_add((void ***)&s1
->target_deps
, &s1
->nb_target_deps
,
1129 tcc_strdup(filename
));
1131 if (flags
& AFF_PREPROCESS
) {
1132 ret
= tcc_preprocess(s1
);
1136 if (!ext
[0] || !PATHCMP(ext
, "c")) {
1137 /* C file assumed */
1138 ret
= tcc_compile(s1
);
1142 #ifdef CONFIG_TCC_ASM
1143 if (!strcmp(ext
, "S")) {
1144 /* preprocessed assembler */
1145 ret
= tcc_assemble(s1
, 1);
1149 if (!strcmp(ext
, "s")) {
1150 /* non preprocessed assembler */
1151 ret
= tcc_assemble(s1
, 0);
1157 /* assume executable format: auto guess file type */
1158 size
= read(fd
, &ehdr
, sizeof(ehdr
));
1159 lseek(fd
, 0, SEEK_SET
);
1161 error_noabort("could not read header");
1165 if (size
== sizeof(ehdr
) &&
1166 ehdr
.e_ident
[0] == ELFMAG0
&&
1167 ehdr
.e_ident
[1] == ELFMAG1
&&
1168 ehdr
.e_ident
[2] == ELFMAG2
&&
1169 ehdr
.e_ident
[3] == ELFMAG3
) {
1171 /* do not display line number if error */
1173 if (ehdr
.e_type
== ET_REL
) {
1174 ret
= tcc_load_object_file(s1
, fd
, 0);
1178 #ifndef TCC_TARGET_PE
1179 if (ehdr
.e_type
== ET_DYN
) {
1180 if (s1
->output_type
== TCC_OUTPUT_MEMORY
) {
1182 h
= dlopen(filename
, RTLD_GLOBAL
| RTLD_LAZY
);
1186 ret
= tcc_load_dll(s1
, fd
, filename
,
1187 (flags
& AFF_REFERENCED_DLL
) != 0);
1192 error_noabort("unrecognized ELF file");
1196 if (memcmp((char *)&ehdr
, ARMAG
, 8) == 0) {
1197 file
->line_num
= 0; /* do not display line number if error */
1198 ret
= tcc_load_archive(s1
, fd
);
1202 #ifdef TCC_TARGET_COFF
1203 if (*(uint16_t *)(&ehdr
) == COFF_C67_MAGIC
) {
1204 ret
= tcc_load_coff(s1
, fd
);
1209 #ifdef TCC_TARGET_PE
1210 ret
= pe_load_file(s1
, filename
, fd
);
1212 /* as GNU ld, consider it is an ld script if not recognized */
1213 ret
= tcc_load_ldscript(s1
);
1216 error_noabort("unrecognized file type");
1223 LIBTCCAPI
int tcc_add_file(TCCState
*s
, const char *filename
)
1225 dynarray_add((void ***)&s
->input_files
, &s
->nb_input_files
, tcc_strdup(filename
));
1227 if (s
->output_type
== TCC_OUTPUT_PREPROCESS
)
1228 return tcc_add_file_internal(s
, filename
, AFF_PRINT_ERROR
| AFF_PREPROCESS
);
1230 return tcc_add_file_internal(s
, filename
, AFF_PRINT_ERROR
);
1233 LIBTCCAPI
int tcc_add_library_path(TCCState
*s
, const char *pathname
)
1237 pathname1
= tcc_strdup(pathname
);
1238 dynarray_add((void ***)&s
->library_paths
, &s
->nb_library_paths
, pathname1
);
1242 /* find and load a dll. Return non zero if not found */
1243 /* XXX: add '-rpath' option support ? */
1244 ST_FUNC
int tcc_add_dll(TCCState
*s
, const char *filename
, int flags
)
1249 for(i
= 0; i
< s
->nb_library_paths
; i
++) {
1250 snprintf(buf
, sizeof(buf
), "%s/%s",
1251 s
->library_paths
[i
], filename
);
1252 if (tcc_add_file_internal(s
, buf
, flags
) == 0)
1258 /* the library name is the same as the argument of the '-l' option */
1259 LIBTCCAPI
int tcc_add_library(TCCState
*s
, const char *libraryname
)
1264 dynarray_add((void ***)&s
->input_libs
, &s
->nb_input_libs
, tcc_strdup(libraryname
));
1266 /* first we look for the dynamic library if not static linking */
1267 if (!s
->static_link
) {
1268 #ifdef TCC_TARGET_PE
1269 if (pe_add_dll(s
, libraryname
) == 0)
1272 snprintf(buf
, sizeof(buf
), "lib%s.so", libraryname
);
1273 if (tcc_add_dll(s
, buf
, 0) == 0)
1277 /* then we look for the static library */
1278 for(i
= 0; i
< s
->nb_library_paths
; i
++) {
1279 snprintf(buf
, sizeof(buf
), "%s/lib%s.a",
1280 s
->library_paths
[i
], libraryname
);
1281 if (tcc_add_file_internal(s
, buf
, 0) == 0)
1287 LIBTCCAPI
int tcc_add_symbol(TCCState
*s
, const char *name
, const void *val
)
1289 #ifdef TCC_TARGET_PE
1290 pe_putimport(s
, 0, name
, val
);
1292 add_elf_sym(symtab_section
, (uplong
)val
, 0,
1293 ELFW(ST_INFO
)(STB_GLOBAL
, STT_NOTYPE
), 0,
1299 LIBTCCAPI
int tcc_set_output_type(TCCState
*s
, int output_type
)
1303 s
->output_type
= output_type
;
1306 /* default include paths */
1307 /* -isystem paths have already been handled */
1308 #ifndef TCC_TARGET_PE
1309 tcc_add_sysinclude_path(s
, CONFIG_SYSROOT
"/usr/local/include");
1310 tcc_add_sysinclude_path(s
, CONFIG_SYSROOT
"/usr/include");
1312 snprintf(buf
, sizeof(buf
), "%s/include", s
->tcc_lib_path
);
1313 tcc_add_sysinclude_path(s
, buf
);
1314 #ifdef TCC_TARGET_PE
1315 snprintf(buf
, sizeof(buf
), "%s/include/winapi", s
->tcc_lib_path
);
1316 tcc_add_sysinclude_path(s
, buf
);
1320 /* if bound checking, then add corresponding sections */
1321 #ifdef CONFIG_TCC_BCHECK
1322 if (s
->do_bounds_check
) {
1324 tcc_define_symbol(s
, "__BOUNDS_CHECKING_ON", NULL
);
1325 /* create bounds sections */
1326 bounds_section
= new_section(s
, ".bounds",
1327 SHT_PROGBITS
, SHF_ALLOC
);
1328 lbounds_section
= new_section(s
, ".lbounds",
1329 SHT_PROGBITS
, SHF_ALLOC
);
1333 if (s
->char_is_unsigned
) {
1334 tcc_define_symbol(s
, "__CHAR_UNSIGNED__", NULL
);
1337 /* add debug sections */
1340 stab_section
= new_section(s
, ".stab", SHT_PROGBITS
, 0);
1341 stab_section
->sh_entsize
= sizeof(Stab_Sym
);
1342 stabstr_section
= new_section(s
, ".stabstr", SHT_STRTAB
, 0);
1343 put_elf_str(stabstr_section
, "");
1344 stab_section
->link
= stabstr_section
;
1345 /* put first entry */
1346 put_stabs("", 0, 0, 0, 0);
1349 /* add libc crt1/crti objects */
1350 #ifndef TCC_TARGET_PE
1351 if ((output_type
== TCC_OUTPUT_EXE
|| output_type
== TCC_OUTPUT_DLL
) &&
1353 if (output_type
!= TCC_OUTPUT_DLL
)
1354 tcc_add_file(s
, CONFIG_TCC_CRT_PREFIX
"/crt1.o");
1355 tcc_add_file(s
, CONFIG_TCC_CRT_PREFIX
"/crti.o");
1359 #ifdef TCC_TARGET_PE
1360 #ifdef CONFIG_TCC_CROSSLIB
1361 snprintf(buf
, sizeof(buf
), "%s/" CONFIG_TCC_CROSSLIB
, s
->tcc_lib_path
);
1362 tcc_add_library_path(s
, buf
);
1364 snprintf(buf
, sizeof(buf
), "%s/lib", s
->tcc_lib_path
);
1365 tcc_add_library_path(s
, buf
);
1367 if (GetSystemDirectory(buf
, sizeof buf
))
1368 tcc_add_library_path(s
, buf
);
1375 #define WD_ALL 0x0001 /* warning is activated when using -Wall */
1376 #define FD_INVERT 0x0002 /* invert value before storing */
1378 typedef struct FlagDef
{
1384 static const FlagDef warning_defs
[] = {
1385 { offsetof(TCCState
, warn_unsupported
), 0, "unsupported" },
1386 { offsetof(TCCState
, warn_write_strings
), 0, "write-strings" },
1387 { offsetof(TCCState
, warn_error
), 0, "error" },
1388 { offsetof(TCCState
, warn_implicit_function_declaration
), WD_ALL
,
1389 "implicit-function-declaration" },
1392 ST_FUNC
int set_flag(TCCState
*s
, const FlagDef
*flags
, int nb_flags
,
1393 const char *name
, int value
)
1400 if (r
[0] == 'n' && r
[1] == 'o' && r
[2] == '-') {
1404 for(i
= 0, p
= flags
; i
< nb_flags
; i
++, p
++) {
1405 if (!strcmp(r
, p
->name
))
1410 if (p
->flags
& FD_INVERT
)
1412 *(int *)((uint8_t *)s
+ p
->offset
) = value
;
1416 /* set/reset a warning */
1417 LIBTCCAPI
int tcc_set_warning(TCCState
*s
, const char *warning_name
, int value
)
1422 if (!strcmp(warning_name
, "all")) {
1423 for(i
= 0, p
= warning_defs
; i
< countof(warning_defs
); i
++, p
++) {
1424 if (p
->flags
& WD_ALL
)
1425 *(int *)((uint8_t *)s
+ p
->offset
) = 1;
1429 return set_flag(s
, warning_defs
, countof(warning_defs
),
1430 warning_name
, value
);
1434 static const FlagDef flag_defs
[] = {
1435 { offsetof(TCCState
, char_is_unsigned
), 0, "unsigned-char" },
1436 { offsetof(TCCState
, char_is_unsigned
), FD_INVERT
, "signed-char" },
1437 { offsetof(TCCState
, nocommon
), FD_INVERT
, "common" },
1438 { offsetof(TCCState
, leading_underscore
), 0, "leading-underscore" },
1441 /* set/reset a flag */
1442 PUB_FUNC
int tcc_set_flag(TCCState
*s
, const char *flag_name
, int value
)
1444 return set_flag(s
, flag_defs
, countof(flag_defs
),
1449 static int strstart(const char *str
, const char *val
, char **ptr
)
1454 while (*q
!= '\0') {
1466 /* Like strstart, but automatically takes into account that ld options can
1468 * - start with double or single dash (e.g. '--soname' or '-soname')
1469 * - arguments can be given as separate or after '=' (e.g. '-Wl,-soname,x.so'
1470 * or '-Wl,-soname=x.so')
1472 * you provide `val` always in 'option[=]' form (no leading -)
1474 static int link_option(const char *str
, const char *val
, char **ptr
)
1478 /* there should be 1 or 2 dashes */
1484 /* then str & val should match (potentialy up to '=') */
1488 while (*q
!= '\0' && *q
!= '=') {
1495 /* '=' near eos means ',' or '=' is ok */
1497 if (*p
!= ',' && *p
!= '=')
1509 /* set linker options */
1510 PUB_FUNC
const char * tcc_set_linker(TCCState
*s
, char *option
, int multi
)
1515 while (option
&& *option
) {
1517 if (link_option(option
, "Bsymbolic", &p
)) {
1519 #ifdef TCC_TARGET_PE
1520 } else if (link_option(option
, "file-alignment=", &p
)) {
1521 s
->pe_file_align
= strtoul(p
, &end
, 16);
1523 } else if (link_option(option
, "fini=", &p
)) {
1525 if (s
->warn_unsupported
)
1526 warning("ignoring -fini %s", p
);
1528 } else if (link_option(option
, "image-base=", &p
)) {
1529 s
->text_addr
= strtoul(p
, &end
, 16);
1530 s
->has_text_addr
= 1;
1531 } else if (link_option(option
, "init=", &p
)) {
1533 if (s
->warn_unsupported
)
1534 warning("ignoring -init %s", p
);
1536 } else if (link_option(option
, "oformat=", &p
)) {
1537 #if defined(TCC_TARGET_PE)
1538 if (strstart(p
, "pe-", NULL
)) {
1540 #if defined(TCC_TARGET_X86_64)
1541 if (strstart(p
, "elf64-", NULL
)) {
1543 if (strstart(p
, "elf32-", NULL
)) {
1546 s
->output_format
= TCC_OUTPUT_FORMAT_ELF
;
1547 } else if (!strcmp(p
, "binary")) {
1548 s
->output_format
= TCC_OUTPUT_FORMAT_BINARY
;
1550 #ifdef TCC_TARGET_COFF
1551 if (!strcmp(p
, "coff")) {
1552 s
->output_format
= TCC_OUTPUT_FORMAT_COFF
;
1559 } else if (link_option(option
, "rpath=", &p
)) {
1561 } else if (link_option(option
, "section-alignment=", &p
)) {
1562 s
->section_align
= strtoul(p
, &end
, 16);
1563 } else if (link_option(option
, "soname=", &p
)) {
1566 #ifdef TCC_TARGET_PE
1567 } else if (link_option(option
, "subsystem=", &p
)) {
1568 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
1569 if (!strcmp(p
, "native")) {
1570 s
->pe_subsystem
= 1;
1571 } else if (!strcmp(p
, "console")) {
1572 s
->pe_subsystem
= 3;
1573 } else if (!strcmp(p
, "gui")) {
1574 s
->pe_subsystem
= 2;
1575 } else if (!strcmp(p
, "posix")) {
1576 s
->pe_subsystem
= 7;
1577 } else if (!strcmp(p
, "efiapp")) {
1578 s
->pe_subsystem
= 10;
1579 } else if (!strcmp(p
, "efiboot")) {
1580 s
->pe_subsystem
= 11;
1581 } else if (!strcmp(p
, "efiruntime")) {
1582 s
->pe_subsystem
= 12;
1583 } else if (!strcmp(p
, "efirom")) {
1584 s
->pe_subsystem
= 13;
1585 #elif defined(TCC_TARGET_ARM)
1586 if (!strcmp(p
, "wince")) {
1587 s
->pe_subsystem
= 9;
1594 } else if (link_option(option
, "Ttext=", &p
)) {
1595 s
->text_addr
= strtoul(p
, &end
, 16);
1596 s
->has_text_addr
= 1;
1604 p
= strchr( (end
) ? end
: p
, ',');
1606 *p
= 0; /* terminate last option */
1615 PUB_FUNC
void tcc_print_stats(TCCState
*s
, int64_t total_time
)
1618 tt
= (double)total_time
/ 1000000.0;
1621 if (total_bytes
< 1)
1623 printf("%d idents, %d lines, %d bytes, %0.3f s, %d lines/s, %0.1f MB/s\n",
1624 tok_ident
- TOK_IDENT
, total_lines
, total_bytes
,
1625 tt
, (int)(total_lines
/ tt
),
1626 total_bytes
/ tt
/ 1000000.0);
1629 /* set CONFIG_TCCDIR at runtime */
1630 LIBTCCAPI
void tcc_set_lib_path(TCCState
*s
, const char *path
)
1632 tcc_free(s
->tcc_lib_path
);
1633 s
->tcc_lib_path
= tcc_strdup(path
);
1636 PUB_FUNC
void set_num_callers(int n
)
1638 #ifdef CONFIG_TCC_BACKTRACE
1644 LIBTCCAPI
const char *tcc_default_target(TCCState
*s
)
1646 /* FIXME will break in multithreaded case */
1647 static char outfile_default
[1024];
1651 strcmp(s
->input_files
[0], "-") == 0 ? "a"
1652 : tcc_basename(s
->input_files
[0]);
1653 pstrcpy(outfile_default
, sizeof(outfile_default
), name
);
1654 ext
= tcc_fileextension(outfile_default
);
1655 #ifdef TCC_TARGET_PE
1656 if (s
->output_type
== TCC_OUTPUT_DLL
)
1657 strcpy(ext
, ".dll");
1659 if (s
->output_type
== TCC_OUTPUT_EXE
)
1660 strcpy(ext
, ".exe");
1663 if (( (s
->output_type
== TCC_OUTPUT_OBJ
&& !s
->reloc_output
) ||
1664 (s
->output_type
== TCC_OUTPUT_PREPROCESS
) )
1668 pstrcpy(outfile_default
, sizeof(outfile_default
), "a.out");
1670 return outfile_default
;
1674 LIBTCCAPI
void tcc_gen_makedeps(TCCState
*s
, const char *target
, const char *filename
)
1677 char buf
[1024], *ext
;
1681 target
= tcc_default_target(s
);
1684 /* compute filename automatically
1685 * dir/file.o -> dir/file.d */
1686 pstrcpy(buf
, sizeof(buf
), target
);
1687 ext
= tcc_fileextension(buf
);
1688 pstrcpy(ext
, sizeof(buf
) - (ext
-buf
), ".d");
1693 printf("<- %s\n", filename
);
1695 /* XXX return err codes instead of error() ? */
1696 depout
= fopen(filename
, "w");
1698 error("could not open '%s'", filename
);
1700 fprintf(depout
, "%s : \\\n", target
);
1701 for (i
=0; i
<s
->nb_target_deps
; ++i
)
1702 fprintf(depout
, "\t%s \\\n", s
->target_deps
[i
]);
1703 fprintf(depout
, "\n");