1 /* C Compatible Compiler Preprocessor (CCCP)
2 Copyright (C) 1986, 87, 89, 92-97, 1998 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, 59 Temple Place - Suite 330,
19 Boston, MA 02111-1307, USA. */
28 #define PRINTF_PROTO(ARGS, m, n) PVPROTO (ARGS) ATTRIBUTE_PRINTF(m, n)
30 #define PRINTF_PROTO_1(ARGS) PRINTF_PROTO(ARGS, 1, 2)
31 #define PRINTF_PROTO_2(ARGS) PRINTF_PROTO(ARGS, 2, 3)
32 #define PRINTF_PROTO_3(ARGS) PRINTF_PROTO(ARGS, 3, 4)
33 #define PRINTF_PROTO_4(ARGS) PRINTF_PROTO(ARGS, 4, 5)
39 #ifdef HAVE_SYS_RESOURCE_H
40 # include <sys/resource.h>
43 typedef unsigned char U_CHAR;
45 #include "gansidecl.h"
48 #ifndef GET_ENVIRONMENT
49 #define GET_ENVIRONMENT(ENV_VALUE,ENV_NAME) ENV_VALUE = getenv (ENV_NAME)
52 #ifndef STANDARD_INCLUDE_DIR
53 # define STANDARD_INCLUDE_DIR "/usr/include"
56 /* By default, colon separates directories in a path. */
57 #ifndef PATH_SEPARATOR
58 # define PATH_SEPARATOR ':'
61 /* By default, the suffix for object files is ".o". */
63 # define HAVE_OBJECT_SUFFIX
65 # define OBJECT_SUFFIX ".o"
68 /* VMS-specific definitions */
73 #define open(fname,mode,prot) VMS_open (fname,mode,prot)
74 #define fopen(fname,mode) VMS_fopen (fname,mode)
75 #define freopen(fname,mode,ofile) VMS_freopen (fname,mode,ofile)
76 #define fstat(fd,stbuf) VMS_fstat (fd,stbuf)
77 static int VMS_fstat (), VMS_stat ();
78 static int VMS_open ();
79 static FILE *VMS_fopen ();
80 static FILE *VMS_freopen ();
81 static int hack_vms_include_specification ();
82 #define INO_T_EQ(a, b) (!bcmp((char *) &(a), (char *) &(b), sizeof (a)))
83 #define INO_T_HASH(a) 0
84 #define INCLUDE_LEN_FUDGE 12 /* leave room for VMS syntax conversion */
87 /* Windows does not natively support inodes, and neither does MSDOS. */
88 #if (defined (_WIN32) && ! defined (CYGWIN32)) || defined (__MSDOS__)
89 #define INO_T_EQ(a, b) 0
94 #define MIN(X,Y) ((X) < (Y) ? (X) : (Y))
95 #define MAX(X,Y) ((X) > (Y) ? (X) : (Y))
97 /* Find the largest host integer type and set its size and type.
98 Watch out: on some crazy hosts `long' is shorter than `int'. */
100 #ifndef HOST_WIDE_INT
102 # include <inttypes.h>
103 # define HOST_WIDE_INT intmax_t
105 # if (HOST_BITS_PER_LONG <= HOST_BITS_PER_INT && HOST_BITS_PER_LONGLONG <= HOST_BITS_PER_INT)
106 # define HOST_WIDE_INT int
108 # if (HOST_BITS_PER_LONGLONG <= HOST_BITS_PER_LONG || ! (defined LONG_LONG_MAX || defined LLONG_MAX))
109 # define HOST_WIDE_INT long
111 # define HOST_WIDE_INT long long
118 #define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
122 #define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
126 #define INO_T_EQ(a, b) ((a) == (b))
130 #define INO_T_HASH(a) (a)
133 #ifndef INCLUDE_LEN_FUDGE
134 #define INCLUDE_LEN_FUDGE 0
137 /* External declarations. */
139 extern char *version_string;
140 extern char *update_path PROTO((char *, char *));
141 HOST_WIDE_INT parse_escape PROTO((char **, HOST_WIDE_INT));
142 HOST_WIDE_INT parse_c_expression PROTO((char *, int));
144 /* Name under which this program was invoked. */
146 static char *progname;
148 /* Nonzero means use extra default include directories for C++. */
150 static int cplusplus;
152 /* Nonzero means handle cplusplus style comments */
154 static int cplusplus_comments;
156 /* Nonzero means handle #import, for objective C. */
160 /* Nonzero means this is an assembly file, and allow
161 unknown directives, which could be comments. */
165 /* Current maximum length of directory names in the search path
166 for include files. (Altered as we get more of them.) */
168 static int max_include_len;
170 /* Nonzero means turn NOTREACHED into #pragma NOTREACHED etc */
172 static int for_lint = 0;
174 /* Nonzero means copy comments into the output file. */
176 static int put_out_comments = 0;
178 /* Nonzero means don't process the ANSI trigraph sequences. */
180 static int no_trigraphs = 0;
182 /* Nonzero means print the names of included files rather than
183 the preprocessed output. 1 means just the #include "...",
184 2 means #include <...> as well. */
186 static int print_deps = 0;
188 /* Nonzero if missing .h files in -M output are assumed to be generated
189 files and not errors. */
191 static int print_deps_missing_files = 0;
193 /* Nonzero means print names of header files (-H). */
195 static int print_include_names = 0;
197 /* Nonzero means don't output line number information. */
199 static int no_line_directives;
201 /* Nonzero means output the text in failing conditionals,
202 inside #failed ... #endfailed. */
204 static int output_conditionals;
206 /* dump_only means inhibit output of the preprocessed text
207 and instead output the definitions of all user-defined
208 macros in a form suitable for use as input to cccp.
209 dump_names means pass #define and the macro name through to output.
210 dump_definitions means pass the whole definition (plus #define) through
213 static enum {dump_none, dump_only, dump_names, dump_definitions}
214 dump_macros = dump_none;
216 /* Nonzero means pass all #define and #undef directives which we actually
217 process through to the output stream. This feature is used primarily
218 to allow cc1 to record the #defines and #undefs for the sake of
219 debuggers which understand about preprocessor macros, but it may
220 also be useful with -E to figure out how symbols are defined, and
221 where they are defined. */
222 static int debug_output = 0;
224 /* Nonzero means pass #include lines through to the output,
225 even if they are ifdefed out. */
226 static int dump_includes;
228 /* Nonzero indicates special processing used by the pcp program. The
229 special effects of this mode are:
231 Inhibit all macro expansion, except those inside #if directives.
233 Process #define directives normally, and output their contents
236 Output preconditions to pcp_outfile indicating all the relevant
237 preconditions for use of this file in a later cpp run.
239 static FILE *pcp_outfile;
241 /* Nonzero means we are inside an IF during a -pcp run. In this mode
242 macro expansion is done, and preconditions are output for all macro
243 uses requiring them. */
244 static int pcp_inside_if;
246 /* Nonzero means never to include precompiled files.
247 This is 1 since there's no way now to make precompiled files,
248 so it's not worth testing for them. */
249 static int no_precomp = 1;
251 /* Nonzero means give all the error messages the ANSI standard requires. */
255 /* Nonzero means try to make failure to fit ANSI C an error. */
257 static int pedantic_errors;
259 /* Nonzero means don't print warning messages. -w. */
261 static int inhibit_warnings = 0;
263 /* Nonzero means warn if slash-star appears in a slash-star comment,
264 or if newline-backslash appears in a slash-slash comment. */
266 static int warn_comments;
268 /* Nonzero means warn if a macro argument is (or would be)
269 stringified with -traditional. */
271 static int warn_stringify;
273 /* Nonzero means warn if there are any trigraphs. */
275 static int warn_trigraphs;
277 /* Nonzero means warn if undefined identifiers are evaluated in an #if. */
279 static int warn_undef;
281 /* Nonzero means warn if #import is used. */
283 static int warn_import = 1;
285 /* Nonzero means turn warnings into errors. */
287 static int warnings_are_errors;
289 /* Nonzero means try to imitate old fashioned non-ANSI preprocessor. */
293 /* Nonzero for the 1989 C Standard, including corrigenda and amendments. */
297 /* Nonzero causes output not to be done,
298 but directives such as #define that have side effects
301 static int no_output;
303 /* Nonzero means we should look for header.gcc files that remap file names. */
306 /* Nonzero means this file was included with a -imacros or -include
307 command line and should not be recorded as an include file. */
309 static int no_record_file;
311 /* Nonzero means that we have finished processing the command line options.
312 This flag is used to decide whether or not to issue certain errors
315 static int done_initializing = 0;
317 /* Line where a newline was first seen in a string constant. */
319 static int multiline_string_line = 0;
321 /* I/O buffer structure.
322 The `fname' field is nonzero for source files and #include files
323 and for the dummy text used for -D and -U.
324 It is zero for rescanning results of macro expansion
325 and for expanding macro arguments. */
326 #define INPUT_STACK_MAX 400
327 static struct file_buf {
329 /* Filename specified with #line directive. */
331 /* The length of nominal_fname, which may contain embedded NULs. */
332 size_t nominal_fname_len;
333 /* Include file description. */
334 struct include_file *inc;
335 /* Record where in the search path this file was found.
336 For #include_next. */
337 struct file_name_list *dir;
342 /* Macro that this level is the expansion of.
343 Included so that we can reenable the macro
344 at the end of this level. */
345 struct hashnode *macro;
346 /* Value of if_stack at start of this file.
347 Used to prohibit unmatched #endif (etc) in an include file. */
348 struct if_stack *if_stack;
349 /* Object to be freed at end of input at this level. */
351 /* True if this is a system header file; see is_system_include. */
352 char system_header_p;
353 } instack[INPUT_STACK_MAX];
355 static int last_error_tick; /* Incremented each time we print it. */
356 static int input_file_stack_tick; /* Incremented when the status changes. */
358 /* Current nesting level of input sources.
359 `instack[indepth]' is the level currently being read. */
360 static int indepth = -1;
361 #define CHECK_DEPTH(code) \
362 if (indepth >= (INPUT_STACK_MAX - 1)) \
364 error_with_line (line_for_error (instack[indepth].lineno), \
365 "macro or `#include' recursion too deep"); \
369 /* Current depth in #include directives that use <...>. */
370 static int system_include_depth = 0;
372 typedef struct file_buf FILE_BUF;
374 /* The output buffer. Its LENGTH field is the amount of room allocated
375 for the buffer, not the number of chars actually present. To get
376 that, subtract outbuf.buf from outbuf.bufp. */
378 #define OUTBUF_SIZE 10 /* initial size of output buffer */
379 static FILE_BUF outbuf;
381 /* Grow output buffer OBUF points at
382 so it can hold at least NEEDED more chars. */
384 #define check_expand(OBUF, NEEDED) \
385 (((OBUF)->length - ((OBUF)->bufp - (OBUF)->buf) <= (NEEDED)) \
386 ? grow_outbuf ((OBUF), (NEEDED)) : 0)
388 struct file_name_list
390 struct file_name_list *next;
391 /* If the following is 1, it is a C-language system include
393 int c_system_include_path;
394 /* Mapping of file names for this directory. */
395 struct file_name_map *name_map;
396 /* Non-zero if name_map is valid. */
398 /* The include directory status. */
400 /* The include prefix: "" denotes the working directory,
401 otherwise fname must end in '/'.
402 The actual size is dynamically allocated. */
406 /* #include "file" looks in source file dir, then stack. */
407 /* #include <file> just looks in the stack. */
408 /* -I directories are added to the end, then the defaults are added. */
410 static struct default_include {
411 char *fname; /* The name of the directory. */
412 char *component; /* The component containing the directory */
413 int cplusplus; /* Only look here if we're compiling C++. */
414 int cxx_aware; /* Includes in this directory don't need to
415 be wrapped in extern "C" when compiling
417 } include_defaults_array[]
418 #ifdef INCLUDE_DEFAULTS
422 /* Pick up GNU C++ specific include files. */
423 { GPLUSPLUS_INCLUDE_DIR, "G++", 1, 1 },
424 { OLD_GPLUSPLUS_INCLUDE_DIR, 0, 1, 1 },
426 /* This is the dir for fixincludes. Put it just before
427 the files that we fix. */
428 { GCC_INCLUDE_DIR, "GCC", 0, 0 },
429 /* For cross-compilation, this dir name is generated
430 automatically in Makefile.in. */
431 { CROSS_INCLUDE_DIR, "GCC", 0, 0 },
432 #ifdef TOOL_INCLUDE_DIR
433 /* This is another place that the target system's headers might be. */
434 { TOOL_INCLUDE_DIR, "BINUTILS", 0, 0 },
436 #else /* not CROSS_COMPILE */
437 #ifdef LOCAL_INCLUDE_DIR
438 /* This should be /usr/local/include and should come before
439 the fixincludes-fixed header files. */
440 { LOCAL_INCLUDE_DIR, 0, 0, 1 },
442 #ifdef TOOL_INCLUDE_DIR
443 /* This is here ahead of GCC_INCLUDE_DIR because assert.h goes here.
444 Likewise, behind LOCAL_INCLUDE_DIR, where glibc puts its assert.h. */
445 { TOOL_INCLUDE_DIR, "BINUTILS", 0, 0 },
447 /* This is the dir for fixincludes. Put it just before
448 the files that we fix. */
449 { GCC_INCLUDE_DIR, "GCC", 0, 0 },
450 /* Some systems have an extra dir of include files. */
451 #ifdef SYSTEM_INCLUDE_DIR
452 { SYSTEM_INCLUDE_DIR, 0, 0, 0 },
454 #ifndef STANDARD_INCLUDE_COMPONENT
455 #define STANDARD_INCLUDE_COMPONENT 0
457 { STANDARD_INCLUDE_DIR, STANDARD_INCLUDE_COMPONENT, 0, 0 },
458 #endif /* not CROSS_COMPILE */
461 #endif /* no INCLUDE_DEFAULTS */
463 /* The code looks at the defaults through this pointer, rather than through
464 the constant structure above. This pointer gets changed if an environment
465 variable specifies other defaults. */
466 static struct default_include *include_defaults = include_defaults_array;
468 static struct file_name_list *include = 0; /* First dir to search */
469 /* First dir to search for <file> */
470 /* This is the first element to use for #include <...>.
471 If it is 0, use the entire chain for such includes. */
472 static struct file_name_list *first_bracket_include = 0;
473 /* This is the first element in the chain that corresponds to
474 a directory of system header files. */
475 static struct file_name_list *first_system_include = 0;
476 static struct file_name_list *last_include = 0; /* Last in chain */
478 /* Chain of include directories to put at the end of the other chain. */
479 static struct file_name_list *after_include = 0;
480 static struct file_name_list *last_after_include = 0; /* Last in chain */
482 /* Chain to put at the start of the system include files. */
483 static struct file_name_list *before_system = 0;
484 static struct file_name_list *last_before_system = 0; /* Last in chain */
486 /* Directory prefix that should replace `/usr' in the standard
487 include file directories. */
488 static char *include_prefix;
490 /* Maintain and search list of included files. */
492 struct include_file {
493 struct include_file *next; /* for include_hashtab */
494 struct include_file *next_ino; /* for include_ino_hashtab */
496 /* If the following is the empty string, it means #pragma once
497 was seen in this include file, or #import was applied to the file.
498 Otherwise, if it is nonzero, it is a macro name.
499 Don't include the file again if that macro is defined. */
500 U_CHAR *control_macro;
501 /* Nonzero if the dependency on this include file has been output. */
506 /* Hash tables of files already included with #include or #import.
507 include_hashtab is by full name; include_ino_hashtab is by inode number. */
509 #define INCLUDE_HASHSIZE 61
510 static struct include_file *include_hashtab[INCLUDE_HASHSIZE];
511 static struct include_file *include_ino_hashtab[INCLUDE_HASHSIZE];
513 /* Global list of strings read in from precompiled files. This list
514 is kept in the order the strings are read in, with new strings being
515 added at the end through stringlist_tailp. We use this list to output
516 the strings at the end of the run.
518 static STRINGDEF *stringlist;
519 static STRINGDEF **stringlist_tailp = &stringlist;
522 /* Structure returned by create_definition */
523 typedef struct macrodef MACRODEF;
526 struct definition *defn;
531 enum sharp_token_type {
532 NO_SHARP_TOKEN = 0, /* token not present */
534 SHARP_TOKEN = '#', /* token spelled with # only */
535 WHITE_SHARP_TOKEN, /* token spelled with # and white space */
537 PERCENT_COLON_TOKEN = '%', /* token spelled with %: only */
538 WHITE_PERCENT_COLON_TOKEN /* token spelled with %: and white space */
541 /* Structure allocated for every #define. For a simple replacement
544 nargs = -1, the `pattern' list is null, and the expansion is just
545 the replacement text. Nargs = 0 means a functionlike macro with no args,
547 #define getchar() getc (stdin) .
548 When there are args, the expansion is the replacement text with the
549 args squashed out, and the reflist is a list describing how to
550 build the output from the input: e.g., "3 chars, then the 1st arg,
551 then 9 chars, then the 3rd arg, then 0 chars, then the 2nd arg".
552 The chars here come from the expansion. Whatever is left of the
553 expansion after the last arg-occurrence is copied after that arg.
554 Note that the reflist can be arbitrarily long---
555 its length depends on the number of times the arguments appear in
556 the replacement text, not how many args there are. Example:
557 #define f(x) x+x+x+x+x+x+x would have replacement text "++++++" and
559 { (0, 1), (1, 1), (1, 1), ..., (1, 1), NULL }
560 where (x, y) means (nchars, argno). */
562 typedef struct definition DEFINITION;
565 int length; /* length of expansion string */
566 int predefined; /* True if the macro was builtin or */
567 /* came from the command line */
569 int line; /* Line number of definition */
570 char *file; /* File of definition */
571 size_t file_len; /* Length of file (which can contain NULs) */
572 char rest_args; /* Nonzero if last arg. absorbs the rest */
574 struct reflist *next;
576 enum sharp_token_type stringify; /* set if a # operator before arg */
577 enum sharp_token_type raw_before; /* set if a ## operator before arg */
578 enum sharp_token_type raw_after; /* set if a ## operator after arg */
580 char rest_args; /* Nonzero if this arg. absorbs the rest */
581 int nchars; /* Number of literal chars to copy before
582 this arg occurrence. */
583 int argno; /* Number of arg to substitute (origin-0) */
586 /* Names of macro args, concatenated in reverse order
587 with comma-space between them.
588 The only use of this is that we warn on redefinition
589 if this differs between the old and new definitions. */
594 /* different kinds of things that can appear in the value field
595 of a hash node. Actually, this may be useless now. */
603 * special extension string that can be added to the last macro argument to
604 * allow it to absorb the "rest" of the arguments when expanded. Ex:
605 * #define wow(a, b...) process (b, a, b)
606 * { wow (1, 2, 3); } -> { process (2, 3, 1, 2, 3); }
607 * { wow (one, two); } -> { process (two, one, two); }
608 * if this "rest_arg" is used with the concat token '##' and if it is not
609 * supplied then the token attached to with ## will not be outputted. Ex:
610 * #define wow (a, b...) process (b ## , a, ## b)
611 * { wow (1, 2); } -> { process (2, 1, 2); }
612 * { wow (one); } -> { process (one); {
614 static char rest_extension[] = "...";
615 #define REST_EXTENSION_LENGTH (sizeof (rest_extension) - 1)
617 /* The structure of a node in the hash table. The hash table
618 has entries for all tokens defined by #define directives (type T_MACRO),
619 plus some special tokens like __LINE__ (these each have their own
620 type, and the appropriate code is run when that type of node is seen.
621 It does not contain control words like "#define", which are recognized
622 by a separate piece of code. */
624 /* different flavors of hash nodes --- also used in keyword table */
626 T_DEFINE = 1, /* the `#define' keyword */
627 T_INCLUDE, /* the `#include' keyword */
628 T_INCLUDE_NEXT, /* the `#include_next' keyword */
629 T_IMPORT, /* the `#import' keyword */
630 T_IFDEF, /* the `#ifdef' keyword */
631 T_IFNDEF, /* the `#ifndef' keyword */
632 T_IF, /* the `#if' keyword */
633 T_ELSE, /* `#else' */
634 T_PRAGMA, /* `#pragma' */
635 T_ELIF, /* `#elif' */
636 T_UNDEF, /* `#undef' */
637 T_LINE, /* `#line' */
638 T_ERROR, /* `#error' */
639 T_WARNING, /* `#warning' */
640 T_ENDIF, /* `#endif' */
641 T_SCCS, /* `#sccs', used on system V. */
642 T_IDENT, /* `#ident', used on system V. */
643 T_ASSERT, /* `#assert', taken from system V. */
644 T_UNASSERT, /* `#unassert', taken from system V. */
645 T_SPECLINE, /* special symbol `__LINE__' */
646 T_DATE, /* `__DATE__' */
647 T_FILE, /* `__FILE__' */
648 T_BASE_FILE, /* `__BASE_FILE__' */
649 T_INCLUDE_LEVEL, /* `__INCLUDE_LEVEL__' */
650 T_VERSION, /* `__VERSION__' */
651 T_SIZE_TYPE, /* `__SIZE_TYPE__' */
652 T_PTRDIFF_TYPE, /* `__PTRDIFF_TYPE__' */
653 T_WCHAR_TYPE, /* `__WCHAR_TYPE__' */
654 T_USER_LABEL_PREFIX_TYPE, /* `__USER_LABEL_PREFIX__' */
655 T_REGISTER_PREFIX_TYPE, /* `__REGISTER_PREFIX__' */
656 T_IMMEDIATE_PREFIX_TYPE, /* `__IMMEDIATE_PREFIX__' */
657 T_TIME, /* `__TIME__' */
658 T_CONST, /* Constant value, used by `__STDC__' */
659 T_MACRO, /* macro defined by `#define' */
660 T_DISABLED, /* macro temporarily turned off for rescan */
661 T_SPEC_DEFINED, /* special `defined' macro for use in #if statements */
662 T_PCSTRING, /* precompiled string (hashval is KEYDEF *) */
663 T_UNUSED /* Used for something not defined. */
667 struct hashnode *next; /* double links for easy deletion */
668 struct hashnode *prev;
669 struct hashnode **bucket_hdr; /* also, a back pointer to this node's hash
670 chain is kept, in case the node is the head
671 of the chain and gets deleted. */
672 enum node_type type; /* type of special token */
673 int length; /* length of token, for quick comparison */
674 U_CHAR *name; /* the actual name */
675 union hashval value; /* pointer to expansion, or whatever */
678 typedef struct hashnode HASHNODE;
680 /* Some definitions for the hash table. The hash function MUST be
681 computed as shown in hashf () below. That is because the rescan
682 loop computes the hash value `on the fly' for most tokens,
683 in order to avoid the overhead of a lot of procedure calls to
684 the hashf () function. Hashf () only exists for the sake of
685 politeness, for use when speed isn't so important. */
687 #define HASHSIZE 1403
688 static HASHNODE *hashtab[HASHSIZE];
689 #define HASHSTEP(old, c) ((old << 2) + c)
690 #define MAKE_POS(v) (v & 0x7fffffff) /* make number positive */
692 /* Symbols to predefine. */
694 #ifdef CPP_PREDEFINES
695 static char *predefs = CPP_PREDEFINES;
697 static char *predefs = "";
700 /* We let tm.h override the types used here, to handle trivial differences
701 such as the choice of unsigned int or long unsigned int for size_t.
702 When machines start needing nontrivial differences in the size type,
703 it would be best to do something here to figure out automatically
704 from other information what type to use. */
706 /* The string value for __SIZE_TYPE__. */
709 #define SIZE_TYPE "long unsigned int"
712 /* The string value for __PTRDIFF_TYPE__. */
715 #define PTRDIFF_TYPE "long int"
718 /* The string value for __WCHAR_TYPE__. */
721 #define WCHAR_TYPE "int"
723 char * wchar_type = WCHAR_TYPE;
726 /* The string value for __USER_LABEL_PREFIX__ */
728 #ifndef USER_LABEL_PREFIX
729 #define USER_LABEL_PREFIX ""
732 /* The string value for __REGISTER_PREFIX__ */
734 #ifndef REGISTER_PREFIX
735 #define REGISTER_PREFIX ""
738 /* The string value for __IMMEDIATE_PREFIX__ */
740 #ifndef IMMEDIATE_PREFIX
741 #define IMMEDIATE_PREFIX ""
744 /* In the definition of a #assert name, this structure forms
745 a list of the individual values asserted.
746 Each value is itself a list of "tokens".
747 These are strings that are compared by name. */
749 struct tokenlist_list {
750 struct tokenlist_list *next;
751 struct arglist *tokens;
754 struct assertion_hashnode {
755 struct assertion_hashnode *next; /* double links for easy deletion */
756 struct assertion_hashnode *prev;
757 /* also, a back pointer to this node's hash
758 chain is kept, in case the node is the head
759 of the chain and gets deleted. */
760 struct assertion_hashnode **bucket_hdr;
761 int length; /* length of token, for quick comparison */
762 U_CHAR *name; /* the actual name */
763 /* List of token-sequences. */
764 struct tokenlist_list *value;
767 typedef struct assertion_hashnode ASSERTION_HASHNODE;
769 /* Some definitions for the hash table. The hash function MUST be
770 computed as shown in hashf below. That is because the rescan
771 loop computes the hash value `on the fly' for most tokens,
772 in order to avoid the overhead of a lot of procedure calls to
773 the hashf function. hashf only exists for the sake of
774 politeness, for use when speed isn't so important. */
776 #define ASSERTION_HASHSIZE 37
777 static ASSERTION_HASHNODE *assertion_hashtab[ASSERTION_HASHSIZE];
779 /* Nonzero means inhibit macroexpansion of what seem to be
780 assertion tests, in rescan. For #if. */
781 static int assertions_flag;
783 /* `struct directive' defines one #-directive, including how to handle it. */
785 #define DO_PROTO PROTO((U_CHAR *, U_CHAR *, FILE_BUF *, struct directive *))
788 int length; /* Length of name */
789 int (*func) DO_PROTO; /* Function to handle directive */
790 char *name; /* Name of directive */
791 enum node_type type; /* Code which describes which directive. */
794 #define IS_INCLUDE_DIRECTIVE_TYPE(t) \
795 ((int) T_INCLUDE <= (int) (t) && (int) (t) <= (int) T_IMPORT)
797 /* These functions are declared to return int instead of void since they
798 are going to be placed in the table and some old compilers have trouble with
799 pointers to functions returning void. */
801 static int do_assert DO_PROTO;
802 static int do_define DO_PROTO;
803 static int do_elif DO_PROTO;
804 static int do_else DO_PROTO;
805 static int do_endif DO_PROTO;
806 static int do_error DO_PROTO;
807 static int do_ident DO_PROTO;
808 static int do_if DO_PROTO;
809 static int do_include DO_PROTO;
810 static int do_line DO_PROTO;
811 static int do_pragma DO_PROTO;
812 #ifdef SCCS_DIRECTIVE
813 static int do_sccs DO_PROTO;
815 static int do_unassert DO_PROTO;
816 static int do_undef DO_PROTO;
817 static int do_warning DO_PROTO;
818 static int do_xifdef DO_PROTO;
820 /* Here is the actual list of #-directives, most-often-used first. */
822 static struct directive directive_table[] = {
823 { 6, do_define, "define", T_DEFINE},
824 { 2, do_if, "if", T_IF},
825 { 5, do_xifdef, "ifdef", T_IFDEF},
826 { 6, do_xifdef, "ifndef", T_IFNDEF},
827 { 5, do_endif, "endif", T_ENDIF},
828 { 4, do_else, "else", T_ELSE},
829 { 4, do_elif, "elif", T_ELIF},
830 { 4, do_line, "line", T_LINE},
831 { 7, do_include, "include", T_INCLUDE},
832 { 12, do_include, "include_next", T_INCLUDE_NEXT},
833 { 6, do_include, "import", T_IMPORT},
834 { 5, do_undef, "undef", T_UNDEF},
835 { 5, do_error, "error", T_ERROR},
836 { 7, do_warning, "warning", T_WARNING},
837 #ifdef SCCS_DIRECTIVE
838 { 4, do_sccs, "sccs", T_SCCS},
840 { 6, do_pragma, "pragma", T_PRAGMA},
841 { 5, do_ident, "ident", T_IDENT},
842 { 6, do_assert, "assert", T_ASSERT},
843 { 8, do_unassert, "unassert", T_UNASSERT},
844 { -1, 0, "", T_UNUSED},
847 /* When a directive handler is called,
848 this points to the # (or the : of the %:) that started the directive. */
849 U_CHAR *directive_start;
851 /* table to tell if char can be part of a C identifier. */
852 U_CHAR is_idchar[256];
853 /* table to tell if char can be first char of a c identifier. */
854 U_CHAR is_idstart[256];
855 /* table to tell if c is horizontal space. */
856 static U_CHAR is_hor_space[256];
857 /* table to tell if c is horizontal or vertical space. */
858 U_CHAR is_space[256];
859 /* names of some characters */
860 static char *char_name[256];
862 #define SKIP_WHITE_SPACE(p) do { while (is_hor_space[*p]) p++; } while (0)
863 #define SKIP_ALL_WHITE_SPACE(p) do { while (is_space[*p]) p++; } while (0)
865 static int errors = 0; /* Error counter for exit code */
867 /* Name of output file, for error messages. */
868 static char *out_fname;
871 /* Stack of conditionals currently in progress
872 (including both successful and failing conditionals). */
875 struct if_stack *next; /* for chaining to the next stack frame */
876 char *fname; /* copied from input when frame is made */
877 size_t fname_len; /* similarly */
878 int lineno; /* similarly */
879 int if_succeeded; /* true if a leg of this if-group
880 has been passed through rescan */
881 U_CHAR *control_macro; /* For #ifndef at start of file,
882 this is the macro name tested. */
883 enum node_type type; /* type of last directive seen in this group */
885 typedef struct if_stack IF_STACK_FRAME;
886 static IF_STACK_FRAME *if_stack = NULL;
888 /* Buffer of -M output. */
889 static char *deps_buffer;
891 /* Number of bytes allocated in above. */
892 static int deps_allocated_size;
894 /* Number of bytes used. */
895 static int deps_size;
897 /* Number of bytes since the last newline. */
898 static int deps_column;
900 /* Nonzero means -I- has been seen,
901 so don't look for #include "foo" the source-file directory. */
902 static int ignore_srcdir;
904 static int safe_read PROTO((int, char *, int));
905 static void safe_write PROTO((int, char *, int));
906 static void eprint_string PROTO((char *, size_t));
908 int main PROTO((int, char **));
910 static void path_include PROTO((char *));
912 static U_CHAR *index0 PROTO((U_CHAR *, int, size_t));
914 static void trigraph_pcp PROTO((FILE_BUF *));
916 static void newline_fix PROTO((U_CHAR *));
917 static void name_newline_fix PROTO((U_CHAR *));
919 static char *get_lintcmd PROTO((U_CHAR *, U_CHAR *, U_CHAR **, int *, int *));
921 static void rescan PROTO((FILE_BUF *, int));
923 static FILE_BUF expand_to_temp_buffer PROTO((U_CHAR *, U_CHAR *, int, int));
925 static int handle_directive PROTO((FILE_BUF *, FILE_BUF *));
927 static struct tm *timestamp PROTO((void));
928 static void special_symbol PROTO((HASHNODE *, FILE_BUF *));
930 static int is_system_include PROTO((char *));
931 static char *base_name PROTO((char *));
932 static int absolute_filename PROTO((char *));
933 static size_t simplify_filename PROTO((char *));
935 static char *read_filename_string PROTO((int, FILE *));
936 static struct file_name_map *read_name_map PROTO((char *));
937 static int open_include_file PROTO((char *, struct file_name_list *, U_CHAR *, struct include_file **));
938 static char *remap_include_file PROTO((char *, struct file_name_list *));
939 static int lookup_ino_include PROTO((struct include_file *));
941 static void finclude PROTO((int, struct include_file *, FILE_BUF *, int, struct file_name_list *));
942 static void record_control_macro PROTO((struct include_file *, U_CHAR *));
944 static char *check_precompiled PROTO((int, struct stat *, char *, char **));
945 static int check_preconditions PROTO((char *));
946 static void pcfinclude PROTO((U_CHAR *, U_CHAR *, U_CHAR *, FILE_BUF *));
947 static void pcstring_used PROTO((HASHNODE *));
948 static void write_output PROTO((void));
949 static void pass_thru_directive PROTO((U_CHAR *, U_CHAR *, FILE_BUF *, struct directive *));
951 static MACRODEF create_definition PROTO((U_CHAR *, U_CHAR *, FILE_BUF *));
953 static int check_macro_name PROTO((U_CHAR *, char *));
954 static int compare_defs PROTO((DEFINITION *, DEFINITION *));
955 static int comp_def_part PROTO((int, U_CHAR *, int, U_CHAR *, int, int));
957 static DEFINITION *collect_expansion PROTO((U_CHAR *, U_CHAR *, int, struct arglist *));
959 int check_assertion PROTO((U_CHAR *, int, int, struct arglist *));
960 static int compare_token_lists PROTO((struct arglist *, struct arglist *));
962 static struct arglist *read_token_list PROTO((U_CHAR **, U_CHAR *, int *));
963 static void free_token_list PROTO((struct arglist *));
965 static ASSERTION_HASHNODE *assertion_install PROTO((U_CHAR *, int, int));
966 static ASSERTION_HASHNODE *assertion_lookup PROTO((U_CHAR *, int, int));
967 static void delete_assertion PROTO((ASSERTION_HASHNODE *));
969 static void do_once PROTO((void));
971 static HOST_WIDE_INT eval_if_expression PROTO((U_CHAR *, int));
972 static void conditional_skip PROTO((FILE_BUF *, int, enum node_type, U_CHAR *, FILE_BUF *));
973 static void skip_if_group PROTO((FILE_BUF *, int, FILE_BUF *));
974 static void validate_else PROTO((U_CHAR *, U_CHAR *));
976 static U_CHAR *skip_to_end_of_comment PROTO((FILE_BUF *, int *, int));
977 static U_CHAR *skip_quoted_string PROTO((U_CHAR *, U_CHAR *, int, int *, int *, int *));
978 static char *quote_string PROTO((char *, char *, size_t));
979 static U_CHAR *skip_paren_group PROTO((FILE_BUF *));
981 /* Last arg to output_line_directive. */
982 enum file_change_code {same_file, enter_file, leave_file};
983 static void output_line_directive PROTO((FILE_BUF *, FILE_BUF *, int, enum file_change_code));
985 static void macroexpand PROTO((HASHNODE *, FILE_BUF *));
988 static char *macarg PROTO((struct argdata *, int));
990 static U_CHAR *macarg1 PROTO((U_CHAR *, U_CHAR *, struct hashnode *, int *, int *, int *, int));
992 static int discard_comments PROTO((U_CHAR *, int, int));
994 static int change_newlines PROTO((U_CHAR *, int));
996 static char *my_strerror PROTO((int));
997 void error PRINTF_PROTO_1((char *, ...));
998 static void verror PROTO((char *, va_list));
999 static void error_from_errno PROTO((char *));
1000 void warning PRINTF_PROTO_1((char *, ...));
1001 static void vwarning PROTO((char *, va_list));
1002 static void error_with_line PRINTF_PROTO_2((int, char *, ...));
1003 static void verror_with_line PROTO((int, char *, va_list));
1004 static void vwarning_with_line PROTO((int, char *, va_list));
1005 static void warning_with_line PRINTF_PROTO_2((int, char *, ...));
1006 void pedwarn PRINTF_PROTO_1((char *, ...));
1007 void pedwarn_with_line PRINTF_PROTO_2((int, char *, ...));
1008 static void pedwarn_with_file_and_line PRINTF_PROTO_4((char *, size_t, int, char *, ...));
1010 static void print_containing_files PROTO((void));
1012 static int line_for_error PROTO((int));
1013 static int grow_outbuf PROTO((FILE_BUF *, int));
1015 static HASHNODE *install PROTO((U_CHAR *, int, enum node_type, char *, int));
1016 HASHNODE *lookup PROTO((U_CHAR *, int, int));
1017 static void delete_macro PROTO((HASHNODE *));
1018 static int hashf PROTO((U_CHAR *, int, int));
1020 static void dump_single_macro PROTO((HASHNODE *, FILE *));
1021 static void dump_all_macros PROTO((void));
1022 static void dump_defn_1 PROTO((U_CHAR *, int, int, FILE *));
1023 static void dump_arg_n PROTO((DEFINITION *, int, FILE *));
1025 static void initialize_char_syntax PROTO((void));
1026 static void initialize_builtins PROTO((FILE_BUF *, FILE_BUF *));
1028 static void make_definition PROTO((char *, FILE_BUF *));
1029 static void make_undef PROTO((char *, FILE_BUF *));
1031 static void make_assertion PROTO((char *, char *));
1033 static struct file_name_list *new_include_prefix PROTO((struct file_name_list *, char *, char *, char *));
1034 static void append_include_chain PROTO((struct file_name_list *, struct file_name_list *));
1036 static int quote_string_for_make PROTO((char *, char *));
1037 static void deps_output PROTO((char *, int));
1039 static void fatal PRINTF_PROTO_1((char *, ...)) __attribute__ ((noreturn));
1040 void fancy_abort PROTO((void)) __attribute__ ((noreturn));
1041 static void perror_with_name PROTO((char *));
1042 static void pfatal_with_name PROTO((char *)) __attribute__ ((noreturn));
1043 static void pipe_closed PROTO((int)) __attribute__ ((noreturn));
1045 static void memory_full PROTO((void)) __attribute__ ((noreturn));
1046 GENERIC_PTR xmalloc PROTO((size_t));
1047 static GENERIC_PTR xrealloc PROTO((GENERIC_PTR, size_t));
1048 static GENERIC_PTR xcalloc PROTO((size_t, size_t));
1049 static char *savestring PROTO((char *));
1051 /* Read LEN bytes at PTR from descriptor DESC, for file FILENAME,
1052 retrying if necessary. If MAX_READ_LEN is defined, read at most
1053 that bytes at a time. Return a negative value if an error occurs,
1054 otherwise return the actual number of bytes read,
1055 which must be LEN unless end-of-file was reached. */
1058 safe_read (desc, ptr, len)
1063 int left, rcount, nchars;
1069 if (rcount > MAX_READ_LEN)
1070 rcount = MAX_READ_LEN;
1072 nchars = read (desc, ptr, rcount);
1089 /* Write LEN bytes at PTR to descriptor DESC,
1090 retrying if necessary, and treating any real error as fatal.
1091 If MAX_WRITE_LEN is defined, write at most that many bytes at a time. */
1094 safe_write (desc, ptr, len)
1099 int wcount, written;
1103 #ifdef MAX_WRITE_LEN
1104 if (wcount > MAX_WRITE_LEN)
1105 wcount = MAX_WRITE_LEN;
1107 written = write (desc, ptr, wcount);
1114 pfatal_with_name (out_fname);
1121 /* Print a string to stderr, with extra handling in case it contains
1122 embedded NUL characters. Any present are written as is.
1124 Using fwrite for this purpose produces undesireable results on VMS
1125 when stderr happens to be a record oriented file, such as a batch log
1126 file, rather than a stream oriented one. */
1129 eprint_string (string, length)
1133 size_t segment_length;
1136 fprintf(stderr, "%s", string);
1137 length -= (segment_length = strlen(string));
1140 fputc('\0', stderr);
1142 /* Advance past the portion which has already been printed. */
1143 string += segment_length + 1;
1145 } while (length > 0);
1159 char **pend_files = (char **) xmalloc (argc * sizeof (char *));
1160 char **pend_defs = (char **) xmalloc (argc * sizeof (char *));
1161 char **pend_undefs = (char **) xmalloc (argc * sizeof (char *));
1162 char **pend_assertions = (char **) xmalloc (argc * sizeof (char *));
1163 char **pend_includes = (char **) xmalloc (argc * sizeof (char *));
1165 /* Record the option used with each element of pend_assertions.
1166 This is preparation for supporting more than one option for making
1168 char **pend_assertion_options = (char **) xmalloc (argc * sizeof (char *));
1169 int inhibit_predefs = 0;
1170 int no_standard_includes = 0;
1171 int no_standard_cplusplus_includes = 0;
1172 int missing_newline = 0;
1174 /* Non-0 means don't output the preprocessed program. */
1175 int inhibit_output = 0;
1176 /* Non-0 means -v, so print the full set of include dirs. */
1179 /* File name which deps are being written to.
1180 This is 0 if deps are being written to stdout. */
1181 char *deps_file = 0;
1182 /* Fopen file mode to open deps_file with. */
1183 char *deps_mode = "a";
1184 /* Stream on which to print the dependency information. */
1185 FILE *deps_stream = 0;
1186 /* Target-name to write with the dependency information. */
1187 char *deps_target = 0;
1189 #if defined (RLIMIT_STACK) && defined (HAVE_GETRLIMIT) && defined (HAVE_SETRLIMIT)
1190 /* Get rid of any avoidable limit on stack size. */
1194 /* Set the stack limit huge so that alloca (particularly stringtab
1195 in dbxread.c) does not fail. */
1196 getrlimit (RLIMIT_STACK, &rlim);
1197 rlim.rlim_cur = rlim.rlim_max;
1198 setrlimit (RLIMIT_STACK, &rlim);
1203 signal (SIGPIPE, pipe_closed);
1206 progname = base_name (argv[0]);
1210 /* Remove extension from PROGNAME. */
1212 char *s = progname = savestring (progname);
1214 if ((p = rindex (s, ';')) != 0) *p = '\0'; /* strip version number */
1215 if ((p = rindex (s, '.')) != 0 /* strip type iff ".exe" */
1216 && (p[1] == 'e' || p[1] == 'E')
1217 && (p[2] == 'x' || p[2] == 'X')
1218 && (p[3] == 'e' || p[3] == 'E')
1227 /* Initialize is_idchar. */
1228 initialize_char_syntax ();
1230 no_line_directives = 0;
1232 dump_macros = dump_none;
1235 cplusplus_comments = 1;
1237 bzero ((char *) pend_files, argc * sizeof (char *));
1238 bzero ((char *) pend_defs, argc * sizeof (char *));
1239 bzero ((char *) pend_undefs, argc * sizeof (char *));
1240 bzero ((char *) pend_assertions, argc * sizeof (char *));
1241 bzero ((char *) pend_includes, argc * sizeof (char *));
1243 /* Process switches and find input file name. */
1245 for (i = 1; i < argc; i++) {
1246 if (argv[i][0] != '-') {
1247 if (out_fname != NULL)
1248 fatal ("Usage: %s [switches] input output", argv[0]);
1249 else if (in_fname != NULL)
1250 out_fname = argv[i];
1254 switch (argv[i][1]) {
1257 if (!strcmp (argv[i], "-include")) {
1261 fatal ("Filename missing after `-include' option");
1263 simplify_filename (pend_includes[temp] = argv[++i]);
1265 if (!strcmp (argv[i], "-imacros")) {
1269 fatal ("Filename missing after `-imacros' option");
1271 simplify_filename (pend_files[temp] = argv[++i]);
1273 if (!strcmp (argv[i], "-iprefix")) {
1275 fatal ("Filename missing after `-iprefix' option");
1277 include_prefix = argv[++i];
1279 if (!strcmp (argv[i], "-ifoutput")) {
1280 output_conditionals = 1;
1282 if (!strcmp (argv[i], "-isystem")) {
1283 struct file_name_list *dirtmp;
1285 if (! (dirtmp = new_include_prefix (NULL_PTR, NULL_PTR,
1288 dirtmp->c_system_include_path = 1;
1290 if (before_system == 0)
1291 before_system = dirtmp;
1293 last_before_system->next = dirtmp;
1294 last_before_system = dirtmp; /* Tail follows the last one */
1296 /* Add directory to end of path for includes,
1297 with the default prefix at the front of its name. */
1298 if (!strcmp (argv[i], "-iwithprefix")) {
1299 struct file_name_list *dirtmp;
1302 if (include_prefix != 0)
1303 prefix = include_prefix;
1305 prefix = savestring (GCC_INCLUDE_DIR);
1306 /* Remove the `include' from /usr/local/lib/gcc.../include. */
1307 if (!strcmp (prefix + strlen (prefix) - 8, "/include"))
1308 prefix[strlen (prefix) - 7] = 0;
1311 if (! (dirtmp = new_include_prefix (NULL_PTR, NULL_PTR,
1312 prefix, argv[++i])))
1315 if (after_include == 0)
1316 after_include = dirtmp;
1318 last_after_include->next = dirtmp;
1319 last_after_include = dirtmp; /* Tail follows the last one */
1321 /* Add directory to main path for includes,
1322 with the default prefix at the front of its name. */
1323 if (!strcmp (argv[i], "-iwithprefixbefore")) {
1324 struct file_name_list *dirtmp;
1327 if (include_prefix != 0)
1328 prefix = include_prefix;
1330 prefix = savestring (GCC_INCLUDE_DIR);
1331 /* Remove the `include' from /usr/local/lib/gcc.../include. */
1332 if (!strcmp (prefix + strlen (prefix) - 8, "/include"))
1333 prefix[strlen (prefix) - 7] = 0;
1336 dirtmp = new_include_prefix (NULL_PTR, NULL_PTR, prefix, argv[++i]);
1337 append_include_chain (dirtmp, dirtmp);
1339 /* Add directory to end of path for includes. */
1340 if (!strcmp (argv[i], "-idirafter")) {
1341 struct file_name_list *dirtmp;
1343 if (! (dirtmp = new_include_prefix (NULL_PTR, NULL_PTR,
1347 if (after_include == 0)
1348 after_include = dirtmp;
1350 last_after_include->next = dirtmp;
1351 last_after_include = dirtmp; /* Tail follows the last one */
1356 if (out_fname != NULL)
1357 fatal ("Output filename specified twice");
1359 fatal ("Filename missing after -o option");
1360 out_fname = argv[++i];
1361 if (!strcmp (out_fname, "-"))
1366 if (!strcmp (argv[i], "-pedantic"))
1368 else if (!strcmp (argv[i], "-pedantic-errors")) {
1370 pedantic_errors = 1;
1371 } else if (!strcmp (argv[i], "-pcp")) {
1374 fatal ("Filename missing after -pcp option");
1375 pcp_fname = argv[++i];
1377 = ((pcp_fname[0] != '-' || pcp_fname[1] != '\0')
1378 ? fopen (pcp_fname, "w")
1380 if (pcp_outfile == 0)
1381 pfatal_with_name (pcp_fname);
1387 if (!strcmp (argv[i], "-traditional")) {
1389 cplusplus_comments = 0;
1390 } else if (!strcmp (argv[i], "-trigraphs")) {
1396 if (! strcmp (argv[i], "-lang-c"))
1397 cplusplus = 0, cplusplus_comments = 1, c89 = 0, objc = 0;
1398 if (! strcmp (argv[i], "-lang-c89"))
1399 cplusplus = 0, cplusplus_comments = 0, c89 = 1, objc = 0;
1400 if (! strcmp (argv[i], "-lang-c++"))
1401 cplusplus = 1, cplusplus_comments = 1, c89 = 0, objc = 0;
1402 if (! strcmp (argv[i], "-lang-objc"))
1403 cplusplus = 0, cplusplus_comments = 1, c89 = 0, objc = 1;
1404 if (! strcmp (argv[i], "-lang-objc++"))
1405 cplusplus = 1, cplusplus_comments = 1, c89 = 0, objc = 1;
1406 if (! strcmp (argv[i], "-lang-asm"))
1408 if (! strcmp (argv[i], "-lint"))
1413 cplusplus = 1, cplusplus_comments = 1;
1417 inhibit_warnings = 1;
1421 if (!strcmp (argv[i], "-Wtrigraphs"))
1423 else if (!strcmp (argv[i], "-Wno-trigraphs"))
1425 else if (!strcmp (argv[i], "-Wcomment"))
1427 else if (!strcmp (argv[i], "-Wno-comment"))
1429 else if (!strcmp (argv[i], "-Wcomments"))
1431 else if (!strcmp (argv[i], "-Wno-comments"))
1433 else if (!strcmp (argv[i], "-Wtraditional"))
1435 else if (!strcmp (argv[i], "-Wno-traditional"))
1437 else if (!strcmp (argv[i], "-Wundef"))
1439 else if (!strcmp (argv[i], "-Wno-undef"))
1441 else if (!strcmp (argv[i], "-Wimport"))
1443 else if (!strcmp (argv[i], "-Wno-import"))
1445 else if (!strcmp (argv[i], "-Werror"))
1446 warnings_are_errors = 1;
1447 else if (!strcmp (argv[i], "-Wno-error"))
1448 warnings_are_errors = 0;
1449 else if (!strcmp (argv[i], "-Wall"))
1457 /* The style of the choices here is a bit mixed.
1458 The chosen scheme is a hybrid of keeping all options in one string
1459 and specifying each option in a separate argument:
1460 -M|-MM|-MD file|-MMD file [-MG]. An alternative is:
1461 -M|-MM|-MD file|-MMD file|-MG|-MMG; or more concisely:
1462 -M[M][G][D file]. This is awkward to handle in specs, and is not
1464 /* ??? -MG must be specified in addition to one of -M or -MM.
1465 This can be relaxed in the future without breaking anything.
1466 The converse isn't true. */
1468 /* -MG isn't valid with -MD or -MMD. This is checked for later. */
1469 if (!strcmp (argv[i], "-MG"))
1471 print_deps_missing_files = 1;
1474 if (!strcmp (argv[i], "-M"))
1476 else if (!strcmp (argv[i], "-MM"))
1478 else if (!strcmp (argv[i], "-MD"))
1480 else if (!strcmp (argv[i], "-MMD"))
1482 /* For -MD and -MMD options, write deps on file named by next arg. */
1483 if (!strcmp (argv[i], "-MD")
1484 || !strcmp (argv[i], "-MMD")) {
1486 fatal ("Filename missing after %s option", argv[i]);
1488 deps_file = argv[i];
1491 /* For -M and -MM, write deps on standard output
1492 and suppress the usual output. */
1493 deps_stream = stdout;
1500 char *p = argv[i] + 2;
1502 while ((c = *p++)) {
1503 /* Arg to -d specifies what parts of macros to dump */
1506 dump_macros = dump_only;
1510 dump_macros = dump_names;
1513 dump_macros = dump_definitions;
1524 if (argv[i][2] == '3')
1529 fprintf (stderr, "GNU CPP version %s", version_string);
1530 #ifdef TARGET_VERSION
1533 fprintf (stderr, "\n");
1538 print_include_names = 1;
1542 if (argv[i][2] != 0)
1543 pend_defs[i] = argv[i] + 2;
1544 else if (i + 1 == argc)
1545 fatal ("Macro name missing after -D option");
1547 i++, pend_defs[i] = argv[i];
1554 if (argv[i][2] != 0)
1556 else if (i + 1 == argc)
1557 fatal ("Assertion missing after -A option");
1561 if (!strcmp (p, "-")) {
1562 /* -A- eliminates all predefined macros and assertions.
1563 Let's include also any that were specified earlier
1564 on the command line. That way we can get rid of any
1565 that were passed automatically in from GCC. */
1567 inhibit_predefs = 1;
1568 for (j = 0; j < i; j++)
1569 pend_defs[j] = pend_assertions[j] = 0;
1571 pend_assertions[i] = p;
1572 pend_assertion_options[i] = "-A";
1577 case 'U': /* JF #undef something */
1578 if (argv[i][2] != 0)
1579 pend_undefs[i] = argv[i] + 2;
1580 else if (i + 1 == argc)
1581 fatal ("Macro name missing after -U option");
1583 pend_undefs[i] = argv[i+1], i++;
1587 put_out_comments = 1;
1590 case 'E': /* -E comes from cc -E; ignore it. */
1594 no_line_directives = 1;
1597 case '$': /* Don't include $ in identifiers. */
1598 is_idchar['$'] = is_idstart['$'] = 0;
1601 case 'I': /* Add directory to path for includes. */
1603 struct file_name_list *dirtmp;
1605 if (! ignore_srcdir && !strcmp (argv[i] + 2, "-")) {
1607 /* Don't use any preceding -I directories for #include <...>. */
1608 first_bracket_include = 0;
1611 dirtmp = new_include_prefix (last_include, NULL_PTR, "",
1612 argv[i][2] ? argv[i] + 2 : argv[++i]);
1613 append_include_chain (dirtmp, dirtmp);
1619 if (!strcmp (argv[i], "-nostdinc"))
1620 /* -nostdinc causes no default include directories.
1621 You must specify all include-file directories with -I. */
1622 no_standard_includes = 1;
1623 else if (!strcmp (argv[i], "-nostdinc++"))
1624 /* -nostdinc++ causes no default C++-specific include directories. */
1625 no_standard_cplusplus_includes = 1;
1626 else if (!strcmp (argv[i], "-noprecomp"))
1631 if (!strcmp (argv[i], "-remap"))
1636 /* Sun compiler passes undocumented switch "-undef".
1637 Let's assume it means to inhibit the predefined symbols. */
1638 inhibit_predefs = 1;
1641 case '\0': /* JF handle '-' as file name meaning stdin or stdout */
1642 if (in_fname == NULL) {
1645 } else if (out_fname == NULL) {
1648 } /* else fall through into error */
1651 fatal ("Invalid option `%s'", argv[i]);
1656 /* Add dirs from CPATH after dirs from -I. */
1657 /* There seems to be confusion about what CPATH should do,
1658 so for the moment it is not documented. */
1659 /* Some people say that CPATH should replace the standard include dirs,
1660 but that seems pointless: it comes before them, so it overrides them
1662 GET_ENVIRONMENT (cp, "CPATH");
1663 if (cp && ! no_standard_includes)
1666 /* Initialize output buffer */
1668 outbuf.buf = (U_CHAR *) xmalloc (OUTBUF_SIZE);
1669 outbuf.bufp = outbuf.buf;
1670 outbuf.length = OUTBUF_SIZE;
1672 /* Do partial setup of input buffer for the sake of generating
1673 early #line directives (when -g is in effect). */
1675 fp = &instack[++indepth];
1676 if (in_fname == NULL)
1678 fp->nominal_fname = fp->fname = in_fname;
1679 fp->nominal_fname_len = strlen (in_fname);
1682 /* In C++, wchar_t is a distinct basic type, and we can expect
1683 __wchar_t to be defined by cc1plus. */
1685 wchar_type = "__wchar_t";
1687 /* Install __LINE__, etc. Must follow initialize_char_syntax
1688 and option processing. */
1689 initialize_builtins (fp, &outbuf);
1691 /* Do standard #defines and assertions
1692 that identify system and machine type. */
1694 if (!inhibit_predefs) {
1695 char *p = (char *) alloca (strlen (predefs) + 1);
1698 struct dsc$descriptor_s lcl_name;
1700 unsigned short length; /* input length */
1701 unsigned short code; /* item code */
1702 unsigned long dptr; /* data ptr */
1703 unsigned long lptr; /* output length ptr */
1706 unsigned long syi_length;
1709 struct item_list items[] = {
1710 { 16, SYI$_VERSION, 0, 0 },
1714 items[0].dptr = (unsigned long)syi_data;
1715 items[0].lptr = (unsigned long)(&syi_length);
1717 if (SYS$GETSYIW (0, 0, 0, items, NULL, NULL, NULL, NULL) == SS$_NORMAL)
1719 unsigned long vms_version_value;
1723 vms_version_value = 0;
1727 if (ISDIGIT (*vers))
1729 vms_version_value = (*vers - '0') * 10000000;
1735 if (ISDIGIT (*vers))
1737 vms_version_value += (*vers - '0') * 100000;
1741 if (vms_version_value > 0)
1745 sprintf (versbuf, "__VMS_VER=%08ld", vms_version_value);
1747 output_line_directive (fp, &outbuf, 0, same_file);
1748 make_definition (versbuf, &outbuf);
1753 strcpy (p, predefs);
1756 while (*p == ' ' || *p == '\t')
1758 /* Handle -D options. */
1759 if (p[0] == '-' && p[1] == 'D') {
1761 while (*p && *p != ' ' && *p != '\t')
1766 output_line_directive (fp, &outbuf, 0, same_file);
1767 make_definition (q, &outbuf);
1768 while (*p == ' ' || *p == '\t')
1770 } else if (p[0] == '-' && p[1] == 'A') {
1771 /* Handle -A options (assertions). */
1780 past_name = assertion;
1781 /* Locate end of name. */
1782 while (*past_name && *past_name != ' '
1783 && *past_name != '\t' && *past_name != '(')
1785 /* Locate `(' at start of value. */
1787 while (*value && (*value == ' ' || *value == '\t'))
1789 if (*value++ != '(')
1791 while (*value && (*value == ' ' || *value == '\t'))
1794 /* Locate end of value. */
1795 while (*past_value && *past_value != ' '
1796 && *past_value != '\t' && *past_value != ')')
1798 termination = past_value;
1799 while (*termination && (*termination == ' ' || *termination == '\t'))
1801 if (*termination++ != ')')
1803 if (*termination && *termination != ' ' && *termination != '\t')
1805 /* Temporarily null-terminate the value. */
1806 save_char = *termination;
1807 *termination = '\0';
1808 /* Install the assertion. */
1809 make_assertion ("-A", assertion);
1810 *termination = (char) save_char;
1812 while (*p == ' ' || *p == '\t')
1820 /* Now handle the command line options. */
1822 /* Do -U's, -D's and -A's in the order they were seen. */
1823 for (i = 1; i < argc; i++) {
1824 if (pend_undefs[i]) {
1826 output_line_directive (fp, &outbuf, 0, same_file);
1827 make_undef (pend_undefs[i], &outbuf);
1831 output_line_directive (fp, &outbuf, 0, same_file);
1832 make_definition (pend_defs[i], &outbuf);
1834 if (pend_assertions[i])
1835 make_assertion (pend_assertion_options[i], pend_assertions[i]);
1838 done_initializing = 1;
1840 { /* Read the appropriate environment variable and if it exists
1841 replace include_defaults with the listed path. */
1843 switch ((objc << 1) + cplusplus)
1846 GET_ENVIRONMENT (epath, "C_INCLUDE_PATH");
1849 GET_ENVIRONMENT (epath, "CPLUS_INCLUDE_PATH");
1852 GET_ENVIRONMENT (epath, "OBJC_INCLUDE_PATH");
1855 GET_ENVIRONMENT (epath, "OBJCPLUS_INCLUDE_PATH");
1858 /* If the environment var for this language is set,
1859 add to the default list of include directories. */
1862 char *startp, *endp;
1864 for (num_dirs = 1, startp = epath; *startp; startp++)
1865 if (*startp == PATH_SEPARATOR)
1868 = (struct default_include *) xmalloc ((num_dirs
1869 * sizeof (struct default_include))
1870 + sizeof (include_defaults_array));
1871 startp = endp = epath;
1875 if (c == PATH_SEPARATOR || !c) {
1877 include_defaults[num_dirs].fname
1878 = startp == endp ? "." : savestring (startp);
1880 include_defaults[num_dirs].component = 0;
1881 include_defaults[num_dirs].cplusplus = cplusplus;
1882 include_defaults[num_dirs].cxx_aware = 1;
1889 /* Put the usual defaults back in at the end. */
1890 bcopy ((char *) include_defaults_array,
1891 (char *) &include_defaults[num_dirs],
1892 sizeof (include_defaults_array));
1896 append_include_chain (before_system, last_before_system);
1897 first_system_include = before_system;
1899 /* Unless -fnostdinc,
1900 tack on the standard include file dirs to the specified list */
1901 if (!no_standard_includes) {
1902 struct default_include *p = include_defaults;
1903 char *specd_prefix = include_prefix;
1904 char *default_prefix = savestring (GCC_INCLUDE_DIR);
1905 int default_len = 0;
1906 /* Remove the `include' from /usr/local/lib/gcc.../include. */
1907 if (!strcmp (default_prefix + strlen (default_prefix) - 8, "/include")) {
1908 default_len = strlen (default_prefix) - 7;
1909 default_prefix[default_len] = 0;
1911 /* Search "translated" versions of GNU directories.
1912 These have /usr/local/lib/gcc... replaced by specd_prefix. */
1913 if (specd_prefix != 0 && default_len != 0)
1914 for (p = include_defaults; p->fname; p++) {
1915 /* Some standard dirs are only for C++. */
1916 if (!p->cplusplus || (cplusplus && !no_standard_cplusplus_includes)) {
1917 /* Does this dir start with the prefix? */
1918 if (!strncmp (p->fname, default_prefix, default_len)) {
1919 /* Yes; change prefix and add to search list. */
1920 struct file_name_list *new
1921 = new_include_prefix (NULL_PTR, NULL_PTR, specd_prefix,
1922 p->fname + default_len);
1924 new->c_system_include_path = !p->cxx_aware;
1925 append_include_chain (new, new);
1926 if (first_system_include == 0)
1927 first_system_include = new;
1932 /* Search ordinary names for GNU include directories. */
1933 for (p = include_defaults; p->fname; p++) {
1934 /* Some standard dirs are only for C++. */
1935 if (!p->cplusplus || (cplusplus && !no_standard_cplusplus_includes)) {
1936 struct file_name_list *new
1937 = new_include_prefix (NULL_PTR, p->component, "", p->fname);
1939 new->c_system_include_path = !p->cxx_aware;
1940 append_include_chain (new, new);
1941 if (first_system_include == 0)
1942 first_system_include = new;
1948 /* Tack the after_include chain at the end of the include chain. */
1949 append_include_chain (after_include, last_after_include);
1950 if (first_system_include == 0)
1951 first_system_include = after_include;
1953 /* With -v, print the list of dirs to search. */
1955 struct file_name_list *p;
1956 fprintf (stderr, "#include \"...\" search starts here:\n");
1957 for (p = include; p; p = p->next) {
1958 if (p == first_bracket_include)
1959 fprintf (stderr, "#include <...> search starts here:\n");
1961 fprintf (stderr, " .\n");
1962 else if (!strcmp (p->fname, "/") || !strcmp (p->fname, "//"))
1963 fprintf (stderr, " %s\n", p->fname);
1965 /* Omit trailing '/'. */
1966 fprintf (stderr, " %.*s\n", (int) strlen (p->fname) - 1, p->fname);
1968 fprintf (stderr, "End of search list.\n");
1971 /* -MG doesn't select the form of output and must be specified with one of
1972 -M or -MM. -MG doesn't make sense with -MD or -MMD since they don't
1973 inhibit compilation. */
1974 if (print_deps_missing_files && (print_deps == 0 || !inhibit_output))
1975 fatal ("-MG must be specified with one of -M or -MM");
1977 /* Either of two environment variables can specify output of deps.
1978 Its value is either "OUTPUT_FILE" or "OUTPUT_FILE DEPS_TARGET",
1979 where OUTPUT_FILE is the file to write deps info to
1980 and DEPS_TARGET is the target to mention in the deps. */
1983 && (getenv ("SUNPRO_DEPENDENCIES") != 0
1984 || getenv ("DEPENDENCIES_OUTPUT") != 0)) {
1985 char *spec = getenv ("DEPENDENCIES_OUTPUT");
1990 spec = getenv ("SUNPRO_DEPENDENCIES");
1997 /* Find the space before the DEPS_TARGET, if there is one. */
1998 /* This should use index. (mrs) */
1999 while (*s != 0 && *s != ' ') s++;
2001 deps_target = s + 1;
2002 output_file = xmalloc (s - spec + 1);
2003 bcopy (spec, output_file, s - spec);
2004 output_file[s - spec] = 0;
2011 deps_file = output_file;
2015 /* For -M, print the expected object file name
2016 as the target of this Make-rule. */
2018 deps_allocated_size = 200;
2019 deps_buffer = xmalloc (deps_allocated_size);
2025 deps_output (deps_target, ':');
2026 } else if (*in_fname == 0) {
2027 deps_output ("-", ':');
2032 q = base_name (in_fname);
2034 /* Copy remainder to mungable area. */
2035 p = (char *) alloca (strlen(q) + 8);
2038 /* Output P, but remove known suffixes. */
2042 && p[len - 2] == '.'
2043 && index("cCsSm", p[len - 1]))
2046 && p[len - 3] == '.'
2047 && p[len - 2] == 'c'
2048 && p[len - 1] == 'c')
2051 && p[len - 4] == '.'
2052 && p[len - 3] == 'c'
2053 && p[len - 2] == 'x'
2054 && p[len - 1] == 'x')
2057 && p[len - 4] == '.'
2058 && p[len - 3] == 'c'
2059 && p[len - 2] == 'p'
2060 && p[len - 1] == 'p')
2063 /* Supply our own suffix. */
2064 strcpy (q, OBJECT_SUFFIX);
2066 deps_output (p, ':');
2067 deps_output (in_fname, ' ');
2071 /* Scan the -imacros files before the main input.
2072 Much like #including them, but with no_output set
2073 so that only their macro definitions matter. */
2075 no_output++; no_record_file++;
2076 for (i = 1; i < argc; i++)
2077 if (pend_files[i]) {
2078 struct include_file *inc;
2079 int fd = open_include_file (pend_files[i], NULL_PTR, NULL_PTR, &inc);
2081 perror_with_name (pend_files[i]);
2082 return FATAL_EXIT_CODE;
2084 finclude (fd, inc, &outbuf, 0, NULL_PTR);
2086 no_output--; no_record_file--;
2088 /* Copy the entire contents of the main input file into
2089 the stacked input buffer previously allocated for it. */
2091 /* JF check for stdin */
2092 if (in_fname == NULL || *in_fname == 0) {
2095 } else if ((f = open (in_fname, O_RDONLY, 0666)) < 0)
2098 if (fstat (f, &st) != 0)
2099 pfatal_with_name (in_fname);
2100 fp->nominal_fname = fp->fname = in_fname;
2101 fp->nominal_fname_len = strlen (in_fname);
2103 fp->system_header_p = 0;
2104 /* JF all this is mine about reading pipes and ttys */
2105 if (! S_ISREG (st.st_mode)) {
2106 /* Read input from a file that is not a normal disk file.
2107 We cannot preallocate a buffer with the correct size,
2108 so we must read in the file a piece at the time and make it bigger. */
2113 if (S_ISDIR (st.st_mode))
2114 fatal ("Input file `%s' is a directory", in_fname);
2118 fp->buf = (U_CHAR *) xmalloc (bsize + 2);
2120 cnt = safe_read (f, (char *) fp->buf + size, bsize - size);
2121 if (cnt < 0) goto perror; /* error! */
2123 if (size != bsize) break; /* End of file */
2125 fp->buf = (U_CHAR *) xrealloc (fp->buf, bsize + 2);
2129 /* Read a file whose size we can determine in advance.
2130 For the sake of VMS, st.st_size is just an upper bound. */
2131 size_t s = (size_t) st.st_size;
2132 if (s != st.st_size || s + 2 < s)
2134 fp->buf = (U_CHAR *) xmalloc (s + 2);
2135 fp->length = safe_read (f, (char *) fp->buf, s);
2136 if (fp->length < 0) goto perror;
2139 fp->if_stack = if_stack;
2141 /* Make sure data ends with a newline. And put a null after it. */
2143 if ((fp->length > 0 && fp->buf[fp->length - 1] != '\n')
2144 /* Backslash-newline at end is not good enough. */
2145 || (fp->length > 1 && fp->buf[fp->length - 2] == '\\')) {
2146 fp->buf[fp->length++] = '\n';
2147 missing_newline = 1;
2149 fp->buf[fp->length] = '\0';
2151 /* Unless inhibited, convert trigraphs in the input. */
2156 /* Now that we know the input file is valid, open the output. */
2158 if (!out_fname || !strcmp (out_fname, ""))
2159 out_fname = "stdout";
2160 else if (! freopen (out_fname, "w", stdout))
2161 pfatal_with_name (out_fname);
2163 output_line_directive (fp, &outbuf, 0, same_file);
2165 /* Scan the -include files before the main input. */
2168 for (i = 1; i < argc; i++)
2169 if (pend_includes[i]) {
2170 struct include_file *inc;
2171 int fd = open_include_file (pend_includes[i], NULL_PTR, NULL_PTR, &inc);
2173 perror_with_name (pend_includes[i]);
2174 return FATAL_EXIT_CODE;
2176 finclude (fd, inc, &outbuf, 0, NULL_PTR);
2180 /* Scan the input, processing macros and directives. */
2182 rescan (&outbuf, 0);
2184 if (missing_newline)
2187 if (pedantic && missing_newline)
2188 pedwarn ("file does not end in newline");
2190 /* Now we have processed the entire input
2191 Write whichever kind of output has been requested. */
2193 if (dump_macros == dump_only)
2195 else if (! inhibit_output) {
2200 /* Don't actually write the deps file if compilation has failed. */
2202 if (deps_file && ! (deps_stream = fopen (deps_file, deps_mode)))
2203 pfatal_with_name (deps_file);
2204 fputs (deps_buffer, deps_stream);
2205 putc ('\n', deps_stream);
2207 if (ferror (deps_stream) || fclose (deps_stream) != 0)
2208 fatal ("I/O error on output");
2213 if (pcp_outfile && pcp_outfile != stdout
2214 && (ferror (pcp_outfile) || fclose (pcp_outfile) != 0))
2215 fatal ("I/O error on `-pcp' output");
2217 if (ferror (stdout) || fclose (stdout) != 0)
2218 fatal ("I/O error on output");
2221 exit (FATAL_EXIT_CODE);
2222 exit (SUCCESS_EXIT_CODE);
2225 pfatal_with_name (in_fname);
2229 /* Given a colon-separated list of file names PATH,
2230 add all the names to the search path for include files. */
2244 struct file_name_list *dirtmp;
2246 /* Find the end of this name. */
2247 while ((c = *q++) != PATH_SEPARATOR && c)
2251 dirtmp = new_include_prefix (last_include, NULL_PTR,
2252 "", p == q ? "." : p);
2254 append_include_chain (dirtmp, dirtmp);
2256 /* Advance past this name. */
2263 /* Return the address of the first character in S that equals C.
2264 S is an array of length N, possibly containing '\0's, and followed by '\0'.
2265 Return 0 if there is no such character. Assume that C itself is not '\0'.
2266 If we knew we could use memchr, we could just invoke memchr (S, C, N),
2267 but unfortunately memchr isn't autoconfigured yet. */
2275 char *p = (char *) s;
2277 char *q = index (p, c);
2279 return (U_CHAR *) q;
2281 size_t l = strlen (p);
2291 /* Pre-C-Preprocessor to translate ANSI trigraph idiocy in BUF
2292 before main CCCP processing. Name `pcp' is also in honor of the
2293 drugs the trigraph designers must have been on.
2295 Using an extra pass through the buffer takes a little extra time,
2296 but is infinitely less hairy than trying to handle trigraphs inside
2297 strings, etc. everywhere, and also makes sure that trigraphs are
2298 only translated in the top level of processing. */
2304 register U_CHAR c, *fptr, *bptr, *sptr, *lptr;
2307 fptr = bptr = sptr = buf->buf;
2308 lptr = fptr + buf->length;
2309 while ((sptr = index0 (sptr, '?', (size_t) (lptr - sptr))) != NULL) {
2346 len = sptr - fptr - 2;
2348 /* BSD doc says bcopy () works right for overlapping strings. In ANSI
2349 C, this will be memmove (). */
2350 if (bptr != fptr && len > 0)
2351 bcopy ((char *) fptr, (char *) bptr, len);
2357 len = buf->length - (fptr - buf->buf);
2358 if (bptr != fptr && len > 0)
2359 bcopy ((char *) fptr, (char *) bptr, len);
2360 buf->length -= fptr - bptr;
2361 buf->buf[buf->length] = '\0';
2362 if (warn_trigraphs && fptr != bptr)
2363 warning_with_line (0, "%lu trigraph(s) encountered",
2364 (unsigned long) (fptr - bptr) / 2);
2367 /* Move all backslash-newline pairs out of embarrassing places.
2368 Exchange all such pairs following BP
2369 with any potentially-embarrassing characters that follow them.
2370 Potentially-embarrassing characters are / and *
2371 (because a backslash-newline inside a comment delimiter
2372 would cause it not to be recognized). */
2378 register U_CHAR *p = bp;
2380 /* First count the backslash-newline pairs here. */
2382 while (p[0] == '\\' && p[1] == '\n')
2385 /* What follows the backslash-newlines is not embarrassing. */
2387 if (*p != '/' && *p != '*')
2390 /* Copy all potentially embarrassing characters
2391 that follow the backslash-newline pairs
2392 down to where the pairs originally started. */
2394 while (*p == '*' || *p == '/')
2397 /* Now write the same number of pairs after the embarrassing chars. */
2404 /* Like newline_fix but for use within a directive-name.
2405 Move any backslash-newlines up past any following symbol constituents. */
2408 name_newline_fix (bp)
2411 register U_CHAR *p = bp;
2413 /* First count the backslash-newline pairs here. */
2414 while (p[0] == '\\' && p[1] == '\n')
2417 /* What follows the backslash-newlines is not embarrassing. */
2422 /* Copy all potentially embarrassing characters
2423 that follow the backslash-newline pairs
2424 down to where the pairs originally started. */
2426 while (is_idchar[*p])
2429 /* Now write the same number of pairs after the embarrassing chars. */
2436 /* Look for lint commands in comments.
2438 When we come in here, ibp points into a comment. Limit is as one expects.
2439 scan within the comment -- it should start, after lwsp, with a lint command.
2440 If so that command is returned as a (constant) string.
2442 Upon return, any arg will be pointed to with argstart and will be
2443 arglen long. Note that we don't parse that arg since it will just
2444 be printed out again. */
2447 get_lintcmd (ibp, limit, argstart, arglen, cmdlen)
2448 register U_CHAR *ibp;
2449 register U_CHAR *limit;
2450 U_CHAR **argstart; /* point to command arg */
2451 int *arglen, *cmdlen; /* how long they are */
2453 HOST_WIDE_INT linsize;
2454 register U_CHAR *numptr; /* temp for arg parsing */
2458 SKIP_WHITE_SPACE (ibp);
2460 if (ibp >= limit) return NULL;
2462 linsize = limit - ibp;
2464 /* Oh, I wish C had lexical functions... hell, I'll just open-code the set */
2465 if ((linsize >= 10) && !bcmp (ibp, "NOTREACHED", 10)) {
2467 return "NOTREACHED";
2469 if ((linsize >= 8) && !bcmp (ibp, "ARGSUSED", 8)) {
2473 if ((linsize >= 11) && !bcmp (ibp, "LINTLIBRARY", 11)) {
2475 return "LINTLIBRARY";
2477 if ((linsize >= 7) && !bcmp (ibp, "VARARGS", 7)) {
2479 ibp += 7; linsize -= 7;
2480 if ((linsize == 0) || ! ISDIGIT (*ibp)) return "VARARGS";
2482 /* OK, read a number */
2483 for (numptr = *argstart = ibp; (numptr < limit) && ISDIGIT (*numptr);
2485 *arglen = numptr - *argstart;
2492 * The main loop of the program.
2494 * Read characters from the input stack, transferring them to the
2497 * Macros are expanded and push levels on the input stack.
2498 * At the end of such a level it is popped off and we keep reading.
2499 * At the end of any other kind of level, we return.
2500 * #-directives are handled, except within macros.
2502 * If OUTPUT_MARKS is nonzero, keep Newline markers found in the input
2503 * and insert them when appropriate. This is set while scanning macro
2504 * arguments before substitution. It is zero when scanning for final output.
2505 * There are three types of Newline markers:
2506 * * Newline - follows a macro name that was not expanded
2507 * because it appeared inside an expansion of the same macro.
2508 * This marker prevents future expansion of that identifier.
2509 * When the input is rescanned into the final output, these are deleted.
2510 * These are also deleted by ## concatenation.
2511 * * Newline Space (or Newline and any other whitespace character)
2512 * stands for a place that tokens must be separated or whitespace
2513 * is otherwise desirable, but where the ANSI standard specifies there
2514 * is no whitespace. This marker turns into a Space (or whichever other
2515 * whitespace char appears in the marker) in the final output,
2516 * but it turns into nothing in an argument that is stringified with #.
2517 * Such stringified arguments are the only place where the ANSI standard
2518 * specifies with precision that whitespace may not appear.
2520 * During this function, IP->bufp is kept cached in IBP for speed of access.
2521 * Likewise, OP->bufp is kept in OBP. Before calling a subroutine
2522 * IBP, IP and OBP must be copied back to memory. IP and IBP are
2523 * copied back with the RECACHE macro. OBP must be copied back from OP->bufp
2524 * explicitly, and before RECACHE, since RECACHE uses OBP.
2528 rescan (op, output_marks)
2532 /* Character being scanned in main loop. */
2535 /* Length of pending accumulated identifier. */
2536 register int ident_length = 0;
2538 /* Hash code of pending accumulated identifier. */
2539 register int hash = 0;
2541 /* Current input level (&instack[indepth]). */
2544 /* Pointer for scanning input. */
2545 register U_CHAR *ibp;
2547 /* Pointer to end of input. End of scan is controlled by LIMIT. */
2548 register U_CHAR *limit;
2550 /* Pointer for storing output. */
2551 register U_CHAR *obp;
2553 /* REDO_CHAR is nonzero if we are processing an identifier
2554 after backing up over the terminating character.
2555 Sometimes we process an identifier without backing up over
2556 the terminating character, if the terminating character
2557 is not special. Backing up is done so that the terminating character
2558 will be dispatched on again once the identifier is dealt with. */
2561 /* 1 if within an identifier inside of which a concatenation
2562 marker (Newline -) has been seen. */
2563 int concatenated = 0;
2565 /* While scanning a comment or a string constant,
2566 this records the line it started on, for error messages. */
2569 /* Record position of last `real' newline. */
2570 U_CHAR *beg_of_line;
2572 /* Pop the innermost input stack level, assuming it is a macro expansion. */
2575 do { ip->macro->type = T_MACRO; \
2576 if (ip->free_ptr) free (ip->free_ptr); \
2577 --indepth; } while (0)
2579 /* Reload `rescan's local variables that describe the current
2580 level of the input stack. */
2583 do { ip = &instack[indepth]; \
2585 limit = ip->buf + ip->length; \
2587 check_expand (op, limit - ibp); \
2589 obp = op->bufp; } while (0)
2591 if (no_output && instack[indepth].fname != 0)
2592 skip_if_group (&instack[indepth], 1, NULL);
2599 /* Our caller must always put a null after the end of
2600 the input at each input stack level. */
2610 if (*ibp == '\n' && !ip->macro) {
2611 /* At the top level, always merge lines ending with backslash-newline,
2612 even in middle of identifier. But do not merge lines in a macro,
2613 since backslash might be followed by a newline-space marker. */
2616 --obp; /* remove backslash from obuf */
2619 /* If ANSI, backslash is just another character outside a string. */
2622 /* Otherwise, backslash suppresses specialness of following char,
2623 so copy it here to prevent the switch from seeing it.
2624 But first get any pending identifier processed. */
2625 if (ident_length > 0)
2632 if (ident_length || ip->macro || traditional)
2634 while (*ibp == '\\' && ibp[1] == '\n') {
2640 /* Treat this %: digraph as if it were #. */
2644 if (assertions_flag) {
2647 /* Copy #foo (bar lose) without macro expansion. */
2648 obp[-1] = '#'; /* In case it was '%'. */
2649 SKIP_WHITE_SPACE (ibp);
2650 while (is_idchar[*ibp])
2652 SKIP_WHITE_SPACE (ibp);
2655 skip_paren_group (ip);
2656 bcopy ((char *) ibp, (char *) obp, ip->bufp - ibp);
2657 obp += ip->bufp - ibp;
2663 /* If this is expanding a macro definition, don't recognize
2664 preprocessing directives. */
2667 /* If this is expand_into_temp_buffer,
2668 don't recognize them either. Warn about them
2669 only after an actual newline at this level,
2670 not at the beginning of the input level. */
2672 if (ip->buf != beg_of_line)
2673 warning ("preprocessing directive not recognized within macro arg");
2680 /* # keyword: a # must be first nonblank char on the line */
2681 if (beg_of_line == 0)
2686 /* Scan from start of line, skipping whitespace, comments
2687 and backslash-newlines, and see if we reach this #.
2688 If not, this # is not special. */
2690 /* If -traditional, require # to be at beginning of line. */
2693 if (is_hor_space[*bp])
2695 else if (*bp == '\\' && bp[1] == '\n')
2697 else if (*bp == '/' && bp[1] == '*') {
2699 while (!(*bp == '*' && bp[1] == '/'))
2703 /* There is no point in trying to deal with C++ // comments here,
2704 because if there is one, then this # must be part of the
2705 comment and we would never reach here. */
2711 while (bp[1] == '\\' && bp[2] == '\n')
2715 /* %: appears at start of line; skip past the ':' too. */
2724 /* This # can start a directive. */
2726 --obp; /* Don't copy the '#' */
2730 if (! handle_directive (ip, op)) {
2734 /* Not a known directive: treat it as ordinary text.
2735 IP, OP, IBP, etc. have not been changed. */
2736 if (no_output && instack[indepth].fname) {
2737 /* If not generating expanded output,
2738 what we do with ordinary text is skip it.
2739 Discard everything until next # directive. */
2740 skip_if_group (&instack[indepth], 1, 0);
2745 *obp++ = '#'; /* Copy # (even if it was originally %:). */
2746 /* Don't expand an identifier that could be a macro directive.
2747 (Section 3.8.3 of the ANSI C standard) */
2748 SKIP_WHITE_SPACE (ibp);
2749 if (is_idstart[*ibp])
2752 while (is_idchar[*ibp])
2760 /* A # directive has been successfully processed. */
2761 /* If not generating expanded output, ignore everything until
2762 next # directive. */
2763 if (no_output && instack[indepth].fname)
2764 skip_if_group (&instack[indepth], 1, 0);
2770 case '\"': /* skip quoted string */
2772 /* A single quoted string is treated like a double -- some
2773 programs (e.g., troff) are perverse this way */
2775 /* Handle any pending identifier;
2776 but the L in L'...' or L"..." is not an identifier. */
2778 if (! (ident_length == 1 && hash == HASHSTEP (0, 'L')))
2780 ident_length = hash = 0;
2783 start_line = ip->lineno;
2785 /* Skip ahead to a matching quote. */
2789 if (ip->macro != 0) {
2790 /* try harder: this string crosses a macro expansion boundary.
2791 This can happen naturally if -traditional.
2792 Otherwise, only -D can make a macro with an unmatched quote. */
2798 error_with_line (line_for_error (start_line),
2799 "unterminated string or character constant");
2800 if (multiline_string_line) {
2801 error_with_line (multiline_string_line,
2802 "possible real start of unterminated constant");
2803 multiline_string_line = 0;
2813 /* Traditionally, end of line ends a string constant with no error.
2814 So exit the loop and record the new line. */
2820 error_with_line (line_for_error (start_line),
2821 "unterminated character constant");
2824 if (multiline_string_line == 0) {
2826 pedwarn_with_line (line_for_error (start_line),
2827 "string constant runs past end of line");
2828 multiline_string_line = ip->lineno - 1;
2834 /* Backslash newline is replaced by nothing at all, but
2835 keep the line counts correct. But if we are reading
2836 from a macro, keep the backslash newline, since backslash
2837 newlines have already been processed. */
2845 /* ANSI stupidly requires that in \\ the second \
2846 is *not* prevented from combining with a newline. */
2848 while (*ibp == '\\' && ibp[1] == '\n') {
2870 if (*ibp == '\\' && ibp[1] == '\n')
2873 && !(cplusplus_comments && *ibp == '/'))
2879 /* C++ style comment... */
2880 start_line = ip->lineno;
2882 /* Comments are equivalent to spaces. */
2883 if (! put_out_comments)
2887 U_CHAR *before_bp = ibp;
2889 while (++ibp < limit) {
2891 if (ibp[-1] != '\\') {
2892 if (put_out_comments) {
2893 bcopy ((char *) before_bp, (char *) obp, ibp - before_bp);
2894 obp += ibp - before_bp;
2899 warning ("multiline `//' comment");
2901 /* Copy the newline into the output buffer, in order to
2902 avoid the pain of a #line every time a multiline comment
2904 if (!put_out_comments)
2913 /* Ordinary C comment. Skip it, optionally copying it to output. */
2915 start_line = ip->lineno;
2917 ++ibp; /* Skip the star. */
2919 /* If this cpp is for lint, we peek inside the comments: */
2923 char *lintcmd = get_lintcmd (ibp, limit, &argbp, &arglen, &cmdlen);
2925 if (lintcmd != NULL) {
2927 check_expand (op, cmdlen + arglen + 14);
2929 /* I believe it is always safe to emit this newline: */
2931 bcopy ("#pragma lint ", (char *) obp, 13);
2933 bcopy (lintcmd, (char *) obp, cmdlen);
2938 bcopy (argbp, (char *) obp, arglen);
2942 /* OK, now bring us back to the state we were in before we entered
2943 this branch. We need #line because the #pragma's newline always
2944 messes up the line count. */
2946 output_line_directive (ip, op, 0, same_file);
2947 check_expand (op, limit - ibp + 2);
2953 /* Comments are equivalent to spaces.
2954 Note that we already output the slash; we might not want it.
2955 For -traditional, a comment is equivalent to nothing. */
2956 if (! put_out_comments) {
2966 U_CHAR *before_bp = ibp;
2971 if (ibp[-2] == '/' && warn_comments)
2972 warning ("`/*' within comment");
2973 if (*ibp == '\\' && ibp[1] == '\n')
2981 /* Copy the newline into the output buffer, in order to
2982 avoid the pain of a #line every time a multiline comment
2984 if (!put_out_comments)
2991 error_with_line (line_for_error (start_line),
2992 "unterminated comment");
3001 if (put_out_comments) {
3002 bcopy ((char *) before_bp, (char *) obp, ibp - before_bp);
3003 obp += ibp - before_bp;
3009 if (! is_idchar['$'])
3012 pedwarn ("`$' in identifier");
3015 case '0': case '1': case '2': case '3': case '4':
3016 case '5': case '6': case '7': case '8': case '9':
3017 /* If digit is not part of identifier, it starts a number,
3018 which means that following letters are not an identifier.
3019 "0x5" does not refer to an identifier "x5".
3020 So copy all alphanumerics that follow without accumulating
3021 as an identifier. Periods also, for sake of "3.e7". */
3023 if (ident_length == 0) {
3026 while (ibp[0] == '\\' && ibp[1] == '\n') {
3032 if (!is_idchar[c] && c != '.') {
3037 /* A sign can be part of a preprocessing number
3038 if it follows an `e' or `p'. */
3039 if (c == 'e' || c == 'E' || c == 'p' || c == 'P') {
3041 while (ibp[0] == '\\' && ibp[1] == '\n') {
3046 if (*ibp == '+' || *ibp == '-') {
3048 /* But traditional C does not let the token go past the sign,
3049 and C89 does not allow `p'. */
3050 if (traditional || (c89 && (c == 'p' || c == 'P')))
3060 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
3061 case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
3062 case 'm': case 'n': case 'o': case 'p': case 'q': case 'r':
3063 case 's': case 't': case 'u': case 'v': case 'w': case 'x':
3065 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
3066 case 'G': case 'H': case 'I': case 'J': case 'K': case 'L':
3067 case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R':
3068 case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
3072 /* Compute step of hash function, to avoid a proc call on every token */
3073 hash = HASHSTEP (hash, c);
3077 if (ip->fname == 0 && *ibp == '-') {
3078 /* Newline - inhibits expansion of preceding token.
3079 If expanding a macro arg, we keep the newline -.
3080 In final output, it is deleted.
3081 We recognize Newline - in macro bodies and macro args. */
3082 if (! concatenated) {
3087 if (!output_marks) {
3090 /* If expanding a macro arg, keep the newline -. */
3096 /* If reprocessing a macro expansion, newline is a special marker. */
3097 else if (ip->macro != 0) {
3098 /* Newline White is a "funny space" to separate tokens that are
3099 supposed to be separate but without space between.
3100 Here White means any whitespace character.
3101 Newline - marks a recursive macro use that is not
3102 supposed to be expandable. */
3104 if (is_space[*ibp]) {
3105 /* Newline Space does not prevent expansion of preceding token
3106 so expand the preceding token and then come back. */
3107 if (ident_length > 0)
3110 /* If generating final output, newline space makes a space. */
3111 if (!output_marks) {
3113 /* And Newline Newline makes a newline, so count it. */
3114 if (obp[-1] == '\n')
3117 /* If expanding a macro arg, keep the newline space.
3118 If the arg gets stringified, newline space makes nothing. */
3121 } else abort (); /* Newline followed by something random? */
3125 /* If there is a pending identifier, handle it and come back here. */
3126 if (ident_length > 0)
3131 /* Update the line counts and output a #line if necessary. */
3134 if (ip->lineno != op->lineno) {
3136 output_line_directive (ip, op, 1, same_file);
3137 check_expand (op, limit - ibp);
3142 /* Come here either after (1) a null character that is part of the input
3143 or (2) at the end of the input, because there is a null there. */
3146 /* Our input really contains a null character. */
3150 /* At end of a macro-expansion level, pop it and read next level. */
3151 if (ip->macro != 0) {
3154 /* If traditional, and we have an identifier that ends here,
3155 process it now, so we get the right error for recursion. */
3156 if (traditional && ident_length
3157 && ! is_idchar[*instack[indepth - 1].bufp]) {
3166 /* If we don't have a pending identifier,
3167 return at end of input. */
3168 if (ident_length == 0) {
3176 /* If we do have a pending identifier, just consider this null
3177 a special character and arrange to dispatch on it again.
3178 The second time, IDENT_LENGTH will be zero so we will return. */
3184 /* Handle the case of a character such as /, ', " or null
3185 seen following an identifier. Back over it so that
3186 after the identifier is processed the special char
3187 will be dispatched on again. */
3197 if (ident_length > 0) {
3198 register HASHNODE *hp;
3200 /* We have just seen an identifier end. If it's a macro, expand it.
3202 IDENT_LENGTH is the length of the identifier
3203 and HASH is its hash code.
3205 The identifier has already been copied to the output,
3206 so if it is a macro we must remove it.
3208 If REDO_CHAR is 0, the char that terminated the identifier
3209 has been skipped in the output and the input.
3210 OBP-IDENT_LENGTH-1 points to the identifier.
3211 If the identifier is a macro, we must back over the terminator.
3213 If REDO_CHAR is 1, the terminating char has already been
3214 backed over. OBP-IDENT_LENGTH points to the identifier. */
3216 if (!pcp_outfile || pcp_inside_if) {
3217 for (hp = hashtab[MAKE_POS (hash) % HASHSIZE]; hp != NULL;
3220 if (hp->length == ident_length) {
3221 int obufp_before_macroname;
3222 int op_lineno_before_macroname;
3223 register int i = ident_length;
3224 register U_CHAR *p = hp->name;
3225 register U_CHAR *q = obp - i;
3231 do { /* All this to avoid a strncmp () */
3236 /* We found a use of a macro name.
3237 see if the context shows it is a macro call. */
3239 /* Back up over terminating character if not already done. */
3245 /* Save this as a displacement from the beginning of the output
3246 buffer. We can not save this as a position in the output
3247 buffer, because it may get realloc'ed by RECACHE. */
3248 obufp_before_macroname = (obp - op->buf) - ident_length;
3249 op_lineno_before_macroname = op->lineno;
3251 if (hp->type == T_PCSTRING) {
3252 pcstring_used (hp); /* Mark the definition of this key
3253 as needed, ensuring that it
3255 break; /* Exit loop, since the key cannot have a
3256 definition any longer. */
3259 /* Record whether the macro is disabled. */
3260 disabled = hp->type == T_DISABLED;
3262 /* This looks like a macro ref, but if the macro was disabled,
3263 just copy its name and put in a marker if requested. */
3267 /* This error check caught useful cases such as
3268 #define foo(x,y) bar (x (y,0), y)
3271 error ("recursive use of macro `%s'", hp->name);
3275 check_expand (op, limit - ibp + 2);
3282 /* If macro wants an arglist, verify that a '(' follows.
3283 first skip all whitespace, copying it to the output
3284 after the macro name. Then, if there is no '(',
3285 decide this is not a macro call and leave things that way. */
3286 if ((hp->type == T_MACRO || hp->type == T_DISABLED)
3287 && hp->value.defn->nargs >= 0)
3289 U_CHAR *old_ibp = ibp;
3290 U_CHAR *old_obp = obp;
3291 int old_iln = ip->lineno;
3292 int old_oln = op->lineno;
3295 /* Scan forward over whitespace, copying it to the output. */
3296 if (ibp == limit && ip->macro != 0) {
3301 old_iln = ip->lineno;
3302 old_oln = op->lineno;
3304 else if (is_space[*ibp]) {
3306 if (ibp[-1] == '\n') {
3307 if (ip->macro == 0) {
3308 /* Newline in a file. Count it. */
3311 } else if (!output_marks) {
3312 /* A newline mark, and we don't want marks
3313 in the output. If it is newline-hyphen,
3314 discard it entirely. Otherwise, it is
3315 newline-whitechar, so keep the whitechar. */
3325 /* A newline mark; copy both chars to the output. */
3332 else if (*ibp == '/') {
3333 /* If a comment, copy it unchanged or discard it. */
3334 if (ibp[1] == '\\' && ibp[2] == '\n')
3335 newline_fix (ibp + 1);
3336 if (ibp[1] == '*') {
3337 if (put_out_comments) {
3340 } else if (! traditional) {
3343 for (ibp += 2; ibp < limit; ibp++) {
3344 /* We need not worry about newline-marks,
3345 since they are never found in comments. */
3346 if (ibp[0] == '*') {
3347 if (ibp[1] == '\\' && ibp[2] == '\n')
3348 newline_fix (ibp + 1);
3349 if (ibp[1] == '/') {
3351 if (put_out_comments) {
3359 /* Newline in a file. Count it. */
3363 if (put_out_comments)
3366 } else if (ibp[1] == '/' && cplusplus_comments) {
3367 if (put_out_comments) {
3370 } else if (! traditional) {
3373 for (ibp += 2; *ibp != '\n' || ibp[-1] == '\\'; ibp++)
3374 if (put_out_comments)
3379 else if (ibp[0] == '\\' && ibp[1] == '\n') {
3386 /* It isn't a macro call.
3387 Put back the space that we just skipped. */
3390 ip->lineno = old_iln;
3391 op->lineno = old_oln;
3392 /* Exit the for loop. */
3397 /* This is now known to be a macro call.
3398 Discard the macro name from the output,
3399 along with any following whitespace just copied,
3400 but preserve newlines if not outputting marks since this
3401 is more likely to do the right thing with line numbers. */
3402 obp = op->buf + obufp_before_macroname;
3404 op->lineno = op_lineno_before_macroname;
3406 int newlines = op->lineno - op_lineno_before_macroname;
3407 while (0 < newlines--)
3411 /* Prevent accidental token-pasting with a character
3412 before the macro call. */
3413 if (!traditional && obp != op->buf) {
3415 case '!': case '%': case '&': case '*':
3416 case '+': case '-': case '.': case '/':
3417 case ':': case '<': case '=': case '>':
3419 /* If we are expanding a macro arg, make a newline marker
3420 to separate the tokens. If we are making real output,
3421 a plain space will do. */
3428 /* Expand the macro, reading arguments as needed,
3429 and push the expansion on the input stack. */
3432 macroexpand (hp, op);
3434 /* Reexamine input stack, since macroexpand has pushed
3435 a new level on it. */
3442 } /* End hash-table-search loop */
3444 ident_length = hash = 0; /* Stop collecting identifier */
3447 } /* End if (ident_length > 0) */
3449 } /* End per-char loop */
3451 /* Come here to return -- but first give an error message
3452 if there was an unterminated successful conditional. */
3454 if (if_stack != ip->if_stack)
3458 switch (if_stack->type)
3479 error_with_line (line_for_error (if_stack->lineno),
3480 "unterminated `#%s' conditional", str);
3482 if_stack = ip->if_stack;
3486 * Rescan a string into a temporary buffer and return the result
3487 * as a FILE_BUF. Note this function returns a struct, not a pointer.
3489 * OUTPUT_MARKS nonzero means keep Newline markers found in the input
3490 * and insert such markers when appropriate. See `rescan' for details.
3491 * OUTPUT_MARKS is 1 for macroexpanding a macro argument separately
3492 * before substitution; it is 0 for other uses.
3495 expand_to_temp_buffer (buf, limit, output_marks, assertions)
3496 U_CHAR *buf, *limit;
3497 int output_marks, assertions;
3499 register FILE_BUF *ip;
3501 int length = limit - buf;
3503 int odepth = indepth;
3504 int save_assertions_flag = assertions_flag;
3506 assertions_flag = assertions;
3511 /* Set up the input on the input stack. */
3513 buf1 = (U_CHAR *) alloca (length + 1);
3515 register U_CHAR *p1 = buf;
3516 register U_CHAR *p2 = buf1;
3523 /* Set up to receive the output. */
3525 obuf.length = length * 2 + 100; /* Usually enough. Why be stingy? */
3526 obuf.bufp = obuf.buf = (U_CHAR *) xmalloc (obuf.length);
3527 obuf.nominal_fname = 0;
3534 obuf.system_header_p = 0;
3536 CHECK_DEPTH ({return obuf;});
3540 ip = &instack[indepth];
3542 ip->nominal_fname = 0;
3543 ip->nominal_fname_len = 0;
3545 ip->system_header_p = 0;
3548 ip->length = length;
3549 ip->buf = ip->bufp = buf1;
3550 ip->if_stack = if_stack;
3552 ip->lineno = obuf.lineno = 1;
3554 /* Scan the input, create the output. */
3555 rescan (&obuf, output_marks);
3557 /* Pop input stack to original state. */
3560 if (indepth != odepth)
3563 /* Record the output. */
3564 obuf.length = obuf.bufp - obuf.buf;
3566 assertions_flag = save_assertions_flag;
3571 * Process a # directive. Expects IP->bufp to point after the '#', as in
3572 * `#define foo bar'. Passes to the directive handler
3573 * (do_define, do_include, etc.): the addresses of the 1st and
3574 * last chars of the directive (starting immediately after the #
3575 * keyword), plus op and the keyword table pointer. If the directive
3576 * contains comments it is copied into a temporary buffer sans comments
3577 * and the temporary buffer is passed to the directive handler instead.
3578 * Likewise for backslash-newlines.
3580 * Returns nonzero if this was a known # directive.
3581 * Otherwise, returns zero, without advancing the input pointer.
3585 handle_directive (ip, op)
3588 register U_CHAR *bp, *cp;
3589 register struct directive *kt;
3590 register int ident_length;
3593 /* Nonzero means we must copy the entire directive
3594 to get rid of comments or backslash-newlines. */
3595 int copy_directive = 0;
3597 U_CHAR *ident, *after_ident;
3601 /* Record where the directive started. do_xifdef needs this. */
3602 directive_start = bp - 1;
3604 /* Skip whitespace and \-newline. */
3606 if (is_hor_space[*bp]) {
3607 if (*bp != ' ' && *bp != '\t' && pedantic)
3608 pedwarn ("%s in preprocessing directive", char_name[*bp]);
3610 } else if (*bp == '/') {
3611 if (bp[1] == '\\' && bp[2] == '\n')
3612 newline_fix (bp + 1);
3613 if (! (bp[1] == '*' || (cplusplus_comments && bp[1] == '/')))
3616 skip_to_end_of_comment (ip, &ip->lineno, 0);
3618 } else if (*bp == '\\' && bp[1] == '\n') {
3619 bp += 2; ip->lineno++;
3623 /* Now find end of directive name.
3624 If we encounter a backslash-newline, exchange it with any following
3625 symbol-constituents so that we end up with a contiguous name. */
3632 if (*cp == '\\' && cp[1] == '\n')
3633 name_newline_fix (cp);
3639 ident_length = cp - bp;
3643 /* A line of just `#' becomes blank. */
3645 if (ident_length == 0 && *after_ident == '\n') {
3646 ip->bufp = after_ident;
3650 if (ident_length == 0 || !is_idstart[*ident]) {
3652 while (is_idchar[*p]) {
3653 if (*p < '0' || *p > '9')
3657 /* Handle # followed by a line number. */
3658 if (p != ident && !is_idchar[*p]) {
3659 static struct directive line_directive_table[] = {
3660 { 4, do_line, "line", T_LINE},
3663 pedwarn ("`#' followed by integer");
3664 after_ident = ident;
3665 kt = line_directive_table;
3669 /* Avoid error for `###' and similar cases unless -pedantic. */
3671 while (*p == '#' || is_hor_space[*p]) p++;
3673 if (pedantic && !lang_asm)
3674 warning ("invalid preprocessing directive");
3680 error ("invalid preprocessing directive name");
3686 * Decode the keyword and call the appropriate expansion
3687 * routine, after moving the input pointer up to the next line.
3689 for (kt = directive_table; kt->length > 0; kt++) {
3690 if (kt->length == ident_length && !bcmp (kt->name, ident, ident_length)) {
3691 register U_CHAR *buf;
3692 register U_CHAR *limit;
3695 int *already_output;
3697 /* Nonzero means do not delete comments within the directive.
3698 #define needs this when -traditional. */
3703 limit = ip->buf + ip->length;
3706 keep_comments = traditional && kt->type == T_DEFINE;
3707 /* #import is defined only in Objective C, or when on the NeXT. */
3708 if (kt->type == T_IMPORT
3709 && !(objc || lookup ((U_CHAR *) "__NeXT__", -1, -1)))
3712 /* Find the end of this directive (first newline not backslashed
3713 and not in a string or comment).
3714 Set COPY_DIRECTIVE if the directive must be copied
3715 (it contains a backslash-newline or a comment). */
3717 buf = bp = after_ident;
3718 while (bp < limit) {
3719 register U_CHAR c = *bp++;
3727 } else if (traditional)
3733 /* "..." is special for #include. */
3734 if (IS_INCLUDE_DIRECTIVE_TYPE (kt->type)) {
3735 while (bp < limit && *bp != '\n') {
3740 if (*bp == '\\' && bp[1] == '\n') {
3751 bp = skip_quoted_string (bp - 1, limit, ip->lineno, &ip->lineno, ©_directive, &unterminated);
3752 /* Don't bother calling the directive if we already got an error
3753 message due to unterminated string. Skip everything and pretend
3754 we called the directive. */
3757 /* Traditional preprocessing permits unterminated strings. */
3766 /* <...> is special for #include. */
3768 if (! IS_INCLUDE_DIRECTIVE_TYPE (kt->type))
3770 while (bp < limit && *bp != '>' && *bp != '\n') {
3771 if (*bp == '\\' && bp[1] == '\n') {
3781 if (*bp == '\\' && bp[1] == '\n')
3784 || (cplusplus_comments && *bp == '/')) {
3785 U_CHAR *obp = bp - 1;
3787 skip_to_end_of_comment (ip, &ip->lineno, 0);
3789 /* No need to copy the directive because of a comment at the end;
3790 just don't include the comment in the directive. */
3791 if (!put_out_comments) {
3793 for (p = bp; *p == ' ' || *p == '\t'; p++)
3800 /* Don't remove the comments if -traditional. */
3801 if (! keep_comments)
3810 pedwarn ("%s in preprocessing directive", char_name[c]);
3814 --bp; /* Point to the newline */
3822 resume_p = ip->bufp;
3823 /* BP is the end of the directive.
3824 RESUME_P is the next interesting data after the directive.
3825 A comment may come between. */
3827 /* If a directive should be copied through, and -C was given,
3828 pass it through before removing comments. */
3829 if (!no_output && put_out_comments
3830 && (kt->type == T_DEFINE ? dump_macros == dump_definitions
3831 : IS_INCLUDE_DIRECTIVE_TYPE (kt->type) ? dump_includes
3832 : kt->type == T_PRAGMA)) {
3835 /* Output directive name. */
3836 check_expand (op, kt->length + 2);
3837 /* Make sure # is at the start of a line */
3838 if (op->bufp > op->buf && op->bufp[-1] != '\n') {
3843 bcopy (kt->name, op->bufp, kt->length);
3844 op->bufp += kt->length;
3846 /* Output arguments. */
3848 check_expand (op, len);
3849 bcopy (buf, (char *) op->bufp, len);
3851 /* Take account of any (escaped) newlines just output. */
3853 if (buf[len] == '\n')
3856 already_output = &junk;
3857 } /* Don't we need a newline or #line? */
3859 if (copy_directive) {
3860 register U_CHAR *xp = buf;
3861 /* Need to copy entire directive into temp buffer before dispatching */
3863 cp = (U_CHAR *) alloca (bp - buf + 5); /* room for directive plus
3867 /* Copy to the new buffer, deleting comments
3868 and backslash-newlines (and whitespace surrounding the latter). */
3871 register U_CHAR c = *xp++;
3876 abort (); /* A bare newline should never part of the line. */
3879 /* <...> is special for #include. */
3881 if (! IS_INCLUDE_DIRECTIVE_TYPE (kt->type))
3883 while (xp < bp && c != '>') {
3885 if (c == '\\' && xp < bp && *xp == '\n')
3896 if (cp != buf && is_hor_space[cp[-1]]) {
3897 while (cp - 1 != buf && is_hor_space[cp[-2]])
3899 SKIP_WHITE_SPACE (xp);
3900 } else if (is_hor_space[*xp]) {
3902 SKIP_WHITE_SPACE (xp);
3904 } else if (traditional && xp < bp) {
3912 register U_CHAR *bp1
3913 = skip_quoted_string (xp - 1, bp, ip->lineno,
3914 NULL_PTR, NULL_PTR, NULL_PTR);
3922 || (cplusplus_comments && *xp == '/')) {
3924 /* If we already copied the directive through,
3925 already_output != 0 prevents outputting comment now. */
3926 skip_to_end_of_comment (ip, already_output, 0);
3928 while (xp != ip->bufp)
3930 /* Delete or replace the slash. */
3931 else if (traditional)
3940 /* Null-terminate the copy. */
3946 ip->bufp = resume_p;
3948 /* Some directives should be written out for cc1 to process,
3949 just as if they were not defined. And sometimes we're copying
3950 directives through. */
3952 if (!no_output && already_output == 0
3953 && (kt->type == T_DEFINE ? (int) dump_names <= (int) dump_macros
3954 : IS_INCLUDE_DIRECTIVE_TYPE (kt->type) ? dump_includes
3955 : kt->type == T_PRAGMA)) {
3958 /* Output directive name. */
3959 check_expand (op, kt->length + 1);
3961 bcopy (kt->name, (char *) op->bufp, kt->length);
3962 op->bufp += kt->length;
3964 if (kt->type == T_DEFINE && dump_macros == dump_names) {
3965 /* Output `#define name' only. */
3968 SKIP_WHITE_SPACE (xp);
3970 while (is_idchar[*xp]) xp++;
3972 check_expand (op, len + 1);
3974 bcopy (yp, (char *) op->bufp, len);
3976 /* Output entire directive. */
3978 check_expand (op, len);
3979 bcopy (buf, (char *) op->bufp, len);
3982 } /* Don't we need a newline or #line? */
3984 /* Call the appropriate directive handler. buf now points to
3985 either the appropriate place in the input buffer, or to
3986 the temp buffer if it was necessary to make one. cp
3987 points to the first char after the contents of the (possibly
3988 copied) directive, in either case. */
3989 (*kt->func) (buf, cp, op, kt);
3990 check_expand (op, ip->length - (ip->bufp - ip->buf));
3996 /* It is deliberate that we don't warn about undefined directives.
3997 That is the responsibility of cc1. */
4004 static struct tm *timebuf;
4006 time_t t = time ((time_t *) 0);
4007 timebuf = localtime (&t);
4012 static char *monthnames[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
4013 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
4017 * expand things like __FILE__. Place the expansion into the output
4018 * buffer *without* rescanning.
4022 special_symbol (hp, op)
4029 FILE_BUF *ip = NULL;
4032 int paren = 0; /* For special `defined' keyword */
4034 if (pcp_outfile && pcp_inside_if
4035 && hp->type != T_SPEC_DEFINED && hp->type != T_CONST)
4036 error ("Predefined macro `%s' used inside `#if' during precompilation",
4039 for (i = indepth; i >= 0; i--)
4040 if (instack[i].fname != NULL) {
4045 error ("cccp error: not in any file?!");
4046 return; /* the show must go on */
4053 FILE_BUF *p = hp->type == T_FILE ? ip : &instack[0];
4054 char *string = p->nominal_fname;
4058 size_t string_len = p->nominal_fname_len;
4059 buf = (char *) alloca (3 + 4 * string_len);
4060 quote_string (buf, string, string_len);
4068 case T_INCLUDE_LEVEL:
4070 for (i = indepth; i >= 0; i--)
4071 if (instack[i].fname != NULL)
4074 buf = (char *) alloca (8); /* Eight bytes ought to be more than enough */
4075 sprintf (buf, "%d", true_indepth - 1);
4079 buf = (char *) alloca (3 + strlen (version_string));
4080 sprintf (buf, "\"%s\"", version_string);
4083 #ifndef NO_BUILTIN_SIZE_TYPE
4089 #ifndef NO_BUILTIN_PTRDIFF_TYPE
4090 case T_PTRDIFF_TYPE:
4099 case T_USER_LABEL_PREFIX_TYPE:
4100 buf = USER_LABEL_PREFIX;
4103 case T_REGISTER_PREFIX_TYPE:
4104 buf = REGISTER_PREFIX;
4107 case T_IMMEDIATE_PREFIX_TYPE:
4108 buf = IMMEDIATE_PREFIX;
4112 buf = hp->value.cpval;
4113 #ifdef STDC_0_IN_SYSTEM_HEADERS
4114 if (ip->system_header_p
4115 && hp->length == 8 && bcmp (hp->name, "__STDC__", 8) == 0
4116 && !lookup ((U_CHAR *) "__STRICT_ANSI__", -1, -1))
4119 if (pcp_inside_if && pcp_outfile)
4120 /* Output a precondition for this macro use */
4121 fprintf (pcp_outfile, "#define %s %s\n", hp->name, buf);
4125 buf = (char *) alloca (10);
4126 sprintf (buf, "%d", ip->lineno);
4131 buf = (char *) alloca (20);
4132 timebuf = timestamp ();
4133 if (hp->type == T_DATE)
4134 sprintf (buf, "\"%s %2d %4d\"", monthnames[timebuf->tm_mon],
4135 timebuf->tm_mday, timebuf->tm_year + 1900);
4137 sprintf (buf, "\"%02d:%02d:%02d\"", timebuf->tm_hour, timebuf->tm_min,
4141 case T_SPEC_DEFINED:
4142 buf = " 0 "; /* Assume symbol is not defined */
4143 ip = &instack[indepth];
4144 SKIP_WHITE_SPACE (ip->bufp);
4145 if (*ip->bufp == '(') {
4147 ip->bufp++; /* Skip over the paren */
4148 SKIP_WHITE_SPACE (ip->bufp);
4151 if (!is_idstart[*ip->bufp])
4153 if (ip->bufp[0] == 'L' && (ip->bufp[1] == '\'' || ip->bufp[1] == '"'))
4155 if ((hp = lookup (ip->bufp, -1, -1))) {
4156 if (pcp_outfile && pcp_inside_if
4157 && (hp->type == T_CONST
4158 || (hp->type == T_MACRO && hp->value.defn->predefined)))
4159 /* Output a precondition for this macro use. */
4160 fprintf (pcp_outfile, "#define %s\n", hp->name);
4164 if (pcp_outfile && pcp_inside_if) {
4165 /* Output a precondition for this macro use */
4166 U_CHAR *cp = ip->bufp;
4167 fprintf (pcp_outfile, "#undef ");
4168 while (is_idchar[*cp]) /* Ick! */
4169 fputc (*cp++, pcp_outfile);
4170 putc ('\n', pcp_outfile);
4172 while (is_idchar[*ip->bufp])
4174 SKIP_WHITE_SPACE (ip->bufp);
4176 if (*ip->bufp != ')')
4184 error ("`defined' without an identifier");
4188 error ("cccp error: invalid special hash type"); /* time for gdb */
4192 check_expand (op, len);
4193 bcopy (buf, (char *) op->bufp, len);
4200 /* Routines to handle #directives */
4202 /* Handle #include and #import.
4203 This function expects to see "fname" or <fname> on the input. */
4206 do_include (buf, limit, op, keyword)
4207 U_CHAR *buf, *limit;
4209 struct directive *keyword;
4211 U_CHAR *importing = keyword->type == T_IMPORT ? (U_CHAR *) "" : (U_CHAR *) 0;
4212 int skip_dirs = (keyword->type == T_INCLUDE_NEXT);
4213 static int import_warning = 0;
4214 char *fname; /* Dynamically allocated fname buffer */
4217 char *fbeg, *fend; /* Beginning and end of fname */
4220 struct file_name_list *search_start = include; /* Chain of dirs to search */
4221 struct file_name_list *dsp; /* First in chain, if #include "..." */
4222 struct file_name_list *searchptr = 0;
4225 int f = -3; /* file number */
4226 struct include_file *inc = 0;
4228 int retried = 0; /* Have already tried macro
4229 expanding the include line*/
4230 int angle_brackets = 0; /* 0 for "...", 1 for <...> */
4232 int vaxc_include = 0; /* 1 for token without punctuation */
4239 if (pedantic && !instack[indepth].system_header_p)
4242 pedwarn ("ANSI C does not allow `#import'");
4244 pedwarn ("ANSI C does not allow `#include_next'");
4247 if (importing && warn_import && !inhibit_warnings
4248 && !instack[indepth].system_header_p && !import_warning) {
4250 warning ("using `#import' is not recommended");
4251 fprintf (stderr, "The fact that a certain header file need not be processed more than once\n");
4252 fprintf (stderr, "should be indicated in the header file, not where it is used.\n");
4253 fprintf (stderr, "The best way to do this is with a conditional of this form:\n\n");
4254 fprintf (stderr, " #ifndef _FOO_H_INCLUDED\n");
4255 fprintf (stderr, " #define _FOO_H_INCLUDED\n");
4256 fprintf (stderr, " ... <real contents of file> ...\n");
4257 fprintf (stderr, " #endif /* Not _FOO_H_INCLUDED */\n\n");
4258 fprintf (stderr, "Then users can use `#include' any number of times.\n");
4259 fprintf (stderr, "GNU C automatically avoids processing the file more than once\n");
4260 fprintf (stderr, "when it is equipped with such a conditional.\n");
4266 SKIP_WHITE_SPACE (fin);
4267 /* Discard trailing whitespace so we can easily see
4268 if we have parsed all the significant chars we were given. */
4269 while (limit != fin && is_hor_space[limit[-1]]) limit--;
4270 fbeg = fend = (char *) alloca (limit - fin);
4276 /* Copy the operand text, concatenating the strings. */
4281 goto invalid_include_file_name;
4289 /* If not at the end, there had better be another string. */
4290 /* Skip just horiz space, and don't go past limit. */
4291 while (fin != limit && is_hor_space[*fin]) fin++;
4292 if (fin != limit && *fin == '\"')
4299 /* We have "filename". Figure out directory this source
4300 file is coming from and put it on the front of the list. */
4302 /* If -I- was specified, don't search current dir, only spec'd ones. */
4303 if (ignore_srcdir) break;
4305 for (fp = &instack[indepth]; fp >= instack; fp--)
4310 if ((nam = fp->nominal_fname) != NULL) {
4311 /* Found a named file. Figure out dir of the file,
4312 and put it in front of the search list. */
4313 dsp = ((struct file_name_list *)
4314 alloca (sizeof (struct file_name_list)
4315 + fp->nominal_fname_len));
4316 strcpy (dsp->fname, nam);
4317 simplify_filename (dsp->fname);
4318 nam = base_name (dsp->fname);
4321 /* for hack_vms_include_specification(), a local
4322 dir specification must start with "./" on VMS. */
4323 if (nam == dsp->fname)
4330 /* But for efficiency's sake, do not insert the dir
4331 if it matches the search list's first dir. */
4332 dsp->next = search_start;
4333 if (!search_start || strcmp (dsp->fname, search_start->fname)) {
4335 n = nam - dsp->fname;
4336 if (n + INCLUDE_LEN_FUDGE > max_include_len)
4337 max_include_len = n + INCLUDE_LEN_FUDGE;
4339 dsp[0].got_name_map = 0;
4347 while (fin != limit && *fin != '>')
4349 if (*fin == '>' && fin + 1 == limit) {
4351 /* If -I-, start with the first -I dir after the -I-. */
4352 search_start = first_bracket_include;
4360 * Support '#include xyz' like VAX-C to allow for easy use of all the
4361 * decwindow include files. It defaults to '#include <xyz.h>' (so the
4362 * code from case '<' is repeated here) and generates a warning.
4363 * (Note: macro expansion of `xyz' takes precedence.)
4365 /* Note: The argument of ISALPHA() can be evaluated twice, so do
4366 the pre-decrement outside of the macro. */
4367 if (retried && (--fbeg, ISALPHA(*(U_CHAR *) (fbeg)))) {
4368 while (fin != limit && (!ISSPACE(*fin)))
4370 warning ("VAX-C-style include specification found, use '#include <filename.h>' !");
4374 /* If -I-, start with the first -I dir after the -I-. */
4375 search_start = first_bracket_include;
4383 /* Expand buffer and then remove any newline markers.
4384 We can't just tell expand_to_temp_buffer to omit the markers,
4385 since it would put extra spaces in include file names. */
4388 int errors_before_expansion = errors;
4389 trybuf = expand_to_temp_buffer (buf, limit, 1, 0);
4390 if (errors != errors_before_expansion) {
4392 goto invalid_include_file_name;
4395 buf = (U_CHAR *) alloca (trybuf.bufp - trybuf.buf + 1);
4397 while (src != trybuf.bufp) {
4398 switch ((*limit++ = *src++)) {
4407 U_CHAR *src1 = skip_quoted_string (src - 1, trybuf.bufp, 0,
4408 NULL_PTR, NULL_PTR, NULL_PTR);
4421 invalid_include_file_name:
4422 error ("`#%s' expects \"FILENAME\" or <FILENAME>", keyword->name);
4426 /* For #include_next, skip in the search path
4427 past the dir in which the containing file was found. */
4430 for (fp = &instack[indepth]; fp >= instack; fp--)
4431 if (fp->fname != NULL) {
4432 /* fp->dir is null if the containing file was specified
4433 with an absolute file name. In that case, don't skip anything. */
4435 search_start = fp->dir->next;
4441 flen = simplify_filename (fbeg);
4445 error ("empty file name in `#%s'", keyword->name);
4449 /* Allocate this permanently, because it gets stored in the definitions
4451 fname = xmalloc (max_include_len + flen + 1);
4452 /* + 1 above for terminating null. */
4454 system_include_depth += angle_brackets;
4456 /* If specified file name is absolute, just open it. */
4458 if (absolute_filename (fbeg)) {
4459 strcpy (fname, fbeg);
4460 f = open_include_file (fname, NULL_PTR, importing, &inc);
4464 struct bypass_dir *next;
4466 struct file_name_list *searchptr;
4467 } **bypass_slot = 0;
4469 /* Search directory path, trying to open the file.
4470 Copy each filename tried into FNAME. */
4472 for (searchptr = search_start; searchptr; searchptr = searchptr->next) {
4474 if (searchptr == first_bracket_include) {
4475 /* Go to bypass directory if we know we've seen this file before. */
4476 static struct bypass_dir *bypass_hashtab[INCLUDE_HASHSIZE];
4477 struct bypass_dir *p;
4478 bypass_slot = &bypass_hashtab[hashf ((U_CHAR *) fbeg, flen,
4480 for (p = *bypass_slot; p; p = p->next)
4481 if (!strcmp (fbeg, p->fname)) {
4482 searchptr = p->searchptr;
4489 /* Change this 1/2 Unix 1/2 VMS file specification into a
4490 full VMS file specification */
4491 if (searchptr->fname[0])
4493 strcpy (fname, searchptr->fname);
4494 if (fname[strlen (fname) - 1] == ':')
4497 slashp = strchr (fbeg, '/');
4499 /* start at root-dir of logical device if no path given. */
4501 strcat (fname, "[000000]");
4503 strcat (fname, fbeg);
4505 /* Fix up the filename */
4506 hack_vms_include_specification (fname, vaxc_include);
4510 /* This is a normal VMS filespec, so use it unchanged. */
4511 strcpy (fname, fbeg);
4512 /* if it's '#include filename', add the missing .h */
4513 if (vaxc_include && index(fname,'.')==NULL)
4514 strcat (fname, ".h");
4517 strcpy (fname, searchptr->fname);
4518 strcat (fname, fbeg);
4520 f = open_include_file (fname, searchptr, importing, &inc);
4522 if (bypass_slot && searchptr != first_bracket_include) {
4523 /* This is the first time we found this include file,
4524 and we found it after first_bracket_include.
4525 Record its location so that we can bypass to here next time. */
4526 struct bypass_dir *p
4527 = (struct bypass_dir *) xmalloc (sizeof (struct bypass_dir));
4528 p->next = *bypass_slot;
4529 p->fname = fname + strlen (searchptr->fname);
4530 p->searchptr = searchptr;
4536 /* Our VMS hacks can produce invalid filespecs, so don't worry
4537 about errors other than EACCES. */
4538 if (errno == EACCES)
4541 if (errno != ENOENT && errno != ENOTDIR)
4551 /* The file was already included. */
4553 /* If generating dependencies and -MG was specified, we assume missing
4554 files are leaf files, living in the same directory as the source file
4555 or other similar place; these missing files may be generated from
4556 other files and may not exist yet (eg: y.tab.h). */
4557 } else if (print_deps_missing_files
4558 && (system_include_depth != 0) < print_deps)
4560 /* If it was requested as a system header file,
4561 then assume it belongs in the first place to look for such. */
4565 char *p = (char *) alloca (strlen (search_start->fname)
4566 + strlen (fbeg) + 1);
4567 strcpy (p, search_start->fname);
4569 deps_output (p, ' ');
4574 /* Otherwise, omit the directory, as if the file existed
4575 in the directory with the source. */
4576 deps_output (fbeg, ' ');
4579 /* If -M was specified, and this header file won't be added to the
4580 dependency list, then don't count this as an error, because we can
4581 still produce correct output. Otherwise, we can't produce correct
4582 output, because there may be dependencies we need inside the missing
4583 file, and we don't know what directory this missing file exists in. */
4584 else if (0 < print_deps && print_deps <= (system_include_depth != 0))
4585 warning ("No include path in which to find %s", fbeg);
4587 error_from_errno (fbeg);
4589 error ("No include path in which to find %s", fbeg);
4593 /* Actually process the file. */
4595 pcftry = (char *) alloca (strlen (fname) + 30);
4602 sprintf (pcftry, "%s%d", fname, pcfnum++);
4604 pcf = open (pcftry, O_RDONLY, 0666);
4609 if (fstat (pcf, &s) != 0)
4610 pfatal_with_name (pcftry);
4611 if (! INO_T_EQ (inc->st.st_ino, s.st_ino)
4612 || inc->st.st_dev != s.st_dev)
4614 pcfbuf = check_precompiled (pcf, &s, fname, &pcfbuflimit);
4615 /* Don't need it any more. */
4620 /* Don't need it at all. */
4625 } while (pcf != -1 && !pcfbuf);
4628 /* Actually process the file */
4630 pcfname = xmalloc (strlen (pcftry) + 1);
4631 strcpy (pcfname, pcftry);
4632 pcfinclude ((U_CHAR *) pcfbuf, (U_CHAR *) pcfbuflimit,
4633 (U_CHAR *) fname, op);
4636 finclude (f, inc, op, is_system_include (fname), searchptr);
4639 system_include_depth -= angle_brackets;
4644 /* Return nonzero if the given FILENAME is an absolute pathname which
4645 designates a file within one of the known "system" include file
4646 directories. We assume here that if the given FILENAME looks like
4647 it is the name of a file which resides either directly in a "system"
4648 include file directory, or within any subdirectory thereof, then the
4649 given file must be a "system" include file. This function tells us
4650 if we should suppress pedantic errors/warnings for the given FILENAME.
4652 The value is 2 if the file is a C-language system header file
4653 for which C++ should (on most systems) assume `extern "C"'. */
4656 is_system_include (filename)
4657 register char *filename;
4659 struct file_name_list *searchptr;
4661 for (searchptr = first_system_include; searchptr;
4662 searchptr = searchptr->next)
4663 if (! strncmp (searchptr->fname, filename, strlen (searchptr->fname)))
4664 return searchptr->c_system_include_path + 1;
4668 /* Yield the non-directory suffix of a file name. */
4676 #if defined (__MSDOS__) || defined (_WIN32)
4677 if (ISALPHA (s[0]) && s[1] == ':') s += 2;
4680 if ((p = rindex (s, ':'))) s = p + 1; /* Skip device. */
4681 if ((p = rindex (s, ']'))) s = p + 1; /* Skip directory. */
4682 if ((p = rindex (s, '>'))) s = p + 1; /* Skip alternate (int'n'l) dir. */
4686 if ((p = rindex (s, '/'))) s = p + 1;
4687 #ifdef DIR_SEPARATOR
4688 if ((p = rindex (s, DIR_SEPARATOR))) s = p + 1;
4693 /* Yield nonzero if FILENAME is absolute (i.e. not relative). */
4696 absolute_filename (filename)
4699 #if defined (__MSDOS__) || (defined (_WIN32) && !defined (__CYGWIN32__))
4700 if (ISALPHA (filename[0]) && filename[1] == ':') filename += 2;
4702 #if defined (__CYGWIN32__)
4703 /* At present, any path that begins with a drive spec is absolute. */
4704 if (ISALPHA (filename[0]) && filename[1] == ':') return 1;
4707 if (index (filename, ':') != 0) return 1;
4709 if (filename[0] == '/') return 1;
4710 #ifdef DIR_SEPARATOR
4711 if (filename[0] == DIR_SEPARATOR) return 1;
4716 /* Remove unnecessary characters from FILENAME in place,
4717 to avoid unnecessary filename aliasing.
4718 Return the length of the resulting string.
4720 Do only the simplifications allowed by Posix.
4721 It is OK to miss simplifications on non-Posix hosts,
4722 since this merely leads to suboptimal results. */
4725 simplify_filename (filename)
4728 register char *from = filename;
4729 register char *to = filename;
4732 /* Remove redundant initial /s. */
4735 if (*++from == '/') {
4736 if (*++from == '/') {
4737 /* 3 or more initial /s are equivalent to 1 /. */
4738 while (*++from == '/')
4741 /* On some hosts // differs from /; Posix allows this. */
4742 static int slashslash_vs_slash;
4743 if (slashslash_vs_slash == 0) {
4745 slashslash_vs_slash = ((stat ("/", &s1) == 0 && stat ("//", &s2) == 0
4746 && INO_T_EQ (s1.st_ino, s2.st_ino)
4747 && s1.st_dev == s2.st_dev)
4750 if (slashslash_vs_slash < 0)
4759 if (from[0] == '.' && from[1] == '/')
4764 /* Copy this component and trailing /, if any. */
4765 while ((*to++ = *from++) != '/') {
4767 /* Trim . component at end of nonempty name. */
4768 to -= filename <= to - 3 && to[-3] == '/' && to[-2] == '.';
4770 /* Trim unnecessary trailing /s. */
4771 while (to0 < --to && to[-1] == '/')
4775 return to - filename;
4780 /* Skip /s after a /. */
4781 while (*from == '/')
4786 /* The file_name_map structure holds a mapping of file names for a
4787 particular directory. This mapping is read from the file named
4788 FILE_NAME_MAP_FILE in that directory. Such a file can be used to
4789 map filenames on a file system with severe filename restrictions,
4790 such as DOS. The format of the file name map file is just a series
4791 of lines with two tokens on each line. The first token is the name
4792 to map, and the second token is the actual name to use. */
4794 struct file_name_map
4796 struct file_name_map *map_next;
4801 #define FILE_NAME_MAP_FILE "header.gcc"
4803 /* Read a space delimited string of unlimited length from a stdio
4807 read_filename_string (ch, f)
4815 set = alloc = xmalloc (len + 1);
4819 while ((ch = getc (f)) != EOF && ! is_space[ch])
4821 if (set - alloc == len)
4824 alloc = xrealloc (alloc, len + 1);
4825 set = alloc + len / 2;
4835 /* Read the file name map file for DIRNAME.
4836 If DIRNAME is empty, read the map file for the working directory;
4837 otherwise DIRNAME must end in '/'. */
4839 static struct file_name_map *
4840 read_name_map (dirname)
4843 /* This structure holds a linked list of file name maps, one per
4845 struct file_name_map_list
4847 struct file_name_map_list *map_list_next;
4848 char *map_list_name;
4849 struct file_name_map *map_list_map;
4851 static struct file_name_map_list *map_list;
4852 register struct file_name_map_list *map_list_ptr;
4857 for (map_list_ptr = map_list; map_list_ptr;
4858 map_list_ptr = map_list_ptr->map_list_next)
4859 if (! strcmp (map_list_ptr->map_list_name, dirname))
4860 return map_list_ptr->map_list_map;
4862 map_list_ptr = ((struct file_name_map_list *)
4863 xmalloc (sizeof (struct file_name_map_list)));
4864 map_list_ptr->map_list_name = savestring (dirname);
4865 map_list_ptr->map_list_map = NULL;
4867 dirlen = strlen (dirname);
4868 name = (char *) alloca (dirlen + strlen (FILE_NAME_MAP_FILE) + 1);
4869 strcpy (name, dirname);
4870 strcat (name, FILE_NAME_MAP_FILE);
4871 f = fopen (name, "r");
4873 map_list_ptr->map_list_map = NULL;
4878 while ((ch = getc (f)) != EOF)
4881 struct file_name_map *ptr;
4886 from = read_filename_string (ch, f);
4887 while ((ch = getc (f)) != EOF && is_hor_space[ch])
4889 to = read_filename_string (ch, f);
4891 simplify_filename (from);
4892 tolen = simplify_filename (to);
4894 ptr = ((struct file_name_map *)
4895 xmalloc (sizeof (struct file_name_map)));
4896 ptr->map_from = from;
4898 /* Make the real filename absolute. */
4899 if (absolute_filename (to))
4903 ptr->map_to = xmalloc (dirlen + tolen + 1);
4904 strcpy (ptr->map_to, dirname);
4905 strcat (ptr->map_to, to);
4909 ptr->map_next = map_list_ptr->map_list_map;
4910 map_list_ptr->map_list_map = ptr;
4912 while ((ch = getc (f)) != '\n')
4919 map_list_ptr->map_list_next = map_list;
4920 map_list = map_list_ptr;
4922 return map_list_ptr->map_list_map;
4925 /* Try to open include file FILENAME. SEARCHPTR is the directory
4926 being tried from the include file search path.
4927 IMPORTING is "" if we are importing, null otherwise.
4928 Return -2 if found, either a matching name or a matching inode.
4929 Otherwise, open the file and return a file descriptor if successful
4930 or -1 if unsuccessful.
4931 Unless unsuccessful, put a descriptor of the included file into *PINC.
4932 This function maps filenames on file systems based on information read by
4936 open_include_file (filename, searchptr, importing, pinc)
4938 struct file_name_list *searchptr;
4940 struct include_file **pinc;
4942 char *fname = remap ? remap_include_file (filename, searchptr) : filename;
4945 /* Look up FNAME in include_hashtab. */
4946 struct include_file **phead = &include_hashtab[hashf ((U_CHAR *) fname,
4949 struct include_file *inc, *head = *phead;
4950 for (inc = head; inc; inc = inc->next)
4951 if (!strcmp (fname, inc->fname))
4955 || ! inc->control_macro
4956 || (inc->control_macro[0] && ! lookup (inc->control_macro, -1, -1))) {
4958 fd = open (fname, O_RDONLY, 0);
4963 /* if #include <dir/file> fails, try again with hacked spec. */
4964 if (!hack_vms_include_specification (fname, 0))
4966 fd = open (fname, O_RDONLY, 0);
4973 /* FNAME was not in include_hashtab; insert a new entry. */
4974 inc = (struct include_file *) xmalloc (sizeof (struct include_file));
4977 inc->control_macro = 0;
4978 inc->deps_output = 0;
4979 if (fstat (fd, &inc->st) != 0)
4980 pfatal_with_name (fname);
4983 /* Look for another file with the same inode and device. */
4984 if (lookup_ino_include (inc)
4985 && inc->control_macro
4986 && (!inc->control_macro[0] || lookup (inc->control_macro, -1, -1))) {
4992 /* For -M, add this file to the dependencies. */
4993 if (! inc->deps_output && (system_include_depth != 0) < print_deps) {
4994 inc->deps_output = 1;
4995 deps_output (fname, ' ');
4998 /* Handle -H option. */
4999 if (print_include_names)
5000 fprintf (stderr, "%*s%s\n", indepth, "", fname);
5004 inc->control_macro = importing;
5010 /* Return the remapped name of the include file FILENAME.
5011 SEARCHPTR is the directory being tried from the include file path. */
5014 remap_include_file (filename, searchptr)
5016 struct file_name_list *searchptr;
5018 register struct file_name_map *map;
5019 register char *from;
5023 if (! searchptr->got_name_map)
5025 searchptr->name_map = read_name_map (searchptr->fname);
5026 searchptr->got_name_map = 1;
5029 /* Check the mapping for the directory we are using. */
5030 from = filename + strlen (searchptr->fname);
5031 for (map = searchptr->name_map; map; map = map->map_next)
5032 if (! strcmp (map->map_from, from))
5036 from = base_name (filename);
5038 if (from != filename || !searchptr)
5040 /* Try to find a mapping file for the particular directory we are
5041 looking in. Thus #include <sys/types.h> will look up sys/types.h
5042 in /usr/include/header.gcc and look up types.h in
5043 /usr/include/sys/header.gcc. */
5045 char *dir = (char *) alloca (from - filename + 1);
5046 bcopy (filename, dir, from - filename);
5047 dir[from - filename] = '\0';
5049 for (map = read_name_map (dir); map; map = map->map_next)
5050 if (! strcmp (map->map_from, from))
5057 /* Insert INC into the include file table, hashed by device and inode number.
5058 If a file with different name but same dev+ino was already in the table,
5059 return 1 and set INC's control macro to the already-known macro. */
5062 lookup_ino_include (inc)
5063 struct include_file *inc;
5065 int hash = ((unsigned) (inc->st.st_dev + INO_T_HASH (inc->st.st_ino))
5066 % INCLUDE_HASHSIZE);
5067 struct include_file *i = include_ino_hashtab[hash];
5069 include_ino_hashtab[hash] = inc;
5071 for (; i; i = i->next_ino)
5072 if (INO_T_EQ (inc->st.st_ino, i->st.st_ino)
5073 && inc->st.st_dev == i->st.st_dev) {
5074 inc->control_macro = i->control_macro;
5081 /* Process file descriptor F, which corresponds to include file INC,
5083 SYSTEM_HEADER_P is 1 if this file resides in any one of the known
5084 "system" include directories (as decided by the `is_system_include'
5086 DIRPTR is the link in the dir path through which this file was found,
5087 or 0 if the file name was absolute. */
5090 finclude (f, inc, op, system_header_p, dirptr)
5092 struct include_file *inc;
5094 int system_header_p;
5095 struct file_name_list *dirptr;
5097 char *fname = inc->fname;
5099 FILE_BUF *fp; /* For input stack frame */
5100 int missing_newline = 0;
5102 CHECK_DEPTH (return;);
5104 fp = &instack[indepth + 1];
5105 bzero ((char *) fp, sizeof (FILE_BUF));
5106 fp->nominal_fname = fp->fname = fname;
5107 fp->nominal_fname_len = strlen (fname);
5111 fp->if_stack = if_stack;
5112 fp->system_header_p = system_header_p;
5115 if (S_ISREG (inc->st.st_mode)) {
5116 size_t s = (size_t) inc->st.st_size;
5117 if (s != inc->st.st_size || s + 2 < s)
5119 fp->buf = (U_CHAR *) xmalloc (s + 2);
5122 /* Read the file contents, knowing that s is an upper bound
5123 on the number of bytes we can read. */
5124 fp->length = safe_read (f, (char *) fp->buf, s);
5125 if (fp->length < 0) goto nope;
5127 else if (S_ISDIR (inc->st.st_mode)) {
5128 error ("directory `%s' specified in #include", fname);
5132 /* Cannot count its file size before reading.
5133 First read the entire file into heap and
5134 copy them into buffer on stack. */
5139 fp->buf = (U_CHAR *) xmalloc (bsize + 2);
5142 i = safe_read (f, (char *) fp->buf + st_size, bsize - st_size);
5144 goto nope; /* error! */
5146 if (st_size != bsize)
5147 break; /* End of file */
5149 fp->buf = (U_CHAR *) xrealloc (fp->buf, bsize + 2);
5152 fp->length = st_size;
5155 if ((fp->length > 0 && fp->buf[fp->length - 1] != '\n')
5156 /* Backslash-newline at end is not good enough. */
5157 || (fp->length > 1 && fp->buf[fp->length - 2] == '\\')) {
5158 fp->buf[fp->length++] = '\n';
5159 missing_newline = 1;
5161 fp->buf[fp->length] = '\0';
5163 /* Close descriptor now, so nesting does not use lots of descriptors. */
5166 /* Must do this before calling trigraph_pcp, so that the correct file name
5167 will be printed in warning messages. */
5170 input_file_stack_tick++;
5175 output_line_directive (fp, op, 0, enter_file);
5178 if (missing_newline)
5181 if (pedantic && missing_newline)
5182 pedwarn ("file does not end in newline");
5185 input_file_stack_tick++;
5186 output_line_directive (&instack[indepth], op, 0, leave_file);
5192 perror_with_name (fname);
5197 /* Record that inclusion of the include file INC
5198 should be controlled by the macro named MACRO_NAME.
5199 This means that trying to include the file again
5200 will do something if that macro is defined. */
5203 record_control_macro (inc, macro_name)
5204 struct include_file *inc;
5207 if (!inc->control_macro || inc->control_macro[0])
5208 inc->control_macro = macro_name;
5211 /* Load the specified precompiled header into core, and verify its
5212 preconditions. PCF indicates the file descriptor to read, which must
5213 be a regular file. *ST is its file status.
5214 FNAME indicates the file name of the original header.
5215 *LIMIT will be set to an address one past the end of the file.
5216 If the preconditions of the file are not satisfied, the buffer is
5217 freed and we return 0. If the preconditions are satisfied, return
5218 the address of the buffer following the preconditions. The buffer, in
5219 this case, should never be freed because various pieces of it will
5220 be referred to until all precompiled strings are output at the end of
5224 check_precompiled (pcf, st, fname, limit)
5227 char *fname ATTRIBUTE_UNUSED;
5237 if (S_ISREG (st->st_mode))
5239 size_t s = (size_t) st->st_size;
5240 if (s != st->st_size || s + 2 < s)
5242 buf = xmalloc (s + 2);
5243 length = safe_read (pcf, buf, s);
5250 if (length > 0 && buf[length-1] != '\n')
5251 buf[length++] = '\n';
5254 *limit = buf + length;
5256 /* File is in core. Check the preconditions. */
5257 if (!check_preconditions (buf))
5259 for (cp = buf; *cp; cp++)
5262 fprintf (stderr, "Using preinclude %s\n", fname);
5268 fprintf (stderr, "Cannot use preinclude %s\n", fname);
5274 /* PREC (null terminated) points to the preconditions of a
5275 precompiled header. These are a series of #define and #undef
5276 lines which must match the current contents of the hash
5280 check_preconditions (prec)
5287 lineend = index (prec, '\n');
5289 if (*prec++ != '#') {
5290 error ("Bad format encountered while reading precompiled file");
5293 if (!strncmp (prec, "define", 6)) {
5297 mdef = create_definition ((U_CHAR *) prec, (U_CHAR *) lineend, NULL_PTR);
5302 if ((hp = lookup (mdef.symnam, mdef.symlen, -1)) == NULL
5303 || (hp->type != T_MACRO && hp->type != T_CONST)
5304 || (hp->type == T_MACRO
5305 && !compare_defs (mdef.defn, hp->value.defn)
5306 && (mdef.defn->length != 2
5307 || mdef.defn->expansion[0] != '\n'
5308 || mdef.defn->expansion[1] != ' ')))
5310 } else if (!strncmp (prec, "undef", 5)) {
5315 while (is_hor_space[(U_CHAR) *prec])
5318 while (is_idchar[(U_CHAR) *prec])
5322 if (lookup ((U_CHAR *) name, len, -1))
5325 error ("Bad format encountered while reading precompiled file");
5330 /* They all passed successfully */
5334 /* Process the main body of a precompiled file. BUF points to the
5335 string section of the file, following the preconditions. LIMIT is one
5336 character past the end. NAME is the name of the file being read
5337 in. OP is the main output buffer. */
5340 pcfinclude (buf, limit, name, op)
5341 U_CHAR *buf, *limit, *name;
5348 /* First in the file comes 4 bytes indicating the number of strings, */
5349 /* in network byte order. (MSB first). */
5351 nstrings = (nstrings << 8) | *cp++;
5352 nstrings = (nstrings << 8) | *cp++;
5353 nstrings = (nstrings << 8) | *cp++;
5355 /* Looping over each string... */
5356 while (nstrings--) {
5357 U_CHAR *string_start;
5358 U_CHAR *endofthiskey;
5362 /* Each string starts with a STRINGDEF structure (str), followed */
5363 /* by the text of the string (string_start) */
5365 /* First skip to a longword boundary */
5366 /* ??? Why a 4-byte boundary? On all machines? */
5367 /* NOTE: This works correctly even if size_t
5368 is narrower than a pointer.
5369 Do not try risky measures here to get another type to use!
5370 Do not include stddef.h--it will fail! */
5371 if ((size_t) cp & 3)
5372 cp += 4 - ((size_t) cp & 3);
5374 /* Now get the string. */
5375 str = (STRINGDEF *) (GENERIC_PTR) cp;
5376 string_start = cp += sizeof (STRINGDEF);
5378 for (; *cp; cp++) /* skip the string */
5381 /* We need to macro expand the string here to ensure that the
5382 proper definition environment is in place. If it were only
5383 expanded when we find out it is needed, macros necessary for
5384 its proper expansion might have had their definitions changed. */
5385 tmpbuf = expand_to_temp_buffer (string_start, cp++, 0, 0);
5386 /* Lineno is already set in the precompiled file */
5387 str->contents = tmpbuf.buf;
5388 str->len = tmpbuf.length;
5390 str->filename = name;
5391 str->output_mark = outbuf.bufp - outbuf.buf;
5394 *stringlist_tailp = str;
5395 stringlist_tailp = &str->chain;
5397 /* Next comes a fourbyte number indicating the number of keys
5400 nkeys = (nkeys << 8) | *cp++;
5401 nkeys = (nkeys << 8) | *cp++;
5402 nkeys = (nkeys << 8) | *cp++;
5404 /* If this number is -1, then the string is mandatory. */
5408 /* Otherwise, for each key, */
5409 for (; nkeys--; free (tmpbuf.buf), cp = endofthiskey + 1) {
5410 KEYDEF *kp = (KEYDEF *) (GENERIC_PTR) cp;
5413 /* It starts with a KEYDEF structure */
5414 cp += sizeof (KEYDEF);
5416 /* Find the end of the key. At the end of this for loop we
5417 advance CP to the start of the next key using this variable. */
5418 endofthiskey = cp + strlen ((char *) cp);
5421 /* Expand the key, and enter it into the hash table. */
5422 tmpbuf = expand_to_temp_buffer (cp, endofthiskey, 0, 0);
5423 tmpbuf.bufp = tmpbuf.buf;
5425 while (is_hor_space[*tmpbuf.bufp])
5427 if (!is_idstart[*tmpbuf.bufp]
5428 || tmpbuf.bufp == tmpbuf.buf + tmpbuf.length) {
5433 hp = lookup (tmpbuf.bufp, -1, -1);
5436 install (tmpbuf.bufp, -1, T_PCSTRING, (char *) kp, -1);
5438 else if (hp->type == T_PCSTRING) {
5439 kp->chain = hp->value.keydef;
5440 hp->value.keydef = kp;
5446 /* This output_line_directive serves to switch us back to the current
5447 input file in case some of these strings get output (which will
5448 result in line directives for the header file being output). */
5449 output_line_directive (&instack[indepth], op, 0, enter_file);
5452 /* Called from rescan when it hits a key for strings. Mark them all
5453 used and clean up. */
5461 for (kp = hp->value.keydef; kp; kp = kp->chain)
5462 kp->str->writeflag = 1;
5466 /* Write the output, interspersing precompiled strings in their
5467 appropriate places. */
5472 STRINGDEF *next_string;
5473 U_CHAR *cur_buf_loc;
5474 int line_directive_len = 80;
5475 char *line_directive = xmalloc (line_directive_len);
5478 /* In each run through the loop, either cur_buf_loc ==
5479 next_string_loc, in which case we print a series of strings, or
5480 it is less than next_string_loc, in which case we write some of
5482 cur_buf_loc = outbuf.buf;
5483 next_string = stringlist;
5485 while (cur_buf_loc < outbuf.bufp || next_string) {
5487 && cur_buf_loc - outbuf.buf == next_string->output_mark) {
5488 if (next_string->writeflag) {
5489 len = 4 * strlen ((char *) next_string->filename) + 32;
5490 while (len > line_directive_len)
5491 line_directive = xrealloc (line_directive,
5492 line_directive_len *= 2);
5493 sprintf (line_directive, "\n# %d ", next_string->lineno);
5494 strcpy (quote_string (line_directive + strlen (line_directive),
5495 (char *) next_string->filename,
5496 strlen ((char *) next_string->filename)),
5498 safe_write (fileno (stdout), line_directive, strlen (line_directive));
5499 safe_write (fileno (stdout),
5500 (char *) next_string->contents, next_string->len);
5502 next_string = next_string->chain;
5506 ? (next_string->output_mark
5507 - (cur_buf_loc - outbuf.buf))
5508 : outbuf.bufp - cur_buf_loc);
5510 safe_write (fileno (stdout), (char *) cur_buf_loc, len);
5514 free (line_directive);
5517 /* Pass a directive through to the output file.
5518 BUF points to the contents of the directive, as a contiguous string.
5519 LIMIT points to the first character past the end of the directive.
5520 KEYWORD is the keyword-table entry for the directive. */
5523 pass_thru_directive (buf, limit, op, keyword)
5524 U_CHAR *buf, *limit;
5526 struct directive *keyword;
5528 register unsigned keyword_length = keyword->length;
5530 check_expand (op, 1 + keyword_length + (limit - buf));
5532 bcopy (keyword->name, (char *) op->bufp, keyword_length);
5533 op->bufp += keyword_length;
5534 if (limit != buf && buf[0] != ' ')
5536 bcopy ((char *) buf, (char *) op->bufp, limit - buf);
5537 op->bufp += (limit - buf);
5540 /* Count the line we have just made in the output,
5541 to get in sync properly. */
5546 /* The arglist structure is built by do_define to tell
5547 collect_definition where the argument names begin. That
5548 is, for a define like "#define f(x,y,z) foo+x-bar*y", the arglist
5549 would contain pointers to the strings x, y, and z.
5550 Collect_definition would then build a DEFINITION node,
5551 with reflist nodes pointing to the places x, y, and z had
5552 appeared. So the arglist is just convenience data passed
5553 between these two routines. It is not kept around after
5554 the current #define has been processed and entered into the
5558 struct arglist *next;
5565 /* Create a DEFINITION node from a #define directive. Arguments are
5566 as for do_define. */
5569 create_definition (buf, limit, op)
5570 U_CHAR *buf, *limit;
5573 U_CHAR *bp; /* temp ptr into input buffer */
5574 U_CHAR *symname; /* remember where symbol name starts */
5575 int sym_length; /* and how long it is */
5576 int line = instack[indepth].lineno;
5577 char *file = instack[indepth].nominal_fname;
5578 size_t file_len = instack[indepth].nominal_fname_len;
5582 int arglengths = 0; /* Accumulate lengths of arg names
5583 plus number of args. */
5588 while (is_hor_space[*bp])
5591 symname = bp; /* remember where it starts */
5592 sym_length = check_macro_name (bp, "macro");
5595 /* Lossage will occur if identifiers or control keywords are broken
5596 across lines using backslash. This is not the right place to take
5600 struct arglist *arg_ptrs = NULL;
5603 bp++; /* skip '(' */
5604 SKIP_WHITE_SPACE (bp);
5606 /* Loop over macro argument names. */
5607 while (*bp != ')') {
5608 struct arglist *temp;
5610 temp = (struct arglist *) alloca (sizeof (struct arglist));
5612 temp->next = arg_ptrs;
5613 temp->argno = argno++;
5614 temp->rest_args = 0;
5618 pedwarn ("another parameter follows `%s'",
5621 if (!is_idstart[*bp])
5622 pedwarn ("invalid character in macro parameter name");
5624 /* Find the end of the arg name. */
5625 while (is_idchar[*bp]) {
5627 /* do we have a "special" rest-args extension here? */
5628 if (limit - bp > REST_EXTENSION_LENGTH
5629 && bcmp (rest_extension, bp, REST_EXTENSION_LENGTH) == 0) {
5630 if (pedantic && !instack[indepth].system_header_p)
5631 pedwarn ("ANSI C does not allow macro with variable arguments");
5633 temp->rest_args = 1;
5637 temp->length = bp - temp->name;
5639 bp += REST_EXTENSION_LENGTH;
5640 arglengths += temp->length + 2;
5641 SKIP_WHITE_SPACE (bp);
5642 if (temp->length == 0 || (*bp != ',' && *bp != ')')) {
5643 error ("badly punctuated parameter list in `#define'");
5648 SKIP_WHITE_SPACE (bp);
5649 /* A comma at this point can only be followed by an identifier. */
5650 if (!is_idstart[*bp]) {
5651 error ("badly punctuated parameter list in `#define'");
5656 error ("unterminated parameter list in `#define'");
5660 struct arglist *otemp;
5662 for (otemp = temp->next; otemp != NULL; otemp = otemp->next)
5663 if (temp->length == otemp->length
5664 && bcmp (temp->name, otemp->name, temp->length) == 0) {
5665 error ("duplicate argument name `%.*s' in `#define'",
5666 temp->length, temp->name);
5672 ++bp; /* skip paren */
5673 SKIP_WHITE_SPACE (bp);
5674 /* now everything from bp before limit is the definition. */
5675 defn = collect_expansion (bp, limit, argno, arg_ptrs);
5676 defn->rest_args = rest_args;
5678 /* Now set defn->args.argnames to the result of concatenating
5679 the argument names in reverse order
5680 with comma-space between them. */
5681 defn->args.argnames = (U_CHAR *) xmalloc (arglengths + 1);
5683 struct arglist *temp;
5685 for (temp = arg_ptrs; temp; temp = temp->next) {
5686 bcopy (temp->name, &defn->args.argnames[i], temp->length);
5688 if (temp->next != 0) {
5689 defn->args.argnames[i++] = ',';
5690 defn->args.argnames[i++] = ' ';
5693 defn->args.argnames[i] = 0;
5696 /* Simple expansion or empty definition. */
5700 if (is_hor_space[*bp]) {
5702 SKIP_WHITE_SPACE (bp);
5703 } else if (sym_length) {
5705 case '!': case '"': case '#': case '%': case '&': case '\'':
5706 case ')': case '*': case '+': case ',': case '-': case '.':
5707 case '/': case ':': case ';': case '<': case '=': case '>':
5708 case '?': case '[': case '\\': case ']': case '^': case '{':
5709 case '|': case '}': case '~':
5710 warning ("missing white space after `#define %.*s'",
5711 sym_length, symname);
5715 pedwarn ("missing white space after `#define %.*s'",
5716 sym_length, symname);
5721 /* Now everything from bp before limit is the definition. */
5722 defn = collect_expansion (bp, limit, -1, NULL_PTR);
5723 defn->args.argnames = (U_CHAR *) "";
5728 defn->file_len = file_len;
5730 /* OP is null if this is a predefinition */
5731 defn->predefined = !op;
5733 mdef.symnam = symname;
5734 mdef.symlen = sym_length;
5743 /* Process a #define directive.
5744 BUF points to the contents of the #define directive, as a contiguous string.
5745 LIMIT points to the first character past the end of the definition.
5746 KEYWORD is the keyword-table entry for #define. */
5749 do_define (buf, limit, op, keyword)
5750 U_CHAR *buf, *limit;
5752 struct directive *keyword;
5757 /* If this is a precompiler run (with -pcp) pass thru #define directives. */
5758 if (pcp_outfile && op)
5759 pass_thru_directive (buf, limit, op, keyword);
5761 mdef = create_definition (buf, limit, op);
5765 hashcode = hashf (mdef.symnam, mdef.symlen, HASHSIZE);
5769 if ((hp = lookup (mdef.symnam, mdef.symlen, hashcode)) != NULL) {
5771 /* Redefining a precompiled key is ok. */
5772 if (hp->type == T_PCSTRING)
5774 /* Redefining a macro is ok if the definitions are the same. */
5775 else if (hp->type == T_MACRO)
5776 ok = ! compare_defs (mdef.defn, hp->value.defn);
5777 /* Redefining a constant is ok with -D. */
5778 else if (hp->type == T_CONST)
5779 ok = ! done_initializing;
5780 /* Print the warning if it's not ok. */
5782 /* If we are passing through #define and #undef directives, do
5783 that for this re-definition now. */
5784 if (debug_output && op)
5785 pass_thru_directive (buf, limit, op, keyword);
5787 pedwarn ("`%.*s' redefined", mdef.symlen, mdef.symnam);
5788 if (hp->type == T_MACRO)
5789 pedwarn_with_file_and_line (hp->value.defn->file,
5790 hp->value.defn->file_len,
5791 hp->value.defn->line,
5792 "this is the location of the previous definition");
5794 /* Replace the old definition. */
5796 hp->value.defn = mdef.defn;
5798 /* If we are passing through #define and #undef directives, do
5799 that for this new definition now. */
5800 if (debug_output && op)
5801 pass_thru_directive (buf, limit, op, keyword);
5802 install (mdef.symnam, mdef.symlen, T_MACRO,
5803 (char *) mdef.defn, hashcode);
5814 /* Check a purported macro name SYMNAME, and yield its length.
5815 USAGE is the kind of name this is intended for. */
5818 check_macro_name (symname, usage)
5825 for (p = symname; is_idchar[*p]; p++)
5827 sym_length = p - symname;
5829 || (sym_length == 1 && *symname == 'L' && (*p == '\'' || *p == '"')))
5830 error ("invalid %s name", usage);
5831 else if (!is_idstart[*symname]
5832 || (sym_length == 7 && ! bcmp (symname, "defined", 7)))
5833 error ("invalid %s name `%.*s'", usage, sym_length, symname);
5837 /* Return zero if two DEFINITIONs are isomorphic. */
5840 compare_defs (d1, d2)
5841 DEFINITION *d1, *d2;
5843 register struct reflist *a1, *a2;
5844 register U_CHAR *p1 = d1->expansion;
5845 register U_CHAR *p2 = d2->expansion;
5848 if (d1->nargs != d2->nargs)
5851 && strcmp ((char *)d1->args.argnames, (char *)d2->args.argnames))
5853 for (a1 = d1->pattern, a2 = d2->pattern; a1 && a2;
5854 a1 = a1->next, a2 = a2->next) {
5855 if (!((a1->nchars == a2->nchars && ! bcmp (p1, p2, a1->nchars))
5856 || ! comp_def_part (first, p1, a1->nchars, p2, a2->nchars, 0))
5857 || a1->argno != a2->argno
5858 || a1->stringify != a2->stringify
5859 || a1->raw_before != a2->raw_before
5860 || a1->raw_after != a2->raw_after)
5868 if (comp_def_part (first, p1, d1->length - (p1 - d1->expansion),
5869 p2, d2->length - (p2 - d2->expansion), 1))
5874 /* Return 1 if two parts of two macro definitions are effectively different.
5875 One of the parts starts at BEG1 and has LEN1 chars;
5876 the other has LEN2 chars at BEG2.
5877 Any sequence of whitespace matches any other sequence of whitespace.
5878 FIRST means these parts are the first of a macro definition;
5879 so ignore leading whitespace entirely.
5880 LAST means these parts are the last of a macro definition;
5881 so ignore trailing whitespace entirely. */
5884 comp_def_part (first, beg1, len1, beg2, len2, last)
5886 U_CHAR *beg1, *beg2;
5890 register U_CHAR *end1 = beg1 + len1;
5891 register U_CHAR *end2 = beg2 + len2;
5893 while (beg1 != end1 && is_space[*beg1]) beg1++;
5894 while (beg2 != end2 && is_space[*beg2]) beg2++;
5897 while (beg1 != end1 && is_space[end1[-1]]) end1--;
5898 while (beg2 != end2 && is_space[end2[-1]]) end2--;
5900 while (beg1 != end1 && beg2 != end2) {
5901 if (is_space[*beg1] && is_space[*beg2]) {
5902 while (beg1 != end1 && is_space[*beg1]) beg1++;
5903 while (beg2 != end2 && is_space[*beg2]) beg2++;
5904 } else if (*beg1 == *beg2) {
5908 return (beg1 != end1) || (beg2 != end2);
5911 /* Read a replacement list for a macro with parameters.
5912 Build the DEFINITION structure.
5913 Reads characters of text starting at BUF until END.
5914 ARGLIST specifies the formal parameters to look for
5915 in the text of the definition; NARGS is the number of args
5916 in that list, or -1 for a macro name that wants no argument list.
5917 MACRONAME is the macro name itself (so we can avoid recursive expansion)
5918 and NAMELEN is its length in characters.
5920 Note that comments, backslash-newlines, and leading white space
5921 have already been deleted from the argument. */
5923 /* If there is no trailing whitespace, a Newline Space is added at the end
5924 to prevent concatenation that would be contrary to the standard. */
5927 collect_expansion (buf, end, nargs, arglist)
5930 struct arglist *arglist;
5933 register U_CHAR *p, *limit, *lastp, *exp_p;
5934 struct reflist *endpat = NULL;
5935 /* Pointer to first nonspace after last ## seen. */
5937 /* Pointer to first nonspace after last single-# seen. */
5938 U_CHAR *stringify = 0;
5939 /* How those tokens were spelled. */
5940 enum sharp_token_type concat_sharp_token_type = NO_SHARP_TOKEN;
5941 enum sharp_token_type stringify_sharp_token_type = NO_SHARP_TOKEN;
5943 int expected_delimiter = '\0';
5945 /* Scan thru the replacement list, ignoring comments and quoted
5946 strings, picking up on the macro calls. It does a linear search
5947 thru the arg list on every potential symbol. Profiling might say
5948 that something smarter should happen. */
5953 /* Find the beginning of the trailing whitespace. */
5956 while (p < limit && is_space[limit[-1]]) limit--;
5958 /* Allocate space for the text in the macro definition.
5959 Each input char may or may not need 1 byte,
5960 so this is an upper bound.
5961 The extra 3 are for invented trailing newline-marker and final null. */
5962 maxsize = (sizeof (DEFINITION)
5964 defn = (DEFINITION *) xcalloc (1, maxsize);
5966 defn->nargs = nargs;
5967 exp_p = defn->expansion = (U_CHAR *) defn + sizeof (DEFINITION);
5972 : p[0] == '%' && p[1] == ':' && p[2] == '%' && p[3] == ':') {
5973 error ("`##' at start of macro definition");
5974 p += p[0] == '#' ? 2 : 4;
5977 /* Process the main body of the definition. */
5979 int skipped_arg = 0;
5980 register U_CHAR c = *p++;
5988 if (expected_delimiter != '\0') {
5989 if (c == expected_delimiter)
5990 expected_delimiter = '\0';
5992 expected_delimiter = c;
5996 if (p < limit && expected_delimiter) {
5997 /* In a string, backslash goes through
5998 and makes next char ordinary. */
6004 if (!expected_delimiter && *p == ':') {
6005 /* %: is not a digraph if preceded by an odd number of '<'s. */
6007 while (buf < p0 && p0[-1] == '<')
6010 /* Treat %:%: as ## and %: as #. */
6011 if (p[1] == '%' && p[2] == ':') {
6013 goto sharp_sharp_token;
6024 /* # is ordinary inside a string. */
6025 if (expected_delimiter)
6029 /* ##: concatenate preceding and following tokens. */
6030 /* Take out the first #, discard preceding whitespace. */
6032 while (exp_p > lastp && is_hor_space[exp_p[-1]])
6034 /* Skip the second #. */
6036 concat_sharp_token_type = c;
6037 if (is_hor_space[*p]) {
6038 concat_sharp_token_type = c + 1;
6040 SKIP_WHITE_SPACE (p);
6044 error ("`##' at end of macro definition");
6045 } else if (nargs >= 0) {
6046 /* Single #: stringify following argument ref.
6047 Don't leave the # in the expansion. */
6050 stringify_sharp_token_type = c;
6051 if (is_hor_space[*p]) {
6052 stringify_sharp_token_type = c + 1;
6054 SKIP_WHITE_SPACE (p);
6056 if (! is_idstart[*p] || nargs == 0
6057 || (*p == 'L' && (p[1] == '\'' || p[1] == '"')))
6058 error ("`#' operator is not followed by a macro argument name");
6065 /* In -traditional mode, recognize arguments inside strings and
6066 character constants, and ignore special properties of #.
6067 Arguments inside strings are considered "stringified", but no
6068 extra quote marks are supplied. */
6072 if (expected_delimiter != '\0') {
6073 if (c == expected_delimiter)
6074 expected_delimiter = '\0';
6076 expected_delimiter = c;
6080 /* Backslash quotes delimiters and itself, but not macro args. */
6081 if (expected_delimiter != 0 && p < limit
6082 && (*p == expected_delimiter || *p == '\\')) {
6089 if (expected_delimiter != '\0') /* No comments inside strings. */
6092 /* If we find a comment that wasn't removed by handle_directive,
6093 this must be -traditional. So replace the comment with
6096 while (++p < limit) {
6097 if (p[0] == '*' && p[1] == '/') {
6103 /* Mark this as a concatenation-point, as if it had been ##. */
6111 /* Handle the start of a symbol. */
6112 if (is_idchar[c] && nargs > 0) {
6113 U_CHAR *id_beg = p - 1;
6117 while (p != limit && is_idchar[*p]) p++;
6118 id_len = p - id_beg;
6121 && ! (id_len == 1 && c == 'L' && (*p == '\'' || *p == '"'))) {
6122 register struct arglist *arg;
6124 for (arg = arglist; arg != NULL; arg = arg->next) {
6125 struct reflist *tpat;
6127 if (arg->name[0] == c
6128 && arg->length == id_len
6129 && bcmp (arg->name, id_beg, id_len) == 0) {
6130 enum sharp_token_type tpat_stringify;
6131 if (expected_delimiter) {
6132 if (warn_stringify) {
6134 warning ("macro argument `%.*s' is stringified.",
6137 warning ("macro arg `%.*s' would be stringified with -traditional.",
6141 /* If ANSI, don't actually substitute inside a string. */
6144 tpat_stringify = SHARP_TOKEN;
6147 = (stringify == id_beg
6148 ? stringify_sharp_token_type : NO_SHARP_TOKEN);
6150 /* make a pat node for this arg and append it to the end of
6152 tpat = (struct reflist *) xmalloc (sizeof (struct reflist));
6155 = concat == id_beg ? concat_sharp_token_type : NO_SHARP_TOKEN;
6156 tpat->raw_after = NO_SHARP_TOKEN;
6157 tpat->rest_args = arg->rest_args;
6158 tpat->stringify = tpat_stringify;
6161 defn->pattern = tpat;
6163 endpat->next = tpat;
6166 tpat->argno = arg->argno;
6167 tpat->nchars = exp_p - lastp;
6169 register U_CHAR *p1 = p;
6170 SKIP_WHITE_SPACE (p1);
6173 : p1[0]=='%' && p1[1]==':' && p1[2]=='%' && p1[3]==':')
6174 tpat->raw_after = p1[0] + (p != p1);
6176 lastp = exp_p; /* place to start copying from next time */
6183 /* If this was not a macro arg, copy it into the expansion. */
6184 if (! skipped_arg) {
6185 register U_CHAR *lim1 = p;
6189 if (stringify == id_beg)
6190 error ("`#' operator should be followed by a macro argument name");
6195 if (!traditional && expected_delimiter == 0) {
6196 /* If ANSI, put in a newline-space marker to prevent token pasting.
6197 But not if "inside a string" (which in ANSI mode happens only for
6205 defn->length = exp_p - defn->expansion;
6207 /* Crash now if we overrun the allocated size. */
6208 if (defn->length + 1 > maxsize)
6212 /* This isn't worth the time it takes. */
6213 /* give back excess storage */
6214 defn->expansion = (U_CHAR *) xrealloc (defn->expansion, defn->length + 1);
6221 do_assert (buf, limit, op, keyword)
6222 U_CHAR *buf, *limit;
6223 FILE_BUF *op ATTRIBUTE_UNUSED;
6224 struct directive *keyword ATTRIBUTE_UNUSED;
6226 U_CHAR *bp; /* temp ptr into input buffer */
6227 U_CHAR *symname; /* remember where symbol name starts */
6228 int sym_length; /* and how long it is */
6229 struct arglist *tokens = NULL;
6231 if (pedantic && done_initializing && !instack[indepth].system_header_p)
6232 pedwarn ("ANSI C does not allow `#assert'");
6236 while (is_hor_space[*bp])
6239 symname = bp; /* remember where it starts */
6240 sym_length = check_macro_name (bp, "assertion");
6242 /* #define doesn't do this, but we should. */
6243 SKIP_WHITE_SPACE (bp);
6245 /* Lossage will occur if identifiers or control tokens are broken
6246 across lines using backslash. This is not the right place to take
6250 error ("missing token-sequence in `#assert'");
6257 bp++; /* skip '(' */
6258 SKIP_WHITE_SPACE (bp);
6260 tokens = read_token_list (&bp, limit, &error_flag);
6264 error ("empty token-sequence in `#assert'");
6268 ++bp; /* skip paren */
6269 SKIP_WHITE_SPACE (bp);
6272 /* If this name isn't already an assertion name, make it one.
6273 Error if it was already in use in some other way. */
6276 ASSERTION_HASHNODE *hp;
6277 int hashcode = hashf (symname, sym_length, ASSERTION_HASHSIZE);
6278 struct tokenlist_list *value
6279 = (struct tokenlist_list *) xmalloc (sizeof (struct tokenlist_list));
6281 hp = assertion_lookup (symname, sym_length, hashcode);
6283 if (sym_length == 7 && ! bcmp (symname, "defined", 7))
6284 error ("`defined' redefined as assertion");
6285 hp = assertion_install (symname, sym_length, hashcode);
6288 /* Add the spec'd token-sequence to the list of such. */
6289 value->tokens = tokens;
6290 value->next = hp->value;
6298 do_unassert (buf, limit, op, keyword)
6299 U_CHAR *buf, *limit;
6300 FILE_BUF *op ATTRIBUTE_UNUSED;
6301 struct directive *keyword ATTRIBUTE_UNUSED;
6303 U_CHAR *bp; /* temp ptr into input buffer */
6304 U_CHAR *symname; /* remember where symbol name starts */
6305 int sym_length; /* and how long it is */
6307 struct arglist *tokens = NULL;
6308 int tokens_specified = 0;
6310 if (pedantic && done_initializing && !instack[indepth].system_header_p)
6311 pedwarn ("ANSI C does not allow `#unassert'");
6315 while (is_hor_space[*bp])
6318 symname = bp; /* remember where it starts */
6319 sym_length = check_macro_name (bp, "assertion");
6321 /* #define doesn't do this, but we should. */
6322 SKIP_WHITE_SPACE (bp);
6324 /* Lossage will occur if identifiers or control tokens are broken
6325 across lines using backslash. This is not the right place to take
6331 bp++; /* skip '(' */
6332 SKIP_WHITE_SPACE (bp);
6334 tokens = read_token_list (&bp, limit, &error_flag);
6338 error ("empty token list in `#unassert'");
6342 tokens_specified = 1;
6344 ++bp; /* skip paren */
6345 SKIP_WHITE_SPACE (bp);
6349 ASSERTION_HASHNODE *hp;
6350 int hashcode = hashf (symname, sym_length, ASSERTION_HASHSIZE);
6351 struct tokenlist_list *tail, *prev;
6353 hp = assertion_lookup (symname, sym_length, hashcode);
6357 /* If no token list was specified, then eliminate this assertion
6359 if (! tokens_specified) {
6360 struct tokenlist_list *next;
6361 for (tail = hp->value; tail; tail = next) {
6363 free_token_list (tail->tokens);
6366 delete_assertion (hp);
6368 /* If a list of tokens was given, then delete any matching list. */
6373 struct tokenlist_list *next = tail->next;
6374 if (compare_token_lists (tail->tokens, tokens)) {
6378 hp->value = tail->next;
6379 free_token_list (tail->tokens);
6392 /* Test whether there is an assertion named NAME
6393 and optionally whether it has an asserted token list TOKENS.
6394 NAME is not null terminated; its length is SYM_LENGTH.
6395 If TOKENS_SPECIFIED is 0, then don't check for any token list. */
6398 check_assertion (name, sym_length, tokens_specified, tokens)
6401 int tokens_specified;
6402 struct arglist *tokens;
6404 ASSERTION_HASHNODE *hp;
6405 int hashcode = hashf (name, sym_length, ASSERTION_HASHSIZE);
6407 if (pedantic && !instack[indepth].system_header_p)
6408 pedwarn ("ANSI C does not allow testing assertions");
6410 hp = assertion_lookup (name, sym_length, hashcode);
6412 /* It is not an assertion; just return false. */
6415 /* If no token list was specified, then value is 1. */
6416 if (! tokens_specified)
6420 struct tokenlist_list *tail;
6424 /* If a list of tokens was given,
6425 then succeed if the assertion records a matching list. */
6428 if (compare_token_lists (tail->tokens, tokens))
6433 /* Fail if the assertion has no matching list. */
6438 /* Compare two lists of tokens for equality including order of tokens. */
6441 compare_token_lists (l1, l2)
6442 struct arglist *l1, *l2;
6445 if (l1->length != l2->length)
6447 if (bcmp (l1->name, l2->name, l1->length))
6453 /* Succeed if both lists end at the same time. */
6457 /* Read a space-separated list of tokens ending in a close parenthesis.
6458 Return a list of strings, in the order they were written.
6459 (In case of error, return 0 and store -1 in *ERROR_FLAG.)
6460 Parse the text starting at *BPP, and update *BPP.
6461 Don't parse beyond LIMIT. */
6463 static struct arglist *
6464 read_token_list (bpp, limit, error_flag)
6469 struct arglist *token_ptrs = 0;
6475 /* Loop over the assertion value tokens. */
6477 struct arglist *temp;
6481 /* Find the end of the token. */
6485 } else if (*bp == ')') {
6490 } else if (*bp == '"' || *bp == '\'')
6491 bp = skip_quoted_string (bp, limit, 0, NULL_PTR, NULL_PTR, &eofp);
6493 while (! is_hor_space[*bp] && *bp != '(' && *bp != ')'
6494 && *bp != '"' && *bp != '\'' && bp != limit)
6497 temp = (struct arglist *) xmalloc (sizeof (struct arglist));
6498 temp->name = (U_CHAR *) xmalloc (bp - beg + 1);
6499 bcopy ((char *) beg, (char *) temp->name, bp - beg);
6500 temp->name[bp - beg] = 0;
6501 temp->next = token_ptrs;
6503 temp->length = bp - beg;
6505 SKIP_WHITE_SPACE (bp);
6508 error ("unterminated token sequence in `#assert' or `#unassert'");
6515 /* We accumulated the names in reverse order.
6516 Now reverse them to get the proper order. */
6518 register struct arglist *prev = 0, *this, *next;
6519 for (this = token_ptrs; this; this = next) {
6529 free_token_list (tokens)
6530 struct arglist *tokens;
6533 struct arglist *next = tokens->next;
6534 free (tokens->name);
6540 /* Install a name in the assertion hash table.
6542 If LEN is >= 0, it is the length of the name.
6543 Otherwise, compute the length by scanning the entire name.
6545 If HASH is >= 0, it is the precomputed hash code.
6546 Otherwise, compute the hash code. */
6548 static ASSERTION_HASHNODE *
6549 assertion_install (name, len, hash)
6554 register ASSERTION_HASHNODE *hp;
6555 register int i, bucket;
6556 register U_CHAR *p, *q;
6558 i = sizeof (ASSERTION_HASHNODE) + len + 1;
6559 hp = (ASSERTION_HASHNODE *) xmalloc (i);
6561 hp->bucket_hdr = &assertion_hashtab[bucket];
6562 hp->next = assertion_hashtab[bucket];
6563 assertion_hashtab[bucket] = hp;
6565 if (hp->next != NULL)
6566 hp->next->prev = hp;
6569 hp->name = ((U_CHAR *) hp) + sizeof (ASSERTION_HASHNODE);
6572 for (i = 0; i < len; i++)
6578 /* Find the most recent hash node for name "name" (ending with first
6579 non-identifier char) installed by install
6581 If LEN is >= 0, it is the length of the name.
6582 Otherwise, compute the length by scanning the entire name.
6584 If HASH is >= 0, it is the precomputed hash code.
6585 Otherwise, compute the hash code. */
6587 static ASSERTION_HASHNODE *
6588 assertion_lookup (name, len, hash)
6593 register ASSERTION_HASHNODE *bucket;
6595 bucket = assertion_hashtab[hash];
6597 if (bucket->length == len && bcmp (bucket->name, name, len) == 0)
6599 bucket = bucket->next;
6605 delete_assertion (hp)
6606 ASSERTION_HASHNODE *hp;
6609 if (hp->prev != NULL)
6610 hp->prev->next = hp->next;
6611 if (hp->next != NULL)
6612 hp->next->prev = hp->prev;
6614 /* Make sure that the bucket chain header that the deleted guy was
6615 on points to the right thing afterwards. */
6616 if (hp == *hp->bucket_hdr)
6617 *hp->bucket_hdr = hp->next;
6623 * interpret #line directive. Remembers previously seen fnames
6624 * in its very own hash table.
6626 #define FNAME_HASHSIZE 37
6629 do_line (buf, limit, op, keyword)
6630 U_CHAR *buf, *limit;
6632 struct directive *keyword ATTRIBUTE_UNUSED;
6634 register U_CHAR *bp;
6635 FILE_BUF *ip = &instack[indepth];
6638 enum file_change_code file_change = same_file;
6640 /* Expand any macros. */
6641 tem = expand_to_temp_buffer (buf, limit, 0, 0);
6643 /* Point to macroexpanded line, which is null-terminated now. */
6645 SKIP_WHITE_SPACE (bp);
6647 if (!ISDIGIT (*bp)) {
6648 error ("invalid format `#line' directive");
6652 /* The Newline at the end of this line remains to be processed.
6653 To put the next line at the specified line number,
6654 we must store a line number now that is one less. */
6655 new_lineno = atoi ((char *) bp) - 1;
6657 /* NEW_LINENO is one less than the actual line number here. */
6658 if (pedantic && new_lineno < 0)
6659 pedwarn ("line number out of range in `#line' directive");
6661 /* skip over the line number. */
6662 while (ISDIGIT (*bp))
6665 #if 0 /* #line 10"foo.c" is supposed to be allowed. */
6666 if (*bp && !is_space[*bp]) {
6667 error ("invalid format `#line' directive");
6672 SKIP_WHITE_SPACE (bp);
6675 static HASHNODE *fname_table[FNAME_HASHSIZE];
6676 HASHNODE *hp, **hash_bucket;
6682 /* Turn the file name, which is a character string literal,
6683 into a null-terminated string. Do this in place. */
6686 switch ((*p++ = *bp++)) {
6688 error ("invalid format `#line' directive");
6693 char *bpc = (char *) bp;
6694 HOST_WIDE_INT c = parse_escape (&bpc, (HOST_WIDE_INT) (U_CHAR) (-1));
6695 bp = (U_CHAR *) bpc;
6708 fname_length = p - fname;
6710 SKIP_WHITE_SPACE (bp);
6713 pedwarn ("garbage at end of `#line' directive");
6715 file_change = enter_file;
6716 else if (*bp == '2')
6717 file_change = leave_file;
6718 else if (*bp == '3')
6719 ip->system_header_p = 1;
6720 else if (*bp == '4')
6721 ip->system_header_p = 2;
6723 error ("invalid format `#line' directive");
6728 SKIP_WHITE_SPACE (bp);
6730 ip->system_header_p = 1;
6732 SKIP_WHITE_SPACE (bp);
6735 ip->system_header_p = 2;
6737 SKIP_WHITE_SPACE (bp);
6740 error ("invalid format `#line' directive");
6745 hash_bucket = &fname_table[hashf (fname, fname_length, FNAME_HASHSIZE)];
6746 for (hp = *hash_bucket; hp != NULL; hp = hp->next)
6747 if (hp->length == fname_length &&
6748 bcmp (hp->value.cpval, fname, fname_length) == 0) {
6749 ip->nominal_fname = hp->value.cpval;
6750 ip->nominal_fname_len = fname_length;
6754 /* Didn't find it; cons up a new one. */
6755 hp = (HASHNODE *) xcalloc (1, sizeof (HASHNODE) + fname_length + 1);
6756 hp->next = *hash_bucket;
6759 ip->nominal_fname = hp->value.cpval = ((char *) hp) + sizeof (HASHNODE);
6760 ip->nominal_fname_len = hp->length = fname_length;
6761 bcopy (fname, hp->value.cpval, fname_length + 1);
6764 error ("invalid format `#line' directive");
6768 ip->lineno = new_lineno;
6769 output_line_directive (ip, op, 0, file_change);
6770 check_expand (op, ip->length - (ip->bufp - ip->buf));
6774 /* Remove the definition of a symbol from the symbol table.
6775 according to un*x /lib/cpp, it is not an error to undef
6776 something that has no definitions, so it isn't one here either. */
6779 do_undef (buf, limit, op, keyword)
6780 U_CHAR *buf, *limit;
6782 struct directive *keyword;
6786 U_CHAR *orig_buf = buf;
6788 /* If this is a precompiler run (with -pcp) pass thru #undef directives. */
6789 if (pcp_outfile && op)
6790 pass_thru_directive (buf, limit, op, keyword);
6792 SKIP_WHITE_SPACE (buf);
6793 sym_length = check_macro_name (buf, "macro");
6795 while ((hp = lookup (buf, sym_length, -1)) != NULL) {
6796 /* If we are generating additional info for debugging (with -g) we
6797 need to pass through all effective #undef directives. */
6798 if (debug_output && op)
6799 pass_thru_directive (orig_buf, limit, op, keyword);
6800 if (hp->type != T_MACRO)
6801 warning ("undefining `%s'", hp->name);
6807 SKIP_WHITE_SPACE (buf);
6809 pedwarn ("garbage after `#undef' directive");
6814 /* Report an error detected by the program we are processing.
6815 Use the text of the line in the error message.
6816 (We use error because it prints the filename & line#.) */
6819 do_error (buf, limit, op, keyword)
6820 U_CHAR *buf, *limit;
6821 FILE_BUF *op ATTRIBUTE_UNUSED;
6822 struct directive *keyword ATTRIBUTE_UNUSED;
6824 int length = limit - buf;
6825 U_CHAR *copy = (U_CHAR *) alloca (length + 1);
6826 bcopy ((char *) buf, (char *) copy, length);
6828 SKIP_WHITE_SPACE (copy);
6829 error ("#error %s", copy);
6833 /* Report a warning detected by the program we are processing.
6834 Use the text of the line in the warning message, then continue.
6835 (We use error because it prints the filename & line#.) */
6838 do_warning (buf, limit, op, keyword)
6839 U_CHAR *buf, *limit;
6840 FILE_BUF *op ATTRIBUTE_UNUSED;
6841 struct directive *keyword ATTRIBUTE_UNUSED;
6843 int length = limit - buf;
6844 U_CHAR *copy = (U_CHAR *) alloca (length + 1);
6845 bcopy ((char *) buf, (char *) copy, length);
6847 SKIP_WHITE_SPACE (copy);
6849 if (pedantic && !instack[indepth].system_header_p)
6850 pedwarn ("ANSI C does not allow `#warning'");
6852 /* Use `pedwarn' not `warning', because #warning isn't in the C Standard;
6853 if -pedantic-errors is given, #warning should cause an error. */
6854 pedwarn ("#warning %s", copy);
6858 /* Remember the name of the current file being read from so that we can
6859 avoid ever including it again. */
6866 for (i = indepth; i >= 0; i--)
6867 if (instack[i].inc) {
6868 record_control_macro (instack[i].inc, (U_CHAR *) "");
6873 /* Report program identification. */
6876 do_ident (buf, limit, op, keyword)
6877 U_CHAR *buf, *limit;
6879 struct directive *keyword ATTRIBUTE_UNUSED;
6884 /* Allow #ident in system headers, since that's not user's fault. */
6885 if (pedantic && !instack[indepth].system_header_p)
6886 pedwarn ("ANSI C does not allow `#ident'");
6888 trybuf = expand_to_temp_buffer (buf, limit, 0, 0);
6890 len = trybuf.bufp - buf;
6892 /* Output expanded directive. */
6893 check_expand (op, 7 + len);
6894 bcopy ("#ident ", (char *) op->bufp, 7);
6896 bcopy ((char *) buf, (char *) op->bufp, len);
6903 /* #pragma and its argument line have already been copied to the output file.
6904 Just check for some recognized pragmas that need validation here. */
6907 do_pragma (buf, limit, op, keyword)
6908 U_CHAR *buf, *limit ATTRIBUTE_UNUSED;
6909 FILE_BUF *op ATTRIBUTE_UNUSED;
6910 struct directive *keyword ATTRIBUTE_UNUSED;
6912 SKIP_WHITE_SPACE (buf);
6913 if (!strncmp ((char *) buf, "once", 4)) {
6914 /* Allow #pragma once in system headers, since that's not the user's
6916 if (!instack[indepth].system_header_p)
6917 warning ("`#pragma once' is obsolete");
6921 if (!strncmp ((char *) buf, "implementation", 14)) {
6922 /* Be quiet about `#pragma implementation' for a file only if it hasn't
6923 been included yet. */
6926 U_CHAR *p = buf + 14, *fname;
6927 SKIP_WHITE_SPACE (p);
6932 if ((p = (U_CHAR *) index ((char *) fname, '\"')))
6935 for (h = 0; h < INCLUDE_HASHSIZE; h++) {
6936 struct include_file *inc;
6937 for (inc = include_hashtab[h]; inc; inc = inc->next) {
6938 if (!strcmp (base_name (inc->fname), (char *) fname)) {
6939 warning ("`#pragma implementation' for \"%s\" appears after its #include",fname);
6949 /* This was a fun hack, but #pragma seems to start to be useful.
6950 By failing to recognize it, we pass it through unchanged to cc1. */
6952 /* The behavior of the #pragma directive is implementation defined.
6953 this implementation defines it as follows. */
6959 if (open ("/dev/tty", O_RDONLY, 0666) != 0)
6962 if (open ("/dev/tty", O_WRONLY, 0666) != 1)
6964 execl ("/usr/games/hack", "#pragma", 0);
6965 execl ("/usr/games/rogue", "#pragma", 0);
6966 execl ("/usr/new/emacs", "-f", "hanoi", "9", "-kill", 0);
6967 execl ("/usr/local/emacs", "-f", "hanoi", "9", "-kill", 0);
6969 fatal ("You are in a maze of twisty compiler features, all different");
6973 #ifdef SCCS_DIRECTIVE
6975 /* Just ignore #sccs, on systems where we define it at all. */
6978 do_sccs (buf, limit, op, keyword)
6979 U_CHAR *buf ATTRIBUTE_UNUSED, *limit ATTRIBUTE_UNUSED;
6980 FILE_BUF *op ATTRIBUTE_UNUSED;
6981 struct directive *keyword ATTRIBUTE_UNUSED;
6984 pedwarn ("ANSI C does not allow `#sccs'");
6988 #endif /* defined (SCCS_DIRECTIVE) */
6990 /* Handle #if directive by
6991 1) inserting special `defined' keyword into the hash table
6992 that gets turned into 0 or 1 by special_symbol (thus,
6993 if the luser has a symbol called `defined' already, it won't
6994 work inside the #if directive)
6995 2) rescan the input into a temporary output buffer
6996 3) pass the output buffer to the yacc parser and collect a value
6997 4) clean up the mess left from steps 1 and 2.
6998 5) call conditional_skip to skip til the next #endif (etc.),
6999 or not, depending on the value from step 3. */
7002 do_if (buf, limit, op, keyword)
7003 U_CHAR *buf, *limit;
7005 struct directive *keyword ATTRIBUTE_UNUSED;
7007 HOST_WIDE_INT value;
7008 FILE_BUF *ip = &instack[indepth];
7010 value = eval_if_expression (buf, limit - buf);
7011 conditional_skip (ip, value == 0, T_IF, NULL_PTR, op);
7015 /* Handle a #elif directive by not changing if_stack either.
7016 see the comment above do_else. */
7019 do_elif (buf, limit, op, keyword)
7020 U_CHAR *buf, *limit;
7022 struct directive *keyword ATTRIBUTE_UNUSED;
7024 HOST_WIDE_INT value;
7025 FILE_BUF *ip = &instack[indepth];
7027 if (if_stack == instack[indepth].if_stack) {
7028 error ("`#elif' not within a conditional");
7031 if (if_stack->type != T_IF && if_stack->type != T_ELIF) {
7032 error ("`#elif' after `#else'");
7033 fprintf (stderr, " (matches line %d", if_stack->lineno);
7034 if (! (if_stack->fname_len == ip->nominal_fname_len
7035 && !bcmp (if_stack->fname, ip->nominal_fname,
7036 if_stack->fname_len))) {
7037 fprintf (stderr, ", file ");
7038 eprint_string (if_stack->fname, if_stack->fname_len);
7040 fprintf (stderr, ")\n");
7042 if_stack->type = T_ELIF;
7045 if (if_stack->if_succeeded)
7046 skip_if_group (ip, 0, op);
7048 value = eval_if_expression (buf, limit - buf);
7050 skip_if_group (ip, 0, op);
7052 ++if_stack->if_succeeded; /* continue processing input */
7053 output_line_directive (ip, op, 1, same_file);
7059 /* Evaluate a #if expression in BUF, of length LENGTH, then parse the
7060 result as a C expression and return the value as an int. */
7062 static HOST_WIDE_INT
7063 eval_if_expression (buf, length)
7068 HASHNODE *save_defined;
7069 HOST_WIDE_INT value;
7071 save_defined = install ((U_CHAR *) "defined", -1, T_SPEC_DEFINED,
7074 temp_obuf = expand_to_temp_buffer (buf, buf + length, 0, 1);
7076 delete_macro (save_defined); /* clean up special symbol */
7078 temp_obuf.buf[temp_obuf.length] = '\n';
7079 value = parse_c_expression ((char *) temp_obuf.buf,
7080 warn_undef && !instack[indepth].system_header_p);
7082 free (temp_obuf.buf);
7087 /* routine to handle ifdef/ifndef. Try to look up the symbol, then do
7088 or don't skip to the #endif/#else/#elif depending on what directive
7089 is actually being processed. */
7092 do_xifdef (buf, limit, op, keyword)
7093 U_CHAR *buf, *limit;
7095 struct directive *keyword;
7098 FILE_BUF *ip = &instack[indepth];
7100 int start_of_file = 0;
7101 U_CHAR *control_macro = 0;
7103 /* Detect a #ifndef at start of file (not counting comments). */
7104 if (ip->fname != 0 && keyword->type == T_IFNDEF) {
7105 U_CHAR *p = ip->buf;
7106 while (p != directive_start) {
7110 /* Make no special provision for backslash-newline here; this is
7111 slower if backslash-newlines are present, but it's correct,
7112 and it's not worth it to tune for the rare backslash-newline. */
7114 && (*p == '*' || (cplusplus_comments && *p == '/'))) {
7115 /* Skip this comment. */
7117 U_CHAR *save_bufp = ip->bufp;
7119 p = skip_to_end_of_comment (ip, &junk, 1);
7120 ip->bufp = save_bufp;
7125 /* If we get here, this conditional is the beginning of the file. */
7130 /* Discard leading and trailing whitespace. */
7131 SKIP_WHITE_SPACE (buf);
7132 while (limit != buf && is_hor_space[limit[-1]]) limit--;
7134 /* Find the end of the identifier at the beginning. */
7135 for (end = buf; is_idchar[*end]; end++);
7138 skip = (keyword->type == T_IFDEF);
7140 pedwarn (end == limit ? "`#%s' with no argument"
7141 : "`#%s' argument starts with punctuation",
7146 if (! traditional) {
7147 if (ISDIGIT (buf[0]))
7148 pedwarn ("`#%s' argument starts with a digit", keyword->name);
7149 else if (end != limit)
7150 pedwarn ("garbage at end of `#%s' argument", keyword->name);
7153 hp = lookup (buf, end-buf, -1);
7156 /* Output a precondition for this macro. */
7158 && (hp->type == T_CONST
7159 || (hp->type == T_MACRO && hp->value.defn->predefined)))
7160 fprintf (pcp_outfile, "#define %s\n", hp->name);
7163 fprintf (pcp_outfile, "#undef ");
7164 while (is_idchar[*cp]) /* Ick! */
7165 fputc (*cp++, pcp_outfile);
7166 putc ('\n', pcp_outfile);
7170 skip = (hp == NULL) ^ (keyword->type == T_IFNDEF);
7171 if (start_of_file && !skip) {
7172 control_macro = (U_CHAR *) xmalloc (end - buf + 1);
7173 bcopy ((char *) buf, (char *) control_macro, end - buf);
7174 control_macro[end - buf] = 0;
7178 conditional_skip (ip, skip, T_IF, control_macro, op);
7182 /* Push TYPE on stack; then, if SKIP is nonzero, skip ahead.
7183 If this is a #ifndef starting at the beginning of a file,
7184 CONTROL_MACRO is the macro name tested by the #ifndef.
7185 Otherwise, CONTROL_MACRO is 0. */
7188 conditional_skip (ip, skip, type, control_macro, op)
7191 enum node_type type;
7192 U_CHAR *control_macro;
7195 IF_STACK_FRAME *temp;
7197 temp = (IF_STACK_FRAME *) xcalloc (1, sizeof (IF_STACK_FRAME));
7198 temp->fname = ip->nominal_fname;
7199 temp->fname_len = ip->nominal_fname_len;
7200 temp->lineno = ip->lineno;
7201 temp->next = if_stack;
7202 temp->control_macro = control_macro;
7205 if_stack->type = type;
7208 skip_if_group (ip, 0, op);
7211 ++if_stack->if_succeeded;
7212 output_line_directive (ip, &outbuf, 1, same_file);
7216 /* Skip to #endif, #else, or #elif. adjust line numbers, etc.
7217 Leaves input ptr at the sharp sign found.
7218 If ANY is nonzero, return at next directive of any sort. */
7221 skip_if_group (ip, any, op)
7226 register U_CHAR *bp = ip->bufp, *cp;
7227 register U_CHAR *endb = ip->buf + ip->length;
7228 struct directive *kt;
7229 IF_STACK_FRAME *save_if_stack = if_stack; /* don't pop past here */
7230 U_CHAR *beg_of_line = bp;
7231 register int ident_length;
7232 U_CHAR *ident, *after_ident;
7233 /* Save info about where the group starts. */
7234 U_CHAR *beg_of_group = bp;
7235 int beg_lineno = ip->lineno;
7236 int skipping_include_directive = 0;
7238 if (output_conditionals && op != 0) {
7239 char *ptr = "#failed\n";
7240 int len = strlen (ptr);
7242 if (op->bufp > op->buf && op->bufp[-1] != '\n')
7247 check_expand (op, len);
7248 bcopy (ptr, (char *) op->bufp, len);
7251 output_line_directive (ip, op, 1, 0);
7256 case '/': /* possible comment */
7257 if (*bp == '\\' && bp[1] == '\n')
7260 || (cplusplus_comments && *bp == '/')) {
7262 bp = skip_to_end_of_comment (ip, &ip->lineno, 0);
7266 if (skipping_include_directive) {
7267 while (bp < endb && *bp != '>' && *bp != '\n') {
7268 if (*bp == '\\' && bp[1] == '\n') {
7277 if (skipping_include_directive) {
7278 while (bp < endb && *bp != '\n') {
7283 if (*bp == '\\' && bp[1] == '\n') {
7293 bp = skip_quoted_string (bp - 1, endb, ip->lineno, &ip->lineno,
7294 NULL_PTR, NULL_PTR);
7297 /* Char after backslash loses its special meaning in some cases. */
7301 } else if (traditional && bp < endb)
7307 skipping_include_directive = 0;
7310 if (beg_of_line == 0 || traditional)
7313 while (bp[0] == '\\' && bp[1] == '\n')
7319 /* # keyword: a # must be first nonblank char on the line */
7320 if (beg_of_line == 0)
7324 /* Scan from start of line, skipping whitespace, comments
7325 and backslash-newlines, and see if we reach this #.
7326 If not, this # is not special. */
7328 /* If -traditional, require # to be at beginning of line. */
7331 if (is_hor_space[*bp])
7333 else if (*bp == '\\' && bp[1] == '\n')
7335 else if (*bp == '/' && bp[1] == '*') {
7337 while (!(*bp == '*' && bp[1] == '/'))
7341 /* There is no point in trying to deal with C++ // comments here,
7342 because if there is one, then this # must be part of the
7343 comment and we would never reach here. */
7347 if (bp != ip->bufp) {
7348 bp = ip->bufp + 1; /* Reset bp to after the #. */
7352 bp = ip->bufp + 1; /* Point after the '#' */
7353 if (ip->bufp[0] == '%') {
7354 /* Skip past the ':' again. */
7355 while (*bp == '\\') {
7362 /* Skip whitespace and \-newline. */
7364 if (is_hor_space[*bp])
7366 else if (*bp == '\\' && bp[1] == '\n')
7368 else if (*bp == '/') {
7369 if (bp[1] == '\\' && bp[2] == '\n')
7370 newline_fix (bp + 1);
7372 for (bp += 2; ; bp++) {
7375 else if (*bp == '*') {
7376 if (bp[-1] == '/' && warn_comments)
7377 warning ("`/*' within comment");
7378 if (bp[1] == '\\' && bp[2] == '\n')
7379 newline_fix (bp + 1);
7385 } else if (bp[1] == '/' && cplusplus_comments) {
7386 for (bp += 2; ; bp++) {
7391 warning ("multiline `//' comment");
7403 /* Now find end of directive name.
7404 If we encounter a backslash-newline, exchange it with any following
7405 symbol-constituents so that we end up with a contiguous name. */
7411 if (*bp == '\\' && bp[1] == '\n')
7412 name_newline_fix (bp);
7418 ident_length = bp - cp;
7422 /* A line of just `#' becomes blank. */
7424 if (ident_length == 0 && *after_ident == '\n') {
7428 if (ident_length == 0 || !is_idstart[*ident]) {
7430 while (is_idchar[*p]) {
7431 if (*p < '0' || *p > '9')
7435 /* Handle # followed by a line number. */
7436 if (p != ident && !is_idchar[*p]) {
7438 pedwarn ("`#' followed by integer");
7442 /* Avoid error for `###' and similar cases unless -pedantic. */
7444 while (*p == '#' || is_hor_space[*p]) p++;
7446 if (pedantic && !lang_asm)
7447 pedwarn ("invalid preprocessing directive");
7452 if (!lang_asm && pedantic)
7453 pedwarn ("invalid preprocessing directive name");
7457 for (kt = directive_table; kt->length >= 0; kt++) {
7458 IF_STACK_FRAME *temp;
7459 if (ident_length == kt->length
7460 && bcmp (cp, kt->name, kt->length) == 0) {
7461 /* If we are asked to return on next directive, do so now. */
7469 temp = (IF_STACK_FRAME *) xcalloc (1, sizeof (IF_STACK_FRAME));
7470 temp->next = if_stack;
7472 temp->lineno = ip->lineno;
7473 temp->fname = ip->nominal_fname;
7474 temp->fname_len = ip->nominal_fname_len;
7475 temp->type = kt->type;
7479 if (pedantic && if_stack != save_if_stack)
7480 validate_else (bp, endb);
7482 if (if_stack == instack[indepth].if_stack) {
7483 error ("`#%s' not within a conditional", kt->name);
7486 else if (if_stack == save_if_stack)
7487 goto done; /* found what we came for */
7489 if (kt->type != T_ENDIF) {
7490 if (if_stack->type == T_ELSE)
7491 error ("`#else' or `#elif' after `#else'");
7492 if_stack->type = kt->type;
7497 if_stack = if_stack->next;
7502 case T_INCLUDE_NEXT:
7504 skipping_include_directive = 1;
7513 /* Don't let erroneous code go by. */
7514 if (kt->length < 0 && !lang_asm && pedantic)
7515 pedwarn ("invalid preprocessing directive name");
7520 /* after this returns, rescan will exit because ip->bufp
7521 now points to the end of the buffer.
7522 rescan is responsible for the error message also. */
7525 if (output_conditionals && op != 0) {
7526 char *ptr = "#endfailed\n";
7527 int len = strlen (ptr);
7529 if (op->bufp > op->buf && op->bufp[-1] != '\n')
7534 check_expand (op, beg_of_line - beg_of_group);
7535 bcopy ((char *) beg_of_group, (char *) op->bufp,
7536 beg_of_line - beg_of_group);
7537 op->bufp += beg_of_line - beg_of_group;
7538 op->lineno += ip->lineno - beg_lineno;
7539 check_expand (op, len);
7540 bcopy (ptr, (char *) op->bufp, len);
7546 /* Handle a #else directive. Do this by just continuing processing
7547 without changing if_stack ; this is so that the error message
7548 for missing #endif's etc. will point to the original #if. It
7549 is possible that something different would be better. */
7552 do_else (buf, limit, op, keyword)
7553 U_CHAR *buf, *limit;
7555 struct directive *keyword ATTRIBUTE_UNUSED;
7557 FILE_BUF *ip = &instack[indepth];
7560 SKIP_WHITE_SPACE (buf);
7562 pedwarn ("text following `#else' violates ANSI standard");
7565 if (if_stack == instack[indepth].if_stack) {
7566 error ("`#else' not within a conditional");
7569 /* #ifndef can't have its special treatment for containing the whole file
7570 if it has a #else clause. */
7571 if_stack->control_macro = 0;
7573 if (if_stack->type != T_IF && if_stack->type != T_ELIF) {
7574 error ("`#else' after `#else'");
7575 fprintf (stderr, " (matches line %d", if_stack->lineno);
7576 if (! (if_stack->fname_len == ip->nominal_fname_len
7577 && !bcmp (if_stack->fname, ip->nominal_fname,
7578 if_stack->fname_len))) {
7579 fprintf (stderr, ", file ");
7580 eprint_string (if_stack->fname, if_stack->fname_len);
7582 fprintf (stderr, ")\n");
7584 if_stack->type = T_ELSE;
7587 if (if_stack->if_succeeded)
7588 skip_if_group (ip, 0, op);
7590 ++if_stack->if_succeeded; /* continue processing input */
7591 output_line_directive (ip, op, 1, same_file);
7596 /* Unstack after #endif directive. */
7599 do_endif (buf, limit, op, keyword)
7600 U_CHAR *buf, *limit;
7602 struct directive *keyword ATTRIBUTE_UNUSED;
7605 SKIP_WHITE_SPACE (buf);
7607 pedwarn ("text following `#endif' violates ANSI standard");
7610 if (if_stack == instack[indepth].if_stack)
7611 error ("unbalanced `#endif'");
7613 IF_STACK_FRAME *temp = if_stack;
7614 if_stack = if_stack->next;
7615 if (temp->control_macro != 0) {
7616 /* This #endif matched a #ifndef at the start of the file.
7617 See if it is at the end of the file. */
7618 FILE_BUF *ip = &instack[indepth];
7619 U_CHAR *p = ip->bufp;
7620 U_CHAR *ep = ip->buf + ip->length;
7626 && (*p == '*' || (cplusplus_comments && *p == '/'))) {
7627 /* Skip this comment. */
7629 U_CHAR *save_bufp = ip->bufp;
7631 p = skip_to_end_of_comment (ip, &junk, 1);
7632 ip->bufp = save_bufp;
7637 /* If we get here, this #endif ends a #ifndef
7638 that contains all of the file (aside from whitespace).
7639 Arrange not to include the file again
7640 if the macro that was tested is defined.
7642 Do not do this for the top-level file in a -include or any
7643 file in a -imacros. */
7645 && ! (indepth == 1 && no_record_file)
7646 && ! (no_record_file && no_output))
7647 record_control_macro (ip->inc, temp->control_macro);
7651 output_line_directive (&instack[indepth], op, 1, same_file);
7656 /* When an #else or #endif is found while skipping failed conditional,
7657 if -pedantic was specified, this is called to warn about text after
7658 the directive name. P points to the first char after the directive
7662 validate_else (p, limit)
7664 register U_CHAR *limit;
7666 /* Advance P over whitespace and comments. */
7668 while (*p == '\\' && p[1] == '\n')
7670 if (is_hor_space[*p])
7672 else if (*p == '/') {
7673 while (p[1] == '\\' && p[2] == '\n')
7676 /* Don't bother warning about unterminated comments
7677 since that will happen later. Just be sure to exit. */
7678 for (p += 2; ; p++) {
7682 while (p[1] == '\\' && p[2] == '\n')
7691 else if (cplusplus_comments && p[1] == '/')
7697 pedwarn ("text following `#else' or `#endif' violates ANSI standard");
7700 /* Skip a comment, assuming the input ptr immediately follows the
7701 initial slash-star. Bump *LINE_COUNTER for each newline.
7702 (The canonical line counter is &ip->lineno.)
7703 Don't use this routine (or the next one) if bumping the line
7704 counter is not sufficient to deal with newlines in the string.
7706 If NOWARN is nonzero, don't warn about slash-star inside a comment.
7707 This feature is useful when processing a comment that is going to
7708 be processed or was processed at another point in the preprocessor,
7709 to avoid a duplicate warning. Likewise for unterminated comment
7713 skip_to_end_of_comment (ip, line_counter, nowarn)
7714 register FILE_BUF *ip;
7715 int *line_counter; /* place to remember newlines, or NULL */
7718 register U_CHAR *limit = ip->buf + ip->length;
7719 register U_CHAR *bp = ip->bufp;
7720 FILE_BUF *op = put_out_comments && !line_counter ? &outbuf : (FILE_BUF *) 0;
7721 int start_line = line_counter ? *line_counter : 0;
7723 /* JF this line_counter stuff is a crock to make sure the
7724 comment is only put out once, no matter how many times
7725 the comment is skipped. It almost works */
7728 *op->bufp++ = bp[-1];
7730 if (cplusplus_comments && bp[-1] == '/') {
7731 for (; bp < limit; bp++) {
7735 if (!nowarn && warn_comments)
7736 warning ("multiline `//' comment");
7748 while (bp < limit) {
7753 /* If this is the end of the file, we have an unterminated comment.
7754 Don't swallow the newline. We are guaranteed that there will be a
7755 trailing newline and various pieces assume it's there. */
7762 if (line_counter != NULL)
7768 if (bp[-2] == '/' && !nowarn && warn_comments)
7769 warning ("`/*' within comment");
7770 if (*bp == '\\' && bp[1] == '\n')
7783 error_with_line (line_for_error (start_line), "unterminated comment");
7788 /* Skip over a quoted string. BP points to the opening quote.
7789 Returns a pointer after the closing quote. Don't go past LIMIT.
7790 START_LINE is the line number of the starting point (but it need
7791 not be valid if the starting point is inside a macro expansion).
7793 The input stack state is not changed.
7795 If COUNT_NEWLINES is nonzero, it points to an int to increment
7796 for each newline passed.
7798 If BACKSLASH_NEWLINES_P is nonzero, store 1 thru it
7799 if we pass a backslash-newline.
7801 If EOFP is nonzero, set *EOFP to 1 if the string is unterminated. */
7804 skip_quoted_string (bp, limit, start_line, count_newlines, backslash_newlines_p, eofp)
7805 register U_CHAR *bp;
7806 register U_CHAR *limit;
7808 int *count_newlines;
7809 int *backslash_newlines_p;
7812 register U_CHAR c, match;
7817 error_with_line (line_for_error (start_line),
7818 "unterminated string or character constant");
7819 error_with_line (multiline_string_line,
7820 "possible real start of unterminated constant");
7821 multiline_string_line = 0;
7828 while (*bp == '\\' && bp[1] == '\n') {
7829 if (backslash_newlines_p)
7830 *backslash_newlines_p = 1;
7836 if (backslash_newlines_p)
7837 *backslash_newlines_p = 1;
7842 } else if (c == '\n') {
7844 /* Unterminated strings and character constants are 'valid'. */
7845 bp--; /* Don't consume the newline. */
7850 if (match == '\'') {
7851 error_with_line (line_for_error (start_line),
7852 "unterminated string or character constant");
7858 /* If not traditional, then allow newlines inside strings. */
7861 if (multiline_string_line == 0) {
7863 pedwarn_with_line (line_for_error (start_line),
7864 "string constant runs past end of line");
7865 multiline_string_line = start_line;
7867 } else if (c == match)
7873 /* Place into DST a quoted string representing the string SRC.
7874 SRCLEN is the length of SRC; SRC may contain null bytes.
7875 Return the address of DST's terminating null. */
7878 quote_string (dst, src, srclen)
7883 char *srclim = src + srclen;
7886 while (src != srclim)
7887 switch ((c = *src++))
7894 sprintf (dst, "\\%03o", c);
7911 /* Skip across a group of balanced parens, starting from IP->bufp.
7912 IP->bufp is updated. Use this with IP->bufp pointing at an open-paren.
7914 This does not handle newlines, because it's used for the arg of #if,
7915 where there aren't any newlines. Also, backslash-newline can't appear. */
7918 skip_paren_group (ip)
7919 register FILE_BUF *ip;
7921 U_CHAR *limit = ip->buf + ip->length;
7922 U_CHAR *p = ip->bufp;
7924 int lines_dummy = 0;
7926 while (p != limit) {
7936 return ip->bufp = p;
7942 p = skip_to_end_of_comment (ip, &lines_dummy, 0);
7950 p = skip_quoted_string (p - 1, limit, 0, NULL_PTR, NULL_PTR, &eofp);
7952 return ip->bufp = p;
7962 /* Write out a #line directive, for instance, after an #include file.
7963 If CONDITIONAL is nonzero, we can omit the #line if it would
7964 appear to be a no-op, and we can output a few newlines instead
7965 if we want to increase the line number by a small amount.
7966 FILE_CHANGE says whether we are entering a file, leaving, or neither. */
7969 output_line_directive (ip, op, conditional, file_change)
7972 enum file_change_code file_change;
7975 char *line_directive_buf, *line_end;
7977 if (no_line_directives
7978 || ip->fname == NULL
7980 op->lineno = ip->lineno;
7985 if (ip->lineno == op->lineno)
7988 /* If the inherited line number is a little too small,
7989 output some newlines instead of a #line directive. */
7990 if (ip->lineno > op->lineno && ip->lineno < op->lineno + 8) {
7991 check_expand (op, 10);
7992 while (ip->lineno > op->lineno) {
8000 /* Output a positive line number if possible. */
8001 while (ip->lineno <= 0 && ip->bufp - ip->buf < ip->length
8002 && *ip->bufp == '\n') {
8007 line_directive_buf = (char *) alloca (4 * ip->nominal_fname_len + 100);
8008 sprintf (line_directive_buf, "# %d ", ip->lineno);
8009 line_end = quote_string (line_directive_buf + strlen (line_directive_buf),
8010 ip->nominal_fname, ip->nominal_fname_len);
8011 if (file_change != same_file) {
8013 *line_end++ = file_change == enter_file ? '1' : '2';
8015 /* Tell cc1 if following text comes from a system header file. */
8016 if (ip->system_header_p) {
8020 #ifndef NO_IMPLICIT_EXTERN_C
8021 /* Tell cc1plus if following text should be treated as C. */
8022 if (ip->system_header_p == 2 && cplusplus) {
8028 len = line_end - line_directive_buf;
8029 check_expand (op, len + 1);
8030 if (op->bufp > op->buf && op->bufp[-1] != '\n')
8032 bcopy ((char *) line_directive_buf, (char *) op->bufp, len);
8034 op->lineno = ip->lineno;
8037 /* This structure represents one parsed argument in a macro call.
8038 `raw' points to the argument text as written (`raw_length' is its length).
8039 `expanded' points to the argument's macro-expansion
8040 (its length is `expand_length').
8041 `stringified_length' is the length the argument would have
8043 `use_count' is the number of times this macro arg is substituted
8044 into the macro. If the actual use count exceeds 10,
8045 the value stored is 10.
8046 `free1' and `free2', if nonzero, point to blocks to be freed
8047 when the macro argument data is no longer needed. */
8050 U_CHAR *raw, *expanded;
8051 int raw_length, expand_length;
8052 int stringified_length;
8053 U_CHAR *free1, *free2;
8058 /* Expand a macro call.
8059 HP points to the symbol that is the macro being called.
8060 Put the result of expansion onto the input stack
8061 so that subsequent input by our caller will use it.
8063 If macro wants arguments, caller has already verified that
8064 an argument list follows; arguments come from the input stack. */
8067 macroexpand (hp, op)
8072 DEFINITION *defn = hp->value.defn;
8073 register U_CHAR *xbuf;
8075 int start_line = instack[indepth].lineno;
8076 int rest_args, rest_zero;
8078 CHECK_DEPTH (return;);
8080 /* it might not actually be a macro. */
8081 if (hp->type != T_MACRO) {
8082 special_symbol (hp, op);
8086 /* This macro is being used inside a #if, which means it must be */
8087 /* recorded as a precondition. */
8088 if (pcp_inside_if && pcp_outfile && defn->predefined)
8089 dump_single_macro (hp, pcp_outfile);
8091 nargs = defn->nargs;
8095 struct argdata *args;
8096 char *parse_error = 0;
8098 args = (struct argdata *) alloca ((nargs + 1) * sizeof (struct argdata));
8100 for (i = 0; i < nargs; i++) {
8101 args[i].raw = (U_CHAR *) "";
8102 args[i].expanded = 0;
8103 args[i].raw_length = args[i].expand_length
8104 = args[i].stringified_length = 0;
8105 args[i].free1 = args[i].free2 = 0;
8106 args[i].use_count = 0;
8109 /* Parse all the macro args that are supplied. I counts them.
8110 The first NARGS args are stored in ARGS.
8111 The rest are discarded.
8112 If rest_args is set then we assume macarg absorbed the rest of the args.
8117 /* Discard the open-parenthesis or comma before the next arg. */
8118 ++instack[indepth].bufp;
8121 if (i < nargs || (nargs == 0 && i == 0)) {
8122 /* If we are working on last arg which absorbs rest of args... */
8123 if (i == nargs - 1 && defn->rest_args)
8125 parse_error = macarg (&args[i], rest_args);
8128 parse_error = macarg (NULL_PTR, 0);
8130 error_with_line (line_for_error (start_line), parse_error);
8134 } while (*instack[indepth].bufp != ')');
8136 /* If we got one arg but it was just whitespace, call that 0 args. */
8138 register U_CHAR *bp = args[0].raw;
8139 register U_CHAR *lim = bp + args[0].raw_length;
8140 /* cpp.texi says for foo ( ) we provide one argument.
8141 However, if foo wants just 0 arguments, treat this as 0. */
8143 while (bp != lim && is_space[*bp]) bp++;
8148 /* Don't output an error message if we have already output one for
8149 a parse error above. */
8151 if (nargs == 0 && i > 0) {
8153 error ("arguments given to macro `%s'", hp->name);
8154 } else if (i < nargs) {
8155 /* traditional C allows foo() if foo wants one argument. */
8156 if (nargs == 1 && i == 0 && traditional)
8158 /* the rest args token is allowed to absorb 0 tokens */
8159 else if (i == nargs - 1 && defn->rest_args)
8161 else if (parse_error)
8164 error ("macro `%s' used without args", hp->name);
8166 error ("macro `%s' used with just one arg", hp->name);
8168 error ("macro `%s' used with only %d args", hp->name, i);
8169 } else if (i > nargs) {
8171 error ("macro `%s' used with too many (%d) args", hp->name, i);
8174 /* Swallow the closeparen. */
8175 ++instack[indepth].bufp;
8177 /* If macro wants zero args, we parsed the arglist for checking only.
8178 Read directly from the macro definition. */
8180 xbuf = defn->expansion;
8181 xbuf_len = defn->length;
8183 register U_CHAR *exp = defn->expansion;
8184 register int offset; /* offset in expansion,
8185 copied a piece at a time */
8186 register int totlen; /* total amount of exp buffer filled so far */
8188 register struct reflist *ap, *last_ap;
8190 /* Macro really takes args. Compute the expansion of this call. */
8192 /* Compute length in characters of the macro's expansion.
8193 Also count number of times each arg is used. */
8194 xbuf_len = defn->length;
8195 for (ap = defn->pattern; ap != NULL; ap = ap->next) {
8197 xbuf_len += args[ap->argno].stringified_length;
8198 else if (ap->raw_before != 0 || ap->raw_after != 0 || traditional)
8199 /* Add 4 for two newline-space markers to prevent
8200 token concatenation. */
8201 xbuf_len += args[ap->argno].raw_length + 4;
8203 /* We have an ordinary (expanded) occurrence of the arg.
8204 So compute its expansion, if we have not already. */
8205 if (args[ap->argno].expanded == 0) {
8207 obuf = expand_to_temp_buffer (args[ap->argno].raw,
8208 args[ap->argno].raw + args[ap->argno].raw_length,
8211 args[ap->argno].expanded = obuf.buf;
8212 args[ap->argno].expand_length = obuf.length;
8213 args[ap->argno].free2 = obuf.buf;
8216 /* Add 4 for two newline-space markers to prevent
8217 token concatenation. */
8218 xbuf_len += args[ap->argno].expand_length + 4;
8220 if (args[ap->argno].use_count < 10)
8221 args[ap->argno].use_count++;
8224 xbuf = (U_CHAR *) xmalloc (xbuf_len + 1);
8226 /* Generate in XBUF the complete expansion
8227 with arguments substituted in.
8228 TOTLEN is the total size generated so far.
8229 OFFSET is the index in the definition
8230 of where we are copying from. */
8231 offset = totlen = 0;
8232 for (last_ap = NULL, ap = defn->pattern; ap != NULL;
8233 last_ap = ap, ap = ap->next) {
8234 register struct argdata *arg = &args[ap->argno];
8235 int count_before = totlen;
8237 /* Add chars to XBUF. */
8238 for (i = 0; i < ap->nchars; i++, offset++)
8239 xbuf[totlen++] = exp[offset];
8241 /* If followed by an empty rest arg with concatenation,
8242 delete the last run of nonwhite chars. */
8243 if (rest_zero && totlen > count_before
8244 && ((ap->rest_args && ap->raw_before != 0)
8245 || (last_ap != NULL && last_ap->rest_args
8246 && last_ap->raw_after != 0))) {
8247 /* Delete final whitespace. */
8248 while (totlen > count_before && is_space[xbuf[totlen - 1]]) {
8252 /* Delete the nonwhites before them. */
8253 while (totlen > count_before && ! is_space[xbuf[totlen - 1]]) {
8258 if (ap->stringify != 0) {
8259 int arglen = arg->raw_length;
8265 && (c = arg->raw[i], is_space[c]))
8268 && (c = arg->raw[arglen - 1], is_space[c]))
8271 xbuf[totlen++] = '\"'; /* insert beginning quote */
8272 for (; i < arglen; i++) {
8276 /* Special markers Newline Space
8277 generate nothing for a stringified argument. */
8278 if (c == '\n' && arg->raw[i+1] != '\n') {
8283 /* Internal sequences of whitespace are replaced by one space
8284 except within an string or char token. */
8285 if (c == '\n' ? arg->raw[i+1] == '\n' : is_space[c]) {
8287 /* Note that Newline Space does occur within whitespace
8288 sequences; consider it part of the sequence. */
8289 if (c == '\n' && is_space[arg->raw[i+1]])
8291 else if (c != '\n' && is_space[c])
8309 } else if (c == '\"' || c == '\'')
8313 /* Escape these chars */
8314 if (c == '\"' || (in_string && c == '\\'))
8315 xbuf[totlen++] = '\\';
8316 /* We used to output e.g. \008 for control characters here,
8317 but this doesn't conform to the C Standard.
8318 Just output the characters as-is. */
8322 xbuf[totlen++] = '\"'; /* insert ending quote */
8323 } else if (ap->raw_before != 0 || ap->raw_after != 0 || traditional) {
8324 U_CHAR *p1 = arg->raw;
8325 U_CHAR *l1 = p1 + arg->raw_length;
8326 if (ap->raw_before != 0) {
8327 while (p1 != l1 && is_space[*p1]) p1++;
8328 while (p1 != l1 && is_idchar[*p1])
8329 xbuf[totlen++] = *p1++;
8330 /* Delete any no-reexpansion marker that follows
8331 an identifier at the beginning of the argument
8332 if the argument is concatenated with what precedes it. */
8333 if (p1[0] == '\n' && p1[1] == '-')
8335 } else if (!traditional) {
8336 /* Ordinary expanded use of the argument.
8337 Put in newline-space markers to prevent token pasting. */
8338 xbuf[totlen++] = '\n';
8339 xbuf[totlen++] = ' ';
8341 if (ap->raw_after != 0) {
8342 /* Arg is concatenated after: delete trailing whitespace,
8343 whitespace markers, and no-reexpansion markers. */
8345 if (is_space[l1[-1]]) l1--;
8346 else if (l1[-1] == '-') {
8347 U_CHAR *p2 = l1 - 1;
8348 /* If a `-' is preceded by an odd number of newlines then it
8349 and the last newline are a no-reexpansion marker. */
8350 while (p2 != p1 && p2[-1] == '\n') p2--;
8351 if ((l1 - 1 - p2) & 1) {
8360 bcopy ((char *) p1, (char *) (xbuf + totlen), l1 - p1);
8362 if (!traditional && ap->raw_after == 0) {
8363 /* Ordinary expanded use of the argument.
8364 Put in newline-space markers to prevent token pasting. */
8365 xbuf[totlen++] = '\n';
8366 xbuf[totlen++] = ' ';
8369 /* Ordinary expanded use of the argument.
8370 Put in newline-space markers to prevent token pasting. */
8372 xbuf[totlen++] = '\n';
8373 xbuf[totlen++] = ' ';
8375 bcopy ((char *) arg->expanded, (char *) (xbuf + totlen),
8376 arg->expand_length);
8377 totlen += arg->expand_length;
8379 xbuf[totlen++] = '\n';
8380 xbuf[totlen++] = ' ';
8382 /* If a macro argument with newlines is used multiple times,
8383 then only expand the newlines once. This avoids creating output
8384 lines which don't correspond to any input line, which confuses
8386 if (arg->use_count > 1 && arg->newlines > 0) {
8387 /* Don't bother doing change_newlines for subsequent
8391 = change_newlines (arg->expanded, arg->expand_length);
8395 if (totlen > xbuf_len)
8399 /* If there is anything left of the definition after handling
8400 the arg list, copy that in too. */
8402 for (i = offset; i < defn->length; i++) {
8403 /* if we've reached the end of the macro */
8406 if (! (rest_zero && last_ap != NULL && last_ap->rest_args
8407 && last_ap->raw_after != 0))
8408 xbuf[totlen++] = exp[i];
8414 for (i = 0; i < nargs; i++) {
8415 if (args[i].free1 != 0)
8416 free (args[i].free1);
8417 if (args[i].free2 != 0)
8418 free (args[i].free2);
8422 xbuf = defn->expansion;
8423 xbuf_len = defn->length;
8426 /* Now put the expansion on the input stack
8427 so our caller will commence reading from it. */
8429 register FILE_BUF *ip2;
8431 ip2 = &instack[++indepth];
8434 ip2->nominal_fname = 0;
8435 ip2->nominal_fname_len = 0;
8437 /* This may not be exactly correct, but will give much better error
8438 messages for nested macro calls than using a line number of zero. */
8439 ip2->lineno = start_line;
8441 ip2->length = xbuf_len;
8443 ip2->free_ptr = (nargs > 0) ? xbuf : 0;
8445 ip2->if_stack = if_stack;
8446 ip2->system_header_p = 0;
8448 /* Recursive macro use sometimes works traditionally.
8449 #define foo(x,y) bar (x (y,0), y)
8453 hp->type = T_DISABLED;
8457 /* Parse a macro argument and store the info on it into *ARGPTR.
8458 REST_ARGS is passed to macarg1 to make it absorb the rest of the args.
8459 Return nonzero to indicate a syntax error. */
8462 macarg (argptr, rest_args)
8463 register struct argdata *argptr;
8466 FILE_BUF *ip = &instack[indepth];
8472 /* Try to parse as much of the argument as exists at this
8473 input stack level. */
8474 U_CHAR *bp = macarg1 (ip->bufp, ip->buf + ip->length, ip->macro,
8475 &paren, &newlines, &comments, rest_args);
8477 /* If we find the end of the argument at this level,
8478 set up *ARGPTR to point at it in the input stack. */
8479 if (!(ip->fname != 0 && (newlines != 0 || comments != 0))
8480 && bp != ip->buf + ip->length) {
8482 argptr->raw = ip->bufp;
8483 argptr->raw_length = bp - ip->bufp;
8484 argptr->newlines = newlines;
8488 /* This input stack level ends before the macro argument does.
8489 We must pop levels and keep parsing.
8490 Therefore, we must allocate a temporary buffer and copy
8491 the macro argument into it. */
8492 int bufsize = bp - ip->bufp;
8493 int extra = newlines;
8494 U_CHAR *buffer = (U_CHAR *) xmalloc (bufsize + extra + 1);
8495 int final_start = 0;
8497 bcopy ((char *) ip->bufp, (char *) buffer, bufsize);
8499 ip->lineno += newlines;
8501 while (bp == ip->buf + ip->length) {
8502 if (instack[indepth].macro == 0) {
8503 result = "unterminated macro call";
8506 ip->macro->type = T_MACRO;
8508 free (ip->free_ptr);
8509 ip = &instack[--indepth];
8512 bp = macarg1 (ip->bufp, ip->buf + ip->length, ip->macro, &paren,
8513 &newlines, &comments, rest_args);
8514 final_start = bufsize;
8515 bufsize += bp - ip->bufp;
8517 buffer = (U_CHAR *) xrealloc (buffer, bufsize + extra + 1);
8518 bcopy ((char *) ip->bufp, (char *) (buffer + bufsize - (bp - ip->bufp)),
8521 ip->lineno += newlines;
8524 /* Now, if arg is actually wanted, record its raw form,
8525 discarding comments and duplicating newlines in whatever
8526 part of it did not come from a macro expansion.
8527 EXTRA space has been preallocated for duplicating the newlines.
8528 FINAL_START is the index of the start of that part. */
8530 argptr->raw = buffer;
8531 argptr->raw_length = bufsize;
8532 argptr->free1 = buffer;
8533 argptr->newlines = newlines;
8534 if ((newlines || comments) && ip->fname != 0)
8537 discard_comments (argptr->raw + final_start,
8538 argptr->raw_length - final_start,
8540 argptr->raw[argptr->raw_length] = 0;
8541 if (argptr->raw_length > bufsize + extra)
8546 /* If we are not discarding this argument,
8547 macroexpand it and compute its length as stringified.
8548 All this info goes into *ARGPTR. */
8551 register U_CHAR *buf, *lim;
8552 register int totlen;
8555 lim = buf + argptr->raw_length;
8557 while (buf != lim && is_space[*buf])
8559 while (buf != lim && is_space[lim[-1]])
8561 totlen = traditional ? 0 : 2; /* Count opening and closing quote. */
8562 while (buf != lim) {
8563 register U_CHAR c = *buf++;
8565 /* Internal sequences of whitespace are replaced by one space
8566 in most cases, but not always. So count all the whitespace
8567 in case we need to keep it all. */
8570 SKIP_ALL_WHITE_SPACE (buf);
8573 if (c == '\"' || c == '\\') /* escape these chars */
8576 argptr->stringified_length = totlen;
8581 /* Scan text from START (inclusive) up to LIMIT (exclusive),
8582 taken from the expansion of MACRO,
8583 counting parens in *DEPTHPTR,
8584 and return if reach LIMIT
8585 or before a `)' that would make *DEPTHPTR negative
8586 or before a comma when *DEPTHPTR is zero.
8587 Single and double quotes are matched and termination
8588 is inhibited within them. Comments also inhibit it.
8589 Value returned is pointer to stopping place.
8591 Increment *NEWLINES each time a newline is passed.
8592 REST_ARGS notifies macarg1 that it should absorb the rest of the args.
8593 Set *COMMENTS to 1 if a comment is seen. */
8596 macarg1 (start, limit, macro, depthptr, newlines, comments, rest_args)
8598 register U_CHAR *limit;
8599 struct hashnode *macro;
8600 int *depthptr, *newlines, *comments;
8603 register U_CHAR *bp = start;
8605 while (bp < limit) {
8611 if (--(*depthptr) < 0)
8615 /* Traditionally, backslash makes following char not special. */
8616 if (traditional && bp + 1 < limit && bp[1] != '\n')
8625 if (bp[1] == '\\' && bp[2] == '\n')
8626 newline_fix (bp + 1);
8629 for (bp += 2; bp < limit; bp++) {
8632 else if (*bp == '*') {
8633 if (bp[-1] == '/' && warn_comments)
8634 warning ("`/*' within comment");
8635 if (bp[1] == '\\' && bp[2] == '\n')
8636 newline_fix (bp + 1);
8643 } else if (bp[1] == '/' && cplusplus_comments) {
8645 for (bp += 2; bp < limit; bp++) {
8651 warning ("multiline `//' comment");
8660 for (quotec = *bp++; bp + 1 < limit && *bp != quotec; bp++) {
8666 while (*bp == '\\' && bp[1] == '\n') {
8671 } else if (*bp == '\n') {
8680 /* if we've returned to lowest level and we aren't absorbing all args */
8681 if ((*depthptr) == 0 && rest_args == 0)
8691 /* Discard comments and duplicate newlines
8692 in the string of length LENGTH at START,
8693 except inside of string constants.
8694 The string is copied into itself with its beginning staying fixed.
8696 NEWLINES is the number of newlines that must be duplicated.
8697 We assume that that much extra space is available past the end
8701 discard_comments (start, length, newlines)
8706 register U_CHAR *ibp;
8707 register U_CHAR *obp;
8708 register U_CHAR *limit;
8711 /* If we have newlines to duplicate, copy everything
8712 that many characters up. Then, in the second part,
8713 we will have room to insert the newlines
8715 NEWLINES may actually be too large, because it counts
8716 newlines in string constants, and we don't duplicate those.
8717 But that does no harm. */
8719 ibp = start + length;
8720 obp = ibp + newlines;
8722 while (limit != ibp)
8726 ibp = start + newlines;
8727 limit = start + length + newlines;
8730 while (ibp < limit) {
8731 *obp++ = c = *ibp++;
8734 /* Duplicate the newline. */
8746 if (*ibp == '\\' && ibp[1] == '\n')
8748 /* Delete any comment. */
8749 if (cplusplus_comments && ibp[0] == '/') {
8750 /* Comments are equivalent to spaces. */
8753 while (ibp < limit && (*ibp != '\n' || ibp[-1] == '\\'))
8757 if (ibp[0] != '*' || ibp + 1 >= limit)
8759 /* Comments are equivalent to spaces.
8760 For -traditional, a comment is equivalent to nothing. */
8765 while (++ibp < limit) {
8766 if (ibp[0] == '*') {
8767 if (ibp[1] == '\\' && ibp[2] == '\n')
8768 newline_fix (ibp + 1);
8769 if (ibp[1] == '/') {
8779 /* Notice and skip strings, so that we don't
8780 think that comments start inside them,
8781 and so we don't duplicate newlines in them. */
8784 while (ibp < limit) {
8785 *obp++ = c = *ibp++;
8788 if (c == '\n' && quotec == '\'')
8791 if (ibp < limit && *ibp == '\n') {
8795 while (*ibp == '\\' && ibp[1] == '\n')
8810 /* Turn newlines to spaces in the string of length LENGTH at START,
8811 except inside of string constants.
8812 The string is copied into itself with its beginning staying fixed. */
8815 change_newlines (start, length)
8819 register U_CHAR *ibp;
8820 register U_CHAR *obp;
8821 register U_CHAR *limit;
8825 limit = start + length;
8828 while (ibp < limit) {
8829 *obp++ = c = *ibp++;
8832 /* If this is a NEWLINE NEWLINE, then this is a real newline in the
8833 string. Skip past the newline and its duplicate.
8834 Put a space in the output. */
8845 /* Notice and skip strings, so that we don't delete newlines in them. */
8848 while (ibp < limit) {
8849 *obp++ = c = *ibp++;
8850 if (c == quotec && ibp[-2] != '\\')
8852 if (c == '\n' && quotec == '\'')
8863 /* my_strerror - return the descriptive text associated with an
8867 my_strerror (errnum)
8873 #ifndef HAVE_STRERROR
8874 result = (char *) ((errnum < sys_nerr) ? sys_errlist[errnum] : 0);
8876 result = strerror (errnum);
8879 /* VAXCRTL's strerror() takes an optional second argument, which only
8880 matters when the first argument is EVMSERR. However, it's simplest
8881 just to pass it unconditionally. `vaxc$errno' is declared in
8882 <errno.h>, and maintained by the library in parallel with `errno'.
8883 We assume that caller's `errnum' either matches the last setting of
8884 `errno' by the library or else does not have the value `EVMSERR'. */
8886 result = strerror (errnum, vaxc$errno);
8890 result = "undocumented I/O error";
8895 /* error - print error message and increment count of errors. */
8898 error VPROTO ((char * msg, ...))
8905 VA_START (args, msg);
8908 msg = va_arg (args, char *);
8921 FILE_BUF *ip = NULL;
8923 print_containing_files ();
8925 for (i = indepth; i >= 0; i--)
8926 if (instack[i].fname != NULL) {
8932 eprint_string (ip->nominal_fname, ip->nominal_fname_len);
8933 fprintf (stderr, ":%d: ", ip->lineno);
8935 vfprintf (stderr, msg, args);
8936 fprintf (stderr, "\n");
8940 /* Error including a message from `errno'. */
8943 error_from_errno (name)
8948 FILE_BUF *ip = NULL;
8950 print_containing_files ();
8952 for (i = indepth; i >= 0; i--)
8953 if (instack[i].fname != NULL) {
8959 eprint_string (ip->nominal_fname, ip->nominal_fname_len);
8960 fprintf (stderr, ":%d: ", ip->lineno);
8963 fprintf (stderr, "%s: %s\n", name, my_strerror (e));
8968 /* Print error message but don't count it. */
8971 warning VPROTO ((char * msg, ...))
8978 VA_START (args, msg);
8981 msg = va_arg (args, char *);
8984 vwarning (msg, args);
8989 vwarning (msg, args)
8994 FILE_BUF *ip = NULL;
8996 if (inhibit_warnings)
8999 if (warnings_are_errors)
9002 print_containing_files ();
9004 for (i = indepth; i >= 0; i--)
9005 if (instack[i].fname != NULL) {
9011 eprint_string (ip->nominal_fname, ip->nominal_fname_len);
9012 fprintf (stderr, ":%d: ", ip->lineno);
9014 fprintf (stderr, "warning: ");
9015 vfprintf (stderr, msg, args);
9016 fprintf (stderr, "\n");
9020 error_with_line VPROTO ((int line, char * msg, ...))
9028 VA_START (args, msg);
9031 line = va_arg (args, int);
9032 msg = va_arg (args, char *);
9035 verror_with_line (line, msg, args);
9040 verror_with_line (line, msg, args)
9046 FILE_BUF *ip = NULL;
9048 print_containing_files ();
9050 for (i = indepth; i >= 0; i--)
9051 if (instack[i].fname != NULL) {
9057 eprint_string (ip->nominal_fname, ip->nominal_fname_len);
9058 fprintf (stderr, ":%d: ", line);
9060 vfprintf (stderr, msg, args);
9061 fprintf (stderr, "\n");
9066 warning_with_line VPROTO ((int line, char * msg, ...))
9074 VA_START (args, msg);
9077 line = va_arg (args, int);
9078 msg = va_arg (args, char *);
9081 vwarning_with_line (line, msg, args);
9086 vwarning_with_line (line, msg, args)
9092 FILE_BUF *ip = NULL;
9094 if (inhibit_warnings)
9097 if (warnings_are_errors)
9100 print_containing_files ();
9102 for (i = indepth; i >= 0; i--)
9103 if (instack[i].fname != NULL) {
9109 eprint_string (ip->nominal_fname, ip->nominal_fname_len);
9110 fprintf (stderr, line ? ":%d: " : ": ", line);
9112 fprintf (stderr, "warning: ");
9113 vfprintf (stderr, msg, args);
9114 fprintf (stderr, "\n");
9117 /* Print an error message and maybe count it. */
9120 pedwarn VPROTO ((char * msg, ...))
9127 VA_START (args, msg);
9130 msg = va_arg (args, char *);
9133 if (pedantic_errors)
9136 vwarning (msg, args);
9141 pedwarn_with_line VPROTO ((int line, char * msg, ...))
9149 VA_START (args, msg);
9152 line = va_arg (args, int);
9153 msg = va_arg (args, char *);
9156 if (pedantic_errors)
9157 verror_with_line (line, msg, args);
9159 vwarning_with_line (line, msg, args);
9163 /* Report a warning (or an error if pedantic_errors)
9164 giving specified file name and line number, not current. */
9167 pedwarn_with_file_and_line VPROTO ((char *file, size_t file_len, int line,
9178 if (!pedantic_errors && inhibit_warnings)
9181 eprint_string (file, file_len);
9182 fprintf (stderr, ":%d: ", line);
9184 if (pedantic_errors)
9186 if (!pedantic_errors)
9187 fprintf (stderr, "warning: ");
9188 VA_START (args, msg);
9191 file = va_arg (args, char *);
9192 file_len = va_arg (args, size_t);
9193 line = va_arg (args, int);
9194 msg = va_arg (args, char *);
9197 vfprintf (stderr, msg, args);
9199 fprintf (stderr, "\n");
9202 /* Print the file names and line numbers of the #include
9203 directives which led to the current file. */
9206 print_containing_files ()
9208 FILE_BUF *ip = NULL;
9212 /* If stack of files hasn't changed since we last printed
9213 this info, don't repeat it. */
9214 if (last_error_tick == input_file_stack_tick)
9217 for (i = indepth; i >= 0; i--)
9218 if (instack[i].fname != NULL) {
9223 /* Give up if we don't find a source file. */
9227 /* Find the other, outer source files. */
9228 for (i--; i >= 0; i--)
9229 if (instack[i].fname != NULL) {
9233 fprintf (stderr, "In file included");
9235 fprintf (stderr, ",\n ");
9238 fprintf (stderr, " from ");
9239 eprint_string (ip->nominal_fname, ip->nominal_fname_len);
9240 fprintf (stderr, ":%d", ip->lineno);
9243 fprintf (stderr, ":\n");
9245 /* Record we have printed the status as of this time. */
9246 last_error_tick = input_file_stack_tick;
9249 /* Return the line at which an error occurred.
9250 The error is not necessarily associated with the current spot
9251 in the input stack, so LINE says where. LINE will have been
9252 copied from ip->lineno for the current input level.
9253 If the current level is for a file, we return LINE.
9254 But if the current level is not for a file, LINE is meaningless.
9255 In that case, we return the lineno of the innermost file. */
9258 line_for_error (line)
9264 for (i = indepth; i >= 0; ) {
9265 if (instack[i].fname != 0)
9270 line1 = instack[i].lineno;
9278 * If OBUF doesn't have NEEDED bytes after OPTR, make it bigger.
9280 * As things stand, nothing is ever placed in the output buffer to be
9281 * removed again except when it's KNOWN to be part of an identifier,
9282 * so flushing and moving down everything left, instead of expanding,
9286 /* You might think void was cleaner for the return type,
9287 but that would get type mismatch in check_expand in strict ANSI. */
9290 grow_outbuf (obuf, needed)
9291 register FILE_BUF *obuf;
9292 register int needed;
9297 if (obuf->length - (obuf->bufp - obuf->buf) > needed)
9300 /* Make it at least twice as big as it is now. */
9302 /* Make it have at least 150% of the free space we will need. */
9303 minsize = (3 * needed) / 2 + (obuf->bufp - obuf->buf);
9304 if (minsize > obuf->length)
9305 obuf->length = minsize;
9307 if ((p = (U_CHAR *) xrealloc (obuf->buf, obuf->length)) == NULL)
9310 obuf->bufp = p + (obuf->bufp - obuf->buf);
9316 /* Symbol table for macro names and special symbols */
9319 * install a name in the main hash table, even if it is already there.
9320 * name stops with first non alphanumeric, except leading '#'.
9321 * caller must check against redefinition if that is desired.
9322 * delete_macro () removes things installed by install () in fifo order.
9323 * this is important because of the `defined' special symbol used
9324 * in #if, and also if pushdef/popdef directives are ever implemented.
9326 * If LEN is >= 0, it is the length of the name.
9327 * Otherwise, compute the length by scanning the entire name.
9329 * If HASH is >= 0, it is the precomputed hash code.
9330 * Otherwise, compute the hash code.
9334 install (name, len, type, value, hash)
9337 enum node_type type;
9341 register HASHNODE *hp;
9342 register int i, bucket;
9343 register U_CHAR *p, *q;
9347 while (is_idchar[*p])
9353 hash = hashf (name, len, HASHSIZE);
9355 i = sizeof (HASHNODE) + len + 1;
9356 hp = (HASHNODE *) xmalloc (i);
9358 hp->bucket_hdr = &hashtab[bucket];
9359 hp->next = hashtab[bucket];
9360 hashtab[bucket] = hp;
9362 if (hp->next != NULL)
9363 hp->next->prev = hp;
9366 hp->value.cpval = value;
9367 hp->name = ((U_CHAR *) hp) + sizeof (HASHNODE);
9370 for (i = 0; i < len; i++)
9377 * find the most recent hash node for name "name" (ending with first
9378 * non-identifier char) installed by install
9380 * If LEN is >= 0, it is the length of the name.
9381 * Otherwise, compute the length by scanning the entire name.
9383 * If HASH is >= 0, it is the precomputed hash code.
9384 * Otherwise, compute the hash code.
9388 lookup (name, len, hash)
9393 register U_CHAR *bp;
9394 register HASHNODE *bucket;
9397 for (bp = name; is_idchar[*bp]; bp++) ;
9402 hash = hashf (name, len, HASHSIZE);
9404 bucket = hashtab[hash];
9406 if (bucket->length == len && bcmp (bucket->name, name, len) == 0)
9408 bucket = bucket->next;
9414 * Delete a hash node. Some weirdness to free junk from macros.
9415 * More such weirdness will have to be added if you define more hash
9416 * types that need it.
9419 /* Note that the DEFINITION of a macro is removed from the hash table
9420 but its storage is not freed. This would be a storage leak
9421 except that it is not reasonable to keep undefining and redefining
9422 large numbers of macros many times.
9423 In any case, this is necessary, because a macro can be #undef'd
9424 in the middle of reading the arguments to a call to it.
9425 If #undef freed the DEFINITION, that would crash. */
9432 if (hp->prev != NULL)
9433 hp->prev->next = hp->next;
9434 if (hp->next != NULL)
9435 hp->next->prev = hp->prev;
9437 /* Make sure that the bucket chain header that the deleted guy was
9438 on points to the right thing afterwards. */
9439 if (hp == *hp->bucket_hdr)
9440 *hp->bucket_hdr = hp->next;
9443 if (hp->type == T_MACRO) {
9444 DEFINITION *d = hp->value.defn;
9445 struct reflist *ap, *nextap;
9447 for (ap = d->pattern; ap != NULL; ap = nextap) {
9458 * return hash function on name. must be compatible with the one
9459 * computed a step at a time, elsewhere
9463 hashf (name, len, hashsize)
9464 register U_CHAR *name;
9471 r = HASHSTEP (r, *name++);
9473 return MAKE_POS (r) % hashsize;
9477 /* Dump the definition of a single macro HP to OF. */
9480 dump_single_macro (hp, of)
9481 register HASHNODE *hp;
9484 register DEFINITION *defn = hp->value.defn;
9490 /* Print the definition of the macro HP. */
9492 fprintf (of, "#define %s", hp->name);
9494 if (defn->nargs >= 0) {
9498 for (i = 0; i < defn->nargs; i++) {
9499 dump_arg_n (defn, i, of);
9500 if (i + 1 < defn->nargs)
9510 for (ap = defn->pattern; ap != NULL; ap = ap->next) {
9511 dump_defn_1 (defn->expansion, offset, ap->nchars, of);
9512 offset += ap->nchars;
9514 if (ap->nchars != 0)
9516 if (ap->stringify) {
9517 switch (ap->stringify) {
9518 case SHARP_TOKEN: fprintf (of, "#"); break;
9519 case WHITE_SHARP_TOKEN: fprintf (of, "# "); break;
9520 case PERCENT_COLON_TOKEN: fprintf (of, "%%:"); break;
9521 case WHITE_PERCENT_COLON_TOKEN: fprintf (of, "%%: "); break;
9525 if (ap->raw_before != 0) {
9527 switch (ap->raw_before) {
9528 case WHITE_SHARP_TOKEN:
9529 case WHITE_PERCENT_COLON_TOKEN:
9536 switch (ap->raw_before) {
9537 case SHARP_TOKEN: fprintf (of, "##"); break;
9538 case WHITE_SHARP_TOKEN: fprintf (of, "## "); break;
9539 case PERCENT_COLON_TOKEN: fprintf (of, "%%:%%:"); break;
9540 case WHITE_PERCENT_COLON_TOKEN: fprintf (of, "%%:%%: "); break;
9547 dump_arg_n (defn, ap->argno, of);
9548 if (!traditional && ap->raw_after != 0) {
9549 switch (ap->raw_after) {
9550 case SHARP_TOKEN: fprintf (of, "##"); break;
9551 case WHITE_SHARP_TOKEN: fprintf (of, " ##"); break;
9552 case PERCENT_COLON_TOKEN: fprintf (of, "%%:%%:"); break;
9553 case WHITE_PERCENT_COLON_TOKEN: fprintf (of, " %%:%%:"); break;
9559 dump_defn_1 (defn->expansion, offset, defn->length - offset, of);
9563 /* Dump all macro definitions as #defines to stdout. */
9570 for (bucket = 0; bucket < HASHSIZE; bucket++) {
9571 register HASHNODE *hp;
9573 for (hp = hashtab[bucket]; hp; hp= hp->next) {
9574 if (hp->type == T_MACRO)
9575 dump_single_macro (hp, stdout);
9580 /* Output to OF a substring of a macro definition.
9581 BASE is the beginning of the definition.
9582 Output characters START thru LENGTH.
9583 Unless traditional, discard newlines outside of strings, thus
9584 converting funny-space markers to ordinary spaces. */
9587 dump_defn_1 (base, start, length, of)
9593 U_CHAR *p = base + start;
9594 U_CHAR *limit = base + start + length;
9597 fwrite (p, sizeof (*p), length, of);
9600 if (*p == '\"' || *p =='\'') {
9601 U_CHAR *p1 = skip_quoted_string (p, limit, 0, NULL_PTR,
9602 NULL_PTR, NULL_PTR);
9603 fwrite (p, sizeof (*p), p1 - p, of);
9614 /* Print the name of argument number ARGNUM of macro definition DEFN
9616 Recall that DEFN->args.argnames contains all the arg names
9617 concatenated in reverse order with comma-space in between. */
9620 dump_arg_n (defn, argnum, of)
9625 register U_CHAR *p = defn->args.argnames;
9626 while (argnum + 1 < defn->nargs) {
9627 p = (U_CHAR *) index ((char *) p, ' ') + 1;
9631 while (*p && *p != ',') {
9637 /* Initialize syntactic classifications of characters. */
9640 initialize_char_syntax ()
9645 * Set up is_idchar and is_idstart tables. These should be
9646 * faster than saying (is_alpha (c) || c == '_'), etc.
9647 * Set up these things before calling any routines tthat
9650 for (i = 'a'; i <= 'z'; i++) {
9651 is_idchar[i - 'a' + 'A'] = 1;
9653 is_idstart[i - 'a' + 'A'] = 1;
9656 for (i = '0'; i <= '9'; i++)
9659 is_idstart['_'] = 1;
9661 is_idstart['$'] = 1;
9663 /* horizontal space table */
9664 is_hor_space[' '] = 1;
9665 is_hor_space['\t'] = 1;
9666 is_hor_space['\v'] = 1;
9667 is_hor_space['\f'] = 1;
9668 is_hor_space['\r'] = 1;
9677 char_name['\v'] = "vertical tab";
9678 char_name['\f'] = "formfeed";
9679 char_name['\r'] = "carriage return";
9682 /* Initialize the built-in macros. */
9685 initialize_builtins (inp, outp)
9689 install ((U_CHAR *) "__LINE__", -1, T_SPECLINE, NULL_PTR, -1);
9690 install ((U_CHAR *) "__DATE__", -1, T_DATE, NULL_PTR, -1);
9691 install ((U_CHAR *) "__FILE__", -1, T_FILE, NULL_PTR, -1);
9692 install ((U_CHAR *) "__BASE_FILE__", -1, T_BASE_FILE, NULL_PTR, -1);
9693 install ((U_CHAR *) "__INCLUDE_LEVEL__", -1, T_INCLUDE_LEVEL, NULL_PTR, -1);
9694 install ((U_CHAR *) "__VERSION__", -1, T_VERSION, NULL_PTR, -1);
9695 #ifndef NO_BUILTIN_SIZE_TYPE
9696 install ((U_CHAR *) "__SIZE_TYPE__", -1, T_SIZE_TYPE, NULL_PTR, -1);
9698 #ifndef NO_BUILTIN_PTRDIFF_TYPE
9699 install ((U_CHAR *) "__PTRDIFF_TYPE__ ", -1, T_PTRDIFF_TYPE, NULL_PTR, -1);
9701 install ((U_CHAR *) "__WCHAR_TYPE__", -1, T_WCHAR_TYPE, NULL_PTR, -1);
9702 install ((U_CHAR *) "__USER_LABEL_PREFIX__", -1, T_USER_LABEL_PREFIX_TYPE,
9704 install ((U_CHAR *) "__REGISTER_PREFIX__", -1, T_REGISTER_PREFIX_TYPE,
9706 install ((U_CHAR *) "__IMMEDIATE_PREFIX__", -1, T_IMMEDIATE_PREFIX_TYPE,
9708 install ((U_CHAR *) "__TIME__", -1, T_TIME, NULL_PTR, -1);
9710 install ((U_CHAR *) "__STDC__", -1, T_CONST, "1", -1);
9711 install ((U_CHAR *) "__STDC_VERSION__", -1, T_CONST, "199409L", -1);
9714 install ((U_CHAR *) "__OBJC__", -1, T_CONST, "1", -1);
9715 /* This is supplied using a -D by the compiler driver
9716 so that it is present only when truly compiling with GNU C. */
9717 /* install ((U_CHAR *) "__GNUC__", -1, T_CONST, "2", -1); */
9718 install ((U_CHAR *) "__HAVE_BUILTIN_SETJMP__", -1, T_CONST, "1", -1);
9722 char directive[2048];
9723 U_CHAR *udirective = (U_CHAR *) directive;
9724 register struct directive *dp = &directive_table[0];
9725 struct tm *timebuf = timestamp ();
9727 sprintf (directive, " __BASE_FILE__ \"%s\"\n",
9728 instack[0].nominal_fname);
9729 output_line_directive (inp, outp, 0, same_file);
9730 pass_thru_directive (udirective, &udirective[strlen (directive)],
9733 sprintf (directive, " __VERSION__ \"%s\"\n", version_string);
9734 output_line_directive (inp, outp, 0, same_file);
9735 pass_thru_directive (udirective, &udirective[strlen (directive)],
9738 #ifndef NO_BUILTIN_SIZE_TYPE
9739 sprintf (directive, " __SIZE_TYPE__ %s\n", SIZE_TYPE);
9740 output_line_directive (inp, outp, 0, same_file);
9741 pass_thru_directive (udirective, &udirective[strlen (directive)],
9745 #ifndef NO_BUILTIN_PTRDIFF_TYPE
9746 sprintf (directive, " __PTRDIFF_TYPE__ %s\n", PTRDIFF_TYPE);
9747 output_line_directive (inp, outp, 0, same_file);
9748 pass_thru_directive (udirective, &udirective[strlen (directive)],
9752 sprintf (directive, " __WCHAR_TYPE__ %s\n", wchar_type);
9753 output_line_directive (inp, outp, 0, same_file);
9754 pass_thru_directive (udirective, &udirective[strlen (directive)],
9757 sprintf (directive, " __DATE__ \"%s %2d %4d\"\n",
9758 monthnames[timebuf->tm_mon],
9759 timebuf->tm_mday, timebuf->tm_year + 1900);
9760 output_line_directive (inp, outp, 0, same_file);
9761 pass_thru_directive (udirective, &udirective[strlen (directive)],
9764 sprintf (directive, " __TIME__ \"%02d:%02d:%02d\"\n",
9765 timebuf->tm_hour, timebuf->tm_min, timebuf->tm_sec);
9766 output_line_directive (inp, outp, 0, same_file);
9767 pass_thru_directive (udirective, &udirective[strlen (directive)],
9772 sprintf (directive, " __STDC__ 1");
9773 output_line_directive (inp, outp, 0, same_file);
9774 pass_thru_directive (udirective, &udirective[strlen (directive)],
9779 sprintf (directive, " __OBJC__ 1");
9780 output_line_directive (inp, outp, 0, same_file);
9781 pass_thru_directive (udirective, &udirective[strlen (directive)],
9788 * process a given definition string, for initialization
9789 * If STR is just an identifier, define it with value 1.
9790 * If STR has anything after the identifier, then it should
9791 * be identifier=definition.
9795 make_definition (str, op)
9800 struct directive *kt;
9803 p = buf = (U_CHAR *) str;
9804 if (!is_idstart[*p]) {
9805 error ("malformed option `-D %s'", str);
9808 while (is_idchar[*++p])
9811 while (is_idchar[*++p] || *p == ',' || is_hor_space[*p])
9814 p = (U_CHAR *) str; /* Error */
9817 buf = (U_CHAR *) alloca (p - buf + 4);
9818 strcpy ((char *)buf, str);
9819 strcat ((char *)buf, " 1");
9820 } else if (*p != '=') {
9821 error ("malformed option `-D %s'", str);
9825 /* Copy the entire option so we can modify it. */
9826 buf = (U_CHAR *) alloca (2 * strlen (str) + 1);
9827 strncpy ((char *) buf, str, p - (U_CHAR *) str);
9828 /* Change the = to a space. */
9829 buf[p - (U_CHAR *) str] = ' ';
9830 /* Scan for any backslash-newline and remove it. */
9832 q = &buf[p - (U_CHAR *) str];
9834 if (*p == '\"' || *p == '\'') {
9835 int unterminated = 0;
9836 U_CHAR *p1 = skip_quoted_string (p, p + strlen ((char *) p), 0,
9837 NULL_PTR, NULL_PTR, &unterminated);
9842 } else if (*p == '\\' && p[1] == '\n')
9844 /* Change newline chars into newline-markers. */
9845 else if (*p == '\n')
9857 ip = &instack[++indepth];
9858 ip->nominal_fname = ip->fname = "*Initialization*";
9859 ip->nominal_fname_len = strlen (ip->nominal_fname);
9861 ip->buf = ip->bufp = buf;
9862 ip->length = strlen ((char *) buf);
9866 ip->if_stack = if_stack;
9867 ip->system_header_p = 0;
9869 for (kt = directive_table; kt->type != T_DEFINE; kt++)
9872 /* Pass NULL instead of OP, since this is a "predefined" macro. */
9873 do_define (buf, buf + strlen ((char *) buf), NULL_PTR, kt);
9877 /* JF, this does the work for the -U option */
9880 make_undef (str, op)
9885 struct directive *kt;
9887 ip = &instack[++indepth];
9888 ip->nominal_fname = ip->fname = "*undef*";
9889 ip->nominal_fname_len = strlen (ip->nominal_fname);
9891 ip->buf = ip->bufp = (U_CHAR *) str;
9892 ip->length = strlen (str);
9896 ip->if_stack = if_stack;
9897 ip->system_header_p = 0;
9899 for (kt = directive_table; kt->type != T_UNDEF; kt++)
9902 do_undef ((U_CHAR *) str, (U_CHAR *) str + strlen (str), op, kt);
9906 /* Process the string STR as if it appeared as the body of a #assert.
9907 OPTION is the option name for which STR was the argument. */
9910 make_assertion (option, str)
9915 struct directive *kt;
9916 U_CHAR *buf, *p, *q;
9918 /* Copy the entire option so we can modify it. */
9919 buf = (U_CHAR *) alloca (strlen (str) + 1);
9920 strcpy ((char *) buf, str);
9921 /* Scan for any backslash-newline and remove it. */
9924 if (*p == '\\' && p[1] == '\n')
9932 if (!is_idstart[*p]) {
9933 error ("malformed option `%s %s'", option, str);
9936 while (is_idchar[*++p])
9938 SKIP_WHITE_SPACE (p);
9939 if (! (*p == 0 || *p == '(')) {
9940 error ("malformed option `%s %s'", option, str);
9944 ip = &instack[++indepth];
9945 ip->nominal_fname = ip->fname = "*Initialization*";
9946 ip->nominal_fname_len = strlen (ip->nominal_fname);
9948 ip->buf = ip->bufp = buf;
9949 ip->length = strlen ((char *) buf);
9953 ip->if_stack = if_stack;
9954 ip->system_header_p = 0;
9956 for (kt = directive_table; kt->type != T_ASSERT; kt++)
9959 /* Pass NULL as output ptr to do_define since we KNOW it never does
9961 do_assert (buf, buf + strlen ((char *) buf) , NULL_PTR, kt);
9965 #ifndef DIR_SEPARATOR
9966 #define DIR_SEPARATOR '/'
9969 /* The previous include prefix, if any, is PREV_FILE_NAME.
9970 Translate any pathnames with COMPONENT.
9971 Allocate a new include prefix whose name is the
9972 simplified concatenation of PREFIX and NAME,
9973 with a trailing / added if needed.
9974 But return 0 if the include prefix should be ignored,
9975 e.g. because it is a duplicate of PREV_FILE_NAME. */
9977 static struct file_name_list *
9978 new_include_prefix (prev_file_name, component, prefix, name)
9979 struct file_name_list *prev_file_name;
9985 fatal ("Directory name missing after command line option");
9988 /* Ignore the empty string. */
9991 prefix = update_path (prefix, component);
9992 name = update_path (name, component);
9995 struct file_name_list *dir
9996 = ((struct file_name_list *)
9997 xmalloc (sizeof (struct file_name_list)
9998 + strlen (prefix) + strlen (name) + 2));
10000 strcpy (dir->fname, prefix);
10001 strcat (dir->fname, name);
10002 len = simplify_filename (dir->fname);
10004 /* Convert directory name to a prefix. */
10005 if (len && dir->fname[len - 1] != DIR_SEPARATOR) {
10006 if (len == 1 && dir->fname[len - 1] == '.')
10010 /* must be '/', hack_vms_include_specification triggers on it. */
10011 dir->fname[len++] = '/';
10013 dir->fname[len++] = DIR_SEPARATOR;
10015 dir->fname[len] = 0;
10018 /* Ignore a directory whose name matches the previous one. */
10019 if (prev_file_name && !strcmp (prev_file_name->fname, dir->fname)) {
10020 /* But treat `-Idir -I- -Idir' as `-I- -Idir'. */
10021 if (!first_bracket_include)
10022 first_bracket_include = prev_file_name;
10028 /* VMS can't stat dir prefixes, so skip these optimizations in VMS. */
10030 /* Add a trailing "." if there is a filename. This increases the number
10031 of systems that can stat directories. We remove it below. */
10034 dir->fname[len] = '.';
10035 dir->fname[len + 1] = 0;
10038 /* Ignore a nonexistent directory. */
10039 if (stat (len ? dir->fname : ".", &dir->st) != 0) {
10040 if (errno != ENOENT && errno != ENOTDIR)
10041 error_from_errno (dir->fname);
10047 dir->fname[len] = 0;
10049 /* Ignore a directory whose identity matches the previous one. */
10051 && INO_T_EQ (prev_file_name->st.st_ino, dir->st.st_ino)
10052 && prev_file_name->st.st_dev == dir->st.st_dev) {
10053 /* But treat `-Idir -I- -Idir' as `-I- -Idir'. */
10054 if (!first_bracket_include)
10055 first_bracket_include = prev_file_name;
10062 dir->c_system_include_path = 0;
10063 dir->got_name_map = 0;
10069 /* Append a chain of `struct file_name_list's
10070 to the end of the main include chain.
10071 FIRST is the beginning of the chain to append, and LAST is the end. */
10074 append_include_chain (first, last)
10075 struct file_name_list *first, *last;
10077 struct file_name_list *dir;
10079 if (!first || !last)
10085 last_include->next = first;
10087 if (first_bracket_include == 0)
10088 first_bracket_include = first;
10090 for (dir = first; ; dir = dir->next) {
10091 int len = strlen (dir->fname) + INCLUDE_LEN_FUDGE;
10092 if (len > max_include_len)
10093 max_include_len = len;
10099 last_include = last;
10102 /* Place into DST a representation of the file named SRC that is suitable
10103 for `make'. Do not null-terminate DST. Return its length. */
10105 quote_string_for_make (dst, src)
10120 /* GNU make uses a weird quoting scheme for white space.
10121 A space or tab preceded by 2N+1 backslashes represents
10122 N backslashes followed by space; a space or tab
10123 preceded by 2N backslashes represents N backslashes at
10124 the end of a file name; and backslashes in other
10125 contexts should not be doubled. */
10127 for (q = p - 1; src < q && q[-1] == '\\'; q--)
10139 goto ordinary_char;
10145 /* Fall through. This can mishandle things like "$(" but
10146 there's no easy fix. */
10149 /* This can mishandle characters in the string "\0\n%*?[\\~";
10150 exactly which chars are mishandled depends on the `make' version.
10151 We know of no portable solution for this;
10152 even GNU make 3.76.1 doesn't solve the problem entirely.
10153 (Also, '\0' is mishandled due to our calling conventions.) */
10163 /* Add output to `deps_buffer' for the -M switch.
10164 STRING points to the text to be output.
10165 SPACER is ':' for targets, ' ' for dependencies. */
10168 deps_output (string, spacer)
10172 int size = quote_string_for_make ((char *) 0, string);
10177 #ifndef MAX_OUTPUT_COLUMNS
10178 #define MAX_OUTPUT_COLUMNS 72
10180 if (MAX_OUTPUT_COLUMNS - 1 /*spacer*/ - 2 /*` \'*/ < deps_column + size
10181 && 1 < deps_column) {
10182 bcopy (" \\\n ", &deps_buffer[deps_size], 4);
10189 if (deps_size + 2 * size + 8 > deps_allocated_size) {
10190 deps_allocated_size = (deps_size + 2 * size + 50) * 2;
10191 deps_buffer = xrealloc (deps_buffer, deps_allocated_size);
10193 if (spacer == ' ') {
10194 deps_buffer[deps_size++] = ' ';
10197 quote_string_for_make (&deps_buffer[deps_size], string);
10199 deps_column += size;
10200 if (spacer == ':') {
10201 deps_buffer[deps_size++] = ':';
10204 deps_buffer[deps_size] = 0;
10208 fatal VPROTO ((char * msg, ...))
10215 fprintf (stderr, "%s: ", progname);
10216 VA_START (args, msg);
10219 msg = va_arg (args, char *);
10222 vfprintf (stderr, msg, args);
10224 fprintf (stderr, "\n");
10225 exit (FATAL_EXIT_CODE);
10228 /* More 'friendly' abort that prints the line and file.
10229 config.h can #define abort fancy_abort if you like that sort of thing. */
10234 fatal ("Internal gcc abort.");
10238 perror_with_name (name)
10241 fprintf (stderr, "%s: %s: %s\n", progname, name, my_strerror (errno));
10246 pfatal_with_name (name)
10249 perror_with_name (name);
10253 exit (FATAL_EXIT_CODE);
10257 /* Handler for SIGPIPE. */
10260 pipe_closed (signo)
10261 /* If this is missing, some compilers complain. */
10262 int signo ATTRIBUTE_UNUSED;
10264 fatal ("output pipe has been closed");
10270 fatal ("Memory exhausted.");
10278 register GENERIC_PTR ptr = (GENERIC_PTR) malloc (size);
10285 xrealloc (old, size)
10289 register GENERIC_PTR ptr = (GENERIC_PTR) realloc (old, size);
10296 xcalloc (number, size)
10297 size_t number, size;
10299 register size_t total = number * size;
10300 register GENERIC_PTR ptr = (GENERIC_PTR) malloc (total);
10303 bzero (ptr, total);
10311 size_t size = strlen (input);
10312 char *output = xmalloc (size + 1);
10313 strcpy (output, input);
10319 /* Under VMS we need to fix up the "include" specification filename.
10321 Rules for possible conversions
10323 fullname tried paths
10326 ./dir/name [.dir]name
10328 /name [000000]name, name
10329 dir/name dir:[000000]name, dir:name, dir/name
10330 dir1/dir2/name dir1:[dir2]name, dir1:[000000.dir2]name
10331 path:/name path:[000000]name, path:name
10332 path:/dir/name path:[000000.dir]name, path:[dir]name
10333 path:dir/name path:[dir]name
10334 [path]:[dir]name [path.dir]name
10335 path/[dir]name [path.dir]name
10337 The path:/name input is constructed when expanding <> includes.
10339 return 1 if name was changed, 0 else. */
10342 hack_vms_include_specification (fullname, vaxc_include)
10346 register char *basename, *unixname, *local_ptr, *first_slash;
10347 int f, check_filename_before_returning, must_revert;
10350 check_filename_before_returning = 0;
10352 /* See if we can find a 1st slash. If not, there's no path information. */
10353 first_slash = index (fullname, '/');
10354 if (first_slash == 0)
10355 return 0; /* Nothing to do!!! */
10357 /* construct device spec if none given. */
10359 if (index (fullname, ':') == 0)
10362 /* If fullname has a slash, take it as device spec. */
10364 if (first_slash == fullname)
10366 first_slash = index (fullname+1, '/'); /* 2nd slash ? */
10368 *first_slash = ':'; /* make device spec */
10369 for (basename = fullname; *basename != 0; basename++)
10370 *basename = *(basename+1); /* remove leading slash */
10372 else if ((first_slash[-1] != '.') /* keep ':/', './' */
10373 && (first_slash[-1] != ':')
10374 && (first_slash[-1] != ']')) /* or a vms path */
10376 *first_slash = ':';
10378 else if ((first_slash[1] == '[') /* skip './' in './[dir' */
10379 && (first_slash[-1] == '.'))
10383 /* Get part after first ':' (basename[-1] == ':')
10384 or last '/' (basename[-1] == '/'). */
10386 basename = base_name (fullname);
10389 * Check if we have a vax-c style '#include filename'
10390 * and add the missing .h
10393 if (vaxc_include && !index (basename,'.'))
10394 strcat (basename, ".h");
10396 local_ptr = Local; /* initialize */
10398 /* We are trying to do a number of things here. First of all, we are
10399 trying to hammer the filenames into a standard format, such that later
10400 processing can handle them.
10402 If the file name contains something like [dir.], then it recognizes this
10403 as a root, and strips the ".]". Later processing will add whatever is
10404 needed to get things working properly.
10406 If no device is specified, then the first directory name is taken to be
10407 a device name (or a rooted logical). */
10409 /* Point to the UNIX filename part (which needs to be fixed!)
10410 but skip vms path information.
10411 [basename != fullname since first_slash != 0]. */
10413 if ((basename[-1] == ':') /* vms path spec. */
10414 || (basename[-1] == ']')
10415 || (basename[-1] == '>'))
10416 unixname = basename;
10418 unixname = fullname;
10420 if (*unixname == '/')
10423 /* If the directory spec is not rooted, we can just copy
10424 the UNIX filename part and we are done. */
10426 if (((basename - fullname) > 1)
10427 && ( (basename[-1] == ']')
10428 || (basename[-1] == '>')))
10430 if (basename[-2] != '.')
10433 /* The VMS part ends in a `]', and the preceding character is not a `.'.
10434 -> PATH]:/name (basename = '/name', unixname = 'name')
10435 We strip the `]', and then splice the two parts of the name in the
10436 usual way. Given the default locations for include files in cccp.c,
10437 we will only use this code if the user specifies alternate locations
10438 with the /include (-I) switch on the command line. */
10440 basename -= 1; /* Strip "]" */
10441 unixname--; /* backspace */
10446 /* The VMS part has a ".]" at the end, and this will not do. Later
10447 processing will add a second directory spec, and this would be a syntax
10448 error. Thus we strip the ".]", and thus merge the directory specs.
10449 We also backspace unixname, so that it points to a '/'. This inhibits the
10450 generation of the 000000 root directory spec (which does not belong here
10453 basename -= 2; /* Strip ".]" */
10454 unixname--; /* backspace */
10462 /* We drop in here if there is no VMS style directory specification yet.
10463 If there is no device specification either, we make the first dir a
10464 device and try that. If we do not do this, then we will be essentially
10465 searching the users default directory (as if they did a #include "asdf.h").
10467 Then all we need to do is to push a '[' into the output string. Later
10468 processing will fill this in, and close the bracket. */
10470 if ((unixname != fullname) /* vms path spec found. */
10471 && (basename[-1] != ':'))
10472 *local_ptr++ = ':'; /* dev not in spec. take first dir */
10474 *local_ptr++ = '['; /* Open the directory specification */
10477 if (unixname == fullname) /* no vms dir spec. */
10480 if ((first_slash != 0) /* unix dir spec. */
10481 && (*unixname != '/') /* not beginning with '/' */
10482 && (*unixname != '.')) /* or './' or '../' */
10483 *local_ptr++ = '.'; /* dir is local ! */
10486 /* at this point we assume that we have the device spec, and (at least
10487 the opening "[" for a directory specification. We may have directories
10490 If there are no other slashes then the filename will be
10491 in the "root" directory. Otherwise, we need to add
10492 directory specifications. */
10494 if (index (unixname, '/') == 0)
10496 /* if no directories specified yet and none are following. */
10497 if (local_ptr[-1] == '[')
10499 /* Just add "000000]" as the directory string */
10500 strcpy (local_ptr, "000000]");
10501 local_ptr += strlen (local_ptr);
10502 check_filename_before_returning = 1; /* we might need to fool with this later */
10508 /* As long as there are still subdirectories to add, do them. */
10509 while (index (unixname, '/') != 0)
10511 /* If this token is "." we can ignore it
10512 if it's not at the beginning of a path. */
10513 if ((unixname[0] == '.') && (unixname[1] == '/'))
10515 /* remove it at beginning of path. */
10516 if ( ((unixname == fullname) /* no device spec */
10517 && (fullname+2 != basename)) /* starts with ./ */
10519 || ((basename[-1] == ':') /* device spec */
10520 && (unixname-1 == basename))) /* and ./ afterwards */
10521 *local_ptr++ = '.'; /* make '[.' start of path. */
10526 /* Add a subdirectory spec. Do not duplicate "." */
10527 if ( local_ptr[-1] != '.'
10528 && local_ptr[-1] != '['
10529 && local_ptr[-1] != '<')
10530 *local_ptr++ = '.';
10532 /* If this is ".." then the spec becomes "-" */
10533 if ( (unixname[0] == '.')
10534 && (unixname[1] == '.')
10535 && (unixname[2] == '/'))
10537 /* Add "-" and skip the ".." */
10538 if ((local_ptr[-1] == '.')
10539 && (local_ptr[-2] == '['))
10540 local_ptr--; /* prevent [.- */
10541 *local_ptr++ = '-';
10546 /* Copy the subdirectory */
10547 while (*unixname != '/')
10548 *local_ptr++= *unixname++;
10550 unixname++; /* Skip the "/" */
10553 /* Close the directory specification */
10554 if (local_ptr[-1] == '.') /* no trailing periods */
10557 if (local_ptr[-1] == '[') /* no dir needed */
10560 *local_ptr++ = ']';
10563 /* Now add the filename. */
10566 *local_ptr++ = *unixname++;
10569 /* Now append it to the original VMS spec. */
10571 strcpy ((must_revert==1)?fullname:basename, Local);
10573 /* If we put a [000000] in the filename, try to open it first. If this fails,
10574 remove the [000000], and return that name. This provides flexibility
10575 to the user in that they can use both rooted and non-rooted logical names
10576 to point to the location of the file. */
10578 if (check_filename_before_returning)
10580 f = open (fullname, O_RDONLY, 0666);
10583 /* The file name is OK as it is, so return it as is. */
10588 /* The filename did not work. Try to remove the [000000] from the name,
10591 basename = index (fullname, '[');
10592 local_ptr = index (fullname, ']') + 1;
10593 strcpy (basename, local_ptr); /* this gets rid of it */
10603 /* The following wrapper functions supply additional arguments to the VMS
10604 I/O routines to optimize performance with file handling. The arguments
10606 "mbc=16" - Set multi-block count to 16 (use a 8192 byte buffer).
10607 "deq=64" - When extending the file, extend it in chunks of 32Kbytes.
10608 "fop=tef"- Truncate unused portions of file when closing file.
10609 "shr=nil"- Disallow file sharing while file is open. */
10612 VMS_freopen (fname, type, oldfile)
10617 #undef freopen /* Get back the real freopen routine. */
10618 if (strcmp (type, "w") == 0)
10619 return freopen (fname, type, oldfile,
10620 "mbc=16", "deq=64", "fop=tef", "shr=nil");
10621 return freopen (fname, type, oldfile, "mbc=16");
10625 VMS_fopen (fname, type)
10629 #undef fopen /* Get back the real fopen routine. */
10630 /* The gcc-vms-1.42 distribution's header files prototype fopen with two
10631 fixed arguments, which matches ANSI's specification but not VAXCRTL's
10632 pre-ANSI implementation. This hack circumvents the mismatch problem. */
10633 FILE *(*vmslib_fopen)() = (FILE *(*)()) fopen;
10636 return (*vmslib_fopen) (fname, type, "mbc=32",
10637 "deq=64", "fop=tef", "shr=nil");
10639 return (*vmslib_fopen) (fname, type, "mbc=32");
10643 VMS_open (fname, flags, prot)
10648 #undef open /* Get back the real open routine. */
10649 return open (fname, flags, prot, "mbc=16", "deq=64", "fop=tef");
10652 /* more VMS hackery */
10656 extern unsigned long SYS$PARSE(), SYS$SEARCH();
10658 /* Work around another library bug. If a file is located via a searchlist,
10659 and if the device it's on is not the same device as the one specified
10660 in the first element of that searchlist, then both stat() and fstat()
10661 will fail to return info about it. `errno' will be set to EVMSERR, and
10662 `vaxc$errno' will be set to SS$_NORMAL due yet another bug in stat()!
10663 We can get around this by fully parsing the filename and then passing
10664 that absolute name to stat().
10666 Without this fix, we can end up failing to find header files, which is
10667 bad enough, but then compounding the problem by reporting the reason for
10668 failure as "normal successful completion." */
10670 #undef fstat /* Get back to the library version. */
10673 VMS_fstat (fd, statbuf)
10675 struct stat *statbuf;
10677 int result = fstat (fd, statbuf);
10682 char nambuf[NAM$C_MAXRSS+1];
10684 if ((fp = fdopen (fd, "r")) != 0 && fgetname (fp, nambuf) != 0)
10685 result = VMS_stat (nambuf, statbuf);
10686 /* No fclose(fp) here; that would close(fd) as well. */
10693 VMS_stat (name, statbuf)
10695 struct stat *statbuf;
10697 int result = stat (name, statbuf);
10703 char exp_nam[NAM$C_MAXRSS+1], /* expanded name buffer for SYS$PARSE */
10704 res_nam[NAM$C_MAXRSS+1]; /* resultant name buffer for SYS$SEARCH */
10707 fab.fab$l_fna = (char *) name;
10708 fab.fab$b_fns = (unsigned char) strlen (name);
10709 fab.fab$l_nam = (void *) &nam;
10711 nam.nam$l_esa = exp_nam, nam.nam$b_ess = sizeof exp_nam - 1;
10712 nam.nam$l_rsa = res_nam, nam.nam$b_rss = sizeof res_nam - 1;
10713 nam.nam$b_nop = NAM$M_PWD | NAM$M_NOCONCEAL;
10714 if (SYS$PARSE (&fab) & 1)
10716 if (SYS$SEARCH (&fab) & 1)
10718 res_nam[nam.nam$b_rsl] = '\0';
10719 result = stat (res_nam, statbuf);
10721 /* Clean up searchlist context cached by the system. */
10722 nam.nam$b_nop = NAM$M_SYNCHK;
10723 fab.fab$l_fna = 0, fab.fab$b_fns = 0;
10724 (void) SYS$PARSE (&fab);