CONFIG_TCC_STATIC: add dummy for dlclose
[tinycc.git] / tcc.c
blob8278a56a8c72ede840bff3df5d00b1d6a2132ec3
1 /*
2 * TCC - Tiny C Compiler
3 *
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
20 #define _GNU_SOURCE
21 #include "config.h"
23 #ifdef CONFIG_TCCBOOT
25 #include "tccboot.h"
26 #define CONFIG_TCC_STATIC
28 #else
30 #include <stdlib.h>
31 #include <stdio.h>
32 #include <stdarg.h>
33 #include <string.h>
34 #include <errno.h>
35 #include <math.h>
36 #include <signal.h>
37 #include <fcntl.h>
38 #include <setjmp.h>
39 #include <time.h>
41 #ifdef _WIN32
42 #include <windows.h>
43 #include <sys/timeb.h>
44 #ifdef _MSC_VER
45 #define inline __inline
46 #endif
47 #endif
49 #ifndef _WIN32
50 #include <unistd.h>
51 #include <sys/time.h>
52 #include <sys/ucontext.h>
53 #include <sys/mman.h>
54 #endif
56 #endif /* !CONFIG_TCCBOOT */
58 #ifndef PAGESIZE
59 #define PAGESIZE 4096
60 #endif
62 #include "elf.h"
63 #include "stab.h"
65 #ifndef O_BINARY
66 #define O_BINARY 0
67 #endif
69 #include "libtcc.h"
71 /* parser debug */
72 //#define PARSE_DEBUG
73 /* preprocessor debug */
74 //#define PP_DEBUG
75 /* include file debug */
76 //#define INC_DEBUG
78 //#define MEM_DEBUG
80 /* assembler debug */
81 //#define ASM_DEBUG
83 /* target selection */
84 //#define TCC_TARGET_I386 /* i386 code generator */
85 //#define TCC_TARGET_ARM /* ARMv4 code generator */
86 //#define TCC_TARGET_C67 /* TMS320C67xx code generator */
87 //#define TCC_TARGET_X86_64 /* x86-64 code generator */
89 /* default target is I386 */
90 #if !defined(TCC_TARGET_I386) && !defined(TCC_TARGET_ARM) && \
91 !defined(TCC_TARGET_C67) && !defined(TCC_TARGET_X86_64)
92 #define TCC_TARGET_I386
93 #endif
95 #if !defined(_WIN32) && !defined(TCC_UCLIBC) && !defined(TCC_TARGET_ARM) && \
96 !defined(TCC_TARGET_C67) && !defined(TCC_TARGET_X86_64)
97 #define CONFIG_TCC_BCHECK /* enable bound checking code */
98 #endif
100 #if defined(_WIN32) && !defined(TCC_TARGET_PE)
101 #define CONFIG_TCC_STATIC
102 #endif
104 /* define it to include assembler support */
105 #if !defined(TCC_TARGET_ARM) && !defined(TCC_TARGET_C67) && \
106 !defined(TCC_TARGET_X86_64)
107 #define CONFIG_TCC_ASM
108 #endif
110 /* object format selection */
111 #if defined(TCC_TARGET_C67)
112 #define TCC_TARGET_COFF
113 #endif
115 #define FALSE 0
116 #define false 0
117 #define TRUE 1
118 #define true 1
119 typedef int BOOL;
121 /* path to find crt1.o, crti.o and crtn.o. Only needed when generating
122 executables or dlls */
123 #define CONFIG_TCC_CRT_PREFIX CONFIG_SYSROOT "/usr/lib"
125 #define INCLUDE_STACK_SIZE 32
126 #define IFDEF_STACK_SIZE 64
127 #define VSTACK_SIZE 256
128 #define STRING_MAX_SIZE 1024
129 #define PACK_STACK_SIZE 8
131 #define TOK_HASH_SIZE 8192 /* must be a power of two */
132 #define TOK_ALLOC_INCR 512 /* must be a power of two */
133 #define TOK_MAX_SIZE 4 /* token max size in int unit when stored in string */
135 /* token symbol management */
136 typedef struct TokenSym {
137 struct TokenSym *hash_next;
138 struct Sym *sym_define; /* direct pointer to define */
139 struct Sym *sym_label; /* direct pointer to label */
140 struct Sym *sym_struct; /* direct pointer to structure */
141 struct Sym *sym_identifier; /* direct pointer to identifier */
142 int tok; /* token number */
143 int len;
144 char str[1];
145 } TokenSym;
147 #ifdef TCC_TARGET_PE
148 typedef unsigned short nwchar_t;
149 #else
150 typedef int nwchar_t;
151 #endif
153 typedef struct CString {
154 int size; /* size in bytes */
155 void *data; /* either 'char *' or 'nwchar_t *' */
156 int size_allocated;
157 void *data_allocated; /* if non NULL, data has been malloced */
158 } CString;
160 /* type definition */
161 typedef struct CType {
162 int t;
163 struct Sym *ref;
164 } CType;
166 /* constant value */
167 typedef union CValue {
168 long double ld;
169 double d;
170 float f;
171 int i;
172 unsigned int ui;
173 unsigned int ul; /* address (should be unsigned long on 64 bit cpu) */
174 long long ll;
175 unsigned long long ull;
176 struct CString *cstr;
177 void *ptr;
178 int tab[1];
179 } CValue;
181 /* value on stack */
182 typedef struct SValue {
183 CType type; /* type */
184 unsigned short r; /* register + flags */
185 unsigned short r2; /* second register, used for 'long long'
186 type. If not used, set to VT_CONST */
187 CValue c; /* constant, if VT_CONST */
188 struct Sym *sym; /* symbol, if (VT_SYM | VT_CONST) */
189 } SValue;
191 /* symbol management */
192 typedef struct Sym {
193 int v; /* symbol token */
194 long r; /* associated register */
195 long c; /* associated number */
196 CType type; /* associated type */
197 struct Sym *next; /* next related symbol */
198 struct Sym *prev; /* prev symbol in stack */
199 struct Sym *prev_tok; /* previous symbol for this token */
200 } Sym;
202 /* section definition */
203 /* XXX: use directly ELF structure for parameters ? */
204 /* special flag to indicate that the section should not be linked to
205 the other ones */
206 #define SHF_PRIVATE 0x80000000
208 typedef struct Section {
209 unsigned long data_offset; /* current data offset */
210 unsigned char *data; /* section data */
211 unsigned long data_allocated; /* used for realloc() handling */
212 int sh_name; /* elf section name (only used during output) */
213 int sh_num; /* elf section number */
214 int sh_type; /* elf section type */
215 int sh_flags; /* elf section flags */
216 int sh_info; /* elf section info */
217 int sh_addralign; /* elf section alignment */
218 int sh_entsize; /* elf entry size */
219 unsigned long sh_size; /* section size (only used during output) */
220 unsigned long sh_addr; /* address at which the section is relocated */
221 unsigned long sh_offset; /* file offset */
222 int nb_hashed_syms; /* used to resize the hash table */
223 struct Section *link; /* link to another section */
224 struct Section *reloc; /* corresponding section for relocation, if any */
225 struct Section *hash; /* hash table for symbols */
226 struct Section *next;
227 char name[1]; /* section name */
228 } Section;
230 typedef struct DLLReference {
231 int level;
232 void *handle;
233 char name[1];
234 } DLLReference;
236 /* GNUC attribute definition */
237 typedef struct AttributeDef {
238 int aligned;
239 int packed;
240 Section *section;
241 int func_attr; /* calling convention, exports, ... */
242 } AttributeDef;
244 /* -------------------------------------------------- */
245 /* gr: wrappers for casting sym->r for other purposes */
246 typedef struct {
247 unsigned
248 func_call : 8,
249 func_args : 8,
250 func_export : 1;
251 } func_attr_t;
253 #define FUNC_CALL(r) (((func_attr_t*)&(r))->func_call)
254 #define FUNC_EXPORT(r) (((func_attr_t*)&(r))->func_export)
255 #define FUNC_ARGS(r) (((func_attr_t*)&(r))->func_args)
256 #define INLINE_DEF(r) (*(int **)&(r))
257 /* -------------------------------------------------- */
259 #define SYM_STRUCT 0x40000000 /* struct/union/enum symbol space */
260 #define SYM_FIELD 0x20000000 /* struct/union field symbol space */
261 #define SYM_FIRST_ANOM 0x10000000 /* first anonymous sym */
263 /* stored in 'Sym.c' field */
264 #define FUNC_NEW 1 /* ansi function prototype */
265 #define FUNC_OLD 2 /* old function prototype */
266 #define FUNC_ELLIPSIS 3 /* ansi function prototype with ... */
268 /* stored in 'Sym.r' field */
269 #define FUNC_CDECL 0 /* standard c call */
270 #define FUNC_STDCALL 1 /* pascal c call */
271 #define FUNC_FASTCALL1 2 /* first param in %eax */
272 #define FUNC_FASTCALL2 3 /* first parameters in %eax, %edx */
273 #define FUNC_FASTCALL3 4 /* first parameter in %eax, %edx, %ecx */
274 #define FUNC_FASTCALLW 5 /* first parameter in %ecx, %edx */
276 /* field 'Sym.t' for macros */
277 #define MACRO_OBJ 0 /* object like macro */
278 #define MACRO_FUNC 1 /* function like macro */
280 /* field 'Sym.r' for C labels */
281 #define LABEL_DEFINED 0 /* label is defined */
282 #define LABEL_FORWARD 1 /* label is forward defined */
283 #define LABEL_DECLARED 2 /* label is declared but never used */
285 /* type_decl() types */
286 #define TYPE_ABSTRACT 1 /* type without variable */
287 #define TYPE_DIRECT 2 /* type with variable */
289 #define IO_BUF_SIZE 8192
291 typedef struct BufferedFile {
292 uint8_t *buf_ptr;
293 uint8_t *buf_end;
294 int fd;
295 int line_num; /* current line number - here to simplify code */
296 int ifndef_macro; /* #ifndef macro / #endif search */
297 int ifndef_macro_saved; /* saved ifndef_macro */
298 int *ifdef_stack_ptr; /* ifdef_stack value at the start of the file */
299 char inc_type; /* type of include */
300 char inc_filename[512]; /* filename specified by the user */
301 char filename[1024]; /* current filename - here to simplify code */
302 unsigned char buffer[IO_BUF_SIZE + 1]; /* extra size for CH_EOB char */
303 } BufferedFile;
305 #define CH_EOB '\\' /* end of buffer or '\0' char in file */
306 #define CH_EOF (-1) /* end of file */
308 /* parsing state (used to save parser state to reparse part of the
309 source several times) */
310 typedef struct ParseState {
311 int *macro_ptr;
312 int line_num;
313 int tok;
314 CValue tokc;
315 } ParseState;
317 /* used to record tokens */
318 typedef struct TokenString {
319 int *str;
320 int len;
321 int allocated_len;
322 int last_line_num;
323 } TokenString;
325 /* include file cache, used to find files faster and also to eliminate
326 inclusion if the include file is protected by #ifndef ... #endif */
327 typedef struct CachedInclude {
328 int ifndef_macro;
329 int hash_next; /* -1 if none */
330 char type; /* '"' or '>' to give include type */
331 char filename[1]; /* path specified in #include */
332 } CachedInclude;
334 #define CACHED_INCLUDES_HASH_SIZE 512
336 /* parser */
337 static struct BufferedFile *file;
338 static int ch, tok;
339 static CString tok_spaces; /* spaces before current token */
340 static CValue tokc;
341 static CString tokcstr; /* current parsed string, if any */
342 /* additional informations about token */
343 static int tok_flags;
344 #define TOK_FLAG_BOL 0x0001 /* beginning of line before */
345 #define TOK_FLAG_BOF 0x0002 /* beginning of file before */
346 #define TOK_FLAG_ENDIF 0x0004 /* a endif was found matching starting #ifdef */
347 #define TOK_FLAG_EOF 0x0008 /* end of file */
349 static int *macro_ptr, *macro_ptr_allocated;
350 static int *unget_saved_macro_ptr;
351 static int unget_saved_buffer[TOK_MAX_SIZE + 1];
352 static int unget_buffer_enabled;
353 static int parse_flags;
354 #define PARSE_FLAG_PREPROCESS 0x0001 /* activate preprocessing */
355 #define PARSE_FLAG_TOK_NUM 0x0002 /* return numbers instead of TOK_PPNUM */
356 #define PARSE_FLAG_LINEFEED 0x0004 /* line feed is returned as a
357 token. line feed is also
358 returned at eof */
359 #define PARSE_FLAG_ASM_COMMENTS 0x0008 /* '#' can be used for line comment */
361 static Section *text_section, *data_section, *bss_section; /* predefined sections */
362 static Section *cur_text_section; /* current section where function code is
363 generated */
364 #ifdef CONFIG_TCC_ASM
365 static Section *last_text_section; /* to handle .previous asm directive */
366 #endif
367 /* bound check related sections */
368 static Section *bounds_section; /* contains global data bound description */
369 static Section *lbounds_section; /* contains local data bound description */
370 /* symbol sections */
371 static Section *symtab_section, *strtab_section;
373 /* debug sections */
374 static Section *stab_section, *stabstr_section;
376 /* loc : local variable index
377 ind : output code index
378 rsym: return symbol
379 anon_sym: anonymous symbol index
381 static int rsym, anon_sym, ind, loc;
382 /* expression generation modifiers */
383 static int const_wanted; /* true if constant wanted */
384 static int nocode_wanted; /* true if no code generation wanted for an expression */
385 static int global_expr; /* true if compound literals must be allocated
386 globally (used during initializers parsing */
387 static CType func_vt; /* current function return type (used by return
388 instruction) */
389 static int func_vc;
390 static int last_line_num, last_ind, func_ind; /* debug last line number and pc */
391 static int tok_ident;
392 static TokenSym **table_ident;
393 static TokenSym *hash_ident[TOK_HASH_SIZE];
394 static char token_buf[STRING_MAX_SIZE + 1];
395 static char *funcname;
396 static Sym *global_stack, *local_stack;
397 static Sym *define_stack;
398 static Sym *global_label_stack, *local_label_stack;
399 /* symbol allocator */
400 #define SYM_POOL_NB (8192 / sizeof(Sym))
401 static Sym *sym_free_first;
402 static void **sym_pools;
403 static int nb_sym_pools;
405 static SValue vstack[VSTACK_SIZE], *vtop;
406 /* some predefined types */
407 static CType char_pointer_type, func_old_type, int_type;
408 /* true if isid(c) || isnum(c) */
409 static unsigned char isidnum_table[256-CH_EOF];
411 /* display some information during compilation */
412 static int verbose = 0;
414 /* compile with debug symbol (and use them if error during execution) */
415 static int do_debug = 0;
417 /* compile with built-in memory and bounds checker */
418 static int do_bounds_check = 0;
420 /* display benchmark infos */
421 #if !defined(LIBTCC)
422 static int do_bench = 0;
423 #endif
424 static int total_lines;
425 static int total_bytes;
427 /* use GNU C extensions */
428 static int gnu_ext = 1;
430 /* use Tiny C extensions */
431 static int tcc_ext = 1;
433 /* max number of callers shown if error */
434 static int num_callers = 6;
435 static const char **rt_bound_error_msg;
437 /* XXX: get rid of this ASAP */
438 static struct TCCState *tcc_state;
440 /* give the path of the tcc libraries */
441 static const char *tcc_lib_path = CONFIG_TCCDIR;
443 struct TCCState {
444 int output_type;
446 BufferedFile **include_stack_ptr;
447 int *ifdef_stack_ptr;
449 /* include file handling */
450 char **include_paths;
451 int nb_include_paths;
452 char **sysinclude_paths;
453 int nb_sysinclude_paths;
454 CachedInclude **cached_includes;
455 int nb_cached_includes;
457 char **library_paths;
458 int nb_library_paths;
460 /* array of all loaded dlls (including those referenced by loaded
461 dlls) */
462 DLLReference **loaded_dlls;
463 int nb_loaded_dlls;
465 /* sections */
466 Section **sections;
467 int nb_sections; /* number of sections, including first dummy section */
469 Section **priv_sections;
470 int nb_priv_sections; /* number of private sections */
472 /* got handling */
473 Section *got;
474 Section *plt;
475 unsigned long *got_offsets;
476 int nb_got_offsets;
477 /* give the correspondance from symtab indexes to dynsym indexes */
478 int *symtab_to_dynsym;
480 /* temporary dynamic symbol sections (for dll loading) */
481 Section *dynsymtab_section;
482 /* exported dynamic symbol section */
483 Section *dynsym;
485 int nostdinc; /* if true, no standard headers are added */
486 int nostdlib; /* if true, no standard libraries are added */
488 int nocommon; /* if true, do not use common symbols for .bss data */
490 /* if true, static linking is performed */
491 int static_link;
493 /* soname as specified on the command line (-soname) */
494 const char *soname;
496 /* if true, all symbols are exported */
497 int rdynamic;
499 /* if true, only link in referenced objects from archive */
500 int alacarte_link;
502 /* address of text section */
503 unsigned long text_addr;
504 int has_text_addr;
506 /* output format, see TCC_OUTPUT_FORMAT_xxx */
507 int output_format;
509 /* C language options */
510 int char_is_unsigned;
511 int leading_underscore;
513 /* warning switches */
514 int warn_write_strings;
515 int warn_unsupported;
516 int warn_error;
517 int warn_none;
518 int warn_implicit_function_declaration;
520 /* error handling */
521 void *error_opaque;
522 void (*error_func)(void *opaque, const char *msg);
523 int error_set_jmp_enabled;
524 jmp_buf error_jmp_buf;
525 int nb_errors;
527 /* tiny assembler state */
528 Sym *asm_labels;
530 /* see include_stack_ptr */
531 BufferedFile *include_stack[INCLUDE_STACK_SIZE];
533 /* see ifdef_stack_ptr */
534 int ifdef_stack[IFDEF_STACK_SIZE];
536 /* see cached_includes */
537 int cached_includes_hash[CACHED_INCLUDES_HASH_SIZE];
539 /* pack stack */
540 int pack_stack[PACK_STACK_SIZE];
541 int *pack_stack_ptr;
543 /* output file for preprocessing */
544 FILE *outfile;
546 /* for tcc_relocate */
547 int runtime_added;
549 #ifdef TCC_TARGET_X86_64
550 /* write PLT and GOT here */
551 char *runtime_plt_and_got;
552 unsigned int runtime_plt_and_got_offset;
553 #endif
556 /* The current value can be: */
557 #define VT_VALMASK 0x00ff
558 #define VT_CONST 0x00f0 /* constant in vc
559 (must be first non register value) */
560 #define VT_LLOCAL 0x00f1 /* lvalue, offset on stack */
561 #define VT_LOCAL 0x00f2 /* offset on stack */
562 #define VT_CMP 0x00f3 /* the value is stored in processor flags (in vc) */
563 #define VT_JMP 0x00f4 /* value is the consequence of jmp true (even) */
564 #define VT_JMPI 0x00f5 /* value is the consequence of jmp false (odd) */
565 #define VT_LVAL 0x0100 /* var is an lvalue */
566 #define VT_SYM 0x0200 /* a symbol value is added */
567 #define VT_MUSTCAST 0x0400 /* value must be casted to be correct (used for
568 char/short stored in integer registers) */
569 #define VT_MUSTBOUND 0x0800 /* bound checking must be done before
570 dereferencing value */
571 #define VT_BOUNDED 0x8000 /* value is bounded. The address of the
572 bounding function call point is in vc */
573 #define VT_LVAL_BYTE 0x1000 /* lvalue is a byte */
574 #define VT_LVAL_SHORT 0x2000 /* lvalue is a short */
575 #define VT_LVAL_UNSIGNED 0x4000 /* lvalue is unsigned */
576 #define VT_LVAL_TYPE (VT_LVAL_BYTE | VT_LVAL_SHORT | VT_LVAL_UNSIGNED)
578 /* types */
579 #define VT_INT 0 /* integer type */
580 #define VT_BYTE 1 /* signed byte type */
581 #define VT_SHORT 2 /* short type */
582 #define VT_VOID 3 /* void type */
583 #define VT_PTR 4 /* pointer */
584 #define VT_ENUM 5 /* enum definition */
585 #define VT_FUNC 6 /* function type */
586 #define VT_STRUCT 7 /* struct/union definition */
587 #define VT_FLOAT 8 /* IEEE float */
588 #define VT_DOUBLE 9 /* IEEE double */
589 #define VT_LDOUBLE 10 /* IEEE long double */
590 #define VT_BOOL 11 /* ISOC99 boolean type */
591 #define VT_LLONG 12 /* 64 bit integer */
592 #define VT_LONG 13 /* long integer (NEVER USED as type, only
593 during parsing) */
594 #define VT_BTYPE 0x000f /* mask for basic type */
595 #define VT_UNSIGNED 0x0010 /* unsigned type */
596 #define VT_ARRAY 0x0020 /* array type (also has VT_PTR) */
597 #define VT_BITFIELD 0x0040 /* bitfield modifier */
598 #define VT_CONSTANT 0x0800 /* const modifier */
599 #define VT_VOLATILE 0x1000 /* volatile modifier */
600 #define VT_SIGNED 0x2000 /* signed type */
602 /* storage */
603 #define VT_EXTERN 0x00000080 /* extern definition */
604 #define VT_STATIC 0x00000100 /* static variable */
605 #define VT_TYPEDEF 0x00000200 /* typedef definition */
606 #define VT_INLINE 0x00000400 /* inline definition */
608 #define VT_STRUCT_SHIFT 16 /* shift for bitfield shift values */
610 /* type mask (except storage) */
611 #define VT_STORAGE (VT_EXTERN | VT_STATIC | VT_TYPEDEF | VT_INLINE)
612 #define VT_TYPE (~(VT_STORAGE))
614 /* token values */
616 /* warning: the following compare tokens depend on i386 asm code */
617 #define TOK_ULT 0x92
618 #define TOK_UGE 0x93
619 #define TOK_EQ 0x94
620 #define TOK_NE 0x95
621 #define TOK_ULE 0x96
622 #define TOK_UGT 0x97
623 #define TOK_Nset 0x98
624 #define TOK_Nclear 0x99
625 #define TOK_LT 0x9c
626 #define TOK_GE 0x9d
627 #define TOK_LE 0x9e
628 #define TOK_GT 0x9f
630 #define TOK_LAND 0xa0
631 #define TOK_LOR 0xa1
633 #define TOK_DEC 0xa2
634 #define TOK_MID 0xa3 /* inc/dec, to void constant */
635 #define TOK_INC 0xa4
636 #define TOK_UDIV 0xb0 /* unsigned division */
637 #define TOK_UMOD 0xb1 /* unsigned modulo */
638 #define TOK_PDIV 0xb2 /* fast division with undefined rounding for pointers */
639 #define TOK_CINT 0xb3 /* number in tokc */
640 #define TOK_CCHAR 0xb4 /* char constant in tokc */
641 #define TOK_STR 0xb5 /* pointer to string in tokc */
642 #define TOK_TWOSHARPS 0xb6 /* ## preprocessing token */
643 #define TOK_LCHAR 0xb7
644 #define TOK_LSTR 0xb8
645 #define TOK_CFLOAT 0xb9 /* float constant */
646 #define TOK_LINENUM 0xba /* line number info */
647 #define TOK_CDOUBLE 0xc0 /* double constant */
648 #define TOK_CLDOUBLE 0xc1 /* long double constant */
649 #define TOK_UMULL 0xc2 /* unsigned 32x32 -> 64 mul */
650 #define TOK_ADDC1 0xc3 /* add with carry generation */
651 #define TOK_ADDC2 0xc4 /* add with carry use */
652 #define TOK_SUBC1 0xc5 /* add with carry generation */
653 #define TOK_SUBC2 0xc6 /* add with carry use */
654 #define TOK_CUINT 0xc8 /* unsigned int constant */
655 #define TOK_CLLONG 0xc9 /* long long constant */
656 #define TOK_CULLONG 0xca /* unsigned long long constant */
657 #define TOK_ARROW 0xcb
658 #define TOK_DOTS 0xcc /* three dots */
659 #define TOK_SHR 0xcd /* unsigned shift right */
660 #define TOK_PPNUM 0xce /* preprocessor number */
662 #define TOK_SHL 0x01 /* shift left */
663 #define TOK_SAR 0x02 /* signed shift right */
665 /* assignement operators : normal operator or 0x80 */
666 #define TOK_A_MOD 0xa5
667 #define TOK_A_AND 0xa6
668 #define TOK_A_MUL 0xaa
669 #define TOK_A_ADD 0xab
670 #define TOK_A_SUB 0xad
671 #define TOK_A_DIV 0xaf
672 #define TOK_A_XOR 0xde
673 #define TOK_A_OR 0xfc
674 #define TOK_A_SHL 0x81
675 #define TOK_A_SAR 0x82
677 #ifndef offsetof
678 #define offsetof(type, field) ((size_t) &((type *)0)->field)
679 #endif
681 #ifndef countof
682 #define countof(tab) (sizeof(tab) / sizeof((tab)[0]))
683 #endif
685 /* WARNING: the content of this string encodes token numbers */
686 static char tok_two_chars[] = "<=\236>=\235!=\225&&\240||\241++\244--\242==\224<<\1>>\2+=\253-=\255*=\252/=\257%=\245&=\246^=\336|=\374->\313..\250##\266";
688 #define TOK_EOF (-1) /* end of file */
689 #define TOK_LINEFEED 10 /* line feed */
691 /* all identificators and strings have token above that */
692 #define TOK_IDENT 256
694 /* only used for i386 asm opcodes definitions */
695 #define DEF_ASM(x) DEF(TOK_ASM_ ## x, #x)
697 #define DEF_BWL(x) \
698 DEF(TOK_ASM_ ## x ## b, #x "b") \
699 DEF(TOK_ASM_ ## x ## w, #x "w") \
700 DEF(TOK_ASM_ ## x ## l, #x "l") \
701 DEF(TOK_ASM_ ## x, #x)
703 #define DEF_WL(x) \
704 DEF(TOK_ASM_ ## x ## w, #x "w") \
705 DEF(TOK_ASM_ ## x ## l, #x "l") \
706 DEF(TOK_ASM_ ## x, #x)
708 #define DEF_FP1(x) \
709 DEF(TOK_ASM_ ## f ## x ## s, "f" #x "s") \
710 DEF(TOK_ASM_ ## fi ## x ## l, "fi" #x "l") \
711 DEF(TOK_ASM_ ## f ## x ## l, "f" #x "l") \
712 DEF(TOK_ASM_ ## fi ## x ## s, "fi" #x "s")
714 #define DEF_FP(x) \
715 DEF(TOK_ASM_ ## f ## x, "f" #x ) \
716 DEF(TOK_ASM_ ## f ## x ## p, "f" #x "p") \
717 DEF_FP1(x)
719 #define DEF_ASMTEST(x) \
720 DEF_ASM(x ## o) \
721 DEF_ASM(x ## no) \
722 DEF_ASM(x ## b) \
723 DEF_ASM(x ## c) \
724 DEF_ASM(x ## nae) \
725 DEF_ASM(x ## nb) \
726 DEF_ASM(x ## nc) \
727 DEF_ASM(x ## ae) \
728 DEF_ASM(x ## e) \
729 DEF_ASM(x ## z) \
730 DEF_ASM(x ## ne) \
731 DEF_ASM(x ## nz) \
732 DEF_ASM(x ## be) \
733 DEF_ASM(x ## na) \
734 DEF_ASM(x ## nbe) \
735 DEF_ASM(x ## a) \
736 DEF_ASM(x ## s) \
737 DEF_ASM(x ## ns) \
738 DEF_ASM(x ## p) \
739 DEF_ASM(x ## pe) \
740 DEF_ASM(x ## np) \
741 DEF_ASM(x ## po) \
742 DEF_ASM(x ## l) \
743 DEF_ASM(x ## nge) \
744 DEF_ASM(x ## nl) \
745 DEF_ASM(x ## ge) \
746 DEF_ASM(x ## le) \
747 DEF_ASM(x ## ng) \
748 DEF_ASM(x ## nle) \
749 DEF_ASM(x ## g)
751 #define TOK_ASM_int TOK_INT
753 enum tcc_token {
754 TOK_LAST = TOK_IDENT - 1,
755 #define DEF(id, str) id,
756 #include "tcctok.h"
757 #undef DEF
760 static const char tcc_keywords[] =
761 #define DEF(id, str) str "\0"
762 #include "tcctok.h"
763 #undef DEF
766 #define TOK_UIDENT TOK_DEFINE
768 #ifdef _WIN32
769 #define snprintf _snprintf
770 #define vsnprintf _vsnprintf
771 #ifndef __GNUC__
772 #define strtold (long double)strtod
773 #define strtof (float)strtod
774 #define strtoll (long long)strtol
775 #endif
776 #elif defined(TCC_UCLIBC) || defined(__FreeBSD__) || defined(__DragonFly__) \
777 || defined(__OpenBSD__)
778 /* currently incorrect */
779 long double strtold(const char *nptr, char **endptr)
781 return (long double)strtod(nptr, endptr);
783 float strtof(const char *nptr, char **endptr)
785 return (float)strtod(nptr, endptr);
787 #else
788 /* XXX: need to define this to use them in non ISOC99 context */
789 extern float strtof (const char *__nptr, char **__endptr);
790 extern long double strtold (const char *__nptr, char **__endptr);
791 #endif
793 static char *pstrcpy(char *buf, int buf_size, const char *s);
794 static char *pstrcat(char *buf, int buf_size, const char *s);
795 static char *tcc_basename(const char *name);
796 static char *tcc_fileextension (const char *p);
798 static void next(void);
799 static void next_nomacro(void);
800 static void parse_expr_type(CType *type);
801 static void expr_type(CType *type);
802 static void unary_type(CType *type);
803 static void block(int *bsym, int *csym, int *case_sym, int *def_sym,
804 int case_reg, int is_expr);
805 static int expr_const(void);
806 static void expr_eq(void);
807 static void gexpr(void);
808 static void gen_inline_functions(void);
809 static void decl(int l);
810 static void decl_initializer(CType *type, Section *sec, unsigned long c,
811 int first, int size_only);
812 static void decl_initializer_alloc(CType *type, AttributeDef *ad, int r,
813 int has_init, int v, int scope);
814 int gv(int rc);
815 void gv2(int rc1, int rc2);
816 void move_reg(int r, int s);
817 void save_regs(int n);
818 void save_reg(int r);
819 void vpop(void);
820 void vswap(void);
821 void vdup(void);
822 int get_reg(int rc);
823 int get_reg_ex(int rc,int rc2);
825 struct macro_level {
826 struct macro_level *prev;
827 int *p;
830 static void macro_subst(TokenString *tok_str, Sym **nested_list,
831 const int *macro_str, struct macro_level **can_read_stream);
832 void gen_op(int op);
833 void force_charshort_cast(int t);
834 static void gen_cast(CType *type);
835 void vstore(void);
836 static Sym *sym_find(int v);
837 static Sym *sym_push(int v, CType *type, int r, int c);
839 /* type handling */
840 static int type_size(CType *type, int *a);
841 static inline CType *pointed_type(CType *type);
842 static int pointed_size(CType *type);
843 static int lvalue_type(int t);
844 static int parse_btype(CType *type, AttributeDef *ad);
845 static void type_decl(CType *type, AttributeDef *ad, int *v, int td);
846 static int compare_types(CType *type1, CType *type2, int unqualified);
847 static int is_compatible_types(CType *type1, CType *type2);
848 static int is_compatible_parameter_types(CType *type1, CType *type2);
850 int ieee_finite(double d);
851 void error(const char *fmt, ...);
852 void vpushi(int v);
853 void vpushll(long long v);
854 void vrott(int n);
855 void vnrott(int n);
856 void lexpand_nr(void);
857 static void vpush_global_sym(CType *type, int v);
858 void vset(CType *type, int r, int v);
859 void type_to_str(char *buf, int buf_size,
860 CType *type, const char *varstr);
861 char *get_tok_str(int v, CValue *cv);
862 static Sym *get_sym_ref(CType *type, Section *sec,
863 unsigned long offset, unsigned long size);
864 static Sym *external_global_sym(int v, CType *type, int r);
866 /* section generation */
867 static void section_realloc(Section *sec, unsigned long new_size);
868 static void *section_ptr_add(Section *sec, unsigned long size);
869 static void put_extern_sym(Sym *sym, Section *section,
870 unsigned long value, unsigned long size);
871 static void greloc(Section *s, Sym *sym, unsigned long addr, int type);
872 static int put_elf_str(Section *s, const char *sym);
873 static int put_elf_sym(Section *s,
874 unsigned long value, unsigned long size,
875 int info, int other, int shndx, const char *name);
876 static int add_elf_sym(Section *s, unsigned long value, unsigned long size,
877 int info, int other, int sh_num, const char *name);
878 static void put_elf_reloc(Section *symtab, Section *s, unsigned long offset,
879 int type, int symbol);
880 static void put_stabs(const char *str, int type, int other, int desc,
881 unsigned long value);
882 static void put_stabs_r(const char *str, int type, int other, int desc,
883 unsigned long value, Section *sec, int sym_index);
884 static void put_stabn(int type, int other, int desc, int value);
885 static void put_stabd(int type, int other, int desc);
886 static int tcc_add_dll(TCCState *s, const char *filename, int flags);
888 #define AFF_PRINT_ERROR 0x0001 /* print error if file not found */
889 #define AFF_REFERENCED_DLL 0x0002 /* load a referenced dll from another dll */
890 #define AFF_PREPROCESS 0x0004 /* preprocess file */
891 static int tcc_add_file_internal(TCCState *s, const char *filename, int flags);
893 /* tcccoff.c */
894 int tcc_output_coff(TCCState *s1, FILE *f);
896 /* tccpe.c */
897 void *resolve_sym(TCCState *s1, const char *sym, int type);
898 int pe_load_def_file(struct TCCState *s1, int fd);
899 int pe_test_res_file(void *v, int size);
900 int pe_load_res_file(struct TCCState *s1, int fd);
901 void pe_add_runtime(struct TCCState *s1);
902 void pe_guess_outfile(char *objfilename, int output_type);
903 int pe_output_file(struct TCCState *s1, const char *filename);
905 /* tccasm.c */
907 #ifdef CONFIG_TCC_ASM
909 typedef struct ExprValue {
910 uint32_t v;
911 Sym *sym;
912 } ExprValue;
914 #define MAX_ASM_OPERANDS 30
916 typedef struct ASMOperand {
917 int id; /* GCC 3 optionnal identifier (0 if number only supported */
918 char *constraint;
919 char asm_str[16]; /* computed asm string for operand */
920 SValue *vt; /* C value of the expression */
921 int ref_index; /* if >= 0, gives reference to a output constraint */
922 int input_index; /* if >= 0, gives reference to an input constraint */
923 int priority; /* priority, used to assign registers */
924 int reg; /* if >= 0, register number used for this operand */
925 int is_llong; /* true if double register value */
926 int is_memory; /* true if memory operand */
927 int is_rw; /* for '+' modifier */
928 } ASMOperand;
930 static void asm_expr(TCCState *s1, ExprValue *pe);
931 static int asm_int_expr(TCCState *s1);
932 static int find_constraint(ASMOperand *operands, int nb_operands,
933 const char *name, const char **pp);
935 static int tcc_assemble(TCCState *s1, int do_preprocess);
937 #endif
939 static void asm_instr(void);
940 static void asm_global_instr(void);
942 /* true if float/double/long double type */
943 static inline int is_float(int t)
945 int bt;
946 bt = t & VT_BTYPE;
947 return bt == VT_LDOUBLE || bt == VT_DOUBLE || bt == VT_FLOAT;
950 #ifdef TCC_TARGET_I386
951 #include "i386-gen.c"
952 #endif
954 #ifdef TCC_TARGET_ARM
955 #include "arm-gen.c"
956 #endif
958 #ifdef TCC_TARGET_C67
959 #include "c67-gen.c"
960 #endif
962 #ifdef TCC_TARGET_X86_64
963 #include "x86_64-gen.c"
964 #endif
966 #ifdef CONFIG_TCC_STATIC
968 #define RTLD_LAZY 0x001
969 #define RTLD_NOW 0x002
970 #define RTLD_GLOBAL 0x100
971 #define RTLD_DEFAULT NULL
973 /* dummy function for profiling */
974 void *dlopen(const char *filename, int flag)
976 return NULL;
979 void dlclose(void *p)
983 const char *dlerror(void)
985 return "error";
988 typedef struct TCCSyms {
989 char *str;
990 void *ptr;
991 } TCCSyms;
993 #define TCCSYM(a) { #a, &a, },
995 /* add the symbol you want here if no dynamic linking is done */
996 static TCCSyms tcc_syms[] = {
997 #if !defined(CONFIG_TCCBOOT)
998 TCCSYM(printf)
999 TCCSYM(fprintf)
1000 TCCSYM(fopen)
1001 TCCSYM(fclose)
1002 #endif
1003 { NULL, NULL },
1006 void *resolve_sym(TCCState *s1, const char *symbol, int type)
1008 TCCSyms *p;
1009 p = tcc_syms;
1010 while (p->str != NULL) {
1011 if (!strcmp(p->str, symbol))
1012 return p->ptr;
1013 p++;
1015 return NULL;
1018 #elif !defined(_WIN32)
1020 #include <dlfcn.h>
1022 void *resolve_sym(TCCState *s1, const char *sym, int type)
1024 return dlsym(RTLD_DEFAULT, sym);
1027 #endif
1029 /********************************************************/
1031 /* we use our own 'finite' function to avoid potential problems with
1032 non standard math libs */
1033 /* XXX: endianness dependent */
1034 int ieee_finite(double d)
1036 int *p = (int *)&d;
1037 return ((unsigned)((p[1] | 0x800fffff) + 1)) >> 31;
1040 /* copy a string and truncate it. */
1041 static char *pstrcpy(char *buf, int buf_size, const char *s)
1043 char *q, *q_end;
1044 int c;
1046 if (buf_size > 0) {
1047 q = buf;
1048 q_end = buf + buf_size - 1;
1049 while (q < q_end) {
1050 c = *s++;
1051 if (c == '\0')
1052 break;
1053 *q++ = c;
1055 *q = '\0';
1057 return buf;
1060 /* strcat and truncate. */
1061 static char *pstrcat(char *buf, int buf_size, const char *s)
1063 int len;
1064 len = strlen(buf);
1065 if (len < buf_size)
1066 pstrcpy(buf + len, buf_size - len, s);
1067 return buf;
1070 #ifndef LIBTCC
1071 static int strstart(const char *str, const char *val, const char **ptr)
1073 const char *p, *q;
1074 p = str;
1075 q = val;
1076 while (*q != '\0') {
1077 if (*p != *q)
1078 return 0;
1079 p++;
1080 q++;
1082 if (ptr)
1083 *ptr = p;
1084 return 1;
1086 #endif
1088 #ifdef _WIN32
1089 #define IS_PATHSEP(c) (c == '/' || c == '\\')
1090 #define IS_ABSPATH(p) (IS_PATHSEP(p[0]) || (p[0] && p[1] == ':' && IS_PATHSEP(p[2])))
1091 #define PATHCMP stricmp
1092 #else
1093 #define IS_PATHSEP(c) (c == '/')
1094 #define IS_ABSPATH(p) IS_PATHSEP(p[0])
1095 #define PATHCMP strcmp
1096 #endif
1098 /* extract the basename of a file */
1099 static char *tcc_basename(const char *name)
1101 char *p = strchr(name, 0);
1102 while (p > name && !IS_PATHSEP(p[-1]))
1103 --p;
1104 return p;
1107 static char *tcc_fileextension (const char *name)
1109 char *b = tcc_basename(name);
1110 char *e = strrchr(b, '.');
1111 return e ? e : strchr(b, 0);
1114 #ifdef _WIN32
1115 char *normalize_slashes(char *path)
1117 char *p;
1118 for (p = path; *p; ++p)
1119 if (*p == '\\')
1120 *p = '/';
1121 return path;
1124 char *w32_tcc_lib_path(void)
1126 /* on win32, we suppose the lib and includes are at the location
1127 of 'tcc.exe' */
1128 char path[1024], *p;
1129 GetModuleFileNameA(NULL, path, sizeof path);
1130 p = tcc_basename(normalize_slashes(strlwr(path)));
1131 if (p - 5 > path && 0 == strncmp(p - 5, "/bin/", 5))
1132 p -= 5;
1133 else if (p > path)
1134 p--;
1135 *p = 0;
1136 return strdup(path);
1138 #endif
1140 void set_pages_executable(void *ptr, unsigned long length)
1142 #ifdef _WIN32
1143 unsigned long old_protect;
1144 VirtualProtect(ptr, length, PAGE_EXECUTE_READWRITE, &old_protect);
1145 #else
1146 unsigned long start, end;
1147 start = (unsigned long)ptr & ~(PAGESIZE - 1);
1148 end = (unsigned long)ptr + length;
1149 end = (end + PAGESIZE - 1) & ~(PAGESIZE - 1);
1150 mprotect((void *)start, end - start, PROT_READ | PROT_WRITE | PROT_EXEC);
1151 #endif
1154 /* memory management */
1155 #ifdef MEM_DEBUG
1156 int mem_cur_size;
1157 int mem_max_size;
1158 unsigned malloc_usable_size(void*);
1159 #endif
1161 static inline void tcc_free(void *ptr)
1163 #ifdef MEM_DEBUG
1164 mem_cur_size -= malloc_usable_size(ptr);
1165 #endif
1166 free(ptr);
1169 static void *tcc_malloc(unsigned long size)
1171 void *ptr;
1172 ptr = malloc(size);
1173 if (!ptr && size)
1174 error("memory full");
1175 #ifdef MEM_DEBUG
1176 mem_cur_size += malloc_usable_size(ptr);
1177 if (mem_cur_size > mem_max_size)
1178 mem_max_size = mem_cur_size;
1179 #endif
1180 return ptr;
1183 static void *tcc_mallocz(unsigned long size)
1185 void *ptr;
1186 ptr = tcc_malloc(size);
1187 memset(ptr, 0, size);
1188 return ptr;
1191 static inline void *tcc_realloc(void *ptr, unsigned long size)
1193 void *ptr1;
1194 #ifdef MEM_DEBUG
1195 mem_cur_size -= malloc_usable_size(ptr);
1196 #endif
1197 ptr1 = realloc(ptr, size);
1198 #ifdef MEM_DEBUG
1199 /* NOTE: count not correct if alloc error, but not critical */
1200 mem_cur_size += malloc_usable_size(ptr1);
1201 if (mem_cur_size > mem_max_size)
1202 mem_max_size = mem_cur_size;
1203 #endif
1204 return ptr1;
1207 static char *tcc_strdup(const char *str)
1209 char *ptr;
1210 ptr = tcc_malloc(strlen(str) + 1);
1211 strcpy(ptr, str);
1212 return ptr;
1215 #define free(p) use_tcc_free(p)
1216 #define malloc(s) use_tcc_malloc(s)
1217 #define realloc(p, s) use_tcc_realloc(p, s)
1219 static void dynarray_add(void ***ptab, int *nb_ptr, void *data)
1221 int nb, nb_alloc;
1222 void **pp;
1224 nb = *nb_ptr;
1225 pp = *ptab;
1226 /* every power of two we double array size */
1227 if ((nb & (nb - 1)) == 0) {
1228 if (!nb)
1229 nb_alloc = 1;
1230 else
1231 nb_alloc = nb * 2;
1232 pp = tcc_realloc(pp, nb_alloc * sizeof(void *));
1233 if (!pp)
1234 error("memory full");
1235 *ptab = pp;
1237 pp[nb++] = data;
1238 *nb_ptr = nb;
1241 static void dynarray_reset(void *pp, int *n)
1243 void **p;
1244 for (p = *(void***)pp; *n; ++p, --*n)
1245 if (*p)
1246 tcc_free(*p);
1247 tcc_free(*(void**)pp);
1248 *(void**)pp = NULL;
1251 /* symbol allocator */
1252 static Sym *__sym_malloc(void)
1254 Sym *sym_pool, *sym, *last_sym;
1255 int i;
1257 sym_pool = tcc_malloc(SYM_POOL_NB * sizeof(Sym));
1258 dynarray_add(&sym_pools, &nb_sym_pools, sym_pool);
1260 last_sym = sym_free_first;
1261 sym = sym_pool;
1262 for(i = 0; i < SYM_POOL_NB; i++) {
1263 sym->next = last_sym;
1264 last_sym = sym;
1265 sym++;
1267 sym_free_first = last_sym;
1268 return last_sym;
1271 static inline Sym *sym_malloc(void)
1273 Sym *sym;
1274 sym = sym_free_first;
1275 if (!sym)
1276 sym = __sym_malloc();
1277 sym_free_first = sym->next;
1278 return sym;
1281 static inline void sym_free(Sym *sym)
1283 sym->next = sym_free_first;
1284 sym_free_first = sym;
1287 Section *new_section(TCCState *s1, const char *name, int sh_type, int sh_flags)
1289 Section *sec;
1291 sec = tcc_mallocz(sizeof(Section) + strlen(name));
1292 strcpy(sec->name, name);
1293 sec->sh_type = sh_type;
1294 sec->sh_flags = sh_flags;
1295 switch(sh_type) {
1296 case SHT_HASH:
1297 case SHT_REL:
1298 case SHT_RELA:
1299 case SHT_DYNSYM:
1300 case SHT_SYMTAB:
1301 case SHT_DYNAMIC:
1302 sec->sh_addralign = 4;
1303 break;
1304 case SHT_STRTAB:
1305 sec->sh_addralign = 1;
1306 break;
1307 default:
1308 sec->sh_addralign = 32; /* default conservative alignment */
1309 break;
1312 if (sh_flags & SHF_PRIVATE) {
1313 dynarray_add((void ***)&s1->priv_sections, &s1->nb_priv_sections, sec);
1314 } else {
1315 sec->sh_num = s1->nb_sections;
1316 dynarray_add((void ***)&s1->sections, &s1->nb_sections, sec);
1319 return sec;
1322 static void free_section(Section *s)
1324 tcc_free(s->data);
1327 /* realloc section and set its content to zero */
1328 static void section_realloc(Section *sec, unsigned long new_size)
1330 unsigned long size;
1331 unsigned char *data;
1333 size = sec->data_allocated;
1334 if (size == 0)
1335 size = 1;
1336 while (size < new_size)
1337 size = size * 2;
1338 data = tcc_realloc(sec->data, size);
1339 if (!data)
1340 error("memory full");
1341 memset(data + sec->data_allocated, 0, size - sec->data_allocated);
1342 sec->data = data;
1343 sec->data_allocated = size;
1346 /* reserve at least 'size' bytes in section 'sec' from
1347 sec->data_offset. */
1348 static void *section_ptr_add(Section *sec, unsigned long size)
1350 unsigned long offset, offset1;
1352 offset = sec->data_offset;
1353 offset1 = offset + size;
1354 if (offset1 > sec->data_allocated)
1355 section_realloc(sec, offset1);
1356 sec->data_offset = offset1;
1357 return sec->data + offset;
1360 /* return a reference to a section, and create it if it does not
1361 exists */
1362 Section *find_section(TCCState *s1, const char *name)
1364 Section *sec;
1365 int i;
1366 for(i = 1; i < s1->nb_sections; i++) {
1367 sec = s1->sections[i];
1368 if (!strcmp(name, sec->name))
1369 return sec;
1371 /* sections are created as PROGBITS */
1372 return new_section(s1, name, SHT_PROGBITS, SHF_ALLOC);
1375 #define SECTION_ABS ((void *)1)
1377 /* update sym->c so that it points to an external symbol in section
1378 'section' with value 'value' */
1379 static void put_extern_sym2(Sym *sym, Section *section,
1380 unsigned long value, unsigned long size,
1381 int can_add_underscore)
1383 int sym_type, sym_bind, sh_num, info, other, attr;
1384 ElfW(Sym) *esym;
1385 const char *name;
1386 char buf1[256];
1388 if (section == NULL)
1389 sh_num = SHN_UNDEF;
1390 else if (section == SECTION_ABS)
1391 sh_num = SHN_ABS;
1392 else
1393 sh_num = section->sh_num;
1395 other = attr = 0;
1397 if ((sym->type.t & VT_BTYPE) == VT_FUNC) {
1398 sym_type = STT_FUNC;
1399 #ifdef TCC_TARGET_PE
1400 if (sym->type.ref)
1401 attr = sym->type.ref->r;
1402 if (FUNC_EXPORT(attr))
1403 other |= 1;
1404 if (FUNC_CALL(attr) == FUNC_STDCALL)
1405 other |= 2;
1406 #endif
1407 } else {
1408 sym_type = STT_OBJECT;
1411 if (sym->type.t & VT_STATIC)
1412 sym_bind = STB_LOCAL;
1413 else
1414 sym_bind = STB_GLOBAL;
1416 if (!sym->c) {
1417 name = get_tok_str(sym->v, NULL);
1418 #ifdef CONFIG_TCC_BCHECK
1419 if (do_bounds_check) {
1420 char buf[32];
1422 /* XXX: avoid doing that for statics ? */
1423 /* if bound checking is activated, we change some function
1424 names by adding the "__bound" prefix */
1425 switch(sym->v) {
1426 #if 0
1427 /* XXX: we rely only on malloc hooks */
1428 case TOK_malloc:
1429 case TOK_free:
1430 case TOK_realloc:
1431 case TOK_memalign:
1432 case TOK_calloc:
1433 #endif
1434 case TOK_memcpy:
1435 case TOK_memmove:
1436 case TOK_memset:
1437 case TOK_strlen:
1438 case TOK_strcpy:
1439 case TOK__alloca:
1440 strcpy(buf, "__bound_");
1441 strcat(buf, name);
1442 name = buf;
1443 break;
1446 #endif
1448 #ifdef TCC_TARGET_PE
1449 if ((other & 2) && can_add_underscore) {
1450 sprintf(buf1, "_%s@%d", name, FUNC_ARGS(attr));
1451 name = buf1;
1452 } else
1453 #endif
1454 if (tcc_state->leading_underscore && can_add_underscore) {
1455 buf1[0] = '_';
1456 pstrcpy(buf1 + 1, sizeof(buf1) - 1, name);
1457 name = buf1;
1459 info = ELFW(ST_INFO)(sym_bind, sym_type);
1460 sym->c = add_elf_sym(symtab_section, value, size, info, other, sh_num, name);
1461 } else {
1462 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
1463 esym->st_value = value;
1464 esym->st_size = size;
1465 esym->st_shndx = sh_num;
1466 esym->st_other |= other;
1470 static void put_extern_sym(Sym *sym, Section *section,
1471 unsigned long value, unsigned long size)
1473 put_extern_sym2(sym, section, value, size, 1);
1476 /* add a new relocation entry to symbol 'sym' in section 's' */
1477 static void greloc(Section *s, Sym *sym, unsigned long offset, int type)
1479 if (!sym->c)
1480 put_extern_sym(sym, NULL, 0, 0);
1481 /* now we can add ELF relocation info */
1482 put_elf_reloc(symtab_section, s, offset, type, sym->c);
1485 static inline int isid(int c)
1487 return (c >= 'a' && c <= 'z') ||
1488 (c >= 'A' && c <= 'Z') ||
1489 c == '_';
1492 static inline int isnum(int c)
1494 return c >= '0' && c <= '9';
1497 static inline int isoct(int c)
1499 return c >= '0' && c <= '7';
1502 static inline int toup(int c)
1504 if (c >= 'a' && c <= 'z')
1505 return c - 'a' + 'A';
1506 else
1507 return c;
1510 static void strcat_vprintf(char *buf, int buf_size, const char *fmt, va_list ap)
1512 int len;
1513 len = strlen(buf);
1514 vsnprintf(buf + len, buf_size - len, fmt, ap);
1517 static void strcat_printf(char *buf, int buf_size, const char *fmt, ...)
1519 va_list ap;
1520 va_start(ap, fmt);
1521 strcat_vprintf(buf, buf_size, fmt, ap);
1522 va_end(ap);
1525 void error1(TCCState *s1, int is_warning, const char *fmt, va_list ap)
1527 char buf[2048];
1528 BufferedFile **f;
1530 buf[0] = '\0';
1531 if (file) {
1532 for(f = s1->include_stack; f < s1->include_stack_ptr; f++)
1533 strcat_printf(buf, sizeof(buf), "In file included from %s:%d:\n",
1534 (*f)->filename, (*f)->line_num);
1535 if (file->line_num > 0) {
1536 strcat_printf(buf, sizeof(buf),
1537 "%s:%d: ", file->filename, file->line_num);
1538 } else {
1539 strcat_printf(buf, sizeof(buf),
1540 "%s: ", file->filename);
1542 } else {
1543 strcat_printf(buf, sizeof(buf),
1544 "tcc: ");
1546 if (is_warning)
1547 strcat_printf(buf, sizeof(buf), "warning: ");
1548 strcat_vprintf(buf, sizeof(buf), fmt, ap);
1550 if (!s1->error_func) {
1551 /* default case: stderr */
1552 fprintf(stderr, "%s\n", buf);
1553 } else {
1554 s1->error_func(s1->error_opaque, buf);
1556 if (!is_warning || s1->warn_error)
1557 s1->nb_errors++;
1560 #ifdef LIBTCC
1561 void tcc_set_error_func(TCCState *s, void *error_opaque,
1562 void (*error_func)(void *opaque, const char *msg))
1564 s->error_opaque = error_opaque;
1565 s->error_func = error_func;
1567 #endif
1569 /* error without aborting current compilation */
1570 void error_noabort(const char *fmt, ...)
1572 TCCState *s1 = tcc_state;
1573 va_list ap;
1575 va_start(ap, fmt);
1576 error1(s1, 0, fmt, ap);
1577 va_end(ap);
1580 void error(const char *fmt, ...)
1582 TCCState *s1 = tcc_state;
1583 va_list ap;
1585 va_start(ap, fmt);
1586 error1(s1, 0, fmt, ap);
1587 va_end(ap);
1588 /* better than nothing: in some cases, we accept to handle errors */
1589 if (s1->error_set_jmp_enabled) {
1590 longjmp(s1->error_jmp_buf, 1);
1591 } else {
1592 /* XXX: eliminate this someday */
1593 exit(1);
1597 void expect(const char *msg)
1599 error("%s expected", msg);
1602 void warning(const char *fmt, ...)
1604 TCCState *s1 = tcc_state;
1605 va_list ap;
1607 if (s1->warn_none)
1608 return;
1610 va_start(ap, fmt);
1611 error1(s1, 1, fmt, ap);
1612 va_end(ap);
1615 void skip(int c)
1617 if (tok != c)
1618 error("'%c' expected", c);
1619 next();
1622 static void test_lvalue(void)
1624 if (!(vtop->r & VT_LVAL))
1625 expect("lvalue");
1628 /* allocate a new token */
1629 static TokenSym *tok_alloc_new(TokenSym **pts, const char *str, int len)
1631 TokenSym *ts, **ptable;
1632 int i;
1634 if (tok_ident >= SYM_FIRST_ANOM)
1635 error("memory full");
1637 /* expand token table if needed */
1638 i = tok_ident - TOK_IDENT;
1639 if ((i % TOK_ALLOC_INCR) == 0) {
1640 ptable = tcc_realloc(table_ident, (i + TOK_ALLOC_INCR) * sizeof(TokenSym *));
1641 if (!ptable)
1642 error("memory full");
1643 table_ident = ptable;
1646 ts = tcc_malloc(sizeof(TokenSym) + len);
1647 table_ident[i] = ts;
1648 ts->tok = tok_ident++;
1649 ts->sym_define = NULL;
1650 ts->sym_label = NULL;
1651 ts->sym_struct = NULL;
1652 ts->sym_identifier = NULL;
1653 ts->len = len;
1654 ts->hash_next = NULL;
1655 memcpy(ts->str, str, len);
1656 ts->str[len] = '\0';
1657 *pts = ts;
1658 return ts;
1661 #define TOK_HASH_INIT 1
1662 #define TOK_HASH_FUNC(h, c) ((h) * 263 + (c))
1664 /* find a token and add it if not found */
1665 static TokenSym *tok_alloc(const char *str, int len)
1667 TokenSym *ts, **pts;
1668 int i;
1669 unsigned int h;
1671 h = TOK_HASH_INIT;
1672 for(i=0;i<len;i++)
1673 h = TOK_HASH_FUNC(h, ((unsigned char *)str)[i]);
1674 h &= (TOK_HASH_SIZE - 1);
1676 pts = &hash_ident[h];
1677 for(;;) {
1678 ts = *pts;
1679 if (!ts)
1680 break;
1681 if (ts->len == len && !memcmp(ts->str, str, len))
1682 return ts;
1683 pts = &(ts->hash_next);
1685 return tok_alloc_new(pts, str, len);
1688 /* CString handling */
1690 static void cstr_realloc(CString *cstr, int new_size)
1692 int size;
1693 void *data;
1695 size = cstr->size_allocated;
1696 if (size == 0)
1697 size = 8; /* no need to allocate a too small first string */
1698 while (size < new_size)
1699 size = size * 2;
1700 data = tcc_realloc(cstr->data_allocated, size);
1701 if (!data)
1702 error("memory full");
1703 cstr->data_allocated = data;
1704 cstr->size_allocated = size;
1705 cstr->data = data;
1708 /* add a byte */
1709 static inline void cstr_ccat(CString *cstr, int ch)
1711 int size;
1712 size = cstr->size + 1;
1713 if (size > cstr->size_allocated)
1714 cstr_realloc(cstr, size);
1715 ((unsigned char *)cstr->data)[size - 1] = ch;
1716 cstr->size = size;
1719 static void cstr_cat(CString *cstr, const char *str)
1721 int c;
1722 for(;;) {
1723 c = *str;
1724 if (c == '\0')
1725 break;
1726 cstr_ccat(cstr, c);
1727 str++;
1731 /* add a wide char */
1732 static void cstr_wccat(CString *cstr, int ch)
1734 int size;
1735 size = cstr->size + sizeof(nwchar_t);
1736 if (size > cstr->size_allocated)
1737 cstr_realloc(cstr, size);
1738 *(nwchar_t *)(((unsigned char *)cstr->data) + size - sizeof(nwchar_t)) = ch;
1739 cstr->size = size;
1742 static void cstr_new(CString *cstr)
1744 memset(cstr, 0, sizeof(CString));
1747 /* free string and reset it to NULL */
1748 static void cstr_free(CString *cstr)
1750 tcc_free(cstr->data_allocated);
1751 cstr_new(cstr);
1754 #define cstr_reset(cstr) cstr_free(cstr)
1756 /* XXX: unicode ? */
1757 static void add_char(CString *cstr, int c)
1759 if (c == '\'' || c == '\"' || c == '\\') {
1760 /* XXX: could be more precise if char or string */
1761 cstr_ccat(cstr, '\\');
1763 if (c >= 32 && c <= 126) {
1764 cstr_ccat(cstr, c);
1765 } else {
1766 cstr_ccat(cstr, '\\');
1767 if (c == '\n') {
1768 cstr_ccat(cstr, 'n');
1769 } else {
1770 cstr_ccat(cstr, '0' + ((c >> 6) & 7));
1771 cstr_ccat(cstr, '0' + ((c >> 3) & 7));
1772 cstr_ccat(cstr, '0' + (c & 7));
1777 /* XXX: buffer overflow */
1778 /* XXX: float tokens */
1779 char *get_tok_str(int v, CValue *cv)
1781 static char buf[STRING_MAX_SIZE + 1];
1782 static CString cstr_buf;
1783 CString *cstr;
1784 unsigned char *q;
1785 char *p;
1786 int i, len;
1788 /* NOTE: to go faster, we give a fixed buffer for small strings */
1789 cstr_reset(&cstr_buf);
1790 cstr_buf.data = buf;
1791 cstr_buf.size_allocated = sizeof(buf);
1792 p = buf;
1794 switch(v) {
1795 case TOK_CINT:
1796 case TOK_CUINT:
1797 /* XXX: not quite exact, but only useful for testing */
1798 sprintf(p, "%u", cv->ui);
1799 break;
1800 case TOK_CLLONG:
1801 case TOK_CULLONG:
1802 /* XXX: not quite exact, but only useful for testing */
1803 sprintf(p, "%Lu", cv->ull);
1804 break;
1805 case TOK_LCHAR:
1806 cstr_ccat(&cstr_buf, 'L');
1807 case TOK_CCHAR:
1808 cstr_ccat(&cstr_buf, '\'');
1809 add_char(&cstr_buf, cv->i);
1810 cstr_ccat(&cstr_buf, '\'');
1811 cstr_ccat(&cstr_buf, '\0');
1812 break;
1813 case TOK_PPNUM:
1814 cstr = cv->cstr;
1815 len = cstr->size - 1;
1816 for(i=0;i<len;i++)
1817 add_char(&cstr_buf, ((unsigned char *)cstr->data)[i]);
1818 cstr_ccat(&cstr_buf, '\0');
1819 break;
1820 case TOK_LSTR:
1821 cstr_ccat(&cstr_buf, 'L');
1822 case TOK_STR:
1823 cstr = cv->cstr;
1824 cstr_ccat(&cstr_buf, '\"');
1825 if (v == TOK_STR) {
1826 len = cstr->size - 1;
1827 for(i=0;i<len;i++)
1828 add_char(&cstr_buf, ((unsigned char *)cstr->data)[i]);
1829 } else {
1830 len = (cstr->size / sizeof(nwchar_t)) - 1;
1831 for(i=0;i<len;i++)
1832 add_char(&cstr_buf, ((nwchar_t *)cstr->data)[i]);
1834 cstr_ccat(&cstr_buf, '\"');
1835 cstr_ccat(&cstr_buf, '\0');
1836 break;
1837 case TOK_LT:
1838 v = '<';
1839 goto addv;
1840 case TOK_GT:
1841 v = '>';
1842 goto addv;
1843 case TOK_DOTS:
1844 return strcpy(p, "...");
1845 case TOK_A_SHL:
1846 return strcpy(p, "<<=");
1847 case TOK_A_SAR:
1848 return strcpy(p, ">>=");
1849 default:
1850 if (v < TOK_IDENT) {
1851 /* search in two bytes table */
1852 q = tok_two_chars;
1853 while (*q) {
1854 if (q[2] == v) {
1855 *p++ = q[0];
1856 *p++ = q[1];
1857 *p = '\0';
1858 return buf;
1860 q += 3;
1862 addv:
1863 *p++ = v;
1864 *p = '\0';
1865 } else if (v < tok_ident) {
1866 return table_ident[v - TOK_IDENT]->str;
1867 } else if (v >= SYM_FIRST_ANOM) {
1868 /* special name for anonymous symbol */
1869 sprintf(p, "L.%u", v - SYM_FIRST_ANOM);
1870 } else {
1871 /* should never happen */
1872 return NULL;
1874 break;
1876 return cstr_buf.data;
1879 /* push, without hashing */
1880 static Sym *sym_push2(Sym **ps, int v, int t, long c)
1882 Sym *s;
1883 s = sym_malloc();
1884 s->v = v;
1885 s->type.t = t;
1886 s->c = c;
1887 s->next = NULL;
1888 /* add in stack */
1889 s->prev = *ps;
1890 *ps = s;
1891 return s;
1894 /* find a symbol and return its associated structure. 's' is the top
1895 of the symbol stack */
1896 static Sym *sym_find2(Sym *s, int v)
1898 while (s) {
1899 if (s->v == v)
1900 return s;
1901 s = s->prev;
1903 return NULL;
1906 /* structure lookup */
1907 static inline Sym *struct_find(int v)
1909 v -= TOK_IDENT;
1910 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1911 return NULL;
1912 return table_ident[v]->sym_struct;
1915 /* find an identifier */
1916 static inline Sym *sym_find(int v)
1918 v -= TOK_IDENT;
1919 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1920 return NULL;
1921 return table_ident[v]->sym_identifier;
1924 /* push a given symbol on the symbol stack */
1925 static Sym *sym_push(int v, CType *type, int r, int c)
1927 Sym *s, **ps;
1928 TokenSym *ts;
1930 if (local_stack)
1931 ps = &local_stack;
1932 else
1933 ps = &global_stack;
1934 s = sym_push2(ps, v, type->t, c);
1935 s->type.ref = type->ref;
1936 s->r = r;
1937 /* don't record fields or anonymous symbols */
1938 /* XXX: simplify */
1939 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
1940 /* record symbol in token array */
1941 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
1942 if (v & SYM_STRUCT)
1943 ps = &ts->sym_struct;
1944 else
1945 ps = &ts->sym_identifier;
1946 s->prev_tok = *ps;
1947 *ps = s;
1949 return s;
1952 /* push a global identifier */
1953 static Sym *global_identifier_push(int v, int t, int c)
1955 Sym *s, **ps;
1956 s = sym_push2(&global_stack, v, t, c);
1957 /* don't record anonymous symbol */
1958 if (v < SYM_FIRST_ANOM) {
1959 ps = &table_ident[v - TOK_IDENT]->sym_identifier;
1960 /* modify the top most local identifier, so that
1961 sym_identifier will point to 's' when popped */
1962 while (*ps != NULL)
1963 ps = &(*ps)->prev_tok;
1964 s->prev_tok = NULL;
1965 *ps = s;
1967 return s;
1970 /* pop symbols until top reaches 'b' */
1971 static void sym_pop(Sym **ptop, Sym *b)
1973 Sym *s, *ss, **ps;
1974 TokenSym *ts;
1975 int v;
1977 s = *ptop;
1978 while(s != b) {
1979 ss = s->prev;
1980 v = s->v;
1981 /* remove symbol in token array */
1982 /* XXX: simplify */
1983 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
1984 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
1985 if (v & SYM_STRUCT)
1986 ps = &ts->sym_struct;
1987 else
1988 ps = &ts->sym_identifier;
1989 *ps = s->prev_tok;
1991 sym_free(s);
1992 s = ss;
1994 *ptop = b;
1997 /* I/O layer */
1999 BufferedFile *tcc_open(TCCState *s1, const char *filename)
2001 int fd;
2002 BufferedFile *bf;
2004 if (strcmp(filename, "-") == 0)
2005 fd = 0, filename = "stdin";
2006 else
2007 fd = open(filename, O_RDONLY | O_BINARY);
2008 if ((verbose == 2 && fd >= 0) || verbose == 3)
2009 printf("%s %*s%s\n", fd < 0 ? "nf":"->",
2010 (s1->include_stack_ptr - s1->include_stack), "", filename);
2011 if (fd < 0)
2012 return NULL;
2013 bf = tcc_malloc(sizeof(BufferedFile));
2014 bf->fd = fd;
2015 bf->buf_ptr = bf->buffer;
2016 bf->buf_end = bf->buffer;
2017 bf->buffer[0] = CH_EOB; /* put eob symbol */
2018 pstrcpy(bf->filename, sizeof(bf->filename), filename);
2019 #ifdef _WIN32
2020 normalize_slashes(bf->filename);
2021 #endif
2022 bf->line_num = 1;
2023 bf->ifndef_macro = 0;
2024 bf->ifdef_stack_ptr = s1->ifdef_stack_ptr;
2025 // printf("opening '%s'\n", filename);
2026 return bf;
2029 void tcc_close(BufferedFile *bf)
2031 total_lines += bf->line_num;
2032 close(bf->fd);
2033 tcc_free(bf);
2036 /* fill input buffer and peek next char */
2037 static int tcc_peekc_slow(BufferedFile *bf)
2039 int len;
2040 /* only tries to read if really end of buffer */
2041 if (bf->buf_ptr >= bf->buf_end) {
2042 if (bf->fd != -1) {
2043 #if defined(PARSE_DEBUG)
2044 len = 8;
2045 #else
2046 len = IO_BUF_SIZE;
2047 #endif
2048 len = read(bf->fd, bf->buffer, len);
2049 if (len < 0)
2050 len = 0;
2051 } else {
2052 len = 0;
2054 total_bytes += len;
2055 bf->buf_ptr = bf->buffer;
2056 bf->buf_end = bf->buffer + len;
2057 *bf->buf_end = CH_EOB;
2059 if (bf->buf_ptr < bf->buf_end) {
2060 return bf->buf_ptr[0];
2061 } else {
2062 bf->buf_ptr = bf->buf_end;
2063 return CH_EOF;
2067 /* return the current character, handling end of block if necessary
2068 (but not stray) */
2069 static int handle_eob(void)
2071 return tcc_peekc_slow(file);
2074 /* read next char from current input file and handle end of input buffer */
2075 static inline void inp(void)
2077 ch = *(++(file->buf_ptr));
2078 /* end of buffer/file handling */
2079 if (ch == CH_EOB)
2080 ch = handle_eob();
2083 /* handle '\[\r]\n' */
2084 static int handle_stray_noerror(void)
2086 while (ch == '\\') {
2087 inp();
2088 if (ch == '\n') {
2089 file->line_num++;
2090 inp();
2091 } else if (ch == '\r') {
2092 inp();
2093 if (ch != '\n')
2094 goto fail;
2095 file->line_num++;
2096 inp();
2097 } else {
2098 fail:
2099 return 1;
2102 return 0;
2105 static void handle_stray(void)
2107 if (handle_stray_noerror())
2108 error("stray '\\' in program");
2111 /* skip the stray and handle the \\n case. Output an error if
2112 incorrect char after the stray */
2113 static int handle_stray1(uint8_t *p)
2115 int c;
2117 if (p >= file->buf_end) {
2118 file->buf_ptr = p;
2119 c = handle_eob();
2120 p = file->buf_ptr;
2121 if (c == '\\')
2122 goto parse_stray;
2123 } else {
2124 parse_stray:
2125 file->buf_ptr = p;
2126 ch = *p;
2127 handle_stray();
2128 p = file->buf_ptr;
2129 c = *p;
2131 return c;
2134 /* handle just the EOB case, but not stray */
2135 #define PEEKC_EOB(c, p)\
2137 p++;\
2138 c = *p;\
2139 if (c == '\\') {\
2140 file->buf_ptr = p;\
2141 c = handle_eob();\
2142 p = file->buf_ptr;\
2146 /* handle the complicated stray case */
2147 #define PEEKC(c, p)\
2149 p++;\
2150 c = *p;\
2151 if (c == '\\') {\
2152 c = handle_stray1(p);\
2153 p = file->buf_ptr;\
2157 /* input with '\[\r]\n' handling. Note that this function cannot
2158 handle other characters after '\', so you cannot call it inside
2159 strings or comments */
2160 static void minp(void)
2162 inp();
2163 if (ch == '\\')
2164 handle_stray();
2168 /* single line C++ comments */
2169 static uint8_t *parse_line_comment(uint8_t *p)
2171 int c;
2173 p++;
2174 for(;;) {
2175 c = *p;
2176 redo:
2177 if (c == '\n' || c == CH_EOF) {
2178 break;
2179 } else if (c == '\\') {
2180 file->buf_ptr = p;
2181 c = handle_eob();
2182 p = file->buf_ptr;
2183 if (c == '\\') {
2184 PEEKC_EOB(c, p);
2185 if (c == '\n') {
2186 file->line_num++;
2187 PEEKC_EOB(c, p);
2188 } else if (c == '\r') {
2189 PEEKC_EOB(c, p);
2190 if (c == '\n') {
2191 file->line_num++;
2192 PEEKC_EOB(c, p);
2195 } else {
2196 goto redo;
2198 } else {
2199 p++;
2202 return p;
2205 /* C comments */
2206 static uint8_t *parse_comment(uint8_t *p)
2208 int c;
2210 p++;
2211 for(;;) {
2212 /* fast skip loop */
2213 for(;;) {
2214 c = *p;
2215 if (c == '\n' || c == '*' || c == '\\')
2216 break;
2217 p++;
2218 c = *p;
2219 if (c == '\n' || c == '*' || c == '\\')
2220 break;
2221 p++;
2223 /* now we can handle all the cases */
2224 if (c == '\n') {
2225 file->line_num++;
2226 p++;
2227 } else if (c == '*') {
2228 p++;
2229 for(;;) {
2230 c = *p;
2231 if (c == '*') {
2232 p++;
2233 } else if (c == '/') {
2234 goto end_of_comment;
2235 } else if (c == '\\') {
2236 file->buf_ptr = p;
2237 c = handle_eob();
2238 p = file->buf_ptr;
2239 if (c == '\\') {
2240 /* skip '\[\r]\n', otherwise just skip the stray */
2241 while (c == '\\') {
2242 PEEKC_EOB(c, p);
2243 if (c == '\n') {
2244 file->line_num++;
2245 PEEKC_EOB(c, p);
2246 } else if (c == '\r') {
2247 PEEKC_EOB(c, p);
2248 if (c == '\n') {
2249 file->line_num++;
2250 PEEKC_EOB(c, p);
2252 } else {
2253 goto after_star;
2257 } else {
2258 break;
2261 after_star: ;
2262 } else {
2263 /* stray, eob or eof */
2264 file->buf_ptr = p;
2265 c = handle_eob();
2266 p = file->buf_ptr;
2267 if (c == CH_EOF) {
2268 error("unexpected end of file in comment");
2269 } else if (c == '\\') {
2270 p++;
2274 end_of_comment:
2275 p++;
2276 return p;
2279 #define cinp minp
2281 /* space exlcuding newline */
2282 static inline int is_space(int ch)
2284 return ch == ' ' || ch == '\t' || ch == '\v' || ch == '\f' || ch == '\r';
2287 static inline void skip_spaces(void)
2289 while (is_space(ch))
2290 cinp();
2293 /* parse a string without interpreting escapes */
2294 static uint8_t *parse_pp_string(uint8_t *p,
2295 int sep, CString *str)
2297 int c;
2298 p++;
2299 for(;;) {
2300 c = *p;
2301 if (c == sep) {
2302 break;
2303 } else if (c == '\\') {
2304 file->buf_ptr = p;
2305 c = handle_eob();
2306 p = file->buf_ptr;
2307 if (c == CH_EOF) {
2308 unterminated_string:
2309 /* XXX: indicate line number of start of string */
2310 error("missing terminating %c character", sep);
2311 } else if (c == '\\') {
2312 /* escape : just skip \[\r]\n */
2313 PEEKC_EOB(c, p);
2314 if (c == '\n') {
2315 file->line_num++;
2316 p++;
2317 } else if (c == '\r') {
2318 PEEKC_EOB(c, p);
2319 if (c != '\n')
2320 expect("'\n' after '\r'");
2321 file->line_num++;
2322 p++;
2323 } else if (c == CH_EOF) {
2324 goto unterminated_string;
2325 } else {
2326 if (str) {
2327 cstr_ccat(str, '\\');
2328 cstr_ccat(str, c);
2330 p++;
2333 } else if (c == '\n') {
2334 file->line_num++;
2335 goto add_char;
2336 } else if (c == '\r') {
2337 PEEKC_EOB(c, p);
2338 if (c != '\n') {
2339 if (str)
2340 cstr_ccat(str, '\r');
2341 } else {
2342 file->line_num++;
2343 goto add_char;
2345 } else {
2346 add_char:
2347 if (str)
2348 cstr_ccat(str, c);
2349 p++;
2352 p++;
2353 return p;
2356 /* skip block of text until #else, #elif or #endif. skip also pairs of
2357 #if/#endif */
2358 void preprocess_skip(void)
2360 int a, start_of_line, c, in_warn_or_error;
2361 uint8_t *p;
2363 p = file->buf_ptr;
2364 a = 0;
2365 redo_start:
2366 start_of_line = 1;
2367 in_warn_or_error = 0;
2368 for(;;) {
2369 redo_no_start:
2370 c = *p;
2371 switch(c) {
2372 case ' ':
2373 case '\t':
2374 case '\f':
2375 case '\v':
2376 case '\r':
2377 p++;
2378 goto redo_no_start;
2379 case '\n':
2380 file->line_num++;
2381 p++;
2382 goto redo_start;
2383 case '\\':
2384 file->buf_ptr = p;
2385 c = handle_eob();
2386 if (c == CH_EOF) {
2387 expect("#endif");
2388 } else if (c == '\\') {
2389 ch = file->buf_ptr[0];
2390 handle_stray_noerror();
2392 p = file->buf_ptr;
2393 goto redo_no_start;
2394 /* skip strings */
2395 case '\"':
2396 case '\'':
2397 if (in_warn_or_error)
2398 goto _default;
2399 p = parse_pp_string(p, c, NULL);
2400 break;
2401 /* skip comments */
2402 case '/':
2403 if (in_warn_or_error)
2404 goto _default;
2405 file->buf_ptr = p;
2406 ch = *p;
2407 minp();
2408 p = file->buf_ptr;
2409 if (ch == '*') {
2410 p = parse_comment(p);
2411 } else if (ch == '/') {
2412 p = parse_line_comment(p);
2414 break;
2415 case '#':
2416 p++;
2417 if (start_of_line) {
2418 file->buf_ptr = p;
2419 next_nomacro();
2420 p = file->buf_ptr;
2421 if (a == 0 &&
2422 (tok == TOK_ELSE || tok == TOK_ELIF || tok == TOK_ENDIF))
2423 goto the_end;
2424 if (tok == TOK_IF || tok == TOK_IFDEF || tok == TOK_IFNDEF)
2425 a++;
2426 else if (tok == TOK_ENDIF)
2427 a--;
2428 else if( tok == TOK_ERROR || tok == TOK_WARNING)
2429 in_warn_or_error = 1;
2431 break;
2432 _default:
2433 default:
2434 p++;
2435 break;
2437 start_of_line = 0;
2439 the_end: ;
2440 file->buf_ptr = p;
2443 /* ParseState handling */
2445 /* XXX: currently, no include file info is stored. Thus, we cannot display
2446 accurate messages if the function or data definition spans multiple
2447 files */
2449 /* save current parse state in 's' */
2450 void save_parse_state(ParseState *s)
2452 s->line_num = file->line_num;
2453 s->macro_ptr = macro_ptr;
2454 s->tok = tok;
2455 s->tokc = tokc;
2458 /* restore parse state from 's' */
2459 void restore_parse_state(ParseState *s)
2461 file->line_num = s->line_num;
2462 macro_ptr = s->macro_ptr;
2463 tok = s->tok;
2464 tokc = s->tokc;
2467 /* return the number of additional 'ints' necessary to store the
2468 token */
2469 static inline int tok_ext_size(int t)
2471 switch(t) {
2472 /* 4 bytes */
2473 case TOK_CINT:
2474 case TOK_CUINT:
2475 case TOK_CCHAR:
2476 case TOK_LCHAR:
2477 case TOK_CFLOAT:
2478 case TOK_LINENUM:
2479 return 1;
2480 case TOK_STR:
2481 case TOK_LSTR:
2482 case TOK_PPNUM:
2483 error("unsupported token");
2484 return 1;
2485 case TOK_CDOUBLE:
2486 case TOK_CLLONG:
2487 case TOK_CULLONG:
2488 return 2;
2489 case TOK_CLDOUBLE:
2490 return LDOUBLE_SIZE / 4;
2491 default:
2492 return 0;
2496 /* token string handling */
2498 static inline void tok_str_new(TokenString *s)
2500 s->str = NULL;
2501 s->len = 0;
2502 s->allocated_len = 0;
2503 s->last_line_num = -1;
2506 static void tok_str_free(int *str)
2508 tcc_free(str);
2511 static int *tok_str_realloc(TokenString *s)
2513 int *str, len;
2515 if (s->allocated_len == 0) {
2516 len = 8;
2517 } else {
2518 len = s->allocated_len * 2;
2520 str = tcc_realloc(s->str, len * sizeof(int));
2521 if (!str)
2522 error("memory full");
2523 s->allocated_len = len;
2524 s->str = str;
2525 return str;
2528 static void tok_str_add(TokenString *s, int t)
2530 int len, *str;
2532 len = s->len;
2533 str = s->str;
2534 if (len >= s->allocated_len)
2535 str = tok_str_realloc(s);
2536 str[len++] = t;
2537 s->len = len;
2540 static void tok_str_add2(TokenString *s, int t, CValue *cv)
2542 int len, *str;
2544 len = s->len;
2545 str = s->str;
2547 /* allocate space for worst case */
2548 if (len + TOK_MAX_SIZE > s->allocated_len)
2549 str = tok_str_realloc(s);
2550 str[len++] = t;
2551 switch(t) {
2552 case TOK_CINT:
2553 case TOK_CUINT:
2554 case TOK_CCHAR:
2555 case TOK_LCHAR:
2556 case TOK_CFLOAT:
2557 case TOK_LINENUM:
2558 str[len++] = cv->tab[0];
2559 break;
2560 case TOK_PPNUM:
2561 case TOK_STR:
2562 case TOK_LSTR:
2564 int nb_words;
2565 CString *cstr;
2567 nb_words = (sizeof(CString) + cv->cstr->size + 3) >> 2;
2568 while ((len + nb_words) > s->allocated_len)
2569 str = tok_str_realloc(s);
2570 cstr = (CString *)(str + len);
2571 cstr->data = NULL;
2572 cstr->size = cv->cstr->size;
2573 cstr->data_allocated = NULL;
2574 cstr->size_allocated = cstr->size;
2575 memcpy((char *)cstr + sizeof(CString),
2576 cv->cstr->data, cstr->size);
2577 len += nb_words;
2579 break;
2580 case TOK_CDOUBLE:
2581 case TOK_CLLONG:
2582 case TOK_CULLONG:
2583 #if LDOUBLE_SIZE == 8
2584 case TOK_CLDOUBLE:
2585 #endif
2586 str[len++] = cv->tab[0];
2587 str[len++] = cv->tab[1];
2588 break;
2589 #if LDOUBLE_SIZE == 12
2590 case TOK_CLDOUBLE:
2591 str[len++] = cv->tab[0];
2592 str[len++] = cv->tab[1];
2593 str[len++] = cv->tab[2];
2594 #elif LDOUBLE_SIZE == 16
2595 case TOK_CLDOUBLE:
2596 str[len++] = cv->tab[0];
2597 str[len++] = cv->tab[1];
2598 str[len++] = cv->tab[2];
2599 str[len++] = cv->tab[3];
2600 #elif LDOUBLE_SIZE != 8
2601 #error add long double size support
2602 #endif
2603 break;
2604 default:
2605 break;
2607 s->len = len;
2610 /* add the current parse token in token string 's' */
2611 static void tok_str_add_tok(TokenString *s)
2613 CValue cval;
2615 /* save line number info */
2616 if (file->line_num != s->last_line_num) {
2617 s->last_line_num = file->line_num;
2618 cval.i = s->last_line_num;
2619 tok_str_add2(s, TOK_LINENUM, &cval);
2621 tok_str_add2(s, tok, &tokc);
2624 #if LDOUBLE_SIZE == 16
2625 #define LDOUBLE_GET(p, cv) \
2626 cv.tab[0] = p[0]; \
2627 cv.tab[1] = p[1]; \
2628 cv.tab[2] = p[2]; \
2629 cv.tab[3] = p[3];
2630 #elif LDOUBLE_SIZE == 12
2631 #define LDOUBLE_GET(p, cv) \
2632 cv.tab[0] = p[0]; \
2633 cv.tab[1] = p[1]; \
2634 cv.tab[2] = p[2];
2635 #elif LDOUBLE_SIZE == 8
2636 #define LDOUBLE_GET(p, cv) \
2637 cv.tab[0] = p[0]; \
2638 cv.tab[1] = p[1];
2639 #else
2640 #error add long double size support
2641 #endif
2644 /* get a token from an integer array and increment pointer
2645 accordingly. we code it as a macro to avoid pointer aliasing. */
2646 #define TOK_GET(t, p, cv) \
2648 t = *p++; \
2649 switch(t) { \
2650 case TOK_CINT: \
2651 case TOK_CUINT: \
2652 case TOK_CCHAR: \
2653 case TOK_LCHAR: \
2654 case TOK_CFLOAT: \
2655 case TOK_LINENUM: \
2656 cv.tab[0] = *p++; \
2657 break; \
2658 case TOK_STR: \
2659 case TOK_LSTR: \
2660 case TOK_PPNUM: \
2661 cv.cstr = (CString *)p; \
2662 cv.cstr->data = (char *)p + sizeof(CString);\
2663 p += (sizeof(CString) + cv.cstr->size + 3) >> 2;\
2664 break; \
2665 case TOK_CDOUBLE: \
2666 case TOK_CLLONG: \
2667 case TOK_CULLONG: \
2668 cv.tab[0] = p[0]; \
2669 cv.tab[1] = p[1]; \
2670 p += 2; \
2671 break; \
2672 case TOK_CLDOUBLE: \
2673 LDOUBLE_GET(p, cv); \
2674 p += LDOUBLE_SIZE / 4; \
2675 break; \
2676 default: \
2677 break; \
2681 /* defines handling */
2682 static inline void define_push(int v, int macro_type, int *str, Sym *first_arg)
2684 Sym *s;
2686 s = sym_push2(&define_stack, v, macro_type, (long)str);
2687 s->next = first_arg;
2688 table_ident[v - TOK_IDENT]->sym_define = s;
2691 /* undefined a define symbol. Its name is just set to zero */
2692 static void define_undef(Sym *s)
2694 int v;
2695 v = s->v;
2696 if (v >= TOK_IDENT && v < tok_ident)
2697 table_ident[v - TOK_IDENT]->sym_define = NULL;
2698 s->v = 0;
2701 static inline Sym *define_find(int v)
2703 v -= TOK_IDENT;
2704 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
2705 return NULL;
2706 return table_ident[v]->sym_define;
2709 /* free define stack until top reaches 'b' */
2710 static void free_defines(Sym *b)
2712 Sym *top, *top1;
2713 int v;
2715 top = define_stack;
2716 while (top != b) {
2717 top1 = top->prev;
2718 /* do not free args or predefined defines */
2719 if (top->c)
2720 tok_str_free((int *)top->c);
2721 v = top->v;
2722 if (v >= TOK_IDENT && v < tok_ident)
2723 table_ident[v - TOK_IDENT]->sym_define = NULL;
2724 sym_free(top);
2725 top = top1;
2727 define_stack = b;
2730 /* label lookup */
2731 static Sym *label_find(int v)
2733 v -= TOK_IDENT;
2734 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
2735 return NULL;
2736 return table_ident[v]->sym_label;
2739 static Sym *label_push(Sym **ptop, int v, int flags)
2741 Sym *s, **ps;
2742 s = sym_push2(ptop, v, 0, 0);
2743 s->r = flags;
2744 ps = &table_ident[v - TOK_IDENT]->sym_label;
2745 if (ptop == &global_label_stack) {
2746 /* modify the top most local identifier, so that
2747 sym_identifier will point to 's' when popped */
2748 while (*ps != NULL)
2749 ps = &(*ps)->prev_tok;
2751 s->prev_tok = *ps;
2752 *ps = s;
2753 return s;
2756 /* pop labels until element last is reached. Look if any labels are
2757 undefined. Define symbols if '&&label' was used. */
2758 static void label_pop(Sym **ptop, Sym *slast)
2760 Sym *s, *s1;
2761 for(s = *ptop; s != slast; s = s1) {
2762 s1 = s->prev;
2763 if (s->r == LABEL_DECLARED) {
2764 warning("label '%s' declared but not used", get_tok_str(s->v, NULL));
2765 } else if (s->r == LABEL_FORWARD) {
2766 error("label '%s' used but not defined",
2767 get_tok_str(s->v, NULL));
2768 } else {
2769 if (s->c) {
2770 /* define corresponding symbol. A size of
2771 1 is put. */
2772 put_extern_sym(s, cur_text_section, (long)s->next, 1);
2775 /* remove label */
2776 table_ident[s->v - TOK_IDENT]->sym_label = s->prev_tok;
2777 sym_free(s);
2779 *ptop = slast;
2782 /* eval an expression for #if/#elif */
2783 static int expr_preprocess(void)
2785 int c, t;
2786 TokenString str;
2788 tok_str_new(&str);
2789 while (tok != TOK_LINEFEED && tok != TOK_EOF) {
2790 next(); /* do macro subst */
2791 if (tok == TOK_DEFINED) {
2792 next_nomacro();
2793 t = tok;
2794 if (t == '(')
2795 next_nomacro();
2796 c = define_find(tok) != 0;
2797 if (t == '(')
2798 next_nomacro();
2799 tok = TOK_CINT;
2800 tokc.i = c;
2801 } else if (tok >= TOK_IDENT) {
2802 /* if undefined macro */
2803 tok = TOK_CINT;
2804 tokc.i = 0;
2806 tok_str_add_tok(&str);
2808 tok_str_add(&str, -1); /* simulate end of file */
2809 tok_str_add(&str, 0);
2810 /* now evaluate C constant expression */
2811 macro_ptr = str.str;
2812 next();
2813 c = expr_const();
2814 macro_ptr = NULL;
2815 tok_str_free(str.str);
2816 return c != 0;
2819 #if defined(PARSE_DEBUG) || defined(PP_DEBUG)
2820 static void tok_print(int *str)
2822 int t;
2823 CValue cval;
2825 while (1) {
2826 TOK_GET(t, str, cval);
2827 if (!t)
2828 break;
2829 printf(" %s", get_tok_str(t, &cval));
2831 printf("\n");
2833 #endif
2835 /* parse after #define */
2836 static void parse_define(void)
2838 Sym *s, *first, **ps;
2839 int v, t, varg, is_vaargs, c;
2840 TokenString str;
2842 v = tok;
2843 if (v < TOK_IDENT)
2844 error("invalid macro name '%s'", get_tok_str(tok, &tokc));
2845 /* XXX: should check if same macro (ANSI) */
2846 first = NULL;
2847 t = MACRO_OBJ;
2848 /* '(' must be just after macro definition for MACRO_FUNC */
2849 c = file->buf_ptr[0];
2850 if (c == '\\')
2851 c = handle_stray1(file->buf_ptr);
2852 if (c == '(') {
2853 next_nomacro();
2854 next_nomacro();
2855 ps = &first;
2856 while (tok != ')') {
2857 varg = tok;
2858 next_nomacro();
2859 is_vaargs = 0;
2860 if (varg == TOK_DOTS) {
2861 varg = TOK___VA_ARGS__;
2862 is_vaargs = 1;
2863 } else if (tok == TOK_DOTS && gnu_ext) {
2864 is_vaargs = 1;
2865 next_nomacro();
2867 if (varg < TOK_IDENT)
2868 error("badly punctuated parameter list");
2869 s = sym_push2(&define_stack, varg | SYM_FIELD, is_vaargs, 0);
2870 *ps = s;
2871 ps = &s->next;
2872 if (tok != ',')
2873 break;
2874 next_nomacro();
2876 t = MACRO_FUNC;
2878 tok_str_new(&str);
2879 next_nomacro();
2880 /* EOF testing necessary for '-D' handling */
2881 while (tok != TOK_LINEFEED && tok != TOK_EOF) {
2882 tok_str_add2(&str, tok, &tokc);
2883 next_nomacro();
2885 tok_str_add(&str, 0);
2886 #ifdef PP_DEBUG
2887 printf("define %s %d: ", get_tok_str(v, NULL), t);
2888 tok_print(str.str);
2889 #endif
2890 define_push(v, t, str.str, first);
2893 static inline int hash_cached_include(int type, const char *filename)
2895 const unsigned char *s;
2896 unsigned int h;
2898 h = TOK_HASH_INIT;
2899 h = TOK_HASH_FUNC(h, type);
2900 s = filename;
2901 while (*s) {
2902 h = TOK_HASH_FUNC(h, *s);
2903 s++;
2905 h &= (CACHED_INCLUDES_HASH_SIZE - 1);
2906 return h;
2909 /* XXX: use a token or a hash table to accelerate matching ? */
2910 static CachedInclude *search_cached_include(TCCState *s1,
2911 int type, const char *filename)
2913 CachedInclude *e;
2914 int i, h;
2915 h = hash_cached_include(type, filename);
2916 i = s1->cached_includes_hash[h];
2917 for(;;) {
2918 if (i == 0)
2919 break;
2920 e = s1->cached_includes[i - 1];
2921 if (e->type == type && !PATHCMP(e->filename, filename))
2922 return e;
2923 i = e->hash_next;
2925 return NULL;
2928 static inline void add_cached_include(TCCState *s1, int type,
2929 const char *filename, int ifndef_macro)
2931 CachedInclude *e;
2932 int h;
2934 if (search_cached_include(s1, type, filename))
2935 return;
2936 #ifdef INC_DEBUG
2937 printf("adding cached '%s' %s\n", filename, get_tok_str(ifndef_macro, NULL));
2938 #endif
2939 e = tcc_malloc(sizeof(CachedInclude) + strlen(filename));
2940 if (!e)
2941 return;
2942 e->type = type;
2943 strcpy(e->filename, filename);
2944 e->ifndef_macro = ifndef_macro;
2945 dynarray_add((void ***)&s1->cached_includes, &s1->nb_cached_includes, e);
2946 /* add in hash table */
2947 h = hash_cached_include(type, filename);
2948 e->hash_next = s1->cached_includes_hash[h];
2949 s1->cached_includes_hash[h] = s1->nb_cached_includes;
2952 static void pragma_parse(TCCState *s1)
2954 int val;
2956 next();
2957 if (tok == TOK_pack) {
2959 This may be:
2960 #pragma pack(1) // set
2961 #pragma pack() // reset to default
2962 #pragma pack(push,1) // push & set
2963 #pragma pack(pop) // restore previous
2965 next();
2966 skip('(');
2967 if (tok == TOK_ASM_pop) {
2968 next();
2969 if (s1->pack_stack_ptr <= s1->pack_stack) {
2970 stk_error:
2971 error("out of pack stack");
2973 s1->pack_stack_ptr--;
2974 } else {
2975 val = 0;
2976 if (tok != ')') {
2977 if (tok == TOK_ASM_push) {
2978 next();
2979 if (s1->pack_stack_ptr >= s1->pack_stack + PACK_STACK_SIZE - 1)
2980 goto stk_error;
2981 s1->pack_stack_ptr++;
2982 skip(',');
2984 if (tok != TOK_CINT) {
2985 pack_error:
2986 error("invalid pack pragma");
2988 val = tokc.i;
2989 if (val < 1 || val > 16 || (val & (val - 1)) != 0)
2990 goto pack_error;
2991 next();
2993 *s1->pack_stack_ptr = val;
2994 skip(')');
2999 /* is_bof is true if first non space token at beginning of file */
3000 static void preprocess(int is_bof)
3002 TCCState *s1 = tcc_state;
3003 int size, i, c, n, saved_parse_flags;
3004 char buf[1024], *q;
3005 char buf1[1024];
3006 BufferedFile *f;
3007 Sym *s;
3008 CachedInclude *e;
3010 saved_parse_flags = parse_flags;
3011 parse_flags = PARSE_FLAG_PREPROCESS | PARSE_FLAG_TOK_NUM |
3012 PARSE_FLAG_LINEFEED;
3013 next_nomacro();
3014 redo:
3015 switch(tok) {
3016 case TOK_DEFINE:
3017 next_nomacro();
3018 parse_define();
3019 break;
3020 case TOK_UNDEF:
3021 next_nomacro();
3022 s = define_find(tok);
3023 /* undefine symbol by putting an invalid name */
3024 if (s)
3025 define_undef(s);
3026 break;
3027 case TOK_INCLUDE:
3028 case TOK_INCLUDE_NEXT:
3029 ch = file->buf_ptr[0];
3030 /* XXX: incorrect if comments : use next_nomacro with a special mode */
3031 skip_spaces();
3032 if (ch == '<') {
3033 c = '>';
3034 goto read_name;
3035 } else if (ch == '\"') {
3036 c = ch;
3037 read_name:
3038 inp();
3039 q = buf;
3040 while (ch != c && ch != '\n' && ch != CH_EOF) {
3041 if ((q - buf) < sizeof(buf) - 1)
3042 *q++ = ch;
3043 if (ch == '\\') {
3044 if (handle_stray_noerror() == 0)
3045 --q;
3046 } else
3047 inp();
3049 *q = '\0';
3050 minp();
3051 #if 0
3052 /* eat all spaces and comments after include */
3053 /* XXX: slightly incorrect */
3054 while (ch1 != '\n' && ch1 != CH_EOF)
3055 inp();
3056 #endif
3057 } else {
3058 /* computed #include : either we have only strings or
3059 we have anything enclosed in '<>' */
3060 next();
3061 buf[0] = '\0';
3062 if (tok == TOK_STR) {
3063 while (tok != TOK_LINEFEED) {
3064 if (tok != TOK_STR) {
3065 include_syntax:
3066 error("'#include' expects \"FILENAME\" or <FILENAME>");
3068 pstrcat(buf, sizeof(buf), (char *)tokc.cstr->data);
3069 next();
3071 c = '\"';
3072 } else {
3073 int len;
3074 while (tok != TOK_LINEFEED) {
3075 pstrcat(buf, sizeof(buf), get_tok_str(tok, &tokc));
3076 next();
3078 len = strlen(buf);
3079 /* check syntax and remove '<>' */
3080 if (len < 2 || buf[0] != '<' || buf[len - 1] != '>')
3081 goto include_syntax;
3082 memmove(buf, buf + 1, len - 2);
3083 buf[len - 2] = '\0';
3084 c = '>';
3088 e = search_cached_include(s1, c, buf);
3089 if (e && define_find(e->ifndef_macro)) {
3090 /* no need to parse the include because the 'ifndef macro'
3091 is defined */
3092 #ifdef INC_DEBUG
3093 printf("%s: skipping %s\n", file->filename, buf);
3094 #endif
3095 } else {
3096 if (s1->include_stack_ptr >= s1->include_stack + INCLUDE_STACK_SIZE)
3097 error("#include recursion too deep");
3098 /* push current file in stack */
3099 /* XXX: fix current line init */
3100 *s1->include_stack_ptr++ = file;
3102 /* check absolute include path */
3103 if (IS_ABSPATH(buf)) {
3104 f = tcc_open(s1, buf);
3105 if (f)
3106 goto found;
3108 if (c == '\"') {
3109 /* first search in current dir if "header.h" */
3110 size = tcc_basename(file->filename) - file->filename;
3111 if (size > sizeof(buf1) - 1)
3112 size = sizeof(buf1) - 1;
3113 memcpy(buf1, file->filename, size);
3114 buf1[size] = '\0';
3115 pstrcat(buf1, sizeof(buf1), buf);
3116 f = tcc_open(s1, buf1);
3117 if (f) {
3118 if (tok == TOK_INCLUDE_NEXT)
3119 tok = TOK_INCLUDE;
3120 else
3121 goto found;
3124 /* now search in all the include paths */
3125 n = s1->nb_include_paths + s1->nb_sysinclude_paths;
3126 for(i = 0; i < n; i++) {
3127 const char *path;
3128 if (i < s1->nb_include_paths)
3129 path = s1->include_paths[i];
3130 else
3131 path = s1->sysinclude_paths[i - s1->nb_include_paths];
3132 pstrcpy(buf1, sizeof(buf1), path);
3133 pstrcat(buf1, sizeof(buf1), "/");
3134 pstrcat(buf1, sizeof(buf1), buf);
3135 f = tcc_open(s1, buf1);
3136 if (f) {
3137 if (tok == TOK_INCLUDE_NEXT)
3138 tok = TOK_INCLUDE;
3139 else
3140 goto found;
3143 --s1->include_stack_ptr;
3144 error("include file '%s' not found", buf);
3145 break;
3146 found:
3147 #ifdef INC_DEBUG
3148 printf("%s: including %s\n", file->filename, buf1);
3149 #endif
3150 f->inc_type = c;
3151 pstrcpy(f->inc_filename, sizeof(f->inc_filename), buf);
3152 file = f;
3153 /* add include file debug info */
3154 if (do_debug) {
3155 put_stabs(file->filename, N_BINCL, 0, 0, 0);
3157 tok_flags |= TOK_FLAG_BOF | TOK_FLAG_BOL;
3158 ch = file->buf_ptr[0];
3159 goto the_end;
3161 break;
3162 case TOK_IFNDEF:
3163 c = 1;
3164 goto do_ifdef;
3165 case TOK_IF:
3166 c = expr_preprocess();
3167 goto do_if;
3168 case TOK_IFDEF:
3169 c = 0;
3170 do_ifdef:
3171 next_nomacro();
3172 if (tok < TOK_IDENT)
3173 error("invalid argument for '#if%sdef'", c ? "n" : "");
3174 if (is_bof) {
3175 if (c) {
3176 #ifdef INC_DEBUG
3177 printf("#ifndef %s\n", get_tok_str(tok, NULL));
3178 #endif
3179 file->ifndef_macro = tok;
3182 c = (define_find(tok) != 0) ^ c;
3183 do_if:
3184 if (s1->ifdef_stack_ptr >= s1->ifdef_stack + IFDEF_STACK_SIZE)
3185 error("memory full");
3186 *s1->ifdef_stack_ptr++ = c;
3187 goto test_skip;
3188 case TOK_ELSE:
3189 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
3190 error("#else without matching #if");
3191 if (s1->ifdef_stack_ptr[-1] & 2)
3192 error("#else after #else");
3193 c = (s1->ifdef_stack_ptr[-1] ^= 3);
3194 goto test_skip;
3195 case TOK_ELIF:
3196 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
3197 error("#elif without matching #if");
3198 c = s1->ifdef_stack_ptr[-1];
3199 if (c > 1)
3200 error("#elif after #else");
3201 /* last #if/#elif expression was true: we skip */
3202 if (c == 1)
3203 goto skip;
3204 c = expr_preprocess();
3205 s1->ifdef_stack_ptr[-1] = c;
3206 test_skip:
3207 if (!(c & 1)) {
3208 skip:
3209 preprocess_skip();
3210 is_bof = 0;
3211 goto redo;
3213 break;
3214 case TOK_ENDIF:
3215 if (s1->ifdef_stack_ptr <= file->ifdef_stack_ptr)
3216 error("#endif without matching #if");
3217 s1->ifdef_stack_ptr--;
3218 /* '#ifndef macro' was at the start of file. Now we check if
3219 an '#endif' is exactly at the end of file */
3220 if (file->ifndef_macro &&
3221 s1->ifdef_stack_ptr == file->ifdef_stack_ptr) {
3222 file->ifndef_macro_saved = file->ifndef_macro;
3223 /* need to set to zero to avoid false matches if another
3224 #ifndef at middle of file */
3225 file->ifndef_macro = 0;
3226 while (tok != TOK_LINEFEED)
3227 next_nomacro();
3228 tok_flags |= TOK_FLAG_ENDIF;
3229 goto the_end;
3231 break;
3232 case TOK_LINE:
3233 next();
3234 if (tok != TOK_CINT)
3235 error("#line");
3236 file->line_num = tokc.i - 1; /* the line number will be incremented after */
3237 next();
3238 if (tok != TOK_LINEFEED) {
3239 if (tok != TOK_STR)
3240 error("#line");
3241 pstrcpy(file->filename, sizeof(file->filename),
3242 (char *)tokc.cstr->data);
3244 break;
3245 case TOK_ERROR:
3246 case TOK_WARNING:
3247 c = tok;
3248 ch = file->buf_ptr[0];
3249 skip_spaces();
3250 q = buf;
3251 while (ch != '\n' && ch != CH_EOF) {
3252 if ((q - buf) < sizeof(buf) - 1)
3253 *q++ = ch;
3254 if (ch == '\\') {
3255 if (handle_stray_noerror() == 0)
3256 --q;
3257 } else
3258 inp();
3260 *q = '\0';
3261 if (c == TOK_ERROR)
3262 error("#error %s", buf);
3263 else
3264 warning("#warning %s", buf);
3265 break;
3266 case TOK_PRAGMA:
3267 pragma_parse(s1);
3268 break;
3269 default:
3270 if (tok == TOK_LINEFEED || tok == '!' || tok == TOK_CINT) {
3271 /* '!' is ignored to allow C scripts. numbers are ignored
3272 to emulate cpp behaviour */
3273 } else {
3274 if (!(saved_parse_flags & PARSE_FLAG_ASM_COMMENTS))
3275 warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok, &tokc));
3277 break;
3279 /* ignore other preprocess commands or #! for C scripts */
3280 while (tok != TOK_LINEFEED)
3281 next_nomacro();
3282 the_end:
3283 parse_flags = saved_parse_flags;
3286 /* evaluate escape codes in a string. */
3287 static void parse_escape_string(CString *outstr, const uint8_t *buf, int is_long)
3289 int c, n;
3290 const uint8_t *p;
3292 p = buf;
3293 for(;;) {
3294 c = *p;
3295 if (c == '\0')
3296 break;
3297 if (c == '\\') {
3298 p++;
3299 /* escape */
3300 c = *p;
3301 switch(c) {
3302 case '0': case '1': case '2': case '3':
3303 case '4': case '5': case '6': case '7':
3304 /* at most three octal digits */
3305 n = c - '0';
3306 p++;
3307 c = *p;
3308 if (isoct(c)) {
3309 n = n * 8 + c - '0';
3310 p++;
3311 c = *p;
3312 if (isoct(c)) {
3313 n = n * 8 + c - '0';
3314 p++;
3317 c = n;
3318 goto add_char_nonext;
3319 case 'x':
3320 case 'u':
3321 case 'U':
3322 p++;
3323 n = 0;
3324 for(;;) {
3325 c = *p;
3326 if (c >= 'a' && c <= 'f')
3327 c = c - 'a' + 10;
3328 else if (c >= 'A' && c <= 'F')
3329 c = c - 'A' + 10;
3330 else if (isnum(c))
3331 c = c - '0';
3332 else
3333 break;
3334 n = n * 16 + c;
3335 p++;
3337 c = n;
3338 goto add_char_nonext;
3339 case 'a':
3340 c = '\a';
3341 break;
3342 case 'b':
3343 c = '\b';
3344 break;
3345 case 'f':
3346 c = '\f';
3347 break;
3348 case 'n':
3349 c = '\n';
3350 break;
3351 case 'r':
3352 c = '\r';
3353 break;
3354 case 't':
3355 c = '\t';
3356 break;
3357 case 'v':
3358 c = '\v';
3359 break;
3360 case 'e':
3361 if (!gnu_ext)
3362 goto invalid_escape;
3363 c = 27;
3364 break;
3365 case '\'':
3366 case '\"':
3367 case '\\':
3368 case '?':
3369 break;
3370 default:
3371 invalid_escape:
3372 if (c >= '!' && c <= '~')
3373 warning("unknown escape sequence: \'\\%c\'", c);
3374 else
3375 warning("unknown escape sequence: \'\\x%x\'", c);
3376 break;
3379 p++;
3380 add_char_nonext:
3381 if (!is_long)
3382 cstr_ccat(outstr, c);
3383 else
3384 cstr_wccat(outstr, c);
3386 /* add a trailing '\0' */
3387 if (!is_long)
3388 cstr_ccat(outstr, '\0');
3389 else
3390 cstr_wccat(outstr, '\0');
3393 /* we use 64 bit numbers */
3394 #define BN_SIZE 2
3396 /* bn = (bn << shift) | or_val */
3397 void bn_lshift(unsigned int *bn, int shift, int or_val)
3399 int i;
3400 unsigned int v;
3401 for(i=0;i<BN_SIZE;i++) {
3402 v = bn[i];
3403 bn[i] = (v << shift) | or_val;
3404 or_val = v >> (32 - shift);
3408 void bn_zero(unsigned int *bn)
3410 int i;
3411 for(i=0;i<BN_SIZE;i++) {
3412 bn[i] = 0;
3416 /* parse number in null terminated string 'p' and return it in the
3417 current token */
3418 void parse_number(const char *p)
3420 int b, t, shift, frac_bits, s, exp_val, ch;
3421 char *q;
3422 unsigned int bn[BN_SIZE];
3423 double d;
3425 /* number */
3426 q = token_buf;
3427 ch = *p++;
3428 t = ch;
3429 ch = *p++;
3430 *q++ = t;
3431 b = 10;
3432 if (t == '.') {
3433 goto float_frac_parse;
3434 } else if (t == '0') {
3435 if (ch == 'x' || ch == 'X') {
3436 q--;
3437 ch = *p++;
3438 b = 16;
3439 } else if (tcc_ext && (ch == 'b' || ch == 'B')) {
3440 q--;
3441 ch = *p++;
3442 b = 2;
3445 /* parse all digits. cannot check octal numbers at this stage
3446 because of floating point constants */
3447 while (1) {
3448 if (ch >= 'a' && ch <= 'f')
3449 t = ch - 'a' + 10;
3450 else if (ch >= 'A' && ch <= 'F')
3451 t = ch - 'A' + 10;
3452 else if (isnum(ch))
3453 t = ch - '0';
3454 else
3455 break;
3456 if (t >= b)
3457 break;
3458 if (q >= token_buf + STRING_MAX_SIZE) {
3459 num_too_long:
3460 error("number too long");
3462 *q++ = ch;
3463 ch = *p++;
3465 if (ch == '.' ||
3466 ((ch == 'e' || ch == 'E') && b == 10) ||
3467 ((ch == 'p' || ch == 'P') && (b == 16 || b == 2))) {
3468 if (b != 10) {
3469 /* NOTE: strtox should support that for hexa numbers, but
3470 non ISOC99 libcs do not support it, so we prefer to do
3471 it by hand */
3472 /* hexadecimal or binary floats */
3473 /* XXX: handle overflows */
3474 *q = '\0';
3475 if (b == 16)
3476 shift = 4;
3477 else
3478 shift = 2;
3479 bn_zero(bn);
3480 q = token_buf;
3481 while (1) {
3482 t = *q++;
3483 if (t == '\0') {
3484 break;
3485 } else if (t >= 'a') {
3486 t = t - 'a' + 10;
3487 } else if (t >= 'A') {
3488 t = t - 'A' + 10;
3489 } else {
3490 t = t - '0';
3492 bn_lshift(bn, shift, t);
3494 frac_bits = 0;
3495 if (ch == '.') {
3496 ch = *p++;
3497 while (1) {
3498 t = ch;
3499 if (t >= 'a' && t <= 'f') {
3500 t = t - 'a' + 10;
3501 } else if (t >= 'A' && t <= 'F') {
3502 t = t - 'A' + 10;
3503 } else if (t >= '0' && t <= '9') {
3504 t = t - '0';
3505 } else {
3506 break;
3508 if (t >= b)
3509 error("invalid digit");
3510 bn_lshift(bn, shift, t);
3511 frac_bits += shift;
3512 ch = *p++;
3515 if (ch != 'p' && ch != 'P')
3516 expect("exponent");
3517 ch = *p++;
3518 s = 1;
3519 exp_val = 0;
3520 if (ch == '+') {
3521 ch = *p++;
3522 } else if (ch == '-') {
3523 s = -1;
3524 ch = *p++;
3526 if (ch < '0' || ch > '9')
3527 expect("exponent digits");
3528 while (ch >= '0' && ch <= '9') {
3529 exp_val = exp_val * 10 + ch - '0';
3530 ch = *p++;
3532 exp_val = exp_val * s;
3534 /* now we can generate the number */
3535 /* XXX: should patch directly float number */
3536 d = (double)bn[1] * 4294967296.0 + (double)bn[0];
3537 d = ldexp(d, exp_val - frac_bits);
3538 t = toup(ch);
3539 if (t == 'F') {
3540 ch = *p++;
3541 tok = TOK_CFLOAT;
3542 /* float : should handle overflow */
3543 tokc.f = (float)d;
3544 } else if (t == 'L') {
3545 ch = *p++;
3546 tok = TOK_CLDOUBLE;
3547 /* XXX: not large enough */
3548 tokc.ld = (long double)d;
3549 } else {
3550 tok = TOK_CDOUBLE;
3551 tokc.d = d;
3553 } else {
3554 /* decimal floats */
3555 if (ch == '.') {
3556 if (q >= token_buf + STRING_MAX_SIZE)
3557 goto num_too_long;
3558 *q++ = ch;
3559 ch = *p++;
3560 float_frac_parse:
3561 while (ch >= '0' && ch <= '9') {
3562 if (q >= token_buf + STRING_MAX_SIZE)
3563 goto num_too_long;
3564 *q++ = ch;
3565 ch = *p++;
3568 if (ch == 'e' || ch == 'E') {
3569 if (q >= token_buf + STRING_MAX_SIZE)
3570 goto num_too_long;
3571 *q++ = ch;
3572 ch = *p++;
3573 if (ch == '-' || ch == '+') {
3574 if (q >= token_buf + STRING_MAX_SIZE)
3575 goto num_too_long;
3576 *q++ = ch;
3577 ch = *p++;
3579 if (ch < '0' || ch > '9')
3580 expect("exponent digits");
3581 while (ch >= '0' && ch <= '9') {
3582 if (q >= token_buf + STRING_MAX_SIZE)
3583 goto num_too_long;
3584 *q++ = ch;
3585 ch = *p++;
3588 *q = '\0';
3589 t = toup(ch);
3590 errno = 0;
3591 if (t == 'F') {
3592 ch = *p++;
3593 tok = TOK_CFLOAT;
3594 tokc.f = strtof(token_buf, NULL);
3595 } else if (t == 'L') {
3596 ch = *p++;
3597 tok = TOK_CLDOUBLE;
3598 tokc.ld = strtold(token_buf, NULL);
3599 } else {
3600 tok = TOK_CDOUBLE;
3601 tokc.d = strtod(token_buf, NULL);
3604 } else {
3605 unsigned long long n, n1;
3606 int lcount, ucount;
3608 /* integer number */
3609 *q = '\0';
3610 q = token_buf;
3611 if (b == 10 && *q == '0') {
3612 b = 8;
3613 q++;
3615 n = 0;
3616 while(1) {
3617 t = *q++;
3618 /* no need for checks except for base 10 / 8 errors */
3619 if (t == '\0') {
3620 break;
3621 } else if (t >= 'a') {
3622 t = t - 'a' + 10;
3623 } else if (t >= 'A') {
3624 t = t - 'A' + 10;
3625 } else {
3626 t = t - '0';
3627 if (t >= b)
3628 error("invalid digit");
3630 n1 = n;
3631 n = n * b + t;
3632 /* detect overflow */
3633 /* XXX: this test is not reliable */
3634 if (n < n1)
3635 error("integer constant overflow");
3638 /* XXX: not exactly ANSI compliant */
3639 if ((n & 0xffffffff00000000LL) != 0) {
3640 if ((n >> 63) != 0)
3641 tok = TOK_CULLONG;
3642 else
3643 tok = TOK_CLLONG;
3644 } else if (n > 0x7fffffff) {
3645 tok = TOK_CUINT;
3646 } else {
3647 tok = TOK_CINT;
3649 lcount = 0;
3650 ucount = 0;
3651 for(;;) {
3652 t = toup(ch);
3653 if (t == 'L') {
3654 if (lcount >= 2)
3655 error("three 'l's in integer constant");
3656 lcount++;
3657 if (lcount == 2) {
3658 if (tok == TOK_CINT)
3659 tok = TOK_CLLONG;
3660 else if (tok == TOK_CUINT)
3661 tok = TOK_CULLONG;
3663 ch = *p++;
3664 } else if (t == 'U') {
3665 if (ucount >= 1)
3666 error("two 'u's in integer constant");
3667 ucount++;
3668 if (tok == TOK_CINT)
3669 tok = TOK_CUINT;
3670 else if (tok == TOK_CLLONG)
3671 tok = TOK_CULLONG;
3672 ch = *p++;
3673 } else {
3674 break;
3677 if (tok == TOK_CINT || tok == TOK_CUINT)
3678 tokc.ui = n;
3679 else
3680 tokc.ull = n;
3682 if (ch)
3683 error("invalid number\n");
3687 #define PARSE2(c1, tok1, c2, tok2) \
3688 case c1: \
3689 PEEKC(c, p); \
3690 if (c == c2) { \
3691 p++; \
3692 tok = tok2; \
3693 } else { \
3694 tok = tok1; \
3696 break;
3698 /* return next token without macro substitution */
3699 static inline void next_nomacro1(void)
3701 int t, c, is_long;
3702 TokenSym *ts;
3703 uint8_t *p, *p1;
3704 unsigned int h;
3706 cstr_reset(&tok_spaces);
3707 p = file->buf_ptr;
3708 redo_no_start:
3709 c = *p;
3710 switch(c) {
3711 case ' ':
3712 case '\t':
3713 case '\f':
3714 case '\v':
3715 case '\r':
3716 cstr_ccat(&tok_spaces, c);
3717 p++;
3718 goto redo_no_start;
3720 case '\\':
3721 /* first look if it is in fact an end of buffer */
3722 if (p >= file->buf_end) {
3723 file->buf_ptr = p;
3724 handle_eob();
3725 p = file->buf_ptr;
3726 if (p >= file->buf_end)
3727 goto parse_eof;
3728 else
3729 goto redo_no_start;
3730 } else {
3731 file->buf_ptr = p;
3732 ch = *p;
3733 handle_stray();
3734 p = file->buf_ptr;
3735 goto redo_no_start;
3737 parse_eof:
3739 TCCState *s1 = tcc_state;
3740 if ((parse_flags & PARSE_FLAG_LINEFEED)
3741 && !(tok_flags & TOK_FLAG_EOF)) {
3742 tok_flags |= TOK_FLAG_EOF;
3743 tok = TOK_LINEFEED;
3744 goto keep_tok_flags;
3745 } else if (s1->include_stack_ptr == s1->include_stack ||
3746 !(parse_flags & PARSE_FLAG_PREPROCESS)) {
3747 /* no include left : end of file. */
3748 tok = TOK_EOF;
3749 } else {
3750 tok_flags &= ~TOK_FLAG_EOF;
3751 /* pop include file */
3753 /* test if previous '#endif' was after a #ifdef at
3754 start of file */
3755 if (tok_flags & TOK_FLAG_ENDIF) {
3756 #ifdef INC_DEBUG
3757 printf("#endif %s\n", get_tok_str(file->ifndef_macro_saved, NULL));
3758 #endif
3759 add_cached_include(s1, file->inc_type, file->inc_filename,
3760 file->ifndef_macro_saved);
3763 /* add end of include file debug info */
3764 if (do_debug) {
3765 put_stabd(N_EINCL, 0, 0);
3767 /* pop include stack */
3768 tcc_close(file);
3769 s1->include_stack_ptr--;
3770 file = *s1->include_stack_ptr;
3771 p = file->buf_ptr;
3772 goto redo_no_start;
3775 break;
3777 case '\n':
3778 file->line_num++;
3779 tok_flags |= TOK_FLAG_BOL;
3780 p++;
3781 if (0 == (parse_flags & PARSE_FLAG_LINEFEED))
3782 goto redo_no_start;
3783 tok = TOK_LINEFEED;
3784 goto keep_tok_flags;
3786 case '#':
3787 /* XXX: simplify */
3788 PEEKC(c, p);
3789 if ((tok_flags & TOK_FLAG_BOL) &&
3790 (parse_flags & PARSE_FLAG_PREPROCESS)) {
3791 file->buf_ptr = p;
3792 preprocess(tok_flags & TOK_FLAG_BOF);
3793 p = file->buf_ptr;
3794 goto redo_no_start;
3795 } else {
3796 if (c == '#') {
3797 p++;
3798 tok = TOK_TWOSHARPS;
3799 } else {
3800 if (parse_flags & PARSE_FLAG_ASM_COMMENTS) {
3801 p = parse_line_comment(p - 1);
3802 goto redo_no_start;
3803 } else {
3804 tok = '#';
3808 break;
3810 case 'a': case 'b': case 'c': case 'd':
3811 case 'e': case 'f': case 'g': case 'h':
3812 case 'i': case 'j': case 'k': case 'l':
3813 case 'm': case 'n': case 'o': case 'p':
3814 case 'q': case 'r': case 's': case 't':
3815 case 'u': case 'v': case 'w': case 'x':
3816 case 'y': case 'z':
3817 case 'A': case 'B': case 'C': case 'D':
3818 case 'E': case 'F': case 'G': case 'H':
3819 case 'I': case 'J': case 'K':
3820 case 'M': case 'N': case 'O': case 'P':
3821 case 'Q': case 'R': case 'S': case 'T':
3822 case 'U': case 'V': case 'W': case 'X':
3823 case 'Y': case 'Z':
3824 case '_':
3825 parse_ident_fast:
3826 p1 = p;
3827 h = TOK_HASH_INIT;
3828 h = TOK_HASH_FUNC(h, c);
3829 p++;
3830 for(;;) {
3831 c = *p;
3832 if (!isidnum_table[c-CH_EOF])
3833 break;
3834 h = TOK_HASH_FUNC(h, c);
3835 p++;
3837 if (c != '\\') {
3838 TokenSym **pts;
3839 int len;
3841 /* fast case : no stray found, so we have the full token
3842 and we have already hashed it */
3843 len = p - p1;
3844 h &= (TOK_HASH_SIZE - 1);
3845 pts = &hash_ident[h];
3846 for(;;) {
3847 ts = *pts;
3848 if (!ts)
3849 break;
3850 if (ts->len == len && !memcmp(ts->str, p1, len))
3851 goto token_found;
3852 pts = &(ts->hash_next);
3854 ts = tok_alloc_new(pts, p1, len);
3855 token_found: ;
3856 } else {
3857 /* slower case */
3858 cstr_reset(&tokcstr);
3860 while (p1 < p) {
3861 cstr_ccat(&tokcstr, *p1);
3862 p1++;
3864 p--;
3865 PEEKC(c, p);
3866 parse_ident_slow:
3867 while (isidnum_table[c-CH_EOF]) {
3868 cstr_ccat(&tokcstr, c);
3869 PEEKC(c, p);
3871 ts = tok_alloc(tokcstr.data, tokcstr.size);
3873 tok = ts->tok;
3874 break;
3875 case 'L':
3876 t = p[1];
3877 if (t != '\\' && t != '\'' && t != '\"') {
3878 /* fast case */
3879 goto parse_ident_fast;
3880 } else {
3881 PEEKC(c, p);
3882 if (c == '\'' || c == '\"') {
3883 is_long = 1;
3884 goto str_const;
3885 } else {
3886 cstr_reset(&tokcstr);
3887 cstr_ccat(&tokcstr, 'L');
3888 goto parse_ident_slow;
3891 break;
3892 case '0': case '1': case '2': case '3':
3893 case '4': case '5': case '6': case '7':
3894 case '8': case '9':
3896 cstr_reset(&tokcstr);
3897 /* after the first digit, accept digits, alpha, '.' or sign if
3898 prefixed by 'eEpP' */
3899 parse_num:
3900 for(;;) {
3901 t = c;
3902 cstr_ccat(&tokcstr, c);
3903 PEEKC(c, p);
3904 if (!(isnum(c) || isid(c) || c == '.' ||
3905 ((c == '+' || c == '-') &&
3906 (t == 'e' || t == 'E' || t == 'p' || t == 'P'))))
3907 break;
3909 /* We add a trailing '\0' to ease parsing */
3910 cstr_ccat(&tokcstr, '\0');
3911 tokc.cstr = &tokcstr;
3912 tok = TOK_PPNUM;
3913 break;
3914 case '.':
3915 /* special dot handling because it can also start a number */
3916 PEEKC(c, p);
3917 if (isnum(c)) {
3918 cstr_reset(&tokcstr);
3919 cstr_ccat(&tokcstr, '.');
3920 goto parse_num;
3921 } else if (c == '.') {
3922 PEEKC(c, p);
3923 if (c != '.')
3924 expect("'.'");
3925 PEEKC(c, p);
3926 tok = TOK_DOTS;
3927 } else {
3928 tok = '.';
3930 break;
3931 case '\'':
3932 case '\"':
3933 is_long = 0;
3934 str_const:
3936 CString str;
3937 int sep;
3939 sep = c;
3941 /* parse the string */
3942 cstr_new(&str);
3943 p = parse_pp_string(p, sep, &str);
3944 cstr_ccat(&str, '\0');
3946 /* eval the escape (should be done as TOK_PPNUM) */
3947 cstr_reset(&tokcstr);
3948 parse_escape_string(&tokcstr, str.data, is_long);
3949 cstr_free(&str);
3951 if (sep == '\'') {
3952 int char_size;
3953 /* XXX: make it portable */
3954 if (!is_long)
3955 char_size = 1;
3956 else
3957 char_size = sizeof(nwchar_t);
3958 if (tokcstr.size <= char_size)
3959 error("empty character constant");
3960 if (tokcstr.size > 2 * char_size)
3961 warning("multi-character character constant");
3962 if (!is_long) {
3963 tokc.i = *(int8_t *)tokcstr.data;
3964 tok = TOK_CCHAR;
3965 } else {
3966 tokc.i = *(nwchar_t *)tokcstr.data;
3967 tok = TOK_LCHAR;
3969 } else {
3970 tokc.cstr = &tokcstr;
3971 if (!is_long)
3972 tok = TOK_STR;
3973 else
3974 tok = TOK_LSTR;
3977 break;
3979 case '<':
3980 PEEKC(c, p);
3981 if (c == '=') {
3982 p++;
3983 tok = TOK_LE;
3984 } else if (c == '<') {
3985 PEEKC(c, p);
3986 if (c == '=') {
3987 p++;
3988 tok = TOK_A_SHL;
3989 } else {
3990 tok = TOK_SHL;
3992 } else {
3993 tok = TOK_LT;
3995 break;
3997 case '>':
3998 PEEKC(c, p);
3999 if (c == '=') {
4000 p++;
4001 tok = TOK_GE;
4002 } else if (c == '>') {
4003 PEEKC(c, p);
4004 if (c == '=') {
4005 p++;
4006 tok = TOK_A_SAR;
4007 } else {
4008 tok = TOK_SAR;
4010 } else {
4011 tok = TOK_GT;
4013 break;
4015 case '&':
4016 PEEKC(c, p);
4017 if (c == '&') {
4018 p++;
4019 tok = TOK_LAND;
4020 } else if (c == '=') {
4021 p++;
4022 tok = TOK_A_AND;
4023 } else {
4024 tok = '&';
4026 break;
4028 case '|':
4029 PEEKC(c, p);
4030 if (c == '|') {
4031 p++;
4032 tok = TOK_LOR;
4033 } else if (c == '=') {
4034 p++;
4035 tok = TOK_A_OR;
4036 } else {
4037 tok = '|';
4039 break;
4041 case '+':
4042 PEEKC(c, p);
4043 if (c == '+') {
4044 p++;
4045 tok = TOK_INC;
4046 } else if (c == '=') {
4047 p++;
4048 tok = TOK_A_ADD;
4049 } else {
4050 tok = '+';
4052 break;
4054 case '-':
4055 PEEKC(c, p);
4056 if (c == '-') {
4057 p++;
4058 tok = TOK_DEC;
4059 } else if (c == '=') {
4060 p++;
4061 tok = TOK_A_SUB;
4062 } else if (c == '>') {
4063 p++;
4064 tok = TOK_ARROW;
4065 } else {
4066 tok = '-';
4068 break;
4070 PARSE2('!', '!', '=', TOK_NE)
4071 PARSE2('=', '=', '=', TOK_EQ)
4072 PARSE2('*', '*', '=', TOK_A_MUL)
4073 PARSE2('%', '%', '=', TOK_A_MOD)
4074 PARSE2('^', '^', '=', TOK_A_XOR)
4076 /* comments or operator */
4077 case '/':
4078 PEEKC(c, p);
4079 if (c == '*') {
4080 p = parse_comment(p);
4081 goto redo_no_start;
4082 } else if (c == '/') {
4083 p = parse_line_comment(p);
4084 goto redo_no_start;
4085 } else if (c == '=') {
4086 p++;
4087 tok = TOK_A_DIV;
4088 } else {
4089 tok = '/';
4091 break;
4093 /* simple tokens */
4094 case '(':
4095 case ')':
4096 case '[':
4097 case ']':
4098 case '{':
4099 case '}':
4100 case ',':
4101 case ';':
4102 case ':':
4103 case '?':
4104 case '~':
4105 case '$': /* only used in assembler */
4106 case '@': /* dito */
4107 tok = c;
4108 p++;
4109 break;
4110 default:
4111 error("unrecognized character \\x%02x", c);
4112 break;
4114 tok_flags = 0;
4115 keep_tok_flags:
4116 file->buf_ptr = p;
4117 #if defined(PARSE_DEBUG)
4118 printf("token = %s\n", get_tok_str(tok, &tokc));
4119 #endif
4122 /* return next token without macro substitution. Can read input from
4123 macro_ptr buffer */
4124 static void next_nomacro(void)
4126 if (macro_ptr) {
4127 redo:
4128 tok = *macro_ptr;
4129 if (tok) {
4130 TOK_GET(tok, macro_ptr, tokc);
4131 if (tok == TOK_LINENUM) {
4132 file->line_num = tokc.i;
4133 goto redo;
4136 } else {
4137 next_nomacro1();
4141 /* substitute args in macro_str and return allocated string */
4142 static int *macro_arg_subst(Sym **nested_list, int *macro_str, Sym *args)
4144 int *st, last_tok, t, notfirst;
4145 Sym *s;
4146 CValue cval;
4147 TokenString str;
4148 CString cstr;
4150 tok_str_new(&str);
4151 last_tok = 0;
4152 while(1) {
4153 TOK_GET(t, macro_str, cval);
4154 if (!t)
4155 break;
4156 if (t == '#') {
4157 /* stringize */
4158 TOK_GET(t, macro_str, cval);
4159 if (!t)
4160 break;
4161 s = sym_find2(args, t);
4162 if (s) {
4163 cstr_new(&cstr);
4164 st = (int *)s->c;
4165 notfirst = 0;
4166 while (*st) {
4167 if (notfirst)
4168 cstr_ccat(&cstr, ' ');
4169 TOK_GET(t, st, cval);
4170 cstr_cat(&cstr, get_tok_str(t, &cval));
4171 #ifndef PP_NOSPACES
4172 notfirst = 1;
4173 #endif
4175 cstr_ccat(&cstr, '\0');
4176 #ifdef PP_DEBUG
4177 printf("stringize: %s\n", (char *)cstr.data);
4178 #endif
4179 /* add string */
4180 cval.cstr = &cstr;
4181 tok_str_add2(&str, TOK_STR, &cval);
4182 cstr_free(&cstr);
4183 } else {
4184 tok_str_add2(&str, t, &cval);
4186 } else if (t >= TOK_IDENT) {
4187 s = sym_find2(args, t);
4188 if (s) {
4189 st = (int *)s->c;
4190 /* if '##' is present before or after, no arg substitution */
4191 if (*macro_str == TOK_TWOSHARPS || last_tok == TOK_TWOSHARPS) {
4192 /* special case for var arg macros : ## eats the
4193 ',' if empty VA_ARGS variable. */
4194 /* XXX: test of the ',' is not 100%
4195 reliable. should fix it to avoid security
4196 problems */
4197 if (gnu_ext && s->type.t &&
4198 last_tok == TOK_TWOSHARPS &&
4199 str.len >= 2 && str.str[str.len - 2] == ',') {
4200 if (*st == 0) {
4201 /* suppress ',' '##' */
4202 str.len -= 2;
4203 } else {
4204 /* suppress '##' and add variable */
4205 str.len--;
4206 goto add_var;
4208 } else {
4209 int t1;
4210 add_var:
4211 for(;;) {
4212 TOK_GET(t1, st, cval);
4213 if (!t1)
4214 break;
4215 tok_str_add2(&str, t1, &cval);
4218 } else {
4219 /* NOTE: the stream cannot be read when macro
4220 substituing an argument */
4221 macro_subst(&str, nested_list, st, NULL);
4223 } else {
4224 tok_str_add(&str, t);
4226 } else {
4227 tok_str_add2(&str, t, &cval);
4229 last_tok = t;
4231 tok_str_add(&str, 0);
4232 return str.str;
4235 static char const ab_month_name[12][4] =
4237 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
4238 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
4241 /* do macro substitution of current token with macro 's' and add
4242 result to (tok_str,tok_len). 'nested_list' is the list of all
4243 macros we got inside to avoid recursing. Return non zero if no
4244 substitution needs to be done */
4245 static int macro_subst_tok(TokenString *tok_str,
4246 Sym **nested_list, Sym *s, struct macro_level **can_read_stream)
4248 Sym *args, *sa, *sa1;
4249 int mstr_allocated, parlevel, *mstr, t, t1;
4250 TokenString str;
4251 char *cstrval;
4252 CValue cval;
4253 CString cstr;
4254 char buf[32];
4256 /* if symbol is a macro, prepare substitution */
4257 /* special macros */
4258 if (tok == TOK___LINE__) {
4259 snprintf(buf, sizeof(buf), "%d", file->line_num);
4260 cstrval = buf;
4261 t1 = TOK_PPNUM;
4262 goto add_cstr1;
4263 } else if (tok == TOK___FILE__) {
4264 cstrval = file->filename;
4265 goto add_cstr;
4266 } else if (tok == TOK___DATE__ || tok == TOK___TIME__) {
4267 time_t ti;
4268 struct tm *tm;
4270 time(&ti);
4271 tm = localtime(&ti);
4272 if (tok == TOK___DATE__) {
4273 snprintf(buf, sizeof(buf), "%s %2d %d",
4274 ab_month_name[tm->tm_mon], tm->tm_mday, tm->tm_year + 1900);
4275 } else {
4276 snprintf(buf, sizeof(buf), "%02d:%02d:%02d",
4277 tm->tm_hour, tm->tm_min, tm->tm_sec);
4279 cstrval = buf;
4280 add_cstr:
4281 t1 = TOK_STR;
4282 add_cstr1:
4283 cstr_new(&cstr);
4284 cstr_cat(&cstr, cstrval);
4285 cstr_ccat(&cstr, '\0');
4286 cval.cstr = &cstr;
4287 tok_str_add2(tok_str, t1, &cval);
4288 cstr_free(&cstr);
4289 } else {
4290 mstr = (int *)s->c;
4291 mstr_allocated = 0;
4292 if (s->type.t == MACRO_FUNC) {
4293 /* NOTE: we do not use next_nomacro to avoid eating the
4294 next token. XXX: find better solution */
4295 redo:
4296 if (macro_ptr) {
4297 t = *macro_ptr;
4298 if (t == 0 && can_read_stream) {
4299 /* end of macro stream: we must look at the token
4300 after in the file */
4301 struct macro_level *ml = *can_read_stream;
4302 macro_ptr = NULL;
4303 if (ml)
4305 macro_ptr = ml->p;
4306 ml->p = NULL;
4307 *can_read_stream = ml -> prev;
4309 goto redo;
4311 } else {
4312 /* XXX: incorrect with comments */
4313 ch = file->buf_ptr[0];
4314 while (is_space(ch) || ch == '\n')
4315 cinp();
4316 t = ch;
4318 if (t != '(') /* no macro subst */
4319 return -1;
4321 /* argument macro */
4322 next_nomacro();
4323 next_nomacro();
4324 args = NULL;
4325 sa = s->next;
4326 /* NOTE: empty args are allowed, except if no args */
4327 for(;;) {
4328 /* handle '()' case */
4329 if (!args && !sa && tok == ')')
4330 break;
4331 if (!sa)
4332 error("macro '%s' used with too many args",
4333 get_tok_str(s->v, 0));
4334 tok_str_new(&str);
4335 parlevel = 0;
4336 /* NOTE: non zero sa->t indicates VA_ARGS */
4337 while ((parlevel > 0 ||
4338 (tok != ')' &&
4339 (tok != ',' || sa->type.t))) &&
4340 tok != -1) {
4341 if (tok == '(')
4342 parlevel++;
4343 else if (tok == ')')
4344 parlevel--;
4345 if (tok != TOK_LINEFEED)
4346 tok_str_add2(&str, tok, &tokc);
4347 next_nomacro();
4349 tok_str_add(&str, 0);
4350 sym_push2(&args, sa->v & ~SYM_FIELD, sa->type.t, (long)str.str);
4351 sa = sa->next;
4352 if (tok == ')') {
4353 /* special case for gcc var args: add an empty
4354 var arg argument if it is omitted */
4355 if (sa && sa->type.t && gnu_ext)
4356 continue;
4357 else
4358 break;
4360 if (tok != ',')
4361 expect(",");
4362 next_nomacro();
4364 if (sa) {
4365 error("macro '%s' used with too few args",
4366 get_tok_str(s->v, 0));
4369 /* now subst each arg */
4370 mstr = macro_arg_subst(nested_list, mstr, args);
4371 /* free memory */
4372 sa = args;
4373 while (sa) {
4374 sa1 = sa->prev;
4375 tok_str_free((int *)sa->c);
4376 sym_free(sa);
4377 sa = sa1;
4379 mstr_allocated = 1;
4381 sym_push2(nested_list, s->v, 0, 0);
4382 macro_subst(tok_str, nested_list, mstr, can_read_stream);
4383 /* pop nested defined symbol */
4384 sa1 = *nested_list;
4385 *nested_list = sa1->prev;
4386 sym_free(sa1);
4387 if (mstr_allocated)
4388 tok_str_free(mstr);
4390 return 0;
4393 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
4394 return the resulting string (which must be freed). */
4395 static inline int *macro_twosharps(const int *macro_str)
4397 TokenSym *ts;
4398 const int *macro_ptr1, *start_macro_ptr, *ptr, *saved_macro_ptr;
4399 int t;
4400 const char *p1, *p2;
4401 CValue cval;
4402 TokenString macro_str1;
4403 CString cstr;
4405 start_macro_ptr = macro_str;
4406 /* we search the first '##' */
4407 for(;;) {
4408 macro_ptr1 = macro_str;
4409 TOK_GET(t, macro_str, cval);
4410 /* nothing more to do if end of string */
4411 if (t == 0)
4412 return NULL;
4413 if (*macro_str == TOK_TWOSHARPS)
4414 break;
4417 /* we saw '##', so we need more processing to handle it */
4418 cstr_new(&cstr);
4419 tok_str_new(&macro_str1);
4420 tok = t;
4421 tokc = cval;
4423 /* add all tokens seen so far */
4424 for(ptr = start_macro_ptr; ptr < macro_ptr1;) {
4425 TOK_GET(t, ptr, cval);
4426 tok_str_add2(&macro_str1, t, &cval);
4428 saved_macro_ptr = macro_ptr;
4429 /* XXX: get rid of the use of macro_ptr here */
4430 macro_ptr = (int *)macro_str;
4431 for(;;) {
4432 while (*macro_ptr == TOK_TWOSHARPS) {
4433 macro_ptr++;
4434 macro_ptr1 = macro_ptr;
4435 t = *macro_ptr;
4436 if (t) {
4437 TOK_GET(t, macro_ptr, cval);
4438 /* We concatenate the two tokens if we have an
4439 identifier or a preprocessing number */
4440 cstr_reset(&cstr);
4441 p1 = get_tok_str(tok, &tokc);
4442 cstr_cat(&cstr, p1);
4443 p2 = get_tok_str(t, &cval);
4444 cstr_cat(&cstr, p2);
4445 cstr_ccat(&cstr, '\0');
4447 if ((tok >= TOK_IDENT || tok == TOK_PPNUM) &&
4448 (t >= TOK_IDENT || t == TOK_PPNUM)) {
4449 if (tok == TOK_PPNUM) {
4450 /* if number, then create a number token */
4451 /* NOTE: no need to allocate because
4452 tok_str_add2() does it */
4453 cstr_reset(&tokcstr);
4454 tokcstr = cstr;
4455 cstr_new(&cstr);
4456 tokc.cstr = &tokcstr;
4457 } else {
4458 /* if identifier, we must do a test to
4459 validate we have a correct identifier */
4460 if (t == TOK_PPNUM) {
4461 const char *p;
4462 int c;
4464 p = p2;
4465 for(;;) {
4466 c = *p;
4467 if (c == '\0')
4468 break;
4469 p++;
4470 if (!isnum(c) && !isid(c))
4471 goto error_pasting;
4474 ts = tok_alloc(cstr.data, strlen(cstr.data));
4475 tok = ts->tok; /* modify current token */
4477 } else {
4478 const char *str = cstr.data;
4479 const unsigned char *q;
4481 /* we look for a valid token */
4482 /* XXX: do more extensive checks */
4483 if (!strcmp(str, ">>=")) {
4484 tok = TOK_A_SAR;
4485 } else if (!strcmp(str, "<<=")) {
4486 tok = TOK_A_SHL;
4487 } else if (strlen(str) == 2) {
4488 /* search in two bytes table */
4489 q = tok_two_chars;
4490 for(;;) {
4491 if (!*q)
4492 goto error_pasting;
4493 if (q[0] == str[0] && q[1] == str[1])
4494 break;
4495 q += 3;
4497 tok = q[2];
4498 } else {
4499 error_pasting:
4500 /* NOTE: because get_tok_str use a static buffer,
4501 we must save it */
4502 cstr_reset(&cstr);
4503 p1 = get_tok_str(tok, &tokc);
4504 cstr_cat(&cstr, p1);
4505 cstr_ccat(&cstr, '\0');
4506 p2 = get_tok_str(t, &cval);
4507 warning("pasting \"%s\" and \"%s\" does not give a valid preprocessing token", cstr.data, p2);
4508 /* cannot merge tokens: just add them separately */
4509 tok_str_add2(&macro_str1, tok, &tokc);
4510 /* XXX: free associated memory ? */
4511 tok = t;
4512 tokc = cval;
4517 tok_str_add2(&macro_str1, tok, &tokc);
4518 next_nomacro();
4519 if (tok == 0)
4520 break;
4522 macro_ptr = (int *)saved_macro_ptr;
4523 cstr_free(&cstr);
4524 tok_str_add(&macro_str1, 0);
4525 return macro_str1.str;
4529 /* do macro substitution of macro_str and add result to
4530 (tok_str,tok_len). 'nested_list' is the list of all macros we got
4531 inside to avoid recursing. */
4532 static void macro_subst(TokenString *tok_str, Sym **nested_list,
4533 const int *macro_str, struct macro_level ** can_read_stream)
4535 Sym *s;
4536 int *macro_str1;
4537 const int *ptr;
4538 int t, ret;
4539 CValue cval;
4540 struct macro_level ml;
4542 /* first scan for '##' operator handling */
4543 ptr = macro_str;
4544 macro_str1 = macro_twosharps(ptr);
4545 if (macro_str1)
4546 ptr = macro_str1;
4547 while (1) {
4548 /* NOTE: ptr == NULL can only happen if tokens are read from
4549 file stream due to a macro function call */
4550 if (ptr == NULL)
4551 break;
4552 TOK_GET(t, ptr, cval);
4553 if (t == 0)
4554 break;
4555 s = define_find(t);
4556 if (s != NULL) {
4557 /* if nested substitution, do nothing */
4558 if (sym_find2(*nested_list, t))
4559 goto no_subst;
4560 ml.p = macro_ptr;
4561 if (can_read_stream)
4562 ml.prev = *can_read_stream, *can_read_stream = &ml;
4563 macro_ptr = (int *)ptr;
4564 tok = t;
4565 ret = macro_subst_tok(tok_str, nested_list, s, can_read_stream);
4566 ptr = (int *)macro_ptr;
4567 macro_ptr = ml.p;
4568 if (can_read_stream && *can_read_stream == &ml)
4569 *can_read_stream = ml.prev;
4570 if (ret != 0)
4571 goto no_subst;
4572 } else {
4573 no_subst:
4574 tok_str_add2(tok_str, t, &cval);
4577 if (macro_str1)
4578 tok_str_free(macro_str1);
4581 /* return next token with macro substitution */
4582 static void next(void)
4584 Sym *nested_list, *s;
4585 TokenString str;
4586 struct macro_level *ml;
4588 redo:
4589 next_nomacro();
4590 if (!macro_ptr) {
4591 /* if not reading from macro substituted string, then try
4592 to substitute macros */
4593 if (tok >= TOK_IDENT &&
4594 (parse_flags & PARSE_FLAG_PREPROCESS)) {
4595 s = define_find(tok);
4596 if (s) {
4597 /* we have a macro: we try to substitute */
4598 tok_str_new(&str);
4599 nested_list = NULL;
4600 ml = NULL;
4601 if (macro_subst_tok(&str, &nested_list, s, &ml) == 0) {
4602 /* substitution done, NOTE: maybe empty */
4603 tok_str_add(&str, 0);
4604 macro_ptr = str.str;
4605 macro_ptr_allocated = str.str;
4606 goto redo;
4610 } else {
4611 if (tok == 0) {
4612 /* end of macro or end of unget buffer */
4613 if (unget_buffer_enabled) {
4614 macro_ptr = unget_saved_macro_ptr;
4615 unget_buffer_enabled = 0;
4616 } else {
4617 /* end of macro string: free it */
4618 tok_str_free(macro_ptr_allocated);
4619 macro_ptr = NULL;
4621 goto redo;
4625 /* convert preprocessor tokens into C tokens */
4626 if (tok == TOK_PPNUM &&
4627 (parse_flags & PARSE_FLAG_TOK_NUM)) {
4628 parse_number((char *)tokc.cstr->data);
4632 /* push back current token and set current token to 'last_tok'. Only
4633 identifier case handled for labels. */
4634 static inline void unget_tok(int last_tok)
4636 int i, n;
4637 int *q;
4638 unget_saved_macro_ptr = macro_ptr;
4639 unget_buffer_enabled = 1;
4640 q = unget_saved_buffer;
4641 macro_ptr = q;
4642 *q++ = tok;
4643 n = tok_ext_size(tok) - 1;
4644 for(i=0;i<n;i++)
4645 *q++ = tokc.tab[i];
4646 *q = 0; /* end of token string */
4647 tok = last_tok;
4651 void swap(int *p, int *q)
4653 int t;
4654 t = *p;
4655 *p = *q;
4656 *q = t;
4659 void vsetc(CType *type, int r, CValue *vc)
4661 int v;
4663 if (vtop >= vstack + (VSTACK_SIZE - 1))
4664 error("memory full");
4665 /* cannot let cpu flags if other instruction are generated. Also
4666 avoid leaving VT_JMP anywhere except on the top of the stack
4667 because it would complicate the code generator. */
4668 if (vtop >= vstack) {
4669 v = vtop->r & VT_VALMASK;
4670 if (v == VT_CMP || (v & ~1) == VT_JMP)
4671 gv(RC_INT);
4673 vtop++;
4674 vtop->type = *type;
4675 vtop->r = r;
4676 vtop->r2 = VT_CONST;
4677 vtop->c = *vc;
4680 /* push integer constant */
4681 void vpushi(int v)
4683 CValue cval;
4684 cval.i = v;
4685 vsetc(&int_type, VT_CONST, &cval);
4688 /* push long long constant */
4689 void vpushll(long long v)
4691 CValue cval;
4692 CType ctype;
4693 ctype.t = VT_LLONG;
4694 cval.ull = v;
4695 vsetc(&ctype, VT_CONST, &cval);
4698 /* Return a static symbol pointing to a section */
4699 static Sym *get_sym_ref(CType *type, Section *sec,
4700 unsigned long offset, unsigned long size)
4702 int v;
4703 Sym *sym;
4705 v = anon_sym++;
4706 sym = global_identifier_push(v, type->t | VT_STATIC, 0);
4707 sym->type.ref = type->ref;
4708 sym->r = VT_CONST | VT_SYM;
4709 put_extern_sym(sym, sec, offset, size);
4710 return sym;
4713 /* push a reference to a section offset by adding a dummy symbol */
4714 static void vpush_ref(CType *type, Section *sec, unsigned long offset, unsigned long size)
4716 CValue cval;
4718 cval.ul = 0;
4719 vsetc(type, VT_CONST | VT_SYM, &cval);
4720 vtop->sym = get_sym_ref(type, sec, offset, size);
4723 /* define a new external reference to a symbol 'v' of type 'u' */
4724 static Sym *external_global_sym(int v, CType *type, int r)
4726 Sym *s;
4728 s = sym_find(v);
4729 if (!s) {
4730 /* push forward reference */
4731 s = global_identifier_push(v, type->t | VT_EXTERN, 0);
4732 s->type.ref = type->ref;
4733 s->r = r | VT_CONST | VT_SYM;
4735 return s;
4738 /* define a new external reference to a symbol 'v' of type 'u' */
4739 static Sym *external_sym(int v, CType *type, int r)
4741 Sym *s;
4743 s = sym_find(v);
4744 if (!s) {
4745 /* push forward reference */
4746 s = sym_push(v, type, r | VT_CONST | VT_SYM, 0);
4747 s->type.t |= VT_EXTERN;
4748 } else {
4749 if (!is_compatible_types(&s->type, type))
4750 error("incompatible types for redefinition of '%s'",
4751 get_tok_str(v, NULL));
4753 return s;
4756 /* push a reference to global symbol v */
4757 static void vpush_global_sym(CType *type, int v)
4759 Sym *sym;
4760 CValue cval;
4762 sym = external_global_sym(v, type, 0);
4763 cval.ul = 0;
4764 vsetc(type, VT_CONST | VT_SYM, &cval);
4765 vtop->sym = sym;
4768 void vset(CType *type, int r, int v)
4770 CValue cval;
4772 cval.i = v;
4773 vsetc(type, r, &cval);
4776 void vseti(int r, int v)
4778 CType type;
4779 type.t = VT_INT;
4780 vset(&type, r, v);
4783 void vswap(void)
4785 SValue tmp;
4787 tmp = vtop[0];
4788 vtop[0] = vtop[-1];
4789 vtop[-1] = tmp;
4792 void vpushv(SValue *v)
4794 if (vtop >= vstack + (VSTACK_SIZE - 1))
4795 error("memory full");
4796 vtop++;
4797 *vtop = *v;
4800 void vdup(void)
4802 vpushv(vtop);
4805 /* save r to the memory stack, and mark it as being free */
4806 void save_reg(int r)
4808 int l, saved, size, align;
4809 SValue *p, sv;
4810 CType *type;
4812 /* modify all stack values */
4813 saved = 0;
4814 l = 0;
4815 for(p=vstack;p<=vtop;p++) {
4816 if ((p->r & VT_VALMASK) == r ||
4817 ((p->type.t & VT_BTYPE) == VT_LLONG && (p->r2 & VT_VALMASK) == r)) {
4818 /* must save value on stack if not already done */
4819 if (!saved) {
4820 /* NOTE: must reload 'r' because r might be equal to r2 */
4821 r = p->r & VT_VALMASK;
4822 /* store register in the stack */
4823 type = &p->type;
4824 if ((p->r & VT_LVAL) ||
4825 (!is_float(type->t) && (type->t & VT_BTYPE) != VT_LLONG))
4826 #ifdef TCC_TARGET_X86_64
4827 type = &char_pointer_type;
4828 #else
4829 type = &int_type;
4830 #endif
4831 size = type_size(type, &align);
4832 loc = (loc - size) & -align;
4833 sv.type.t = type->t;
4834 sv.r = VT_LOCAL | VT_LVAL;
4835 sv.c.ul = loc;
4836 store(r, &sv);
4837 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
4838 /* x86 specific: need to pop fp register ST0 if saved */
4839 if (r == TREG_ST0) {
4840 o(0xd9dd); /* fstp %st(1) */
4842 #endif
4843 #ifndef TCC_TARGET_X86_64
4844 /* special long long case */
4845 if ((type->t & VT_BTYPE) == VT_LLONG) {
4846 sv.c.ul += 4;
4847 store(p->r2, &sv);
4849 #endif
4850 l = loc;
4851 saved = 1;
4853 /* mark that stack entry as being saved on the stack */
4854 if (p->r & VT_LVAL) {
4855 /* also clear the bounded flag because the
4856 relocation address of the function was stored in
4857 p->c.ul */
4858 p->r = (p->r & ~(VT_VALMASK | VT_BOUNDED)) | VT_LLOCAL;
4859 } else {
4860 p->r = lvalue_type(p->type.t) | VT_LOCAL;
4862 p->r2 = VT_CONST;
4863 p->c.ul = l;
4868 /* find a register of class 'rc2' with at most one reference on stack.
4869 * If none, call get_reg(rc) */
4870 int get_reg_ex(int rc, int rc2)
4872 int r;
4873 SValue *p;
4875 for(r=0;r<NB_REGS;r++) {
4876 if (reg_classes[r] & rc2) {
4877 int n;
4878 n=0;
4879 for(p = vstack; p <= vtop; p++) {
4880 if ((p->r & VT_VALMASK) == r ||
4881 (p->r2 & VT_VALMASK) == r)
4882 n++;
4884 if (n <= 1)
4885 return r;
4888 return get_reg(rc);
4891 /* find a free register of class 'rc'. If none, save one register */
4892 int get_reg(int rc)
4894 int r;
4895 SValue *p;
4897 /* find a free register */
4898 for(r=0;r<NB_REGS;r++) {
4899 if (reg_classes[r] & rc) {
4900 for(p=vstack;p<=vtop;p++) {
4901 if ((p->r & VT_VALMASK) == r ||
4902 (p->r2 & VT_VALMASK) == r)
4903 goto notfound;
4905 return r;
4907 notfound: ;
4910 /* no register left : free the first one on the stack (VERY
4911 IMPORTANT to start from the bottom to ensure that we don't
4912 spill registers used in gen_opi()) */
4913 for(p=vstack;p<=vtop;p++) {
4914 r = p->r & VT_VALMASK;
4915 if (r < VT_CONST && (reg_classes[r] & rc))
4916 goto save_found;
4917 /* also look at second register (if long long) */
4918 r = p->r2 & VT_VALMASK;
4919 if (r < VT_CONST && (reg_classes[r] & rc)) {
4920 save_found:
4921 save_reg(r);
4922 return r;
4925 /* Should never comes here */
4926 return -1;
4929 /* save registers up to (vtop - n) stack entry */
4930 void save_regs(int n)
4932 int r;
4933 SValue *p, *p1;
4934 p1 = vtop - n;
4935 for(p = vstack;p <= p1; p++) {
4936 r = p->r & VT_VALMASK;
4937 if (r < VT_CONST) {
4938 save_reg(r);
4943 /* move register 's' to 'r', and flush previous value of r to memory
4944 if needed */
4945 void move_reg(int r, int s)
4947 SValue sv;
4949 if (r != s) {
4950 save_reg(r);
4951 sv.type.t = VT_INT;
4952 sv.r = s;
4953 sv.c.ul = 0;
4954 load(r, &sv);
4958 /* get address of vtop (vtop MUST BE an lvalue) */
4959 void gaddrof(void)
4961 vtop->r &= ~VT_LVAL;
4962 /* tricky: if saved lvalue, then we can go back to lvalue */
4963 if ((vtop->r & VT_VALMASK) == VT_LLOCAL)
4964 vtop->r = (vtop->r & ~(VT_VALMASK | VT_LVAL_TYPE)) | VT_LOCAL | VT_LVAL;
4967 #ifdef CONFIG_TCC_BCHECK
4968 /* generate lvalue bound code */
4969 void gbound(void)
4971 int lval_type;
4972 CType type1;
4974 vtop->r &= ~VT_MUSTBOUND;
4975 /* if lvalue, then use checking code before dereferencing */
4976 if (vtop->r & VT_LVAL) {
4977 /* if not VT_BOUNDED value, then make one */
4978 if (!(vtop->r & VT_BOUNDED)) {
4979 lval_type = vtop->r & (VT_LVAL_TYPE | VT_LVAL);
4980 /* must save type because we must set it to int to get pointer */
4981 type1 = vtop->type;
4982 vtop->type.t = VT_INT;
4983 gaddrof();
4984 vpushi(0);
4985 gen_bounded_ptr_add();
4986 vtop->r |= lval_type;
4987 vtop->type = type1;
4989 /* then check for dereferencing */
4990 gen_bounded_ptr_deref();
4993 #endif
4995 /* store vtop a register belonging to class 'rc'. lvalues are
4996 converted to values. Cannot be used if cannot be converted to
4997 register value (such as structures). */
4998 int gv(int rc)
5000 int r, rc2, bit_pos, bit_size, size, align, i;
5002 /* NOTE: get_reg can modify vstack[] */
5003 if (vtop->type.t & VT_BITFIELD) {
5004 CType type;
5005 int bits = 32;
5006 bit_pos = (vtop->type.t >> VT_STRUCT_SHIFT) & 0x3f;
5007 bit_size = (vtop->type.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
5008 /* remove bit field info to avoid loops */
5009 vtop->type.t &= ~(VT_BITFIELD | (-1 << VT_STRUCT_SHIFT));
5010 /* cast to int to propagate signedness in following ops */
5011 if ((vtop->type.t & VT_BTYPE) == VT_LLONG) {
5012 type.t = VT_LLONG;
5013 bits = 64;
5014 } else
5015 type.t = VT_INT;
5016 if((vtop->type.t & VT_UNSIGNED) ||
5017 (vtop->type.t & VT_BTYPE) == VT_BOOL)
5018 type.t |= VT_UNSIGNED;
5019 gen_cast(&type);
5020 /* generate shifts */
5021 vpushi(bits - (bit_pos + bit_size));
5022 gen_op(TOK_SHL);
5023 vpushi(bits - bit_size);
5024 /* NOTE: transformed to SHR if unsigned */
5025 gen_op(TOK_SAR);
5026 r = gv(rc);
5027 } else {
5028 if (is_float(vtop->type.t) &&
5029 (vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
5030 Sym *sym;
5031 int *ptr;
5032 unsigned long offset;
5033 #if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
5034 CValue check;
5035 #endif
5037 /* XXX: unify with initializers handling ? */
5038 /* CPUs usually cannot use float constants, so we store them
5039 generically in data segment */
5040 size = type_size(&vtop->type, &align);
5041 offset = (data_section->data_offset + align - 1) & -align;
5042 data_section->data_offset = offset;
5043 /* XXX: not portable yet */
5044 #if defined(__i386__) || defined(__x86_64__)
5045 /* Zero pad x87 tenbyte long doubles */
5046 if (size == LDOUBLE_SIZE)
5047 vtop->c.tab[2] &= 0xffff;
5048 #endif
5049 ptr = section_ptr_add(data_section, size);
5050 size = size >> 2;
5051 #if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
5052 check.d = 1;
5053 if(check.tab[0])
5054 for(i=0;i<size;i++)
5055 ptr[i] = vtop->c.tab[size-1-i];
5056 else
5057 #endif
5058 for(i=0;i<size;i++)
5059 ptr[i] = vtop->c.tab[i];
5060 sym = get_sym_ref(&vtop->type, data_section, offset, size << 2);
5061 vtop->r |= VT_LVAL | VT_SYM;
5062 vtop->sym = sym;
5063 vtop->c.ul = 0;
5065 #ifdef CONFIG_TCC_BCHECK
5066 if (vtop->r & VT_MUSTBOUND)
5067 gbound();
5068 #endif
5070 r = vtop->r & VT_VALMASK;
5071 rc2 = RC_INT;
5072 if (rc == RC_IRET)
5073 rc2 = RC_LRET;
5074 /* need to reload if:
5075 - constant
5076 - lvalue (need to dereference pointer)
5077 - already a register, but not in the right class */
5078 if (r >= VT_CONST ||
5079 (vtop->r & VT_LVAL) ||
5080 !(reg_classes[r] & rc) ||
5081 ((vtop->type.t & VT_BTYPE) == VT_LLONG &&
5082 !(reg_classes[vtop->r2] & rc2))) {
5083 r = get_reg(rc);
5084 #ifndef TCC_TARGET_X86_64
5085 if ((vtop->type.t & VT_BTYPE) == VT_LLONG) {
5086 int r2;
5087 unsigned long long ll;
5088 /* two register type load : expand to two words
5089 temporarily */
5090 if ((vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
5091 /* load constant */
5092 ll = vtop->c.ull;
5093 vtop->c.ui = ll; /* first word */
5094 load(r, vtop);
5095 vtop->r = r; /* save register value */
5096 vpushi(ll >> 32); /* second word */
5097 } else if (r >= VT_CONST || /* XXX: test to VT_CONST incorrect ? */
5098 (vtop->r & VT_LVAL)) {
5099 /* We do not want to modifier the long long
5100 pointer here, so the safest (and less
5101 efficient) is to save all the other registers
5102 in the stack. XXX: totally inefficient. */
5103 save_regs(1);
5104 /* load from memory */
5105 load(r, vtop);
5106 vdup();
5107 vtop[-1].r = r; /* save register value */
5108 /* increment pointer to get second word */
5109 vtop->type.t = VT_INT;
5110 gaddrof();
5111 vpushi(4);
5112 gen_op('+');
5113 vtop->r |= VT_LVAL;
5114 } else {
5115 /* move registers */
5116 load(r, vtop);
5117 vdup();
5118 vtop[-1].r = r; /* save register value */
5119 vtop->r = vtop[-1].r2;
5121 /* allocate second register */
5122 r2 = get_reg(rc2);
5123 load(r2, vtop);
5124 vpop();
5125 /* write second register */
5126 vtop->r2 = r2;
5127 } else
5128 #endif
5129 if ((vtop->r & VT_LVAL) && !is_float(vtop->type.t)) {
5130 int t1, t;
5131 /* lvalue of scalar type : need to use lvalue type
5132 because of possible cast */
5133 t = vtop->type.t;
5134 t1 = t;
5135 /* compute memory access type */
5136 if (vtop->r & VT_LVAL_BYTE)
5137 t = VT_BYTE;
5138 else if (vtop->r & VT_LVAL_SHORT)
5139 t = VT_SHORT;
5140 if (vtop->r & VT_LVAL_UNSIGNED)
5141 t |= VT_UNSIGNED;
5142 vtop->type.t = t;
5143 load(r, vtop);
5144 /* restore wanted type */
5145 vtop->type.t = t1;
5146 } else {
5147 /* one register type load */
5148 load(r, vtop);
5151 vtop->r = r;
5152 #ifdef TCC_TARGET_C67
5153 /* uses register pairs for doubles */
5154 if ((vtop->type.t & VT_BTYPE) == VT_DOUBLE)
5155 vtop->r2 = r+1;
5156 #endif
5158 return r;
5161 /* generate vtop[-1] and vtop[0] in resp. classes rc1 and rc2 */
5162 void gv2(int rc1, int rc2)
5164 int v;
5166 /* generate more generic register first. But VT_JMP or VT_CMP
5167 values must be generated first in all cases to avoid possible
5168 reload errors */
5169 v = vtop[0].r & VT_VALMASK;
5170 if (v != VT_CMP && (v & ~1) != VT_JMP && rc1 <= rc2) {
5171 vswap();
5172 gv(rc1);
5173 vswap();
5174 gv(rc2);
5175 /* test if reload is needed for first register */
5176 if ((vtop[-1].r & VT_VALMASK) >= VT_CONST) {
5177 vswap();
5178 gv(rc1);
5179 vswap();
5181 } else {
5182 gv(rc2);
5183 vswap();
5184 gv(rc1);
5185 vswap();
5186 /* test if reload is needed for first register */
5187 if ((vtop[0].r & VT_VALMASK) >= VT_CONST) {
5188 gv(rc2);
5193 /* wrapper around RC_FRET to return a register by type */
5194 int rc_fret(int t)
5196 #ifdef TCC_TARGET_X86_64
5197 if (t == VT_LDOUBLE) {
5198 return RC_ST0;
5200 #endif
5201 return RC_FRET;
5204 /* wrapper around REG_FRET to return a register by type */
5205 int reg_fret(int t)
5207 #ifdef TCC_TARGET_X86_64
5208 if (t == VT_LDOUBLE) {
5209 return TREG_ST0;
5211 #endif
5212 return REG_FRET;
5215 /* expand long long on stack in two int registers */
5216 void lexpand(void)
5218 int u;
5220 u = vtop->type.t & VT_UNSIGNED;
5221 gv(RC_INT);
5222 vdup();
5223 vtop[0].r = vtop[-1].r2;
5224 vtop[0].r2 = VT_CONST;
5225 vtop[-1].r2 = VT_CONST;
5226 vtop[0].type.t = VT_INT | u;
5227 vtop[-1].type.t = VT_INT | u;
5230 #ifdef TCC_TARGET_ARM
5231 /* expand long long on stack */
5232 void lexpand_nr(void)
5234 int u,v;
5236 u = vtop->type.t & VT_UNSIGNED;
5237 vdup();
5238 vtop->r2 = VT_CONST;
5239 vtop->type.t = VT_INT | u;
5240 v=vtop[-1].r & (VT_VALMASK | VT_LVAL);
5241 if (v == VT_CONST) {
5242 vtop[-1].c.ui = vtop->c.ull;
5243 vtop->c.ui = vtop->c.ull >> 32;
5244 vtop->r = VT_CONST;
5245 } else if (v == (VT_LVAL|VT_CONST) || v == (VT_LVAL|VT_LOCAL)) {
5246 vtop->c.ui += 4;
5247 vtop->r = vtop[-1].r;
5248 } else if (v > VT_CONST) {
5249 vtop--;
5250 lexpand();
5251 } else
5252 vtop->r = vtop[-1].r2;
5253 vtop[-1].r2 = VT_CONST;
5254 vtop[-1].type.t = VT_INT | u;
5256 #endif
5258 /* build a long long from two ints */
5259 void lbuild(int t)
5261 gv2(RC_INT, RC_INT);
5262 vtop[-1].r2 = vtop[0].r;
5263 vtop[-1].type.t = t;
5264 vpop();
5267 /* rotate n first stack elements to the bottom
5268 I1 ... In -> I2 ... In I1 [top is right]
5270 void vrotb(int n)
5272 int i;
5273 SValue tmp;
5275 tmp = vtop[-n + 1];
5276 for(i=-n+1;i!=0;i++)
5277 vtop[i] = vtop[i+1];
5278 vtop[0] = tmp;
5281 /* rotate n first stack elements to the top
5282 I1 ... In -> In I1 ... I(n-1) [top is right]
5284 void vrott(int n)
5286 int i;
5287 SValue tmp;
5289 tmp = vtop[0];
5290 for(i = 0;i < n - 1; i++)
5291 vtop[-i] = vtop[-i - 1];
5292 vtop[-n + 1] = tmp;
5295 #ifdef TCC_TARGET_ARM
5296 /* like vrott but in other direction
5297 In ... I1 -> I(n-1) ... I1 In [top is right]
5299 void vnrott(int n)
5301 int i;
5302 SValue tmp;
5304 tmp = vtop[-n + 1];
5305 for(i = n - 1; i > 0; i--)
5306 vtop[-i] = vtop[-i + 1];
5307 vtop[0] = tmp;
5309 #endif
5311 /* pop stack value */
5312 void vpop(void)
5314 int v;
5315 v = vtop->r & VT_VALMASK;
5316 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
5317 /* for x86, we need to pop the FP stack */
5318 if (v == TREG_ST0 && !nocode_wanted) {
5319 o(0xd9dd); /* fstp %st(1) */
5320 } else
5321 #endif
5322 if (v == VT_JMP || v == VT_JMPI) {
5323 /* need to put correct jump if && or || without test */
5324 gsym(vtop->c.ul);
5326 vtop--;
5329 /* convert stack entry to register and duplicate its value in another
5330 register */
5331 void gv_dup(void)
5333 int rc, t, r, r1;
5334 SValue sv;
5336 t = vtop->type.t;
5337 if ((t & VT_BTYPE) == VT_LLONG) {
5338 lexpand();
5339 gv_dup();
5340 vswap();
5341 vrotb(3);
5342 gv_dup();
5343 vrotb(4);
5344 /* stack: H L L1 H1 */
5345 lbuild(t);
5346 vrotb(3);
5347 vrotb(3);
5348 vswap();
5349 lbuild(t);
5350 vswap();
5351 } else {
5352 /* duplicate value */
5353 rc = RC_INT;
5354 sv.type.t = VT_INT;
5355 if (is_float(t)) {
5356 rc = RC_FLOAT;
5357 #ifdef TCC_TARGET_X86_64
5358 if ((t & VT_BTYPE) == VT_LDOUBLE) {
5359 rc = RC_ST0;
5361 #endif
5362 sv.type.t = t;
5364 r = gv(rc);
5365 r1 = get_reg(rc);
5366 sv.r = r;
5367 sv.c.ul = 0;
5368 load(r1, &sv); /* move r to r1 */
5369 vdup();
5370 /* duplicates value */
5371 vtop->r = r1;
5375 #ifndef TCC_TARGET_X86_64
5376 /* generate CPU independent (unsigned) long long operations */
5377 void gen_opl(int op)
5379 int t, a, b, op1, c, i;
5380 int func;
5381 unsigned short reg_iret = REG_IRET;
5382 unsigned short reg_lret = REG_LRET;
5383 SValue tmp;
5385 switch(op) {
5386 case '/':
5387 case TOK_PDIV:
5388 func = TOK___divdi3;
5389 goto gen_func;
5390 case TOK_UDIV:
5391 func = TOK___udivdi3;
5392 goto gen_func;
5393 case '%':
5394 func = TOK___moddi3;
5395 goto gen_mod_func;
5396 case TOK_UMOD:
5397 func = TOK___umoddi3;
5398 gen_mod_func:
5399 #ifdef TCC_ARM_EABI
5400 reg_iret = TREG_R2;
5401 reg_lret = TREG_R3;
5402 #endif
5403 gen_func:
5404 /* call generic long long function */
5405 vpush_global_sym(&func_old_type, func);
5406 vrott(3);
5407 gfunc_call(2);
5408 vpushi(0);
5409 vtop->r = reg_iret;
5410 vtop->r2 = reg_lret;
5411 break;
5412 case '^':
5413 case '&':
5414 case '|':
5415 case '*':
5416 case '+':
5417 case '-':
5418 t = vtop->type.t;
5419 vswap();
5420 lexpand();
5421 vrotb(3);
5422 lexpand();
5423 /* stack: L1 H1 L2 H2 */
5424 tmp = vtop[0];
5425 vtop[0] = vtop[-3];
5426 vtop[-3] = tmp;
5427 tmp = vtop[-2];
5428 vtop[-2] = vtop[-3];
5429 vtop[-3] = tmp;
5430 vswap();
5431 /* stack: H1 H2 L1 L2 */
5432 if (op == '*') {
5433 vpushv(vtop - 1);
5434 vpushv(vtop - 1);
5435 gen_op(TOK_UMULL);
5436 lexpand();
5437 /* stack: H1 H2 L1 L2 ML MH */
5438 for(i=0;i<4;i++)
5439 vrotb(6);
5440 /* stack: ML MH H1 H2 L1 L2 */
5441 tmp = vtop[0];
5442 vtop[0] = vtop[-2];
5443 vtop[-2] = tmp;
5444 /* stack: ML MH H1 L2 H2 L1 */
5445 gen_op('*');
5446 vrotb(3);
5447 vrotb(3);
5448 gen_op('*');
5449 /* stack: ML MH M1 M2 */
5450 gen_op('+');
5451 gen_op('+');
5452 } else if (op == '+' || op == '-') {
5453 /* XXX: add non carry method too (for MIPS or alpha) */
5454 if (op == '+')
5455 op1 = TOK_ADDC1;
5456 else
5457 op1 = TOK_SUBC1;
5458 gen_op(op1);
5459 /* stack: H1 H2 (L1 op L2) */
5460 vrotb(3);
5461 vrotb(3);
5462 gen_op(op1 + 1); /* TOK_xxxC2 */
5463 } else {
5464 gen_op(op);
5465 /* stack: H1 H2 (L1 op L2) */
5466 vrotb(3);
5467 vrotb(3);
5468 /* stack: (L1 op L2) H1 H2 */
5469 gen_op(op);
5470 /* stack: (L1 op L2) (H1 op H2) */
5472 /* stack: L H */
5473 lbuild(t);
5474 break;
5475 case TOK_SAR:
5476 case TOK_SHR:
5477 case TOK_SHL:
5478 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
5479 t = vtop[-1].type.t;
5480 vswap();
5481 lexpand();
5482 vrotb(3);
5483 /* stack: L H shift */
5484 c = (int)vtop->c.i;
5485 /* constant: simpler */
5486 /* NOTE: all comments are for SHL. the other cases are
5487 done by swaping words */
5488 vpop();
5489 if (op != TOK_SHL)
5490 vswap();
5491 if (c >= 32) {
5492 /* stack: L H */
5493 vpop();
5494 if (c > 32) {
5495 vpushi(c - 32);
5496 gen_op(op);
5498 if (op != TOK_SAR) {
5499 vpushi(0);
5500 } else {
5501 gv_dup();
5502 vpushi(31);
5503 gen_op(TOK_SAR);
5505 vswap();
5506 } else {
5507 vswap();
5508 gv_dup();
5509 /* stack: H L L */
5510 vpushi(c);
5511 gen_op(op);
5512 vswap();
5513 vpushi(32 - c);
5514 if (op == TOK_SHL)
5515 gen_op(TOK_SHR);
5516 else
5517 gen_op(TOK_SHL);
5518 vrotb(3);
5519 /* stack: L L H */
5520 vpushi(c);
5521 if (op == TOK_SHL)
5522 gen_op(TOK_SHL);
5523 else
5524 gen_op(TOK_SHR);
5525 gen_op('|');
5527 if (op != TOK_SHL)
5528 vswap();
5529 lbuild(t);
5530 } else {
5531 /* XXX: should provide a faster fallback on x86 ? */
5532 switch(op) {
5533 case TOK_SAR:
5534 func = TOK___ashrdi3;
5535 goto gen_func;
5536 case TOK_SHR:
5537 func = TOK___lshrdi3;
5538 goto gen_func;
5539 case TOK_SHL:
5540 func = TOK___ashldi3;
5541 goto gen_func;
5544 break;
5545 default:
5546 /* compare operations */
5547 t = vtop->type.t;
5548 vswap();
5549 lexpand();
5550 vrotb(3);
5551 lexpand();
5552 /* stack: L1 H1 L2 H2 */
5553 tmp = vtop[-1];
5554 vtop[-1] = vtop[-2];
5555 vtop[-2] = tmp;
5556 /* stack: L1 L2 H1 H2 */
5557 /* compare high */
5558 op1 = op;
5559 /* when values are equal, we need to compare low words. since
5560 the jump is inverted, we invert the test too. */
5561 if (op1 == TOK_LT)
5562 op1 = TOK_LE;
5563 else if (op1 == TOK_GT)
5564 op1 = TOK_GE;
5565 else if (op1 == TOK_ULT)
5566 op1 = TOK_ULE;
5567 else if (op1 == TOK_UGT)
5568 op1 = TOK_UGE;
5569 a = 0;
5570 b = 0;
5571 gen_op(op1);
5572 if (op1 != TOK_NE) {
5573 a = gtst(1, 0);
5575 if (op != TOK_EQ) {
5576 /* generate non equal test */
5577 /* XXX: NOT PORTABLE yet */
5578 if (a == 0) {
5579 b = gtst(0, 0);
5580 } else {
5581 #if defined(TCC_TARGET_I386)
5582 b = psym(0x850f, 0);
5583 #elif defined(TCC_TARGET_ARM)
5584 b = ind;
5585 o(0x1A000000 | encbranch(ind, 0, 1));
5586 #elif defined(TCC_TARGET_C67)
5587 error("not implemented");
5588 #else
5589 #error not supported
5590 #endif
5593 /* compare low. Always unsigned */
5594 op1 = op;
5595 if (op1 == TOK_LT)
5596 op1 = TOK_ULT;
5597 else if (op1 == TOK_LE)
5598 op1 = TOK_ULE;
5599 else if (op1 == TOK_GT)
5600 op1 = TOK_UGT;
5601 else if (op1 == TOK_GE)
5602 op1 = TOK_UGE;
5603 gen_op(op1);
5604 a = gtst(1, a);
5605 gsym(b);
5606 vseti(VT_JMPI, a);
5607 break;
5610 #endif
5612 /* handle integer constant optimizations and various machine
5613 independent opt */
5614 void gen_opic(int op)
5616 int c1, c2, t1, t2, n;
5617 SValue *v1, *v2;
5618 long long l1, l2;
5619 typedef unsigned long long U;
5621 v1 = vtop - 1;
5622 v2 = vtop;
5623 t1 = v1->type.t & VT_BTYPE;
5624 t2 = v2->type.t & VT_BTYPE;
5626 if (t1 == VT_LLONG)
5627 l1 = v1->c.ll;
5628 else if (v1->type.t & VT_UNSIGNED)
5629 l1 = v1->c.ui;
5630 else
5631 l1 = v1->c.i;
5633 if (t2 == VT_LLONG)
5634 l2 = v2->c.ll;
5635 else if (v2->type.t & VT_UNSIGNED)
5636 l2 = v2->c.ui;
5637 else
5638 l2 = v2->c.i;
5640 /* currently, we cannot do computations with forward symbols */
5641 c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
5642 c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
5643 if (c1 && c2) {
5644 switch(op) {
5645 case '+': l1 += l2; break;
5646 case '-': l1 -= l2; break;
5647 case '&': l1 &= l2; break;
5648 case '^': l1 ^= l2; break;
5649 case '|': l1 |= l2; break;
5650 case '*': l1 *= l2; break;
5652 case TOK_PDIV:
5653 case '/':
5654 case '%':
5655 case TOK_UDIV:
5656 case TOK_UMOD:
5657 /* if division by zero, generate explicit division */
5658 if (l2 == 0) {
5659 if (const_wanted)
5660 error("division by zero in constant");
5661 goto general_case;
5663 switch(op) {
5664 default: l1 /= l2; break;
5665 case '%': l1 %= l2; break;
5666 case TOK_UDIV: l1 = (U)l1 / l2; break;
5667 case TOK_UMOD: l1 = (U)l1 % l2; break;
5669 break;
5670 case TOK_SHL: l1 <<= l2; break;
5671 case TOK_SHR: l1 = (U)l1 >> l2; break;
5672 case TOK_SAR: l1 >>= l2; break;
5673 /* tests */
5674 case TOK_ULT: l1 = (U)l1 < (U)l2; break;
5675 case TOK_UGE: l1 = (U)l1 >= (U)l2; break;
5676 case TOK_EQ: l1 = l1 == l2; break;
5677 case TOK_NE: l1 = l1 != l2; break;
5678 case TOK_ULE: l1 = (U)l1 <= (U)l2; break;
5679 case TOK_UGT: l1 = (U)l1 > (U)l2; break;
5680 case TOK_LT: l1 = l1 < l2; break;
5681 case TOK_GE: l1 = l1 >= l2; break;
5682 case TOK_LE: l1 = l1 <= l2; break;
5683 case TOK_GT: l1 = l1 > l2; break;
5684 /* logical */
5685 case TOK_LAND: l1 = l1 && l2; break;
5686 case TOK_LOR: l1 = l1 || l2; break;
5687 default:
5688 goto general_case;
5690 v1->c.ll = l1;
5691 vtop--;
5692 } else {
5693 /* if commutative ops, put c2 as constant */
5694 if (c1 && (op == '+' || op == '&' || op == '^' ||
5695 op == '|' || op == '*')) {
5696 vswap();
5697 c2 = c1; //c = c1, c1 = c2, c2 = c;
5698 l2 = l1; //l = l1, l1 = l2, l2 = l;
5700 /* Filter out NOP operations like x*1, x-0, x&-1... */
5701 if (c2 && (((op == '*' || op == '/' || op == TOK_UDIV ||
5702 op == TOK_PDIV) &&
5703 l2 == 1) ||
5704 ((op == '+' || op == '-' || op == '|' || op == '^' ||
5705 op == TOK_SHL || op == TOK_SHR || op == TOK_SAR) &&
5706 l2 == 0) ||
5707 (op == '&' &&
5708 l2 == -1))) {
5709 /* nothing to do */
5710 vtop--;
5711 } else if (c2 && (op == '*' || op == TOK_PDIV || op == TOK_UDIV)) {
5712 /* try to use shifts instead of muls or divs */
5713 if (l2 > 0 && (l2 & (l2 - 1)) == 0) {
5714 n = -1;
5715 while (l2) {
5716 l2 >>= 1;
5717 n++;
5719 vtop->c.ll = n;
5720 if (op == '*')
5721 op = TOK_SHL;
5722 else if (op == TOK_PDIV)
5723 op = TOK_SAR;
5724 else
5725 op = TOK_SHR;
5727 goto general_case;
5728 } else if (c2 && (op == '+' || op == '-') &&
5729 ((vtop[-1].r & (VT_VALMASK | VT_LVAL | VT_SYM)) ==
5730 (VT_CONST | VT_SYM) ||
5731 (vtop[-1].r & (VT_VALMASK | VT_LVAL)) == VT_LOCAL)) {
5732 /* symbol + constant case */
5733 if (op == '-')
5734 l2 = -l2;
5735 vtop--;
5736 vtop->c.ll += l2;
5737 } else {
5738 general_case:
5739 if (!nocode_wanted) {
5740 /* call low level op generator */
5741 if (t1 == VT_LLONG || t2 == VT_LLONG)
5742 gen_opl(op);
5743 else
5744 gen_opi(op);
5745 } else {
5746 vtop--;
5752 /* generate a floating point operation with constant propagation */
5753 void gen_opif(int op)
5755 int c1, c2;
5756 SValue *v1, *v2;
5757 long double f1, f2;
5759 v1 = vtop - 1;
5760 v2 = vtop;
5761 /* currently, we cannot do computations with forward symbols */
5762 c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
5763 c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
5764 if (c1 && c2) {
5765 if (v1->type.t == VT_FLOAT) {
5766 f1 = v1->c.f;
5767 f2 = v2->c.f;
5768 } else if (v1->type.t == VT_DOUBLE) {
5769 f1 = v1->c.d;
5770 f2 = v2->c.d;
5771 } else {
5772 f1 = v1->c.ld;
5773 f2 = v2->c.ld;
5776 /* NOTE: we only do constant propagation if finite number (not
5777 NaN or infinity) (ANSI spec) */
5778 if (!ieee_finite(f1) || !ieee_finite(f2))
5779 goto general_case;
5781 switch(op) {
5782 case '+': f1 += f2; break;
5783 case '-': f1 -= f2; break;
5784 case '*': f1 *= f2; break;
5785 case '/':
5786 if (f2 == 0.0) {
5787 if (const_wanted)
5788 error("division by zero in constant");
5789 goto general_case;
5791 f1 /= f2;
5792 break;
5793 /* XXX: also handles tests ? */
5794 default:
5795 goto general_case;
5797 /* XXX: overflow test ? */
5798 if (v1->type.t == VT_FLOAT) {
5799 v1->c.f = f1;
5800 } else if (v1->type.t == VT_DOUBLE) {
5801 v1->c.d = f1;
5802 } else {
5803 v1->c.ld = f1;
5805 vtop--;
5806 } else {
5807 general_case:
5808 if (!nocode_wanted) {
5809 gen_opf(op);
5810 } else {
5811 vtop--;
5816 static int pointed_size(CType *type)
5818 int align;
5819 return type_size(pointed_type(type), &align);
5822 static inline int is_null_pointer(SValue *p)
5824 if ((p->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
5825 return 0;
5826 return ((p->type.t & VT_BTYPE) == VT_INT && p->c.i == 0) ||
5827 ((p->type.t & VT_BTYPE) == VT_LLONG && p->c.ll == 0);
5830 static inline int is_integer_btype(int bt)
5832 return (bt == VT_BYTE || bt == VT_SHORT ||
5833 bt == VT_INT || bt == VT_LLONG);
5836 /* check types for comparison or substraction of pointers */
5837 static void check_comparison_pointer_types(SValue *p1, SValue *p2, int op)
5839 CType *type1, *type2, tmp_type1, tmp_type2;
5840 int bt1, bt2;
5842 /* null pointers are accepted for all comparisons as gcc */
5843 if (is_null_pointer(p1) || is_null_pointer(p2))
5844 return;
5845 type1 = &p1->type;
5846 type2 = &p2->type;
5847 bt1 = type1->t & VT_BTYPE;
5848 bt2 = type2->t & VT_BTYPE;
5849 /* accept comparison between pointer and integer with a warning */
5850 if ((is_integer_btype(bt1) || is_integer_btype(bt2)) && op != '-') {
5851 if (op != TOK_LOR && op != TOK_LAND )
5852 warning("comparison between pointer and integer");
5853 return;
5856 /* both must be pointers or implicit function pointers */
5857 if (bt1 == VT_PTR) {
5858 type1 = pointed_type(type1);
5859 } else if (bt1 != VT_FUNC)
5860 goto invalid_operands;
5862 if (bt2 == VT_PTR) {
5863 type2 = pointed_type(type2);
5864 } else if (bt2 != VT_FUNC) {
5865 invalid_operands:
5866 error("invalid operands to binary %s", get_tok_str(op, NULL));
5868 if ((type1->t & VT_BTYPE) == VT_VOID ||
5869 (type2->t & VT_BTYPE) == VT_VOID)
5870 return;
5871 tmp_type1 = *type1;
5872 tmp_type2 = *type2;
5873 tmp_type1.t &= ~(VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
5874 tmp_type2.t &= ~(VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
5875 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
5876 /* gcc-like error if '-' is used */
5877 if (op == '-')
5878 goto invalid_operands;
5879 else
5880 warning("comparison of distinct pointer types lacks a cast");
5884 /* generic gen_op: handles types problems */
5885 void gen_op(int op)
5887 int u, t1, t2, bt1, bt2, t;
5888 CType type1;
5890 t1 = vtop[-1].type.t;
5891 t2 = vtop[0].type.t;
5892 bt1 = t1 & VT_BTYPE;
5893 bt2 = t2 & VT_BTYPE;
5895 if (bt1 == VT_PTR || bt2 == VT_PTR) {
5896 /* at least one operand is a pointer */
5897 /* relationnal op: must be both pointers */
5898 if (op >= TOK_ULT && op <= TOK_LOR) {
5899 check_comparison_pointer_types(vtop - 1, vtop, op);
5900 /* pointers are handled are unsigned */
5901 #ifdef TCC_TARGET_X86_64
5902 t = VT_LLONG | VT_UNSIGNED;
5903 #else
5904 t = VT_INT | VT_UNSIGNED;
5905 #endif
5906 goto std_op;
5908 /* if both pointers, then it must be the '-' op */
5909 if (bt1 == VT_PTR && bt2 == VT_PTR) {
5910 if (op != '-')
5911 error("cannot use pointers here");
5912 check_comparison_pointer_types(vtop - 1, vtop, op);
5913 /* XXX: check that types are compatible */
5914 u = pointed_size(&vtop[-1].type);
5915 gen_opic(op);
5916 /* set to integer type */
5917 #ifdef TCC_TARGET_X86_64
5918 vtop->type.t = VT_LLONG;
5919 #else
5920 vtop->type.t = VT_INT;
5921 #endif
5922 vpushi(u);
5923 gen_op(TOK_PDIV);
5924 } else {
5925 /* exactly one pointer : must be '+' or '-'. */
5926 if (op != '-' && op != '+')
5927 error("cannot use pointers here");
5928 /* Put pointer as first operand */
5929 if (bt2 == VT_PTR) {
5930 vswap();
5931 swap(&t1, &t2);
5933 type1 = vtop[-1].type;
5934 #ifdef TCC_TARGET_X86_64
5935 vpushll(pointed_size(&vtop[-1].type));
5936 #else
5937 /* XXX: cast to int ? (long long case) */
5938 vpushi(pointed_size(&vtop[-1].type));
5939 #endif
5940 gen_op('*');
5941 #ifdef CONFIG_TCC_BCHECK
5942 /* if evaluating constant expression, no code should be
5943 generated, so no bound check */
5944 if (do_bounds_check && !const_wanted) {
5945 /* if bounded pointers, we generate a special code to
5946 test bounds */
5947 if (op == '-') {
5948 vpushi(0);
5949 vswap();
5950 gen_op('-');
5952 gen_bounded_ptr_add();
5953 } else
5954 #endif
5956 gen_opic(op);
5958 /* put again type if gen_opic() swaped operands */
5959 vtop->type = type1;
5961 } else if (is_float(bt1) || is_float(bt2)) {
5962 /* compute bigger type and do implicit casts */
5963 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
5964 t = VT_LDOUBLE;
5965 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
5966 t = VT_DOUBLE;
5967 } else {
5968 t = VT_FLOAT;
5970 /* floats can only be used for a few operations */
5971 if (op != '+' && op != '-' && op != '*' && op != '/' &&
5972 (op < TOK_ULT || op > TOK_GT))
5973 error("invalid operands for binary operation");
5974 goto std_op;
5975 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
5976 /* cast to biggest op */
5977 t = VT_LLONG;
5978 /* convert to unsigned if it does not fit in a long long */
5979 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED) ||
5980 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED))
5981 t |= VT_UNSIGNED;
5982 goto std_op;
5983 } else {
5984 /* integer operations */
5985 t = VT_INT;
5986 /* convert to unsigned if it does not fit in an integer */
5987 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED) ||
5988 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED))
5989 t |= VT_UNSIGNED;
5990 std_op:
5991 /* XXX: currently, some unsigned operations are explicit, so
5992 we modify them here */
5993 if (t & VT_UNSIGNED) {
5994 if (op == TOK_SAR)
5995 op = TOK_SHR;
5996 else if (op == '/')
5997 op = TOK_UDIV;
5998 else if (op == '%')
5999 op = TOK_UMOD;
6000 else if (op == TOK_LT)
6001 op = TOK_ULT;
6002 else if (op == TOK_GT)
6003 op = TOK_UGT;
6004 else if (op == TOK_LE)
6005 op = TOK_ULE;
6006 else if (op == TOK_GE)
6007 op = TOK_UGE;
6009 vswap();
6010 type1.t = t;
6011 gen_cast(&type1);
6012 vswap();
6013 /* special case for shifts and long long: we keep the shift as
6014 an integer */
6015 if (op == TOK_SHR || op == TOK_SAR || op == TOK_SHL)
6016 type1.t = VT_INT;
6017 gen_cast(&type1);
6018 if (is_float(t))
6019 gen_opif(op);
6020 else
6021 gen_opic(op);
6022 if (op >= TOK_ULT && op <= TOK_GT) {
6023 /* relationnal op: the result is an int */
6024 vtop->type.t = VT_INT;
6025 } else {
6026 vtop->type.t = t;
6031 #ifndef TCC_TARGET_ARM
6032 /* generic itof for unsigned long long case */
6033 void gen_cvt_itof1(int t)
6035 if ((vtop->type.t & (VT_BTYPE | VT_UNSIGNED)) ==
6036 (VT_LLONG | VT_UNSIGNED)) {
6038 if (t == VT_FLOAT)
6039 vpush_global_sym(&func_old_type, TOK___floatundisf);
6040 #if LDOUBLE_SIZE != 8
6041 else if (t == VT_LDOUBLE)
6042 vpush_global_sym(&func_old_type, TOK___floatundixf);
6043 #endif
6044 else
6045 vpush_global_sym(&func_old_type, TOK___floatundidf);
6046 vrott(2);
6047 gfunc_call(1);
6048 vpushi(0);
6049 vtop->r = reg_fret(t);
6050 } else {
6051 gen_cvt_itof(t);
6054 #endif
6056 /* generic ftoi for unsigned long long case */
6057 void gen_cvt_ftoi1(int t)
6059 int st;
6061 if (t == (VT_LLONG | VT_UNSIGNED)) {
6062 /* not handled natively */
6063 st = vtop->type.t & VT_BTYPE;
6064 if (st == VT_FLOAT)
6065 vpush_global_sym(&func_old_type, TOK___fixunssfdi);
6066 #if LDOUBLE_SIZE != 8
6067 else if (st == VT_LDOUBLE)
6068 vpush_global_sym(&func_old_type, TOK___fixunsxfdi);
6069 #endif
6070 else
6071 vpush_global_sym(&func_old_type, TOK___fixunsdfdi);
6072 vrott(2);
6073 gfunc_call(1);
6074 vpushi(0);
6075 vtop->r = REG_IRET;
6076 vtop->r2 = REG_LRET;
6077 } else {
6078 gen_cvt_ftoi(t);
6082 /* force char or short cast */
6083 void force_charshort_cast(int t)
6085 int bits, dbt;
6086 dbt = t & VT_BTYPE;
6087 /* XXX: add optimization if lvalue : just change type and offset */
6088 if (dbt == VT_BYTE)
6089 bits = 8;
6090 else
6091 bits = 16;
6092 if (t & VT_UNSIGNED) {
6093 vpushi((1 << bits) - 1);
6094 gen_op('&');
6095 } else {
6096 bits = 32 - bits;
6097 vpushi(bits);
6098 gen_op(TOK_SHL);
6099 /* result must be signed or the SAR is converted to an SHL
6100 This was not the case when "t" was a signed short
6101 and the last value on the stack was an unsigned int */
6102 vtop->type.t &= ~VT_UNSIGNED;
6103 vpushi(bits);
6104 gen_op(TOK_SAR);
6108 /* cast 'vtop' to 'type'. Casting to bitfields is forbidden. */
6109 static void gen_cast(CType *type)
6111 int sbt, dbt, sf, df, c, p;
6113 /* special delayed cast for char/short */
6114 /* XXX: in some cases (multiple cascaded casts), it may still
6115 be incorrect */
6116 if (vtop->r & VT_MUSTCAST) {
6117 vtop->r &= ~VT_MUSTCAST;
6118 force_charshort_cast(vtop->type.t);
6121 /* bitfields first get cast to ints */
6122 if (vtop->type.t & VT_BITFIELD) {
6123 gv(RC_INT);
6126 dbt = type->t & (VT_BTYPE | VT_UNSIGNED);
6127 sbt = vtop->type.t & (VT_BTYPE | VT_UNSIGNED);
6129 if (sbt != dbt) {
6130 sf = is_float(sbt);
6131 df = is_float(dbt);
6132 c = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
6133 p = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == (VT_CONST | VT_SYM);
6134 if (c) {
6135 /* constant case: we can do it now */
6136 /* XXX: in ISOC, cannot do it if error in convert */
6137 if (sbt == VT_FLOAT)
6138 vtop->c.ld = vtop->c.f;
6139 else if (sbt == VT_DOUBLE)
6140 vtop->c.ld = vtop->c.d;
6142 if (df) {
6143 if ((sbt & VT_BTYPE) == VT_LLONG) {
6144 if (sbt & VT_UNSIGNED)
6145 vtop->c.ld = vtop->c.ull;
6146 else
6147 vtop->c.ld = vtop->c.ll;
6148 } else if(!sf) {
6149 if (sbt & VT_UNSIGNED)
6150 vtop->c.ld = vtop->c.ui;
6151 else
6152 vtop->c.ld = vtop->c.i;
6155 if (dbt == VT_FLOAT)
6156 vtop->c.f = (float)vtop->c.ld;
6157 else if (dbt == VT_DOUBLE)
6158 vtop->c.d = (double)vtop->c.ld;
6159 } else if (sf && dbt == (VT_LLONG|VT_UNSIGNED)) {
6160 vtop->c.ull = (unsigned long long)vtop->c.ld;
6161 } else if (sf && dbt == VT_BOOL) {
6162 vtop->c.i = (vtop->c.ld != 0);
6163 } else {
6164 if(sf)
6165 vtop->c.ll = (long long)vtop->c.ld;
6166 else if (sbt == (VT_LLONG|VT_UNSIGNED))
6167 vtop->c.ll = vtop->c.ull;
6168 else if (sbt & VT_UNSIGNED)
6169 vtop->c.ll = vtop->c.ui;
6170 else if (sbt != VT_LLONG)
6171 vtop->c.ll = vtop->c.i;
6173 if (dbt == (VT_LLONG|VT_UNSIGNED))
6174 vtop->c.ull = vtop->c.ll;
6175 else if (dbt == VT_BOOL)
6176 vtop->c.i = (vtop->c.ll != 0);
6177 else if (dbt != VT_LLONG) {
6178 int s = 0;
6179 if ((dbt & VT_BTYPE) == VT_BYTE)
6180 s = 24;
6181 else if ((dbt & VT_BTYPE) == VT_SHORT)
6182 s = 16;
6184 if(dbt & VT_UNSIGNED)
6185 vtop->c.ui = ((unsigned int)vtop->c.ll << s) >> s;
6186 else
6187 vtop->c.i = ((int)vtop->c.ll << s) >> s;
6190 } else if (p && dbt == VT_BOOL) {
6191 vtop->r = VT_CONST;
6192 vtop->c.i = 1;
6193 } else if (!nocode_wanted) {
6194 /* non constant case: generate code */
6195 if (sf && df) {
6196 /* convert from fp to fp */
6197 gen_cvt_ftof(dbt);
6198 } else if (df) {
6199 /* convert int to fp */
6200 gen_cvt_itof1(dbt);
6201 } else if (sf) {
6202 /* convert fp to int */
6203 if (dbt == VT_BOOL) {
6204 vpushi(0);
6205 gen_op(TOK_NE);
6206 } else {
6207 /* we handle char/short/etc... with generic code */
6208 if (dbt != (VT_INT | VT_UNSIGNED) &&
6209 dbt != (VT_LLONG | VT_UNSIGNED) &&
6210 dbt != VT_LLONG)
6211 dbt = VT_INT;
6212 gen_cvt_ftoi1(dbt);
6213 if (dbt == VT_INT && (type->t & (VT_BTYPE | VT_UNSIGNED)) != dbt) {
6214 /* additional cast for char/short... */
6215 vtop->type.t = dbt;
6216 gen_cast(type);
6219 #ifndef TCC_TARGET_X86_64
6220 } else if ((dbt & VT_BTYPE) == VT_LLONG) {
6221 if ((sbt & VT_BTYPE) != VT_LLONG) {
6222 /* scalar to long long */
6223 /* machine independent conversion */
6224 gv(RC_INT);
6225 /* generate high word */
6226 if (sbt == (VT_INT | VT_UNSIGNED)) {
6227 vpushi(0);
6228 gv(RC_INT);
6229 } else {
6230 if (sbt == VT_PTR) {
6231 /* cast from pointer to int before we apply
6232 shift operation, which pointers don't support*/
6233 gen_cast(&int_type);
6235 gv_dup();
6236 vpushi(31);
6237 gen_op(TOK_SAR);
6239 /* patch second register */
6240 vtop[-1].r2 = vtop->r;
6241 vpop();
6243 #else
6244 } else if ((dbt & VT_BTYPE) == VT_LLONG ||
6245 (dbt & VT_BTYPE) == VT_PTR) {
6246 /* XXX: not sure if this is perfect... need more tests */
6247 if ((sbt & VT_BTYPE) != VT_LLONG) {
6248 int r = gv(RC_INT);
6249 if (sbt != (VT_INT | VT_UNSIGNED) &&
6250 sbt != VT_PTR && sbt != VT_FUNC) {
6251 /* x86_64 specific: movslq */
6252 o(0x6348);
6253 o(0xc0 + (REG_VALUE(r) << 3) + REG_VALUE(r));
6256 #endif
6257 } else if (dbt == VT_BOOL) {
6258 /* scalar to bool */
6259 vpushi(0);
6260 gen_op(TOK_NE);
6261 } else if ((dbt & VT_BTYPE) == VT_BYTE ||
6262 (dbt & VT_BTYPE) == VT_SHORT) {
6263 if (sbt == VT_PTR) {
6264 vtop->type.t = VT_INT;
6265 warning("nonportable conversion from pointer to char/short");
6267 force_charshort_cast(dbt);
6268 } else if ((dbt & VT_BTYPE) == VT_INT) {
6269 /* scalar to int */
6270 if (sbt == VT_LLONG) {
6271 /* from long long: just take low order word */
6272 lexpand();
6273 vpop();
6275 /* if lvalue and single word type, nothing to do because
6276 the lvalue already contains the real type size (see
6277 VT_LVAL_xxx constants) */
6280 } else if ((dbt & VT_BTYPE) == VT_PTR && !(vtop->r & VT_LVAL)) {
6281 /* if we are casting between pointer types,
6282 we must update the VT_LVAL_xxx size */
6283 vtop->r = (vtop->r & ~VT_LVAL_TYPE)
6284 | (lvalue_type(type->ref->type.t) & VT_LVAL_TYPE);
6286 vtop->type = *type;
6289 /* return type size. Put alignment at 'a' */
6290 static int type_size(CType *type, int *a)
6292 Sym *s;
6293 int bt;
6295 bt = type->t & VT_BTYPE;
6296 if (bt == VT_STRUCT) {
6297 /* struct/union */
6298 s = type->ref;
6299 *a = s->r;
6300 return s->c;
6301 } else if (bt == VT_PTR) {
6302 if (type->t & VT_ARRAY) {
6303 int ts;
6305 s = type->ref;
6306 ts = type_size(&s->type, a);
6308 if (ts < 0 && s->c < 0)
6309 ts = -ts;
6311 return ts * s->c;
6312 } else {
6313 *a = PTR_SIZE;
6314 return PTR_SIZE;
6316 } else if (bt == VT_LDOUBLE) {
6317 *a = LDOUBLE_ALIGN;
6318 return LDOUBLE_SIZE;
6319 } else if (bt == VT_DOUBLE || bt == VT_LLONG) {
6320 #ifdef TCC_TARGET_I386
6321 #ifdef TCC_TARGET_PE
6322 *a = 8;
6323 #else
6324 *a = 4;
6325 #endif
6326 #elif defined(TCC_TARGET_ARM)
6327 #ifdef TCC_ARM_EABI
6328 *a = 8;
6329 #else
6330 *a = 4;
6331 #endif
6332 #else
6333 *a = 8;
6334 #endif
6335 return 8;
6336 } else if (bt == VT_INT || bt == VT_ENUM || bt == VT_FLOAT) {
6337 *a = 4;
6338 return 4;
6339 } else if (bt == VT_SHORT) {
6340 *a = 2;
6341 return 2;
6342 } else {
6343 /* char, void, function, _Bool */
6344 *a = 1;
6345 return 1;
6349 /* return the pointed type of t */
6350 static inline CType *pointed_type(CType *type)
6352 return &type->ref->type;
6355 /* modify type so that its it is a pointer to type. */
6356 static void mk_pointer(CType *type)
6358 Sym *s;
6359 s = sym_push(SYM_FIELD, type, 0, -1);
6360 type->t = VT_PTR | (type->t & ~VT_TYPE);
6361 type->ref = s;
6364 /* compare function types. OLD functions match any new functions */
6365 static int is_compatible_func(CType *type1, CType *type2)
6367 Sym *s1, *s2;
6369 s1 = type1->ref;
6370 s2 = type2->ref;
6371 if (!is_compatible_types(&s1->type, &s2->type))
6372 return 0;
6373 /* check func_call */
6374 if (FUNC_CALL(s1->r) != FUNC_CALL(s2->r))
6375 return 0;
6376 /* XXX: not complete */
6377 if (s1->c == FUNC_OLD || s2->c == FUNC_OLD)
6378 return 1;
6379 if (s1->c != s2->c)
6380 return 0;
6381 while (s1 != NULL) {
6382 if (s2 == NULL)
6383 return 0;
6384 if (!is_compatible_parameter_types(&s1->type, &s2->type))
6385 return 0;
6386 s1 = s1->next;
6387 s2 = s2->next;
6389 if (s2)
6390 return 0;
6391 return 1;
6394 /* return true if type1 and type2 are the same. If unqualified is
6395 true, qualifiers on the types are ignored.
6397 - enums are not checked as gcc __builtin_types_compatible_p ()
6399 static int compare_types(CType *type1, CType *type2, int unqualified)
6401 int bt1, t1, t2;
6403 t1 = type1->t & VT_TYPE;
6404 t2 = type2->t & VT_TYPE;
6405 if (unqualified) {
6406 /* strip qualifiers before comparing */
6407 t1 &= ~(VT_CONSTANT | VT_VOLATILE);
6408 t2 &= ~(VT_CONSTANT | VT_VOLATILE);
6410 /* XXX: bitfields ? */
6411 if (t1 != t2)
6412 return 0;
6413 /* test more complicated cases */
6414 bt1 = t1 & VT_BTYPE;
6415 if (bt1 == VT_PTR) {
6416 type1 = pointed_type(type1);
6417 type2 = pointed_type(type2);
6418 return is_compatible_types(type1, type2);
6419 } else if (bt1 == VT_STRUCT) {
6420 return (type1->ref == type2->ref);
6421 } else if (bt1 == VT_FUNC) {
6422 return is_compatible_func(type1, type2);
6423 } else {
6424 return 1;
6428 /* return true if type1 and type2 are exactly the same (including
6429 qualifiers).
6431 static int is_compatible_types(CType *type1, CType *type2)
6433 return compare_types(type1,type2,0);
6436 /* return true if type1 and type2 are the same (ignoring qualifiers).
6438 static int is_compatible_parameter_types(CType *type1, CType *type2)
6440 return compare_types(type1,type2,1);
6443 /* print a type. If 'varstr' is not NULL, then the variable is also
6444 printed in the type */
6445 /* XXX: union */
6446 /* XXX: add array and function pointers */
6447 void type_to_str(char *buf, int buf_size,
6448 CType *type, const char *varstr)
6450 int bt, v, t;
6451 Sym *s, *sa;
6452 char buf1[256];
6453 const char *tstr;
6455 t = type->t & VT_TYPE;
6456 bt = t & VT_BTYPE;
6457 buf[0] = '\0';
6458 if (t & VT_CONSTANT)
6459 pstrcat(buf, buf_size, "const ");
6460 if (t & VT_VOLATILE)
6461 pstrcat(buf, buf_size, "volatile ");
6462 if (t & VT_UNSIGNED)
6463 pstrcat(buf, buf_size, "unsigned ");
6464 switch(bt) {
6465 case VT_VOID:
6466 tstr = "void";
6467 goto add_tstr;
6468 case VT_BOOL:
6469 tstr = "_Bool";
6470 goto add_tstr;
6471 case VT_BYTE:
6472 tstr = "char";
6473 goto add_tstr;
6474 case VT_SHORT:
6475 tstr = "short";
6476 goto add_tstr;
6477 case VT_INT:
6478 tstr = "int";
6479 goto add_tstr;
6480 case VT_LONG:
6481 tstr = "long";
6482 goto add_tstr;
6483 case VT_LLONG:
6484 tstr = "long long";
6485 goto add_tstr;
6486 case VT_FLOAT:
6487 tstr = "float";
6488 goto add_tstr;
6489 case VT_DOUBLE:
6490 tstr = "double";
6491 goto add_tstr;
6492 case VT_LDOUBLE:
6493 tstr = "long double";
6494 add_tstr:
6495 pstrcat(buf, buf_size, tstr);
6496 break;
6497 case VT_ENUM:
6498 case VT_STRUCT:
6499 if (bt == VT_STRUCT)
6500 tstr = "struct ";
6501 else
6502 tstr = "enum ";
6503 pstrcat(buf, buf_size, tstr);
6504 v = type->ref->v & ~SYM_STRUCT;
6505 if (v >= SYM_FIRST_ANOM)
6506 pstrcat(buf, buf_size, "<anonymous>");
6507 else
6508 pstrcat(buf, buf_size, get_tok_str(v, NULL));
6509 break;
6510 case VT_FUNC:
6511 s = type->ref;
6512 type_to_str(buf, buf_size, &s->type, varstr);
6513 pstrcat(buf, buf_size, "(");
6514 sa = s->next;
6515 while (sa != NULL) {
6516 type_to_str(buf1, sizeof(buf1), &sa->type, NULL);
6517 pstrcat(buf, buf_size, buf1);
6518 sa = sa->next;
6519 if (sa)
6520 pstrcat(buf, buf_size, ", ");
6522 pstrcat(buf, buf_size, ")");
6523 goto no_var;
6524 case VT_PTR:
6525 s = type->ref;
6526 pstrcpy(buf1, sizeof(buf1), "*");
6527 if (varstr)
6528 pstrcat(buf1, sizeof(buf1), varstr);
6529 type_to_str(buf, buf_size, &s->type, buf1);
6530 goto no_var;
6532 if (varstr) {
6533 pstrcat(buf, buf_size, " ");
6534 pstrcat(buf, buf_size, varstr);
6536 no_var: ;
6539 /* verify type compatibility to store vtop in 'dt' type, and generate
6540 casts if needed. */
6541 static void gen_assign_cast(CType *dt)
6543 CType *st, *type1, *type2, tmp_type1, tmp_type2;
6544 char buf1[256], buf2[256];
6545 int dbt, sbt;
6547 st = &vtop->type; /* source type */
6548 dbt = dt->t & VT_BTYPE;
6549 sbt = st->t & VT_BTYPE;
6550 if (dt->t & VT_CONSTANT)
6551 warning("assignment of read-only location");
6552 switch(dbt) {
6553 case VT_PTR:
6554 /* special cases for pointers */
6555 /* '0' can also be a pointer */
6556 if (is_null_pointer(vtop))
6557 goto type_ok;
6558 /* accept implicit pointer to integer cast with warning */
6559 if (is_integer_btype(sbt)) {
6560 warning("assignment makes pointer from integer without a cast");
6561 goto type_ok;
6563 type1 = pointed_type(dt);
6564 /* a function is implicitely a function pointer */
6565 if (sbt == VT_FUNC) {
6566 if ((type1->t & VT_BTYPE) != VT_VOID &&
6567 !is_compatible_types(pointed_type(dt), st))
6568 goto error;
6569 else
6570 goto type_ok;
6572 if (sbt != VT_PTR)
6573 goto error;
6574 type2 = pointed_type(st);
6575 if ((type1->t & VT_BTYPE) == VT_VOID ||
6576 (type2->t & VT_BTYPE) == VT_VOID) {
6577 /* void * can match anything */
6578 } else {
6579 /* exact type match, except for unsigned */
6580 tmp_type1 = *type1;
6581 tmp_type2 = *type2;
6582 tmp_type1.t &= ~(VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
6583 tmp_type2.t &= ~(VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
6584 if (!is_compatible_types(&tmp_type1, &tmp_type2))
6585 warning("assignment from incompatible pointer type");
6587 /* check const and volatile */
6588 if ((!(type1->t & VT_CONSTANT) && (type2->t & VT_CONSTANT)) ||
6589 (!(type1->t & VT_VOLATILE) && (type2->t & VT_VOLATILE)))
6590 warning("assignment discards qualifiers from pointer target type");
6591 break;
6592 case VT_BYTE:
6593 case VT_SHORT:
6594 case VT_INT:
6595 case VT_LLONG:
6596 if (sbt == VT_PTR || sbt == VT_FUNC) {
6597 warning("assignment makes integer from pointer without a cast");
6599 /* XXX: more tests */
6600 break;
6601 case VT_STRUCT:
6602 tmp_type1 = *dt;
6603 tmp_type2 = *st;
6604 tmp_type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
6605 tmp_type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
6606 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
6607 error:
6608 type_to_str(buf1, sizeof(buf1), st, NULL);
6609 type_to_str(buf2, sizeof(buf2), dt, NULL);
6610 error("cannot cast '%s' to '%s'", buf1, buf2);
6612 break;
6614 type_ok:
6615 gen_cast(dt);
6618 /* store vtop in lvalue pushed on stack */
6619 void vstore(void)
6621 int sbt, dbt, ft, r, t, size, align, bit_size, bit_pos, rc, delayed_cast;
6623 ft = vtop[-1].type.t;
6624 sbt = vtop->type.t & VT_BTYPE;
6625 dbt = ft & VT_BTYPE;
6626 if (((sbt == VT_INT || sbt == VT_SHORT) && dbt == VT_BYTE) ||
6627 (sbt == VT_INT && dbt == VT_SHORT)) {
6628 /* optimize char/short casts */
6629 delayed_cast = VT_MUSTCAST;
6630 vtop->type.t = ft & (VT_TYPE & ~(VT_BITFIELD | (-1 << VT_STRUCT_SHIFT)));
6631 /* XXX: factorize */
6632 if (ft & VT_CONSTANT)
6633 warning("assignment of read-only location");
6634 } else {
6635 delayed_cast = 0;
6636 if (!(ft & VT_BITFIELD))
6637 gen_assign_cast(&vtop[-1].type);
6640 if (sbt == VT_STRUCT) {
6641 /* if structure, only generate pointer */
6642 /* structure assignment : generate memcpy */
6643 /* XXX: optimize if small size */
6644 if (!nocode_wanted) {
6645 size = type_size(&vtop->type, &align);
6647 #ifdef TCC_ARM_EABI
6648 if(!(align & 7))
6649 vpush_global_sym(&func_old_type, TOK_memcpy8);
6650 else if(!(align & 3))
6651 vpush_global_sym(&func_old_type, TOK_memcpy4);
6652 else
6653 #endif
6654 vpush_global_sym(&func_old_type, TOK_memcpy);
6656 /* destination */
6657 vpushv(vtop - 2);
6658 vtop->type.t = VT_PTR;
6659 gaddrof();
6660 /* source */
6661 vpushv(vtop - 2);
6662 vtop->type.t = VT_PTR;
6663 gaddrof();
6664 /* type size */
6665 vpushi(size);
6666 gfunc_call(3);
6668 vswap();
6669 vpop();
6670 } else {
6671 vswap();
6672 vpop();
6674 /* leave source on stack */
6675 } else if (ft & VT_BITFIELD) {
6676 /* bitfield store handling */
6677 bit_pos = (ft >> VT_STRUCT_SHIFT) & 0x3f;
6678 bit_size = (ft >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
6679 /* remove bit field info to avoid loops */
6680 vtop[-1].type.t = ft & ~(VT_BITFIELD | (-1 << VT_STRUCT_SHIFT));
6682 /* duplicate source into other register */
6683 gv_dup();
6684 vswap();
6685 vrott(3);
6687 if((ft & VT_BTYPE) == VT_BOOL) {
6688 gen_cast(&vtop[-1].type);
6689 vtop[-1].type.t = (vtop[-1].type.t & ~VT_BTYPE) | (VT_BYTE | VT_UNSIGNED);
6692 /* duplicate destination */
6693 vdup();
6694 vtop[-1] = vtop[-2];
6696 /* mask and shift source */
6697 if((ft & VT_BTYPE) != VT_BOOL) {
6698 if((ft & VT_BTYPE) == VT_LLONG) {
6699 vpushll((1ULL << bit_size) - 1ULL);
6700 } else {
6701 vpushi((1 << bit_size) - 1);
6703 gen_op('&');
6705 vpushi(bit_pos);
6706 gen_op(TOK_SHL);
6707 /* load destination, mask and or with source */
6708 vswap();
6709 if((ft & VT_BTYPE) == VT_LLONG) {
6710 vpushll(~(((1ULL << bit_size) - 1ULL) << bit_pos));
6711 } else {
6712 vpushi(~(((1 << bit_size) - 1) << bit_pos));
6714 gen_op('&');
6715 gen_op('|');
6716 /* store result */
6717 vstore();
6719 /* pop off shifted source from "duplicate source..." above */
6720 vpop();
6722 } else {
6723 #ifdef CONFIG_TCC_BCHECK
6724 /* bound check case */
6725 if (vtop[-1].r & VT_MUSTBOUND) {
6726 vswap();
6727 gbound();
6728 vswap();
6730 #endif
6731 if (!nocode_wanted) {
6732 rc = RC_INT;
6733 if (is_float(ft)) {
6734 rc = RC_FLOAT;
6735 #ifdef TCC_TARGET_X86_64
6736 if ((ft & VT_BTYPE) == VT_LDOUBLE) {
6737 rc = RC_ST0;
6739 #endif
6741 r = gv(rc); /* generate value */
6742 /* if lvalue was saved on stack, must read it */
6743 if ((vtop[-1].r & VT_VALMASK) == VT_LLOCAL) {
6744 SValue sv;
6745 t = get_reg(RC_INT);
6746 #ifdef TCC_TARGET_X86_64
6747 sv.type.t = VT_PTR;
6748 #else
6749 sv.type.t = VT_INT;
6750 #endif
6751 sv.r = VT_LOCAL | VT_LVAL;
6752 sv.c.ul = vtop[-1].c.ul;
6753 load(t, &sv);
6754 vtop[-1].r = t | VT_LVAL;
6756 store(r, vtop - 1);
6757 #ifndef TCC_TARGET_X86_64
6758 /* two word case handling : store second register at word + 4 */
6759 if ((ft & VT_BTYPE) == VT_LLONG) {
6760 vswap();
6761 /* convert to int to increment easily */
6762 vtop->type.t = VT_INT;
6763 gaddrof();
6764 vpushi(4);
6765 gen_op('+');
6766 vtop->r |= VT_LVAL;
6767 vswap();
6768 /* XXX: it works because r2 is spilled last ! */
6769 store(vtop->r2, vtop - 1);
6771 #endif
6773 vswap();
6774 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
6775 vtop->r |= delayed_cast;
6779 /* post defines POST/PRE add. c is the token ++ or -- */
6780 void inc(int post, int c)
6782 test_lvalue();
6783 vdup(); /* save lvalue */
6784 if (post) {
6785 gv_dup(); /* duplicate value */
6786 vrotb(3);
6787 vrotb(3);
6789 /* add constant */
6790 vpushi(c - TOK_MID);
6791 gen_op('+');
6792 vstore(); /* store value */
6793 if (post)
6794 vpop(); /* if post op, return saved value */
6797 /* Parse GNUC __attribute__ extension. Currently, the following
6798 extensions are recognized:
6799 - aligned(n) : set data/function alignment.
6800 - packed : force data alignment to 1
6801 - section(x) : generate data/code in this section.
6802 - unused : currently ignored, but may be used someday.
6803 - regparm(n) : pass function parameters in registers (i386 only)
6805 static void parse_attribute(AttributeDef *ad)
6807 int t, n;
6809 while (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2) {
6810 next();
6811 skip('(');
6812 skip('(');
6813 while (tok != ')') {
6814 if (tok < TOK_IDENT)
6815 expect("attribute name");
6816 t = tok;
6817 next();
6818 switch(t) {
6819 case TOK_SECTION1:
6820 case TOK_SECTION2:
6821 skip('(');
6822 if (tok != TOK_STR)
6823 expect("section name");
6824 ad->section = find_section(tcc_state, (char *)tokc.cstr->data);
6825 next();
6826 skip(')');
6827 break;
6828 case TOK_ALIGNED1:
6829 case TOK_ALIGNED2:
6830 if (tok == '(') {
6831 next();
6832 n = expr_const();
6833 if (n <= 0 || (n & (n - 1)) != 0)
6834 error("alignment must be a positive power of two");
6835 skip(')');
6836 } else {
6837 n = MAX_ALIGN;
6839 ad->aligned = n;
6840 break;
6841 case TOK_PACKED1:
6842 case TOK_PACKED2:
6843 ad->packed = 1;
6844 break;
6845 case TOK_UNUSED1:
6846 case TOK_UNUSED2:
6847 /* currently, no need to handle it because tcc does not
6848 track unused objects */
6849 break;
6850 case TOK_NORETURN1:
6851 case TOK_NORETURN2:
6852 /* currently, no need to handle it because tcc does not
6853 track unused objects */
6854 break;
6855 case TOK_CDECL1:
6856 case TOK_CDECL2:
6857 case TOK_CDECL3:
6858 FUNC_CALL(ad->func_attr) = FUNC_CDECL;
6859 break;
6860 case TOK_STDCALL1:
6861 case TOK_STDCALL2:
6862 case TOK_STDCALL3:
6863 FUNC_CALL(ad->func_attr) = FUNC_STDCALL;
6864 break;
6865 #ifdef TCC_TARGET_I386
6866 case TOK_REGPARM1:
6867 case TOK_REGPARM2:
6868 skip('(');
6869 n = expr_const();
6870 if (n > 3)
6871 n = 3;
6872 else if (n < 0)
6873 n = 0;
6874 if (n > 0)
6875 FUNC_CALL(ad->func_attr) = FUNC_FASTCALL1 + n - 1;
6876 skip(')');
6877 break;
6878 case TOK_FASTCALL1:
6879 case TOK_FASTCALL2:
6880 case TOK_FASTCALL3:
6881 FUNC_CALL(ad->func_attr) = FUNC_FASTCALLW;
6882 break;
6883 #endif
6884 case TOK_DLLEXPORT:
6885 FUNC_EXPORT(ad->func_attr) = 1;
6886 break;
6887 default:
6888 if (tcc_state->warn_unsupported)
6889 warning("'%s' attribute ignored", get_tok_str(t, NULL));
6890 /* skip parameters */
6891 if (tok == '(') {
6892 int parenthesis = 0;
6893 do {
6894 if (tok == '(')
6895 parenthesis++;
6896 else if (tok == ')')
6897 parenthesis--;
6898 next();
6899 } while (parenthesis && tok != -1);
6901 break;
6903 if (tok != ',')
6904 break;
6905 next();
6907 skip(')');
6908 skip(')');
6912 /* enum/struct/union declaration. u is either VT_ENUM or VT_STRUCT */
6913 static void struct_decl(CType *type, int u)
6915 int a, v, size, align, maxalign, c, offset;
6916 int bit_size, bit_pos, bsize, bt, lbit_pos, prevbt;
6917 Sym *s, *ss, *ass, **ps;
6918 AttributeDef ad;
6919 CType type1, btype;
6921 a = tok; /* save decl type */
6922 next();
6923 if (tok != '{') {
6924 v = tok;
6925 next();
6926 /* struct already defined ? return it */
6927 if (v < TOK_IDENT)
6928 expect("struct/union/enum name");
6929 s = struct_find(v);
6930 if (s) {
6931 if (s->type.t != a)
6932 error("invalid type");
6933 goto do_decl;
6935 } else {
6936 v = anon_sym++;
6938 type1.t = a;
6939 /* we put an undefined size for struct/union */
6940 s = sym_push(v | SYM_STRUCT, &type1, 0, -1);
6941 s->r = 0; /* default alignment is zero as gcc */
6942 /* put struct/union/enum name in type */
6943 do_decl:
6944 type->t = u;
6945 type->ref = s;
6947 if (tok == '{') {
6948 next();
6949 if (s->c != -1)
6950 error("struct/union/enum already defined");
6951 /* cannot be empty */
6952 c = 0;
6953 /* non empty enums are not allowed */
6954 if (a == TOK_ENUM) {
6955 for(;;) {
6956 v = tok;
6957 if (v < TOK_UIDENT)
6958 expect("identifier");
6959 next();
6960 if (tok == '=') {
6961 next();
6962 c = expr_const();
6964 /* enum symbols have static storage */
6965 ss = sym_push(v, &int_type, VT_CONST, c);
6966 ss->type.t |= VT_STATIC;
6967 if (tok != ',')
6968 break;
6969 next();
6970 c++;
6971 /* NOTE: we accept a trailing comma */
6972 if (tok == '}')
6973 break;
6975 skip('}');
6976 } else {
6977 maxalign = 1;
6978 ps = &s->next;
6979 prevbt = VT_INT;
6980 bit_pos = 0;
6981 offset = 0;
6982 while (tok != '}') {
6983 parse_btype(&btype, &ad);
6984 while (1) {
6985 bit_size = -1;
6986 v = 0;
6987 type1 = btype;
6988 if (tok != ':') {
6989 type_decl(&type1, &ad, &v, TYPE_DIRECT | TYPE_ABSTRACT);
6990 if (v == 0 && (type1.t & VT_BTYPE) != VT_STRUCT)
6991 expect("identifier");
6992 if ((type1.t & VT_BTYPE) == VT_FUNC ||
6993 (type1.t & (VT_TYPEDEF | VT_STATIC | VT_EXTERN | VT_INLINE)))
6994 error("invalid type for '%s'",
6995 get_tok_str(v, NULL));
6997 if (tok == ':') {
6998 next();
6999 bit_size = expr_const();
7000 /* XXX: handle v = 0 case for messages */
7001 if (bit_size < 0)
7002 error("negative width in bit-field '%s'",
7003 get_tok_str(v, NULL));
7004 if (v && bit_size == 0)
7005 error("zero width for bit-field '%s'",
7006 get_tok_str(v, NULL));
7008 size = type_size(&type1, &align);
7009 if (ad.aligned) {
7010 if (align < ad.aligned)
7011 align = ad.aligned;
7012 } else if (ad.packed) {
7013 align = 1;
7014 } else if (*tcc_state->pack_stack_ptr) {
7015 if (align > *tcc_state->pack_stack_ptr)
7016 align = *tcc_state->pack_stack_ptr;
7018 lbit_pos = 0;
7019 if (bit_size >= 0) {
7020 bt = type1.t & VT_BTYPE;
7021 if (bt != VT_INT &&
7022 bt != VT_BYTE &&
7023 bt != VT_SHORT &&
7024 bt != VT_BOOL &&
7025 bt != VT_ENUM &&
7026 bt != VT_LLONG)
7027 error("bitfields must have scalar type");
7028 bsize = size * 8;
7029 if (bit_size > bsize) {
7030 error("width of '%s' exceeds its type",
7031 get_tok_str(v, NULL));
7032 } else if (bit_size == bsize) {
7033 /* no need for bit fields */
7034 bit_pos = 0;
7035 } else if (bit_size == 0) {
7036 /* XXX: what to do if only padding in a
7037 structure ? */
7038 /* zero size: means to pad */
7039 bit_pos = 0;
7040 } else {
7041 /* we do not have enough room ?
7042 did the type change?
7043 is it a union? */
7044 if ((bit_pos + bit_size) > bsize ||
7045 bt != prevbt || a == TOK_UNION)
7046 bit_pos = 0;
7047 lbit_pos = bit_pos;
7048 /* XXX: handle LSB first */
7049 type1.t |= VT_BITFIELD |
7050 (bit_pos << VT_STRUCT_SHIFT) |
7051 (bit_size << (VT_STRUCT_SHIFT + 6));
7052 bit_pos += bit_size;
7054 prevbt = bt;
7055 } else {
7056 bit_pos = 0;
7058 if (v != 0 || (type1.t & VT_BTYPE) == VT_STRUCT) {
7059 /* add new memory data only if starting
7060 bit field */
7061 if (lbit_pos == 0) {
7062 if (a == TOK_STRUCT) {
7063 c = (c + align - 1) & -align;
7064 offset = c;
7065 if (size > 0)
7066 c += size;
7067 } else {
7068 offset = 0;
7069 if (size > c)
7070 c = size;
7072 if (align > maxalign)
7073 maxalign = align;
7075 #if 0
7076 printf("add field %s offset=%d",
7077 get_tok_str(v, NULL), offset);
7078 if (type1.t & VT_BITFIELD) {
7079 printf(" pos=%d size=%d",
7080 (type1.t >> VT_STRUCT_SHIFT) & 0x3f,
7081 (type1.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f);
7083 printf("\n");
7084 #endif
7086 if (v == 0 && (type1.t & VT_BTYPE) == VT_STRUCT) {
7087 ass = type1.ref;
7088 while ((ass = ass->next) != NULL) {
7089 ss = sym_push(ass->v, &ass->type, 0, offset + ass->c);
7090 *ps = ss;
7091 ps = &ss->next;
7093 } else if (v) {
7094 ss = sym_push(v | SYM_FIELD, &type1, 0, offset);
7095 *ps = ss;
7096 ps = &ss->next;
7098 if (tok == ';' || tok == TOK_EOF)
7099 break;
7100 skip(',');
7102 skip(';');
7104 skip('}');
7105 /* store size and alignment */
7106 s->c = (c + maxalign - 1) & -maxalign;
7107 s->r = maxalign;
7112 /* return 0 if no type declaration. otherwise, return the basic type
7113 and skip it.
7115 static int parse_btype(CType *type, AttributeDef *ad)
7117 int t, u, type_found, typespec_found, typedef_found;
7118 Sym *s;
7119 CType type1;
7121 memset(ad, 0, sizeof(AttributeDef));
7122 type_found = 0;
7123 typespec_found = 0;
7124 typedef_found = 0;
7125 t = 0;
7126 while(1) {
7127 switch(tok) {
7128 case TOK_EXTENSION:
7129 /* currently, we really ignore extension */
7130 next();
7131 continue;
7133 /* basic types */
7134 case TOK_CHAR:
7135 u = VT_BYTE;
7136 basic_type:
7137 next();
7138 basic_type1:
7139 if ((t & VT_BTYPE) != 0)
7140 error("too many basic types");
7141 t |= u;
7142 typespec_found = 1;
7143 break;
7144 case TOK_VOID:
7145 u = VT_VOID;
7146 goto basic_type;
7147 case TOK_SHORT:
7148 u = VT_SHORT;
7149 goto basic_type;
7150 case TOK_INT:
7151 next();
7152 typespec_found = 1;
7153 break;
7154 case TOK_LONG:
7155 next();
7156 if ((t & VT_BTYPE) == VT_DOUBLE) {
7157 t = (t & ~VT_BTYPE) | VT_LDOUBLE;
7158 } else if ((t & VT_BTYPE) == VT_LONG) {
7159 t = (t & ~VT_BTYPE) | VT_LLONG;
7160 } else {
7161 u = VT_LONG;
7162 goto basic_type1;
7164 break;
7165 case TOK_BOOL:
7166 u = VT_BOOL;
7167 goto basic_type;
7168 case TOK_FLOAT:
7169 u = VT_FLOAT;
7170 goto basic_type;
7171 case TOK_DOUBLE:
7172 next();
7173 if ((t & VT_BTYPE) == VT_LONG) {
7174 t = (t & ~VT_BTYPE) | VT_LDOUBLE;
7175 } else {
7176 u = VT_DOUBLE;
7177 goto basic_type1;
7179 break;
7180 case TOK_ENUM:
7181 struct_decl(&type1, VT_ENUM);
7182 basic_type2:
7183 u = type1.t;
7184 type->ref = type1.ref;
7185 goto basic_type1;
7186 case TOK_STRUCT:
7187 case TOK_UNION:
7188 struct_decl(&type1, VT_STRUCT);
7189 goto basic_type2;
7191 /* type modifiers */
7192 case TOK_CONST1:
7193 case TOK_CONST2:
7194 case TOK_CONST3:
7195 t |= VT_CONSTANT;
7196 next();
7197 break;
7198 case TOK_VOLATILE1:
7199 case TOK_VOLATILE2:
7200 case TOK_VOLATILE3:
7201 t |= VT_VOLATILE;
7202 next();
7203 break;
7204 case TOK_SIGNED1:
7205 case TOK_SIGNED2:
7206 case TOK_SIGNED3:
7207 typespec_found = 1;
7208 t |= VT_SIGNED;
7209 next();
7210 break;
7211 case TOK_REGISTER:
7212 case TOK_AUTO:
7213 case TOK_RESTRICT1:
7214 case TOK_RESTRICT2:
7215 case TOK_RESTRICT3:
7216 next();
7217 break;
7218 case TOK_UNSIGNED:
7219 t |= VT_UNSIGNED;
7220 next();
7221 typespec_found = 1;
7222 break;
7224 /* storage */
7225 case TOK_EXTERN:
7226 t |= VT_EXTERN;
7227 next();
7228 break;
7229 case TOK_STATIC:
7230 t |= VT_STATIC;
7231 next();
7232 break;
7233 case TOK_TYPEDEF:
7234 t |= VT_TYPEDEF;
7235 next();
7236 break;
7237 case TOK_INLINE1:
7238 case TOK_INLINE2:
7239 case TOK_INLINE3:
7240 t |= VT_INLINE;
7241 next();
7242 break;
7244 /* GNUC attribute */
7245 case TOK_ATTRIBUTE1:
7246 case TOK_ATTRIBUTE2:
7247 parse_attribute(ad);
7248 break;
7249 /* GNUC typeof */
7250 case TOK_TYPEOF1:
7251 case TOK_TYPEOF2:
7252 case TOK_TYPEOF3:
7253 next();
7254 parse_expr_type(&type1);
7255 goto basic_type2;
7256 default:
7257 if (typespec_found || typedef_found)
7258 goto the_end;
7259 s = sym_find(tok);
7260 if (!s || !(s->type.t & VT_TYPEDEF))
7261 goto the_end;
7262 typedef_found = 1;
7263 t |= (s->type.t & ~VT_TYPEDEF);
7264 type->ref = s->type.ref;
7265 next();
7266 typespec_found = 1;
7267 break;
7269 type_found = 1;
7271 the_end:
7272 if ((t & (VT_SIGNED|VT_UNSIGNED)) == (VT_SIGNED|VT_UNSIGNED))
7273 error("signed and unsigned modifier");
7274 if (tcc_state->char_is_unsigned) {
7275 if ((t & (VT_SIGNED|VT_UNSIGNED|VT_BTYPE)) == VT_BYTE)
7276 t |= VT_UNSIGNED;
7278 t &= ~VT_SIGNED;
7280 /* long is never used as type */
7281 if ((t & VT_BTYPE) == VT_LONG)
7282 #ifndef TCC_TARGET_X86_64
7283 t = (t & ~VT_BTYPE) | VT_INT;
7284 #else
7285 t = (t & ~VT_BTYPE) | VT_LLONG;
7286 #endif
7287 type->t = t;
7288 return type_found;
7291 /* convert a function parameter type (array to pointer and function to
7292 function pointer) */
7293 static inline void convert_parameter_type(CType *pt)
7295 /* remove const and volatile qualifiers (XXX: const could be used
7296 to indicate a const function parameter */
7297 pt->t &= ~(VT_CONSTANT | VT_VOLATILE);
7298 /* array must be transformed to pointer according to ANSI C */
7299 pt->t &= ~VT_ARRAY;
7300 if ((pt->t & VT_BTYPE) == VT_FUNC) {
7301 mk_pointer(pt);
7305 static void post_type(CType *type, AttributeDef *ad)
7307 int n, l, t1, arg_size, align;
7308 Sym **plast, *s, *first;
7309 AttributeDef ad1;
7310 CType pt;
7312 if (tok == '(') {
7313 /* function declaration */
7314 next();
7315 l = 0;
7316 first = NULL;
7317 plast = &first;
7318 arg_size = 0;
7319 if (tok != ')') {
7320 for(;;) {
7321 /* read param name and compute offset */
7322 if (l != FUNC_OLD) {
7323 if (!parse_btype(&pt, &ad1)) {
7324 if (l) {
7325 error("invalid type");
7326 } else {
7327 l = FUNC_OLD;
7328 goto old_proto;
7331 l = FUNC_NEW;
7332 if ((pt.t & VT_BTYPE) == VT_VOID && tok == ')')
7333 break;
7334 type_decl(&pt, &ad1, &n, TYPE_DIRECT | TYPE_ABSTRACT);
7335 if ((pt.t & VT_BTYPE) == VT_VOID)
7336 error("parameter declared as void");
7337 arg_size += (type_size(&pt, &align) + 3) & ~3;
7338 } else {
7339 old_proto:
7340 n = tok;
7341 if (n < TOK_UIDENT)
7342 expect("identifier");
7343 pt.t = VT_INT;
7344 next();
7346 convert_parameter_type(&pt);
7347 s = sym_push(n | SYM_FIELD, &pt, 0, 0);
7348 *plast = s;
7349 plast = &s->next;
7350 if (tok == ')')
7351 break;
7352 skip(',');
7353 if (l == FUNC_NEW && tok == TOK_DOTS) {
7354 l = FUNC_ELLIPSIS;
7355 next();
7356 break;
7360 /* if no parameters, then old type prototype */
7361 if (l == 0)
7362 l = FUNC_OLD;
7363 skip(')');
7364 t1 = type->t & VT_STORAGE;
7365 /* NOTE: const is ignored in returned type as it has a special
7366 meaning in gcc / C++ */
7367 type->t &= ~(VT_STORAGE | VT_CONSTANT);
7368 post_type(type, ad);
7369 /* we push a anonymous symbol which will contain the function prototype */
7370 FUNC_ARGS(ad->func_attr) = arg_size;
7371 s = sym_push(SYM_FIELD, type, ad->func_attr, l);
7372 s->next = first;
7373 type->t = t1 | VT_FUNC;
7374 type->ref = s;
7375 } else if (tok == '[') {
7376 /* array definition */
7377 next();
7378 if (tok == TOK_RESTRICT1)
7379 next();
7380 n = -1;
7381 if (tok != ']') {
7382 n = expr_const();
7383 if (n < 0)
7384 error("invalid array size");
7386 skip(']');
7387 /* parse next post type */
7388 t1 = type->t & VT_STORAGE;
7389 type->t &= ~VT_STORAGE;
7390 post_type(type, ad);
7392 /* we push a anonymous symbol which will contain the array
7393 element type */
7394 s = sym_push(SYM_FIELD, type, 0, n);
7395 type->t = t1 | VT_ARRAY | VT_PTR;
7396 type->ref = s;
7400 /* Parse a type declaration (except basic type), and return the type
7401 in 'type'. 'td' is a bitmask indicating which kind of type decl is
7402 expected. 'type' should contain the basic type. 'ad' is the
7403 attribute definition of the basic type. It can be modified by
7404 type_decl().
7406 static void type_decl(CType *type, AttributeDef *ad, int *v, int td)
7408 Sym *s;
7409 CType type1, *type2;
7410 int qualifiers;
7412 while (tok == '*') {
7413 qualifiers = 0;
7414 redo:
7415 next();
7416 switch(tok) {
7417 case TOK_CONST1:
7418 case TOK_CONST2:
7419 case TOK_CONST3:
7420 qualifiers |= VT_CONSTANT;
7421 goto redo;
7422 case TOK_VOLATILE1:
7423 case TOK_VOLATILE2:
7424 case TOK_VOLATILE3:
7425 qualifiers |= VT_VOLATILE;
7426 goto redo;
7427 case TOK_RESTRICT1:
7428 case TOK_RESTRICT2:
7429 case TOK_RESTRICT3:
7430 goto redo;
7432 mk_pointer(type);
7433 type->t |= qualifiers;
7436 /* XXX: clarify attribute handling */
7437 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
7438 parse_attribute(ad);
7440 /* recursive type */
7441 /* XXX: incorrect if abstract type for functions (e.g. 'int ()') */
7442 type1.t = 0; /* XXX: same as int */
7443 if (tok == '(') {
7444 next();
7445 /* XXX: this is not correct to modify 'ad' at this point, but
7446 the syntax is not clear */
7447 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
7448 parse_attribute(ad);
7449 type_decl(&type1, ad, v, td);
7450 skip(')');
7451 } else {
7452 /* type identifier */
7453 if (tok >= TOK_IDENT && (td & TYPE_DIRECT)) {
7454 *v = tok;
7455 next();
7456 } else {
7457 if (!(td & TYPE_ABSTRACT))
7458 expect("identifier");
7459 *v = 0;
7462 post_type(type, ad);
7463 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
7464 parse_attribute(ad);
7465 if (!type1.t)
7466 return;
7467 /* append type at the end of type1 */
7468 type2 = &type1;
7469 for(;;) {
7470 s = type2->ref;
7471 type2 = &s->type;
7472 if (!type2->t) {
7473 *type2 = *type;
7474 break;
7477 *type = type1;
7480 /* compute the lvalue VT_LVAL_xxx needed to match type t. */
7481 static int lvalue_type(int t)
7483 int bt, r;
7484 r = VT_LVAL;
7485 bt = t & VT_BTYPE;
7486 if (bt == VT_BYTE || bt == VT_BOOL)
7487 r |= VT_LVAL_BYTE;
7488 else if (bt == VT_SHORT)
7489 r |= VT_LVAL_SHORT;
7490 else
7491 return r;
7492 if (t & VT_UNSIGNED)
7493 r |= VT_LVAL_UNSIGNED;
7494 return r;
7497 /* indirection with full error checking and bound check */
7498 static void indir(void)
7500 if ((vtop->type.t & VT_BTYPE) != VT_PTR) {
7501 if ((vtop->type.t & VT_BTYPE) == VT_FUNC)
7502 return;
7503 expect("pointer");
7505 if ((vtop->r & VT_LVAL) && !nocode_wanted)
7506 gv(RC_INT);
7507 vtop->type = *pointed_type(&vtop->type);
7508 /* Arrays and functions are never lvalues */
7509 if (!(vtop->type.t & VT_ARRAY)
7510 && (vtop->type.t & VT_BTYPE) != VT_FUNC) {
7511 vtop->r |= lvalue_type(vtop->type.t);
7512 /* if bound checking, the referenced pointer must be checked */
7513 if (do_bounds_check)
7514 vtop->r |= VT_MUSTBOUND;
7518 /* pass a parameter to a function and do type checking and casting */
7519 static void gfunc_param_typed(Sym *func, Sym *arg)
7521 int func_type;
7522 CType type;
7524 func_type = func->c;
7525 if (func_type == FUNC_OLD ||
7526 (func_type == FUNC_ELLIPSIS && arg == NULL)) {
7527 /* default casting : only need to convert float to double */
7528 if ((vtop->type.t & VT_BTYPE) == VT_FLOAT) {
7529 type.t = VT_DOUBLE;
7530 gen_cast(&type);
7532 } else if (arg == NULL) {
7533 error("too many arguments to function");
7534 } else {
7535 type = arg->type;
7536 type.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
7537 gen_assign_cast(&type);
7541 /* parse an expression of the form '(type)' or '(expr)' and return its
7542 type */
7543 static void parse_expr_type(CType *type)
7545 int n;
7546 AttributeDef ad;
7548 skip('(');
7549 if (parse_btype(type, &ad)) {
7550 type_decl(type, &ad, &n, TYPE_ABSTRACT);
7551 } else {
7552 expr_type(type);
7554 skip(')');
7557 static void parse_type(CType *type)
7559 AttributeDef ad;
7560 int n;
7562 if (!parse_btype(type, &ad)) {
7563 expect("type");
7565 type_decl(type, &ad, &n, TYPE_ABSTRACT);
7568 static void vpush_tokc(int t)
7570 CType type;
7571 type.t = t;
7572 vsetc(&type, VT_CONST, &tokc);
7575 static void unary(void)
7577 int n, t, align, size, r;
7578 CType type;
7579 Sym *s;
7580 AttributeDef ad;
7582 /* XXX: GCC 2.95.3 does not generate a table although it should be
7583 better here */
7584 tok_next:
7585 switch(tok) {
7586 case TOK_EXTENSION:
7587 next();
7588 goto tok_next;
7589 case TOK_CINT:
7590 case TOK_CCHAR:
7591 case TOK_LCHAR:
7592 vpushi(tokc.i);
7593 next();
7594 break;
7595 case TOK_CUINT:
7596 vpush_tokc(VT_INT | VT_UNSIGNED);
7597 next();
7598 break;
7599 case TOK_CLLONG:
7600 vpush_tokc(VT_LLONG);
7601 next();
7602 break;
7603 case TOK_CULLONG:
7604 vpush_tokc(VT_LLONG | VT_UNSIGNED);
7605 next();
7606 break;
7607 case TOK_CFLOAT:
7608 vpush_tokc(VT_FLOAT);
7609 next();
7610 break;
7611 case TOK_CDOUBLE:
7612 vpush_tokc(VT_DOUBLE);
7613 next();
7614 break;
7615 case TOK_CLDOUBLE:
7616 vpush_tokc(VT_LDOUBLE);
7617 next();
7618 break;
7619 case TOK___FUNCTION__:
7620 if (!gnu_ext)
7621 goto tok_identifier;
7622 /* fall thru */
7623 case TOK___FUNC__:
7625 void *ptr;
7626 int len;
7627 /* special function name identifier */
7628 len = strlen(funcname) + 1;
7629 /* generate char[len] type */
7630 type.t = VT_BYTE;
7631 mk_pointer(&type);
7632 type.t |= VT_ARRAY;
7633 type.ref->c = len;
7634 vpush_ref(&type, data_section, data_section->data_offset, len);
7635 ptr = section_ptr_add(data_section, len);
7636 memcpy(ptr, funcname, len);
7637 next();
7639 break;
7640 case TOK_LSTR:
7641 #ifdef TCC_TARGET_PE
7642 t = VT_SHORT | VT_UNSIGNED;
7643 #else
7644 t = VT_INT;
7645 #endif
7646 goto str_init;
7647 case TOK_STR:
7648 /* string parsing */
7649 t = VT_BYTE;
7650 str_init:
7651 if (tcc_state->warn_write_strings)
7652 t |= VT_CONSTANT;
7653 type.t = t;
7654 mk_pointer(&type);
7655 type.t |= VT_ARRAY;
7656 memset(&ad, 0, sizeof(AttributeDef));
7657 decl_initializer_alloc(&type, &ad, VT_CONST, 2, 0, 0);
7658 break;
7659 case '(':
7660 next();
7661 /* cast ? */
7662 if (parse_btype(&type, &ad)) {
7663 type_decl(&type, &ad, &n, TYPE_ABSTRACT);
7664 skip(')');
7665 /* check ISOC99 compound literal */
7666 if (tok == '{') {
7667 /* data is allocated locally by default */
7668 if (global_expr)
7669 r = VT_CONST;
7670 else
7671 r = VT_LOCAL;
7672 /* all except arrays are lvalues */
7673 if (!(type.t & VT_ARRAY))
7674 r |= lvalue_type(type.t);
7675 memset(&ad, 0, sizeof(AttributeDef));
7676 decl_initializer_alloc(&type, &ad, r, 1, 0, 0);
7677 } else {
7678 unary();
7679 gen_cast(&type);
7681 } else if (tok == '{') {
7682 /* save all registers */
7683 save_regs(0);
7684 /* statement expression : we do not accept break/continue
7685 inside as GCC does */
7686 block(NULL, NULL, NULL, NULL, 0, 1);
7687 skip(')');
7688 } else {
7689 gexpr();
7690 skip(')');
7692 break;
7693 case '*':
7694 next();
7695 unary();
7696 indir();
7697 break;
7698 case '&':
7699 next();
7700 unary();
7701 /* functions names must be treated as function pointers,
7702 except for unary '&' and sizeof. Since we consider that
7703 functions are not lvalues, we only have to handle it
7704 there and in function calls. */
7705 /* arrays can also be used although they are not lvalues */
7706 if ((vtop->type.t & VT_BTYPE) != VT_FUNC &&
7707 !(vtop->type.t & VT_ARRAY) && !(vtop->type.t & VT_LLOCAL))
7708 test_lvalue();
7709 mk_pointer(&vtop->type);
7710 gaddrof();
7711 break;
7712 case '!':
7713 next();
7714 unary();
7715 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
7716 CType boolean;
7717 boolean.t = VT_BOOL;
7718 gen_cast(&boolean);
7719 vtop->c.i = !vtop->c.i;
7720 } else if ((vtop->r & VT_VALMASK) == VT_CMP)
7721 vtop->c.i = vtop->c.i ^ 1;
7722 else {
7723 save_regs(1);
7724 vseti(VT_JMP, gtst(1, 0));
7726 break;
7727 case '~':
7728 next();
7729 unary();
7730 vpushi(-1);
7731 gen_op('^');
7732 break;
7733 case '+':
7734 next();
7735 /* in order to force cast, we add zero */
7736 unary();
7737 if ((vtop->type.t & VT_BTYPE) == VT_PTR)
7738 error("pointer not accepted for unary plus");
7739 vpushi(0);
7740 gen_op('+');
7741 break;
7742 case TOK_SIZEOF:
7743 case TOK_ALIGNOF1:
7744 case TOK_ALIGNOF2:
7745 t = tok;
7746 next();
7747 if (tok == '(') {
7748 parse_expr_type(&type);
7749 } else {
7750 unary_type(&type);
7752 size = type_size(&type, &align);
7753 if (t == TOK_SIZEOF) {
7754 if (size < 0)
7755 error("sizeof applied to an incomplete type");
7756 vpushi(size);
7757 } else {
7758 vpushi(align);
7760 vtop->type.t |= VT_UNSIGNED;
7761 break;
7763 case TOK_builtin_types_compatible_p:
7765 CType type1, type2;
7766 next();
7767 skip('(');
7768 parse_type(&type1);
7769 skip(',');
7770 parse_type(&type2);
7771 skip(')');
7772 type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
7773 type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
7774 vpushi(is_compatible_types(&type1, &type2));
7776 break;
7777 case TOK_builtin_constant_p:
7779 int saved_nocode_wanted, res;
7780 next();
7781 skip('(');
7782 saved_nocode_wanted = nocode_wanted;
7783 nocode_wanted = 1;
7784 gexpr();
7785 res = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
7786 vpop();
7787 nocode_wanted = saved_nocode_wanted;
7788 skip(')');
7789 vpushi(res);
7791 break;
7792 case TOK_builtin_frame_address:
7794 CType type;
7795 next();
7796 skip('(');
7797 if (tok != TOK_CINT) {
7798 error("__builtin_frame_address only takes integers");
7800 if (tokc.i != 0) {
7801 error("TCC only supports __builtin_frame_address(0)");
7803 next();
7804 skip(')');
7805 type.t = VT_VOID;
7806 mk_pointer(&type);
7807 vset(&type, VT_LOCAL, 0);
7809 break;
7810 #ifdef TCC_TARGET_X86_64
7811 case TOK_builtin_malloc:
7812 tok = TOK_malloc;
7813 goto tok_identifier;
7814 case TOK_builtin_free:
7815 tok = TOK_free;
7816 goto tok_identifier;
7817 #endif
7818 case TOK_INC:
7819 case TOK_DEC:
7820 t = tok;
7821 next();
7822 unary();
7823 inc(0, t);
7824 break;
7825 case '-':
7826 next();
7827 vpushi(0);
7828 unary();
7829 gen_op('-');
7830 break;
7831 case TOK_LAND:
7832 if (!gnu_ext)
7833 goto tok_identifier;
7834 next();
7835 /* allow to take the address of a label */
7836 if (tok < TOK_UIDENT)
7837 expect("label identifier");
7838 s = label_find(tok);
7839 if (!s) {
7840 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
7841 } else {
7842 if (s->r == LABEL_DECLARED)
7843 s->r = LABEL_FORWARD;
7845 if (!s->type.t) {
7846 s->type.t = VT_VOID;
7847 mk_pointer(&s->type);
7848 s->type.t |= VT_STATIC;
7850 vset(&s->type, VT_CONST | VT_SYM, 0);
7851 vtop->sym = s;
7852 next();
7853 break;
7854 default:
7855 tok_identifier:
7856 t = tok;
7857 next();
7858 if (t < TOK_UIDENT)
7859 expect("identifier");
7860 s = sym_find(t);
7861 if (!s) {
7862 if (tok != '(')
7863 error("'%s' undeclared", get_tok_str(t, NULL));
7864 /* for simple function calls, we tolerate undeclared
7865 external reference to int() function */
7866 if (tcc_state->warn_implicit_function_declaration)
7867 warning("implicit declaration of function '%s'",
7868 get_tok_str(t, NULL));
7869 s = external_global_sym(t, &func_old_type, 0);
7871 if ((s->type.t & (VT_STATIC | VT_INLINE | VT_BTYPE)) ==
7872 (VT_STATIC | VT_INLINE | VT_FUNC)) {
7873 /* if referencing an inline function, then we generate a
7874 symbol to it if not already done. It will have the
7875 effect to generate code for it at the end of the
7876 compilation unit. Inline function as always
7877 generated in the text section. */
7878 if (!s->c)
7879 put_extern_sym(s, text_section, 0, 0);
7880 r = VT_SYM | VT_CONST;
7881 } else {
7882 r = s->r;
7884 vset(&s->type, r, s->c);
7885 /* if forward reference, we must point to s */
7886 if (vtop->r & VT_SYM) {
7887 vtop->sym = s;
7888 vtop->c.ul = 0;
7890 break;
7893 /* post operations */
7894 while (1) {
7895 if (tok == TOK_INC || tok == TOK_DEC) {
7896 inc(1, tok);
7897 next();
7898 } else if (tok == '.' || tok == TOK_ARROW) {
7899 /* field */
7900 if (tok == TOK_ARROW)
7901 indir();
7902 test_lvalue();
7903 gaddrof();
7904 next();
7905 /* expect pointer on structure */
7906 if ((vtop->type.t & VT_BTYPE) != VT_STRUCT)
7907 expect("struct or union");
7908 s = vtop->type.ref;
7909 /* find field */
7910 tok |= SYM_FIELD;
7911 while ((s = s->next) != NULL) {
7912 if (s->v == tok)
7913 break;
7915 if (!s)
7916 error("field not found: %s", get_tok_str(tok & ~SYM_FIELD, NULL));
7917 /* add field offset to pointer */
7918 vtop->type = char_pointer_type; /* change type to 'char *' */
7919 vpushi(s->c);
7920 gen_op('+');
7921 /* change type to field type, and set to lvalue */
7922 vtop->type = s->type;
7923 /* an array is never an lvalue */
7924 if (!(vtop->type.t & VT_ARRAY)) {
7925 vtop->r |= lvalue_type(vtop->type.t);
7926 /* if bound checking, the referenced pointer must be checked */
7927 if (do_bounds_check)
7928 vtop->r |= VT_MUSTBOUND;
7930 next();
7931 } else if (tok == '[') {
7932 next();
7933 gexpr();
7934 gen_op('+');
7935 indir();
7936 skip(']');
7937 } else if (tok == '(') {
7938 SValue ret;
7939 Sym *sa;
7940 int nb_args;
7942 /* function call */
7943 if ((vtop->type.t & VT_BTYPE) != VT_FUNC) {
7944 /* pointer test (no array accepted) */
7945 if ((vtop->type.t & (VT_BTYPE | VT_ARRAY)) == VT_PTR) {
7946 vtop->type = *pointed_type(&vtop->type);
7947 if ((vtop->type.t & VT_BTYPE) != VT_FUNC)
7948 goto error_func;
7949 } else {
7950 error_func:
7951 expect("function pointer");
7953 } else {
7954 vtop->r &= ~VT_LVAL; /* no lvalue */
7956 /* get return type */
7957 s = vtop->type.ref;
7958 next();
7959 sa = s->next; /* first parameter */
7960 nb_args = 0;
7961 ret.r2 = VT_CONST;
7962 /* compute first implicit argument if a structure is returned */
7963 if ((s->type.t & VT_BTYPE) == VT_STRUCT) {
7964 /* get some space for the returned structure */
7965 size = type_size(&s->type, &align);
7966 loc = (loc - size) & -align;
7967 ret.type = s->type;
7968 ret.r = VT_LOCAL | VT_LVAL;
7969 /* pass it as 'int' to avoid structure arg passing
7970 problems */
7971 vseti(VT_LOCAL, loc);
7972 ret.c = vtop->c;
7973 nb_args++;
7974 } else {
7975 ret.type = s->type;
7976 /* return in register */
7977 if (is_float(ret.type.t)) {
7978 ret.r = reg_fret(ret.type.t);
7979 } else {
7980 if ((ret.type.t & VT_BTYPE) == VT_LLONG)
7981 ret.r2 = REG_LRET;
7982 ret.r = REG_IRET;
7984 ret.c.i = 0;
7986 if (tok != ')') {
7987 for(;;) {
7988 expr_eq();
7989 gfunc_param_typed(s, sa);
7990 nb_args++;
7991 if (sa)
7992 sa = sa->next;
7993 if (tok == ')')
7994 break;
7995 skip(',');
7998 if (sa)
7999 error("too few arguments to function");
8000 skip(')');
8001 if (!nocode_wanted) {
8002 gfunc_call(nb_args);
8003 } else {
8004 vtop -= (nb_args + 1);
8006 /* return value */
8007 vsetc(&ret.type, ret.r, &ret.c);
8008 vtop->r2 = ret.r2;
8009 } else {
8010 break;
8015 static void uneq(void)
8017 int t;
8019 unary();
8020 if (tok == '=' ||
8021 (tok >= TOK_A_MOD && tok <= TOK_A_DIV) ||
8022 tok == TOK_A_XOR || tok == TOK_A_OR ||
8023 tok == TOK_A_SHL || tok == TOK_A_SAR) {
8024 test_lvalue();
8025 t = tok;
8026 next();
8027 if (t == '=') {
8028 expr_eq();
8029 } else {
8030 vdup();
8031 expr_eq();
8032 gen_op(t & 0x7f);
8034 vstore();
8038 static void expr_prod(void)
8040 int t;
8042 uneq();
8043 while (tok == '*' || tok == '/' || tok == '%') {
8044 t = tok;
8045 next();
8046 uneq();
8047 gen_op(t);
8051 static void expr_sum(void)
8053 int t;
8055 expr_prod();
8056 while (tok == '+' || tok == '-') {
8057 t = tok;
8058 next();
8059 expr_prod();
8060 gen_op(t);
8064 static void expr_shift(void)
8066 int t;
8068 expr_sum();
8069 while (tok == TOK_SHL || tok == TOK_SAR) {
8070 t = tok;
8071 next();
8072 expr_sum();
8073 gen_op(t);
8077 static void expr_cmp(void)
8079 int t;
8081 expr_shift();
8082 while ((tok >= TOK_ULE && tok <= TOK_GT) ||
8083 tok == TOK_ULT || tok == TOK_UGE) {
8084 t = tok;
8085 next();
8086 expr_shift();
8087 gen_op(t);
8091 static void expr_cmpeq(void)
8093 int t;
8095 expr_cmp();
8096 while (tok == TOK_EQ || tok == TOK_NE) {
8097 t = tok;
8098 next();
8099 expr_cmp();
8100 gen_op(t);
8104 static void expr_and(void)
8106 expr_cmpeq();
8107 while (tok == '&') {
8108 next();
8109 expr_cmpeq();
8110 gen_op('&');
8114 static void expr_xor(void)
8116 expr_and();
8117 while (tok == '^') {
8118 next();
8119 expr_and();
8120 gen_op('^');
8124 static void expr_or(void)
8126 expr_xor();
8127 while (tok == '|') {
8128 next();
8129 expr_xor();
8130 gen_op('|');
8134 /* XXX: fix this mess */
8135 static void expr_land_const(void)
8137 expr_or();
8138 while (tok == TOK_LAND) {
8139 next();
8140 expr_or();
8141 gen_op(TOK_LAND);
8145 /* XXX: fix this mess */
8146 static void expr_lor_const(void)
8148 expr_land_const();
8149 while (tok == TOK_LOR) {
8150 next();
8151 expr_land_const();
8152 gen_op(TOK_LOR);
8156 /* only used if non constant */
8157 static void expr_land(void)
8159 int t;
8161 expr_or();
8162 if (tok == TOK_LAND) {
8163 t = 0;
8164 save_regs(1);
8165 for(;;) {
8166 t = gtst(1, t);
8167 if (tok != TOK_LAND) {
8168 vseti(VT_JMPI, t);
8169 break;
8171 next();
8172 expr_or();
8177 static void expr_lor(void)
8179 int t;
8181 expr_land();
8182 if (tok == TOK_LOR) {
8183 t = 0;
8184 save_regs(1);
8185 for(;;) {
8186 t = gtst(0, t);
8187 if (tok != TOK_LOR) {
8188 vseti(VT_JMP, t);
8189 break;
8191 next();
8192 expr_land();
8197 /* XXX: better constant handling */
8198 static void expr_eq(void)
8200 int tt, u, r1, r2, rc, t1, t2, bt1, bt2;
8201 SValue sv;
8202 CType type, type1, type2;
8204 if (const_wanted) {
8205 expr_lor_const();
8206 if (tok == '?') {
8207 CType boolean;
8208 int c;
8209 boolean.t = VT_BOOL;
8210 vdup();
8211 gen_cast(&boolean);
8212 c = vtop->c.i;
8213 vpop();
8214 next();
8215 if (tok != ':' || !gnu_ext) {
8216 vpop();
8217 gexpr();
8219 if (!c)
8220 vpop();
8221 skip(':');
8222 expr_eq();
8223 if (c)
8224 vpop();
8226 } else {
8227 expr_lor();
8228 if (tok == '?') {
8229 next();
8230 if (vtop != vstack) {
8231 /* needed to avoid having different registers saved in
8232 each branch */
8233 if (is_float(vtop->type.t)) {
8234 rc = RC_FLOAT;
8235 #ifdef TCC_TARGET_X86_64
8236 if ((vtop->type.t & VT_BTYPE) == VT_LDOUBLE) {
8237 rc = RC_ST0;
8239 #endif
8241 else
8242 rc = RC_INT;
8243 gv(rc);
8244 save_regs(1);
8246 if (tok == ':' && gnu_ext) {
8247 gv_dup();
8248 tt = gtst(1, 0);
8249 } else {
8250 tt = gtst(1, 0);
8251 gexpr();
8253 type1 = vtop->type;
8254 sv = *vtop; /* save value to handle it later */
8255 vtop--; /* no vpop so that FP stack is not flushed */
8256 skip(':');
8257 u = gjmp(0);
8258 gsym(tt);
8259 expr_eq();
8260 type2 = vtop->type;
8262 t1 = type1.t;
8263 bt1 = t1 & VT_BTYPE;
8264 t2 = type2.t;
8265 bt2 = t2 & VT_BTYPE;
8266 /* cast operands to correct type according to ISOC rules */
8267 if (is_float(bt1) || is_float(bt2)) {
8268 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
8269 type.t = VT_LDOUBLE;
8270 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
8271 type.t = VT_DOUBLE;
8272 } else {
8273 type.t = VT_FLOAT;
8275 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
8276 /* cast to biggest op */
8277 type.t = VT_LLONG;
8278 /* convert to unsigned if it does not fit in a long long */
8279 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED) ||
8280 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED))
8281 type.t |= VT_UNSIGNED;
8282 } else if (bt1 == VT_PTR || bt2 == VT_PTR) {
8283 /* XXX: test pointer compatibility */
8284 type = type1;
8285 } else if (bt1 == VT_FUNC || bt2 == VT_FUNC) {
8286 /* XXX: test function pointer compatibility */
8287 type = type1;
8288 } else if (bt1 == VT_STRUCT || bt2 == VT_STRUCT) {
8289 /* XXX: test structure compatibility */
8290 type = type1;
8291 } else if (bt1 == VT_VOID || bt2 == VT_VOID) {
8292 /* NOTE: as an extension, we accept void on only one side */
8293 type.t = VT_VOID;
8294 } else {
8295 /* integer operations */
8296 type.t = VT_INT;
8297 /* convert to unsigned if it does not fit in an integer */
8298 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED) ||
8299 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED))
8300 type.t |= VT_UNSIGNED;
8303 /* now we convert second operand */
8304 gen_cast(&type);
8305 if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
8306 gaddrof();
8307 rc = RC_INT;
8308 if (is_float(type.t)) {
8309 rc = RC_FLOAT;
8310 #ifdef TCC_TARGET_X86_64
8311 if ((type.t & VT_BTYPE) == VT_LDOUBLE) {
8312 rc = RC_ST0;
8314 #endif
8315 } else if ((type.t & VT_BTYPE) == VT_LLONG) {
8316 /* for long longs, we use fixed registers to avoid having
8317 to handle a complicated move */
8318 rc = RC_IRET;
8321 r2 = gv(rc);
8322 /* this is horrible, but we must also convert first
8323 operand */
8324 tt = gjmp(0);
8325 gsym(u);
8326 /* put again first value and cast it */
8327 *vtop = sv;
8328 gen_cast(&type);
8329 if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
8330 gaddrof();
8331 r1 = gv(rc);
8332 move_reg(r2, r1);
8333 vtop->r = r2;
8334 gsym(tt);
8339 static void gexpr(void)
8341 while (1) {
8342 expr_eq();
8343 if (tok != ',')
8344 break;
8345 vpop();
8346 next();
8350 /* parse an expression and return its type without any side effect. */
8351 static void expr_type(CType *type)
8353 int saved_nocode_wanted;
8355 saved_nocode_wanted = nocode_wanted;
8356 nocode_wanted = 1;
8357 gexpr();
8358 *type = vtop->type;
8359 vpop();
8360 nocode_wanted = saved_nocode_wanted;
8363 /* parse a unary expression and return its type without any side
8364 effect. */
8365 static void unary_type(CType *type)
8367 int a;
8369 a = nocode_wanted;
8370 nocode_wanted = 1;
8371 unary();
8372 *type = vtop->type;
8373 vpop();
8374 nocode_wanted = a;
8377 /* parse a constant expression and return value in vtop. */
8378 static void expr_const1(void)
8380 int a;
8381 a = const_wanted;
8382 const_wanted = 1;
8383 expr_eq();
8384 const_wanted = a;
8387 /* parse an integer constant and return its value. */
8388 static int expr_const(void)
8390 int c;
8391 expr_const1();
8392 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
8393 expect("constant expression");
8394 c = vtop->c.i;
8395 vpop();
8396 return c;
8399 /* return the label token if current token is a label, otherwise
8400 return zero */
8401 static int is_label(void)
8403 int last_tok;
8405 /* fast test first */
8406 if (tok < TOK_UIDENT)
8407 return 0;
8408 /* no need to save tokc because tok is an identifier */
8409 last_tok = tok;
8410 next();
8411 if (tok == ':') {
8412 next();
8413 return last_tok;
8414 } else {
8415 unget_tok(last_tok);
8416 return 0;
8420 static void block(int *bsym, int *csym, int *case_sym, int *def_sym,
8421 int case_reg, int is_expr)
8423 int a, b, c, d;
8424 Sym *s;
8426 /* generate line number info */
8427 if (do_debug &&
8428 (last_line_num != file->line_num || last_ind != ind)) {
8429 put_stabn(N_SLINE, 0, file->line_num, ind - func_ind);
8430 last_ind = ind;
8431 last_line_num = file->line_num;
8434 if (is_expr) {
8435 /* default return value is (void) */
8436 vpushi(0);
8437 vtop->type.t = VT_VOID;
8440 if (tok == TOK_IF) {
8441 /* if test */
8442 next();
8443 skip('(');
8444 gexpr();
8445 skip(')');
8446 a = gtst(1, 0);
8447 block(bsym, csym, case_sym, def_sym, case_reg, 0);
8448 c = tok;
8449 if (c == TOK_ELSE) {
8450 next();
8451 d = gjmp(0);
8452 gsym(a);
8453 block(bsym, csym, case_sym, def_sym, case_reg, 0);
8454 gsym(d); /* patch else jmp */
8455 } else
8456 gsym(a);
8457 } else if (tok == TOK_WHILE) {
8458 next();
8459 d = ind;
8460 skip('(');
8461 gexpr();
8462 skip(')');
8463 a = gtst(1, 0);
8464 b = 0;
8465 block(&a, &b, case_sym, def_sym, case_reg, 0);
8466 gjmp_addr(d);
8467 gsym(a);
8468 gsym_addr(b, d);
8469 } else if (tok == '{') {
8470 Sym *llabel;
8472 next();
8473 /* record local declaration stack position */
8474 s = local_stack;
8475 llabel = local_label_stack;
8476 /* handle local labels declarations */
8477 if (tok == TOK_LABEL) {
8478 next();
8479 for(;;) {
8480 if (tok < TOK_UIDENT)
8481 expect("label identifier");
8482 label_push(&local_label_stack, tok, LABEL_DECLARED);
8483 next();
8484 if (tok == ',') {
8485 next();
8486 } else {
8487 skip(';');
8488 break;
8492 while (tok != '}') {
8493 decl(VT_LOCAL);
8494 if (tok != '}') {
8495 if (is_expr)
8496 vpop();
8497 block(bsym, csym, case_sym, def_sym, case_reg, is_expr);
8500 /* pop locally defined labels */
8501 label_pop(&local_label_stack, llabel);
8502 /* pop locally defined symbols */
8503 if(is_expr) {
8504 /* XXX: this solution makes only valgrind happy...
8505 triggered by gcc.c-torture/execute/20000917-1.c */
8506 Sym *p;
8507 switch(vtop->type.t & VT_BTYPE) {
8508 case VT_PTR:
8509 case VT_STRUCT:
8510 case VT_ENUM:
8511 case VT_FUNC:
8512 for(p=vtop->type.ref;p;p=p->prev)
8513 if(p->prev==s)
8514 error("unsupported expression type");
8517 sym_pop(&local_stack, s);
8518 next();
8519 } else if (tok == TOK_RETURN) {
8520 next();
8521 if (tok != ';') {
8522 gexpr();
8523 gen_assign_cast(&func_vt);
8524 if ((func_vt.t & VT_BTYPE) == VT_STRUCT) {
8525 CType type;
8526 /* if returning structure, must copy it to implicit
8527 first pointer arg location */
8528 #ifdef TCC_ARM_EABI
8529 int align, size;
8530 size = type_size(&func_vt,&align);
8531 if(size <= 4)
8533 if((vtop->r != (VT_LOCAL | VT_LVAL) || (vtop->c.i & 3))
8534 && (align & 3))
8536 int addr;
8537 loc = (loc - size) & -4;
8538 addr = loc;
8539 type = func_vt;
8540 vset(&type, VT_LOCAL | VT_LVAL, addr);
8541 vswap();
8542 vstore();
8543 vset(&int_type, VT_LOCAL | VT_LVAL, addr);
8545 vtop->type = int_type;
8546 gv(RC_IRET);
8547 } else {
8548 #endif
8549 type = func_vt;
8550 mk_pointer(&type);
8551 vset(&type, VT_LOCAL | VT_LVAL, func_vc);
8552 indir();
8553 vswap();
8554 /* copy structure value to pointer */
8555 vstore();
8556 #ifdef TCC_ARM_EABI
8558 #endif
8559 } else if (is_float(func_vt.t)) {
8560 gv(rc_fret(func_vt.t));
8561 } else {
8562 gv(RC_IRET);
8564 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
8566 skip(';');
8567 rsym = gjmp(rsym); /* jmp */
8568 } else if (tok == TOK_BREAK) {
8569 /* compute jump */
8570 if (!bsym)
8571 error("cannot break");
8572 *bsym = gjmp(*bsym);
8573 next();
8574 skip(';');
8575 } else if (tok == TOK_CONTINUE) {
8576 /* compute jump */
8577 if (!csym)
8578 error("cannot continue");
8579 *csym = gjmp(*csym);
8580 next();
8581 skip(';');
8582 } else if (tok == TOK_FOR) {
8583 int e;
8584 next();
8585 skip('(');
8586 if (tok != ';') {
8587 gexpr();
8588 vpop();
8590 skip(';');
8591 d = ind;
8592 c = ind;
8593 a = 0;
8594 b = 0;
8595 if (tok != ';') {
8596 gexpr();
8597 a = gtst(1, 0);
8599 skip(';');
8600 if (tok != ')') {
8601 e = gjmp(0);
8602 c = ind;
8603 gexpr();
8604 vpop();
8605 gjmp_addr(d);
8606 gsym(e);
8608 skip(')');
8609 block(&a, &b, case_sym, def_sym, case_reg, 0);
8610 gjmp_addr(c);
8611 gsym(a);
8612 gsym_addr(b, c);
8613 } else
8614 if (tok == TOK_DO) {
8615 next();
8616 a = 0;
8617 b = 0;
8618 d = ind;
8619 block(&a, &b, case_sym, def_sym, case_reg, 0);
8620 skip(TOK_WHILE);
8621 skip('(');
8622 gsym(b);
8623 gexpr();
8624 c = gtst(0, 0);
8625 gsym_addr(c, d);
8626 skip(')');
8627 gsym(a);
8628 skip(';');
8629 } else
8630 if (tok == TOK_SWITCH) {
8631 next();
8632 skip('(');
8633 gexpr();
8634 /* XXX: other types than integer */
8635 case_reg = gv(RC_INT);
8636 vpop();
8637 skip(')');
8638 a = 0;
8639 b = gjmp(0); /* jump to first case */
8640 c = 0;
8641 block(&a, csym, &b, &c, case_reg, 0);
8642 /* if no default, jmp after switch */
8643 if (c == 0)
8644 c = ind;
8645 /* default label */
8646 gsym_addr(b, c);
8647 /* break label */
8648 gsym(a);
8649 } else
8650 if (tok == TOK_CASE) {
8651 int v1, v2;
8652 if (!case_sym)
8653 expect("switch");
8654 next();
8655 v1 = expr_const();
8656 v2 = v1;
8657 if (gnu_ext && tok == TOK_DOTS) {
8658 next();
8659 v2 = expr_const();
8660 if (v2 < v1)
8661 warning("empty case range");
8663 /* since a case is like a label, we must skip it with a jmp */
8664 b = gjmp(0);
8665 gsym(*case_sym);
8666 vseti(case_reg, 0);
8667 vpushi(v1);
8668 if (v1 == v2) {
8669 gen_op(TOK_EQ);
8670 *case_sym = gtst(1, 0);
8671 } else {
8672 gen_op(TOK_GE);
8673 *case_sym = gtst(1, 0);
8674 vseti(case_reg, 0);
8675 vpushi(v2);
8676 gen_op(TOK_LE);
8677 *case_sym = gtst(1, *case_sym);
8679 gsym(b);
8680 skip(':');
8681 is_expr = 0;
8682 goto block_after_label;
8683 } else
8684 if (tok == TOK_DEFAULT) {
8685 next();
8686 skip(':');
8687 if (!def_sym)
8688 expect("switch");
8689 if (*def_sym)
8690 error("too many 'default'");
8691 *def_sym = ind;
8692 is_expr = 0;
8693 goto block_after_label;
8694 } else
8695 if (tok == TOK_GOTO) {
8696 next();
8697 if (tok == '*' && gnu_ext) {
8698 /* computed goto */
8699 next();
8700 gexpr();
8701 if ((vtop->type.t & VT_BTYPE) != VT_PTR)
8702 expect("pointer");
8703 ggoto();
8704 } else if (tok >= TOK_UIDENT) {
8705 s = label_find(tok);
8706 /* put forward definition if needed */
8707 if (!s) {
8708 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
8709 } else {
8710 if (s->r == LABEL_DECLARED)
8711 s->r = LABEL_FORWARD;
8713 /* label already defined */
8714 if (s->r & LABEL_FORWARD)
8715 s->next = (void *)gjmp((long)s->next);
8716 else
8717 gjmp_addr((long)s->next);
8718 next();
8719 } else {
8720 expect("label identifier");
8722 skip(';');
8723 } else if (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3) {
8724 asm_instr();
8725 } else {
8726 b = is_label();
8727 if (b) {
8728 /* label case */
8729 s = label_find(b);
8730 if (s) {
8731 if (s->r == LABEL_DEFINED)
8732 error("duplicate label '%s'", get_tok_str(s->v, NULL));
8733 gsym((long)s->next);
8734 s->r = LABEL_DEFINED;
8735 } else {
8736 s = label_push(&global_label_stack, b, LABEL_DEFINED);
8738 s->next = (void *)ind;
8739 /* we accept this, but it is a mistake */
8740 block_after_label:
8741 if (tok == '}') {
8742 warning("deprecated use of label at end of compound statement");
8743 } else {
8744 if (is_expr)
8745 vpop();
8746 block(bsym, csym, case_sym, def_sym, case_reg, is_expr);
8748 } else {
8749 /* expression case */
8750 if (tok != ';') {
8751 if (is_expr) {
8752 vpop();
8753 gexpr();
8754 } else {
8755 gexpr();
8756 vpop();
8759 skip(';');
8764 /* t is the array or struct type. c is the array or struct
8765 address. cur_index/cur_field is the pointer to the current
8766 value. 'size_only' is true if only size info is needed (only used
8767 in arrays) */
8768 static void decl_designator(CType *type, Section *sec, unsigned long c,
8769 int *cur_index, Sym **cur_field,
8770 int size_only)
8772 Sym *s, *f;
8773 int notfirst, index, index_last, align, l, nb_elems, elem_size;
8774 CType type1;
8776 notfirst = 0;
8777 elem_size = 0;
8778 nb_elems = 1;
8779 if (gnu_ext && (l = is_label()) != 0)
8780 goto struct_field;
8781 while (tok == '[' || tok == '.') {
8782 if (tok == '[') {
8783 if (!(type->t & VT_ARRAY))
8784 expect("array type");
8785 s = type->ref;
8786 next();
8787 index = expr_const();
8788 if (index < 0 || (s->c >= 0 && index >= s->c))
8789 expect("invalid index");
8790 if (tok == TOK_DOTS && gnu_ext) {
8791 next();
8792 index_last = expr_const();
8793 if (index_last < 0 ||
8794 (s->c >= 0 && index_last >= s->c) ||
8795 index_last < index)
8796 expect("invalid index");
8797 } else {
8798 index_last = index;
8800 skip(']');
8801 if (!notfirst)
8802 *cur_index = index_last;
8803 type = pointed_type(type);
8804 elem_size = type_size(type, &align);
8805 c += index * elem_size;
8806 /* NOTE: we only support ranges for last designator */
8807 nb_elems = index_last - index + 1;
8808 if (nb_elems != 1) {
8809 notfirst = 1;
8810 break;
8812 } else {
8813 next();
8814 l = tok;
8815 next();
8816 struct_field:
8817 if ((type->t & VT_BTYPE) != VT_STRUCT)
8818 expect("struct/union type");
8819 s = type->ref;
8820 l |= SYM_FIELD;
8821 f = s->next;
8822 while (f) {
8823 if (f->v == l)
8824 break;
8825 f = f->next;
8827 if (!f)
8828 expect("field");
8829 if (!notfirst)
8830 *cur_field = f;
8831 /* XXX: fix this mess by using explicit storage field */
8832 type1 = f->type;
8833 type1.t |= (type->t & ~VT_TYPE);
8834 type = &type1;
8835 c += f->c;
8837 notfirst = 1;
8839 if (notfirst) {
8840 if (tok == '=') {
8841 next();
8842 } else {
8843 if (!gnu_ext)
8844 expect("=");
8846 } else {
8847 if (type->t & VT_ARRAY) {
8848 index = *cur_index;
8849 type = pointed_type(type);
8850 c += index * type_size(type, &align);
8851 } else {
8852 f = *cur_field;
8853 if (!f)
8854 error("too many field init");
8855 /* XXX: fix this mess by using explicit storage field */
8856 type1 = f->type;
8857 type1.t |= (type->t & ~VT_TYPE);
8858 type = &type1;
8859 c += f->c;
8862 decl_initializer(type, sec, c, 0, size_only);
8864 /* XXX: make it more general */
8865 if (!size_only && nb_elems > 1) {
8866 unsigned long c_end;
8867 uint8_t *src, *dst;
8868 int i;
8870 if (!sec)
8871 error("range init not supported yet for dynamic storage");
8872 c_end = c + nb_elems * elem_size;
8873 if (c_end > sec->data_allocated)
8874 section_realloc(sec, c_end);
8875 src = sec->data + c;
8876 dst = src;
8877 for(i = 1; i < nb_elems; i++) {
8878 dst += elem_size;
8879 memcpy(dst, src, elem_size);
8884 #define EXPR_VAL 0
8885 #define EXPR_CONST 1
8886 #define EXPR_ANY 2
8888 /* store a value or an expression directly in global data or in local array */
8889 static void init_putv(CType *type, Section *sec, unsigned long c,
8890 int v, int expr_type)
8892 int saved_global_expr, bt, bit_pos, bit_size;
8893 void *ptr;
8894 unsigned long long bit_mask;
8895 CType dtype;
8897 switch(expr_type) {
8898 case EXPR_VAL:
8899 vpushi(v);
8900 break;
8901 case EXPR_CONST:
8902 /* compound literals must be allocated globally in this case */
8903 saved_global_expr = global_expr;
8904 global_expr = 1;
8905 expr_const1();
8906 global_expr = saved_global_expr;
8907 /* NOTE: symbols are accepted */
8908 if ((vtop->r & (VT_VALMASK | VT_LVAL)) != VT_CONST)
8909 error("initializer element is not constant");
8910 break;
8911 case EXPR_ANY:
8912 expr_eq();
8913 break;
8916 dtype = *type;
8917 dtype.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
8919 if (sec) {
8920 /* XXX: not portable */
8921 /* XXX: generate error if incorrect relocation */
8922 gen_assign_cast(&dtype);
8923 bt = type->t & VT_BTYPE;
8924 /* we'll write at most 12 bytes */
8925 if (c + 12 > sec->data_allocated) {
8926 section_realloc(sec, c + 12);
8928 ptr = sec->data + c;
8929 /* XXX: make code faster ? */
8930 if (!(type->t & VT_BITFIELD)) {
8931 bit_pos = 0;
8932 bit_size = 32;
8933 bit_mask = -1LL;
8934 } else {
8935 bit_pos = (vtop->type.t >> VT_STRUCT_SHIFT) & 0x3f;
8936 bit_size = (vtop->type.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
8937 bit_mask = (1LL << bit_size) - 1;
8939 if ((vtop->r & VT_SYM) &&
8940 (bt == VT_BYTE ||
8941 bt == VT_SHORT ||
8942 bt == VT_DOUBLE ||
8943 bt == VT_LDOUBLE ||
8944 bt == VT_LLONG ||
8945 (bt == VT_INT && bit_size != 32)))
8946 error("initializer element is not computable at load time");
8947 switch(bt) {
8948 case VT_BOOL:
8949 vtop->c.i = (vtop->c.i != 0);
8950 case VT_BYTE:
8951 *(char *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
8952 break;
8953 case VT_SHORT:
8954 *(short *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
8955 break;
8956 case VT_DOUBLE:
8957 *(double *)ptr = vtop->c.d;
8958 break;
8959 case VT_LDOUBLE:
8960 *(long double *)ptr = vtop->c.ld;
8961 break;
8962 case VT_LLONG:
8963 *(long long *)ptr |= (vtop->c.ll & bit_mask) << bit_pos;
8964 break;
8965 default:
8966 if (vtop->r & VT_SYM) {
8967 greloc(sec, vtop->sym, c, R_DATA_32);
8969 *(int *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
8970 break;
8972 vtop--;
8973 } else {
8974 vset(&dtype, VT_LOCAL|VT_LVAL, c);
8975 vswap();
8976 vstore();
8977 vpop();
8981 /* put zeros for variable based init */
8982 static void init_putz(CType *t, Section *sec, unsigned long c, int size)
8984 if (sec) {
8985 /* nothing to do because globals are already set to zero */
8986 } else {
8987 vpush_global_sym(&func_old_type, TOK_memset);
8988 vseti(VT_LOCAL, c);
8989 vpushi(0);
8990 vpushi(size);
8991 gfunc_call(3);
8995 /* 't' contains the type and storage info. 'c' is the offset of the
8996 object in section 'sec'. If 'sec' is NULL, it means stack based
8997 allocation. 'first' is true if array '{' must be read (multi
8998 dimension implicit array init handling). 'size_only' is true if
8999 size only evaluation is wanted (only for arrays). */
9000 static void decl_initializer(CType *type, Section *sec, unsigned long c,
9001 int first, int size_only)
9003 int index, array_length, n, no_oblock, nb, parlevel, i;
9004 int size1, align1, expr_type;
9005 Sym *s, *f;
9006 CType *t1;
9008 if (type->t & VT_ARRAY) {
9009 s = type->ref;
9010 n = s->c;
9011 array_length = 0;
9012 t1 = pointed_type(type);
9013 size1 = type_size(t1, &align1);
9015 no_oblock = 1;
9016 if ((first && tok != TOK_LSTR && tok != TOK_STR) ||
9017 tok == '{') {
9018 skip('{');
9019 no_oblock = 0;
9022 /* only parse strings here if correct type (otherwise: handle
9023 them as ((w)char *) expressions */
9024 if ((tok == TOK_LSTR &&
9025 #ifdef TCC_TARGET_PE
9026 (t1->t & VT_BTYPE) == VT_SHORT && (t1->t & VT_UNSIGNED)
9027 #else
9028 (t1->t & VT_BTYPE) == VT_INT
9029 #endif
9030 ) || (tok == TOK_STR && (t1->t & VT_BTYPE) == VT_BYTE)) {
9031 while (tok == TOK_STR || tok == TOK_LSTR) {
9032 int cstr_len, ch;
9033 CString *cstr;
9035 cstr = tokc.cstr;
9036 /* compute maximum number of chars wanted */
9037 if (tok == TOK_STR)
9038 cstr_len = cstr->size;
9039 else
9040 cstr_len = cstr->size / sizeof(nwchar_t);
9041 cstr_len--;
9042 nb = cstr_len;
9043 if (n >= 0 && nb > (n - array_length))
9044 nb = n - array_length;
9045 if (!size_only) {
9046 if (cstr_len > nb)
9047 warning("initializer-string for array is too long");
9048 /* in order to go faster for common case (char
9049 string in global variable, we handle it
9050 specifically */
9051 if (sec && tok == TOK_STR && size1 == 1) {
9052 memcpy(sec->data + c + array_length, cstr->data, nb);
9053 } else {
9054 for(i=0;i<nb;i++) {
9055 if (tok == TOK_STR)
9056 ch = ((unsigned char *)cstr->data)[i];
9057 else
9058 ch = ((nwchar_t *)cstr->data)[i];
9059 init_putv(t1, sec, c + (array_length + i) * size1,
9060 ch, EXPR_VAL);
9064 array_length += nb;
9065 next();
9067 /* only add trailing zero if enough storage (no
9068 warning in this case since it is standard) */
9069 if (n < 0 || array_length < n) {
9070 if (!size_only) {
9071 init_putv(t1, sec, c + (array_length * size1), 0, EXPR_VAL);
9073 array_length++;
9075 } else {
9076 index = 0;
9077 while (tok != '}') {
9078 decl_designator(type, sec, c, &index, NULL, size_only);
9079 if (n >= 0 && index >= n)
9080 error("index too large");
9081 /* must put zero in holes (note that doing it that way
9082 ensures that it even works with designators) */
9083 if (!size_only && array_length < index) {
9084 init_putz(t1, sec, c + array_length * size1,
9085 (index - array_length) * size1);
9087 index++;
9088 if (index > array_length)
9089 array_length = index;
9090 /* special test for multi dimensional arrays (may not
9091 be strictly correct if designators are used at the
9092 same time) */
9093 if (index >= n && no_oblock)
9094 break;
9095 if (tok == '}')
9096 break;
9097 skip(',');
9100 if (!no_oblock)
9101 skip('}');
9102 /* put zeros at the end */
9103 if (!size_only && n >= 0 && array_length < n) {
9104 init_putz(t1, sec, c + array_length * size1,
9105 (n - array_length) * size1);
9107 /* patch type size if needed */
9108 if (n < 0)
9109 s->c = array_length;
9110 } else if ((type->t & VT_BTYPE) == VT_STRUCT &&
9111 (sec || !first || tok == '{')) {
9112 int par_count;
9114 /* NOTE: the previous test is a specific case for automatic
9115 struct/union init */
9116 /* XXX: union needs only one init */
9118 /* XXX: this test is incorrect for local initializers
9119 beginning with ( without {. It would be much more difficult
9120 to do it correctly (ideally, the expression parser should
9121 be used in all cases) */
9122 par_count = 0;
9123 if (tok == '(') {
9124 AttributeDef ad1;
9125 CType type1;
9126 next();
9127 while (tok == '(') {
9128 par_count++;
9129 next();
9131 if (!parse_btype(&type1, &ad1))
9132 expect("cast");
9133 type_decl(&type1, &ad1, &n, TYPE_ABSTRACT);
9134 #if 0
9135 if (!is_assignable_types(type, &type1))
9136 error("invalid type for cast");
9137 #endif
9138 skip(')');
9140 no_oblock = 1;
9141 if (first || tok == '{') {
9142 skip('{');
9143 no_oblock = 0;
9145 s = type->ref;
9146 f = s->next;
9147 array_length = 0;
9148 index = 0;
9149 n = s->c;
9150 while (tok != '}') {
9151 decl_designator(type, sec, c, NULL, &f, size_only);
9152 index = f->c;
9153 if (!size_only && array_length < index) {
9154 init_putz(type, sec, c + array_length,
9155 index - array_length);
9157 index = index + type_size(&f->type, &align1);
9158 if (index > array_length)
9159 array_length = index;
9160 f = f->next;
9161 if (no_oblock && f == NULL)
9162 break;
9163 if (tok == '}')
9164 break;
9165 skip(',');
9167 /* put zeros at the end */
9168 if (!size_only && array_length < n) {
9169 init_putz(type, sec, c + array_length,
9170 n - array_length);
9172 if (!no_oblock)
9173 skip('}');
9174 while (par_count) {
9175 skip(')');
9176 par_count--;
9178 } else if (tok == '{') {
9179 next();
9180 decl_initializer(type, sec, c, first, size_only);
9181 skip('}');
9182 } else if (size_only) {
9183 /* just skip expression */
9184 parlevel = 0;
9185 while ((parlevel > 0 || (tok != '}' && tok != ',')) &&
9186 tok != -1) {
9187 if (tok == '(')
9188 parlevel++;
9189 else if (tok == ')')
9190 parlevel--;
9191 next();
9193 } else {
9194 /* currently, we always use constant expression for globals
9195 (may change for scripting case) */
9196 expr_type = EXPR_CONST;
9197 if (!sec)
9198 expr_type = EXPR_ANY;
9199 init_putv(type, sec, c, 0, expr_type);
9203 /* parse an initializer for type 't' if 'has_init' is non zero, and
9204 allocate space in local or global data space ('r' is either
9205 VT_LOCAL or VT_CONST). If 'v' is non zero, then an associated
9206 variable 'v' of scope 'scope' is declared before initializers are
9207 parsed. If 'v' is zero, then a reference to the new object is put
9208 in the value stack. If 'has_init' is 2, a special parsing is done
9209 to handle string constants. */
9210 static void decl_initializer_alloc(CType *type, AttributeDef *ad, int r,
9211 int has_init, int v, int scope)
9213 int size, align, addr, data_offset;
9214 int level;
9215 ParseState saved_parse_state = {0};
9216 TokenString init_str;
9217 Section *sec;
9219 size = type_size(type, &align);
9220 /* If unknown size, we must evaluate it before
9221 evaluating initializers because
9222 initializers can generate global data too
9223 (e.g. string pointers or ISOC99 compound
9224 literals). It also simplifies local
9225 initializers handling */
9226 tok_str_new(&init_str);
9227 if (size < 0) {
9228 if (!has_init)
9229 error("unknown type size");
9230 /* get all init string */
9231 if (has_init == 2) {
9232 /* only get strings */
9233 while (tok == TOK_STR || tok == TOK_LSTR) {
9234 tok_str_add_tok(&init_str);
9235 next();
9237 } else {
9238 level = 0;
9239 while (level > 0 || (tok != ',' && tok != ';')) {
9240 if (tok < 0)
9241 error("unexpected end of file in initializer");
9242 tok_str_add_tok(&init_str);
9243 if (tok == '{')
9244 level++;
9245 else if (tok == '}') {
9246 level--;
9247 if (level <= 0) {
9248 next();
9249 break;
9252 next();
9255 tok_str_add(&init_str, -1);
9256 tok_str_add(&init_str, 0);
9258 /* compute size */
9259 save_parse_state(&saved_parse_state);
9261 macro_ptr = init_str.str;
9262 next();
9263 decl_initializer(type, NULL, 0, 1, 1);
9264 /* prepare second initializer parsing */
9265 macro_ptr = init_str.str;
9266 next();
9268 /* if still unknown size, error */
9269 size = type_size(type, &align);
9270 if (size < 0)
9271 error("unknown type size");
9273 /* take into account specified alignment if bigger */
9274 if (ad->aligned) {
9275 if (ad->aligned > align)
9276 align = ad->aligned;
9277 } else if (ad->packed) {
9278 align = 1;
9280 if ((r & VT_VALMASK) == VT_LOCAL) {
9281 sec = NULL;
9282 if (do_bounds_check && (type->t & VT_ARRAY))
9283 loc--;
9284 loc = (loc - size) & -align;
9285 addr = loc;
9286 /* handles bounds */
9287 /* XXX: currently, since we do only one pass, we cannot track
9288 '&' operators, so we add only arrays */
9289 if (do_bounds_check && (type->t & VT_ARRAY)) {
9290 unsigned long *bounds_ptr;
9291 /* add padding between regions */
9292 loc--;
9293 /* then add local bound info */
9294 bounds_ptr = section_ptr_add(lbounds_section, 2 * sizeof(unsigned long));
9295 bounds_ptr[0] = addr;
9296 bounds_ptr[1] = size;
9298 if (v) {
9299 /* local variable */
9300 sym_push(v, type, r, addr);
9301 } else {
9302 /* push local reference */
9303 vset(type, r, addr);
9305 } else {
9306 Sym *sym;
9308 sym = NULL;
9309 if (v && scope == VT_CONST) {
9310 /* see if the symbol was already defined */
9311 sym = sym_find(v);
9312 if (sym) {
9313 if (!is_compatible_types(&sym->type, type))
9314 error("incompatible types for redefinition of '%s'",
9315 get_tok_str(v, NULL));
9316 if (sym->type.t & VT_EXTERN) {
9317 /* if the variable is extern, it was not allocated */
9318 sym->type.t &= ~VT_EXTERN;
9319 /* set array size if it was ommited in extern
9320 declaration */
9321 if ((sym->type.t & VT_ARRAY) &&
9322 sym->type.ref->c < 0 &&
9323 type->ref->c >= 0)
9324 sym->type.ref->c = type->ref->c;
9325 } else {
9326 /* we accept several definitions of the same
9327 global variable. this is tricky, because we
9328 must play with the SHN_COMMON type of the symbol */
9329 /* XXX: should check if the variable was already
9330 initialized. It is incorrect to initialized it
9331 twice */
9332 /* no init data, we won't add more to the symbol */
9333 if (!has_init)
9334 goto no_alloc;
9339 /* allocate symbol in corresponding section */
9340 sec = ad->section;
9341 if (!sec) {
9342 if (has_init)
9343 sec = data_section;
9344 else if (tcc_state->nocommon)
9345 sec = bss_section;
9347 if (sec) {
9348 data_offset = sec->data_offset;
9349 data_offset = (data_offset + align - 1) & -align;
9350 addr = data_offset;
9351 /* very important to increment global pointer at this time
9352 because initializers themselves can create new initializers */
9353 data_offset += size;
9354 /* add padding if bound check */
9355 if (do_bounds_check)
9356 data_offset++;
9357 sec->data_offset = data_offset;
9358 /* allocate section space to put the data */
9359 if (sec->sh_type != SHT_NOBITS &&
9360 data_offset > sec->data_allocated)
9361 section_realloc(sec, data_offset);
9362 /* align section if needed */
9363 if (align > sec->sh_addralign)
9364 sec->sh_addralign = align;
9365 } else {
9366 addr = 0; /* avoid warning */
9369 if (v) {
9370 if (scope != VT_CONST || !sym) {
9371 sym = sym_push(v, type, r | VT_SYM, 0);
9373 /* update symbol definition */
9374 if (sec) {
9375 put_extern_sym(sym, sec, addr, size);
9376 } else {
9377 ElfW(Sym) *esym;
9378 /* put a common area */
9379 put_extern_sym(sym, NULL, align, size);
9380 /* XXX: find a nicer way */
9381 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
9382 esym->st_shndx = SHN_COMMON;
9384 } else {
9385 CValue cval;
9387 /* push global reference */
9388 sym = get_sym_ref(type, sec, addr, size);
9389 cval.ul = 0;
9390 vsetc(type, VT_CONST | VT_SYM, &cval);
9391 vtop->sym = sym;
9394 /* handles bounds now because the symbol must be defined
9395 before for the relocation */
9396 if (do_bounds_check) {
9397 unsigned long *bounds_ptr;
9399 greloc(bounds_section, sym, bounds_section->data_offset, R_DATA_32);
9400 /* then add global bound info */
9401 bounds_ptr = section_ptr_add(bounds_section, 2 * sizeof(long));
9402 bounds_ptr[0] = 0; /* relocated */
9403 bounds_ptr[1] = size;
9406 if (has_init) {
9407 decl_initializer(type, sec, addr, 1, 0);
9408 /* restore parse state if needed */
9409 if (init_str.str) {
9410 tok_str_free(init_str.str);
9411 restore_parse_state(&saved_parse_state);
9414 no_alloc: ;
9417 void put_func_debug(Sym *sym)
9419 char buf[512];
9421 /* stabs info */
9422 /* XXX: we put here a dummy type */
9423 snprintf(buf, sizeof(buf), "%s:%c1",
9424 funcname, sym->type.t & VT_STATIC ? 'f' : 'F');
9425 put_stabs_r(buf, N_FUN, 0, file->line_num, 0,
9426 cur_text_section, sym->c);
9427 /* //gr gdb wants a line at the function */
9428 put_stabn(N_SLINE, 0, file->line_num, 0);
9429 last_ind = 0;
9430 last_line_num = 0;
9433 /* parse an old style function declaration list */
9434 /* XXX: check multiple parameter */
9435 static void func_decl_list(Sym *func_sym)
9437 AttributeDef ad;
9438 int v;
9439 Sym *s;
9440 CType btype, type;
9442 /* parse each declaration */
9443 while (tok != '{' && tok != ';' && tok != ',' && tok != TOK_EOF) {
9444 if (!parse_btype(&btype, &ad))
9445 expect("declaration list");
9446 if (((btype.t & VT_BTYPE) == VT_ENUM ||
9447 (btype.t & VT_BTYPE) == VT_STRUCT) &&
9448 tok == ';') {
9449 /* we accept no variable after */
9450 } else {
9451 for(;;) {
9452 type = btype;
9453 type_decl(&type, &ad, &v, TYPE_DIRECT);
9454 /* find parameter in function parameter list */
9455 s = func_sym->next;
9456 while (s != NULL) {
9457 if ((s->v & ~SYM_FIELD) == v)
9458 goto found;
9459 s = s->next;
9461 error("declaration for parameter '%s' but no such parameter",
9462 get_tok_str(v, NULL));
9463 found:
9464 /* check that no storage specifier except 'register' was given */
9465 if (type.t & VT_STORAGE)
9466 error("storage class specified for '%s'", get_tok_str(v, NULL));
9467 convert_parameter_type(&type);
9468 /* we can add the type (NOTE: it could be local to the function) */
9469 s->type = type;
9470 /* accept other parameters */
9471 if (tok == ',')
9472 next();
9473 else
9474 break;
9477 skip(';');
9481 /* parse a function defined by symbol 'sym' and generate its code in
9482 'cur_text_section' */
9483 static void gen_function(Sym *sym)
9485 int saved_nocode_wanted = nocode_wanted;
9486 nocode_wanted = 0;
9487 ind = cur_text_section->data_offset;
9488 /* NOTE: we patch the symbol size later */
9489 put_extern_sym(sym, cur_text_section, ind, 0);
9490 funcname = get_tok_str(sym->v, NULL);
9491 func_ind = ind;
9492 /* put debug symbol */
9493 if (do_debug)
9494 put_func_debug(sym);
9495 /* push a dummy symbol to enable local sym storage */
9496 sym_push2(&local_stack, SYM_FIELD, 0, 0);
9497 gfunc_prolog(&sym->type);
9498 rsym = 0;
9499 block(NULL, NULL, NULL, NULL, 0, 0);
9500 gsym(rsym);
9501 gfunc_epilog();
9502 cur_text_section->data_offset = ind;
9503 label_pop(&global_label_stack, NULL);
9504 sym_pop(&local_stack, NULL); /* reset local stack */
9505 /* end of function */
9506 /* patch symbol size */
9507 ((ElfW(Sym) *)symtab_section->data)[sym->c].st_size =
9508 ind - func_ind;
9509 if (do_debug) {
9510 put_stabn(N_FUN, 0, 0, ind - func_ind);
9512 /* It's better to crash than to generate wrong code */
9513 cur_text_section = NULL;
9514 funcname = ""; /* for safety */
9515 func_vt.t = VT_VOID; /* for safety */
9516 ind = 0; /* for safety */
9517 nocode_wanted = saved_nocode_wanted;
9520 static void gen_inline_functions(void)
9522 Sym *sym;
9523 CType *type;
9524 int *str, inline_generated;
9526 /* iterate while inline function are referenced */
9527 for(;;) {
9528 inline_generated = 0;
9529 for(sym = global_stack; sym != NULL; sym = sym->prev) {
9530 type = &sym->type;
9531 if (((type->t & VT_BTYPE) == VT_FUNC) &&
9532 (type->t & (VT_STATIC | VT_INLINE)) ==
9533 (VT_STATIC | VT_INLINE) &&
9534 sym->c != 0) {
9535 /* the function was used: generate its code and
9536 convert it to a normal function */
9537 str = INLINE_DEF(sym->r);
9538 sym->r = VT_SYM | VT_CONST;
9539 sym->type.t &= ~VT_INLINE;
9541 macro_ptr = str;
9542 next();
9543 cur_text_section = text_section;
9544 gen_function(sym);
9545 macro_ptr = NULL; /* fail safe */
9547 tok_str_free(str);
9548 inline_generated = 1;
9551 if (!inline_generated)
9552 break;
9555 /* free all remaining inline function tokens */
9556 for(sym = global_stack; sym != NULL; sym = sym->prev) {
9557 type = &sym->type;
9558 if (((type->t & VT_BTYPE) == VT_FUNC) &&
9559 (type->t & (VT_STATIC | VT_INLINE)) ==
9560 (VT_STATIC | VT_INLINE)) {
9561 //gr printf("sym %d %s\n", sym->r, get_tok_str(sym->v, NULL));
9562 if (sym->r == (VT_SYM | VT_CONST)) //gr beware!
9563 continue;
9564 str = INLINE_DEF(sym->r);
9565 tok_str_free(str);
9566 sym->r = 0; /* fail safe */
9571 /* 'l' is VT_LOCAL or VT_CONST to define default storage type */
9572 static void decl(int l)
9574 int v, has_init, r;
9575 CType type, btype;
9576 Sym *sym;
9577 AttributeDef ad;
9579 while (1) {
9580 if (!parse_btype(&btype, &ad)) {
9581 /* skip redundant ';' */
9582 /* XXX: find more elegant solution */
9583 if (tok == ';') {
9584 next();
9585 continue;
9587 if (l == VT_CONST &&
9588 (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3)) {
9589 /* global asm block */
9590 asm_global_instr();
9591 continue;
9593 /* special test for old K&R protos without explicit int
9594 type. Only accepted when defining global data */
9595 if (l == VT_LOCAL || tok < TOK_DEFINE)
9596 break;
9597 btype.t = VT_INT;
9599 if (((btype.t & VT_BTYPE) == VT_ENUM ||
9600 (btype.t & VT_BTYPE) == VT_STRUCT) &&
9601 tok == ';') {
9602 /* we accept no variable after */
9603 next();
9604 continue;
9606 while (1) { /* iterate thru each declaration */
9607 type = btype;
9608 type_decl(&type, &ad, &v, TYPE_DIRECT);
9609 #if 0
9611 char buf[500];
9612 type_to_str(buf, sizeof(buf), t, get_tok_str(v, NULL));
9613 printf("type = '%s'\n", buf);
9615 #endif
9616 if ((type.t & VT_BTYPE) == VT_FUNC) {
9617 /* if old style function prototype, we accept a
9618 declaration list */
9619 sym = type.ref;
9620 if (sym->c == FUNC_OLD)
9621 func_decl_list(sym);
9624 if (tok == '{') {
9625 if (l == VT_LOCAL)
9626 error("cannot use local functions");
9627 if ((type.t & VT_BTYPE) != VT_FUNC)
9628 expect("function definition");
9630 /* reject abstract declarators in function definition */
9631 sym = type.ref;
9632 while ((sym = sym->next) != NULL)
9633 if (!(sym->v & ~SYM_FIELD))
9634 expect("identifier");
9636 /* XXX: cannot do better now: convert extern line to static inline */
9637 if ((type.t & (VT_EXTERN | VT_INLINE)) == (VT_EXTERN | VT_INLINE))
9638 type.t = (type.t & ~VT_EXTERN) | VT_STATIC;
9640 sym = sym_find(v);
9641 if (sym) {
9642 if ((sym->type.t & VT_BTYPE) != VT_FUNC)
9643 goto func_error1;
9644 /* specific case: if not func_call defined, we put
9645 the one of the prototype */
9646 /* XXX: should have default value */
9647 r = sym->type.ref->r;
9648 if (FUNC_CALL(r) != FUNC_CDECL
9649 && FUNC_CALL(type.ref->r) == FUNC_CDECL)
9650 FUNC_CALL(type.ref->r) = FUNC_CALL(r);
9651 if (FUNC_EXPORT(r))
9652 FUNC_EXPORT(type.ref->r) = 1;
9654 if (!is_compatible_types(&sym->type, &type)) {
9655 func_error1:
9656 error("incompatible types for redefinition of '%s'",
9657 get_tok_str(v, NULL));
9659 /* if symbol is already defined, then put complete type */
9660 sym->type = type;
9661 } else {
9662 /* put function symbol */
9663 sym = global_identifier_push(v, type.t, 0);
9664 sym->type.ref = type.ref;
9667 /* static inline functions are just recorded as a kind
9668 of macro. Their code will be emitted at the end of
9669 the compilation unit only if they are used */
9670 if ((type.t & (VT_INLINE | VT_STATIC)) ==
9671 (VT_INLINE | VT_STATIC)) {
9672 TokenString func_str;
9673 int block_level;
9675 tok_str_new(&func_str);
9677 block_level = 0;
9678 for(;;) {
9679 int t;
9680 if (tok == TOK_EOF)
9681 error("unexpected end of file");
9682 tok_str_add_tok(&func_str);
9683 t = tok;
9684 next();
9685 if (t == '{') {
9686 block_level++;
9687 } else if (t == '}') {
9688 block_level--;
9689 if (block_level == 0)
9690 break;
9693 tok_str_add(&func_str, -1);
9694 tok_str_add(&func_str, 0);
9695 INLINE_DEF(sym->r) = func_str.str;
9696 } else {
9697 /* compute text section */
9698 cur_text_section = ad.section;
9699 if (!cur_text_section)
9700 cur_text_section = text_section;
9701 sym->r = VT_SYM | VT_CONST;
9702 gen_function(sym);
9704 break;
9705 } else {
9706 if (btype.t & VT_TYPEDEF) {
9707 /* save typedefed type */
9708 /* XXX: test storage specifiers ? */
9709 sym = sym_push(v, &type, 0, 0);
9710 sym->type.t |= VT_TYPEDEF;
9711 } else if ((type.t & VT_BTYPE) == VT_FUNC) {
9712 /* external function definition */
9713 /* specific case for func_call attribute */
9714 if (ad.func_attr)
9715 type.ref->r = ad.func_attr;
9716 external_sym(v, &type, 0);
9717 } else {
9718 /* not lvalue if array */
9719 r = 0;
9720 if (!(type.t & VT_ARRAY))
9721 r |= lvalue_type(type.t);
9722 has_init = (tok == '=');
9723 if ((btype.t & VT_EXTERN) ||
9724 ((type.t & VT_ARRAY) && (type.t & VT_STATIC) &&
9725 !has_init && l == VT_CONST && type.ref->c < 0)) {
9726 /* external variable */
9727 /* NOTE: as GCC, uninitialized global static
9728 arrays of null size are considered as
9729 extern */
9730 external_sym(v, &type, r);
9731 } else {
9732 type.t |= (btype.t & VT_STATIC); /* Retain "static". */
9733 if (type.t & VT_STATIC)
9734 r |= VT_CONST;
9735 else
9736 r |= l;
9737 if (has_init)
9738 next();
9739 decl_initializer_alloc(&type, &ad, r,
9740 has_init, v, l);
9743 if (tok != ',') {
9744 skip(';');
9745 break;
9747 next();
9753 /* better than nothing, but needs extension to handle '-E' option
9754 correctly too */
9755 static void preprocess_init(TCCState *s1)
9757 s1->include_stack_ptr = s1->include_stack;
9758 /* XXX: move that before to avoid having to initialize
9759 file->ifdef_stack_ptr ? */
9760 s1->ifdef_stack_ptr = s1->ifdef_stack;
9761 file->ifdef_stack_ptr = s1->ifdef_stack_ptr;
9763 /* XXX: not ANSI compliant: bound checking says error */
9764 vtop = vstack - 1;
9765 s1->pack_stack[0] = 0;
9766 s1->pack_stack_ptr = s1->pack_stack;
9769 /* compile the C file opened in 'file'. Return non zero if errors. */
9770 static int tcc_compile(TCCState *s1)
9772 Sym *define_start;
9773 char buf[512];
9774 volatile int section_sym;
9776 #ifdef INC_DEBUG
9777 printf("%s: **** new file\n", file->filename);
9778 #endif
9779 preprocess_init(s1);
9781 cur_text_section = NULL;
9782 funcname = "";
9783 anon_sym = SYM_FIRST_ANOM;
9785 /* file info: full path + filename */
9786 section_sym = 0; /* avoid warning */
9787 if (do_debug) {
9788 section_sym = put_elf_sym(symtab_section, 0, 0,
9789 ELFW(ST_INFO)(STB_LOCAL, STT_SECTION), 0,
9790 text_section->sh_num, NULL);
9791 getcwd(buf, sizeof(buf));
9792 #ifdef _WIN32
9793 normalize_slashes(buf);
9794 #endif
9795 pstrcat(buf, sizeof(buf), "/");
9796 put_stabs_r(buf, N_SO, 0, 0,
9797 text_section->data_offset, text_section, section_sym);
9798 put_stabs_r(file->filename, N_SO, 0, 0,
9799 text_section->data_offset, text_section, section_sym);
9801 /* an elf symbol of type STT_FILE must be put so that STB_LOCAL
9802 symbols can be safely used */
9803 put_elf_sym(symtab_section, 0, 0,
9804 ELFW(ST_INFO)(STB_LOCAL, STT_FILE), 0,
9805 SHN_ABS, file->filename);
9807 /* define some often used types */
9808 int_type.t = VT_INT;
9810 char_pointer_type.t = VT_BYTE;
9811 mk_pointer(&char_pointer_type);
9813 func_old_type.t = VT_FUNC;
9814 func_old_type.ref = sym_push(SYM_FIELD, &int_type, FUNC_CDECL, FUNC_OLD);
9816 #if defined(TCC_ARM_EABI) && defined(TCC_ARM_VFP)
9817 float_type.t = VT_FLOAT;
9818 double_type.t = VT_DOUBLE;
9820 func_float_type.t = VT_FUNC;
9821 func_float_type.ref = sym_push(SYM_FIELD, &float_type, FUNC_CDECL, FUNC_OLD);
9822 func_double_type.t = VT_FUNC;
9823 func_double_type.ref = sym_push(SYM_FIELD, &double_type, FUNC_CDECL, FUNC_OLD);
9824 #endif
9826 #if 0
9827 /* define 'void *alloca(unsigned int)' builtin function */
9829 Sym *s1;
9831 p = anon_sym++;
9832 sym = sym_push(p, mk_pointer(VT_VOID), FUNC_CDECL, FUNC_NEW);
9833 s1 = sym_push(SYM_FIELD, VT_UNSIGNED | VT_INT, 0, 0);
9834 s1->next = NULL;
9835 sym->next = s1;
9836 sym_push(TOK_alloca, VT_FUNC | (p << VT_STRUCT_SHIFT), VT_CONST, 0);
9838 #endif
9840 define_start = define_stack;
9841 nocode_wanted = 1;
9843 if (setjmp(s1->error_jmp_buf) == 0) {
9844 s1->nb_errors = 0;
9845 s1->error_set_jmp_enabled = 1;
9847 ch = file->buf_ptr[0];
9848 tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
9849 parse_flags = PARSE_FLAG_PREPROCESS | PARSE_FLAG_TOK_NUM;
9850 next();
9851 decl(VT_CONST);
9852 if (tok != TOK_EOF)
9853 expect("declaration");
9855 /* end of translation unit info */
9856 if (do_debug) {
9857 put_stabs_r(NULL, N_SO, 0, 0,
9858 text_section->data_offset, text_section, section_sym);
9861 s1->error_set_jmp_enabled = 0;
9863 /* reset define stack, but leave -Dsymbols (may be incorrect if
9864 they are undefined) */
9865 free_defines(define_start);
9867 gen_inline_functions();
9869 sym_pop(&global_stack, NULL);
9870 sym_pop(&local_stack, NULL);
9872 return s1->nb_errors != 0 ? -1 : 0;
9875 /* Preprocess the current file */
9876 /* XXX: add line and file infos,
9877 * XXX: add options to preserve spaces (partly done, only spaces in macro are
9878 * not preserved)
9880 static int tcc_preprocess(TCCState *s1)
9882 Sym *define_start;
9883 BufferedFile *file_ref;
9884 int token_seen, line_ref;
9886 preprocess_init(s1);
9887 define_start = define_stack;
9888 ch = file->buf_ptr[0];
9890 tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
9891 parse_flags = PARSE_FLAG_ASM_COMMENTS | PARSE_FLAG_PREPROCESS |
9892 PARSE_FLAG_LINEFEED;
9894 token_seen = 0;
9895 line_ref = 0;
9896 file_ref = NULL;
9898 for (;;) {
9899 next();
9900 if (tok == TOK_EOF) {
9901 break;
9902 } else if (tok == TOK_LINEFEED) {
9903 if (!token_seen)
9904 continue;
9905 ++line_ref;
9906 token_seen = 0;
9907 } else if (token_seen) {
9908 fwrite(tok_spaces.data, tok_spaces.size, 1, s1->outfile);
9909 } else {
9910 int d = file->line_num - line_ref;
9911 if (file != file_ref || d < 0 || d >= 8)
9912 fprintf(s1->outfile, "# %d \"%s\"\n", file->line_num, file->filename);
9913 else
9914 while (d)
9915 fputs("\n", s1->outfile), --d;
9916 line_ref = (file_ref = file)->line_num;
9917 token_seen = 1;
9919 fputs(get_tok_str(tok, &tokc), s1->outfile);
9921 free_defines(define_start);
9922 return 0;
9925 #ifdef LIBTCC
9926 int tcc_compile_string(TCCState *s, const char *str)
9928 BufferedFile bf1, *bf = &bf1;
9929 int ret, len;
9930 char *buf;
9932 /* init file structure */
9933 bf->fd = -1;
9934 /* XXX: avoid copying */
9935 len = strlen(str);
9936 buf = tcc_malloc(len + 1);
9937 if (!buf)
9938 return -1;
9939 memcpy(buf, str, len);
9940 buf[len] = CH_EOB;
9941 bf->buf_ptr = buf;
9942 bf->buf_end = buf + len;
9943 pstrcpy(bf->filename, sizeof(bf->filename), "<string>");
9944 bf->line_num = 1;
9945 file = bf;
9946 ret = tcc_compile(s);
9947 file = NULL;
9948 tcc_free(buf);
9950 /* currently, no need to close */
9951 return ret;
9953 #endif
9955 /* define a preprocessor symbol. A value can also be provided with the '=' operator */
9956 void tcc_define_symbol(TCCState *s1, const char *sym, const char *value)
9958 BufferedFile bf1, *bf = &bf1;
9960 pstrcpy(bf->buffer, IO_BUF_SIZE, sym);
9961 pstrcat(bf->buffer, IO_BUF_SIZE, " ");
9962 /* default value */
9963 if (!value)
9964 value = "1";
9965 pstrcat(bf->buffer, IO_BUF_SIZE, value);
9967 /* init file structure */
9968 bf->fd = -1;
9969 bf->buf_ptr = bf->buffer;
9970 bf->buf_end = bf->buffer + strlen(bf->buffer);
9971 *bf->buf_end = CH_EOB;
9972 bf->filename[0] = '\0';
9973 bf->line_num = 1;
9974 file = bf;
9976 s1->include_stack_ptr = s1->include_stack;
9978 /* parse with define parser */
9979 ch = file->buf_ptr[0];
9980 next_nomacro();
9981 parse_define();
9982 file = NULL;
9985 /* undefine a preprocessor symbol */
9986 void tcc_undefine_symbol(TCCState *s1, const char *sym)
9988 TokenSym *ts;
9989 Sym *s;
9990 ts = tok_alloc(sym, strlen(sym));
9991 s = define_find(ts->tok);
9992 /* undefine symbol by putting an invalid name */
9993 if (s)
9994 define_undef(s);
9997 #ifdef CONFIG_TCC_ASM
9999 #ifdef TCC_TARGET_I386
10000 #include "i386-asm.c"
10001 #endif
10002 #include "tccasm.c"
10004 #else
10005 static void asm_instr(void)
10007 error("inline asm() not supported");
10009 static void asm_global_instr(void)
10011 error("inline asm() not supported");
10013 #endif
10015 #include "tccelf.c"
10017 #ifdef TCC_TARGET_COFF
10018 #include "tcccoff.c"
10019 #endif
10021 #ifdef TCC_TARGET_PE
10022 #include "tccpe.c"
10023 #endif
10025 /* print the position in the source file of PC value 'pc' by reading
10026 the stabs debug information */
10027 static void rt_printline(unsigned long wanted_pc)
10029 Stab_Sym *sym, *sym_end;
10030 char func_name[128], last_func_name[128];
10031 unsigned long func_addr, last_pc, pc;
10032 const char *incl_files[INCLUDE_STACK_SIZE];
10033 int incl_index, len, last_line_num, i;
10034 const char *str, *p;
10036 fprintf(stderr, "0x%08lx:", wanted_pc);
10038 func_name[0] = '\0';
10039 func_addr = 0;
10040 incl_index = 0;
10041 last_func_name[0] = '\0';
10042 last_pc = 0xffffffff;
10043 last_line_num = 1;
10044 sym = (Stab_Sym *)stab_section->data + 1;
10045 sym_end = (Stab_Sym *)(stab_section->data + stab_section->data_offset);
10046 while (sym < sym_end) {
10047 switch(sym->n_type) {
10048 /* function start or end */
10049 case N_FUN:
10050 if (sym->n_strx == 0) {
10051 /* we test if between last line and end of function */
10052 pc = sym->n_value + func_addr;
10053 if (wanted_pc >= last_pc && wanted_pc < pc)
10054 goto found;
10055 func_name[0] = '\0';
10056 func_addr = 0;
10057 } else {
10058 str = stabstr_section->data + sym->n_strx;
10059 p = strchr(str, ':');
10060 if (!p) {
10061 pstrcpy(func_name, sizeof(func_name), str);
10062 } else {
10063 len = p - str;
10064 if (len > sizeof(func_name) - 1)
10065 len = sizeof(func_name) - 1;
10066 memcpy(func_name, str, len);
10067 func_name[len] = '\0';
10069 func_addr = sym->n_value;
10071 break;
10072 /* line number info */
10073 case N_SLINE:
10074 pc = sym->n_value + func_addr;
10075 if (wanted_pc >= last_pc && wanted_pc < pc)
10076 goto found;
10077 last_pc = pc;
10078 last_line_num = sym->n_desc;
10079 /* XXX: slow! */
10080 strcpy(last_func_name, func_name);
10081 break;
10082 /* include files */
10083 case N_BINCL:
10084 str = stabstr_section->data + sym->n_strx;
10085 add_incl:
10086 if (incl_index < INCLUDE_STACK_SIZE) {
10087 incl_files[incl_index++] = str;
10089 break;
10090 case N_EINCL:
10091 if (incl_index > 1)
10092 incl_index--;
10093 break;
10094 case N_SO:
10095 if (sym->n_strx == 0) {
10096 incl_index = 0; /* end of translation unit */
10097 } else {
10098 str = stabstr_section->data + sym->n_strx;
10099 /* do not add path */
10100 len = strlen(str);
10101 if (len > 0 && str[len - 1] != '/')
10102 goto add_incl;
10104 break;
10106 sym++;
10109 /* second pass: we try symtab symbols (no line number info) */
10110 incl_index = 0;
10112 ElfW(Sym) *sym, *sym_end;
10113 int type;
10115 sym_end = (ElfW(Sym) *)(symtab_section->data + symtab_section->data_offset);
10116 for(sym = (ElfW(Sym) *)symtab_section->data + 1;
10117 sym < sym_end;
10118 sym++) {
10119 type = ELFW(ST_TYPE)(sym->st_info);
10120 if (type == STT_FUNC) {
10121 if (wanted_pc >= sym->st_value &&
10122 wanted_pc < sym->st_value + sym->st_size) {
10123 pstrcpy(last_func_name, sizeof(last_func_name),
10124 strtab_section->data + sym->st_name);
10125 goto found;
10130 /* did not find any info: */
10131 fprintf(stderr, " ???\n");
10132 return;
10133 found:
10134 if (last_func_name[0] != '\0') {
10135 fprintf(stderr, " %s()", last_func_name);
10137 if (incl_index > 0) {
10138 fprintf(stderr, " (%s:%d",
10139 incl_files[incl_index - 1], last_line_num);
10140 for(i = incl_index - 2; i >= 0; i--)
10141 fprintf(stderr, ", included from %s", incl_files[i]);
10142 fprintf(stderr, ")");
10144 fprintf(stderr, "\n");
10147 #if !defined(_WIN32) && !defined(CONFIG_TCCBOOT)
10149 #ifdef __i386__
10151 /* fix for glibc 2.1 */
10152 #ifndef REG_EIP
10153 #define REG_EIP EIP
10154 #define REG_EBP EBP
10155 #endif
10157 /* return the PC at frame level 'level'. Return non zero if not found */
10158 static int rt_get_caller_pc(unsigned long *paddr,
10159 ucontext_t *uc, int level)
10161 unsigned long fp;
10162 int i;
10164 if (level == 0) {
10165 #if defined(__FreeBSD__)
10166 *paddr = uc->uc_mcontext.mc_eip;
10167 #elif defined(__dietlibc__)
10168 *paddr = uc->uc_mcontext.eip;
10169 #else
10170 *paddr = uc->uc_mcontext.gregs[REG_EIP];
10171 #endif
10172 return 0;
10173 } else {
10174 #if defined(__FreeBSD__)
10175 fp = uc->uc_mcontext.mc_ebp;
10176 #elif defined(__dietlibc__)
10177 fp = uc->uc_mcontext.ebp;
10178 #else
10179 fp = uc->uc_mcontext.gregs[REG_EBP];
10180 #endif
10181 for(i=1;i<level;i++) {
10182 /* XXX: check address validity with program info */
10183 if (fp <= 0x1000 || fp >= 0xc0000000)
10184 return -1;
10185 fp = ((unsigned long *)fp)[0];
10187 *paddr = ((unsigned long *)fp)[1];
10188 return 0;
10191 #elif defined(__x86_64__)
10192 /* return the PC at frame level 'level'. Return non zero if not found */
10193 static int rt_get_caller_pc(unsigned long *paddr,
10194 ucontext_t *uc, int level)
10196 unsigned long fp;
10197 int i;
10199 if (level == 0) {
10200 /* XXX: only support linux */
10201 *paddr = uc->uc_mcontext.gregs[REG_RIP];
10202 return 0;
10203 } else {
10204 fp = uc->uc_mcontext.gregs[REG_RBP];
10205 for(i=1;i<level;i++) {
10206 /* XXX: check address validity with program info */
10207 if (fp <= 0x1000)
10208 return -1;
10209 fp = ((unsigned long *)fp)[0];
10211 *paddr = ((unsigned long *)fp)[1];
10212 return 0;
10215 #else
10217 #warning add arch specific rt_get_caller_pc()
10219 static int rt_get_caller_pc(unsigned long *paddr,
10220 ucontext_t *uc, int level)
10222 return -1;
10224 #endif
10226 /* emit a run time error at position 'pc' */
10227 void rt_error(ucontext_t *uc, const char *fmt, ...)
10229 va_list ap;
10230 unsigned long pc;
10231 int i;
10233 va_start(ap, fmt);
10234 fprintf(stderr, "Runtime error: ");
10235 vfprintf(stderr, fmt, ap);
10236 fprintf(stderr, "\n");
10237 for(i=0;i<num_callers;i++) {
10238 if (rt_get_caller_pc(&pc, uc, i) < 0)
10239 break;
10240 if (i == 0)
10241 fprintf(stderr, "at ");
10242 else
10243 fprintf(stderr, "by ");
10244 rt_printline(pc);
10246 exit(255);
10247 va_end(ap);
10250 /* signal handler for fatal errors */
10251 static void sig_error(int signum, siginfo_t *siginf, void *puc)
10253 ucontext_t *uc = puc;
10255 switch(signum) {
10256 case SIGFPE:
10257 switch(siginf->si_code) {
10258 case FPE_INTDIV:
10259 case FPE_FLTDIV:
10260 rt_error(uc, "division by zero");
10261 break;
10262 default:
10263 rt_error(uc, "floating point exception");
10264 break;
10266 break;
10267 case SIGBUS:
10268 case SIGSEGV:
10269 if (rt_bound_error_msg && *rt_bound_error_msg)
10270 rt_error(uc, *rt_bound_error_msg);
10271 else
10272 rt_error(uc, "dereferencing invalid pointer");
10273 break;
10274 case SIGILL:
10275 rt_error(uc, "illegal instruction");
10276 break;
10277 case SIGABRT:
10278 rt_error(uc, "abort() called");
10279 break;
10280 default:
10281 rt_error(uc, "caught signal %d", signum);
10282 break;
10284 exit(255);
10286 #endif
10288 /* copy code into memory passed in by the caller and do all relocations
10289 (needed before using tcc_get_symbol()).
10290 returns -1 on error and required size if ptr is NULL */
10291 int tcc_relocate(TCCState *s1, void *ptr)
10293 Section *s;
10294 unsigned long offset, length, mem;
10295 int i;
10297 s1->nb_errors = 0;
10299 if (0 == s1->runtime_added) {
10300 #ifdef TCC_TARGET_PE
10301 pe_add_runtime(s1);
10302 relocate_common_syms();
10303 tcc_add_linker_symbols(s1);
10304 #else
10305 tcc_add_runtime(s1);
10306 relocate_common_syms();
10307 tcc_add_linker_symbols(s1);
10308 build_got_entries(s1);
10309 #endif
10310 s1->runtime_added = 1;
10313 offset = 0;
10314 mem = (unsigned long)ptr;
10315 for(i = 1; i < s1->nb_sections; i++) {
10316 s = s1->sections[i];
10317 if (0 == (s->sh_flags & SHF_ALLOC))
10318 continue;
10319 length = s->data_offset;
10320 if (0 == mem) {
10321 s->sh_addr = 0;
10322 } else if (1 == mem) {
10323 /* section are relocated in place.
10324 We also alloc the bss space */
10325 if (s->sh_type == SHT_NOBITS)
10326 s->data = tcc_malloc(length);
10327 s->sh_addr = (unsigned long)s->data;
10328 } else {
10329 /* sections are relocated to new memory */
10330 s->sh_addr = (mem + offset + 15) & ~15;
10332 offset = (offset + length + 15) & ~15;
10335 #ifdef TCC_TARGET_X86_64
10336 s1->runtime_plt_and_got_offset = 0;
10337 s1->runtime_plt_and_got = (char *)(mem + offset);
10338 /* double the size of the buffer for got and plt entries
10339 XXX: calculate exact size for them? */
10340 offset *= 2;
10341 #endif
10343 if (0 == mem)
10344 return offset + 15;
10346 /* relocate symbols */
10347 relocate_syms(s1, 1);
10348 if (s1->nb_errors)
10349 return -1;
10351 /* relocate each section */
10352 for(i = 1; i < s1->nb_sections; i++) {
10353 s = s1->sections[i];
10354 if (s->reloc)
10355 relocate_section(s1, s);
10358 for(i = 1; i < s1->nb_sections; i++) {
10359 s = s1->sections[i];
10360 if (0 == (s->sh_flags & SHF_ALLOC))
10361 continue;
10362 length = s->data_offset;
10363 // printf("%-12s %08x %04x\n", s->name, s->sh_addr, length);
10364 ptr = (void*)s->sh_addr;
10365 if (NULL == s->data || s->sh_type == SHT_NOBITS)
10366 memset(ptr, 0, length);
10367 else if (ptr != s->data)
10368 memcpy(ptr, s->data, length);
10369 /* mark executable sections as executable in memory */
10370 if (s->sh_flags & SHF_EXECINSTR)
10371 set_pages_executable(ptr, length);
10373 #ifdef TCC_TARGET_X86_64
10374 set_pages_executable(s1->runtime_plt_and_got,
10375 s1->runtime_plt_and_got_offset);
10376 #endif
10377 return 0;
10380 /* launch the compiled program with the given arguments */
10381 int tcc_run(TCCState *s1, int argc, char **argv)
10383 int (*prog_main)(int, char **);
10384 void *ptr;
10385 int ret;
10387 ret = tcc_relocate(s1, NULL);
10388 if (ret < 0)
10389 return -1;
10390 ptr = tcc_malloc(ret);
10391 tcc_relocate(s1, ptr);
10393 prog_main = tcc_get_symbol_err(s1, "main");
10395 if (do_debug) {
10396 #if defined(_WIN32) || defined(CONFIG_TCCBOOT)
10397 error("debug mode currently not available for Windows");
10398 #else
10399 struct sigaction sigact;
10400 /* install TCC signal handlers to print debug info on fatal
10401 runtime errors */
10402 sigact.sa_flags = SA_SIGINFO | SA_RESETHAND;
10403 sigact.sa_sigaction = sig_error;
10404 sigemptyset(&sigact.sa_mask);
10405 sigaction(SIGFPE, &sigact, NULL);
10406 sigaction(SIGILL, &sigact, NULL);
10407 sigaction(SIGSEGV, &sigact, NULL);
10408 sigaction(SIGBUS, &sigact, NULL);
10409 sigaction(SIGABRT, &sigact, NULL);
10410 #endif
10413 #ifdef CONFIG_TCC_BCHECK
10414 if (do_bounds_check) {
10415 void (*bound_init)(void);
10417 /* set error function */
10418 rt_bound_error_msg = tcc_get_symbol_err(s1, "__bound_error_msg");
10420 /* XXX: use .init section so that it also work in binary ? */
10421 bound_init = (void *)tcc_get_symbol_err(s1, "__bound_init");
10422 bound_init();
10424 #endif
10425 ret = (*prog_main)(argc, argv);
10426 tcc_free(ptr);
10427 return ret;
10430 void tcc_memstats(void)
10432 #ifdef MEM_DEBUG
10433 printf("memory in use: %d\n", mem_cur_size);
10434 #endif
10437 static void tcc_cleanup(void)
10439 int i, n;
10441 if (NULL == tcc_state)
10442 return;
10443 tcc_state = NULL;
10445 /* free -D defines */
10446 free_defines(NULL);
10448 /* free tokens */
10449 n = tok_ident - TOK_IDENT;
10450 for(i = 0; i < n; i++)
10451 tcc_free(table_ident[i]);
10452 tcc_free(table_ident);
10454 /* free sym_pools */
10455 dynarray_reset(&sym_pools, &nb_sym_pools);
10456 /* string buffer */
10457 cstr_free(&tokcstr);
10458 cstr_free(&tok_spaces);
10459 /* reset symbol stack */
10460 sym_free_first = NULL;
10461 /* cleanup from error/setjmp */
10462 macro_ptr = NULL;
10465 TCCState *tcc_new(void)
10467 const char *p, *r;
10468 TCCState *s;
10469 TokenSym *ts;
10470 int i, c;
10472 tcc_cleanup();
10474 s = tcc_mallocz(sizeof(TCCState));
10475 if (!s)
10476 return NULL;
10477 tcc_state = s;
10478 s->output_type = TCC_OUTPUT_MEMORY;
10480 /* init isid table */
10481 for(i=CH_EOF;i<256;i++)
10482 isidnum_table[i-CH_EOF] = isid(i) || isnum(i);
10484 /* add all tokens */
10485 table_ident = NULL;
10486 memset(hash_ident, 0, TOK_HASH_SIZE * sizeof(TokenSym *));
10488 tok_ident = TOK_IDENT;
10489 p = tcc_keywords;
10490 while (*p) {
10491 r = p;
10492 for(;;) {
10493 c = *r++;
10494 if (c == '\0')
10495 break;
10497 ts = tok_alloc(p, r - p - 1);
10498 p = r;
10501 /* we add dummy defines for some special macros to speed up tests
10502 and to have working defined() */
10503 define_push(TOK___LINE__, MACRO_OBJ, NULL, NULL);
10504 define_push(TOK___FILE__, MACRO_OBJ, NULL, NULL);
10505 define_push(TOK___DATE__, MACRO_OBJ, NULL, NULL);
10506 define_push(TOK___TIME__, MACRO_OBJ, NULL, NULL);
10508 /* standard defines */
10509 tcc_define_symbol(s, "__STDC__", NULL);
10510 tcc_define_symbol(s, "__STDC_VERSION__", "199901L");
10511 #if defined(TCC_TARGET_I386)
10512 tcc_define_symbol(s, "__i386__", NULL);
10513 #endif
10514 #if defined(TCC_TARGET_X86_64)
10515 tcc_define_symbol(s, "__x86_64__", NULL);
10516 #endif
10517 #if defined(TCC_TARGET_ARM)
10518 tcc_define_symbol(s, "__ARM_ARCH_4__", NULL);
10519 tcc_define_symbol(s, "__arm_elf__", NULL);
10520 tcc_define_symbol(s, "__arm_elf", NULL);
10521 tcc_define_symbol(s, "arm_elf", NULL);
10522 tcc_define_symbol(s, "__arm__", NULL);
10523 tcc_define_symbol(s, "__arm", NULL);
10524 tcc_define_symbol(s, "arm", NULL);
10525 tcc_define_symbol(s, "__APCS_32__", NULL);
10526 #endif
10527 #ifdef TCC_TARGET_PE
10528 tcc_define_symbol(s, "_WIN32", NULL);
10529 #else
10530 tcc_define_symbol(s, "__unix__", NULL);
10531 tcc_define_symbol(s, "__unix", NULL);
10532 #if defined(__linux)
10533 tcc_define_symbol(s, "__linux__", NULL);
10534 tcc_define_symbol(s, "__linux", NULL);
10535 #endif
10536 #endif
10537 /* tiny C specific defines */
10538 tcc_define_symbol(s, "__TINYC__", NULL);
10540 /* tiny C & gcc defines */
10541 tcc_define_symbol(s, "__SIZE_TYPE__", "unsigned int");
10542 tcc_define_symbol(s, "__PTRDIFF_TYPE__", "int");
10543 #ifdef TCC_TARGET_PE
10544 tcc_define_symbol(s, "__WCHAR_TYPE__", "unsigned short");
10545 #else
10546 tcc_define_symbol(s, "__WCHAR_TYPE__", "int");
10547 #endif
10549 #ifndef TCC_TARGET_PE
10550 /* default library paths */
10551 tcc_add_library_path(s, CONFIG_SYSROOT "/usr/local/lib");
10552 tcc_add_library_path(s, CONFIG_SYSROOT "/usr/lib");
10553 tcc_add_library_path(s, CONFIG_SYSROOT "/lib");
10554 #endif
10556 /* no section zero */
10557 dynarray_add((void ***)&s->sections, &s->nb_sections, NULL);
10559 /* create standard sections */
10560 text_section = new_section(s, ".text", SHT_PROGBITS, SHF_ALLOC | SHF_EXECINSTR);
10561 data_section = new_section(s, ".data", SHT_PROGBITS, SHF_ALLOC | SHF_WRITE);
10562 bss_section = new_section(s, ".bss", SHT_NOBITS, SHF_ALLOC | SHF_WRITE);
10564 /* symbols are always generated for linking stage */
10565 symtab_section = new_symtab(s, ".symtab", SHT_SYMTAB, 0,
10566 ".strtab",
10567 ".hashtab", SHF_PRIVATE);
10568 strtab_section = symtab_section->link;
10570 /* private symbol table for dynamic symbols */
10571 s->dynsymtab_section = new_symtab(s, ".dynsymtab", SHT_SYMTAB, SHF_PRIVATE,
10572 ".dynstrtab",
10573 ".dynhashtab", SHF_PRIVATE);
10574 s->alacarte_link = 1;
10576 #ifdef CHAR_IS_UNSIGNED
10577 s->char_is_unsigned = 1;
10578 #endif
10579 #if defined(TCC_TARGET_PE) && 0
10580 /* XXX: currently the PE linker is not ready to support that */
10581 s->leading_underscore = 1;
10582 #endif
10583 return s;
10586 void tcc_delete(TCCState *s1)
10588 int i;
10590 tcc_cleanup();
10592 /* free all sections */
10593 for(i = 1; i < s1->nb_sections; i++)
10594 free_section(s1->sections[i]);
10595 dynarray_reset(&s1->sections, &s1->nb_sections);
10597 for(i = 0; i < s1->nb_priv_sections; i++)
10598 free_section(s1->priv_sections[i]);
10599 dynarray_reset(&s1->priv_sections, &s1->nb_priv_sections);
10601 /* free any loaded DLLs */
10602 for ( i = 0; i < s1->nb_loaded_dlls; i++) {
10603 DLLReference *ref = s1->loaded_dlls[i];
10604 if ( ref->handle )
10605 dlclose(ref->handle);
10608 /* free loaded dlls array */
10609 dynarray_reset(&s1->loaded_dlls, &s1->nb_loaded_dlls);
10611 /* free library paths */
10612 dynarray_reset(&s1->library_paths, &s1->nb_library_paths);
10614 /* free include paths */
10615 dynarray_reset(&s1->cached_includes, &s1->nb_cached_includes);
10616 dynarray_reset(&s1->include_paths, &s1->nb_include_paths);
10617 dynarray_reset(&s1->sysinclude_paths, &s1->nb_sysinclude_paths);
10619 tcc_free(s1);
10622 int tcc_add_include_path(TCCState *s1, const char *pathname)
10624 char *pathname1;
10626 pathname1 = tcc_strdup(pathname);
10627 dynarray_add((void ***)&s1->include_paths, &s1->nb_include_paths, pathname1);
10628 return 0;
10631 int tcc_add_sysinclude_path(TCCState *s1, const char *pathname)
10633 char *pathname1;
10635 pathname1 = tcc_strdup(pathname);
10636 dynarray_add((void ***)&s1->sysinclude_paths, &s1->nb_sysinclude_paths, pathname1);
10637 return 0;
10640 static int tcc_add_file_internal(TCCState *s1, const char *filename, int flags)
10642 const char *ext;
10643 ElfW(Ehdr) ehdr;
10644 int fd, ret;
10645 BufferedFile *saved_file;
10647 /* find source file type with extension */
10648 ext = tcc_fileextension(filename);
10649 if (ext[0])
10650 ext++;
10652 /* open the file */
10653 saved_file = file;
10654 file = tcc_open(s1, filename);
10655 if (!file) {
10656 if (flags & AFF_PRINT_ERROR) {
10657 error_noabort("file '%s' not found", filename);
10659 ret = -1;
10660 goto fail1;
10663 if (flags & AFF_PREPROCESS) {
10664 ret = tcc_preprocess(s1);
10665 } else if (!ext[0] || !PATHCMP(ext, "c")) {
10666 /* C file assumed */
10667 ret = tcc_compile(s1);
10668 } else
10669 #ifdef CONFIG_TCC_ASM
10670 if (!strcmp(ext, "S")) {
10671 /* preprocessed assembler */
10672 ret = tcc_assemble(s1, 1);
10673 } else if (!strcmp(ext, "s")) {
10674 /* non preprocessed assembler */
10675 ret = tcc_assemble(s1, 0);
10676 } else
10677 #endif
10678 #ifdef TCC_TARGET_PE
10679 if (!PATHCMP(ext, "def")) {
10680 ret = pe_load_def_file(s1, file->fd);
10681 } else
10682 #endif
10684 fd = file->fd;
10685 /* assume executable format: auto guess file type */
10686 ret = read(fd, &ehdr, sizeof(ehdr));
10687 lseek(fd, 0, SEEK_SET);
10688 if (ret <= 0) {
10689 error_noabort("could not read header");
10690 goto fail;
10691 } else if (ret != sizeof(ehdr)) {
10692 goto try_load_script;
10695 if (ehdr.e_ident[0] == ELFMAG0 &&
10696 ehdr.e_ident[1] == ELFMAG1 &&
10697 ehdr.e_ident[2] == ELFMAG2 &&
10698 ehdr.e_ident[3] == ELFMAG3) {
10699 file->line_num = 0; /* do not display line number if error */
10700 if (ehdr.e_type == ET_REL) {
10701 ret = tcc_load_object_file(s1, fd, 0);
10702 } else if (ehdr.e_type == ET_DYN) {
10703 if (s1->output_type == TCC_OUTPUT_MEMORY) {
10704 #ifdef TCC_TARGET_PE
10705 ret = -1;
10706 #else
10707 void *h;
10708 h = dlopen(filename, RTLD_GLOBAL | RTLD_LAZY);
10709 if (h)
10710 ret = 0;
10711 else
10712 ret = -1;
10713 #endif
10714 } else {
10715 ret = tcc_load_dll(s1, fd, filename,
10716 (flags & AFF_REFERENCED_DLL) != 0);
10718 } else {
10719 error_noabort("unrecognized ELF file");
10720 goto fail;
10722 } else if (memcmp((char *)&ehdr, ARMAG, 8) == 0) {
10723 file->line_num = 0; /* do not display line number if error */
10724 ret = tcc_load_archive(s1, fd);
10725 } else
10726 #ifdef TCC_TARGET_COFF
10727 if (*(uint16_t *)(&ehdr) == COFF_C67_MAGIC) {
10728 ret = tcc_load_coff(s1, fd);
10729 } else
10730 #endif
10731 #ifdef TCC_TARGET_PE
10732 if (pe_test_res_file(&ehdr, ret)) {
10733 ret = pe_load_res_file(s1, fd);
10734 } else
10735 #endif
10737 /* as GNU ld, consider it is an ld script if not recognized */
10738 try_load_script:
10739 ret = tcc_load_ldscript(s1);
10740 if (ret < 0) {
10741 error_noabort("unrecognized file type");
10742 goto fail;
10746 the_end:
10747 tcc_close(file);
10748 fail1:
10749 file = saved_file;
10750 return ret;
10751 fail:
10752 ret = -1;
10753 goto the_end;
10756 int tcc_add_file(TCCState *s, const char *filename)
10758 return tcc_add_file_internal(s, filename, AFF_PRINT_ERROR);
10761 int tcc_add_library_path(TCCState *s, const char *pathname)
10763 char *pathname1;
10765 pathname1 = tcc_strdup(pathname);
10766 dynarray_add((void ***)&s->library_paths, &s->nb_library_paths, pathname1);
10767 return 0;
10770 /* find and load a dll. Return non zero if not found */
10771 /* XXX: add '-rpath' option support ? */
10772 static int tcc_add_dll(TCCState *s, const char *filename, int flags)
10774 char buf[1024];
10775 int i;
10777 for(i = 0; i < s->nb_library_paths; i++) {
10778 snprintf(buf, sizeof(buf), "%s/%s",
10779 s->library_paths[i], filename);
10780 if (tcc_add_file_internal(s, buf, flags) == 0)
10781 return 0;
10783 return -1;
10786 /* the library name is the same as the argument of the '-l' option */
10787 int tcc_add_library(TCCState *s, const char *libraryname)
10789 char buf[1024];
10790 int i;
10792 /* first we look for the dynamic library if not static linking */
10793 if (!s->static_link) {
10794 #ifdef TCC_TARGET_PE
10795 snprintf(buf, sizeof(buf), "%s.def", libraryname);
10796 #else
10797 snprintf(buf, sizeof(buf), "lib%s.so", libraryname);
10798 #endif
10799 if (tcc_add_dll(s, buf, 0) == 0)
10800 return 0;
10803 /* then we look for the static library */
10804 for(i = 0; i < s->nb_library_paths; i++) {
10805 snprintf(buf, sizeof(buf), "%s/lib%s.a",
10806 s->library_paths[i], libraryname);
10807 if (tcc_add_file_internal(s, buf, 0) == 0)
10808 return 0;
10810 return -1;
10813 int tcc_add_symbol(TCCState *s, const char *name, void *val)
10815 add_elf_sym(symtab_section, (unsigned long)val, 0,
10816 ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE), 0,
10817 SHN_ABS, name);
10818 return 0;
10821 int tcc_set_output_type(TCCState *s, int output_type)
10823 char buf[1024];
10825 s->output_type = output_type;
10827 if (!s->nostdinc) {
10828 /* default include paths */
10829 /* XXX: reverse order needed if -isystem support */
10830 #ifndef TCC_TARGET_PE
10831 tcc_add_sysinclude_path(s, CONFIG_SYSROOT "/usr/local/include");
10832 tcc_add_sysinclude_path(s, CONFIG_SYSROOT "/usr/include");
10833 #endif
10834 snprintf(buf, sizeof(buf), "%s/include", tcc_lib_path);
10835 tcc_add_sysinclude_path(s, buf);
10836 #ifdef TCC_TARGET_PE
10837 snprintf(buf, sizeof(buf), "%s/include/winapi", tcc_lib_path);
10838 tcc_add_sysinclude_path(s, buf);
10839 #endif
10842 /* if bound checking, then add corresponding sections */
10843 #ifdef CONFIG_TCC_BCHECK
10844 if (do_bounds_check) {
10845 /* define symbol */
10846 tcc_define_symbol(s, "__BOUNDS_CHECKING_ON", NULL);
10847 /* create bounds sections */
10848 bounds_section = new_section(s, ".bounds",
10849 SHT_PROGBITS, SHF_ALLOC);
10850 lbounds_section = new_section(s, ".lbounds",
10851 SHT_PROGBITS, SHF_ALLOC);
10853 #endif
10855 if (s->char_is_unsigned) {
10856 tcc_define_symbol(s, "__CHAR_UNSIGNED__", NULL);
10859 /* add debug sections */
10860 if (do_debug) {
10861 /* stab symbols */
10862 stab_section = new_section(s, ".stab", SHT_PROGBITS, 0);
10863 stab_section->sh_entsize = sizeof(Stab_Sym);
10864 stabstr_section = new_section(s, ".stabstr", SHT_STRTAB, 0);
10865 put_elf_str(stabstr_section, "");
10866 stab_section->link = stabstr_section;
10867 /* put first entry */
10868 put_stabs("", 0, 0, 0, 0);
10871 /* add libc crt1/crti objects */
10872 #ifndef TCC_TARGET_PE
10873 if ((output_type == TCC_OUTPUT_EXE || output_type == TCC_OUTPUT_DLL) &&
10874 !s->nostdlib) {
10875 if (output_type != TCC_OUTPUT_DLL)
10876 tcc_add_file(s, CONFIG_TCC_CRT_PREFIX "/crt1.o");
10877 tcc_add_file(s, CONFIG_TCC_CRT_PREFIX "/crti.o");
10879 #endif
10881 #ifdef TCC_TARGET_PE
10882 snprintf(buf, sizeof(buf), "%s/lib", tcc_lib_path);
10883 tcc_add_library_path(s, buf);
10884 #endif
10886 return 0;
10889 #define WD_ALL 0x0001 /* warning is activated when using -Wall */
10890 #define FD_INVERT 0x0002 /* invert value before storing */
10892 typedef struct FlagDef {
10893 uint16_t offset;
10894 uint16_t flags;
10895 const char *name;
10896 } FlagDef;
10898 static const FlagDef warning_defs[] = {
10899 { offsetof(TCCState, warn_unsupported), 0, "unsupported" },
10900 { offsetof(TCCState, warn_write_strings), 0, "write-strings" },
10901 { offsetof(TCCState, warn_error), 0, "error" },
10902 { offsetof(TCCState, warn_implicit_function_declaration), WD_ALL,
10903 "implicit-function-declaration" },
10906 static int set_flag(TCCState *s, const FlagDef *flags, int nb_flags,
10907 const char *name, int value)
10909 int i;
10910 const FlagDef *p;
10911 const char *r;
10913 r = name;
10914 if (r[0] == 'n' && r[1] == 'o' && r[2] == '-') {
10915 r += 3;
10916 value = !value;
10918 for(i = 0, p = flags; i < nb_flags; i++, p++) {
10919 if (!strcmp(r, p->name))
10920 goto found;
10922 return -1;
10923 found:
10924 if (p->flags & FD_INVERT)
10925 value = !value;
10926 *(int *)((uint8_t *)s + p->offset) = value;
10927 return 0;
10931 /* set/reset a warning */
10932 int tcc_set_warning(TCCState *s, const char *warning_name, int value)
10934 int i;
10935 const FlagDef *p;
10937 if (!strcmp(warning_name, "all")) {
10938 for(i = 0, p = warning_defs; i < countof(warning_defs); i++, p++) {
10939 if (p->flags & WD_ALL)
10940 *(int *)((uint8_t *)s + p->offset) = 1;
10942 return 0;
10943 } else {
10944 return set_flag(s, warning_defs, countof(warning_defs),
10945 warning_name, value);
10949 static const FlagDef flag_defs[] = {
10950 { offsetof(TCCState, char_is_unsigned), 0, "unsigned-char" },
10951 { offsetof(TCCState, char_is_unsigned), FD_INVERT, "signed-char" },
10952 { offsetof(TCCState, nocommon), FD_INVERT, "common" },
10953 { offsetof(TCCState, leading_underscore), 0, "leading-underscore" },
10956 /* set/reset a flag */
10957 int tcc_set_flag(TCCState *s, const char *flag_name, int value)
10959 return set_flag(s, flag_defs, countof(flag_defs),
10960 flag_name, value);
10963 #if !defined(LIBTCC)
10965 static int64_t getclock_us(void)
10967 #ifdef _WIN32
10968 struct _timeb tb;
10969 _ftime(&tb);
10970 return (tb.time * 1000LL + tb.millitm) * 1000LL;
10971 #else
10972 struct timeval tv;
10973 gettimeofday(&tv, NULL);
10974 return tv.tv_sec * 1000000LL + tv.tv_usec;
10975 #endif
10978 void help(void)
10980 printf("tcc version " TCC_VERSION " - Tiny C Compiler - Copyright (C) 2001-2006 Fabrice Bellard\n"
10981 "usage: tcc [-v] [-c] [-o outfile] [-Bdir] [-bench] [-Idir] [-Dsym[=val]] [-Usym]\n"
10982 " [-Wwarn] [-g] [-b] [-bt N] [-Ldir] [-llib] [-shared] [-soname name]\n"
10983 " [-static] [infile1 infile2...] [-run infile args...]\n"
10984 "\n"
10985 "General options:\n"
10986 " -v display current version, increase verbosity\n"
10987 " -c compile only - generate an object file\n"
10988 " -o outfile set output filename\n"
10989 " -Bdir set tcc internal library path\n"
10990 " -bench output compilation statistics\n"
10991 " -run run compiled source\n"
10992 " -fflag set or reset (with 'no-' prefix) 'flag' (see man page)\n"
10993 " -Wwarning set or reset (with 'no-' prefix) 'warning' (see man page)\n"
10994 " -w disable all warnings\n"
10995 "Preprocessor options:\n"
10996 " -E preprocess only\n"
10997 " -Idir add include path 'dir'\n"
10998 " -Dsym[=val] define 'sym' with value 'val'\n"
10999 " -Usym undefine 'sym'\n"
11000 "Linker options:\n"
11001 " -Ldir add library path 'dir'\n"
11002 " -llib link with dynamic or static library 'lib'\n"
11003 " -shared generate a shared library\n"
11004 " -soname set name for shared library to be used at runtime\n"
11005 " -static static linking\n"
11006 " -rdynamic export all global symbols to dynamic linker\n"
11007 " -r generate (relocatable) object file\n"
11008 "Debugger options:\n"
11009 " -g generate runtime debug info\n"
11010 #ifdef CONFIG_TCC_BCHECK
11011 " -b compile with built-in memory and bounds checker (implies -g)\n"
11012 #endif
11013 " -bt N show N callers in stack traces\n"
11017 #define TCC_OPTION_HAS_ARG 0x0001
11018 #define TCC_OPTION_NOSEP 0x0002 /* cannot have space before option and arg */
11020 typedef struct TCCOption {
11021 const char *name;
11022 uint16_t index;
11023 uint16_t flags;
11024 } TCCOption;
11026 enum {
11027 TCC_OPTION_HELP,
11028 TCC_OPTION_I,
11029 TCC_OPTION_D,
11030 TCC_OPTION_U,
11031 TCC_OPTION_L,
11032 TCC_OPTION_B,
11033 TCC_OPTION_l,
11034 TCC_OPTION_bench,
11035 TCC_OPTION_bt,
11036 TCC_OPTION_b,
11037 TCC_OPTION_g,
11038 TCC_OPTION_c,
11039 TCC_OPTION_static,
11040 TCC_OPTION_shared,
11041 TCC_OPTION_soname,
11042 TCC_OPTION_o,
11043 TCC_OPTION_r,
11044 TCC_OPTION_Wl,
11045 TCC_OPTION_W,
11046 TCC_OPTION_O,
11047 TCC_OPTION_m,
11048 TCC_OPTION_f,
11049 TCC_OPTION_nostdinc,
11050 TCC_OPTION_nostdlib,
11051 TCC_OPTION_print_search_dirs,
11052 TCC_OPTION_rdynamic,
11053 TCC_OPTION_run,
11054 TCC_OPTION_v,
11055 TCC_OPTION_w,
11056 TCC_OPTION_pipe,
11057 TCC_OPTION_E,
11060 static const TCCOption tcc_options[] = {
11061 { "h", TCC_OPTION_HELP, 0 },
11062 { "?", TCC_OPTION_HELP, 0 },
11063 { "I", TCC_OPTION_I, TCC_OPTION_HAS_ARG },
11064 { "D", TCC_OPTION_D, TCC_OPTION_HAS_ARG },
11065 { "U", TCC_OPTION_U, TCC_OPTION_HAS_ARG },
11066 { "L", TCC_OPTION_L, TCC_OPTION_HAS_ARG },
11067 { "B", TCC_OPTION_B, TCC_OPTION_HAS_ARG },
11068 { "l", TCC_OPTION_l, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
11069 { "bench", TCC_OPTION_bench, 0 },
11070 { "bt", TCC_OPTION_bt, TCC_OPTION_HAS_ARG },
11071 #ifdef CONFIG_TCC_BCHECK
11072 { "b", TCC_OPTION_b, 0 },
11073 #endif
11074 { "g", TCC_OPTION_g, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
11075 { "c", TCC_OPTION_c, 0 },
11076 { "static", TCC_OPTION_static, 0 },
11077 { "shared", TCC_OPTION_shared, 0 },
11078 { "soname", TCC_OPTION_soname, TCC_OPTION_HAS_ARG },
11079 { "o", TCC_OPTION_o, TCC_OPTION_HAS_ARG },
11080 { "run", TCC_OPTION_run, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
11081 { "rdynamic", TCC_OPTION_rdynamic, 0 },
11082 { "r", TCC_OPTION_r, 0 },
11083 { "Wl,", TCC_OPTION_Wl, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
11084 { "W", TCC_OPTION_W, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
11085 { "O", TCC_OPTION_O, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
11086 { "m", TCC_OPTION_m, TCC_OPTION_HAS_ARG },
11087 { "f", TCC_OPTION_f, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
11088 { "nostdinc", TCC_OPTION_nostdinc, 0 },
11089 { "nostdlib", TCC_OPTION_nostdlib, 0 },
11090 { "print-search-dirs", TCC_OPTION_print_search_dirs, 0 },
11091 { "v", TCC_OPTION_v, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
11092 { "w", TCC_OPTION_w, 0 },
11093 { "pipe", TCC_OPTION_pipe, 0},
11094 { "E", TCC_OPTION_E, 0},
11095 { NULL },
11098 /* convert 'str' into an array of space separated strings */
11099 static int expand_args(char ***pargv, const char *str)
11101 const char *s1;
11102 char **argv, *arg;
11103 int argc, len;
11105 argc = 0;
11106 argv = NULL;
11107 for(;;) {
11108 while (is_space(*str))
11109 str++;
11110 if (*str == '\0')
11111 break;
11112 s1 = str;
11113 while (*str != '\0' && !is_space(*str))
11114 str++;
11115 len = str - s1;
11116 arg = tcc_malloc(len + 1);
11117 memcpy(arg, s1, len);
11118 arg[len] = '\0';
11119 dynarray_add((void ***)&argv, &argc, arg);
11121 *pargv = argv;
11122 return argc;
11125 static char **files;
11126 static int nb_files, nb_libraries;
11127 static int multiple_files;
11128 static int print_search_dirs;
11129 static int output_type;
11130 static int reloc_output;
11131 static const char *outfile;
11133 int parse_args(TCCState *s, int argc, char **argv)
11135 int optind;
11136 const TCCOption *popt;
11137 const char *optarg, *p1, *r1;
11138 char *r;
11140 optind = 0;
11141 while (optind < argc) {
11143 r = argv[optind++];
11144 if (r[0] != '-' || r[1] == '\0') {
11145 /* add a new file */
11146 dynarray_add((void ***)&files, &nb_files, r);
11147 if (!multiple_files) {
11148 optind--;
11149 /* argv[0] will be this file */
11150 break;
11152 } else {
11153 /* find option in table (match only the first chars */
11154 popt = tcc_options;
11155 for(;;) {
11156 p1 = popt->name;
11157 if (p1 == NULL)
11158 error("invalid option -- '%s'", r);
11159 r1 = r + 1;
11160 for(;;) {
11161 if (*p1 == '\0')
11162 goto option_found;
11163 if (*r1 != *p1)
11164 break;
11165 p1++;
11166 r1++;
11168 popt++;
11170 option_found:
11171 if (popt->flags & TCC_OPTION_HAS_ARG) {
11172 if (*r1 != '\0' || (popt->flags & TCC_OPTION_NOSEP)) {
11173 optarg = r1;
11174 } else {
11175 if (optind >= argc)
11176 error("argument to '%s' is missing", r);
11177 optarg = argv[optind++];
11179 } else {
11180 if (*r1 != '\0')
11181 return 0;
11182 optarg = NULL;
11185 switch(popt->index) {
11186 case TCC_OPTION_HELP:
11187 return 0;
11189 case TCC_OPTION_I:
11190 if (tcc_add_include_path(s, optarg) < 0)
11191 error("too many include paths");
11192 break;
11193 case TCC_OPTION_D:
11195 char *sym, *value;
11196 sym = (char *)optarg;
11197 value = strchr(sym, '=');
11198 if (value) {
11199 *value = '\0';
11200 value++;
11202 tcc_define_symbol(s, sym, value);
11204 break;
11205 case TCC_OPTION_U:
11206 tcc_undefine_symbol(s, optarg);
11207 break;
11208 case TCC_OPTION_L:
11209 tcc_add_library_path(s, optarg);
11210 break;
11211 case TCC_OPTION_B:
11212 /* set tcc utilities path (mainly for tcc development) */
11213 tcc_lib_path = optarg;
11214 break;
11215 case TCC_OPTION_l:
11216 dynarray_add((void ***)&files, &nb_files, r);
11217 nb_libraries++;
11218 break;
11219 case TCC_OPTION_bench:
11220 do_bench = 1;
11221 break;
11222 case TCC_OPTION_bt:
11223 num_callers = atoi(optarg);
11224 break;
11225 #ifdef CONFIG_TCC_BCHECK
11226 case TCC_OPTION_b:
11227 do_bounds_check = 1;
11228 do_debug = 1;
11229 break;
11230 #endif
11231 case TCC_OPTION_g:
11232 do_debug = 1;
11233 break;
11234 case TCC_OPTION_c:
11235 multiple_files = 1;
11236 output_type = TCC_OUTPUT_OBJ;
11237 break;
11238 case TCC_OPTION_static:
11239 s->static_link = 1;
11240 break;
11241 case TCC_OPTION_shared:
11242 output_type = TCC_OUTPUT_DLL;
11243 break;
11244 case TCC_OPTION_soname:
11245 s->soname = optarg;
11246 break;
11247 case TCC_OPTION_o:
11248 multiple_files = 1;
11249 outfile = optarg;
11250 break;
11251 case TCC_OPTION_r:
11252 /* generate a .o merging several output files */
11253 reloc_output = 1;
11254 output_type = TCC_OUTPUT_OBJ;
11255 break;
11256 case TCC_OPTION_nostdinc:
11257 s->nostdinc = 1;
11258 break;
11259 case TCC_OPTION_nostdlib:
11260 s->nostdlib = 1;
11261 break;
11262 case TCC_OPTION_print_search_dirs:
11263 print_search_dirs = 1;
11264 break;
11265 case TCC_OPTION_run:
11267 int argc1;
11268 char **argv1;
11269 argc1 = expand_args(&argv1, optarg);
11270 if (argc1 > 0) {
11271 parse_args(s, argc1, argv1);
11273 multiple_files = 0;
11274 output_type = TCC_OUTPUT_MEMORY;
11276 break;
11277 case TCC_OPTION_v:
11278 do {
11279 if (0 == verbose++)
11280 printf("tcc version %s\n", TCC_VERSION);
11281 } while (*optarg++ == 'v');
11282 break;
11283 case TCC_OPTION_f:
11284 if (tcc_set_flag(s, optarg, 1) < 0 && s->warn_unsupported)
11285 goto unsupported_option;
11286 break;
11287 case TCC_OPTION_W:
11288 if (tcc_set_warning(s, optarg, 1) < 0 &&
11289 s->warn_unsupported)
11290 goto unsupported_option;
11291 break;
11292 case TCC_OPTION_w:
11293 s->warn_none = 1;
11294 break;
11295 case TCC_OPTION_rdynamic:
11296 s->rdynamic = 1;
11297 break;
11298 case TCC_OPTION_Wl:
11300 const char *p;
11301 if (strstart(optarg, "-Ttext,", &p)) {
11302 s->text_addr = strtoul(p, NULL, 16);
11303 s->has_text_addr = 1;
11304 } else if (strstart(optarg, "--oformat,", &p)) {
11305 if (strstart(p, "elf32-", NULL)) {
11306 s->output_format = TCC_OUTPUT_FORMAT_ELF;
11307 } else if (!strcmp(p, "binary")) {
11308 s->output_format = TCC_OUTPUT_FORMAT_BINARY;
11309 } else
11310 #ifdef TCC_TARGET_COFF
11311 if (!strcmp(p, "coff")) {
11312 s->output_format = TCC_OUTPUT_FORMAT_COFF;
11313 } else
11314 #endif
11316 error("target %s not found", p);
11318 } else {
11319 error("unsupported linker option '%s'", optarg);
11322 break;
11323 case TCC_OPTION_E:
11324 output_type = TCC_OUTPUT_PREPROCESS;
11325 break;
11326 default:
11327 if (s->warn_unsupported) {
11328 unsupported_option:
11329 warning("unsupported option '%s'", r);
11331 break;
11335 return optind + 1;
11338 int main(int argc, char **argv)
11340 int i;
11341 TCCState *s;
11342 int nb_objfiles, ret, optind;
11343 char objfilename[1024];
11344 int64_t start_time = 0;
11346 #ifdef _WIN32
11347 tcc_lib_path = w32_tcc_lib_path();
11348 #endif
11350 s = tcc_new();
11351 output_type = TCC_OUTPUT_EXE;
11352 outfile = NULL;
11353 multiple_files = 1;
11354 files = NULL;
11355 nb_files = 0;
11356 nb_libraries = 0;
11357 reloc_output = 0;
11358 print_search_dirs = 0;
11359 ret = 0;
11361 optind = parse_args(s, argc - 1, argv + 1);
11362 if (print_search_dirs) {
11363 /* enough for Linux kernel */
11364 printf("install: %s/\n", tcc_lib_path);
11365 return 0;
11367 if (optind == 0 || nb_files == 0) {
11368 if (optind && verbose)
11369 return 0;
11370 help();
11371 return 1;
11374 nb_objfiles = nb_files - nb_libraries;
11376 /* if outfile provided without other options, we output an
11377 executable */
11378 if (outfile && output_type == TCC_OUTPUT_MEMORY)
11379 output_type = TCC_OUTPUT_EXE;
11381 /* check -c consistency : only single file handled. XXX: checks file type */
11382 if (output_type == TCC_OUTPUT_OBJ && !reloc_output) {
11383 /* accepts only a single input file */
11384 if (nb_objfiles != 1)
11385 error("cannot specify multiple files with -c");
11386 if (nb_libraries != 0)
11387 error("cannot specify libraries with -c");
11391 if (output_type == TCC_OUTPUT_PREPROCESS) {
11392 if (!outfile) {
11393 s->outfile = stdout;
11394 } else {
11395 s->outfile = fopen(outfile, "w");
11396 if (!s->outfile)
11397 error("could not open '%s", outfile);
11399 } else if (output_type != TCC_OUTPUT_MEMORY) {
11400 if (!outfile) {
11401 /* compute default outfile name */
11402 char *ext;
11403 const char *name =
11404 strcmp(files[0], "-") == 0 ? "a" : tcc_basename(files[0]);
11405 pstrcpy(objfilename, sizeof(objfilename), name);
11406 ext = tcc_fileextension(objfilename);
11407 #ifdef TCC_TARGET_PE
11408 if (output_type == TCC_OUTPUT_DLL)
11409 strcpy(ext, ".dll");
11410 else
11411 if (output_type == TCC_OUTPUT_EXE)
11412 strcpy(ext, ".exe");
11413 else
11414 #endif
11415 if (output_type == TCC_OUTPUT_OBJ && !reloc_output && *ext)
11416 strcpy(ext, ".o");
11417 else
11418 pstrcpy(objfilename, sizeof(objfilename), "a.out");
11419 outfile = objfilename;
11423 if (do_bench) {
11424 start_time = getclock_us();
11427 tcc_set_output_type(s, output_type);
11429 /* compile or add each files or library */
11430 for(i = 0; i < nb_files && ret == 0; i++) {
11431 const char *filename;
11433 filename = files[i];
11434 if (output_type == TCC_OUTPUT_PREPROCESS) {
11435 if (tcc_add_file_internal(s, filename,
11436 AFF_PRINT_ERROR | AFF_PREPROCESS) < 0)
11437 ret = 1;
11438 } else if (filename[0] == '-' && filename[1]) {
11439 if (tcc_add_library(s, filename + 2) < 0)
11440 error("cannot find %s", filename);
11441 } else {
11442 if (1 == verbose)
11443 printf("-> %s\n", filename);
11444 if (tcc_add_file(s, filename) < 0)
11445 ret = 1;
11449 /* free all files */
11450 tcc_free(files);
11452 if (ret)
11453 goto the_end;
11455 if (do_bench) {
11456 double total_time;
11457 total_time = (double)(getclock_us() - start_time) / 1000000.0;
11458 if (total_time < 0.001)
11459 total_time = 0.001;
11460 if (total_bytes < 1)
11461 total_bytes = 1;
11462 printf("%d idents, %d lines, %d bytes, %0.3f s, %d lines/s, %0.1f MB/s\n",
11463 tok_ident - TOK_IDENT, total_lines, total_bytes,
11464 total_time, (int)(total_lines / total_time),
11465 total_bytes / total_time / 1000000.0);
11468 if (s->output_type == TCC_OUTPUT_PREPROCESS) {
11469 if (outfile)
11470 fclose(s->outfile);
11471 } else if (s->output_type == TCC_OUTPUT_MEMORY) {
11472 ret = tcc_run(s, argc - optind, argv + optind);
11473 } else
11474 ret = tcc_output_file(s, outfile) ? 1 : 0;
11475 the_end:
11476 /* XXX: cannot do it with bound checking because of the malloc hooks */
11477 if (!do_bounds_check)
11478 tcc_delete(s);
11480 #ifdef MEM_DEBUG
11481 if (do_bench) {
11482 printf("memory: %d bytes, max = %d bytes\n", mem_cur_size, mem_max_size);
11484 #endif
11485 return ret;
11488 #endif