1 /* C Compatible Compiler Preprocessor (CCCP)
2 Copyright (C) 1986, 87, 89, 92, 93, 94, 1995 Free Software Foundation, Inc.
3 Written by Paul Rubin, June 1986
4 Adapted to ANSI C, Richard Stallman, Jan 1987
6 This program is free software; you can redistribute it and/or modify it
7 under the terms of the GNU General Public License as published by the
8 Free Software Foundation; either version 2, or (at your option) any
11 This program 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
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program; if not, write to the Free Software
18 Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
20 In other words, you are welcome to use, share and improve this program.
21 You are forbidden to forbid anyone else to use, share and improve
22 what you give them. Help stamp out software-hoarding! */
24 typedef unsigned char U_CHAR;
28 #include "../src/config.h"
36 /* The macro EMACS is defined when cpp is distributed as part of Emacs,
37 for the sake of machines with limited C compilers. */
40 #endif /* not EMACS */
42 #ifndef STANDARD_INCLUDE_DIR
43 #define STANDARD_INCLUDE_DIR "/usr/include"
46 #ifndef LOCAL_INCLUDE_DIR
47 #define LOCAL_INCLUDE_DIR "/usr/local/include"
50 #if 0 /* We can't get ptrdiff_t, so I arranged not to need PTR_INT_TYPE. */
52 #define PTR_INT_TYPE ptrdiff_t
54 #define PTR_INT_TYPE long
64 /* By default, colon separates directories in a path. */
65 #ifndef PATH_SEPARATOR
66 #define PATH_SEPARATOR ':'
69 /* In case config.h defines these. */
74 #include <sys/types.h>
82 #include <sys/time.h> /* for __DATE__ and __TIME__ */
83 #include <sys/resource.h>
90 /* This defines "errno" properly for VMS, and gives us EACCES. */
93 /* VMS-specific definitions */
97 #define O_RDONLY 0 /* Open arg for Read/Only */
98 #define O_WRONLY 1 /* Open arg for Write/Only */
99 #define read(fd,buf,size) VMS_read (fd,buf,size)
100 #define write(fd,buf,size) VMS_write (fd,buf,size)
101 #define open(fname,mode,prot) VMS_open (fname,mode,prot)
102 #define fopen(fname,mode) VMS_fopen (fname,mode)
103 #define freopen(fname,mode,ofile) VMS_freopen (fname,mode,ofile)
104 #define strncat(dst,src,cnt) VMS_strncat (dst,src,cnt)
105 static char * VMS_strncat ();
106 static int VMS_read ();
107 static int VMS_write ();
108 static int VMS_open ();
109 static FILE * VMS_fopen ();
110 static FILE * VMS_freopen ();
111 static void hack_vms_include_specification ();
112 typedef struct { unsigned :16, :16, :16; } vms_ino_t;
113 #define ino_t vms_ino_t
114 #define INCLUDE_LEN_FUDGE 10 /* leave room for VMS syntax conversion */
116 #define BSTRING /* VMS/GCC supplies the bstring routines */
117 #endif /* __GNUC__ */
120 extern char *index ();
121 extern char *rindex ();
129 #define MIN(X,Y) ((X) < (Y) ? (X) : (Y))
130 #define MAX(X,Y) ((X) > (Y) ? (X) : (Y))
132 /* Find the largest host integer type and set its size and type. */
134 #ifndef HOST_BITS_PER_WIDE_INT
136 #if HOST_BITS_PER_LONG > HOST_BITS_PER_INT
137 #define HOST_BITS_PER_WIDE_INT HOST_BITS_PER_LONG
138 #define HOST_WIDE_INT long
140 #define HOST_BITS_PER_WIDE_INT HOST_BITS_PER_INT
141 #define HOST_WIDE_INT int
147 #define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
151 #define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
154 /* Define a generic NULL if one hasn't already been defined. */
161 #if defined (USE_PROTOTYPES) ? USE_PROTOTYPES : defined (__STDC__)
162 #define GENERIC_PTR void *
164 #define GENERIC_PTR char *
169 #define NULL_PTR ((GENERIC_PTR)0)
172 #ifndef INCLUDE_LEN_FUDGE
173 #define INCLUDE_LEN_FUDGE 0
176 /* Forward declarations. */
182 /* External declarations. */
184 extern char *getenv ();
185 extern FILE *fdopen ();
186 extern char *version_string;
187 extern struct tm *localtime ();
189 #ifndef HAVE_STRERROR
191 #if defined(bsd4_4) || defined(__NetBSD__)
192 extern const char *const sys_errlist[];
194 extern char *sys_errlist[];
196 #else /* HAVE_STERRROR */
200 char *strerror (int,...);
202 extern int parse_escape ();
203 extern HOST_WIDE_INT parse_c_expression ();
209 /* Forward declarations. */
216 #if defined(USG) || defined(VMS)
224 /* These functions are declared to return int instead of void since they
225 are going to be placed in a table and some old compilers have trouble with
226 pointers to functions returning void. */
228 static int do_define ();
229 static int do_line ();
230 static int do_include ();
231 static int do_undef ();
232 static int do_error ();
233 static int do_pragma ();
234 static int do_ident ();
236 static int do_xifdef ();
237 static int do_else ();
238 static int do_elif ();
239 static int do_endif ();
240 static int do_sccs ();
241 static int do_once ();
242 static int do_assert ();
243 static int do_unassert ();
244 static int do_warning ();
246 static void add_import ();
247 static void append_include_chain ();
248 static void deps_output ();
249 static void make_undef ();
250 static void make_definition ();
251 static void make_assertion ();
252 static void path_include ();
253 static void initialize_builtins ();
254 static void initialize_char_syntax ();
255 static void dump_arg_n ();
256 static void dump_defn_1 ();
257 static void delete_macro ();
258 static void trigraph_pcp ();
259 static void rescan ();
260 static void finclude ();
261 static void validate_else ();
262 static int comp_def_part ();
263 static void error_from_errno ();
264 static void error_with_line ();
266 void pedwarn_with_line ();
267 static void pedwarn_with_file_and_line ();
268 static void fatal ();
270 static void pfatal_with_name ();
271 static void perror_with_name ();
272 static void pipe_closed ();
273 static void print_containing_files ();
274 static int lookup_import ();
275 static int redundant_include_p ();
276 static is_system_include ();
277 static struct file_name_map *read_name_map ();
278 static char *read_filename_string ();
279 static int open_include_file ();
280 static int check_preconditions ();
281 static void pcfinclude ();
282 static void pcstring_used ();
283 static void write_output ();
284 static int check_macro_name ();
285 static int compare_defs ();
286 static int compare_token_lists ();
287 static HOST_WIDE_INT eval_if_expression ();
288 static int discard_comments ();
289 static int change_newlines ();
290 static int line_for_error ();
292 static int file_size_and_mode ();
294 static struct arglist *read_token_list ();
295 static void free_token_list ();
297 static struct hashnode *install ();
298 struct hashnode *lookup ();
300 static struct assertion_hashnode *assertion_install ();
301 static struct assertion_hashnode *assertion_lookup ();
303 static char *xrealloc ();
304 static char *xcalloc ();
305 static char *savestring ();
307 static void delete_assertion ();
308 static void macroexpand ();
309 static void dump_all_macros ();
310 static void conditional_skip ();
311 static void skip_if_group ();
312 static void output_line_command ();
314 /* Last arg to output_line_command. */
315 enum file_change_code {same_file, enter_file, leave_file};
317 static int grow_outbuf ();
318 static int handle_directive ();
319 static void memory_full ();
321 static U_CHAR *macarg1 ();
322 static char *macarg ();
324 static U_CHAR *skip_to_end_of_comment ();
325 static U_CHAR *skip_quoted_string ();
326 static U_CHAR *skip_paren_group ();
327 static char *quote_string ();
329 static char *check_precompiled ();
330 /* static struct macrodef create_definition (); [moved below] */
331 static void dump_single_macro ();
332 static void output_dots ();
334 #ifndef FAILURE_EXIT_CODE
335 #define FAILURE_EXIT_CODE 33 /* gnu cc command understands this */
338 #ifndef SUCCESS_EXIT_CODE
339 #define SUCCESS_EXIT_CODE 0 /* 0 means success on Unix. */
342 /* Name under which this program was invoked. */
344 static char *progname;
346 /* Nonzero means use extra default include directories for C++. */
348 static int cplusplus;
350 /* Nonzero means handle cplusplus style comments */
352 static int cplusplus_comments;
354 /* Nonzero means handle #import, for objective C. */
358 /* Nonzero means this is an assembly file, and allow
359 unknown directives, which could be comments. */
363 /* Current maximum length of directory names in the search path
364 for include files. (Altered as we get more of them.) */
366 static int max_include_len;
368 /* Nonzero means turn NOTREACHED into #pragma NOTREACHED etc */
370 static int for_lint = 0;
372 /* Nonzero means copy comments into the output file. */
374 static int put_out_comments = 0;
376 /* Nonzero means don't process the ANSI trigraph sequences. */
378 static int no_trigraphs = 0;
380 /* Nonzero means print the names of included files rather than
381 the preprocessed output. 1 means just the #include "...",
382 2 means #include <...> as well. */
384 static int print_deps = 0;
386 /* Nonzero if missing .h files in -M output are assumed to be generated
387 files and not errors. */
389 static int print_deps_missing_files = 0;
391 /* Nonzero means print names of header files (-H). */
393 static int print_include_names = 0;
395 /* Nonzero means don't output line number information. */
397 static int no_line_commands;
399 /* Nonzero means output the text in failing conditionals,
400 inside #failed ... #endfailed. */
402 static int output_conditionals;
404 /* dump_only means inhibit output of the preprocessed text
405 and instead output the definitions of all user-defined
406 macros in a form suitable for use as input to cccp.
407 dump_names means pass #define and the macro name through to output.
408 dump_definitions means pass the whole definition (plus #define) through
411 static enum {dump_none, dump_only, dump_names, dump_definitions}
412 dump_macros = dump_none;
414 /* Nonzero means pass all #define and #undef directives which we actually
415 process through to the output stream. This feature is used primarily
416 to allow cc1 to record the #defines and #undefs for the sake of
417 debuggers which understand about preprocessor macros, but it may
418 also be useful with -E to figure out how symbols are defined, and
419 where they are defined. */
420 static int debug_output = 0;
422 /* Nonzero indicates special processing used by the pcp program. The
423 special effects of this mode are:
425 Inhibit all macro expansion, except those inside #if directives.
427 Process #define directives normally, and output their contents
430 Output preconditions to pcp_outfile indicating all the relevant
431 preconditions for use of this file in a later cpp run.
433 static FILE *pcp_outfile;
435 /* Nonzero means we are inside an IF during a -pcp run. In this mode
436 macro expansion is done, and preconditions are output for all macro
437 uses requiring them. */
438 static int pcp_inside_if;
440 /* Nonzero means never to include precompiled files.
441 This is 1 since there's no way now to make precompiled files,
442 so it's not worth testing for them. */
443 static int no_precomp = 1;
445 /* Nonzero means give all the error messages the ANSI standard requires. */
449 /* Nonzero means try to make failure to fit ANSI C an error. */
451 static int pedantic_errors;
453 /* Nonzero means don't print warning messages. -w. */
455 static int inhibit_warnings = 0;
457 /* Nonzero means warn if slash-star appears in a comment. */
459 static int warn_comments;
461 /* Nonzero means warn if a macro argument is (or would be)
462 stringified with -traditional. */
464 static int warn_stringify;
466 /* Nonzero means warn if there are any trigraphs. */
468 static int warn_trigraphs;
470 /* Nonzero means warn if #import is used. */
472 static int warn_import = 1;
474 /* Nonzero means turn warnings into errors. */
476 static int warnings_are_errors;
478 /* Nonzero means try to imitate old fashioned non-ANSI preprocessor. */
482 /* Nonzero causes output not to be done,
483 but directives such as #define that have side effects
486 static int no_output;
488 /* Nonzero means this file was included with a -imacros or -include
489 command line and should not be recorded as an include file. */
491 static int no_record_file;
493 /* Nonzero means that we have finished processing the command line options.
494 This flag is used to decide whether or not to issue certain errors
497 static int done_initializing = 0;
499 /* Line where a newline was first seen in a string constant. */
501 static int multiline_string_line = 0;
503 /* I/O buffer structure.
504 The `fname' field is nonzero for source files and #include files
505 and for the dummy text used for -D and -U.
506 It is zero for rescanning results of macro expansion
507 and for expanding macro arguments. */
508 #define INPUT_STACK_MAX 400
509 static struct file_buf {
511 /* Filename specified with #line command. */
513 /* Record where in the search path this file was found.
514 For #include_next. */
515 struct file_name_list *dir;
520 /* Macro that this level is the expansion of.
521 Included so that we can reenable the macro
522 at the end of this level. */
523 struct hashnode *macro;
524 /* Value of if_stack at start of this file.
525 Used to prohibit unmatched #endif (etc) in an include file. */
526 struct if_stack *if_stack;
527 /* Object to be freed at end of input at this level. */
529 /* True if this is a header file included using <FILENAME>. */
530 char system_header_p;
531 } instack[INPUT_STACK_MAX];
533 static int last_error_tick; /* Incremented each time we print it. */
534 static int input_file_stack_tick; /* Incremented when the status changes. */
536 /* Current nesting level of input sources.
537 `instack[indepth]' is the level currently being read. */
538 static int indepth = -1;
539 #define CHECK_DEPTH(code) \
540 if (indepth >= (INPUT_STACK_MAX - 1)) \
542 error_with_line (line_for_error (instack[indepth].lineno), \
543 "macro or `#include' recursion too deep"); \
547 /* Current depth in #include directives that use <...>. */
548 static int system_include_depth = 0;
550 typedef struct file_buf FILE_BUF;
552 /* The output buffer. Its LENGTH field is the amount of room allocated
553 for the buffer, not the number of chars actually present. To get
554 that, subtract outbuf.buf from outbuf.bufp. */
556 #define OUTBUF_SIZE 10 /* initial size of output buffer */
557 static FILE_BUF outbuf;
559 /* Grow output buffer OBUF points at
560 so it can hold at least NEEDED more chars. */
562 #define check_expand(OBUF, NEEDED) \
563 (((OBUF)->length - ((OBUF)->bufp - (OBUF)->buf) <= (NEEDED)) \
564 ? grow_outbuf ((OBUF), (NEEDED)) : 0)
566 struct file_name_list
568 struct file_name_list *next;
570 /* If the following is nonzero, it is a macro name.
571 Don't include the file again if that macro is defined. */
572 U_CHAR *control_macro;
573 /* If the following is nonzero, it is a C-language system include
575 int c_system_include_path;
576 /* Mapping of file names for this directory. */
577 struct file_name_map *name_map;
578 /* Non-zero if name_map is valid. */
582 /* #include "file" looks in source file dir, then stack. */
583 /* #include <file> just looks in the stack. */
584 /* -I directories are added to the end, then the defaults are added. */
586 static struct default_include {
587 char *fname; /* The name of the directory. */
588 int cplusplus; /* Only look here if we're compiling C++. */
589 int cxx_aware; /* Includes in this directory don't need to
590 be wrapped in extern "C" when compiling
592 } include_defaults_array[]
593 #ifdef INCLUDE_DEFAULTS
597 /* Pick up GNU C++ specific include files. */
598 { GPLUSPLUS_INCLUDE_DIR, 1, 1 },
600 /* This is the dir for fixincludes. Put it just before
601 the files that we fix. */
602 { GCC_INCLUDE_DIR, 0, 0 },
603 /* For cross-compilation, this dir name is generated
604 automatically in Makefile.in. */
605 { CROSS_INCLUDE_DIR, 0, 0 },
606 /* This is another place that the target system's headers might be. */
607 { TOOL_INCLUDE_DIR, 0, 0 },
608 #else /* not CROSS_COMPILE */
609 /* This should be /usr/local/include and should come before
610 the fixincludes-fixed header files. */
611 { LOCAL_INCLUDE_DIR, 0, 1 },
612 /* This is here ahead of GCC_INCLUDE_DIR because assert.h goes here.
613 Likewise, behind LOCAL_INCLUDE_DIR, where glibc puts its assert.h. */
614 { TOOL_INCLUDE_DIR, 0, 0 },
615 /* This is the dir for fixincludes. Put it just before
616 the files that we fix. */
617 { GCC_INCLUDE_DIR, 0, 0 },
618 /* Some systems have an extra dir of include files. */
619 #ifdef SYSTEM_INCLUDE_DIR
620 { SYSTEM_INCLUDE_DIR, 0, 0 },
622 { STANDARD_INCLUDE_DIR, 0, 0 },
623 #endif /* not CROSS_COMPILE */
626 #endif /* no INCLUDE_DEFAULTS */
628 /* The code looks at the defaults through this pointer, rather than through
629 the constant structure above. This pointer gets changed if an environment
630 variable specifies other defaults. */
631 static struct default_include *include_defaults = include_defaults_array;
633 static struct file_name_list *include = 0; /* First dir to search */
634 /* First dir to search for <file> */
635 /* This is the first element to use for #include <...>.
636 If it is 0, use the entire chain for such includes. */
637 static struct file_name_list *first_bracket_include = 0;
638 /* This is the first element in the chain that corresponds to
639 a directory of system header files. */
640 static struct file_name_list *first_system_include = 0;
641 static struct file_name_list *last_include = 0; /* Last in chain */
643 /* Chain of include directories to put at the end of the other chain. */
644 static struct file_name_list *after_include = 0;
645 static struct file_name_list *last_after_include = 0; /* Last in chain */
647 /* Chain to put at the start of the system include files. */
648 static struct file_name_list *before_system = 0;
649 static struct file_name_list *last_before_system = 0; /* Last in chain */
651 /* List of included files that contained #pragma once. */
652 static struct file_name_list *dont_repeat_files = 0;
654 /* List of other included files.
655 If ->control_macro if nonzero, the file had a #ifndef
656 around the entire contents, and ->control_macro gives the macro name. */
657 static struct file_name_list *all_include_files = 0;
659 /* Directory prefix that should replace `/usr' in the standard
660 include file directories. */
661 static char *include_prefix;
663 /* Global list of strings read in from precompiled files. This list
664 is kept in the order the strings are read in, with new strings being
665 added at the end through stringlist_tailp. We use this list to output
666 the strings at the end of the run.
668 static STRINGDEF *stringlist;
669 static STRINGDEF **stringlist_tailp = &stringlist;
672 /* Structure returned by create_definition */
673 typedef struct macrodef MACRODEF;
676 struct definition *defn;
681 static struct macrodef create_definition ();
684 /* Structure allocated for every #define. For a simple replacement
687 nargs = -1, the `pattern' list is null, and the expansion is just
688 the replacement text. Nargs = 0 means a functionlike macro with no args,
690 #define getchar() getc (stdin) .
691 When there are args, the expansion is the replacement text with the
692 args squashed out, and the reflist is a list describing how to
693 build the output from the input: e.g., "3 chars, then the 1st arg,
694 then 9 chars, then the 3rd arg, then 0 chars, then the 2nd arg".
695 The chars here come from the expansion. Whatever is left of the
696 expansion after the last arg-occurrence is copied after that arg.
697 Note that the reflist can be arbitrarily long---
698 its length depends on the number of times the arguments appear in
699 the replacement text, not how many args there are. Example:
700 #define f(x) x+x+x+x+x+x+x would have replacement text "++++++" and
702 { (0, 1), (1, 1), (1, 1), ..., (1, 1), NULL }
703 where (x, y) means (nchars, argno). */
705 typedef struct definition DEFINITION;
708 int length; /* length of expansion string */
709 int predefined; /* True if the macro was builtin or */
710 /* came from the command line */
712 int line; /* Line number of definition */
713 char *file; /* File of definition */
714 char rest_args; /* Nonzero if last arg. absorbs the rest */
716 struct reflist *next;
717 char stringify; /* nonzero if this arg was preceded by a
719 char raw_before; /* Nonzero if a ## operator before arg. */
720 char raw_after; /* Nonzero if a ## operator after arg. */
721 char rest_args; /* Nonzero if this arg. absorbs the rest */
722 int nchars; /* Number of literal chars to copy before
723 this arg occurrence. */
724 int argno; /* Number of arg to substitute (origin-0) */
727 /* Names of macro args, concatenated in reverse order
728 with comma-space between them.
729 The only use of this is that we warn on redefinition
730 if this differs between the old and new definitions. */
735 /* different kinds of things that can appear in the value field
736 of a hash node. Actually, this may be useless now. */
745 * special extension string that can be added to the last macro argument to
746 * allow it to absorb the "rest" of the arguments when expanded. Ex:
747 * #define wow(a, b...) process (b, a, b)
748 * { wow (1, 2, 3); } -> { process (2, 3, 1, 2, 3); }
749 * { wow (one, two); } -> { process (two, one, two); }
750 * if this "rest_arg" is used with the concat token '##' and if it is not
751 * supplied then the token attached to with ## will not be outputted. Ex:
752 * #define wow (a, b...) process (b ## , a, ## b)
753 * { wow (1, 2); } -> { process (2, 1, 2); }
754 * { wow (one); } -> { process (one); {
756 static char rest_extension[] = "...";
757 #define REST_EXTENSION_LENGTH (sizeof (rest_extension) - 1)
759 /* The structure of a node in the hash table. The hash table
760 has entries for all tokens defined by #define commands (type T_MACRO),
761 plus some special tokens like __LINE__ (these each have their own
762 type, and the appropriate code is run when that type of node is seen.
763 It does not contain control words like "#define", which are recognized
764 by a separate piece of code. */
766 /* different flavors of hash nodes --- also used in keyword table */
768 T_DEFINE = 1, /* the `#define' keyword */
769 T_INCLUDE, /* the `#include' keyword */
770 T_INCLUDE_NEXT, /* the `#include_next' keyword */
771 T_IMPORT, /* the `#import' keyword */
772 T_IFDEF, /* the `#ifdef' keyword */
773 T_IFNDEF, /* the `#ifndef' keyword */
774 T_IF, /* the `#if' keyword */
775 T_ELSE, /* `#else' */
776 T_PRAGMA, /* `#pragma' */
777 T_ELIF, /* `#elif' */
778 T_UNDEF, /* `#undef' */
779 T_LINE, /* `#line' */
780 T_ERROR, /* `#error' */
781 T_WARNING, /* `#warning' */
782 T_ENDIF, /* `#endif' */
783 T_SCCS, /* `#sccs', used on system V. */
784 T_IDENT, /* `#ident', used on system V. */
785 T_ASSERT, /* `#assert', taken from system V. */
786 T_UNASSERT, /* `#unassert', taken from system V. */
787 T_SPECLINE, /* special symbol `__LINE__' */
788 T_DATE, /* `__DATE__' */
789 T_FILE, /* `__FILE__' */
790 T_BASE_FILE, /* `__BASE_FILE__' */
791 T_INCLUDE_LEVEL, /* `__INCLUDE_LEVEL__' */
792 T_VERSION, /* `__VERSION__' */
793 T_SIZE_TYPE, /* `__SIZE_TYPE__' */
794 T_PTRDIFF_TYPE, /* `__PTRDIFF_TYPE__' */
795 T_WCHAR_TYPE, /* `__WCHAR_TYPE__' */
796 T_USER_LABEL_PREFIX_TYPE, /* `__USER_LABEL_PREFIX__' */
797 T_REGISTER_PREFIX_TYPE, /* `__REGISTER_PREFIX__' */
798 T_TIME, /* `__TIME__' */
799 T_CONST, /* Constant value, used by `__STDC__' */
800 T_MACRO, /* macro defined by `#define' */
801 T_DISABLED, /* macro temporarily turned off for rescan */
802 T_SPEC_DEFINED, /* special `defined' macro for use in #if statements */
803 T_PCSTRING, /* precompiled string (hashval is KEYDEF *) */
804 T_UNUSED /* Used for something not defined. */
808 struct hashnode *next; /* double links for easy deletion */
809 struct hashnode *prev;
810 struct hashnode **bucket_hdr; /* also, a back pointer to this node's hash
811 chain is kept, in case the node is the head
812 of the chain and gets deleted. */
813 enum node_type type; /* type of special token */
814 int length; /* length of token, for quick comparison */
815 U_CHAR *name; /* the actual name */
816 union hashval value; /* pointer to expansion, or whatever */
819 typedef struct hashnode HASHNODE;
821 /* Some definitions for the hash table. The hash function MUST be
822 computed as shown in hashf () below. That is because the rescan
823 loop computes the hash value `on the fly' for most tokens,
824 in order to avoid the overhead of a lot of procedure calls to
825 the hashf () function. Hashf () only exists for the sake of
826 politeness, for use when speed isn't so important. */
828 #define HASHSIZE 1403
829 static HASHNODE *hashtab[HASHSIZE];
830 #define HASHSTEP(old, c) ((old << 2) + c)
831 #define MAKE_POS(v) (v & 0x7fffffff) /* make number positive */
833 /* Symbols to predefine. */
835 #ifdef CPP_PREDEFINES
836 static char *predefs = CPP_PREDEFINES;
838 static char *predefs = "";
841 /* We let tm.h override the types used here, to handle trivial differences
842 such as the choice of unsigned int or long unsigned int for size_t.
843 When machines start needing nontrivial differences in the size type,
844 it would be best to do something here to figure out automatically
845 from other information what type to use. */
847 /* The string value for __SIZE_TYPE__. */
850 #define SIZE_TYPE "long unsigned int"
853 /* The string value for __PTRDIFF_TYPE__. */
856 #define PTRDIFF_TYPE "long int"
859 /* The string value for __WCHAR_TYPE__. */
862 #define WCHAR_TYPE "int"
864 char * wchar_type = WCHAR_TYPE;
867 /* The string value for __USER_LABEL_PREFIX__ */
869 #ifndef USER_LABEL_PREFIX
870 #define USER_LABEL_PREFIX ""
873 /* The string value for __REGISTER_PREFIX__ */
875 #ifndef REGISTER_PREFIX
876 #define REGISTER_PREFIX ""
879 /* In the definition of a #assert name, this structure forms
880 a list of the individual values asserted.
881 Each value is itself a list of "tokens".
882 These are strings that are compared by name. */
884 struct tokenlist_list {
885 struct tokenlist_list *next;
886 struct arglist *tokens;
889 struct assertion_hashnode {
890 struct assertion_hashnode *next; /* double links for easy deletion */
891 struct assertion_hashnode *prev;
892 /* also, a back pointer to this node's hash
893 chain is kept, in case the node is the head
894 of the chain and gets deleted. */
895 struct assertion_hashnode **bucket_hdr;
896 int length; /* length of token, for quick comparison */
897 U_CHAR *name; /* the actual name */
898 /* List of token-sequences. */
899 struct tokenlist_list *value;
902 typedef struct assertion_hashnode ASSERTION_HASHNODE;
904 /* Some definitions for the hash table. The hash function MUST be
905 computed as shown in hashf below. That is because the rescan
906 loop computes the hash value `on the fly' for most tokens,
907 in order to avoid the overhead of a lot of procedure calls to
908 the hashf function. hashf only exists for the sake of
909 politeness, for use when speed isn't so important. */
911 #define ASSERTION_HASHSIZE 37
912 static ASSERTION_HASHNODE *assertion_hashtab[ASSERTION_HASHSIZE];
914 /* Nonzero means inhibit macroexpansion of what seem to be
915 assertion tests, in rescan. For #if. */
916 static int assertions_flag;
918 /* `struct directive' defines one #-directive, including how to handle it. */
921 int length; /* Length of name */
922 int (*func)(); /* Function to handle directive */
923 char *name; /* Name of directive */
924 enum node_type type; /* Code which describes which directive. */
925 char angle_brackets; /* Nonzero => <...> is special. */
926 char traditional_comments; /* Nonzero: keep comments if -traditional. */
927 char pass_thru; /* Copy preprocessed directive to output file. */
930 /* Here is the actual list of #-directives, most-often-used first. */
932 static struct directive directive_table[] = {
933 { 6, do_define, "define", T_DEFINE, 0, 1},
934 { 2, do_if, "if", T_IF},
935 { 5, do_xifdef, "ifdef", T_IFDEF},
936 { 6, do_xifdef, "ifndef", T_IFNDEF},
937 { 5, do_endif, "endif", T_ENDIF},
938 { 4, do_else, "else", T_ELSE},
939 { 4, do_elif, "elif", T_ELIF},
940 { 4, do_line, "line", T_LINE},
941 { 7, do_include, "include", T_INCLUDE, 1},
942 { 12, do_include, "include_next", T_INCLUDE_NEXT, 1},
943 { 6, do_include, "import", T_IMPORT, 1},
944 { 5, do_undef, "undef", T_UNDEF},
945 { 5, do_error, "error", T_ERROR},
946 { 7, do_warning, "warning", T_WARNING},
947 #ifdef SCCS_DIRECTIVE
948 { 4, do_sccs, "sccs", T_SCCS},
950 { 6, do_pragma, "pragma", T_PRAGMA, 0, 0, 1},
951 { 5, do_ident, "ident", T_IDENT},
952 { 6, do_assert, "assert", T_ASSERT},
953 { 8, do_unassert, "unassert", T_UNASSERT},
954 { -1, 0, "", T_UNUSED},
957 /* When a directive handler is called,
958 this points to the # that started the directive. */
959 U_CHAR *directive_start;
961 /* table to tell if char can be part of a C identifier. */
962 U_CHAR is_idchar[256];
963 /* table to tell if char can be first char of a c identifier. */
964 U_CHAR is_idstart[256];
965 /* table to tell if c is horizontal space. */
966 U_CHAR is_hor_space[256];
967 /* table to tell if c is horizontal or vertical space. */
968 static U_CHAR is_space[256];
969 /* names of some characters */
970 static char *char_name[256];
972 #define SKIP_WHITE_SPACE(p) do { while (is_hor_space[*p]) p++; } while (0)
973 #define SKIP_ALL_WHITE_SPACE(p) do { while (is_space[*p]) p++; } while (0)
975 static int errors = 0; /* Error counter for exit code */
977 /* Name of output file, for error messages. */
978 static char *out_fname;
980 /* Zero means dollar signs are punctuation.
981 -$ stores 0; -traditional may store 1. Default is 1 for VMS, 0 otherwise.
982 This must be 0 for correct processing of this ANSI C program:
984 #define lose(b) foo (b)
987 static int dollars_in_ident;
988 #ifndef DOLLARS_IN_IDENTIFIERS
989 #define DOLLARS_IN_IDENTIFIERS 1
992 static FILE_BUF expand_to_temp_buffer ();
994 static DEFINITION *collect_expansion ();
996 /* Stack of conditionals currently in progress
997 (including both successful and failing conditionals). */
1000 struct if_stack *next; /* for chaining to the next stack frame */
1001 char *fname; /* copied from input when frame is made */
1002 int lineno; /* similarly */
1003 int if_succeeded; /* true if a leg of this if-group
1004 has been passed through rescan */
1005 U_CHAR *control_macro; /* For #ifndef at start of file,
1006 this is the macro name tested. */
1007 enum node_type type; /* type of last directive seen in this group */
1009 typedef struct if_stack IF_STACK_FRAME;
1010 static IF_STACK_FRAME *if_stack = NULL;
1012 /* Buffer of -M output. */
1013 static char *deps_buffer;
1015 /* Number of bytes allocated in above. */
1016 static int deps_allocated_size;
1018 /* Number of bytes used. */
1019 static int deps_size;
1021 /* Number of bytes since the last newline. */
1022 static int deps_column;
1024 /* Nonzero means -I- has been seen,
1025 so don't look for #include "foo" the source-file directory. */
1026 static int ignore_srcdir;
1028 /* Read LEN bytes at PTR from descriptor DESC, for file FILENAME,
1029 retrying if necessary. Return a negative value if an error occurs,
1030 otherwise return the actual number of bytes read,
1031 which must be LEN unless end-of-file was reached. */
1034 safe_read (desc, ptr, len)
1041 int nchars = read (desc, ptr, left);
1058 /* Write LEN bytes at PTR to descriptor DESC,
1059 retrying if necessary, and treating any real error as fatal. */
1062 safe_write (desc, ptr, len)
1068 int written = write (desc, ptr, len);
1075 pfatal_with_name (out_fname);
1093 char **pend_files = (char **) xmalloc (argc * sizeof (char *));
1094 char **pend_defs = (char **) xmalloc (argc * sizeof (char *));
1095 char **pend_undefs = (char **) xmalloc (argc * sizeof (char *));
1096 char **pend_assertions = (char **) xmalloc (argc * sizeof (char *));
1097 char **pend_includes = (char **) xmalloc (argc * sizeof (char *));
1099 /* Record the option used with each element of pend_assertions.
1100 This is preparation for supporting more than one option for making
1102 char **pend_assertion_options = (char **) xmalloc (argc * sizeof (char *));
1103 int inhibit_predefs = 0;
1104 int no_standard_includes = 0;
1105 int no_standard_cplusplus_includes = 0;
1106 int missing_newline = 0;
1108 /* Non-0 means don't output the preprocessed program. */
1109 int inhibit_output = 0;
1110 /* Non-0 means -v, so print the full set of include dirs. */
1113 /* File name which deps are being written to.
1114 This is 0 if deps are being written to stdout. */
1115 char *deps_file = 0;
1116 /* Fopen file mode to open deps_file with. */
1117 char *deps_mode = "a";
1118 /* Stream on which to print the dependency information. */
1119 FILE *deps_stream = 0;
1120 /* Target-name to write with the dependency information. */
1121 char *deps_target = 0;
1124 /* Get rid of any avoidable limit on stack size. */
1128 /* Set the stack limit huge so that alloca (particularly stringtab
1129 * in dbxread.c) does not fail. */
1130 getrlimit (RLIMIT_STACK, &rlim);
1131 rlim.rlim_cur = rlim.rlim_max;
1132 setrlimit (RLIMIT_STACK, &rlim);
1134 #endif /* RLIMIT_STACK defined */
1137 signal (SIGPIPE, pipe_closed);
1140 p = argv[0] + strlen (argv[0]);
1141 while (p != argv[0] && p[-1] != '/'
1142 #ifdef DIR_SEPARATOR
1143 && p[-1] != DIR_SEPARATOR
1151 /* Remove directories from PROGNAME. */
1154 if ((p = rindex (s, ':')) != 0) s = p + 1; /* skip device */
1155 if ((p = rindex (s, ']')) != 0) s = p + 1; /* skip directory */
1156 if ((p = rindex (s, '>')) != 0) s = p + 1; /* alternate (int'n'l) dir */
1157 s = progname = savestring (s);
1158 if ((p = rindex (s, ';')) != 0) *p = '\0'; /* strip version number */
1159 if ((p = rindex (s, '.')) != 0 /* strip type iff ".exe" */
1160 && (p[1] == 'e' || p[1] == 'E')
1161 && (p[2] == 'x' || p[2] == 'X')
1162 && (p[3] == 'e' || p[3] == 'E')
1171 /* Initialize is_idchar to allow $. */
1172 dollars_in_ident = 1;
1173 initialize_char_syntax ();
1174 dollars_in_ident = DOLLARS_IN_IDENTIFIERS > 0;
1176 no_line_commands = 0;
1178 dump_macros = dump_none;
1181 cplusplus_comments = 0;
1183 bzero ((char *) pend_files, argc * sizeof (char *));
1184 bzero ((char *) pend_defs, argc * sizeof (char *));
1185 bzero ((char *) pend_undefs, argc * sizeof (char *));
1186 bzero ((char *) pend_assertions, argc * sizeof (char *));
1187 bzero ((char *) pend_includes, argc * sizeof (char *));
1189 /* Process switches and find input file name. */
1191 for (i = 1; i < argc; i++) {
1192 if (argv[i][0] != '-') {
1193 if (out_fname != NULL)
1194 fatal ("Usage: %s [switches] input output", argv[0]);
1195 else if (in_fname != NULL)
1196 out_fname = argv[i];
1200 switch (argv[i][1]) {
1203 if (!strcmp (argv[i], "-include")) {
1205 fatal ("Filename missing after `-include' option");
1207 pend_includes[i] = argv[i+1], i++;
1209 if (!strcmp (argv[i], "-imacros")) {
1211 fatal ("Filename missing after `-imacros' option");
1213 pend_files[i] = argv[i+1], i++;
1215 if (!strcmp (argv[i], "-iprefix")) {
1217 fatal ("Filename missing after `-iprefix' option");
1219 include_prefix = argv[++i];
1221 if (!strcmp (argv[i], "-ifoutput")) {
1222 output_conditionals = 1;
1224 if (!strcmp (argv[i], "-isystem")) {
1225 struct file_name_list *dirtmp;
1228 fatal ("Filename missing after `-isystem' option");
1230 dirtmp = (struct file_name_list *)
1231 xmalloc (sizeof (struct file_name_list));
1233 dirtmp->control_macro = 0;
1234 dirtmp->c_system_include_path = 1;
1235 dirtmp->fname = (char *) xmalloc (strlen (argv[i+1]) + 1);
1236 strcpy (dirtmp->fname, argv[++i]);
1237 dirtmp->got_name_map = 0;
1239 if (before_system == 0)
1240 before_system = dirtmp;
1242 last_before_system->next = dirtmp;
1243 last_before_system = dirtmp; /* Tail follows the last one */
1245 /* Add directory to end of path for includes,
1246 with the default prefix at the front of its name. */
1247 if (!strcmp (argv[i], "-iwithprefix")) {
1248 struct file_name_list *dirtmp;
1251 if (include_prefix != 0)
1252 prefix = include_prefix;
1254 prefix = savestring (GCC_INCLUDE_DIR);
1255 /* Remove the `include' from /usr/local/lib/gcc.../include. */
1256 if (!strcmp (prefix + strlen (prefix) - 8, "/include"))
1257 prefix[strlen (prefix) - 7] = 0;
1260 dirtmp = (struct file_name_list *)
1261 xmalloc (sizeof (struct file_name_list));
1262 dirtmp->next = 0; /* New one goes on the end */
1263 dirtmp->control_macro = 0;
1264 dirtmp->c_system_include_path = 0;
1266 fatal ("Directory name missing after `-iwithprefix' option");
1268 dirtmp->fname = (char *) xmalloc (strlen (argv[i+1])
1269 + strlen (prefix) + 1);
1270 strcpy (dirtmp->fname, prefix);
1271 strcat (dirtmp->fname, argv[++i]);
1272 dirtmp->got_name_map = 0;
1274 if (after_include == 0)
1275 after_include = dirtmp;
1277 last_after_include->next = dirtmp;
1278 last_after_include = dirtmp; /* Tail follows the last one */
1280 /* Add directory to main path for includes,
1281 with the default prefix at the front of its name. */
1282 if (!strcmp (argv[i], "-iwithprefixbefore")) {
1283 struct file_name_list *dirtmp;
1286 if (include_prefix != 0)
1287 prefix = include_prefix;
1289 prefix = savestring (GCC_INCLUDE_DIR);
1290 /* Remove the `include' from /usr/local/lib/gcc.../include. */
1291 if (!strcmp (prefix + strlen (prefix) - 8, "/include"))
1292 prefix[strlen (prefix) - 7] = 0;
1295 dirtmp = (struct file_name_list *)
1296 xmalloc (sizeof (struct file_name_list));
1297 dirtmp->next = 0; /* New one goes on the end */
1298 dirtmp->control_macro = 0;
1299 dirtmp->c_system_include_path = 0;
1301 fatal ("Directory name missing after `-iwithprefixbefore' option");
1303 dirtmp->fname = (char *) xmalloc (strlen (argv[i+1])
1304 + strlen (prefix) + 1);
1305 strcpy (dirtmp->fname, prefix);
1306 strcat (dirtmp->fname, argv[++i]);
1307 dirtmp->got_name_map = 0;
1309 append_include_chain (dirtmp, dirtmp);
1311 /* Add directory to end of path for includes. */
1312 if (!strcmp (argv[i], "-idirafter")) {
1313 struct file_name_list *dirtmp;
1315 dirtmp = (struct file_name_list *)
1316 xmalloc (sizeof (struct file_name_list));
1317 dirtmp->next = 0; /* New one goes on the end */
1318 dirtmp->control_macro = 0;
1319 dirtmp->c_system_include_path = 0;
1321 fatal ("Directory name missing after `-idirafter' option");
1323 dirtmp->fname = argv[++i];
1324 dirtmp->got_name_map = 0;
1326 if (after_include == 0)
1327 after_include = dirtmp;
1329 last_after_include->next = dirtmp;
1330 last_after_include = dirtmp; /* Tail follows the last one */
1335 if (out_fname != NULL)
1336 fatal ("Output filename specified twice");
1338 fatal ("Filename missing after -o option");
1339 out_fname = argv[++i];
1340 if (!strcmp (out_fname, "-"))
1345 if (!strcmp (argv[i], "-pedantic"))
1347 else if (!strcmp (argv[i], "-pedantic-errors")) {
1349 pedantic_errors = 1;
1350 } else if (!strcmp (argv[i], "-pcp")) {
1353 fatal ("Filename missing after -pcp option");
1354 pcp_fname = argv[++i];
1356 ((pcp_fname[0] != '-' || pcp_fname[1] != '\0')
1357 ? fopen (pcp_fname, "w")
1358 : fdopen (dup (fileno (stdout)), "w"));
1359 if (pcp_outfile == 0)
1360 pfatal_with_name (pcp_fname);
1366 if (!strcmp (argv[i], "-traditional")) {
1368 if (dollars_in_ident > 0)
1369 dollars_in_ident = 1;
1370 } else if (!strcmp (argv[i], "-trigraphs")) {
1376 if (! strcmp (argv[i], "-lang-c"))
1377 cplusplus = 0, cplusplus_comments = 0, objc = 0;
1378 if (! strcmp (argv[i], "-lang-c++"))
1379 cplusplus = 1, cplusplus_comments = 1, objc = 0;
1380 if (! strcmp (argv[i], "-lang-c-c++-comments"))
1381 cplusplus = 0, cplusplus_comments = 1, objc = 0;
1382 if (! strcmp (argv[i], "-lang-objc"))
1383 objc = 1, cplusplus = 0, cplusplus_comments = 1;
1384 if (! strcmp (argv[i], "-lang-objc++"))
1385 objc = 1, cplusplus = 1, cplusplus_comments = 1;
1386 if (! strcmp (argv[i], "-lang-asm"))
1388 if (! strcmp (argv[i], "-lint"))
1393 cplusplus = 1, cplusplus_comments = 1;
1397 inhibit_warnings = 1;
1401 if (!strcmp (argv[i], "-Wtrigraphs"))
1403 else if (!strcmp (argv[i], "-Wno-trigraphs"))
1405 else if (!strcmp (argv[i], "-Wcomment"))
1407 else if (!strcmp (argv[i], "-Wno-comment"))
1409 else if (!strcmp (argv[i], "-Wcomments"))
1411 else if (!strcmp (argv[i], "-Wno-comments"))
1413 else if (!strcmp (argv[i], "-Wtraditional"))
1415 else if (!strcmp (argv[i], "-Wno-traditional"))
1417 else if (!strcmp (argv[i], "-Wimport"))
1419 else if (!strcmp (argv[i], "-Wno-import"))
1421 else if (!strcmp (argv[i], "-Werror"))
1422 warnings_are_errors = 1;
1423 else if (!strcmp (argv[i], "-Wno-error"))
1424 warnings_are_errors = 0;
1425 else if (!strcmp (argv[i], "-Wall"))
1433 /* The style of the choices here is a bit mixed.
1434 The chosen scheme is a hybrid of keeping all options in one string
1435 and specifying each option in a separate argument:
1436 -M|-MM|-MD file|-MMD file [-MG]. An alternative is:
1437 -M|-MM|-MD file|-MMD file|-MG|-MMG; or more concisely:
1438 -M[M][G][D file]. This is awkward to handle in specs, and is not
1440 /* ??? -MG must be specified in addition to one of -M or -MM.
1441 This can be relaxed in the future without breaking anything.
1442 The converse isn't true. */
1444 /* -MG isn't valid with -MD or -MMD. This is checked for later. */
1445 if (!strcmp (argv[i], "-MG"))
1447 print_deps_missing_files = 1;
1450 if (!strcmp (argv[i], "-M"))
1452 else if (!strcmp (argv[i], "-MM"))
1454 else if (!strcmp (argv[i], "-MD"))
1456 else if (!strcmp (argv[i], "-MMD"))
1458 /* For -MD and -MMD options, write deps on file named by next arg. */
1459 if (!strcmp (argv[i], "-MD")
1460 || !strcmp (argv[i], "-MMD")) {
1462 fatal ("Filename missing after %s option", argv[i]);
1464 deps_file = argv[i];
1467 /* For -M and -MM, write deps on standard output
1468 and suppress the usual output. */
1469 deps_stream = stdout;
1476 char *p = argv[i] + 2;
1479 /* Arg to -d specifies what parts of macros to dump */
1482 dump_macros = dump_only;
1486 dump_macros = dump_names;
1489 dump_macros = dump_definitions;
1497 if (argv[i][2] == '3')
1502 fprintf (stderr, "GNU CPP version %s", version_string);
1503 #ifdef TARGET_VERSION
1506 fprintf (stderr, "\n");
1511 print_include_names = 1;
1515 if (argv[i][2] != 0)
1516 pend_defs[i] = argv[i] + 2;
1517 else if (i + 1 == argc)
1518 fatal ("Macro name missing after -D option");
1520 i++, pend_defs[i] = argv[i];
1527 if (argv[i][2] != 0)
1529 else if (i + 1 == argc)
1530 fatal ("Assertion missing after -A option");
1534 if (!strcmp (p, "-")) {
1535 /* -A- eliminates all predefined macros and assertions.
1536 Let's include also any that were specified earlier
1537 on the command line. That way we can get rid of any
1538 that were passed automatically in from GCC. */
1540 inhibit_predefs = 1;
1541 for (j = 0; j < i; j++)
1542 pend_defs[j] = pend_assertions[j] = 0;
1544 pend_assertions[i] = p;
1545 pend_assertion_options[i] = "-A";
1550 case 'U': /* JF #undef something */
1551 if (argv[i][2] != 0)
1552 pend_undefs[i] = argv[i] + 2;
1553 else if (i + 1 == argc)
1554 fatal ("Macro name missing after -U option");
1556 pend_undefs[i] = argv[i+1], i++;
1560 put_out_comments = 1;
1563 case 'E': /* -E comes from cc -E; ignore it. */
1567 no_line_commands = 1;
1570 case '$': /* Don't include $ in identifiers. */
1571 dollars_in_ident = 0;
1574 case 'I': /* Add directory to path for includes. */
1576 struct file_name_list *dirtmp;
1578 if (! ignore_srcdir && !strcmp (argv[i] + 2, "-")) {
1580 /* Don't use any preceding -I directories for #include <...>. */
1581 first_bracket_include = 0;
1584 dirtmp = (struct file_name_list *)
1585 xmalloc (sizeof (struct file_name_list));
1586 dirtmp->next = 0; /* New one goes on the end */
1587 dirtmp->control_macro = 0;
1588 dirtmp->c_system_include_path = 0;
1589 if (argv[i][2] != 0)
1590 dirtmp->fname = argv[i] + 2;
1591 else if (i + 1 == argc)
1592 fatal ("Directory name missing after -I option");
1594 dirtmp->fname = argv[++i];
1595 dirtmp->got_name_map = 0;
1596 append_include_chain (dirtmp, dirtmp);
1602 if (!strcmp (argv[i], "-nostdinc"))
1603 /* -nostdinc causes no default include directories.
1604 You must specify all include-file directories with -I. */
1605 no_standard_includes = 1;
1606 else if (!strcmp (argv[i], "-nostdinc++"))
1607 /* -nostdinc++ causes no default C++-specific include directories. */
1608 no_standard_cplusplus_includes = 1;
1609 else if (!strcmp (argv[i], "-noprecomp"))
1614 /* Sun compiler passes undocumented switch "-undef".
1615 Let's assume it means to inhibit the predefined symbols. */
1616 inhibit_predefs = 1;
1619 case '\0': /* JF handle '-' as file name meaning stdin or stdout */
1620 if (in_fname == NULL) {
1623 } else if (out_fname == NULL) {
1626 } /* else fall through into error */
1629 fatal ("Invalid option `%s'", argv[i]);
1634 /* Add dirs from CPATH after dirs from -I. */
1635 /* There seems to be confusion about what CPATH should do,
1636 so for the moment it is not documented. */
1637 /* Some people say that CPATH should replace the standard include dirs,
1638 but that seems pointless: it comes before them, so it overrides them
1641 p = (char *) getenv ("Include");
1643 p = (char *) getenv ("CPATH");
1645 if (p != 0 && ! no_standard_includes)
1648 /* Now that dollars_in_ident is known, initialize is_idchar. */
1649 initialize_char_syntax ();
1651 /* Initialize output buffer */
1653 outbuf.buf = (U_CHAR *) xmalloc (OUTBUF_SIZE);
1654 outbuf.bufp = outbuf.buf;
1655 outbuf.length = OUTBUF_SIZE;
1657 /* Do partial setup of input buffer for the sake of generating
1658 early #line directives (when -g is in effect). */
1660 fp = &instack[++indepth];
1661 if (in_fname == NULL)
1663 fp->nominal_fname = fp->fname = in_fname;
1666 /* In C++, wchar_t is a distinct basic type, and we can expect
1667 __wchar_t to be defined by cc1plus. */
1669 wchar_type = "__wchar_t";
1671 /* Install __LINE__, etc. Must follow initialize_char_syntax
1672 and option processing. */
1673 initialize_builtins (fp, &outbuf);
1675 /* Do standard #defines and assertions
1676 that identify system and machine type. */
1678 if (!inhibit_predefs) {
1679 char *p = (char *) alloca (strlen (predefs) + 1);
1680 strcpy (p, predefs);
1683 while (*p == ' ' || *p == '\t')
1685 /* Handle -D options. */
1686 if (p[0] == '-' && p[1] == 'D') {
1688 while (*p && *p != ' ' && *p != '\t')
1693 output_line_command (fp, &outbuf, 0, same_file);
1694 make_definition (q, &outbuf);
1695 while (*p == ' ' || *p == '\t')
1697 } else if (p[0] == '-' && p[1] == 'A') {
1698 /* Handle -A options (assertions). */
1707 past_name = assertion;
1708 /* Locate end of name. */
1709 while (*past_name && *past_name != ' '
1710 && *past_name != '\t' && *past_name != '(')
1712 /* Locate `(' at start of value. */
1714 while (*value && (*value == ' ' || *value == '\t'))
1716 if (*value++ != '(')
1718 while (*value && (*value == ' ' || *value == '\t'))
1721 /* Locate end of value. */
1722 while (*past_value && *past_value != ' '
1723 && *past_value != '\t' && *past_value != ')')
1725 termination = past_value;
1726 while (*termination && (*termination == ' ' || *termination == '\t'))
1728 if (*termination++ != ')')
1730 if (*termination && *termination != ' ' && *termination != '\t')
1732 /* Temporarily null-terminate the value. */
1733 save_char = *termination;
1734 *termination = '\0';
1735 /* Install the assertion. */
1736 make_assertion ("-A", assertion);
1737 *termination = (char) save_char;
1739 while (*p == ' ' || *p == '\t')
1747 /* Now handle the command line options. */
1749 /* Do -U's, -D's and -A's in the order they were seen. */
1750 for (i = 1; i < argc; i++) {
1751 if (pend_undefs[i]) {
1753 output_line_command (fp, &outbuf, 0, same_file);
1754 make_undef (pend_undefs[i], &outbuf);
1758 output_line_command (fp, &outbuf, 0, same_file);
1759 make_definition (pend_defs[i], &outbuf);
1761 if (pend_assertions[i])
1762 make_assertion (pend_assertion_options[i], pend_assertions[i]);
1765 done_initializing = 1;
1767 { /* read the appropriate environment variable and if it exists
1768 replace include_defaults with the listed path. */
1770 switch ((objc << 1) + cplusplus)
1773 epath = getenv ("C_INCLUDE_PATH");
1776 epath = getenv ("CPLUS_INCLUDE_PATH");
1779 epath = getenv ("OBJC_INCLUDE_PATH");
1782 epath = getenv ("OBJCPLUS_INCLUDE_PATH");
1785 /* If the environment var for this language is set,
1786 add to the default list of include directories. */
1788 char *nstore = (char *) alloca (strlen (epath) + 2);
1790 char *startp, *endp;
1792 for (num_dirs = 1, startp = epath; *startp; startp++)
1793 if (*startp == PATH_SEPARATOR)
1796 = (struct default_include *) xmalloc ((num_dirs
1797 * sizeof (struct default_include))
1798 + sizeof (include_defaults_array));
1799 startp = endp = epath;
1802 /* Handle cases like c:/usr/lib:d:/gcc/lib */
1803 if ((*endp == PATH_SEPARATOR
1804 #if 0 /* Obsolete, now that we use semicolons as the path separator. */
1806 && (endp-startp != 1 || !isalpha (*startp))
1811 strncpy (nstore, startp, endp-startp);
1813 strcpy (nstore, ".");
1815 nstore[endp-startp] = '\0';
1817 include_defaults[num_dirs].fname = savestring (nstore);
1818 include_defaults[num_dirs].cplusplus = cplusplus;
1819 include_defaults[num_dirs].cxx_aware = 1;
1823 endp = startp = endp + 1;
1827 /* Put the usual defaults back in at the end. */
1828 bcopy ((char *) include_defaults_array,
1829 (char *) &include_defaults[num_dirs],
1830 sizeof (include_defaults_array));
1834 append_include_chain (before_system, last_before_system);
1835 first_system_include = before_system;
1837 /* Unless -fnostdinc,
1838 tack on the standard include file dirs to the specified list */
1839 if (!no_standard_includes) {
1840 struct default_include *p = include_defaults;
1841 char *specd_prefix = include_prefix;
1842 char *default_prefix = savestring (GCC_INCLUDE_DIR);
1843 int default_len = 0;
1844 /* Remove the `include' from /usr/local/lib/gcc.../include. */
1845 if (!strcmp (default_prefix + strlen (default_prefix) - 8, "/include")) {
1846 default_len = strlen (default_prefix) - 7;
1847 default_prefix[default_len] = 0;
1849 /* Search "translated" versions of GNU directories.
1850 These have /usr/local/lib/gcc... replaced by specd_prefix. */
1851 if (specd_prefix != 0 && default_len != 0)
1852 for (p = include_defaults; p->fname; p++) {
1853 /* Some standard dirs are only for C++. */
1854 if (!p->cplusplus || (cplusplus && !no_standard_cplusplus_includes)) {
1855 /* Does this dir start with the prefix? */
1856 if (!strncmp (p->fname, default_prefix, default_len)) {
1857 /* Yes; change prefix and add to search list. */
1858 struct file_name_list *new
1859 = (struct file_name_list *) xmalloc (sizeof (struct file_name_list));
1860 int this_len = strlen (specd_prefix) + strlen (p->fname) - default_len;
1861 char *str = (char *) xmalloc (this_len + 1);
1862 strcpy (str, specd_prefix);
1863 strcat (str, p->fname + default_len);
1865 new->control_macro = 0;
1866 new->c_system_include_path = !p->cxx_aware;
1867 new->got_name_map = 0;
1868 append_include_chain (new, new);
1869 if (first_system_include == 0)
1870 first_system_include = new;
1874 /* Search ordinary names for GNU include directories. */
1875 for (p = include_defaults; p->fname; p++) {
1876 /* Some standard dirs are only for C++. */
1877 if (!p->cplusplus || (cplusplus && !no_standard_cplusplus_includes)) {
1878 struct file_name_list *new
1879 = (struct file_name_list *) xmalloc (sizeof (struct file_name_list));
1880 new->control_macro = 0;
1881 new->c_system_include_path = !p->cxx_aware;
1882 new->fname = p->fname;
1883 new->got_name_map = 0;
1884 append_include_chain (new, new);
1885 if (first_system_include == 0)
1886 first_system_include = new;
1891 /* Tack the after_include chain at the end of the include chain. */
1892 append_include_chain (after_include, last_after_include);
1893 if (first_system_include == 0)
1894 first_system_include = after_include;
1896 /* With -v, print the list of dirs to search. */
1898 struct file_name_list *p;
1899 fprintf (stderr, "#include \"...\" search starts here:\n");
1900 for (p = include; p; p = p->next) {
1901 if (p == first_bracket_include)
1902 fprintf (stderr, "#include <...> search starts here:\n");
1903 fprintf (stderr, " %s\n", p->fname);
1905 fprintf (stderr, "End of search list.\n");
1908 /* Scan the -imacros files before the main input.
1909 Much like #including them, but with no_output set
1910 so that only their macro definitions matter. */
1912 no_output++; no_record_file++;
1913 for (i = 1; i < argc; i++)
1914 if (pend_files[i]) {
1915 int fd = open (pend_files[i], O_RDONLY, 0666);
1917 perror_with_name (pend_files[i]);
1918 return FAILURE_EXIT_CODE;
1920 finclude (fd, pend_files[i], &outbuf, 0, NULL_PTR);
1922 no_output--; no_record_file--;
1924 /* Copy the entire contents of the main input file into
1925 the stacked input buffer previously allocated for it. */
1927 /* JF check for stdin */
1928 if (in_fname == NULL || *in_fname == 0) {
1931 } else if ((f = open (in_fname, O_RDONLY, 0666)) < 0)
1934 /* -MG doesn't select the form of output and must be specified with one of
1935 -M or -MM. -MG doesn't make sense with -MD or -MMD since they don't
1936 inhibit compilation. */
1937 if (print_deps_missing_files && (print_deps == 0 || !inhibit_output))
1938 fatal ("-MG must be specified with one of -M or -MM");
1940 /* Either of two environment variables can specify output of deps.
1941 Its value is either "OUTPUT_FILE" or "OUTPUT_FILE DEPS_TARGET",
1942 where OUTPUT_FILE is the file to write deps info to
1943 and DEPS_TARGET is the target to mention in the deps. */
1946 && (getenv ("SUNPRO_DEPENDENCIES") != 0
1947 || getenv ("DEPENDENCIES_OUTPUT") != 0)) {
1948 char *spec = getenv ("DEPENDENCIES_OUTPUT");
1953 spec = getenv ("SUNPRO_DEPENDENCIES");
1960 /* Find the space before the DEPS_TARGET, if there is one. */
1961 /* This should use index. (mrs) */
1962 while (*s != 0 && *s != ' ') s++;
1964 deps_target = s + 1;
1965 output_file = (char *) xmalloc (s - spec + 1);
1966 bcopy (spec, output_file, s - spec);
1967 output_file[s - spec] = 0;
1974 deps_file = output_file;
1978 /* For -M, print the expected object file name
1979 as the target of this Make-rule. */
1981 deps_allocated_size = 200;
1982 deps_buffer = (char *) xmalloc (deps_allocated_size);
1988 deps_output (deps_target, ':');
1989 } else if (*in_fname == 0) {
1990 deps_output ("-", ':');
1995 /* Discard all directory prefixes from filename. */
1996 if ((q = rindex (in_fname, '/')) != NULL
1997 #ifdef DIR_SEPARATOR
1998 && (q = rindex (in_fname, DIR_SEPARATOR)) != NULL
2005 /* Copy remainder to mungable area. */
2006 p = (char *) alloca (strlen(q) + 8);
2009 /* Output P, but remove known suffixes. */
2013 && p[len - 2] == '.'
2014 && index("cCsSm", p[len - 1]))
2017 && p[len - 3] == '.'
2018 && p[len - 2] == 'c'
2019 && p[len - 1] == 'c')
2022 && p[len - 4] == '.'
2023 && p[len - 3] == 'c'
2024 && p[len - 2] == 'x'
2025 && p[len - 1] == 'x')
2028 && p[len - 4] == '.'
2029 && p[len - 3] == 'c'
2030 && p[len - 2] == 'p'
2031 && p[len - 1] == 'p')
2034 /* Supply our own suffix. */
2041 deps_output (p, ':');
2042 deps_output (in_fname, ' ');
2046 file_size_and_mode (f, &st_mode, &st_size);
2047 fp->nominal_fname = fp->fname = in_fname;
2049 fp->system_header_p = 0;
2050 /* JF all this is mine about reading pipes and ttys */
2051 if (! S_ISREG (st_mode)) {
2052 /* Read input from a file that is not a normal disk file.
2053 We cannot preallocate a buffer with the correct size,
2054 so we must read in the file a piece at the time and make it bigger. */
2061 fp->buf = (U_CHAR *) xmalloc (bsize + 2);
2063 cnt = safe_read (f, fp->buf + size, bsize - size);
2064 if (cnt < 0) goto perror; /* error! */
2066 if (size != bsize) break; /* End of file */
2068 fp->buf = (U_CHAR *) xrealloc (fp->buf, bsize + 2);
2072 /* Read a file whose size we can determine in advance.
2073 For the sake of VMS, st_size is just an upper bound. */
2074 fp->buf = (U_CHAR *) xmalloc (st_size + 2);
2075 fp->length = safe_read (f, fp->buf, st_size);
2076 if (fp->length < 0) goto perror;
2079 fp->if_stack = if_stack;
2081 /* Make sure data ends with a newline. And put a null after it. */
2083 if ((fp->length > 0 && fp->buf[fp->length - 1] != '\n')
2084 /* Backslash-newline at end is not good enough. */
2085 || (fp->length > 1 && fp->buf[fp->length - 2] == '\\')) {
2086 fp->buf[fp->length++] = '\n';
2087 missing_newline = 1;
2089 fp->buf[fp->length] = '\0';
2091 /* Unless inhibited, convert trigraphs in the input. */
2096 /* Now that we know the input file is valid, open the output. */
2098 if (!out_fname || !strcmp (out_fname, ""))
2099 out_fname = "stdout";
2100 else if (! freopen (out_fname, "w", stdout))
2101 pfatal_with_name (out_fname);
2103 output_line_command (fp, &outbuf, 0, same_file);
2105 /* Scan the -include files before the main input. */
2108 for (i = 1; i < argc; i++)
2109 if (pend_includes[i]) {
2110 int fd = open (pend_includes[i], O_RDONLY, 0666);
2112 perror_with_name (pend_includes[i]);
2113 return FAILURE_EXIT_CODE;
2115 finclude (fd, pend_includes[i], &outbuf, 0, NULL_PTR);
2119 /* Scan the input, processing macros and directives. */
2121 rescan (&outbuf, 0);
2123 if (missing_newline)
2126 if (pedantic && missing_newline)
2127 pedwarn ("file does not end in newline");
2129 /* Now we have processed the entire input
2130 Write whichever kind of output has been requested. */
2132 if (dump_macros == dump_only)
2134 else if (! inhibit_output) {
2139 /* Don't actually write the deps file if compilation has failed. */
2141 if (deps_file && ! (deps_stream = fopen (deps_file, deps_mode)))
2142 pfatal_with_name (deps_file);
2143 fputs (deps_buffer, deps_stream);
2144 putc ('\n', deps_stream);
2146 if (ferror (deps_stream) || fclose (deps_stream) != 0)
2147 fatal ("I/O error on output");
2152 if (pcp_outfile && pcp_outfile != stdout
2153 && (ferror (pcp_outfile) || fclose (pcp_outfile) != 0))
2154 fatal ("I/O error on `-pcp' output");
2156 if (ferror (stdout) || fclose (stdout) != 0)
2157 fatal ("I/O error on output");
2160 exit (FAILURE_EXIT_CODE);
2161 exit (SUCCESS_EXIT_CODE);
2164 pfatal_with_name (in_fname);
2168 /* Given a colon-separated list of file names PATH,
2169 add all the names to the search path for include files. */
2183 struct file_name_list *dirtmp;
2185 /* Find the end of this name. */
2186 while (*q != 0 && *q != PATH_SEPARATOR) q++;
2188 /* An empty name in the path stands for the current directory. */
2189 name = (char *) xmalloc (2);
2193 /* Otherwise use the directory that is named. */
2194 name = (char *) xmalloc (q - p + 1);
2195 bcopy (p, name, q - p);
2199 dirtmp = (struct file_name_list *)
2200 xmalloc (sizeof (struct file_name_list));
2201 dirtmp->next = 0; /* New one goes on the end */
2202 dirtmp->control_macro = 0;
2203 dirtmp->c_system_include_path = 0;
2204 dirtmp->fname = name;
2205 dirtmp->got_name_map = 0;
2206 append_include_chain (dirtmp, dirtmp);
2208 /* Advance past this name. */
2212 /* Skip the colon. */
2217 /* Return the address of the first character in S that equals C.
2218 S is an array of length N, possibly containing '\0's, and followed by '\0'.
2219 Return 0 if there is no such character. Assume that C itself is not '\0'.
2220 If we knew we could use memchr, we could just invoke memchr (S, C, N),
2221 but unfortunately memchr isn't autoconfigured yet. */
2230 char *q = index (s, c);
2232 return (U_CHAR *) q;
2244 /* Pre-C-Preprocessor to translate ANSI trigraph idiocy in BUF
2245 before main CCCP processing. Name `pcp' is also in honor of the
2246 drugs the trigraph designers must have been on.
2248 Using an extra pass through the buffer takes a little extra time,
2249 but is infinitely less hairy than trying to handle trigraphs inside
2250 strings, etc. everywhere, and also makes sure that trigraphs are
2251 only translated in the top level of processing. */
2257 register U_CHAR c, *fptr, *bptr, *sptr, *lptr;
2260 fptr = bptr = sptr = buf->buf;
2261 lptr = fptr + buf->length;
2262 while ((sptr = (U_CHAR *) index0 (sptr, '?', lptr - sptr)) != NULL) {
2299 len = sptr - fptr - 2;
2301 /* BSD doc says bcopy () works right for overlapping strings. In ANSI
2302 C, this will be memmove (). */
2303 if (bptr != fptr && len > 0)
2304 bcopy ((char *) fptr, (char *) bptr, len);
2310 len = buf->length - (fptr - buf->buf);
2311 if (bptr != fptr && len > 0)
2312 bcopy ((char *) fptr, (char *) bptr, len);
2313 buf->length -= fptr - bptr;
2314 buf->buf[buf->length] = '\0';
2315 if (warn_trigraphs && fptr != bptr)
2316 warning ("%d trigraph(s) encountered", (fptr - bptr) / 2);
2319 /* Move all backslash-newline pairs out of embarrassing places.
2320 Exchange all such pairs following BP
2321 with any potentially-embarrassing characters that follow them.
2322 Potentially-embarrassing characters are / and *
2323 (because a backslash-newline inside a comment delimiter
2324 would cause it not to be recognized). */
2330 register U_CHAR *p = bp;
2332 /* First count the backslash-newline pairs here. */
2334 while (p[0] == '\\' && p[1] == '\n')
2337 /* What follows the backslash-newlines is not embarrassing. */
2339 if (*p != '/' && *p != '*')
2342 /* Copy all potentially embarrassing characters
2343 that follow the backslash-newline pairs
2344 down to where the pairs originally started. */
2346 while (*p == '*' || *p == '/')
2349 /* Now write the same number of pairs after the embarrassing chars. */
2356 /* Like newline_fix but for use within a directive-name.
2357 Move any backslash-newlines up past any following symbol constituents. */
2360 name_newline_fix (bp)
2363 register U_CHAR *p = bp;
2365 /* First count the backslash-newline pairs here. */
2366 while (p[0] == '\\' && p[1] == '\n')
2369 /* What follows the backslash-newlines is not embarrassing. */
2374 /* Copy all potentially embarrassing characters
2375 that follow the backslash-newline pairs
2376 down to where the pairs originally started. */
2378 while (is_idchar[*p])
2381 /* Now write the same number of pairs after the embarrassing chars. */
2388 /* Look for lint commands in comments.
2390 When we come in here, ibp points into a comment. Limit is as one expects.
2391 scan within the comment -- it should start, after lwsp, with a lint command.
2392 If so that command is returned as a (constant) string.
2394 Upon return, any arg will be pointed to with argstart and will be
2395 arglen long. Note that we don't parse that arg since it will just
2396 be printed out again.
2400 get_lintcmd (ibp, limit, argstart, arglen, cmdlen)
2401 register U_CHAR *ibp;
2402 register U_CHAR *limit;
2403 U_CHAR **argstart; /* point to command arg */
2404 int *arglen, *cmdlen; /* how long they are */
2407 register U_CHAR *numptr; /* temp for arg parsing */
2411 SKIP_WHITE_SPACE (ibp);
2413 if (ibp >= limit) return NULL;
2415 linsize = limit - ibp;
2417 /* Oh, I wish C had lexical functions... hell, I'll just open-code the set */
2418 if ((linsize >= 10) && !strncmp (ibp, "NOTREACHED", 10)) {
2420 return "NOTREACHED";
2422 if ((linsize >= 8) && !strncmp (ibp, "ARGSUSED", 8)) {
2426 if ((linsize >= 11) && !strncmp (ibp, "LINTLIBRARY", 11)) {
2428 return "LINTLIBRARY";
2430 if ((linsize >= 7) && !strncmp (ibp, "VARARGS", 7)) {
2432 ibp += 7; linsize -= 7;
2433 if ((linsize == 0) || ! isdigit (*ibp)) return "VARARGS";
2435 /* OK, read a number */
2436 for (numptr = *argstart = ibp; (numptr < limit) && isdigit (*numptr);
2438 *arglen = numptr - *argstart;
2445 * The main loop of the program.
2447 * Read characters from the input stack, transferring them to the
2450 * Macros are expanded and push levels on the input stack.
2451 * At the end of such a level it is popped off and we keep reading.
2452 * At the end of any other kind of level, we return.
2453 * #-directives are handled, except within macros.
2455 * If OUTPUT_MARKS is nonzero, keep Newline markers found in the input
2456 * and insert them when appropriate. This is set while scanning macro
2457 * arguments before substitution. It is zero when scanning for final output.
2458 * There are three types of Newline markers:
2459 * * Newline - follows a macro name that was not expanded
2460 * because it appeared inside an expansion of the same macro.
2461 * This marker prevents future expansion of that identifier.
2462 * When the input is rescanned into the final output, these are deleted.
2463 * These are also deleted by ## concatenation.
2464 * * Newline Space (or Newline and any other whitespace character)
2465 * stands for a place that tokens must be separated or whitespace
2466 * is otherwise desirable, but where the ANSI standard specifies there
2467 * is no whitespace. This marker turns into a Space (or whichever other
2468 * whitespace char appears in the marker) in the final output,
2469 * but it turns into nothing in an argument that is stringified with #.
2470 * Such stringified arguments are the only place where the ANSI standard
2471 * specifies with precision that whitespace may not appear.
2473 * During this function, IP->bufp is kept cached in IBP for speed of access.
2474 * Likewise, OP->bufp is kept in OBP. Before calling a subroutine
2475 * IBP, IP and OBP must be copied back to memory. IP and IBP are
2476 * copied back with the RECACHE macro. OBP must be copied back from OP->bufp
2477 * explicitly, and before RECACHE, since RECACHE uses OBP.
2481 rescan (op, output_marks)
2485 /* Character being scanned in main loop. */
2488 /* Length of pending accumulated identifier. */
2489 register int ident_length = 0;
2491 /* Hash code of pending accumulated identifier. */
2492 register int hash = 0;
2494 /* Current input level (&instack[indepth]). */
2497 /* Pointer for scanning input. */
2498 register U_CHAR *ibp;
2500 /* Pointer to end of input. End of scan is controlled by LIMIT. */
2501 register U_CHAR *limit;
2503 /* Pointer for storing output. */
2504 register U_CHAR *obp;
2506 /* REDO_CHAR is nonzero if we are processing an identifier
2507 after backing up over the terminating character.
2508 Sometimes we process an identifier without backing up over
2509 the terminating character, if the terminating character
2510 is not special. Backing up is done so that the terminating character
2511 will be dispatched on again once the identifier is dealt with. */
2514 /* 1 if within an identifier inside of which a concatenation
2515 marker (Newline -) has been seen. */
2516 int concatenated = 0;
2518 /* While scanning a comment or a string constant,
2519 this records the line it started on, for error messages. */
2522 /* Record position of last `real' newline. */
2523 U_CHAR *beg_of_line;
2525 /* Pop the innermost input stack level, assuming it is a macro expansion. */
2528 do { ip->macro->type = T_MACRO; \
2529 if (ip->free_ptr) free (ip->free_ptr); \
2530 --indepth; } while (0)
2532 /* Reload `rescan's local variables that describe the current
2533 level of the input stack. */
2536 do { ip = &instack[indepth]; \
2538 limit = ip->buf + ip->length; \
2540 check_expand (op, limit - ibp); \
2542 obp = op->bufp; } while (0)
2544 if (no_output && instack[indepth].fname != 0)
2545 skip_if_group (&instack[indepth], 1, NULL);
2552 /* Our caller must always put a null after the end of
2553 the input at each input stack level. */
2563 if (*ibp == '\n' && !ip->macro) {
2564 /* At the top level, always merge lines ending with backslash-newline,
2565 even in middle of identifier. But do not merge lines in a macro,
2566 since backslash might be followed by a newline-space marker. */
2569 --obp; /* remove backslash from obuf */
2572 /* If ANSI, backslash is just another character outside a string. */
2575 /* Otherwise, backslash suppresses specialness of following char,
2576 so copy it here to prevent the switch from seeing it.
2577 But first get any pending identifier processed. */
2578 if (ident_length > 0)
2585 if (assertions_flag) {
2586 /* Copy #foo (bar lose) without macro expansion. */
2587 SKIP_WHITE_SPACE (ibp);
2588 while (is_idchar[*ibp])
2590 SKIP_WHITE_SPACE (ibp);
2593 skip_paren_group (ip);
2594 bcopy ((char *) ibp, (char *) obp, ip->bufp - ibp);
2595 obp += ip->bufp - ibp;
2600 /* If this is expanding a macro definition, don't recognize
2601 preprocessor directives. */
2604 /* If this is expand_into_temp_buffer, recognize them
2605 only after an actual newline at this level,
2606 not at the beginning of the input level. */
2607 if (ip->fname == 0 && beg_of_line == ip->buf)
2613 /* # keyword: a # must be first nonblank char on the line */
2614 if (beg_of_line == 0)
2619 /* Scan from start of line, skipping whitespace, comments
2620 and backslash-newlines, and see if we reach this #.
2621 If not, this # is not special. */
2623 /* If -traditional, require # to be at beginning of line. */
2626 if (is_hor_space[*bp])
2628 else if (*bp == '\\' && bp[1] == '\n')
2630 else if (*bp == '/' && bp[1] == '*') {
2632 while (!(*bp == '*' && bp[1] == '/'))
2636 /* There is no point in trying to deal with C++ // comments here,
2637 because if there is one, then this # must be part of the
2638 comment and we would never reach here. */
2645 /* This # can start a directive. */
2647 --obp; /* Don't copy the '#' */
2651 if (! handle_directive (ip, op)) {
2655 /* Not a known directive: treat it as ordinary text.
2656 IP, OP, IBP, etc. have not been changed. */
2657 if (no_output && instack[indepth].fname) {
2658 /* If not generating expanded output,
2659 what we do with ordinary text is skip it.
2660 Discard everything until next # directive. */
2661 skip_if_group (&instack[indepth], 1, 0);
2666 ++obp; /* Copy the '#' after all */
2667 /* Don't expand an identifier that could be a macro directive.
2668 (Section 3.8.3 of the ANSI C standard) */
2669 SKIP_WHITE_SPACE (ibp);
2670 if (is_idstart[*ibp])
2673 while (is_idchar[*ibp])
2681 /* A # directive has been successfully processed. */
2682 /* If not generating expanded output, ignore everything until
2683 next # directive. */
2684 if (no_output && instack[indepth].fname)
2685 skip_if_group (&instack[indepth], 1, 0);
2691 case '\"': /* skip quoted string */
2693 /* A single quoted string is treated like a double -- some
2694 programs (e.g., troff) are perverse this way */
2699 start_line = ip->lineno;
2701 /* Skip ahead to a matching quote. */
2705 if (ip->macro != 0) {
2706 /* try harder: this string crosses a macro expansion boundary.
2707 This can happen naturally if -traditional.
2708 Otherwise, only -D can make a macro with an unmatched quote. */
2714 error_with_line (line_for_error (start_line),
2715 "unterminated string or character constant");
2716 error_with_line (multiline_string_line,
2717 "possible real start of unterminated constant");
2718 multiline_string_line = 0;
2727 /* Traditionally, end of line ends a string constant with no error.
2728 So exit the loop and record the new line. */
2734 error_with_line (line_for_error (start_line),
2735 "unterminated character constant");
2738 if (pedantic && multiline_string_line == 0) {
2739 pedwarn_with_line (line_for_error (start_line),
2740 "string constant runs past end of line");
2742 if (multiline_string_line == 0)
2743 multiline_string_line = ip->lineno - 1;
2750 /* Backslash newline is replaced by nothing at all,
2751 but keep the line counts correct. */
2756 /* ANSI stupidly requires that in \\ the second \
2757 is *not* prevented from combining with a newline. */
2758 while (*ibp == '\\' && ibp[1] == '\n') {
2777 if (*ibp == '\\' && ibp[1] == '\n')
2781 && !(cplusplus_comments && *ibp == '/'))
2789 /* C++ style comment... */
2790 start_line = ip->lineno;
2792 --ibp; /* Back over the slash */
2795 /* Comments are equivalent to spaces. */
2796 if (! put_out_comments)
2799 /* must fake up a comment here */
2804 U_CHAR *before_bp = ibp+2;
2806 while (ibp < limit) {
2807 if (ibp[-1] != '\\' && *ibp == '\n') {
2808 if (put_out_comments) {
2809 bcopy ((char *) before_bp, (char *) obp, ibp - before_bp);
2810 obp += ibp - before_bp;
2816 /* Copy the newline into the output buffer, in order to
2817 avoid the pain of a #line every time a multiline comment
2819 if (!put_out_comments)
2830 /* Ordinary C comment. Skip it, optionally copying it to output. */
2832 start_line = ip->lineno;
2834 ++ibp; /* Skip the star. */
2836 /* If this cpp is for lint, we peek inside the comments: */
2840 char *lintcmd = get_lintcmd (ibp, limit, &argbp, &arglen, &cmdlen);
2842 if (lintcmd != NULL) {
2844 check_expand (op, cmdlen + arglen + 14);
2846 /* I believe it is always safe to emit this newline: */
2848 bcopy ("#pragma lint ", (char *) obp, 13);
2850 bcopy (lintcmd, (char *) obp, cmdlen);
2855 bcopy (argbp, (char *) obp, arglen);
2859 /* OK, now bring us back to the state we were in before we entered
2860 this branch. We need #line because the #pragma's newline always
2861 messes up the line count. */
2863 output_line_command (ip, op, 0, same_file);
2864 check_expand (op, limit - ibp + 2);
2870 /* Comments are equivalent to spaces.
2871 Note that we already output the slash; we might not want it.
2872 For -traditional, a comment is equivalent to nothing. */
2873 if (! put_out_comments) {
2883 U_CHAR *before_bp = ibp;
2885 while (ibp < limit) {
2888 if (warn_comments && *ibp == '*')
2889 warning ("`/*' within comment");
2892 if (*ibp == '\\' && ibp[1] == '\n')
2894 if (ibp >= limit || *ibp == '/')
2899 /* Copy the newline into the output buffer, in order to
2900 avoid the pain of a #line every time a multiline comment
2902 if (!put_out_comments)
2910 error_with_line (line_for_error (start_line),
2911 "unterminated comment");
2914 if (put_out_comments) {
2915 bcopy ((char *) before_bp, (char *) obp, ibp - before_bp);
2916 obp += ibp - before_bp;
2923 if (!dollars_in_ident)
2927 case '0': case '1': case '2': case '3': case '4':
2928 case '5': case '6': case '7': case '8': case '9':
2929 /* If digit is not part of identifier, it starts a number,
2930 which means that following letters are not an identifier.
2931 "0x5" does not refer to an identifier "x5".
2932 So copy all alphanumerics that follow without accumulating
2933 as an identifier. Periods also, for sake of "3.e7". */
2935 if (ident_length == 0) {
2937 while (ibp[0] == '\\' && ibp[1] == '\n') {
2942 if (!is_idchar[c] && c != '.') {
2947 /* A sign can be part of a preprocessing number
2948 if it follows an e. */
2949 if (c == 'e' || c == 'E') {
2950 while (ibp[0] == '\\' && ibp[1] == '\n') {
2954 if (*ibp == '+' || *ibp == '-') {
2956 /* But traditional C does not let the token go past the sign. */
2967 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
2968 case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
2969 case 'm': case 'n': case 'o': case 'p': case 'q': case 'r':
2970 case 's': case 't': case 'u': case 'v': case 'w': case 'x':
2972 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
2973 case 'G': case 'H': case 'I': case 'J': case 'K': case 'L':
2974 case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R':
2975 case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
2979 /* Compute step of hash function, to avoid a proc call on every token */
2980 hash = HASHSTEP (hash, c);
2984 if (ip->fname == 0 && *ibp == '-') {
2985 /* Newline - inhibits expansion of preceding token.
2986 If expanding a macro arg, we keep the newline -.
2987 In final output, it is deleted.
2988 We recognize Newline - in macro bodies and macro args. */
2989 if (! concatenated) {
2994 if (!output_marks) {
2997 /* If expanding a macro arg, keep the newline -. */
3003 /* If reprocessing a macro expansion, newline is a special marker. */
3004 else if (ip->macro != 0) {
3005 /* Newline White is a "funny space" to separate tokens that are
3006 supposed to be separate but without space between.
3007 Here White means any whitespace character.
3008 Newline - marks a recursive macro use that is not
3009 supposed to be expandable. */
3011 if (is_space[*ibp]) {
3012 /* Newline Space does not prevent expansion of preceding token
3013 so expand the preceding token and then come back. */
3014 if (ident_length > 0)
3017 /* If generating final output, newline space makes a space. */
3018 if (!output_marks) {
3020 /* And Newline Newline makes a newline, so count it. */
3021 if (obp[-1] == '\n')
3024 /* If expanding a macro arg, keep the newline space.
3025 If the arg gets stringified, newline space makes nothing. */
3028 } else abort (); /* Newline followed by something random? */
3032 /* If there is a pending identifier, handle it and come back here. */
3033 if (ident_length > 0)
3038 /* Update the line counts and output a #line if necessary. */
3041 if (ip->lineno != op->lineno) {
3043 output_line_command (ip, op, 1, same_file);
3044 check_expand (op, limit - ibp);
3049 /* Come here either after (1) a null character that is part of the input
3050 or (2) at the end of the input, because there is a null there. */
3053 /* Our input really contains a null character. */
3056 /* At end of a macro-expansion level, pop it and read next level. */
3057 if (ip->macro != 0) {
3060 /* If traditional, and we have an identifier that ends here,
3061 process it now, so we get the right error for recursion. */
3062 if (traditional && ident_length
3063 && ! is_idchar[*instack[indepth - 1].bufp]) {
3072 /* If we don't have a pending identifier,
3073 return at end of input. */
3074 if (ident_length == 0) {
3082 /* If we do have a pending identifier, just consider this null
3083 a special character and arrange to dispatch on it again.
3084 The second time, IDENT_LENGTH will be zero so we will return. */
3090 /* Handle the case of a character such as /, ', " or null
3091 seen following an identifier. Back over it so that
3092 after the identifier is processed the special char
3093 will be dispatched on again. */
3103 if (ident_length > 0) {
3104 register HASHNODE *hp;
3106 /* We have just seen an identifier end. If it's a macro, expand it.
3108 IDENT_LENGTH is the length of the identifier
3109 and HASH is its hash code.
3111 The identifier has already been copied to the output,
3112 so if it is a macro we must remove it.
3114 If REDO_CHAR is 0, the char that terminated the identifier
3115 has been skipped in the output and the input.
3116 OBP-IDENT_LENGTH-1 points to the identifier.
3117 If the identifier is a macro, we must back over the terminator.
3119 If REDO_CHAR is 1, the terminating char has already been
3120 backed over. OBP-IDENT_LENGTH points to the identifier. */
3122 if (!pcp_outfile || pcp_inside_if) {
3124 for (hp = hashtab[MAKE_POS (hash) % HASHSIZE]; hp != NULL;
3127 if (hp->length == ident_length) {
3128 int obufp_before_macroname;
3129 int op_lineno_before_macroname;
3130 register int i = ident_length;
3131 register U_CHAR *p = hp->name;
3132 register U_CHAR *q = obp - i;
3138 do { /* All this to avoid a strncmp () */
3143 /* We found a use of a macro name.
3144 see if the context shows it is a macro call. */
3146 /* Back up over terminating character if not already done. */
3152 /* Save this as a displacement from the beginning of the output
3153 buffer. We can not save this as a position in the output
3154 buffer, because it may get realloc'ed by RECACHE. */
3155 obufp_before_macroname = (obp - op->buf) - ident_length;
3156 op_lineno_before_macroname = op->lineno;
3158 if (hp->type == T_PCSTRING) {
3159 pcstring_used (hp); /* Mark the definition of this key
3160 as needed, ensuring that it
3162 break; /* Exit loop, since the key cannot have a
3163 definition any longer. */
3166 /* Record whether the macro is disabled. */
3167 disabled = hp->type == T_DISABLED;
3169 /* This looks like a macro ref, but if the macro was disabled,
3170 just copy its name and put in a marker if requested. */
3174 /* This error check caught useful cases such as
3175 #define foo(x,y) bar (x (y,0), y)
3178 error ("recursive use of macro `%s'", hp->name);
3182 check_expand (op, limit - ibp + 2);
3189 /* If macro wants an arglist, verify that a '(' follows.
3190 first skip all whitespace, copying it to the output
3191 after the macro name. Then, if there is no '(',
3192 decide this is not a macro call and leave things that way. */
3193 if ((hp->type == T_MACRO || hp->type == T_DISABLED)
3194 && hp->value.defn->nargs >= 0)
3196 U_CHAR *old_ibp = ibp;
3197 U_CHAR *old_obp = obp;
3198 int old_iln = ip->lineno;
3199 int old_oln = op->lineno;
3202 /* Scan forward over whitespace, copying it to the output. */
3203 if (ibp == limit && ip->macro != 0) {
3208 old_iln = ip->lineno;
3209 old_oln = op->lineno;
3211 /* A comment: copy it unchanged or discard it. */
3212 else if (*ibp == '/' && ibp[1] == '*') {
3213 if (put_out_comments) {
3216 } else if (! traditional) {
3220 while (ibp + 1 != limit
3221 && !(ibp[0] == '*' && ibp[1] == '/')) {
3222 /* We need not worry about newline-marks,
3223 since they are never found in comments. */
3225 /* Newline in a file. Count it. */
3229 if (put_out_comments)
3235 if (put_out_comments) {
3240 else if (is_space[*ibp]) {
3242 if (ibp[-1] == '\n') {
3243 if (ip->macro == 0) {
3244 /* Newline in a file. Count it. */
3247 } else if (!output_marks) {
3248 /* A newline mark, and we don't want marks
3249 in the output. If it is newline-hyphen,
3250 discard it entirely. Otherwise, it is
3251 newline-whitechar, so keep the whitechar. */
3261 /* A newline mark; copy both chars to the output. */
3269 /* It isn't a macro call.
3270 Put back the space that we just skipped. */
3273 ip->lineno = old_iln;
3274 op->lineno = old_oln;
3275 /* Exit the for loop. */
3280 /* This is now known to be a macro call.
3281 Discard the macro name from the output,
3282 along with any following whitespace just copied,
3283 but preserve newlines if not outputting marks since this
3284 is more likely to do the right thing with line numbers. */
3285 obp = op->buf + obufp_before_macroname;
3287 op->lineno = op_lineno_before_macroname;
3289 int newlines = op->lineno - op_lineno_before_macroname;
3290 while (0 < newlines--)
3294 /* Prevent accidental token-pasting with a character
3295 before the macro call. */
3296 if (!traditional && obp != op->buf) {
3298 case '&': case '+': case '-': case '<': case '>': case '|':
3299 /* If we are expanding a macro arg, make a newline marker
3300 to separate the tokens. If we are making real output,
3301 a plain space will do. */
3308 /* Expand the macro, reading arguments as needed,
3309 and push the expansion on the input stack. */
3312 macroexpand (hp, op);
3314 /* Reexamine input stack, since macroexpand has pushed
3315 a new level on it. */
3322 } /* End hash-table-search loop */
3324 ident_length = hash = 0; /* Stop collecting identifier */
3327 } /* End if (ident_length > 0) */
3329 } /* End per-char loop */
3331 /* Come here to return -- but first give an error message
3332 if there was an unterminated successful conditional. */
3334 if (if_stack != ip->if_stack)
3336 char *str = "unknown";
3338 switch (if_stack->type)
3357 error_with_line (line_for_error (if_stack->lineno),
3358 "unterminated `#%s' conditional", str);
3360 if_stack = ip->if_stack;
3364 * Rescan a string into a temporary buffer and return the result
3365 * as a FILE_BUF. Note this function returns a struct, not a pointer.
3367 * OUTPUT_MARKS nonzero means keep Newline markers found in the input
3368 * and insert such markers when appropriate. See `rescan' for details.
3369 * OUTPUT_MARKS is 1 for macroexpanding a macro argument separately
3370 * before substitution; it is 0 for other uses.
3373 expand_to_temp_buffer (buf, limit, output_marks, assertions)
3374 U_CHAR *buf, *limit;
3375 int output_marks, assertions;
3377 register FILE_BUF *ip;
3379 int length = limit - buf;
3381 int odepth = indepth;
3382 int save_assertions_flag = assertions_flag;
3384 assertions_flag = assertions;
3389 /* Set up the input on the input stack. */
3391 buf1 = (U_CHAR *) alloca (length + 1);
3393 register U_CHAR *p1 = buf;
3394 register U_CHAR *p2 = buf1;
3401 /* Set up to receive the output. */
3403 obuf.length = length * 2 + 100; /* Usually enough. Why be stingy? */
3404 obuf.bufp = obuf.buf = (U_CHAR *) xmalloc (obuf.length);
3409 CHECK_DEPTH ({return obuf;});
3413 ip = &instack[indepth];
3415 ip->nominal_fname = 0;
3416 ip->system_header_p = 0;
3419 ip->length = length;
3420 ip->buf = ip->bufp = buf1;
3421 ip->if_stack = if_stack;
3423 ip->lineno = obuf.lineno = 1;
3425 /* Scan the input, create the output. */
3426 rescan (&obuf, output_marks);
3428 /* Pop input stack to original state. */
3431 if (indepth != odepth)
3434 /* Record the output. */
3435 obuf.length = obuf.bufp - obuf.buf;
3437 assertions_flag = save_assertions_flag;
3442 * Process a # directive. Expects IP->bufp to point after the '#', as in
3443 * `#define foo bar'. Passes to the command handler
3444 * (do_define, do_include, etc.): the addresses of the 1st and
3445 * last chars of the command (starting immediately after the #
3446 * keyword), plus op and the keyword table pointer. If the command
3447 * contains comments it is copied into a temporary buffer sans comments
3448 * and the temporary buffer is passed to the command handler instead.
3449 * Likewise for backslash-newlines.
3451 * Returns nonzero if this was a known # directive.
3452 * Otherwise, returns zero, without advancing the input pointer.
3456 handle_directive (ip, op)
3459 register U_CHAR *bp, *cp;
3460 register struct directive *kt;
3461 register int ident_length;
3464 /* Nonzero means we must copy the entire command
3465 to get rid of comments or backslash-newlines. */
3466 int copy_command = 0;
3468 U_CHAR *ident, *after_ident;
3472 /* Record where the directive started. do_xifdef needs this. */
3473 directive_start = bp - 1;
3475 /* Skip whitespace and \-newline. */
3477 if (is_hor_space[*bp]) {
3478 if (*bp != ' ' && *bp != '\t' && pedantic)
3479 pedwarn ("%s in preprocessing directive", char_name[*bp]);
3481 } else if (*bp == '/' && (bp[1] == '*'
3482 || (cplusplus_comments && bp[1] == '/'))) {
3484 skip_to_end_of_comment (ip, &ip->lineno, 0);
3486 } else if (*bp == '\\' && bp[1] == '\n') {
3487 bp += 2; ip->lineno++;
3491 /* Now find end of directive name.
3492 If we encounter a backslash-newline, exchange it with any following
3493 symbol-constituents so that we end up with a contiguous name. */
3500 if (*cp == '\\' && cp[1] == '\n')
3501 name_newline_fix (cp);
3507 ident_length = cp - bp;
3511 /* A line of just `#' becomes blank. */
3513 if (ident_length == 0 && *after_ident == '\n') {
3514 ip->bufp = after_ident;
3518 if (ident_length == 0 || !is_idstart[*ident]) {
3520 while (is_idchar[*p]) {
3521 if (*p < '0' || *p > '9')
3525 /* Handle # followed by a line number. */
3526 if (p != ident && !is_idchar[*p]) {
3527 static struct directive line_directive_table[] = {
3528 { 4, do_line, "line", T_LINE},
3531 pedwarn ("`#' followed by integer");
3532 after_ident = ident;
3533 kt = line_directive_table;
3537 /* Avoid error for `###' and similar cases unless -pedantic. */
3539 while (*p == '#' || is_hor_space[*p]) p++;
3541 if (pedantic && !lang_asm)
3542 warning ("invalid preprocessor directive");
3548 error ("invalid preprocessor directive name");
3554 * Decode the keyword and call the appropriate expansion
3555 * routine, after moving the input pointer up to the next line.
3557 for (kt = directive_table; kt->length > 0; kt++) {
3558 if (kt->length == ident_length && !strncmp (kt->name, ident, ident_length)) {
3559 register U_CHAR *buf;
3560 register U_CHAR *limit;
3563 int *already_output;
3565 /* Nonzero means do not delete comments within the directive.
3566 #define needs this when -traditional. */
3571 limit = ip->buf + ip->length;
3574 keep_comments = traditional && kt->traditional_comments;
3575 /* #import is defined only in Objective C, or when on the NeXT. */
3576 if (kt->type == T_IMPORT && !(objc || lookup ("__NeXT__", -1, -1)))
3579 /* Find the end of this command (first newline not backslashed
3580 and not in a string or comment).
3581 Set COPY_COMMAND if the command must be copied
3582 (it contains a backslash-newline or a comment). */
3584 buf = bp = after_ident;
3585 while (bp < limit) {
3586 register U_CHAR c = *bp++;
3594 } else if (traditional)
3601 bp = skip_quoted_string (bp - 1, limit, ip->lineno, &ip->lineno, ©_command, &unterminated);
3602 /* Don't bother calling the directive if we already got an error
3603 message due to unterminated string. Skip everything and pretend
3604 we called the directive. */
3607 /* Traditional preprocessing permits unterminated strings. */
3616 /* <...> is special for #include. */
3618 if (!kt->angle_brackets)
3620 while (bp < limit && *bp != '>' && *bp != '\n') {
3621 if (*bp == '\\' && bp[1] == '\n') {
3631 if (*bp == '\\' && bp[1] == '\n')
3634 || (cplusplus_comments && *bp == '/')) {
3635 U_CHAR *obp = bp - 1;
3637 skip_to_end_of_comment (ip, &ip->lineno, 0);
3639 /* No need to copy the command because of a comment at the end;
3640 just don't include the comment in the directive. */
3641 if (bp == limit || *bp == '\n') {
3645 /* Don't remove the comments if -traditional. */
3646 if (! keep_comments)
3655 pedwarn ("%s in preprocessing directive", char_name[c]);
3659 --bp; /* Point to the newline */
3667 resume_p = ip->bufp;
3668 /* BP is the end of the directive.
3669 RESUME_P is the next interesting data after the directive.
3670 A comment may come between. */
3672 /* If a directive should be copied through, and -E was given,
3673 pass it through before removing comments. */
3674 if (!no_output && kt->pass_thru && put_out_comments) {
3677 /* Output directive name. */
3678 check_expand (op, kt->length + 2);
3679 /* Make sure # is at the start of a line */
3680 if (op->bufp > op->buf && op->bufp[-1] != '\n') {
3685 bcopy (kt->name, op->bufp, kt->length);
3686 op->bufp += kt->length;
3688 /* Output arguments. */
3690 check_expand (op, len);
3691 bcopy (buf, (char *) op->bufp, len);
3693 /* Take account of any (escaped) newlines just output. */
3695 if (buf[len] == '\n')
3698 already_output = &junk;
3699 } /* Don't we need a newline or #line? */
3702 register U_CHAR *xp = buf;
3703 /* Need to copy entire command into temp buffer before dispatching */
3705 cp = (U_CHAR *) alloca (bp - buf + 5); /* room for cmd plus
3709 /* Copy to the new buffer, deleting comments
3710 and backslash-newlines (and whitespace surrounding the latter). */
3713 register U_CHAR c = *xp++;
3718 abort (); /* A bare newline should never part of the line. */
3721 /* <...> is special for #include. */
3723 if (!kt->angle_brackets)
3725 while (xp < bp && c != '>') {
3727 if (c == '\\' && xp < bp && *xp == '\n')
3738 if (cp != buf && is_space[cp[-1]]) {
3739 while (cp != buf && is_space[cp[-1]]) cp--;
3741 SKIP_WHITE_SPACE (xp);
3742 } else if (is_space[*xp]) {
3744 SKIP_WHITE_SPACE (xp);
3746 } else if (traditional && xp < bp) {
3754 register U_CHAR *bp1
3755 = skip_quoted_string (xp - 1, bp, ip->lineno,
3756 NULL_PTR, NULL_PTR, NULL_PTR);
3770 || (cplusplus_comments && *xp == '/')) {
3772 /* If we already copied the command through,
3773 already_output != 0 prevents outputting comment now. */
3774 skip_to_end_of_comment (ip, already_output, 0);
3776 while (xp != ip->bufp)
3778 /* Delete or replace the slash. */
3779 else if (traditional)
3788 /* Null-terminate the copy. */
3794 ip->bufp = resume_p;
3796 /* Some directives should be written out for cc1 to process,
3797 just as if they were not defined. And sometimes we're copying
3798 definitions through. */
3800 if (!no_output && already_output == 0
3802 || (kt->type == T_DEFINE
3803 && (dump_macros == dump_names
3804 || dump_macros == dump_definitions)))) {
3807 /* Output directive name. */
3808 check_expand (op, kt->length + 1);
3810 bcopy (kt->name, (char *) op->bufp, kt->length);
3811 op->bufp += kt->length;
3813 if (kt->pass_thru || dump_macros == dump_definitions) {
3814 /* Output arguments. */
3816 check_expand (op, len);
3817 bcopy (buf, (char *) op->bufp, len);
3819 } else if (kt->type == T_DEFINE && dump_macros == dump_names) {
3822 SKIP_WHITE_SPACE (xp);
3824 while (is_idchar[*xp]) xp++;
3826 check_expand (op, len + 1);
3828 bcopy (yp, op->bufp, len);
3831 } /* Don't we need a newline or #line? */
3833 /* Call the appropriate command handler. buf now points to
3834 either the appropriate place in the input buffer, or to
3835 the temp buffer if it was necessary to make one. cp
3836 points to the first char after the contents of the (possibly
3837 copied) command, in either case. */
3838 (*kt->func) (buf, cp, op, kt);
3839 check_expand (op, ip->length - (ip->bufp - ip->buf));
3845 /* It is deliberate that we don't warn about undefined directives.
3846 That is the responsibility of cc1. */
3853 static struct tm *timebuf;
3855 time_t t = time ((time_t *)0);
3856 timebuf = localtime (&t);
3861 static char *monthnames[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
3862 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
3866 * expand things like __FILE__. Place the expansion into the output
3867 * buffer *without* rescanning.
3871 special_symbol (hp, op)
3878 FILE_BUF *ip = NULL;
3881 int paren = 0; /* For special `defined' keyword */
3883 if (pcp_outfile && pcp_inside_if
3884 && hp->type != T_SPEC_DEFINED && hp->type != T_CONST)
3885 error ("Predefined macro `%s' used inside `#if' during precompilation",
3888 for (i = indepth; i >= 0; i--)
3889 if (instack[i].fname != NULL) {
3894 error ("cccp error: not in any file?!");
3895 return; /* the show must go on */
3903 if (hp->type == T_FILE)
3904 string = ip->nominal_fname;
3906 string = instack[0].nominal_fname;
3910 buf = (char *) alloca (3 + 4 * strlen (string));
3911 quote_string (buf, string);
3919 case T_INCLUDE_LEVEL:
3921 for (i = indepth; i >= 0; i--)
3922 if (instack[i].fname != NULL)
3925 buf = (char *) alloca (8); /* Eight bytes ought to be more than enough */
3926 sprintf (buf, "%d", true_indepth - 1);
3930 buf = (char *) alloca (3 + strlen (version_string));
3931 sprintf (buf, "\"%s\"", version_string);
3934 #ifndef NO_BUILTIN_SIZE_TYPE
3940 #ifndef NO_BUILTIN_PTRDIFF_TYPE
3941 case T_PTRDIFF_TYPE:
3950 case T_USER_LABEL_PREFIX_TYPE:
3951 buf = USER_LABEL_PREFIX;
3954 case T_REGISTER_PREFIX_TYPE:
3955 buf = REGISTER_PREFIX;
3959 buf = (char *) alloca (4 * sizeof (int));
3960 sprintf (buf, "%d", hp->value.ival);
3961 if (pcp_inside_if && pcp_outfile)
3962 /* Output a precondition for this macro use */
3963 fprintf (pcp_outfile, "#define %s %d\n", hp->name, hp->value.ival);
3967 buf = (char *) alloca (10);
3968 sprintf (buf, "%d", ip->lineno);
3973 buf = (char *) alloca (20);
3974 timebuf = timestamp ();
3975 if (hp->type == T_DATE)
3976 sprintf (buf, "\"%s %2d %4d\"", monthnames[timebuf->tm_mon],
3977 timebuf->tm_mday, timebuf->tm_year + 1900);
3979 sprintf (buf, "\"%02d:%02d:%02d\"", timebuf->tm_hour, timebuf->tm_min,
3983 case T_SPEC_DEFINED:
3984 buf = " 0 "; /* Assume symbol is not defined */
3985 ip = &instack[indepth];
3986 SKIP_WHITE_SPACE (ip->bufp);
3987 if (*ip->bufp == '(') {
3989 ip->bufp++; /* Skip over the paren */
3990 SKIP_WHITE_SPACE (ip->bufp);
3993 if (!is_idstart[*ip->bufp])
3995 if (hp = lookup (ip->bufp, -1, -1)) {
3996 if (pcp_outfile && pcp_inside_if
3997 && (hp->type == T_CONST
3998 || (hp->type == T_MACRO && hp->value.defn->predefined)))
3999 /* Output a precondition for this macro use. */
4000 fprintf (pcp_outfile, "#define %s\n", hp->name);
4004 if (pcp_outfile && pcp_inside_if) {
4005 /* Output a precondition for this macro use */
4006 U_CHAR *cp = ip->bufp;
4007 fprintf (pcp_outfile, "#undef ");
4008 while (is_idchar[*cp]) /* Ick! */
4009 fputc (*cp++, pcp_outfile);
4010 putc ('\n', pcp_outfile);
4012 while (is_idchar[*ip->bufp])
4014 SKIP_WHITE_SPACE (ip->bufp);
4016 if (*ip->bufp != ')')
4024 error ("`defined' without an identifier");
4028 error ("cccp error: invalid special hash type"); /* time for gdb */
4032 check_expand (op, len);
4033 bcopy (buf, (char *) op->bufp, len);
4040 /* Routines to handle #directives */
4042 /* Handle #include and #import.
4043 This function expects to see "fname" or <fname> on the input. */
4046 do_include (buf, limit, op, keyword)
4047 U_CHAR *buf, *limit;
4049 struct directive *keyword;
4051 int importing = (keyword->type == T_IMPORT);
4052 int skip_dirs = (keyword->type == T_INCLUDE_NEXT);
4053 static int import_warning = 0;
4054 char *fname; /* Dynamically allocated fname buffer */
4057 U_CHAR *fbeg, *fend; /* Beginning and end of fname */
4059 struct file_name_list *search_start = include; /* Chain of dirs to search */
4060 struct file_name_list dsp[1]; /* First in chain, if #include "..." */
4061 struct file_name_list *searchptr = 0;
4064 int f; /* file number */
4066 int retried = 0; /* Have already tried macro
4067 expanding the include line*/
4068 int angle_brackets = 0; /* 0 for "...", 1 for <...> */
4073 f= -1; /* JF we iz paranoid! */
4075 if (importing && warn_import && !inhibit_warnings
4076 && !instack[indepth].system_header_p && !import_warning) {
4078 warning ("using `#import' is not recommended");
4079 fprintf (stderr, "The fact that a certain header file need not be processed more than once\n");
4080 fprintf (stderr, "should be indicated in the header file, not where it is used.\n");
4081 fprintf (stderr, "The best way to do this is with a conditional of this form:\n\n");
4082 fprintf (stderr, " #ifndef _FOO_H_INCLUDED\n");
4083 fprintf (stderr, " #define _FOO_H_INCLUDED\n");
4084 fprintf (stderr, " ... <real contents of file> ...\n");
4085 fprintf (stderr, " #endif /* Not _FOO_H_INCLUDED */\n\n");
4086 fprintf (stderr, "Then users can use `#include' any number of times.\n");
4087 fprintf (stderr, "GNU C automatically avoids processing the file more than once\n");
4088 fprintf (stderr, "when it is equipped with such a conditional.\n");
4094 SKIP_WHITE_SPACE (fbeg);
4095 /* Discard trailing whitespace so we can easily see
4096 if we have parsed all the significant chars we were given. */
4097 while (limit != fbeg && is_hor_space[limit[-1]]) limit--;
4103 /* Copy the operand text, concatenating the strings. */
4106 fbeg = (U_CHAR *) alloca (limit - fbeg + 1);
4108 while (fin != limit) {
4109 while (fin != limit && *fin != '\"')
4114 /* If not at the end, there had better be another string. */
4115 /* Skip just horiz space, and don't go past limit. */
4116 while (fin != limit && is_hor_space[*fin]) fin++;
4117 if (fin != limit && *fin == '\"')
4125 /* We have "filename". Figure out directory this source
4126 file is coming from and put it on the front of the list. */
4128 /* If -I- was specified, don't search current dir, only spec'd ones. */
4129 if (ignore_srcdir) break;
4131 for (fp = &instack[indepth]; fp >= instack; fp--)
4136 if ((nam = fp->nominal_fname) != NULL) {
4137 /* Found a named file. Figure out dir of the file,
4138 and put it in front of the search list. */
4139 dsp[0].next = search_start;
4142 ep = rindex (nam, '/');
4143 #ifdef DIR_SEPARATOR
4144 if (ep == NULL) ep = rindex (nam, DIR_SEPARATOR);
4146 char *tmp = rindex (nam, DIR_SEPARATOR);
4147 if (tmp != NULL && tmp > ep) ep = tmp;
4151 ep = rindex (nam, ']');
4152 if (ep == NULL) ep = rindex (nam, '>');
4153 if (ep == NULL) ep = rindex (nam, ':');
4154 if (ep != NULL) ep++;
4158 dsp[0].fname = (char *) alloca (n + 1);
4159 strncpy (dsp[0].fname, nam, n);
4160 dsp[0].fname[n] = '\0';
4161 if (n + INCLUDE_LEN_FUDGE > max_include_len)
4162 max_include_len = n + INCLUDE_LEN_FUDGE;
4164 dsp[0].fname = 0; /* Current directory */
4166 dsp[0].got_name_map = 0;
4175 while (fend != limit && *fend != '>') fend++;
4176 if (*fend == '>' && fend + 1 == limit) {
4178 /* If -I-, start with the first -I dir after the -I-. */
4179 if (first_bracket_include)
4180 search_start = first_bracket_include;
4188 * Support '#include xyz' like VAX-C to allow for easy use of all the
4189 * decwindow include files. It defaults to '#include <xyz.h>' (so the
4190 * code from case '<' is repeated here) and generates a warning.
4191 * (Note: macro expansion of `xyz' takes precedence.)
4193 if (retried && isalpha(*(--fbeg))) {
4195 while (fend != limit && (!isspace(*fend))) fend++;
4196 warning ("VAX-C-style include specification found, use '#include <filename.h>' !");
4197 if (fend == limit) {
4199 /* If -I-, start with the first -I dir after the -I-. */
4200 if (first_bracket_include)
4201 search_start = first_bracket_include;
4209 error ("`#%s' expects \"FILENAME\" or <FILENAME>", keyword->name);
4212 /* Expand buffer and then remove any newline markers.
4213 We can't just tell expand_to_temp_buffer to omit the markers,
4214 since it would put extra spaces in include file names. */
4217 trybuf = expand_to_temp_buffer (buf, limit, 1, 0);
4219 buf = (U_CHAR *) alloca (trybuf.bufp - trybuf.buf + 1);
4221 while (src != trybuf.bufp) {
4222 switch ((*limit++ = *src++)) {
4231 U_CHAR *src1 = skip_quoted_string (src - 1, trybuf.bufp, 0,
4232 NULL_PTR, NULL_PTR, NULL_PTR);
4246 /* For #include_next, skip in the search path
4247 past the dir in which the containing file was found. */
4250 for (fp = &instack[indepth]; fp >= instack; fp--)
4251 if (fp->fname != NULL) {
4252 /* fp->dir is null if the containing file was specified
4253 with an absolute file name. In that case, don't skip anything. */
4255 search_start = fp->dir->next;
4264 error ("empty file name in `#%s'", keyword->name);
4268 /* Allocate this permanently, because it gets stored in the definitions
4270 fname = (char *) xmalloc (max_include_len + flen + 4);
4271 /* + 2 above for slash and terminating null. */
4272 /* + 2 added for '.h' on VMS (to support '#include filename') */
4274 /* If specified file name is absolute, just open it. */
4277 #ifdef DIR_SEPARATOR
4278 || *fbeg == DIR_SEPARATOR
4281 strncpy (fname, fbeg, flen);
4283 if (redundant_include_p (fname))
4286 f = lookup_import (fname, NULL_PTR);
4288 f = open_include_file (fname, NULL_PTR);
4290 return 0; /* Already included this file */
4292 /* Search directory path, trying to open the file.
4293 Copy each filename tried into FNAME. */
4295 for (searchptr = search_start; searchptr; searchptr = searchptr->next) {
4296 if (searchptr->fname) {
4297 /* The empty string in a search path is ignored.
4298 This makes it possible to turn off entirely
4299 a standard piece of the list. */
4300 if (searchptr->fname[0] == 0)
4302 strcpy (fname, searchptr->fname);
4303 strcat (fname, "/");
4304 fname[strlen (fname) + flen] = 0;
4308 strncat (fname, fbeg, flen);
4310 /* Change this 1/2 Unix 1/2 VMS file specification into a
4311 full VMS file specification */
4312 if (searchptr->fname && (searchptr->fname[0] != 0)) {
4313 /* Fix up the filename */
4314 hack_vms_include_specification (fname);
4316 /* This is a normal VMS filespec, so use it unchanged. */
4317 strncpy (fname, fbeg, flen);
4319 /* if it's '#include filename', add the missing .h */
4320 if (index(fname,'.')==NULL) {
4321 strcat (fname, ".h");
4326 f = lookup_import (fname, searchptr);
4328 f = open_include_file (fname, searchptr);
4330 return 0; /* Already included this file */
4332 else if (f == -1 && errno == EACCES)
4333 warning ("Header file %s exists, but is not readable", fname);
4335 if (redundant_include_p (fname)) {
4345 /* A file that was not found. */
4347 strncpy (fname, fbeg, flen);
4349 /* If generating dependencies and -MG was specified, we assume missing
4350 files are leaf files, living in the same directory as the source file
4351 or other similar place; these missing files may be generated from
4352 other files and may not exist yet (eg: y.tab.h). */
4353 if (print_deps_missing_files
4354 && print_deps > (angle_brackets || (system_include_depth > 0)))
4356 /* If it was requested as a system header file,
4357 then assume it belongs in the first place to look for such. */
4360 for (searchptr = search_start; searchptr; searchptr = searchptr->next)
4362 if (searchptr->fname)
4366 if (searchptr->fname[0] == 0)
4368 p = xmalloc (strlen (searchptr->fname)
4369 + strlen (fname) + 2);
4370 strcpy (p, searchptr->fname);
4373 deps_output (p, ' ');
4380 /* Otherwise, omit the directory, as if the file existed
4381 in the directory with the source. */
4382 deps_output (fname, ' ');
4385 /* If -M was specified, and this header file won't be added to the
4386 dependency list, then don't count this as an error, because we can
4387 still produce correct output. Otherwise, we can't produce correct
4388 output, because there may be dependencies we need inside the missing
4389 file, and we don't know what directory this missing file exists in. */
4391 && (print_deps <= (angle_brackets || (system_include_depth > 0))))
4392 warning ("No include path in which to find %s", fname);
4393 else if (search_start)
4394 error_from_errno (fname);
4396 error ("No include path in which to find %s", fname);
4400 /* Check to see if this include file is a once-only include file.
4403 struct file_name_list* ptr;
4405 for (ptr = dont_repeat_files; ptr; ptr = ptr->next) {
4406 if (!strcmp (ptr->fname, fname)) {
4408 return 0; /* This file was once'd. */
4412 for (ptr = all_include_files; ptr; ptr = ptr->next) {
4413 if (!strcmp (ptr->fname, fname))
4414 break; /* This file was included before. */
4418 /* This is the first time for this file. */
4419 /* Add it to list of files included. */
4421 ptr = (struct file_name_list *) xmalloc (sizeof (struct file_name_list));
4422 ptr->control_macro = 0;
4423 ptr->c_system_include_path = 0;
4424 ptr->next = all_include_files;
4425 all_include_files = ptr;
4426 ptr->fname = savestring (fname);
4427 ptr->got_name_map = 0;
4429 /* For -M, add this file to the dependencies. */
4430 if (print_deps > (angle_brackets || (system_include_depth > 0)))
4431 deps_output (fname, ' ');
4434 /* Handle -H option. */
4435 if (print_include_names) {
4436 output_dots (stderr, indepth);
4437 fprintf (stderr, "%s\n", fname);
4441 system_include_depth++;
4443 /* Actually process the file. */
4444 add_import (f, fname); /* Record file on "seen" list for #import. */
4446 pcftry = (char *) alloca (strlen (fname) + 30);
4454 sprintf (pcftry, "%s%d", fname, pcfnum++);
4456 pcf = open (pcftry, O_RDONLY, 0666);
4462 if (bcmp ((char *) &stat_f.st_ino, (char *) &s.st_ino,
4464 || stat_f.st_dev != s.st_dev)
4466 pcfbuf = check_precompiled (pcf, fname, &pcfbuflimit);
4467 /* Don't need it any more. */
4472 /* Don't need it at all. */
4477 } while (pcf != -1 && !pcfbuf);
4479 /* Actually process the file */
4481 pcfname = xmalloc (strlen (pcftry) + 1);
4482 strcpy (pcfname, pcftry);
4483 pcfinclude (pcfbuf, pcfbuflimit, fname, op);
4486 finclude (f, fname, op, is_system_include (fname), searchptr);
4489 system_include_depth--;
4494 /* Return nonzero if there is no need to include file NAME
4495 because it has already been included and it contains a conditional
4496 to make a repeated include do nothing. */
4499 redundant_include_p (name)
4502 struct file_name_list *l = all_include_files;
4503 for (; l; l = l->next)
4504 if (! strcmp (name, l->fname)
4506 && lookup (l->control_macro, -1, -1))
4511 /* Return nonzero if the given FILENAME is an absolute pathname which
4512 designates a file within one of the known "system" include file
4513 directories. We assume here that if the given FILENAME looks like
4514 it is the name of a file which resides either directly in a "system"
4515 include file directory, or within any subdirectory thereof, then the
4516 given file must be a "system" include file. This function tells us
4517 if we should suppress pedantic errors/warnings for the given FILENAME.
4519 The value is 2 if the file is a C-language system header file
4520 for which C++ should (on most systems) assume `extern "C"'. */
4523 is_system_include (filename)
4524 register char *filename;
4526 struct file_name_list *searchptr;
4528 for (searchptr = first_system_include; searchptr;
4529 searchptr = searchptr->next)
4530 if (searchptr->fname) {
4531 register char *sys_dir = searchptr->fname;
4532 register unsigned length = strlen (sys_dir);
4534 if (! strncmp (sys_dir, filename, length)
4535 && (filename[length] == '/'
4536 #ifdef DIR_SEPARATOR
4537 || filename[length] == DIR_SEPARATOR
4540 if (searchptr->c_system_include_path)
4549 /* The file_name_map structure holds a mapping of file names for a
4550 particular directory. This mapping is read from the file named
4551 FILE_NAME_MAP_FILE in that directory. Such a file can be used to
4552 map filenames on a file system with severe filename restrictions,
4553 such as DOS. The format of the file name map file is just a series
4554 of lines with two tokens on each line. The first token is the name
4555 to map, and the second token is the actual name to use. */
4557 struct file_name_map
4559 struct file_name_map *map_next;
4564 #define FILE_NAME_MAP_FILE "header.gcc"
4566 /* Read a space delimited string of unlimited length from a stdio
4570 read_filename_string (ch, f)
4578 set = alloc = xmalloc (len + 1);
4582 while ((ch = getc (f)) != EOF && ! is_space[ch])
4584 if (set - alloc == len)
4587 alloc = xrealloc (alloc, len + 1);
4588 set = alloc + len / 2;
4598 /* Read the file name map file for DIRNAME. */
4600 static struct file_name_map *
4601 read_name_map (dirname)
4604 /* This structure holds a linked list of file name maps, one per
4606 struct file_name_map_list
4608 struct file_name_map_list *map_list_next;
4609 char *map_list_name;
4610 struct file_name_map *map_list_map;
4612 static struct file_name_map_list *map_list;
4613 register struct file_name_map_list *map_list_ptr;
4617 for (map_list_ptr = map_list; map_list_ptr;
4618 map_list_ptr = map_list_ptr->map_list_next)
4619 if (! strcmp (map_list_ptr->map_list_name, dirname))
4620 return map_list_ptr->map_list_map;
4622 map_list_ptr = ((struct file_name_map_list *)
4623 xmalloc (sizeof (struct file_name_map_list)));
4624 map_list_ptr->map_list_name = savestring (dirname);
4625 map_list_ptr->map_list_map = NULL;
4627 name = (char *) alloca (strlen (dirname) + strlen (FILE_NAME_MAP_FILE) + 2);
4628 strcpy (name, dirname);
4631 strcat (name, FILE_NAME_MAP_FILE);
4632 f = fopen (name, "r");
4634 map_list_ptr->map_list_map = NULL;
4638 int dirlen = strlen (dirname);
4640 while ((ch = getc (f)) != EOF)
4643 struct file_name_map *ptr;
4647 from = read_filename_string (ch, f);
4648 while ((ch = getc (f)) != EOF && is_hor_space[ch])
4650 to = read_filename_string (ch, f);
4652 ptr = ((struct file_name_map *)
4653 xmalloc (sizeof (struct file_name_map)));
4654 ptr->map_from = from;
4656 /* Make the real filename absolute. */
4661 ptr->map_to = xmalloc (dirlen + strlen (to) + 2);
4662 strcpy (ptr->map_to, dirname);
4663 ptr->map_to[dirlen] = '/';
4664 strcpy (ptr->map_to + dirlen + 1, to);
4668 ptr->map_next = map_list_ptr->map_list_map;
4669 map_list_ptr->map_list_map = ptr;
4671 while ((ch = getc (f)) != '\n')
4678 map_list_ptr->map_list_next = map_list;
4679 map_list = map_list_ptr;
4681 return map_list_ptr->map_list_map;
4684 /* Try to open include file FILENAME. SEARCHPTR is the directory
4685 being tried from the include file search path. This function maps
4686 filenames on file systems based on information read by
4690 open_include_file (filename, searchptr)
4692 struct file_name_list *searchptr;
4694 register struct file_name_map *map;
4695 register char *from;
4698 if (searchptr && ! searchptr->got_name_map)
4700 searchptr->name_map = read_name_map (searchptr->fname
4701 ? searchptr->fname : ".");
4702 searchptr->got_name_map = 1;
4705 /* First check the mapping for the directory we are using. */
4706 if (searchptr && searchptr->name_map)
4709 if (searchptr->fname)
4710 from += strlen (searchptr->fname) + 1;
4711 for (map = searchptr->name_map; map; map = map->map_next)
4713 if (! strcmp (map->map_from, from))
4715 /* Found a match. */
4716 return open (map->map_to, O_RDONLY, 0666);
4721 /* Try to find a mapping file for the particular directory we are
4722 looking in. Thus #include <sys/types.h> will look up sys/types.h
4723 in /usr/include/header.gcc and look up types.h in
4724 /usr/include/sys/header.gcc. */
4725 p = rindex (filename, '/');
4726 #ifdef DIR_SEPARATOR
4727 if (! p) p = rindex (filename, DIR_SEPARATOR);
4729 char *tmp = rindex (filename, DIR_SEPARATOR);
4730 if (tmp != NULL && tmp > p) p = tmp;
4737 && strlen (searchptr->fname) == p - filename
4738 && ! strncmp (searchptr->fname, filename, p - filename))
4740 /* FILENAME is in SEARCHPTR, which we've already checked. */
4741 return open (filename, O_RDONLY, 0666);
4751 dir = (char *) alloca (p - filename + 1);
4752 bcopy (filename, dir, p - filename);
4753 dir[p - filename] = '\0';
4756 for (map = read_name_map (dir); map; map = map->map_next)
4757 if (! strcmp (map->map_from, from))
4758 return open (map->map_to, O_RDONLY, 0666);
4760 return open (filename, O_RDONLY, 0666);
4763 /* Process the contents of include file FNAME, already open on descriptor F,
4765 SYSTEM_HEADER_P is 1 if this file resides in any one of the known
4766 "system" include directories (as decided by the `is_system_include'
4768 DIRPTR is the link in the dir path through which this file was found,
4769 or 0 if the file name was absolute. */
4772 finclude (f, fname, op, system_header_p, dirptr)
4776 int system_header_p;
4777 struct file_name_list *dirptr;
4782 FILE_BUF *fp; /* For input stack frame */
4783 int missing_newline = 0;
4785 CHECK_DEPTH (return;);
4787 if (file_size_and_mode (f, &st_mode, &st_size) < 0)
4789 perror_with_name (fname);
4794 fp = &instack[indepth + 1];
4795 bzero ((char *) fp, sizeof (FILE_BUF));
4796 fp->nominal_fname = fp->fname = fname;
4799 fp->if_stack = if_stack;
4800 fp->system_header_p = system_header_p;
4803 if (S_ISREG (st_mode)) {
4804 fp->buf = (U_CHAR *) xmalloc (st_size + 2);
4807 /* Read the file contents, knowing that st_size is an upper bound
4808 on the number of bytes we can read. */
4809 fp->length = safe_read (f, fp->buf, st_size);
4810 if (fp->length < 0) goto nope;
4812 else if (S_ISDIR (st_mode)) {
4813 error ("directory `%s' specified in #include", fname);
4817 /* Cannot count its file size before reading.
4818 First read the entire file into heap and
4819 copy them into buffer on stack. */
4824 fp->buf = (U_CHAR *) xmalloc (bsize + 2);
4827 i = safe_read (f, fp->buf + st_size, bsize - st_size);
4829 goto nope; /* error! */
4831 if (st_size != bsize)
4832 break; /* End of file */
4834 fp->buf = (U_CHAR *) xrealloc (fp->buf, bsize + 2);
4837 fp->length = st_size;
4840 if ((fp->length > 0 && fp->buf[fp->length - 1] != '\n')
4841 /* Backslash-newline at end is not good enough. */
4842 || (fp->length > 1 && fp->buf[fp->length - 2] == '\\')) {
4843 fp->buf[fp->length++] = '\n';
4844 missing_newline = 1;
4846 fp->buf[fp->length] = '\0';
4848 /* Close descriptor now, so nesting does not use lots of descriptors. */
4851 /* Must do this before calling trigraph_pcp, so that the correct file name
4852 will be printed in warning messages. */
4855 input_file_stack_tick++;
4860 output_line_command (fp, op, 0, enter_file);
4863 if (missing_newline)
4866 if (pedantic && missing_newline)
4867 pedwarn ("file does not end in newline");
4870 input_file_stack_tick++;
4871 output_line_command (&instack[indepth], op, 0, leave_file);
4877 perror_with_name (fname);
4882 /* Record that inclusion of the file named FILE
4883 should be controlled by the macro named MACRO_NAME.
4884 This means that trying to include the file again
4885 will do something if that macro is defined. */
4888 record_control_macro (file, macro_name)
4892 struct file_name_list *new;
4894 for (new = all_include_files; new; new = new->next) {
4895 if (!strcmp (new->fname, file)) {
4896 new->control_macro = macro_name;
4901 /* If the file is not in all_include_files, something's wrong. */
4905 /* Maintain and search list of included files, for #import. */
4907 #define IMPORT_HASH_SIZE 31
4909 struct import_file {
4913 struct import_file *next;
4916 /* Hash table of files already included with #include or #import. */
4918 static struct import_file *import_hash_table[IMPORT_HASH_SIZE];
4920 /* Hash a file name for import_hash_table. */
4928 while (*f) val += *f++;
4929 return (val%IMPORT_HASH_SIZE);
4932 /* Search for file FILENAME in import_hash_table.
4933 Return -2 if found, either a matching name or a matching inode.
4934 Otherwise, open the file and return a file descriptor if successful
4935 or -1 if unsuccessful. */
4938 lookup_import (filename, searchptr)
4940 struct file_name_list *searchptr;
4942 struct import_file *i;
4948 hashval = import_hash (filename);
4950 /* Attempt to find file in list of already included files */
4951 i = import_hash_table[hashval];
4954 if (!strcmp (filename, i->name))
4955 return -2; /* return found */
4958 /* Open it and try a match on inode/dev */
4959 fd = open_include_file (filename, searchptr);
4963 for (h = 0; h < IMPORT_HASH_SIZE; h++) {
4964 i = import_hash_table[h];
4966 /* Compare the inode and the device.
4967 Supposedly on some systems the inode is not a scalar. */
4968 if (!bcmp ((char *) &i->inode, (char *) &sb.st_ino, sizeof (sb.st_ino))
4969 && i->dev == sb.st_dev) {
4971 return -2; /* return found */
4976 return fd; /* Not found, return open file */
4979 /* Add the file FNAME, open on descriptor FD, to import_hash_table. */
4982 add_import (fd, fname)
4986 struct import_file *i;
4990 hashval = import_hash (fname);
4992 i = (struct import_file *)xmalloc (sizeof (struct import_file));
4993 i->name = (char *)xmalloc (strlen (fname)+1);
4994 strcpy (i->name, fname);
4995 bcopy ((char *) &sb.st_ino, (char *) &i->inode, sizeof (sb.st_ino));
4997 i->next = import_hash_table[hashval];
4998 import_hash_table[hashval] = i;
5001 /* Load the specified precompiled header into core, and verify its
5002 preconditions. PCF indicates the file descriptor to read, which must
5003 be a regular file. FNAME indicates the file name of the original
5004 header. *LIMIT will be set to an address one past the end of the file.
5005 If the preconditions of the file are not satisfied, the buffer is
5006 freed and we return 0. If the preconditions are satisfied, return
5007 the address of the buffer following the preconditions. The buffer, in
5008 this case, should never be freed because various pieces of it will
5009 be referred to until all precompiled strings are output at the end of
5013 check_precompiled (pcf, fname, limit)
5027 if (file_size_and_mode (pcf, &st_mode, &st_size) < 0)
5030 if (S_ISREG (st_mode))
5032 buf = xmalloc (st_size + 2);
5033 length = safe_read (pcf, buf, st_size);
5040 if (length > 0 && buf[length-1] != '\n')
5041 buf[length++] = '\n';
5044 *limit = buf + length;
5046 /* File is in core. Check the preconditions. */
5047 if (!check_preconditions (buf))
5049 for (cp = buf; *cp; cp++)
5052 fprintf (stderr, "Using preinclude %s\n", fname);
5058 fprintf (stderr, "Cannot use preinclude %s\n", fname);
5064 /* PREC (null terminated) points to the preconditions of a
5065 precompiled header. These are a series of #define and #undef
5066 lines which must match the current contents of the hash
5069 check_preconditions (prec)
5076 lineend = (char *) index (prec, '\n');
5078 if (*prec++ != '#') {
5079 error ("Bad format encountered while reading precompiled file");
5082 if (!strncmp (prec, "define", 6)) {
5086 mdef = create_definition (prec, lineend, NULL_PTR);
5091 if ((hp = lookup (mdef.symnam, mdef.symlen, -1)) == NULL
5092 || (hp->type != T_MACRO && hp->type != T_CONST)
5093 || (hp->type == T_MACRO
5094 && !compare_defs (mdef.defn, hp->value.defn)
5095 && (mdef.defn->length != 2
5096 || mdef.defn->expansion[0] != '\n'
5097 || mdef.defn->expansion[1] != ' ')))
5099 } else if (!strncmp (prec, "undef", 5)) {
5104 while (is_hor_space[(U_CHAR) *prec])
5107 while (is_idchar[(U_CHAR) *prec])
5111 if (lookup (name, len, -1))
5114 error ("Bad format encountered while reading precompiled file");
5119 /* They all passed successfully */
5123 /* Process the main body of a precompiled file. BUF points to the
5124 string section of the file, following the preconditions. LIMIT is one
5125 character past the end. NAME is the name of the file being read
5126 in. OP is the main output buffer */
5128 pcfinclude (buf, limit, name, op)
5129 U_CHAR *buf, *limit, *name;
5136 /* First in the file comes 4 bytes indicating the number of strings, */
5137 /* in network byte order. (MSB first). */
5139 nstrings = (nstrings << 8) | *cp++;
5140 nstrings = (nstrings << 8) | *cp++;
5141 nstrings = (nstrings << 8) | *cp++;
5143 /* Looping over each string... */
5144 while (nstrings--) {
5145 U_CHAR *string_start;
5146 U_CHAR *endofthiskey;
5150 /* Each string starts with a STRINGDEF structure (str), followed */
5151 /* by the text of the string (string_start) */
5153 /* First skip to a longword boundary */
5154 /* ??? Why a 4-byte boundary? On all machines? */
5155 /* NOTE: This works correctly even if HOST_WIDE_INT
5156 is narrower than a pointer.
5157 Do not try risky measures here to get another type to use!
5158 Do not include stddef.h--it will fail! */
5159 if ((HOST_WIDE_INT) cp & 3)
5160 cp += 4 - ((HOST_WIDE_INT) cp & 3);
5162 /* Now get the string. */
5163 str = (STRINGDEF *) cp;
5164 string_start = cp += sizeof (STRINGDEF);
5166 for (; *cp; cp++) /* skip the string */
5169 /* We need to macro expand the string here to ensure that the
5170 proper definition environment is in place. If it were only
5171 expanded when we find out it is needed, macros necessary for
5172 its proper expansion might have had their definitions changed. */
5173 tmpbuf = expand_to_temp_buffer (string_start, cp++, 0, 0);
5174 /* Lineno is already set in the precompiled file */
5175 str->contents = tmpbuf.buf;
5176 str->len = tmpbuf.length;
5178 str->filename = name;
5179 str->output_mark = outbuf.bufp - outbuf.buf;
5182 *stringlist_tailp = str;
5183 stringlist_tailp = &str->chain;
5185 /* Next comes a fourbyte number indicating the number of keys */
5186 /* for this string. */
5188 nkeys = (nkeys << 8) | *cp++;
5189 nkeys = (nkeys << 8) | *cp++;
5190 nkeys = (nkeys << 8) | *cp++;
5192 /* If this number is -1, then the string is mandatory. */
5196 /* Otherwise, for each key, */
5197 for (; nkeys--; free (tmpbuf.buf), cp = endofthiskey + 1) {
5198 KEYDEF *kp = (KEYDEF *) cp;
5201 /* It starts with a KEYDEF structure */
5202 cp += sizeof (KEYDEF);
5204 /* Find the end of the key. At the end of this for loop we
5205 advance CP to the start of the next key using this variable. */
5206 endofthiskey = cp + strlen (cp);
5209 /* Expand the key, and enter it into the hash table. */
5210 tmpbuf = expand_to_temp_buffer (cp, endofthiskey, 0, 0);
5211 tmpbuf.bufp = tmpbuf.buf;
5213 while (is_hor_space[*tmpbuf.bufp])
5215 if (!is_idstart[*tmpbuf.bufp]
5216 || tmpbuf.bufp == tmpbuf.buf + tmpbuf.length) {
5221 hp = lookup (tmpbuf.bufp, -1, -1);
5224 install (tmpbuf.bufp, -1, T_PCSTRING, 0, (char *) kp, -1);
5226 else if (hp->type == T_PCSTRING) {
5227 kp->chain = hp->value.keydef;
5228 hp->value.keydef = kp;
5234 /* This output_line_command serves to switch us back to the current
5235 input file in case some of these strings get output (which will
5236 result in line commands for the header file being output). */
5237 output_line_command (&instack[indepth], op, 0, enter_file);
5240 /* Called from rescan when it hits a key for strings. Mark them all */
5241 /* used and clean up. */
5248 for (kp = hp->value.keydef; kp; kp = kp->chain)
5249 kp->str->writeflag = 1;
5253 /* Write the output, interspersing precompiled strings in their */
5254 /* appropriate places. */
5258 STRINGDEF *next_string;
5259 U_CHAR *cur_buf_loc;
5260 int line_command_len = 80;
5261 char *line_command = xmalloc (line_command_len);
5264 /* In each run through the loop, either cur_buf_loc == */
5265 /* next_string_loc, in which case we print a series of strings, or */
5266 /* it is less than next_string_loc, in which case we write some of */
5268 cur_buf_loc = outbuf.buf;
5269 next_string = stringlist;
5271 while (cur_buf_loc < outbuf.bufp || next_string) {
5273 && cur_buf_loc - outbuf.buf == next_string->output_mark) {
5274 if (next_string->writeflag) {
5275 len = 4 * strlen (next_string->filename) + 32;
5276 while (len > line_command_len)
5277 line_command = xrealloc (line_command,
5278 line_command_len *= 2);
5279 sprintf (line_command, "\n# %d ", next_string->lineno);
5280 strcpy (quote_string (line_command + strlen (line_command),
5281 next_string->filename),
5283 safe_write (fileno (stdout), line_command, strlen (line_command));
5284 safe_write (fileno (stdout), next_string->contents, next_string->len);
5286 next_string = next_string->chain;
5290 ? (next_string->output_mark
5291 - (cur_buf_loc - outbuf.buf))
5292 : outbuf.bufp - cur_buf_loc);
5294 safe_write (fileno (stdout), cur_buf_loc, len);
5298 free (line_command);
5301 /* Pass a directive through to the output file.
5302 BUF points to the contents of the directive, as a contiguous string.
5303 LIMIT points to the first character past the end of the directive.
5304 KEYWORD is the keyword-table entry for the directive. */
5307 pass_thru_directive (buf, limit, op, keyword)
5308 U_CHAR *buf, *limit;
5310 struct directive *keyword;
5312 register unsigned keyword_length = keyword->length;
5314 check_expand (op, 1 + keyword_length + (limit - buf));
5316 bcopy (keyword->name, (char *) op->bufp, keyword_length);
5317 op->bufp += keyword_length;
5318 if (limit != buf && buf[0] != ' ')
5320 bcopy ((char *) buf, (char *) op->bufp, limit - buf);
5321 op->bufp += (limit - buf);
5324 /* Count the line we have just made in the output,
5325 to get in sync properly. */
5330 /* The arglist structure is built by do_define to tell
5331 collect_definition where the argument names begin. That
5332 is, for a define like "#define f(x,y,z) foo+x-bar*y", the arglist
5333 would contain pointers to the strings x, y, and z.
5334 Collect_definition would then build a DEFINITION node,
5335 with reflist nodes pointing to the places x, y, and z had
5336 appeared. So the arglist is just convenience data passed
5337 between these two routines. It is not kept around after
5338 the current #define has been processed and entered into the
5342 struct arglist *next;
5349 /* Create a DEFINITION node from a #define directive. Arguments are
5350 as for do_define. */
5352 create_definition (buf, limit, op)
5353 U_CHAR *buf, *limit;
5356 U_CHAR *bp; /* temp ptr into input buffer */
5357 U_CHAR *symname; /* remember where symbol name starts */
5358 int sym_length; /* and how long it is */
5359 int line = instack[indepth].lineno;
5360 char *file = instack[indepth].nominal_fname;
5364 int arglengths = 0; /* Accumulate lengths of arg names
5365 plus number of args. */
5370 while (is_hor_space[*bp])
5373 symname = bp; /* remember where it starts */
5374 sym_length = check_macro_name (bp, "macro");
5377 /* Lossage will occur if identifiers or control keywords are broken
5378 across lines using backslash. This is not the right place to take
5382 struct arglist *arg_ptrs = NULL;
5385 bp++; /* skip '(' */
5386 SKIP_WHITE_SPACE (bp);
5388 /* Loop over macro argument names. */
5389 while (*bp != ')') {
5390 struct arglist *temp;
5392 temp = (struct arglist *) alloca (sizeof (struct arglist));
5394 temp->next = arg_ptrs;
5395 temp->argno = argno++;
5396 temp->rest_args = 0;
5400 pedwarn ("another parameter follows `%s'",
5403 if (!is_idstart[*bp])
5404 pedwarn ("invalid character in macro parameter name");
5406 /* Find the end of the arg name. */
5407 while (is_idchar[*bp]) {
5409 /* do we have a "special" rest-args extension here? */
5410 if (limit - bp > REST_EXTENSION_LENGTH &&
5411 strncmp (rest_extension, bp, REST_EXTENSION_LENGTH) == 0) {
5413 temp->rest_args = 1;
5417 temp->length = bp - temp->name;
5419 bp += REST_EXTENSION_LENGTH;
5420 arglengths += temp->length + 2;
5421 SKIP_WHITE_SPACE (bp);
5422 if (temp->length == 0 || (*bp != ',' && *bp != ')')) {
5423 error ("badly punctuated parameter list in `#define'");
5428 SKIP_WHITE_SPACE (bp);
5429 /* A comma at this point can only be followed by an identifier. */
5430 if (!is_idstart[*bp]) {
5431 error ("badly punctuated parameter list in `#define'");
5436 error ("unterminated parameter list in `#define'");
5440 struct arglist *otemp;
5442 for (otemp = temp->next; otemp != NULL; otemp = otemp->next)
5443 if (temp->length == otemp->length &&
5444 strncmp (temp->name, otemp->name, temp->length) == 0) {
5447 name = (U_CHAR *) alloca (temp->length + 1);
5448 (void) strncpy (name, temp->name, temp->length);
5449 name[temp->length] = '\0';
5450 error ("duplicate argument name `%s' in `#define'", name);
5456 ++bp; /* skip paren */
5457 SKIP_WHITE_SPACE (bp);
5458 /* now everything from bp before limit is the definition. */
5459 defn = collect_expansion (bp, limit, argno, arg_ptrs);
5460 defn->rest_args = rest_args;
5462 /* Now set defn->args.argnames to the result of concatenating
5463 the argument names in reverse order
5464 with comma-space between them. */
5465 defn->args.argnames = (U_CHAR *) xmalloc (arglengths + 1);
5467 struct arglist *temp;
5469 for (temp = arg_ptrs; temp; temp = temp->next) {
5470 bcopy (temp->name, &defn->args.argnames[i], temp->length);
5472 if (temp->next != 0) {
5473 defn->args.argnames[i++] = ',';
5474 defn->args.argnames[i++] = ' ';
5477 defn->args.argnames[i] = 0;
5480 /* Simple expansion or empty definition. */
5484 if (is_hor_space[*bp]) {
5486 SKIP_WHITE_SPACE (bp);
5489 case '!': case '"': case '#': case '%': case '&': case '\'':
5490 case ')': case '*': case '+': case ',': case '-': case '.':
5491 case '/': case ':': case ';': case '<': case '=': case '>':
5492 case '?': case '[': case '\\': case ']': case '^': case '{':
5493 case '|': case '}': case '~':
5494 warning ("missing white space after `#define %.*s'",
5495 sym_length, symname);
5499 pedwarn ("missing white space after `#define %.*s'",
5500 sym_length, symname);
5505 /* Now everything from bp before limit is the definition. */
5506 defn = collect_expansion (bp, limit, -1, NULL_PTR);
5507 defn->args.argnames = (U_CHAR *) "";
5513 /* OP is null if this is a predefinition */
5514 defn->predefined = !op;
5516 mdef.symnam = symname;
5517 mdef.symlen = sym_length;
5526 /* Process a #define command.
5527 BUF points to the contents of the #define command, as a contiguous string.
5528 LIMIT points to the first character past the end of the definition.
5529 KEYWORD is the keyword-table entry for #define. */
5532 do_define (buf, limit, op, keyword)
5533 U_CHAR *buf, *limit;
5535 struct directive *keyword;
5540 /* If this is a precompiler run (with -pcp) pass thru #define commands. */
5541 if (pcp_outfile && op)
5542 pass_thru_directive (buf, limit, op, keyword);
5544 mdef = create_definition (buf, limit, op);
5548 hashcode = hashf (mdef.symnam, mdef.symlen, HASHSIZE);
5552 if ((hp = lookup (mdef.symnam, mdef.symlen, hashcode)) != NULL) {
5554 /* Redefining a precompiled key is ok. */
5555 if (hp->type == T_PCSTRING)
5557 /* Redefining a macro is ok if the definitions are the same. */
5558 else if (hp->type == T_MACRO)
5559 ok = ! compare_defs (mdef.defn, hp->value.defn);
5560 /* Redefining a constant is ok with -D. */
5561 else if (hp->type == T_CONST)
5562 ok = ! done_initializing;
5563 /* Print the warning if it's not ok. */
5565 U_CHAR *msg; /* what pain... */
5567 /* If we are passing through #define and #undef directives, do
5568 that for this re-definition now. */
5569 if (debug_output && op)
5570 pass_thru_directive (buf, limit, op, keyword);
5572 msg = (U_CHAR *) alloca (mdef.symlen + 22);
5574 bcopy ((char *) mdef.symnam, (char *) (msg + 1), mdef.symlen);
5575 strcpy ((char *) (msg + mdef.symlen + 1), "' redefined");
5577 if (hp->type == T_MACRO)
5578 pedwarn_with_file_and_line (hp->value.defn->file, hp->value.defn->line,
5579 "this is the location of the previous definition");
5581 /* Replace the old definition. */
5583 hp->value.defn = mdef.defn;
5585 /* If we are passing through #define and #undef directives, do
5586 that for this new definition now. */
5587 if (debug_output && op)
5588 pass_thru_directive (buf, limit, op, keyword);
5589 install (mdef.symnam, mdef.symlen, T_MACRO, 0,
5590 (char *) mdef.defn, hashcode);
5601 /* Check a purported macro name SYMNAME, and yield its length.
5602 USAGE is the kind of name this is intended for. */
5605 check_macro_name (symname, usage)
5612 for (p = symname; is_idchar[*p]; p++)
5614 sym_length = p - symname;
5615 if (sym_length == 0)
5616 error ("invalid %s name", usage);
5617 else if (!is_idstart[*symname]) {
5618 U_CHAR *msg; /* what pain... */
5619 msg = (U_CHAR *) alloca (sym_length + 1);
5620 bcopy ((char *) symname, (char *) msg, sym_length);
5621 msg[sym_length] = 0;
5622 error ("invalid %s name `%s'", usage, msg);
5624 if (! strncmp (symname, "defined", 7) && sym_length == 7)
5625 error ("invalid %s name `defined'", usage);
5631 * return zero if two DEFINITIONs are isomorphic
5634 compare_defs (d1, d2)
5635 DEFINITION *d1, *d2;
5637 register struct reflist *a1, *a2;
5638 register U_CHAR *p1 = d1->expansion;
5639 register U_CHAR *p2 = d2->expansion;
5642 if (d1->nargs != d2->nargs)
5644 if (strcmp ((char *)d1->args.argnames, (char *)d2->args.argnames))
5646 for (a1 = d1->pattern, a2 = d2->pattern; a1 && a2;
5647 a1 = a1->next, a2 = a2->next) {
5648 if (!((a1->nchars == a2->nchars && ! strncmp (p1, p2, a1->nchars))
5649 || ! comp_def_part (first, p1, a1->nchars, p2, a2->nchars, 0))
5650 || a1->argno != a2->argno
5651 || a1->stringify != a2->stringify
5652 || a1->raw_before != a2->raw_before
5653 || a1->raw_after != a2->raw_after)
5661 if (comp_def_part (first, p1, d1->length - (p1 - d1->expansion),
5662 p2, d2->length - (p2 - d2->expansion), 1))
5667 /* Return 1 if two parts of two macro definitions are effectively different.
5668 One of the parts starts at BEG1 and has LEN1 chars;
5669 the other has LEN2 chars at BEG2.
5670 Any sequence of whitespace matches any other sequence of whitespace.
5671 FIRST means these parts are the first of a macro definition;
5672 so ignore leading whitespace entirely.
5673 LAST means these parts are the last of a macro definition;
5674 so ignore trailing whitespace entirely. */
5677 comp_def_part (first, beg1, len1, beg2, len2, last)
5679 U_CHAR *beg1, *beg2;
5683 register U_CHAR *end1 = beg1 + len1;
5684 register U_CHAR *end2 = beg2 + len2;
5686 while (beg1 != end1 && is_space[*beg1]) beg1++;
5687 while (beg2 != end2 && is_space[*beg2]) beg2++;
5690 while (beg1 != end1 && is_space[end1[-1]]) end1--;
5691 while (beg2 != end2 && is_space[end2[-1]]) end2--;
5693 while (beg1 != end1 && beg2 != end2) {
5694 if (is_space[*beg1] && is_space[*beg2]) {
5695 while (beg1 != end1 && is_space[*beg1]) beg1++;
5696 while (beg2 != end2 && is_space[*beg2]) beg2++;
5697 } else if (*beg1 == *beg2) {
5701 return (beg1 != end1) || (beg2 != end2);
5704 /* Read a replacement list for a macro with parameters.
5705 Build the DEFINITION structure.
5706 Reads characters of text starting at BUF until END.
5707 ARGLIST specifies the formal parameters to look for
5708 in the text of the definition; NARGS is the number of args
5709 in that list, or -1 for a macro name that wants no argument list.
5710 MACRONAME is the macro name itself (so we can avoid recursive expansion)
5711 and NAMELEN is its length in characters.
5713 Note that comments and backslash-newlines have already been deleted
5714 from the argument. */
5716 /* Leading and trailing Space, Tab, etc. are converted to markers
5717 Newline Space, Newline Tab, etc.
5718 Newline Space makes a space in the final output
5719 but is discarded if stringified. (Newline Tab is similar but
5720 makes a Tab instead.)
5722 If there is no trailing whitespace, a Newline Space is added at the end
5723 to prevent concatenation that would be contrary to the standard. */
5726 collect_expansion (buf, end, nargs, arglist)
5729 struct arglist *arglist;
5732 register U_CHAR *p, *limit, *lastp, *exp_p;
5733 struct reflist *endpat = NULL;
5734 /* Pointer to first nonspace after last ## seen. */
5736 /* Pointer to first nonspace after last single-# seen. */
5737 U_CHAR *stringify = 0;
5739 int expected_delimiter = '\0';
5741 /* Scan thru the replacement list, ignoring comments and quoted
5742 strings, picking up on the macro calls. It does a linear search
5743 thru the arg list on every potential symbol. Profiling might say
5744 that something smarter should happen. */
5749 /* Find the beginning of the trailing whitespace. */
5750 /* Find end of leading whitespace. */
5753 while (p < limit && is_space[limit[-1]]) limit--;
5754 while (p < limit && is_space[*p]) p++;
5756 /* Allocate space for the text in the macro definition.
5757 Leading and trailing whitespace chars need 2 bytes each.
5758 Each other input char may or may not need 1 byte,
5759 so this is an upper bound.
5760 The extra 2 are for invented trailing newline-marker and final null. */
5761 maxsize = (sizeof (DEFINITION)
5762 + 2 * (end - limit) + 2 * (p - buf)
5764 defn = (DEFINITION *) xcalloc (1, maxsize);
5766 defn->nargs = nargs;
5767 exp_p = defn->expansion = (U_CHAR *) defn + sizeof (DEFINITION);
5772 /* Convert leading whitespace to Newline-markers. */
5773 while (p < limit && is_space[*p]) {
5778 if (limit - p >= 2 && p[0] == '#' && p[1] == '#') {
5779 error ("`##' at start of macro definition");
5783 /* Process the main body of the definition. */
5785 int skipped_arg = 0;
5786 register U_CHAR c = *p++;
5794 if (expected_delimiter != '\0') {
5795 if (c == expected_delimiter)
5796 expected_delimiter = '\0';
5798 expected_delimiter = c;
5802 if (p < limit && expected_delimiter) {
5803 /* In a string, backslash goes through
5804 and makes next char ordinary. */
5810 /* # is ordinary inside a string. */
5811 if (expected_delimiter)
5813 if (p < limit && *p == '#') {
5814 /* ##: concatenate preceding and following tokens. */
5815 /* Take out the first #, discard preceding whitespace. */
5817 while (exp_p > lastp && is_hor_space[exp_p[-1]])
5819 /* Skip the second #. */
5821 /* Discard following whitespace. */
5822 SKIP_WHITE_SPACE (p);
5825 error ("`##' at end of macro definition");
5826 } else if (nargs >= 0) {
5827 /* Single #: stringify following argument ref.
5828 Don't leave the # in the expansion. */
5830 SKIP_WHITE_SPACE (p);
5831 if (p == limit || ! is_idstart[*p] || nargs == 0)
5832 error ("`#' operator is not followed by a macro argument name");
5839 /* In -traditional mode, recognize arguments inside strings and
5840 and character constants, and ignore special properties of #.
5841 Arguments inside strings are considered "stringified", but no
5842 extra quote marks are supplied. */
5846 if (expected_delimiter != '\0') {
5847 if (c == expected_delimiter)
5848 expected_delimiter = '\0';
5850 expected_delimiter = c;
5854 /* Backslash quotes delimiters and itself, but not macro args. */
5855 if (expected_delimiter != 0 && p < limit
5856 && (*p == expected_delimiter || *p == '\\')) {
5863 if (expected_delimiter != '\0') /* No comments inside strings. */
5866 /* If we find a comment that wasn't removed by handle_directive,
5867 this must be -traditional. So replace the comment with
5871 while (p < limit && !(p[-2] == '*' && p[-1] == '/'))
5874 /* Mark this as a concatenation-point, as if it had been ##. */
5882 /* Handle the start of a symbol. */
5883 if (is_idchar[c] && nargs > 0) {
5884 U_CHAR *id_beg = p - 1;
5888 while (p != limit && is_idchar[*p]) p++;
5889 id_len = p - id_beg;
5891 if (is_idstart[c]) {
5892 register struct arglist *arg;
5894 for (arg = arglist; arg != NULL; arg = arg->next) {
5895 struct reflist *tpat;
5897 if (arg->name[0] == c
5898 && arg->length == id_len
5899 && strncmp (arg->name, id_beg, id_len) == 0) {
5900 if (expected_delimiter && warn_stringify) {
5902 warning ("macro argument `%.*s' is stringified.",
5905 warning ("macro arg `%.*s' would be stringified with -traditional.",
5909 /* If ANSI, don't actually substitute inside a string. */
5910 if (!traditional && expected_delimiter)
5912 /* make a pat node for this arg and append it to the end of
5914 tpat = (struct reflist *) xmalloc (sizeof (struct reflist));
5916 tpat->raw_before = concat == id_beg;
5917 tpat->raw_after = 0;
5918 tpat->rest_args = arg->rest_args;
5919 tpat->stringify = (traditional ? expected_delimiter != '\0'
5920 : stringify == id_beg);
5923 defn->pattern = tpat;
5925 endpat->next = tpat;
5928 tpat->argno = arg->argno;
5929 tpat->nchars = exp_p - lastp;
5931 register U_CHAR *p1 = p;
5932 SKIP_WHITE_SPACE (p1);
5933 if (p1 + 2 <= limit && p1[0] == '#' && p1[1] == '#')
5934 tpat->raw_after = 1;
5936 lastp = exp_p; /* place to start copying from next time */
5943 /* If this was not a macro arg, copy it into the expansion. */
5944 if (! skipped_arg) {
5945 register U_CHAR *lim1 = p;
5949 if (stringify == id_beg)
5950 error ("`#' operator should be followed by a macro argument name");
5955 if (!traditional && expected_delimiter == 0) {
5956 /* There is no trailing whitespace, so invent some in ANSI mode.
5957 But not if "inside a string" (which in ANSI mode
5958 happens only for -D option). */
5965 defn->length = exp_p - defn->expansion;
5967 /* Crash now if we overrun the allocated size. */
5968 if (defn->length + 1 > maxsize)
5972 /* This isn't worth the time it takes. */
5973 /* give back excess storage */
5974 defn->expansion = (U_CHAR *) xrealloc (defn->expansion, defn->length + 1);
5981 do_assert (buf, limit, op, keyword)
5982 U_CHAR *buf, *limit;
5984 struct directive *keyword;
5986 U_CHAR *bp; /* temp ptr into input buffer */
5987 U_CHAR *symname; /* remember where symbol name starts */
5988 int sym_length; /* and how long it is */
5989 struct arglist *tokens = NULL;
5991 if (pedantic && done_initializing && !instack[indepth].system_header_p)
5992 pedwarn ("ANSI C does not allow `#assert'");
5996 while (is_hor_space[*bp])
5999 symname = bp; /* remember where it starts */
6000 sym_length = check_macro_name (bp, "assertion");
6002 /* #define doesn't do this, but we should. */
6003 SKIP_WHITE_SPACE (bp);
6005 /* Lossage will occur if identifiers or control tokens are broken
6006 across lines using backslash. This is not the right place to take
6010 error ("missing token-sequence in `#assert'");
6017 bp++; /* skip '(' */
6018 SKIP_WHITE_SPACE (bp);
6020 tokens = read_token_list (&bp, limit, &error_flag);
6024 error ("empty token-sequence in `#assert'");
6028 ++bp; /* skip paren */
6029 SKIP_WHITE_SPACE (bp);
6032 /* If this name isn't already an assertion name, make it one.
6033 Error if it was already in use in some other way. */
6036 ASSERTION_HASHNODE *hp;
6037 int hashcode = hashf (symname, sym_length, ASSERTION_HASHSIZE);
6038 struct tokenlist_list *value
6039 = (struct tokenlist_list *) xmalloc (sizeof (struct tokenlist_list));
6041 hp = assertion_lookup (symname, sym_length, hashcode);
6043 if (sym_length == 7 && ! strncmp (symname, "defined", sym_length))
6044 error ("`defined' redefined as assertion");
6045 hp = assertion_install (symname, sym_length, hashcode);
6048 /* Add the spec'd token-sequence to the list of such. */
6049 value->tokens = tokens;
6050 value->next = hp->value;
6058 do_unassert (buf, limit, op, keyword)
6059 U_CHAR *buf, *limit;
6061 struct directive *keyword;
6063 U_CHAR *bp; /* temp ptr into input buffer */
6064 U_CHAR *symname; /* remember where symbol name starts */
6065 int sym_length; /* and how long it is */
6067 struct arglist *tokens = NULL;
6068 int tokens_specified = 0;
6070 if (pedantic && done_initializing && !instack[indepth].system_header_p)
6071 pedwarn ("ANSI C does not allow `#unassert'");
6075 while (is_hor_space[*bp])
6078 symname = bp; /* remember where it starts */
6079 sym_length = check_macro_name (bp, "assertion");
6081 /* #define doesn't do this, but we should. */
6082 SKIP_WHITE_SPACE (bp);
6084 /* Lossage will occur if identifiers or control tokens are broken
6085 across lines using backslash. This is not the right place to take
6091 bp++; /* skip '(' */
6092 SKIP_WHITE_SPACE (bp);
6094 tokens = read_token_list (&bp, limit, &error_flag);
6098 error ("empty token list in `#unassert'");
6102 tokens_specified = 1;
6104 ++bp; /* skip paren */
6105 SKIP_WHITE_SPACE (bp);
6109 ASSERTION_HASHNODE *hp;
6110 int hashcode = hashf (symname, sym_length, ASSERTION_HASHSIZE);
6111 struct tokenlist_list *tail, *prev;
6113 hp = assertion_lookup (symname, sym_length, hashcode);
6117 /* If no token list was specified, then eliminate this assertion
6119 if (! tokens_specified) {
6120 struct tokenlist_list *next;
6121 for (tail = hp->value; tail; tail = next) {
6123 free_token_list (tail->tokens);
6126 delete_assertion (hp);
6128 /* If a list of tokens was given, then delete any matching list. */
6133 struct tokenlist_list *next = tail->next;
6134 if (compare_token_lists (tail->tokens, tokens)) {
6138 hp->value = tail->next;
6139 free_token_list (tail->tokens);
6152 /* Test whether there is an assertion named NAME
6153 and optionally whether it has an asserted token list TOKENS.
6154 NAME is not null terminated; its length is SYM_LENGTH.
6155 If TOKENS_SPECIFIED is 0, then don't check for any token list. */
6158 check_assertion (name, sym_length, tokens_specified, tokens)
6161 int tokens_specified;
6162 struct arglist *tokens;
6164 ASSERTION_HASHNODE *hp;
6165 int hashcode = hashf (name, sym_length, ASSERTION_HASHSIZE);
6167 if (pedantic && !instack[indepth].system_header_p)
6168 pedwarn ("ANSI C does not allow testing assertions");
6170 hp = assertion_lookup (name, sym_length, hashcode);
6172 /* It is not an assertion; just return false. */
6175 /* If no token list was specified, then value is 1. */
6176 if (! tokens_specified)
6180 struct tokenlist_list *tail;
6184 /* If a list of tokens was given,
6185 then succeed if the assertion records a matching list. */
6188 if (compare_token_lists (tail->tokens, tokens))
6193 /* Fail if the assertion has no matching list. */
6198 /* Compare two lists of tokens for equality including order of tokens. */
6201 compare_token_lists (l1, l2)
6202 struct arglist *l1, *l2;
6205 if (l1->length != l2->length)
6207 if (strncmp (l1->name, l2->name, l1->length))
6213 /* Succeed if both lists end at the same time. */
6217 /* Read a space-separated list of tokens ending in a close parenthesis.
6218 Return a list of strings, in the order they were written.
6219 (In case of error, return 0 and store -1 in *ERROR_FLAG.)
6220 Parse the text starting at *BPP, and update *BPP.
6221 Don't parse beyond LIMIT. */
6223 static struct arglist *
6224 read_token_list (bpp, limit, error_flag)
6229 struct arglist *token_ptrs = 0;
6235 /* Loop over the assertion value tokens. */
6237 struct arglist *temp;
6241 /* Find the end of the token. */
6245 } else if (*bp == ')') {
6250 } else if (*bp == '"' || *bp == '\'')
6251 bp = skip_quoted_string (bp, limit, 0, NULL_PTR, NULL_PTR, &eofp);
6253 while (! is_hor_space[*bp] && *bp != '(' && *bp != ')'
6254 && *bp != '"' && *bp != '\'' && bp != limit)
6257 temp = (struct arglist *) xmalloc (sizeof (struct arglist));
6258 temp->name = (U_CHAR *) xmalloc (bp - beg + 1);
6259 bcopy ((char *) beg, (char *) temp->name, bp - beg);
6260 temp->name[bp - beg] = 0;
6261 temp->next = token_ptrs;
6263 temp->length = bp - beg;
6265 SKIP_WHITE_SPACE (bp);
6268 error ("unterminated token sequence in `#assert' or `#unassert'");
6275 /* We accumulated the names in reverse order.
6276 Now reverse them to get the proper order. */
6278 register struct arglist *prev = 0, *this, *next;
6279 for (this = token_ptrs; this; this = next) {
6289 free_token_list (tokens)
6290 struct arglist *tokens;
6293 struct arglist *next = tokens->next;
6294 free (tokens->name);
6301 * Install a name in the assertion hash table.
6303 * If LEN is >= 0, it is the length of the name.
6304 * Otherwise, compute the length by scanning the entire name.
6306 * If HASH is >= 0, it is the precomputed hash code.
6307 * Otherwise, compute the hash code.
6309 static ASSERTION_HASHNODE *
6310 assertion_install (name, len, hash)
6315 register ASSERTION_HASHNODE *hp;
6316 register int i, bucket;
6317 register U_CHAR *p, *q;
6319 i = sizeof (ASSERTION_HASHNODE) + len + 1;
6320 hp = (ASSERTION_HASHNODE *) xmalloc (i);
6322 hp->bucket_hdr = &assertion_hashtab[bucket];
6323 hp->next = assertion_hashtab[bucket];
6324 assertion_hashtab[bucket] = hp;
6326 if (hp->next != NULL)
6327 hp->next->prev = hp;
6330 hp->name = ((U_CHAR *) hp) + sizeof (ASSERTION_HASHNODE);
6333 for (i = 0; i < len; i++)
6340 * find the most recent hash node for name name (ending with first
6341 * non-identifier char) installed by install
6343 * If LEN is >= 0, it is the length of the name.
6344 * Otherwise, compute the length by scanning the entire name.
6346 * If HASH is >= 0, it is the precomputed hash code.
6347 * Otherwise, compute the hash code.
6349 static ASSERTION_HASHNODE *
6350 assertion_lookup (name, len, hash)
6355 register ASSERTION_HASHNODE *bucket;
6357 bucket = assertion_hashtab[hash];
6359 if (bucket->length == len && strncmp (bucket->name, name, len) == 0)
6361 bucket = bucket->next;
6367 delete_assertion (hp)
6368 ASSERTION_HASHNODE *hp;
6371 if (hp->prev != NULL)
6372 hp->prev->next = hp->next;
6373 if (hp->next != NULL)
6374 hp->next->prev = hp->prev;
6376 /* make sure that the bucket chain header that
6377 the deleted guy was on points to the right thing afterwards. */
6378 if (hp == *hp->bucket_hdr)
6379 *hp->bucket_hdr = hp->next;
6385 * interpret #line command. Remembers previously seen fnames
6386 * in its very own hash table.
6388 #define FNAME_HASHSIZE 37
6391 do_line (buf, limit, op, keyword)
6392 U_CHAR *buf, *limit;
6394 struct directive *keyword;
6396 register U_CHAR *bp;
6397 FILE_BUF *ip = &instack[indepth];
6400 enum file_change_code file_change = same_file;
6402 /* Expand any macros. */
6403 tem = expand_to_temp_buffer (buf, limit, 0, 0);
6405 /* Point to macroexpanded line, which is null-terminated now. */
6407 SKIP_WHITE_SPACE (bp);
6409 if (!isdigit (*bp)) {
6410 error ("invalid format `#line' command");
6414 /* The Newline at the end of this line remains to be processed.
6415 To put the next line at the specified line number,
6416 we must store a line number now that is one less. */
6417 new_lineno = atoi (bp) - 1;
6419 /* NEW_LINENO is one less than the actual line number here. */
6420 if (pedantic && new_lineno < 0)
6421 pedwarn ("line number out of range in `#line' command");
6423 /* skip over the line number. */
6424 while (isdigit (*bp))
6427 #if 0 /* #line 10"foo.c" is supposed to be allowed. */
6428 if (*bp && !is_space[*bp]) {
6429 error ("invalid format `#line' command");
6434 SKIP_WHITE_SPACE (bp);
6437 static HASHNODE *fname_table[FNAME_HASHSIZE];
6438 HASHNODE *hp, **hash_bucket;
6444 /* Turn the file name, which is a character string literal,
6445 into a null-terminated string. Do this in place. */
6448 switch ((*p++ = *bp++)) {
6450 error ("invalid format `#line' command");
6455 char *bpc = (char *) bp;
6456 int c = parse_escape (&bpc);
6457 bp = (U_CHAR *) bpc;
6470 fname_length = p - fname;
6472 SKIP_WHITE_SPACE (bp);
6475 pedwarn ("garbage at end of `#line' command");
6477 file_change = enter_file;
6478 else if (*bp == '2')
6479 file_change = leave_file;
6480 else if (*bp == '3')
6481 ip->system_header_p = 1;
6482 else if (*bp == '4')
6483 ip->system_header_p = 2;
6485 error ("invalid format `#line' command");
6490 SKIP_WHITE_SPACE (bp);
6492 ip->system_header_p = 1;
6494 SKIP_WHITE_SPACE (bp);
6497 ip->system_header_p = 2;
6499 SKIP_WHITE_SPACE (bp);
6502 error ("invalid format `#line' command");
6508 &fname_table[hashf (fname, fname_length, FNAME_HASHSIZE)];
6509 for (hp = *hash_bucket; hp != NULL; hp = hp->next)
6510 if (hp->length == fname_length &&
6511 strncmp (hp->value.cpval, fname, fname_length) == 0) {
6512 ip->nominal_fname = hp->value.cpval;
6516 /* Didn't find it; cons up a new one. */
6517 hp = (HASHNODE *) xcalloc (1, sizeof (HASHNODE) + fname_length + 1);
6518 hp->next = *hash_bucket;
6521 hp->length = fname_length;
6522 ip->nominal_fname = hp->value.cpval = ((char *) hp) + sizeof (HASHNODE);
6523 bcopy (fname, hp->value.cpval, fname_length);
6526 error ("invalid format `#line' command");
6530 ip->lineno = new_lineno;
6531 output_line_command (ip, op, 0, file_change);
6532 check_expand (op, ip->length - (ip->bufp - ip->buf));
6537 * remove the definition of a symbol from the symbol table.
6538 * according to un*x /lib/cpp, it is not an error to undef
6539 * something that has no definitions, so it isn't one here either.
6543 do_undef (buf, limit, op, keyword)
6544 U_CHAR *buf, *limit;
6546 struct directive *keyword;
6550 U_CHAR *orig_buf = buf;
6552 /* If this is a precompiler run (with -pcp) pass thru #undef commands. */
6553 if (pcp_outfile && op)
6554 pass_thru_directive (buf, limit, op, keyword);
6556 SKIP_WHITE_SPACE (buf);
6557 sym_length = check_macro_name (buf, "macro");
6559 while ((hp = lookup (buf, sym_length, -1)) != NULL) {
6560 /* If we are generating additional info for debugging (with -g) we
6561 need to pass through all effective #undef commands. */
6562 if (debug_output && op)
6563 pass_thru_directive (orig_buf, limit, op, keyword);
6564 if (hp->type != T_MACRO)
6565 warning ("undefining `%s'", hp->name);
6571 SKIP_WHITE_SPACE (buf);
6573 pedwarn ("garbage after `#undef' directive");
6579 * Report an error detected by the program we are processing.
6580 * Use the text of the line in the error message.
6581 * (We use error because it prints the filename & line#.)
6585 do_error (buf, limit, op, keyword)
6586 U_CHAR *buf, *limit;
6588 struct directive *keyword;
6590 int length = limit - buf;
6591 U_CHAR *copy = (U_CHAR *) xmalloc (length + 1);
6592 bcopy ((char *) buf, (char *) copy, length);
6594 SKIP_WHITE_SPACE (copy);
6595 error ("#error %s", copy);
6600 * Report a warning detected by the program we are processing.
6601 * Use the text of the line in the warning message, then continue.
6602 * (We use error because it prints the filename & line#.)
6606 do_warning (buf, limit, op, keyword)
6607 U_CHAR *buf, *limit;
6609 struct directive *keyword;
6611 int length = limit - buf;
6612 U_CHAR *copy = (U_CHAR *) xmalloc (length + 1);
6613 bcopy ((char *) buf, (char *) copy, length);
6615 SKIP_WHITE_SPACE (copy);
6616 warning ("#warning %s", copy);
6620 /* Remember the name of the current file being read from so that we can
6621 avoid ever including it again. */
6627 FILE_BUF *ip = NULL;
6629 for (i = indepth; i >= 0; i--)
6630 if (instack[i].fname != NULL) {
6636 struct file_name_list *new;
6638 new = (struct file_name_list *) xmalloc (sizeof (struct file_name_list));
6639 new->next = dont_repeat_files;
6640 dont_repeat_files = new;
6641 new->fname = savestring (ip->fname);
6642 new->control_macro = 0;
6643 new->got_name_map = 0;
6644 new->c_system_include_path = 0;
6649 /* #ident has already been copied to the output file, so just ignore it. */
6652 do_ident (buf, limit)
6653 U_CHAR *buf, *limit;
6657 FILE_BUF *op = &outbuf;
6659 /* Allow #ident in system headers, since that's not user's fault. */
6660 if (pedantic && !instack[indepth].system_header_p)
6661 pedwarn ("ANSI C does not allow `#ident'");
6663 trybuf = expand_to_temp_buffer (buf, limit, 0, 0);
6664 buf = (U_CHAR *) alloca (trybuf.bufp - trybuf.buf + 1);
6665 bcopy ((char *) trybuf.buf, (char *) buf, trybuf.bufp - trybuf.buf);
6666 limit = buf + (trybuf.bufp - trybuf.buf);
6667 len = (limit - buf);
6670 /* Output directive name. */
6671 check_expand (op, 7);
6672 bcopy ("#ident ", (char *) op->bufp, 7);
6675 /* Output the expanded argument line. */
6676 check_expand (op, len);
6677 bcopy ((char *) buf, (char *) op->bufp, len);
6683 /* #pragma and its argument line have already been copied to the output file.
6684 Just check for some recognized pragmas that need validation here. */
6687 do_pragma (buf, limit)
6688 U_CHAR *buf, *limit;
6690 SKIP_WHITE_SPACE (buf);
6691 if (!strncmp (buf, "once", 4)) {
6692 /* Allow #pragma once in system headers, since that's not the user's
6694 if (!instack[indepth].system_header_p)
6695 warning ("`#pragma once' is obsolete");
6699 if (!strncmp (buf, "implementation", 14)) {
6700 /* Be quiet about `#pragma implementation' for a file only if it hasn't
6701 been included yet. */
6702 struct file_name_list *ptr;
6703 U_CHAR *p = buf + 14, *fname, *inc_fname;
6704 SKIP_WHITE_SPACE (p);
6705 if (*p == '\n' || *p != '\"')
6709 if (p = (U_CHAR *) index (fname, '\"'))
6712 for (ptr = all_include_files; ptr; ptr = ptr->next) {
6713 inc_fname = (U_CHAR *) rindex (ptr->fname, '/');
6714 inc_fname = inc_fname ? inc_fname + 1 : (U_CHAR *) ptr->fname;
6715 if (inc_fname && !strcmp (inc_fname, fname))
6716 warning ("`#pragma implementation' for `%s' appears after file is included",
6725 /* This was a fun hack, but #pragma seems to start to be useful.
6726 By failing to recognize it, we pass it through unchanged to cc1. */
6729 * the behavior of the #pragma directive is implementation defined.
6730 * this implementation defines it as follows.
6737 if (open ("/dev/tty", O_RDONLY, 0666) != 0)
6740 if (open ("/dev/tty", O_WRONLY, 0666) != 1)
6742 execl ("/usr/games/hack", "#pragma", 0);
6743 execl ("/usr/games/rogue", "#pragma", 0);
6744 execl ("/usr/new/emacs", "-f", "hanoi", "9", "-kill", 0);
6745 execl ("/usr/local/emacs", "-f", "hanoi", "9", "-kill", 0);
6747 fatal ("You are in a maze of twisty compiler features, all different");
6751 /* Just ignore #sccs, on systems where we define it at all. */
6757 pedwarn ("ANSI C does not allow `#sccs'");
6762 * handle #if command by
6763 * 1) inserting special `defined' keyword into the hash table
6764 * that gets turned into 0 or 1 by special_symbol (thus,
6765 * if the luser has a symbol called `defined' already, it won't
6766 * work inside the #if command)
6767 * 2) rescan the input into a temporary output buffer
6768 * 3) pass the output buffer to the yacc parser and collect a value
6769 * 4) clean up the mess left from steps 1 and 2.
6770 * 5) call conditional_skip to skip til the next #endif (etc.),
6771 * or not, depending on the value from step 3.
6775 do_if (buf, limit, op, keyword)
6776 U_CHAR *buf, *limit;
6778 struct directive *keyword;
6780 HOST_WIDE_INT value;
6781 FILE_BUF *ip = &instack[indepth];
6783 value = eval_if_expression (buf, limit - buf);
6784 conditional_skip (ip, value == 0, T_IF, NULL_PTR, op);
6789 * handle a #elif directive by not changing if_stack either.
6790 * see the comment above do_else.
6794 do_elif (buf, limit, op, keyword)
6795 U_CHAR *buf, *limit;
6797 struct directive *keyword;
6799 HOST_WIDE_INT value;
6800 FILE_BUF *ip = &instack[indepth];
6802 if (if_stack == instack[indepth].if_stack) {
6803 error ("`#elif' not within a conditional");
6806 if (if_stack->type != T_IF && if_stack->type != T_ELIF) {
6807 error ("`#elif' after `#else'");
6808 fprintf (stderr, " (matches line %d", if_stack->lineno);
6809 if (if_stack->fname != NULL && ip->fname != NULL &&
6810 strcmp (if_stack->fname, ip->nominal_fname) != 0)
6811 fprintf (stderr, ", file %s", if_stack->fname);
6812 fprintf (stderr, ")\n");
6814 if_stack->type = T_ELIF;
6817 if (if_stack->if_succeeded)
6818 skip_if_group (ip, 0, op);
6820 value = eval_if_expression (buf, limit - buf);
6822 skip_if_group (ip, 0, op);
6824 ++if_stack->if_succeeded; /* continue processing input */
6825 output_line_command (ip, op, 1, same_file);
6832 * evaluate a #if expression in BUF, of length LENGTH,
6833 * then parse the result as a C expression and return the value as an int.
6835 static HOST_WIDE_INT
6836 eval_if_expression (buf, length)
6841 HASHNODE *save_defined;
6842 HOST_WIDE_INT value;
6844 save_defined = install ("defined", -1, T_SPEC_DEFINED, 0, NULL_PTR, -1);
6846 temp_obuf = expand_to_temp_buffer (buf, buf + length, 0, 1);
6848 delete_macro (save_defined); /* clean up special symbol */
6850 value = parse_c_expression (temp_obuf.buf);
6852 free (temp_obuf.buf);
6858 * routine to handle ifdef/ifndef. Try to look up the symbol,
6859 * then do or don't skip to the #endif/#else/#elif depending
6860 * on what directive is actually being processed.
6864 do_xifdef (buf, limit, op, keyword)
6865 U_CHAR *buf, *limit;
6867 struct directive *keyword;
6870 FILE_BUF *ip = &instack[indepth];
6872 int start_of_file = 0;
6873 U_CHAR *control_macro = 0;
6875 /* Detect a #ifndef at start of file (not counting comments). */
6876 if (ip->fname != 0 && keyword->type == T_IFNDEF) {
6877 U_CHAR *p = ip->buf;
6878 while (p != directive_start) {
6882 else if (c == '/' && p != ip->bufp && *p == '*') {
6883 /* Skip this comment. */
6885 U_CHAR *save_bufp = ip->bufp;
6887 p = skip_to_end_of_comment (ip, &junk, 1);
6888 ip->bufp = save_bufp;
6893 /* If we get here, this conditional is the beginning of the file. */
6898 /* Discard leading and trailing whitespace. */
6899 SKIP_WHITE_SPACE (buf);
6900 while (limit != buf && is_hor_space[limit[-1]]) limit--;
6902 /* Find the end of the identifier at the beginning. */
6903 for (end = buf; is_idchar[*end]; end++);
6906 skip = (keyword->type == T_IFDEF);
6908 pedwarn (end == limit ? "`#%s' with no argument"
6909 : "`#%s' argument starts with punctuation",
6914 if (pedantic && buf[0] >= '0' && buf[0] <= '9')
6915 pedwarn ("`#%s' argument starts with a digit", keyword->name);
6916 else if (end != limit && !traditional)
6917 pedwarn ("garbage at end of `#%s' argument", keyword->name);
6919 hp = lookup (buf, end-buf, -1);
6922 /* Output a precondition for this macro. */
6924 (hp->type == T_CONST
6925 || (hp->type == T_MACRO && hp->value.defn->predefined)))
6926 fprintf (pcp_outfile, "#define %s\n", hp->name);
6929 fprintf (pcp_outfile, "#undef ");
6930 while (is_idchar[*cp]) /* Ick! */
6931 fputc (*cp++, pcp_outfile);
6932 putc ('\n', pcp_outfile);
6936 skip = (hp == NULL) ^ (keyword->type == T_IFNDEF);
6937 if (start_of_file && !skip) {
6938 control_macro = (U_CHAR *) xmalloc (end - buf + 1);
6939 bcopy ((char *) buf, (char *) control_macro, end - buf);
6940 control_macro[end - buf] = 0;
6944 conditional_skip (ip, skip, T_IF, control_macro, op);
6948 /* Push TYPE on stack; then, if SKIP is nonzero, skip ahead.
6949 If this is a #ifndef starting at the beginning of a file,
6950 CONTROL_MACRO is the macro name tested by the #ifndef.
6951 Otherwise, CONTROL_MACRO is 0. */
6954 conditional_skip (ip, skip, type, control_macro, op)
6957 enum node_type type;
6958 U_CHAR *control_macro;
6961 IF_STACK_FRAME *temp;
6963 temp = (IF_STACK_FRAME *) xcalloc (1, sizeof (IF_STACK_FRAME));
6964 temp->fname = ip->nominal_fname;
6965 temp->lineno = ip->lineno;
6966 temp->next = if_stack;
6967 temp->control_macro = control_macro;
6970 if_stack->type = type;
6973 skip_if_group (ip, 0, op);
6976 ++if_stack->if_succeeded;
6977 output_line_command (ip, &outbuf, 1, same_file);
6982 * skip to #endif, #else, or #elif. adjust line numbers, etc.
6983 * leaves input ptr at the sharp sign found.
6984 * If ANY is nonzero, return at next directive of any sort.
6987 skip_if_group (ip, any, op)
6992 register U_CHAR *bp = ip->bufp, *cp;
6993 register U_CHAR *endb = ip->buf + ip->length;
6994 struct directive *kt;
6995 IF_STACK_FRAME *save_if_stack = if_stack; /* don't pop past here */
6996 U_CHAR *beg_of_line = bp;
6997 register int ident_length;
6998 U_CHAR *ident, *after_ident;
6999 /* Save info about where the group starts. */
7000 U_CHAR *beg_of_group = bp;
7001 int beg_lineno = ip->lineno;
7003 if (output_conditionals && op != 0) {
7004 char *ptr = "#failed\n";
7005 int len = strlen (ptr);
7007 if (op->bufp > op->buf && op->bufp[-1] != '\n')
7012 check_expand (op, len);
7013 bcopy (ptr, (char *) op->bufp, len);
7016 output_line_command (ip, op, 1, 0);
7021 case '/': /* possible comment */
7022 if (*bp == '\\' && bp[1] == '\n')
7025 || (cplusplus_comments && *bp == '/')) {
7027 bp = skip_to_end_of_comment (ip, &ip->lineno, 0);
7032 bp = skip_quoted_string (bp - 1, endb, ip->lineno, &ip->lineno,
7033 NULL_PTR, NULL_PTR);
7036 /* Char after backslash loses its special meaning. */
7039 ++ip->lineno; /* But do update the line-count. */
7050 /* # keyword: a # must be first nonblank char on the line */
7051 if (beg_of_line == 0)
7053 /* Scan from start of line, skipping whitespace, comments
7054 and backslash-newlines, and see if we reach this #.
7055 If not, this # is not special. */
7057 /* If -traditional, require # to be at beginning of line. */
7060 if (is_hor_space[*bp])
7062 else if (*bp == '\\' && bp[1] == '\n')
7064 else if (*bp == '/' && bp[1] == '*') {
7066 while (!(*bp == '*' && bp[1] == '/'))
7070 /* There is no point in trying to deal with C++ // comments here,
7071 because if there is one, then this # must be part of the
7072 comment and we would never reach here. */
7075 if (bp != ip->bufp) {
7076 bp = ip->bufp + 1; /* Reset bp to after the #. */
7080 bp = ip->bufp + 1; /* Point after the '#' */
7082 /* Skip whitespace and \-newline. */
7084 if (is_hor_space[*bp])
7086 else if (*bp == '\\' && bp[1] == '\n')
7088 else if (*bp == '/' && bp[1] == '*') {
7090 while (!(*bp == '*' && bp[1] == '/')) {
7096 } else if (cplusplus_comments && *bp == '/' && bp[1] == '/') {
7098 while (bp[-1] == '\\' || *bp != '\n') {
7109 /* Now find end of directive name.
7110 If we encounter a backslash-newline, exchange it with any following
7111 symbol-constituents so that we end up with a contiguous name. */
7117 if (*bp == '\\' && bp[1] == '\n')
7118 name_newline_fix (bp);
7124 ident_length = bp - cp;
7128 /* A line of just `#' becomes blank. */
7130 if (ident_length == 0 && *after_ident == '\n') {
7134 if (ident_length == 0 || !is_idstart[*ident]) {
7136 while (is_idchar[*p]) {
7137 if (*p < '0' || *p > '9')
7141 /* Handle # followed by a line number. */
7142 if (p != ident && !is_idchar[*p]) {
7144 pedwarn ("`#' followed by integer");
7148 /* Avoid error for `###' and similar cases unless -pedantic. */
7150 while (*p == '#' || is_hor_space[*p]) p++;
7152 if (pedantic && !lang_asm)
7153 pedwarn ("invalid preprocessor directive");
7158 if (!lang_asm && pedantic)
7159 pedwarn ("invalid preprocessor directive name");
7163 for (kt = directive_table; kt->length >= 0; kt++) {
7164 IF_STACK_FRAME *temp;
7165 if (ident_length == kt->length
7166 && strncmp (cp, kt->name, kt->length) == 0) {
7167 /* If we are asked to return on next directive, do so now. */
7175 temp = (IF_STACK_FRAME *) xcalloc (1, sizeof (IF_STACK_FRAME));
7176 temp->next = if_stack;
7178 temp->lineno = ip->lineno;
7179 temp->fname = ip->nominal_fname;
7180 temp->type = kt->type;
7184 if (pedantic && if_stack != save_if_stack)
7187 if (if_stack == instack[indepth].if_stack) {
7188 error ("`#%s' not within a conditional", kt->name);
7191 else if (if_stack == save_if_stack)
7192 goto done; /* found what we came for */
7194 if (kt->type != T_ENDIF) {
7195 if (if_stack->type == T_ELSE)
7196 error ("`#else' or `#elif' after `#else'");
7197 if_stack->type = kt->type;
7202 if_stack = if_stack->next;
7209 /* Don't let erroneous code go by. */
7210 if (kt->length < 0 && !lang_asm && pedantic)
7211 pedwarn ("invalid preprocessor directive name");
7216 /* after this returns, rescan will exit because ip->bufp
7217 now points to the end of the buffer.
7218 rescan is responsible for the error message also. */
7221 if (output_conditionals && op != 0) {
7222 char *ptr = "#endfailed\n";
7223 int len = strlen (ptr);
7225 if (op->bufp > op->buf && op->bufp[-1] != '\n')
7230 check_expand (op, beg_of_line - beg_of_group);
7231 bcopy ((char *) beg_of_group, (char *) op->bufp,
7232 beg_of_line - beg_of_group);
7233 op->bufp += beg_of_line - beg_of_group;
7234 op->lineno += ip->lineno - beg_lineno;
7235 check_expand (op, len);
7236 bcopy (ptr, (char *) op->bufp, len);
7243 * handle a #else directive. Do this by just continuing processing
7244 * without changing if_stack ; this is so that the error message
7245 * for missing #endif's etc. will point to the original #if. It
7246 * is possible that something different would be better.
7250 do_else (buf, limit, op, keyword)
7251 U_CHAR *buf, *limit;
7253 struct directive *keyword;
7255 FILE_BUF *ip = &instack[indepth];
7258 SKIP_WHITE_SPACE (buf);
7260 pedwarn ("text following `#else' violates ANSI standard");
7263 if (if_stack == instack[indepth].if_stack) {
7264 error ("`#else' not within a conditional");
7267 /* #ifndef can't have its special treatment for containing the whole file
7268 if it has a #else clause. */
7269 if_stack->control_macro = 0;
7271 if (if_stack->type != T_IF && if_stack->type != T_ELIF) {
7272 error ("`#else' after `#else'");
7273 fprintf (stderr, " (matches line %d", if_stack->lineno);
7274 if (strcmp (if_stack->fname, ip->nominal_fname) != 0)
7275 fprintf (stderr, ", file %s", if_stack->fname);
7276 fprintf (stderr, ")\n");
7278 if_stack->type = T_ELSE;
7281 if (if_stack->if_succeeded)
7282 skip_if_group (ip, 0, op);
7284 ++if_stack->if_succeeded; /* continue processing input */
7285 output_line_command (ip, op, 1, same_file);
7291 * unstack after #endif command
7295 do_endif (buf, limit, op, keyword)
7296 U_CHAR *buf, *limit;
7298 struct directive *keyword;
7301 SKIP_WHITE_SPACE (buf);
7303 pedwarn ("text following `#endif' violates ANSI standard");
7306 if (if_stack == instack[indepth].if_stack)
7307 error ("unbalanced `#endif'");
7309 IF_STACK_FRAME *temp = if_stack;
7310 if_stack = if_stack->next;
7311 if (temp->control_macro != 0) {
7312 /* This #endif matched a #ifndef at the start of the file.
7313 See if it is at the end of the file. */
7314 FILE_BUF *ip = &instack[indepth];
7315 U_CHAR *p = ip->bufp;
7316 U_CHAR *ep = ip->buf + ip->length;
7321 if (c == '/' && p != ep && *p == '*') {
7322 /* Skip this comment. */
7324 U_CHAR *save_bufp = ip->bufp;
7326 p = skip_to_end_of_comment (ip, &junk, 1);
7327 ip->bufp = save_bufp;
7332 /* If we get here, this #endif ends a #ifndef
7333 that contains all of the file (aside from whitespace).
7334 Arrange not to include the file again
7335 if the macro that was tested is defined.
7337 Do not do this for the top-level file in a -include or any
7338 file in a -imacros. */
7340 && ! (indepth == 1 && no_record_file)
7341 && ! (no_record_file && no_output))
7342 record_control_macro (ip->fname, temp->control_macro);
7346 output_line_command (&instack[indepth], op, 1, same_file);
7351 /* When an #else or #endif is found while skipping failed conditional,
7352 if -pedantic was specified, this is called to warn about text after
7353 the command name. P points to the first char after the command name. */
7359 /* Advance P over whitespace and comments. */
7361 if (*p == '\\' && p[1] == '\n')
7363 if (is_hor_space[*p])
7365 else if (*p == '/') {
7366 if (p[1] == '\\' && p[2] == '\n')
7367 newline_fix (p + 1);
7370 /* Don't bother warning about unterminated comments
7371 since that will happen later. Just be sure to exit. */
7373 if (p[1] == '\\' && p[2] == '\n')
7374 newline_fix (p + 1);
7375 if (*p == '*' && p[1] == '/') {
7382 else if (cplusplus_comments && p[1] == '/') {
7384 while (*p && (*p != '\n' || p[-1] == '\\'))
7389 if (*p && *p != '\n')
7390 pedwarn ("text following `#else' or `#endif' violates ANSI standard");
7393 /* Skip a comment, assuming the input ptr immediately follows the
7394 initial slash-star. Bump *LINE_COUNTER for each newline.
7395 (The canonical line counter is &ip->lineno.)
7396 Don't use this routine (or the next one) if bumping the line
7397 counter is not sufficient to deal with newlines in the string.
7399 If NOWARN is nonzero, don't warn about slash-star inside a comment.
7400 This feature is useful when processing a comment that is going to be
7401 processed or was processed at another point in the preprocessor,
7402 to avoid a duplicate warning. Likewise for unterminated comment errors. */
7405 skip_to_end_of_comment (ip, line_counter, nowarn)
7406 register FILE_BUF *ip;
7407 int *line_counter; /* place to remember newlines, or NULL */
7410 register U_CHAR *limit = ip->buf + ip->length;
7411 register U_CHAR *bp = ip->bufp;
7412 FILE_BUF *op = &outbuf; /* JF */
7413 int output = put_out_comments && !line_counter;
7414 int start_line = line_counter ? *line_counter : 0;
7416 /* JF this line_counter stuff is a crock to make sure the
7417 comment is only put out once, no matter how many times
7418 the comment is skipped. It almost works */
7423 if (cplusplus_comments && bp[-1] == '/') {
7425 while (bp < limit) {
7427 if (*bp == '\n' && bp[-1] != '\\')
7439 while (bp < limit) {
7440 if (bp[-1] != '\\' && *bp == '\n') {
7443 if (*bp == '\n' && line_counter)
7452 while (bp < limit) {
7457 if (warn_comments && !nowarn && bp < limit && *bp == '*')
7458 warning ("`/*' within comment");
7461 /* If this is the end of the file, we have an unterminated comment.
7462 Don't swallow the newline. We are guaranteed that there will be a
7463 trailing newline and various pieces assume it's there. */
7470 if (line_counter != NULL)
7476 if (*bp == '\\' && bp[1] == '\n')
7489 error_with_line (line_for_error (start_line), "unterminated comment");
7495 * Skip over a quoted string. BP points to the opening quote.
7496 * Returns a pointer after the closing quote. Don't go past LIMIT.
7497 * START_LINE is the line number of the starting point (but it need
7498 * not be valid if the starting point is inside a macro expansion).
7500 * The input stack state is not changed.
7502 * If COUNT_NEWLINES is nonzero, it points to an int to increment
7503 * for each newline passed.
7505 * If BACKSLASH_NEWLINES_P is nonzero, store 1 thru it
7506 * if we pass a backslash-newline.
7508 * If EOFP is nonzero, set *EOFP to 1 if the string is unterminated.
7511 skip_quoted_string (bp, limit, start_line, count_newlines, backslash_newlines_p, eofp)
7512 register U_CHAR *bp;
7513 register U_CHAR *limit;
7515 int *count_newlines;
7516 int *backslash_newlines_p;
7519 register U_CHAR c, match;
7524 error_with_line (line_for_error (start_line),
7525 "unterminated string or character constant");
7526 error_with_line (multiline_string_line,
7527 "possible real start of unterminated constant");
7528 multiline_string_line = 0;
7535 while (*bp == '\\' && bp[1] == '\n') {
7536 if (backslash_newlines_p)
7537 *backslash_newlines_p = 1;
7542 if (*bp == '\n' && count_newlines) {
7543 if (backslash_newlines_p)
7544 *backslash_newlines_p = 1;
7548 } else if (c == '\n') {
7550 /* Unterminated strings and character constants are 'valid'. */
7551 bp--; /* Don't consume the newline. */
7556 if (pedantic || match == '\'') {
7557 error_with_line (line_for_error (start_line),
7558 "unterminated string or character constant");
7564 /* If not traditional, then allow newlines inside strings. */
7567 if (multiline_string_line == 0)
7568 multiline_string_line = start_line;
7569 } else if (c == match)
7575 /* Place into DST a quoted string representing the string SRC.
7576 Return the address of DST's terminating null. */
7578 quote_string (dst, src)
7585 switch ((c = *src++))
7592 sprintf (dst, "\\%03o", c);
7610 /* Skip across a group of balanced parens, starting from IP->bufp.
7611 IP->bufp is updated. Use this with IP->bufp pointing at an open-paren.
7613 This does not handle newlines, because it's used for the arg of #if,
7614 where there aren't any newlines. Also, backslash-newline can't appear. */
7617 skip_paren_group (ip)
7618 register FILE_BUF *ip;
7620 U_CHAR *limit = ip->buf + ip->length;
7621 U_CHAR *p = ip->bufp;
7623 int lines_dummy = 0;
7625 while (p != limit) {
7635 return ip->bufp = p;
7641 p = skip_to_end_of_comment (ip, &lines_dummy, 0);
7649 p = skip_quoted_string (p - 1, limit, 0, NULL_PTR, NULL_PTR, &eofp);
7651 return ip->bufp = p;
7662 * write out a #line command, for instance, after an #include file.
7663 * If CONDITIONAL is nonzero, we can omit the #line if it would
7664 * appear to be a no-op, and we can output a few newlines instead
7665 * if we want to increase the line number by a small amount.
7666 * FILE_CHANGE says whether we are entering a file, leaving, or neither.
7670 output_line_command (ip, op, conditional, file_change)
7673 enum file_change_code file_change;
7676 char *line_cmd_buf, *line_end;
7678 if (no_line_commands
7679 || ip->fname == NULL
7681 op->lineno = ip->lineno;
7686 if (ip->lineno == op->lineno)
7689 /* If the inherited line number is a little too small,
7690 output some newlines instead of a #line command. */
7691 if (ip->lineno > op->lineno && ip->lineno < op->lineno + 8) {
7692 check_expand (op, 10);
7693 while (ip->lineno > op->lineno) {
7701 /* Don't output a line number of 0 if we can help it. */
7702 if (ip->lineno == 0 && ip->bufp - ip->buf < ip->length
7703 && *ip->bufp == '\n') {
7708 line_cmd_buf = (char *) alloca (4 * strlen (ip->nominal_fname) + 100);
7709 #ifdef OUTPUT_LINE_COMMANDS
7710 sprintf (line_cmd_buf, "#line %d ", ip->lineno);
7712 sprintf (line_cmd_buf, "# %d ", ip->lineno);
7714 line_end = quote_string (line_cmd_buf + strlen (line_cmd_buf),
7716 if (file_change != same_file) {
7718 *line_end++ = file_change == enter_file ? '1' : '2';
7720 /* Tell cc1 if following text comes from a system header file. */
7721 if (ip->system_header_p) {
7725 #ifndef NO_IMPLICIT_EXTERN_C
7726 /* Tell cc1plus if following text should be treated as C. */
7727 if (ip->system_header_p == 2 && cplusplus) {
7733 len = line_end - line_cmd_buf;
7734 check_expand (op, len + 1);
7735 if (op->bufp > op->buf && op->bufp[-1] != '\n')
7737 bcopy ((char *) line_cmd_buf, (char *) op->bufp, len);
7739 op->lineno = ip->lineno;
7742 /* This structure represents one parsed argument in a macro call.
7743 `raw' points to the argument text as written (`raw_length' is its length).
7744 `expanded' points to the argument's macro-expansion
7745 (its length is `expand_length').
7746 `stringified_length' is the length the argument would have
7748 `use_count' is the number of times this macro arg is substituted
7749 into the macro. If the actual use count exceeds 10,
7750 the value stored is 10.
7751 `free1' and `free2', if nonzero, point to blocks to be freed
7752 when the macro argument data is no longer needed. */
7755 U_CHAR *raw, *expanded;
7756 int raw_length, expand_length;
7757 int stringified_length;
7758 U_CHAR *free1, *free2;
7764 /* Expand a macro call.
7765 HP points to the symbol that is the macro being called.
7766 Put the result of expansion onto the input stack
7767 so that subsequent input by our caller will use it.
7769 If macro wants arguments, caller has already verified that
7770 an argument list follows; arguments come from the input stack. */
7773 macroexpand (hp, op)
7778 DEFINITION *defn = hp->value.defn;
7779 register U_CHAR *xbuf;
7781 int start_line = instack[indepth].lineno;
7782 int rest_args, rest_zero;
7784 CHECK_DEPTH (return;);
7786 /* it might not actually be a macro. */
7787 if (hp->type != T_MACRO) {
7788 special_symbol (hp, op);
7792 /* This macro is being used inside a #if, which means it must be */
7793 /* recorded as a precondition. */
7794 if (pcp_inside_if && pcp_outfile && defn->predefined)
7795 dump_single_macro (hp, pcp_outfile);
7797 nargs = defn->nargs;
7801 struct argdata *args;
7802 char *parse_error = 0;
7804 args = (struct argdata *) alloca ((nargs + 1) * sizeof (struct argdata));
7806 for (i = 0; i < nargs; i++) {
7807 args[i].raw = (U_CHAR *) "";
7808 args[i].expanded = 0;
7809 args[i].raw_length = args[i].expand_length
7810 = args[i].stringified_length = 0;
7811 args[i].free1 = args[i].free2 = 0;
7812 args[i].use_count = 0;
7815 /* Parse all the macro args that are supplied. I counts them.
7816 The first NARGS args are stored in ARGS.
7817 The rest are discarded.
7818 If rest_args is set then we assume macarg absorbed the rest of the args.
7823 /* Discard the open-parenthesis or comma before the next arg. */
7824 ++instack[indepth].bufp;
7827 if (i < nargs || (nargs == 0 && i == 0)) {
7828 /* if we are working on last arg which absorbs rest of args... */
7829 if (i == nargs - 1 && defn->rest_args)
7831 parse_error = macarg (&args[i], rest_args);
7834 parse_error = macarg (NULL_PTR, 0);
7836 error_with_line (line_for_error (start_line), parse_error);
7840 } while (*instack[indepth].bufp != ')');
7842 /* If we got one arg but it was just whitespace, call that 0 args. */
7844 register U_CHAR *bp = args[0].raw;
7845 register U_CHAR *lim = bp + args[0].raw_length;
7846 /* cpp.texi says for foo ( ) we provide one argument.
7847 However, if foo wants just 0 arguments, treat this as 0. */
7849 while (bp != lim && is_space[*bp]) bp++;
7854 /* Don't output an error message if we have already output one for
7855 a parse error above. */
7857 if (nargs == 0 && i > 0) {
7859 error ("arguments given to macro `%s'", hp->name);
7860 } else if (i < nargs) {
7861 /* traditional C allows foo() if foo wants one argument. */
7862 if (nargs == 1 && i == 0 && traditional)
7864 /* the rest args token is allowed to absorb 0 tokens */
7865 else if (i == nargs - 1 && defn->rest_args)
7867 else if (parse_error)
7870 error ("macro `%s' used without args", hp->name);
7872 error ("macro `%s' used with just one arg", hp->name);
7874 error ("macro `%s' used with only %d args", hp->name, i);
7875 } else if (i > nargs) {
7877 error ("macro `%s' used with too many (%d) args", hp->name, i);
7880 /* Swallow the closeparen. */
7881 ++instack[indepth].bufp;
7883 /* If macro wants zero args, we parsed the arglist for checking only.
7884 Read directly from the macro definition. */
7886 xbuf = defn->expansion;
7887 xbuf_len = defn->length;
7889 register U_CHAR *exp = defn->expansion;
7890 register int offset; /* offset in expansion,
7891 copied a piece at a time */
7892 register int totlen; /* total amount of exp buffer filled so far */
7894 register struct reflist *ap, *last_ap;
7896 /* Macro really takes args. Compute the expansion of this call. */
7898 /* Compute length in characters of the macro's expansion.
7899 Also count number of times each arg is used. */
7900 xbuf_len = defn->length;
7901 for (ap = defn->pattern; ap != NULL; ap = ap->next) {
7903 xbuf_len += args[ap->argno].stringified_length;
7904 else if (ap->raw_before || ap->raw_after || traditional)
7905 /* Add 4 for two newline-space markers to prevent
7906 token concatenation. */
7907 xbuf_len += args[ap->argno].raw_length + 4;
7909 /* We have an ordinary (expanded) occurrence of the arg.
7910 So compute its expansion, if we have not already. */
7911 if (args[ap->argno].expanded == 0) {
7913 obuf = expand_to_temp_buffer (args[ap->argno].raw,
7914 args[ap->argno].raw + args[ap->argno].raw_length,
7917 args[ap->argno].expanded = obuf.buf;
7918 args[ap->argno].expand_length = obuf.length;
7919 args[ap->argno].free2 = obuf.buf;
7922 /* Add 4 for two newline-space markers to prevent
7923 token concatenation. */
7924 xbuf_len += args[ap->argno].expand_length + 4;
7926 if (args[ap->argno].use_count < 10)
7927 args[ap->argno].use_count++;
7930 xbuf = (U_CHAR *) xmalloc (xbuf_len + 1);
7932 /* Generate in XBUF the complete expansion
7933 with arguments substituted in.
7934 TOTLEN is the total size generated so far.
7935 OFFSET is the index in the definition
7936 of where we are copying from. */
7937 offset = totlen = 0;
7938 for (last_ap = NULL, ap = defn->pattern; ap != NULL;
7939 last_ap = ap, ap = ap->next) {
7940 register struct argdata *arg = &args[ap->argno];
7941 int count_before = totlen;
7943 /* Add chars to XBUF. */
7944 for (i = 0; i < ap->nchars; i++, offset++)
7945 xbuf[totlen++] = exp[offset];
7947 /* If followed by an empty rest arg with concatenation,
7948 delete the last run of nonwhite chars. */
7949 if (rest_zero && totlen > count_before
7950 && ((ap->rest_args && ap->raw_before)
7951 || (last_ap != NULL && last_ap->rest_args
7952 && last_ap->raw_after))) {
7953 /* Delete final whitespace. */
7954 while (totlen > count_before && is_space[xbuf[totlen - 1]]) {
7958 /* Delete the nonwhites before them. */
7959 while (totlen > count_before && ! is_space[xbuf[totlen - 1]]) {
7964 if (ap->stringify != 0) {
7965 int arglen = arg->raw_length;
7971 && (c = arg->raw[i], is_space[c]))
7974 && (c = arg->raw[arglen - 1], is_space[c]))
7977 xbuf[totlen++] = '\"'; /* insert beginning quote */
7978 for (; i < arglen; i++) {
7981 /* Special markers Newline Space
7982 generate nothing for a stringified argument. */
7983 if (c == '\n' && arg->raw[i+1] != '\n') {
7988 /* Internal sequences of whitespace are replaced by one space
7989 except within an string or char token. */
7991 && (c == '\n' ? arg->raw[i+1] == '\n' : is_space[c])) {
7993 /* Note that Newline Space does occur within whitespace
7994 sequences; consider it part of the sequence. */
7995 if (c == '\n' && is_space[arg->raw[i+1]])
7997 else if (c != '\n' && is_space[c])
8014 } else if (c == '\"' || c == '\'')
8018 /* Escape these chars */
8019 if (c == '\"' || (in_string && c == '\\'))
8020 xbuf[totlen++] = '\\';
8024 sprintf ((char *) &xbuf[totlen], "\\%03o", (unsigned int) c);
8029 xbuf[totlen++] = '\"'; /* insert ending quote */
8030 } else if (ap->raw_before || ap->raw_after || traditional) {
8031 U_CHAR *p1 = arg->raw;
8032 U_CHAR *l1 = p1 + arg->raw_length;
8033 if (ap->raw_before) {
8034 while (p1 != l1 && is_space[*p1]) p1++;
8035 while (p1 != l1 && is_idchar[*p1])
8036 xbuf[totlen++] = *p1++;
8037 /* Delete any no-reexpansion marker that follows
8038 an identifier at the beginning of the argument
8039 if the argument is concatenated with what precedes it. */
8040 if (p1[0] == '\n' && p1[1] == '-')
8042 } else if (!traditional) {
8043 /* Ordinary expanded use of the argument.
8044 Put in newline-space markers to prevent token pasting. */
8045 xbuf[totlen++] = '\n';
8046 xbuf[totlen++] = ' ';
8048 if (ap->raw_after) {
8049 /* Arg is concatenated after: delete trailing whitespace,
8050 whitespace markers, and no-reexpansion markers. */
8052 if (is_space[l1[-1]]) l1--;
8053 else if (l1[-1] == '-') {
8054 U_CHAR *p2 = l1 - 1;
8055 /* If a `-' is preceded by an odd number of newlines then it
8056 and the last newline are a no-reexpansion marker. */
8057 while (p2 != p1 && p2[-1] == '\n') p2--;
8058 if ((l1 - 1 - p2) & 1) {
8067 bcopy ((char *) p1, (char *) (xbuf + totlen), l1 - p1);
8069 if (!traditional && !ap->raw_after) {
8070 /* Ordinary expanded use of the argument.
8071 Put in newline-space markers to prevent token pasting. */
8072 xbuf[totlen++] = '\n';
8073 xbuf[totlen++] = ' ';
8076 /* Ordinary expanded use of the argument.
8077 Put in newline-space markers to prevent token pasting. */
8079 xbuf[totlen++] = '\n';
8080 xbuf[totlen++] = ' ';
8082 bcopy ((char *) arg->expanded, (char *) (xbuf + totlen),
8083 arg->expand_length);
8084 totlen += arg->expand_length;
8086 xbuf[totlen++] = '\n';
8087 xbuf[totlen++] = ' ';
8089 /* If a macro argument with newlines is used multiple times,
8090 then only expand the newlines once. This avoids creating output
8091 lines which don't correspond to any input line, which confuses
8093 if (arg->use_count > 1 && arg->newlines > 0) {
8094 /* Don't bother doing change_newlines for subsequent
8098 = change_newlines (arg->expanded, arg->expand_length);
8102 if (totlen > xbuf_len)
8106 /* if there is anything left of the definition
8107 after handling the arg list, copy that in too. */
8109 for (i = offset; i < defn->length; i++) {
8110 /* if we've reached the end of the macro */
8113 if (! (rest_zero && last_ap != NULL && last_ap->rest_args
8114 && last_ap->raw_after))
8115 xbuf[totlen++] = exp[i];
8121 for (i = 0; i < nargs; i++) {
8122 if (args[i].free1 != 0)
8123 free (args[i].free1);
8124 if (args[i].free2 != 0)
8125 free (args[i].free2);
8129 xbuf = defn->expansion;
8130 xbuf_len = defn->length;
8133 /* Now put the expansion on the input stack
8134 so our caller will commence reading from it. */
8136 register FILE_BUF *ip2;
8138 ip2 = &instack[++indepth];
8141 ip2->nominal_fname = 0;
8142 /* This may not be exactly correct, but will give much better error
8143 messages for nested macro calls than using a line number of zero. */
8144 ip2->lineno = start_line;
8146 ip2->length = xbuf_len;
8148 ip2->free_ptr = (nargs > 0) ? xbuf : 0;
8150 ip2->if_stack = if_stack;
8151 ip2->system_header_p = 0;
8153 /* Recursive macro use sometimes works traditionally.
8154 #define foo(x,y) bar (x (y,0), y)
8158 hp->type = T_DISABLED;
8163 * Parse a macro argument and store the info on it into *ARGPTR.
8164 * REST_ARGS is passed to macarg1 to make it absorb the rest of the args.
8165 * Return nonzero to indicate a syntax error.
8169 macarg (argptr, rest_args)
8170 register struct argdata *argptr;
8173 FILE_BUF *ip = &instack[indepth];
8178 /* Try to parse as much of the argument as exists at this
8179 input stack level. */
8180 U_CHAR *bp = macarg1 (ip->bufp, ip->buf + ip->length,
8181 &paren, &newlines, &comments, rest_args);
8183 /* If we find the end of the argument at this level,
8184 set up *ARGPTR to point at it in the input stack. */
8185 if (!(ip->fname != 0 && (newlines != 0 || comments != 0))
8186 && bp != ip->buf + ip->length) {
8188 argptr->raw = ip->bufp;
8189 argptr->raw_length = bp - ip->bufp;
8190 argptr->newlines = newlines;
8194 /* This input stack level ends before the macro argument does.
8195 We must pop levels and keep parsing.
8196 Therefore, we must allocate a temporary buffer and copy
8197 the macro argument into it. */
8198 int bufsize = bp - ip->bufp;
8199 int extra = newlines;
8200 U_CHAR *buffer = (U_CHAR *) xmalloc (bufsize + extra + 1);
8201 int final_start = 0;
8203 bcopy ((char *) ip->bufp, (char *) buffer, bufsize);
8205 ip->lineno += newlines;
8207 while (bp == ip->buf + ip->length) {
8208 if (instack[indepth].macro == 0) {
8210 return "unterminated macro call";
8212 ip->macro->type = T_MACRO;
8214 free (ip->free_ptr);
8215 ip = &instack[--indepth];
8218 bp = macarg1 (ip->bufp, ip->buf + ip->length, &paren,
8219 &newlines, &comments, rest_args);
8220 final_start = bufsize;
8221 bufsize += bp - ip->bufp;
8223 buffer = (U_CHAR *) xrealloc (buffer, bufsize + extra + 1);
8224 bcopy ((char *) ip->bufp, (char *) (buffer + bufsize - (bp - ip->bufp)),
8227 ip->lineno += newlines;
8230 /* Now, if arg is actually wanted, record its raw form,
8231 discarding comments and duplicating newlines in whatever
8232 part of it did not come from a macro expansion.
8233 EXTRA space has been preallocated for duplicating the newlines.
8234 FINAL_START is the index of the start of that part. */
8236 argptr->raw = buffer;
8237 argptr->raw_length = bufsize;
8238 argptr->free1 = buffer;
8239 argptr->newlines = newlines;
8240 argptr->comments = comments;
8241 if ((newlines || comments) && ip->fname != 0)
8244 discard_comments (argptr->raw + final_start,
8245 argptr->raw_length - final_start,
8247 argptr->raw[argptr->raw_length] = 0;
8248 if (argptr->raw_length > bufsize + extra)
8253 /* If we are not discarding this argument,
8254 macroexpand it and compute its length as stringified.
8255 All this info goes into *ARGPTR. */
8258 register U_CHAR *buf, *lim;
8259 register int totlen;
8262 lim = buf + argptr->raw_length;
8264 while (buf != lim && is_space[*buf])
8266 while (buf != lim && is_space[lim[-1]])
8268 totlen = traditional ? 0 : 2; /* Count opening and closing quote. */
8269 while (buf != lim) {
8270 register U_CHAR c = *buf++;
8272 /* Internal sequences of whitespace are replaced by one space
8273 in most cases, but not always. So count all the whitespace
8274 in case we need to keep it all. */
8277 SKIP_ALL_WHITE_SPACE (buf);
8280 if (c == '\"' || c == '\\') /* escape these chars */
8282 else if (!isprint (c))
8285 argptr->stringified_length = totlen;
8290 /* Scan text from START (inclusive) up to LIMIT (exclusive),
8291 counting parens in *DEPTHPTR,
8292 and return if reach LIMIT
8293 or before a `)' that would make *DEPTHPTR negative
8294 or before a comma when *DEPTHPTR is zero.
8295 Single and double quotes are matched and termination
8296 is inhibited within them. Comments also inhibit it.
8297 Value returned is pointer to stopping place.
8299 Increment *NEWLINES each time a newline is passed.
8300 REST_ARGS notifies macarg1 that it should absorb the rest of the args.
8301 Set *COMMENTS to 1 if a comment is seen. */
8304 macarg1 (start, limit, depthptr, newlines, comments, rest_args)
8306 register U_CHAR *limit;
8307 int *depthptr, *newlines, *comments;
8310 register U_CHAR *bp = start;
8312 while (bp < limit) {
8318 if (--(*depthptr) < 0)
8322 /* Traditionally, backslash makes following char not special. */
8323 if (bp + 1 < limit && traditional)
8326 /* But count source lines anyway. */
8335 if (bp[1] == '\\' && bp[2] == '\n')
8336 newline_fix (bp + 1);
8337 if (cplusplus_comments && bp[1] == '/') {
8340 while (bp < limit && (*bp != '\n' || bp[-1] == '\\')) {
8341 if (*bp == '\n') ++*newlines;
8344 /* Now count the newline that we are about to skip. */
8348 if (bp[1] != '*' || bp + 1 >= limit)
8352 while (bp + 1 < limit) {
8354 && bp[1] == '\\' && bp[2] == '\n')
8355 newline_fix (bp + 1);
8356 if (bp[0] == '*' && bp[1] == '/')
8358 if (*bp == '\n') ++*newlines;
8366 for (quotec = *bp++; bp + 1 < limit && *bp != quotec; bp++) {
8371 while (*bp == '\\' && bp[1] == '\n') {
8374 } else if (*bp == '\n') {
8383 /* if we've returned to lowest level and we aren't absorbing all args */
8384 if ((*depthptr) == 0 && rest_args == 0)
8394 /* Discard comments and duplicate newlines
8395 in the string of length LENGTH at START,
8396 except inside of string constants.
8397 The string is copied into itself with its beginning staying fixed.
8399 NEWLINES is the number of newlines that must be duplicated.
8400 We assume that that much extra space is available past the end
8404 discard_comments (start, length, newlines)
8409 register U_CHAR *ibp;
8410 register U_CHAR *obp;
8411 register U_CHAR *limit;
8414 /* If we have newlines to duplicate, copy everything
8415 that many characters up. Then, in the second part,
8416 we will have room to insert the newlines
8418 NEWLINES may actually be too large, because it counts
8419 newlines in string constants, and we don't duplicate those.
8420 But that does no harm. */
8422 ibp = start + length;
8423 obp = ibp + newlines;
8425 while (limit != ibp)
8429 ibp = start + newlines;
8430 limit = start + length + newlines;
8433 while (ibp < limit) {
8434 *obp++ = c = *ibp++;
8437 /* Duplicate the newline. */
8449 if (*ibp == '\\' && ibp[1] == '\n')
8451 /* Delete any comment. */
8452 if (cplusplus_comments && ibp[0] == '/') {
8453 /* Comments are equivalent to spaces. */
8456 while (ibp < limit && (*ibp != '\n' || ibp[-1] == '\\'))
8460 if (ibp[0] != '*' || ibp + 1 >= limit)
8462 /* Comments are equivalent to spaces.
8463 For -traditional, a comment is equivalent to nothing. */
8469 while (ibp + 1 < limit) {
8471 && ibp[1] == '\\' && ibp[2] == '\n')
8472 newline_fix (ibp + 1);
8473 if (ibp[0] == '*' && ibp[1] == '/')
8482 /* Notice and skip strings, so that we don't
8483 think that comments start inside them,
8484 and so we don't duplicate newlines in them. */
8487 while (ibp < limit) {
8488 *obp++ = c = *ibp++;
8491 if (c == '\n' && quotec == '\'')
8493 if (c == '\\' && ibp < limit) {
8494 while (*ibp == '\\' && ibp[1] == '\n')
8507 /* Turn newlines to spaces in the string of length LENGTH at START,
8508 except inside of string constants.
8509 The string is copied into itself with its beginning staying fixed. */
8512 change_newlines (start, length)
8516 register U_CHAR *ibp;
8517 register U_CHAR *obp;
8518 register U_CHAR *limit;
8522 limit = start + length;
8525 while (ibp < limit) {
8526 *obp++ = c = *ibp++;
8529 /* If this is a NEWLINE NEWLINE, then this is a real newline in the
8530 string. Skip past the newline and its duplicate.
8531 Put a space in the output. */
8542 /* Notice and skip strings, so that we don't delete newlines in them. */
8545 while (ibp < limit) {
8546 *obp++ = c = *ibp++;
8549 if (c == '\n' && quotec == '\'')
8561 * my_strerror - return the descriptive text associated with an `errno' code.
8565 my_strerror (errnum)
8571 #ifndef HAVE_STRERROR
8572 result = (char *) ((errnum < sys_nerr) ? sys_errlist[errnum] : 0);
8574 result = strerror (errnum);
8577 /* VAXCRTL's strerror() takes an optional second argument, which only
8578 matters when the first argument is EVMSERR. However, it's simplest
8579 just to pass it unconditionally. `vaxc$errno' is declared in
8580 <errno.h>, and maintained by the library in parallel with `errno'.
8581 We assume that caller's `errnum' either matches the last setting of
8582 `errno' by the library or else does not have the value `EVMSERR'. */
8584 result = strerror (errnum, vaxc$errno);
8588 result = "undocumented I/O error";
8594 * error - print error message and increment count of errors.
8598 error (msg, arg1, arg2, arg3)
8600 char *arg1, *arg2, *arg3;
8603 FILE_BUF *ip = NULL;
8605 print_containing_files ();
8607 for (i = indepth; i >= 0; i--)
8608 if (instack[i].fname != NULL) {
8614 fprintf (stderr, "%s:%d: ", ip->nominal_fname, ip->lineno);
8615 fprintf (stderr, msg, arg1, arg2, arg3);
8616 fprintf (stderr, "\n");
8620 /* Error including a message from `errno'. */
8623 error_from_errno (name)
8627 FILE_BUF *ip = NULL;
8629 print_containing_files ();
8631 for (i = indepth; i >= 0; i--)
8632 if (instack[i].fname != NULL) {
8638 fprintf (stderr, "%s:%d: ", ip->nominal_fname, ip->lineno);
8640 fprintf (stderr, "%s: %s\n", name, my_strerror (errno));
8645 /* Print error message but don't count it. */
8648 warning (msg, arg1, arg2, arg3)
8650 char *arg1, *arg2, *arg3;
8653 FILE_BUF *ip = NULL;
8655 if (inhibit_warnings)
8658 if (warnings_are_errors)
8661 print_containing_files ();
8663 for (i = indepth; i >= 0; i--)
8664 if (instack[i].fname != NULL) {
8670 fprintf (stderr, "%s:%d: ", ip->nominal_fname, ip->lineno);
8671 fprintf (stderr, "warning: ");
8672 fprintf (stderr, msg, arg1, arg2, arg3);
8673 fprintf (stderr, "\n");
8677 error_with_line (line, msg, arg1, arg2, arg3)
8680 char *arg1, *arg2, *arg3;
8683 FILE_BUF *ip = NULL;
8685 print_containing_files ();
8687 for (i = indepth; i >= 0; i--)
8688 if (instack[i].fname != NULL) {
8694 fprintf (stderr, "%s:%d: ", ip->nominal_fname, line);
8695 fprintf (stderr, msg, arg1, arg2, arg3);
8696 fprintf (stderr, "\n");
8701 warning_with_line (line, msg, arg1, arg2, arg3)
8704 char *arg1, *arg2, *arg3;
8707 FILE_BUF *ip = NULL;
8709 if (inhibit_warnings)
8712 if (warnings_are_errors)
8715 print_containing_files ();
8717 for (i = indepth; i >= 0; i--)
8718 if (instack[i].fname != NULL) {
8724 fprintf (stderr, "%s:%d: ", ip->nominal_fname, line);
8725 fprintf (stderr, "warning: ");
8726 fprintf (stderr, msg, arg1, arg2, arg3);
8727 fprintf (stderr, "\n");
8730 /* print an error message and maybe count it. */
8733 pedwarn (msg, arg1, arg2, arg3)
8735 char *arg1, *arg2, *arg3;
8737 if (pedantic_errors)
8738 error (msg, arg1, arg2, arg3);
8740 warning (msg, arg1, arg2, arg3);
8744 pedwarn_with_line (line, msg, arg1, arg2, arg3)
8747 char *arg1, *arg2, *arg3;
8749 if (pedantic_errors)
8750 error_with_line (line, msg, arg1, arg2, arg3);
8752 warning_with_line (line, msg, arg1, arg2, arg3);
8755 /* Report a warning (or an error if pedantic_errors)
8756 giving specified file name and line number, not current. */
8759 pedwarn_with_file_and_line (file, line, msg, arg1, arg2, arg3)
8763 char *arg1, *arg2, *arg3;
8765 if (!pedantic_errors && inhibit_warnings)
8768 fprintf (stderr, "%s:%d: ", file, line);
8769 if (pedantic_errors)
8771 if (!pedantic_errors)
8772 fprintf (stderr, "warning: ");
8773 fprintf (stderr, msg, arg1, arg2, arg3);
8774 fprintf (stderr, "\n");
8777 /* Print the file names and line numbers of the #include
8778 commands which led to the current file. */
8781 print_containing_files ()
8783 FILE_BUF *ip = NULL;
8787 /* If stack of files hasn't changed since we last printed
8788 this info, don't repeat it. */
8789 if (last_error_tick == input_file_stack_tick)
8792 for (i = indepth; i >= 0; i--)
8793 if (instack[i].fname != NULL) {
8798 /* Give up if we don't find a source file. */
8802 /* Find the other, outer source files. */
8803 for (i--; i >= 0; i--)
8804 if (instack[i].fname != NULL) {
8808 fprintf (stderr, "In file included");
8810 fprintf (stderr, ",\n ");
8813 fprintf (stderr, " from %s:%d", ip->nominal_fname, ip->lineno);
8816 fprintf (stderr, ":\n");
8818 /* Record we have printed the status as of this time. */
8819 last_error_tick = input_file_stack_tick;
8822 /* Return the line at which an error occurred.
8823 The error is not necessarily associated with the current spot
8824 in the input stack, so LINE says where. LINE will have been
8825 copied from ip->lineno for the current input level.
8826 If the current level is for a file, we return LINE.
8827 But if the current level is not for a file, LINE is meaningless.
8828 In that case, we return the lineno of the innermost file. */
8831 line_for_error (line)
8837 for (i = indepth; i >= 0; ) {
8838 if (instack[i].fname != 0)
8843 line1 = instack[i].lineno;
8851 * If OBUF doesn't have NEEDED bytes after OPTR, make it bigger.
8853 * As things stand, nothing is ever placed in the output buffer to be
8854 * removed again except when it's KNOWN to be part of an identifier,
8855 * so flushing and moving down everything left, instead of expanding,
8859 /* You might think void was cleaner for the return type,
8860 but that would get type mismatch in check_expand in strict ANSI. */
8862 grow_outbuf (obuf, needed)
8863 register FILE_BUF *obuf;
8864 register int needed;
8869 if (obuf->length - (obuf->bufp - obuf->buf) > needed)
8872 /* Make it at least twice as big as it is now. */
8874 /* Make it have at least 150% of the free space we will need. */
8875 minsize = (3 * needed) / 2 + (obuf->bufp - obuf->buf);
8876 if (minsize > obuf->length)
8877 obuf->length = minsize;
8879 if ((p = (U_CHAR *) xrealloc (obuf->buf, obuf->length)) == NULL)
8882 obuf->bufp = p + (obuf->bufp - obuf->buf);
8888 /* Symbol table for macro names and special symbols */
8891 * install a name in the main hash table, even if it is already there.
8892 * name stops with first non alphanumeric, except leading '#'.
8893 * caller must check against redefinition if that is desired.
8894 * delete_macro () removes things installed by install () in fifo order.
8895 * this is important because of the `defined' special symbol used
8896 * in #if, and also if pushdef/popdef directives are ever implemented.
8898 * If LEN is >= 0, it is the length of the name.
8899 * Otherwise, compute the length by scanning the entire name.
8901 * If HASH is >= 0, it is the precomputed hash code.
8902 * Otherwise, compute the hash code.
8905 install (name, len, type, ivalue, value, hash)
8908 enum node_type type;
8913 register HASHNODE *hp;
8914 register int i, bucket;
8915 register U_CHAR *p, *q;
8919 while (is_idchar[*p])
8925 hash = hashf (name, len, HASHSIZE);
8927 i = sizeof (HASHNODE) + len + 1;
8928 hp = (HASHNODE *) xmalloc (i);
8930 hp->bucket_hdr = &hashtab[bucket];
8931 hp->next = hashtab[bucket];
8932 hashtab[bucket] = hp;
8934 if (hp->next != NULL)
8935 hp->next->prev = hp;
8938 if (hp->type == T_CONST)
8939 hp->value.ival = ivalue;
8941 hp->value.cpval = value;
8942 hp->name = ((U_CHAR *) hp) + sizeof (HASHNODE);
8945 for (i = 0; i < len; i++)
8952 * find the most recent hash node for name name (ending with first
8953 * non-identifier char) installed by install
8955 * If LEN is >= 0, it is the length of the name.
8956 * Otherwise, compute the length by scanning the entire name.
8958 * If HASH is >= 0, it is the precomputed hash code.
8959 * Otherwise, compute the hash code.
8962 lookup (name, len, hash)
8967 register U_CHAR *bp;
8968 register HASHNODE *bucket;
8971 for (bp = name; is_idchar[*bp]; bp++) ;
8976 hash = hashf (name, len, HASHSIZE);
8978 bucket = hashtab[hash];
8980 if (bucket->length == len && strncmp (bucket->name, name, len) == 0)
8982 bucket = bucket->next;
8988 * Delete a hash node. Some weirdness to free junk from macros.
8989 * More such weirdness will have to be added if you define more hash
8990 * types that need it.
8993 /* Note that the DEFINITION of a macro is removed from the hash table
8994 but its storage is not freed. This would be a storage leak
8995 except that it is not reasonable to keep undefining and redefining
8996 large numbers of macros many times.
8997 In any case, this is necessary, because a macro can be #undef'd
8998 in the middle of reading the arguments to a call to it.
8999 If #undef freed the DEFINITION, that would crash. */
9006 if (hp->prev != NULL)
9007 hp->prev->next = hp->next;
9008 if (hp->next != NULL)
9009 hp->next->prev = hp->prev;
9011 /* make sure that the bucket chain header that
9012 the deleted guy was on points to the right thing afterwards. */
9013 if (hp == *hp->bucket_hdr)
9014 *hp->bucket_hdr = hp->next;
9017 if (hp->type == T_MACRO) {
9018 DEFINITION *d = hp->value.defn;
9019 struct reflist *ap, *nextap;
9021 for (ap = d->pattern; ap != NULL; ap = nextap) {
9032 * return hash function on name. must be compatible with the one
9033 * computed a step at a time, elsewhere
9036 hashf (name, len, hashsize)
9037 register U_CHAR *name;
9044 r = HASHSTEP (r, *name++);
9046 return MAKE_POS (r) % hashsize;
9050 /* Dump the definition of a single macro HP to OF. */
9052 dump_single_macro (hp, of)
9053 register HASHNODE *hp;
9056 register DEFINITION *defn = hp->value.defn;
9062 /* Print the definition of the macro HP. */
9064 fprintf (of, "#define %s", hp->name);
9066 if (defn->nargs >= 0) {
9070 for (i = 0; i < defn->nargs; i++) {
9071 dump_arg_n (defn, i, of);
9072 if (i + 1 < defn->nargs)
9082 for (ap = defn->pattern; ap != NULL; ap = ap->next) {
9083 dump_defn_1 (defn->expansion, offset, ap->nchars, of);
9084 offset += ap->nchars;
9086 if (ap->nchars != 0)
9090 if (ap->raw_before && !concat)
9091 fprintf (of, " ## ");
9094 dump_arg_n (defn, ap->argno, of);
9095 if (!traditional && ap->raw_after) {
9096 fprintf (of, " ## ");
9100 dump_defn_1 (defn->expansion, offset, defn->length - offset, of);
9104 /* Dump all macro definitions as #defines to stdout. */
9111 for (bucket = 0; bucket < HASHSIZE; bucket++) {
9112 register HASHNODE *hp;
9114 for (hp = hashtab[bucket]; hp; hp= hp->next) {
9115 if (hp->type == T_MACRO)
9116 dump_single_macro (hp, stdout);
9121 /* Output to OF a substring of a macro definition.
9122 BASE is the beginning of the definition.
9123 Output characters START thru LENGTH.
9124 Unless traditional, discard newlines outside of strings, thus
9125 converting funny-space markers to ordinary spaces. */
9128 dump_defn_1 (base, start, length, of)
9134 U_CHAR *p = base + start;
9135 U_CHAR *limit = base + start + length;
9138 fwrite (p, sizeof (*p), length, of);
9141 if (*p == '\"' || *p =='\'') {
9142 U_CHAR *p1 = skip_quoted_string (p, limit, 0, NULL_PTR,
9143 NULL_PTR, NULL_PTR);
9144 fwrite (p, sizeof (*p), p1 - p, of);
9155 /* Print the name of argument number ARGNUM of macro definition DEFN
9157 Recall that DEFN->args.argnames contains all the arg names
9158 concatenated in reverse order with comma-space in between. */
9161 dump_arg_n (defn, argnum, of)
9166 register U_CHAR *p = defn->args.argnames;
9167 while (argnum + 1 < defn->nargs) {
9168 p = (U_CHAR *) index (p, ' ') + 1;
9172 while (*p && *p != ',') {
9178 /* Initialize syntactic classifications of characters. */
9181 initialize_char_syntax ()
9186 * Set up is_idchar and is_idstart tables. These should be
9187 * faster than saying (is_alpha (c) || c == '_'), etc.
9188 * Set up these things before calling any routines tthat
9191 for (i = 'a'; i <= 'z'; i++) {
9192 is_idchar[i - 'a' + 'A'] = 1;
9194 is_idstart[i - 'a' + 'A'] = 1;
9197 for (i = '0'; i <= '9'; i++)
9200 is_idstart['_'] = 1;
9201 is_idchar['$'] = dollars_in_ident;
9202 is_idstart['$'] = dollars_in_ident;
9204 /* horizontal space table */
9205 is_hor_space[' '] = 1;
9206 is_hor_space['\t'] = 1;
9207 is_hor_space['\v'] = 1;
9208 is_hor_space['\f'] = 1;
9209 is_hor_space['\r'] = 1;
9218 char_name['\v'] = "vertical tab";
9219 char_name['\f'] = "formfeed";
9220 char_name['\r'] = "carriage return";
9223 /* Initialize the built-in macros. */
9226 initialize_builtins (inp, outp)
9230 install ("__LINE__", -1, T_SPECLINE, 0, NULL_PTR, -1);
9231 install ("__DATE__", -1, T_DATE, 0, NULL_PTR, -1);
9232 install ("__FILE__", -1, T_FILE, 0, NULL_PTR, -1);
9233 install ("__BASE_FILE__", -1, T_BASE_FILE, 0, NULL_PTR, -1);
9234 install ("__INCLUDE_LEVEL__", -1, T_INCLUDE_LEVEL, 0, NULL_PTR, -1);
9235 install ("__VERSION__", -1, T_VERSION, 0, NULL_PTR, -1);
9236 #ifndef NO_BUILTIN_SIZE_TYPE
9237 install ("__SIZE_TYPE__", -1, T_SIZE_TYPE, 0, NULL_PTR, -1);
9239 #ifndef NO_BUILTIN_PTRDIFF_TYPE
9240 install ("__PTRDIFF_TYPE__ ", -1, T_PTRDIFF_TYPE, 0, NULL_PTR, -1);
9242 install ("__WCHAR_TYPE__", -1, T_WCHAR_TYPE, 0, NULL_PTR, -1);
9243 install ("__USER_LABEL_PREFIX__",-1,T_USER_LABEL_PREFIX_TYPE,0,NULL_PTR, -1);
9244 install ("__REGISTER_PREFIX__", -1, T_REGISTER_PREFIX_TYPE, 0, NULL_PTR, -1);
9245 install ("__TIME__", -1, T_TIME, 0, NULL_PTR, -1);
9247 install ("__STDC__", -1, T_CONST, STDC_VALUE, NULL_PTR, -1);
9249 install ("__OBJC__", -1, T_CONST, 1, NULL_PTR, -1);
9250 /* This is supplied using a -D by the compiler driver
9251 so that it is present only when truly compiling with GNU C. */
9252 /* install ("__GNUC__", -1, T_CONST, 2, NULL_PTR, -1); */
9256 char directive[2048];
9257 register struct directive *dp = &directive_table[0];
9258 struct tm *timebuf = timestamp ();
9260 sprintf (directive, " __BASE_FILE__ \"%s\"\n",
9261 instack[0].nominal_fname);
9262 output_line_command (inp, outp, 0, same_file);
9263 pass_thru_directive (directive, &directive[strlen (directive)], outp, dp);
9265 sprintf (directive, " __VERSION__ \"%s\"\n", version_string);
9266 output_line_command (inp, outp, 0, same_file);
9267 pass_thru_directive (directive, &directive[strlen (directive)], outp, dp);
9269 #ifndef NO_BUILTIN_SIZE_TYPE
9270 sprintf (directive, " __SIZE_TYPE__ %s\n", SIZE_TYPE);
9271 output_line_command (inp, outp, 0, same_file);
9272 pass_thru_directive (directive, &directive[strlen (directive)], outp, dp);
9275 #ifndef NO_BUILTIN_PTRDIFF_TYPE
9276 sprintf (directive, " __PTRDIFF_TYPE__ %s\n", PTRDIFF_TYPE);
9277 output_line_command (inp, outp, 0, same_file);
9278 pass_thru_directive (directive, &directive[strlen (directive)], outp, dp);
9281 sprintf (directive, " __WCHAR_TYPE__ %s\n", wchar_type);
9282 output_line_command (inp, outp, 0, same_file);
9283 pass_thru_directive (directive, &directive[strlen (directive)], outp, dp);
9285 sprintf (directive, " __DATE__ \"%s %2d %4d\"\n",
9286 monthnames[timebuf->tm_mon],
9287 timebuf->tm_mday, timebuf->tm_year + 1900);
9288 output_line_command (inp, outp, 0, same_file);
9289 pass_thru_directive (directive, &directive[strlen (directive)], outp, dp);
9291 sprintf (directive, " __TIME__ \"%02d:%02d:%02d\"\n",
9292 timebuf->tm_hour, timebuf->tm_min, timebuf->tm_sec);
9293 output_line_command (inp, outp, 0, same_file);
9294 pass_thru_directive (directive, &directive[strlen (directive)], outp, dp);
9298 sprintf (directive, " __STDC__ 1");
9299 output_line_command (inp, outp, 0, same_file);
9300 pass_thru_directive (directive, &directive[strlen (directive)],
9305 sprintf (directive, " __OBJC__ 1");
9306 output_line_command (inp, outp, 0, same_file);
9307 pass_thru_directive (directive, &directive[strlen (directive)],
9314 * process a given definition string, for initialization
9315 * If STR is just an identifier, define it with value 1.
9316 * If STR has anything after the identifier, then it should
9317 * be identifier=definition.
9321 make_definition (str, op)
9326 struct directive *kt;
9331 if (!is_idstart[*p]) {
9332 error ("malformed option `-D %s'", str);
9335 while (is_idchar[*++p])
9338 while (is_idchar[*++p] || *p == ',' || is_hor_space[*p])
9341 p = str; /* Error */
9344 buf = (U_CHAR *) alloca (p - buf + 4);
9345 strcpy ((char *)buf, str);
9346 strcat ((char *)buf, " 1");
9347 } else if (*p != '=') {
9348 error ("malformed option `-D %s'", str);
9352 /* Copy the entire option so we can modify it. */
9353 buf = (U_CHAR *) alloca (2 * strlen (str) + 1);
9354 strncpy (buf, str, p - str);
9355 /* Change the = to a space. */
9357 /* Scan for any backslash-newline and remove it. */
9361 if (*p == '\"' || *p == '\'') {
9362 int unterminated = 0;
9363 U_CHAR *p1 = skip_quoted_string (p, p + strlen (p), 0,
9364 NULL_PTR, NULL_PTR, &unterminated);
9368 if (*p == '\\' && p[1] == '\n')
9372 } else if (*p == '\\' && p[1] == '\n')
9374 /* Change newline chars into newline-markers. */
9375 else if (*p == '\n')
9387 ip = &instack[++indepth];
9388 ip->nominal_fname = ip->fname = "*Initialization*";
9390 ip->buf = ip->bufp = buf;
9391 ip->length = strlen (buf);
9395 ip->if_stack = if_stack;
9396 ip->system_header_p = 0;
9398 for (kt = directive_table; kt->type != T_DEFINE; kt++)
9401 /* Pass NULL instead of OP, since this is a "predefined" macro. */
9402 do_define (buf, buf + strlen (buf), NULL_PTR, kt);
9406 /* JF, this does the work for the -U option */
9409 make_undef (str, op)
9414 struct directive *kt;
9416 ip = &instack[++indepth];
9417 ip->nominal_fname = ip->fname = "*undef*";
9419 ip->buf = ip->bufp = str;
9420 ip->length = strlen (str);
9424 ip->if_stack = if_stack;
9425 ip->system_header_p = 0;
9427 for (kt = directive_table; kt->type != T_UNDEF; kt++)
9430 do_undef (str, str + strlen (str), op, kt);
9434 /* Process the string STR as if it appeared as the body of a #assert.
9435 OPTION is the option name for which STR was the argument. */
9438 make_assertion (option, str)
9443 struct directive *kt;
9444 U_CHAR *buf, *p, *q;
9446 /* Copy the entire option so we can modify it. */
9447 buf = (U_CHAR *) alloca (strlen (str) + 1);
9448 strcpy ((char *) buf, str);
9449 /* Scan for any backslash-newline and remove it. */
9452 if (*p == '\\' && p[1] == '\n')
9460 if (!is_idstart[*p]) {
9461 error ("malformed option `%s %s'", option, str);
9464 while (is_idchar[*++p])
9466 SKIP_WHITE_SPACE (p);
9467 if (! (*p == 0 || *p == '(')) {
9468 error ("malformed option `%s %s'", option, str);
9472 ip = &instack[++indepth];
9473 ip->nominal_fname = ip->fname = "*Initialization*";
9475 ip->buf = ip->bufp = buf;
9476 ip->length = strlen (buf);
9480 ip->if_stack = if_stack;
9481 ip->system_header_p = 0;
9483 for (kt = directive_table; kt->type != T_ASSERT; kt++)
9486 /* pass NULL as output ptr to do_define since we KNOW it never
9487 does any output.... */
9488 do_assert (buf, buf + strlen (buf) , NULL_PTR, kt);
9492 /* Append a chain of `struct file_name_list's
9493 to the end of the main include chain.
9494 FIRST is the beginning of the chain to append, and LAST is the end. */
9497 append_include_chain (first, last)
9498 struct file_name_list *first, *last;
9500 struct file_name_list *dir;
9502 if (!first || !last)
9508 last_include->next = first;
9510 if (first_bracket_include == 0)
9511 first_bracket_include = first;
9513 for (dir = first; ; dir = dir->next) {
9514 int len = strlen (dir->fname) + INCLUDE_LEN_FUDGE;
9515 if (len > max_include_len)
9516 max_include_len = len;
9522 last_include = last;
9525 /* Add output to `deps_buffer' for the -M switch.
9526 STRING points to the text to be output.
9527 SPACER is ':' for targets, ' ' for dependencies, zero for text
9528 to be inserted literally. */
9531 deps_output (string, spacer)
9535 int size = strlen (string);
9540 #ifndef MAX_OUTPUT_COLUMNS
9541 #define MAX_OUTPUT_COLUMNS 72
9545 && (deps_column + size) > MAX_OUTPUT_COLUMNS)
9547 deps_output (" \\\n ", 0);
9551 if (deps_size + size + 8 > deps_allocated_size) {
9552 deps_allocated_size = (deps_size + size + 50) * 2;
9553 deps_buffer = (char *) xrealloc (deps_buffer, deps_allocated_size);
9555 if (spacer == ' ' && deps_column > 0)
9556 deps_buffer[deps_size++] = ' ';
9557 bcopy (string, &deps_buffer[deps_size], size);
9559 deps_column += size;
9561 deps_buffer[deps_size++] = ':';
9562 deps_buffer[deps_size] = 0;
9565 #if defined(USG) || defined(VMS)
9571 register unsigned length;
9573 while (length-- > 0)
9578 bcopy (b1, b2, length)
9581 register unsigned length;
9583 while (length-- > 0)
9588 bcmp (b1, b2, length) /* This could be a macro! */
9591 register unsigned length;
9593 while (length-- > 0)
9599 #endif /* not BSTRING */
9600 #endif /* USG or VMS */
9607 fprintf (stderr, "%s: ", progname);
9608 fprintf (stderr, str, arg);
9609 fprintf (stderr, "\n");
9610 exit (FAILURE_EXIT_CODE);
9613 /* More 'friendly' abort that prints the line and file.
9614 config.h can #define abort fancy_abort if you like that sort of thing. */
9619 fatal ("Internal gcc abort.");
9623 perror_with_name (name)
9626 fprintf (stderr, "%s: ", progname);
9627 fprintf (stderr, "%s: %s\n", name, my_strerror (errno));
9632 pfatal_with_name (name)
9635 perror_with_name (name);
9639 exit (FAILURE_EXIT_CODE);
9643 /* Handler for SIGPIPE. */
9647 /* If this is missing, some compilers complain. */
9650 fatal ("output pipe has been closed");
9656 fatal ("Memory exhausted.");
9664 register char *ptr = (char *) malloc (size);
9665 if (ptr != 0) return (ptr);
9672 xrealloc (old, size)
9676 register char *ptr = (char *) realloc (old, size);
9677 if (ptr != 0) return (ptr);
9684 xcalloc (number, size)
9685 unsigned number, size;
9687 register unsigned total = number * size;
9688 register char *ptr = (char *) malloc (total);
9693 /* It's not too long, so loop, zeroing by longs.
9694 It must be safe because malloc values are always well aligned. */
9695 register long *zp = (long *) ptr;
9696 register long *zl = (long *) (ptr + total - 4);
9697 register int i = total - 4;
9716 unsigned size = strlen (input);
9717 char *output = xmalloc (size + 1);
9718 strcpy (output, input);
9722 /* Get the file-mode and data size of the file open on FD
9723 and store them in *MODE_POINTER and *SIZE_POINTER. */
9726 file_size_and_mode (fd, mode_pointer, size_pointer)
9729 long int *size_pointer;
9733 if (fstat (fd, &sbuf) < 0) return (-1);
9734 if (mode_pointer) *mode_pointer = sbuf.st_mode;
9735 if (size_pointer) *size_pointer = sbuf.st_size;
9740 output_dots (fd, depth)
9753 /* Under VMS we need to fix up the "include" specification
9754 filename so that everything following the 1st slash is
9755 changed into its correct VMS file specification. */
9758 hack_vms_include_specification (fname)
9761 register char *cp, *cp1, *cp2;
9762 int f, check_filename_before_returning, no_prefix_seen;
9765 check_filename_before_returning = 0;
9768 /* Ignore leading "./"s */
9769 while (fname[0] == '.' && fname[1] == '/') {
9770 strcpy (fname, fname+2);
9771 no_prefix_seen = 1; /* mark this for later */
9773 /* Look for the boundary between the VMS and UNIX filespecs */
9774 cp = rindex (fname, ']'); /* Look for end of dirspec. */
9775 if (cp == 0) cp = rindex (fname, '>'); /* ... Ditto */
9776 if (cp == 0) cp = rindex (fname, ':'); /* Look for end of devspec. */
9780 cp = index (fname, '/'); /* Look for the "/" */
9784 * Check if we have a vax-c style '#include filename'
9785 * and add the missing .h
9788 if (index(fname,'.') == 0)
9789 strcat(fname, ".h");
9791 if (index(cp,'.') == 0)
9795 cp2 = Local; /* initialize */
9797 /* We are trying to do a number of things here. First of all, we are
9798 trying to hammer the filenames into a standard format, such that later
9799 processing can handle them.
9801 If the file name contains something like [dir.], then it recognizes this
9802 as a root, and strips the ".]". Later processing will add whatever is
9803 needed to get things working properly.
9805 If no device is specified, then the first directory name is taken to be
9806 a device name (or a rooted logical). */
9808 /* See if we found that 1st slash */
9809 if (cp == 0) return; /* Nothing to do!!! */
9810 if (*cp != '/') return; /* Nothing to do!!! */
9811 /* Point to the UNIX filename part (which needs to be fixed!) */
9813 /* If the directory spec is not rooted, we can just copy
9814 the UNIX filename part and we are done */
9815 if (((cp - fname) > 1) && ((cp[-1] == ']') || (cp[-1] == '>'))) {
9816 if (cp[-2] != '.') {
9818 * The VMS part ends in a `]', and the preceding character is not a `.'.
9819 * We strip the `]', and then splice the two parts of the name in the
9820 * usual way. Given the default locations for include files in cccp.c,
9821 * we will only use this code if the user specifies alternate locations
9822 * with the /include (-I) switch on the command line. */
9823 cp -= 1; /* Strip "]" */
9824 cp1--; /* backspace */
9827 * The VMS part has a ".]" at the end, and this will not do. Later
9828 * processing will add a second directory spec, and this would be a syntax
9829 * error. Thus we strip the ".]", and thus merge the directory specs.
9830 * We also backspace cp1, so that it points to a '/'. This inhibits the
9831 * generation of the 000000 root directory spec (which does not belong here
9834 cp -= 2; /* Strip ".]" */
9835 cp1--; }; /* backspace */
9838 /* We drop in here if there is no VMS style directory specification yet.
9839 * If there is no device specification either, we make the first dir a
9840 * device and try that. If we do not do this, then we will be essentially
9841 * searching the users default directory (as if they did a #include "asdf.h").
9843 * Then all we need to do is to push a '[' into the output string. Later
9844 * processing will fill this in, and close the bracket.
9846 if (cp[-1] != ':') *cp2++ = ':'; /* dev not in spec. take first dir */
9847 *cp2++ = '['; /* Open the directory specification */
9850 /* at this point we assume that we have the device spec, and (at least
9851 the opening "[" for a directory specification. We may have directories
9852 specified already */
9854 /* If there are no other slashes then the filename will be
9855 in the "root" directory. Otherwise, we need to add
9856 directory specifications. */
9857 if (index (cp1, '/') == 0) {
9858 /* Just add "000000]" as the directory string */
9859 strcpy (cp2, "000000]");
9860 cp2 += strlen (cp2);
9861 check_filename_before_returning = 1; /* we might need to fool with this later */
9863 /* As long as there are still subdirectories to add, do them. */
9864 while (index (cp1, '/') != 0) {
9865 /* If this token is "." we can ignore it */
9866 if ((cp1[0] == '.') && (cp1[1] == '/')) {
9870 /* Add a subdirectory spec. Do not duplicate "." */
9871 if (cp2[-1] != '.' && cp2[-1] != '[' && cp2[-1] != '<')
9873 /* If this is ".." then the spec becomes "-" */
9874 if ((cp1[0] == '.') && (cp1[1] == '.') && (cp[2] == '/')) {
9875 /* Add "-" and skip the ".." */
9880 /* Copy the subdirectory */
9881 while (*cp1 != '/') *cp2++= *cp1++;
9882 cp1++; /* Skip the "/" */
9884 /* Close the directory specification */
9885 if (cp2[-1] == '.') /* no trailing periods */
9889 /* Now add the filename */
9890 while (*cp1) *cp2++ = *cp1++;
9892 /* Now append it to the original VMS spec. */
9895 /* If we put a [000000] in the filename, try to open it first. If this fails,
9896 remove the [000000], and return that name. This provides flexibility
9897 to the user in that they can use both rooted and non-rooted logical names
9898 to point to the location of the file. */
9900 if (check_filename_before_returning && no_prefix_seen) {
9901 f = open (fname, O_RDONLY, 0666);
9903 /* The file name is OK as it is, so return it as is. */
9907 /* The filename did not work. Try to remove the [000000] from the name,
9909 cp = index (fname, '[');
9910 cp2 = index (fname, ']') + 1;
9911 strcpy (cp, cp2); /* this gets rid of it */
9919 /* These are the read/write replacement routines for
9920 VAX-11 "C". They make read/write behave enough
9921 like their UNIX counterparts that CCCP will work */
9924 read (fd, buf, size)
9929 #undef read /* Get back the REAL read routine */
9931 register int total = 0;
9933 /* Read until the buffer is exhausted */
9935 /* Limit each read to 32KB */
9936 i = (size > (32*1024)) ? (32*1024) : size;
9937 i = read (fd, buf, i);
9939 if (i == 0) return (total);
9942 /* Account for this read */
9951 write (fd, buf, size)
9956 #undef write /* Get back the REAL write routine */
9960 /* Limit individual writes to 32Kb */
9963 j = (i > (32*1024)) ? (32*1024) : i;
9964 if (write (fd, buf, j) < 0) return (-1);
9965 /* Account for the data written */
9972 /* The following wrapper functions supply additional arguments to the VMS
9973 I/O routines to optimize performance with file handling. The arguments
9975 "mbc=16" - Set multi-block count to 16 (use a 8192 byte buffer).
9976 "deq=64" - When extending the file, extend it in chunks of 32Kbytes.
9977 "fop=tef"- Truncate unused portions of file when closing file.
9978 "shr=nil"- Disallow file sharing while file is open.
9982 freopen (fname, type, oldfile)
9987 #undef freopen /* Get back the REAL fopen routine */
9988 if (strcmp (type, "w") == 0)
9989 return freopen (fname, type, oldfile, "mbc=16", "deq=64", "fop=tef", "shr=nil");
9990 return freopen (fname, type, oldfile, "mbc=16");
9998 #undef fopen /* Get back the REAL fopen routine */
9999 /* The gcc-vms-1.42 distribution's header files prototype fopen with two
10000 fixed arguments, which matches ANSI's specification but not VAXCRTL's
10001 pre-ANSI implmentation. This hack circumvents the mismatch problem. */
10002 FILE *(*vmslib_fopen)() = (FILE *(*)()) fopen;
10005 return (*vmslib_fopen) (fname, type, "mbc=32",
10006 "deq=64", "fop=tef", "shr=nil");
10008 return (*vmslib_fopen) (fname, type, "mbc=32");
10012 open (fname, flags, prot)
10017 #undef open /* Get back the REAL open routine */
10018 return open (fname, flags, prot, "mbc=16", "deq=64", "fop=tef");
10021 /* Avoid run-time library bug, where copying M out of N+M characters with
10022 N >= 65535 results in VAXCRTL's strncat falling into an infinite loop.
10023 gcc-cpp exercises this particular bug. */
10026 strncat (dst, src, cnt)
10031 register char *d = dst, *s = (char *) src;
10032 register int n = cnt; /* convert to _signed_ type */
10034 while (*d) d++; /* advance to end */
10036 if (!(*d++ = *s++)) break;
10037 if (n < 0) *d = '\0';