1 /* C Compatible Compiler Preprocessor (CCCP)
2 Copyright (C) 1986, 1987, 1989, 1992, 1993, 1994, 1995, 1996, 1997, 1998,
3 1999, 2000 Free Software Foundation, Inc.
4 Written by Paul Rubin, June 1986
5 Adapted to ANSI C, Richard Stallman, Jan 1987
7 This program is free software; you can redistribute it and/or modify it
8 under the terms of the GNU General Public License as published by the
9 Free Software Foundation; either version 2, or (at your option) any
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, 59 Temple Place - Suite 330,
20 Boston, MA 02111-1307, USA. */
22 /* $FreeBSD: src/contrib/gcc/cccp.c,v 1.6.2.2 2002/06/20 23:12:24 obrien Exp $ */
23 /* $DragonFly: src/contrib/gcc/Attic/cccp.c,v 1.2 2003/06/17 04:23:59 dillon Exp $ */
31 #ifdef HAVE_SYS_RESOURCE_H
32 # include <sys/resource.h>
35 typedef unsigned char U_CHAR;
41 #ifdef MULTIBYTE_CHARS
44 #endif /* MULTIBYTE_CHARS */
46 #ifndef GET_ENV_PATH_LIST
47 #define GET_ENV_PATH_LIST(VAR,NAME) do { (VAR) = getenv (NAME); } while (0)
50 #ifndef STANDARD_INCLUDE_DIR
51 # define STANDARD_INCLUDE_DIR "/usr/include"
54 /* By default, colon separates directories in a path. */
55 #ifndef PATH_SEPARATOR
56 # define PATH_SEPARATOR ':'
59 /* By default, a slash separates directory names. */
61 # define DIR_SEPARATOR '/'
64 /* By default, the suffix for object files is ".o". */
66 # define HAVE_OBJECT_SUFFIX
68 # define OBJECT_SUFFIX ".o"
71 /* VMS-specific definitions */
76 #define open(fname,mode,prot) VMS_open (fname,mode,prot)
77 #define fopen(fname,mode) VMS_fopen (fname,mode)
78 #define freopen(fname,mode,ofile) VMS_freopen (fname,mode,ofile)
79 #define fstat(fd,stbuf) VMS_fstat (fd,stbuf)
80 static int VMS_fstat (), VMS_stat ();
81 static int VMS_open ();
82 static FILE *VMS_fopen ();
83 static FILE *VMS_freopen ();
84 static int hack_vms_include_specification ();
85 #define INO_T_EQ(a, b) (!bcmp((char *) &(a), (char *) &(b), sizeof (a)))
86 #define INO_T_HASH(a) 0
87 #define INCLUDE_LEN_FUDGE 12 /* leave room for VMS syntax conversion */
90 /* Windows does not natively support inodes, and neither does MSDOS. */
91 #if (defined (_WIN32) && ! defined (__CYGWIN__) && ! defined (_UWIN)) \
92 || defined (__MSDOS__)
93 #define INO_T_EQ(a, b) 0
97 #define INO_T_EQ(a, b) ((a) == (b))
101 #define INO_T_HASH(a) (a)
104 #ifndef INCLUDE_LEN_FUDGE
105 #define INCLUDE_LEN_FUDGE 0
108 /* External declarations. */
110 extern char *version_string;
111 HOST_WIDEST_INT parse_escape PROTO((char **, HOST_WIDEST_INT));
112 HOST_WIDEST_INT parse_c_expression PROTO((char *, int));
114 /* Name under which this program was invoked. */
116 static char *progname;
118 /* Nonzero means use extra default include directories for C++. */
120 static int cplusplus;
122 /* Nonzero means handle cplusplus style comments */
124 static int cplusplus_comments;
126 /* Nonzero means handle #import, for objective C. */
130 /* Nonzero means this is an assembly file, and allow
131 unknown directives, which could be comments. */
135 /* Current maximum length of directory names in the search path
136 for include files. (Altered as we get more of them.) */
138 static int max_include_len;
140 /* Nonzero means turn NOTREACHED into #pragma NOTREACHED etc */
142 static int for_lint = 0;
144 /* Nonzero means copy comments into the output file. */
146 static int put_out_comments = 0;
148 /* Nonzero means don't process the ANSI trigraph sequences. */
150 static int no_trigraphs = 0;
152 /* Nonzero means print the names of included files rather than
153 the preprocessed output. 1 means just the #include "...",
154 2 means #include <...> as well. */
156 static int print_deps = 0;
158 /* Nonzero if missing .h files in -M output are assumed to be generated
159 files and not errors. */
161 static int print_deps_missing_files = 0;
163 /* Nonzero means print names of header files (-H). */
165 static int print_include_names = 0;
167 /* Nonzero means don't output line number information. */
169 static int no_line_directives;
171 /* Nonzero means output the text in failing conditionals,
172 inside #failed ... #endfailed. */
174 static int output_conditionals;
176 /* dump_only means inhibit output of the preprocessed text
177 and instead output the definitions of all user-defined
178 macros in a form suitable for use as input to cccp.
179 dump_names means pass #define and the macro name through to output.
180 dump_definitions means pass the whole definition (plus #define) through
183 static enum {dump_none, dump_only, dump_names, dump_definitions}
184 dump_macros = dump_none;
186 /* Nonzero means pass all #define and #undef directives which we actually
187 process through to the output stream. This feature is used primarily
188 to allow cc1 to record the #defines and #undefs for the sake of
189 debuggers which understand about preprocessor macros, but it may
190 also be useful with -E to figure out how symbols are defined, and
191 where they are defined. */
192 static int debug_output = 0;
194 /* Nonzero means pass #include lines through to the output,
195 even if they are ifdefed out. */
196 static int dump_includes;
198 /* Nonzero indicates special processing used by the pcp program. The
199 special effects of this mode are:
201 Inhibit all macro expansion, except those inside #if directives.
203 Process #define directives normally, and output their contents
206 Output preconditions to pcp_outfile indicating all the relevant
207 preconditions for use of this file in a later cpp run.
209 static FILE *pcp_outfile;
211 /* Nonzero means we are inside an IF during a -pcp run. In this mode
212 macro expansion is done, and preconditions are output for all macro
213 uses requiring them. */
214 static int pcp_inside_if;
216 /* Nonzero means never to include precompiled files.
217 This is 1 since there's no way now to make precompiled files,
218 so it's not worth testing for them. */
219 static int no_precomp = 1;
221 /* Nonzero means give all the error messages the ANSI standard requires. */
225 /* Nonzero means try to make failure to fit ANSI C an error. */
227 static int pedantic_errors;
229 /* Nonzero means don't print warning messages. -w. */
231 static int inhibit_warnings = 0;
233 /* Nonzero means warn if slash-star appears in a slash-star comment,
234 or if newline-backslash appears in a slash-slash comment. */
236 static int warn_comments;
238 /* Nonzero means warn if a macro argument is (or would be)
239 stringified with -traditional. */
241 static int warn_stringify;
243 /* Nonzero means warn if there are any trigraphs. */
245 static int warn_trigraphs;
247 /* Nonzero means warn if undefined identifiers are evaluated in an #if. */
249 static int warn_undef;
251 /* Nonzero means warn if #import is used. */
253 static int warn_import = 1;
255 /* Nonzero means turn warnings into errors. */
257 static int warnings_are_errors;
259 /* Nonzero means try to imitate old fashioned non-ANSI preprocessor. */
263 /* Nonzero for the 1989 C Standard, including corrigenda and amendments. */
267 /* Nonzero for the 199x C Standard. */
271 /* Nonzero causes output not to be done,
272 but directives such as #define that have side effects
275 static int no_output;
277 /* Nonzero means we should look for header.gcc files that remap file names. */
280 /* Nonzero means this file was included with a -imacros or -include
281 command line and should not be recorded as an include file. */
283 static int no_record_file;
285 /* Nonzero means that we have finished processing the command line options.
286 This flag is used to decide whether or not to issue certain errors
289 static int done_initializing = 0;
291 /* Line where a newline was first seen in a string constant. */
293 static int multiline_string_line = 0;
295 /* I/O buffer structure.
296 The `fname' field is nonzero for source files and #include files
297 and for the dummy text used for -D and -U.
298 It is zero for rescanning results of macro expansion
299 and for expanding macro arguments. */
300 #define INPUT_STACK_MAX 400
301 static struct file_buf {
303 /* Filename specified with #line directive. */
305 /* The length of nominal_fname, which may contain embedded NULs. */
306 size_t nominal_fname_len;
307 /* Include file description. */
308 struct include_file *inc;
309 /* Record where in the search path this file was found.
310 For #include_next. */
311 struct file_name_list *dir;
316 /* Macro that this level is the expansion of.
317 Included so that we can reenable the macro
318 at the end of this level. */
319 struct hashnode *macro;
320 /* Value of if_stack at start of this file.
321 Used to prohibit unmatched #endif (etc) in an include file. */
322 struct if_stack *if_stack;
323 /* Object to be freed at end of input at this level. */
325 /* True if this is a system header file; see is_system_include. */
326 char system_header_p;
327 } instack[INPUT_STACK_MAX];
329 static int last_error_tick; /* Incremented each time we print it. */
330 static int input_file_stack_tick; /* Incremented when the status changes. */
332 /* Current nesting level of input sources.
333 `instack[indepth]' is the level currently being read. */
334 static int indepth = -1;
335 #define CHECK_DEPTH(code) \
336 if (indepth >= (INPUT_STACK_MAX - 1)) \
338 error_with_line (line_for_error (instack[indepth].lineno), \
339 "macro or `#include' recursion too deep"); \
343 /* Current depth in #include directives that use <...>. */
344 static int system_include_depth = 0;
346 typedef struct file_buf FILE_BUF;
348 /* The output buffer. Its LENGTH field is the amount of room allocated
349 for the buffer, not the number of chars actually present. To get
350 that, subtract outbuf.buf from outbuf.bufp. */
352 #define OUTBUF_SIZE 10 /* initial size of output buffer */
353 static FILE_BUF outbuf;
355 /* Grow output buffer OBUF points at
356 so it can hold at least NEEDED more chars. */
358 #define check_expand(OBUF, NEEDED) \
359 (((OBUF)->length - ((OBUF)->bufp - (OBUF)->buf) <= (NEEDED)) \
360 ? grow_outbuf ((OBUF), (NEEDED)) : 0)
362 struct file_name_list
364 struct file_name_list *next;
365 /* If the following is 1, it is a C-language system include
367 int c_system_include_path;
368 /* Mapping of file names for this directory. */
369 struct file_name_map *name_map;
370 /* Non-zero if name_map is valid. */
372 /* The include directory status. */
374 /* The include prefix: "" denotes the working directory,
375 otherwise fname must end in '/'.
376 The actual size is dynamically allocated. */
380 /* #include "file" looks in source file dir, then stack. */
381 /* #include <file> just looks in the stack. */
382 /* -I directories are added to the end, then the defaults are added. */
384 static struct default_include {
385 char *fname; /* The name of the directory. */
386 char *component; /* The component containing the directory */
387 int cplusplus; /* Only look here if we're compiling C++. */
388 int cxx_aware; /* Includes in this directory don't need to
389 be wrapped in extern "C" when compiling
391 int included; /* Set if the directory is acceptable. */
392 } include_defaults_array[]
393 #ifdef INCLUDE_DEFAULTS
397 /* Pick up GNU C++ specific include files. */
398 { GPLUSPLUS_INCLUDE_DIR, "G++", 1, 1, 0 },
400 /* This is the dir for fixincludes. Put it just before
401 the files that we fix. */
402 { GCC_INCLUDE_DIR, "GCC", 0, 0, 0 },
403 /* For cross-compilation, this dir name is generated
404 automatically in Makefile.in. */
405 { CROSS_INCLUDE_DIR, "GCC", 0, 0, 0 },
406 #ifdef TOOL_INCLUDE_DIR
407 /* This is another place that the target system's headers might be. */
408 { TOOL_INCLUDE_DIR, "BINUTILS", 0, 0, 0 },
410 #else /* not CROSS_COMPILE */
411 #ifdef LOCAL_INCLUDE_DIR
412 /* This should be /usr/local/include and should come before
413 the fixincludes-fixed header files. */
414 { LOCAL_INCLUDE_DIR, 0, 0, 1, 0 },
416 #ifdef TOOL_INCLUDE_DIR
417 /* This is here ahead of GCC_INCLUDE_DIR because assert.h goes here.
418 Likewise, behind LOCAL_INCLUDE_DIR, where glibc puts its assert.h. */
419 { TOOL_INCLUDE_DIR, "BINUTILS", 0, 0, 0 },
421 /* This is the dir for fixincludes. Put it just before
422 the files that we fix. */
423 { GCC_INCLUDE_DIR, "GCC", 0, 0, 0 },
424 /* Some systems have an extra dir of include files. */
425 #ifdef SYSTEM_INCLUDE_DIR
426 { SYSTEM_INCLUDE_DIR, 0, 0, 0, 0 },
428 #ifndef STANDARD_INCLUDE_COMPONENT
429 #define STANDARD_INCLUDE_COMPONENT 0
431 { STANDARD_INCLUDE_DIR, STANDARD_INCLUDE_COMPONENT, 0, 0, 0 },
432 #endif /* not CROSS_COMPILE */
435 #endif /* no INCLUDE_DEFAULTS */
437 /* The code looks at the defaults through this pointer, rather than through
438 the constant structure above. This pointer gets changed if an environment
439 variable specifies other defaults. */
440 static struct default_include *include_defaults = include_defaults_array;
442 static struct file_name_list *include = 0; /* First dir to search */
443 /* First dir to search for <file> */
444 /* This is the first element to use for #include <...>.
445 If it is 0, use the entire chain for such includes. */
446 static struct file_name_list *first_bracket_include = 0;
447 /* This is the first element in the chain that corresponds to
448 a directory of system header files. */
449 static struct file_name_list *first_system_include = 0;
450 static struct file_name_list *last_include = 0; /* Last in chain */
452 /* Chain of include directories to put at the end of the other chain. */
453 static struct file_name_list *after_include = 0;
454 static struct file_name_list *last_after_include = 0; /* Last in chain */
456 /* Chain to put at the start of the system include files. */
457 static struct file_name_list *before_system = 0;
458 static struct file_name_list *last_before_system = 0; /* Last in chain */
460 /* Directory prefix that should replace `/usr' in the standard
461 include file directories. */
462 static char *include_prefix;
464 /* Maintain and search list of included files. */
466 struct include_file {
467 struct include_file *next; /* for include_hashtab */
468 struct include_file *next_ino; /* for include_ino_hashtab */
470 /* If the following is the empty string, it means #pragma once
471 was seen in this include file, or #import was applied to the file.
472 Otherwise, if it is nonzero, it is a macro name.
473 Don't include the file again if that macro is defined. */
474 U_CHAR *control_macro;
475 /* Nonzero if the dependency on this include file has been output. */
480 /* Hash tables of files already included with #include or #import.
481 include_hashtab is by full name; include_ino_hashtab is by inode number. */
483 #define INCLUDE_HASHSIZE 61
484 static struct include_file *include_hashtab[INCLUDE_HASHSIZE];
485 static struct include_file *include_ino_hashtab[INCLUDE_HASHSIZE];
487 /* Global list of strings read in from precompiled files. This list
488 is kept in the order the strings are read in, with new strings being
489 added at the end through stringlist_tailp. We use this list to output
490 the strings at the end of the run.
492 static STRINGDEF *stringlist;
493 static STRINGDEF **stringlist_tailp = &stringlist;
496 /* Structure returned by create_definition */
497 typedef struct macrodef MACRODEF;
500 struct definition *defn;
505 enum sharp_token_type {
506 NO_SHARP_TOKEN = 0, /* token not present */
508 SHARP_TOKEN = '#', /* token spelled with # only */
509 WHITE_SHARP_TOKEN, /* token spelled with # and white space */
511 PERCENT_COLON_TOKEN = '%', /* token spelled with %: only */
512 WHITE_PERCENT_COLON_TOKEN /* token spelled with %: and white space */
515 /* Structure allocated for every #define. For a simple replacement
518 nargs = -1, the `pattern' list is null, and the expansion is just
519 the replacement text. Nargs = 0 means a functionlike macro with no args,
521 #define getchar() getc (stdin) .
522 When there are args, the expansion is the replacement text with the
523 args squashed out, and the reflist is a list describing how to
524 build the output from the input: e.g., "3 chars, then the 1st arg,
525 then 9 chars, then the 3rd arg, then 0 chars, then the 2nd arg".
526 The chars here come from the expansion. Whatever is left of the
527 expansion after the last arg-occurrence is copied after that arg.
528 Note that the reflist can be arbitrarily long---
529 its length depends on the number of times the arguments appear in
530 the replacement text, not how many args there are. Example:
531 #define f(x) x+x+x+x+x+x+x would have replacement text "++++++" and
533 { (0, 1), (1, 1), (1, 1), ..., (1, 1), NULL }
534 where (x, y) means (nchars, argno). */
536 typedef struct definition DEFINITION;
539 int length; /* length of expansion string */
540 int predefined; /* True if the macro was builtin or */
541 /* came from the command line */
543 int line; /* Line number of definition */
544 char *file; /* File of definition */
545 size_t file_len; /* Length of file (which can contain NULs) */
546 char rest_args; /* Nonzero if last arg. absorbs the rest */
548 struct reflist *next;
550 enum sharp_token_type stringify; /* set if a # operator before arg */
551 enum sharp_token_type raw_before; /* set if a ## operator before arg */
552 enum sharp_token_type raw_after; /* set if a ## operator after arg */
554 char rest_args; /* Nonzero if this arg. absorbs the rest */
555 int nchars; /* Number of literal chars to copy before
556 this arg occurrence. */
557 int argno; /* Number of arg to substitute (origin-0) */
560 /* Names of macro args, concatenated in reverse order
561 with comma-space between them.
562 The only use of this is that we warn on redefinition
563 if this differs between the old and new definitions. */
568 /* different kinds of things that can appear in the value field
569 of a hash node. Actually, this may be useless now. */
577 * special extension string that can be added to the last macro argument to
578 * allow it to absorb the "rest" of the arguments when expanded. Ex:
579 * #define wow(a, b...) process (b, a, b)
580 * { wow (1, 2, 3); } -> { process (2, 3, 1, 2, 3); }
581 * { wow (one, two); } -> { process (two, one, two); }
582 * if this "rest_arg" is used with the concat token '##' and if it is not
583 * supplied then the token attached to with ## will not be outputted. Ex:
584 * #define wow (a, b...) process (b ## , a, ## b)
585 * { wow (1, 2); } -> { process (2, 1, 2); }
586 * { wow (one); } -> { process (one); {
588 static char rest_extension[] = "...";
589 #define REST_EXTENSION_LENGTH (sizeof (rest_extension) - 1)
591 /* This is the implicit parameter name when using variable number of
592 parameters for macros using the ISO C 9x extension. */
593 static char va_args_name[] = "__VA_ARGS__";
594 #define VA_ARGS_NAME_LENGTH (sizeof (va_args_name) - 1)
596 /* The structure of a node in the hash table. The hash table
597 has entries for all tokens defined by #define directives (type T_MACRO),
598 plus some special tokens like __LINE__ (these each have their own
599 type, and the appropriate code is run when that type of node is seen.
600 It does not contain control words like "#define", which are recognized
601 by a separate piece of code. */
603 /* different flavors of hash nodes --- also used in keyword table */
605 T_DEFINE = 1, /* the `#define' keyword */
606 T_INCLUDE, /* the `#include' keyword */
607 T_INCLUDE_NEXT, /* the `#include_next' keyword */
608 T_IMPORT, /* the `#import' keyword */
609 T_IFDEF, /* the `#ifdef' keyword */
610 T_IFNDEF, /* the `#ifndef' keyword */
611 T_IF, /* the `#if' keyword */
612 T_ELSE, /* `#else' */
613 T_PRAGMA, /* `#pragma' */
614 T_ELIF, /* `#elif' */
615 T_UNDEF, /* `#undef' */
616 T_LINE, /* `#line' */
617 T_ERROR, /* `#error' */
618 T_WARNING, /* `#warning' */
619 T_ENDIF, /* `#endif' */
620 T_SCCS, /* `#sccs', used on system V. */
621 T_IDENT, /* `#ident', used on system V. */
622 T_ASSERT, /* `#assert', taken from system V. */
623 T_UNASSERT, /* `#unassert', taken from system V. */
624 T_SPECLINE, /* special symbol `__LINE__' */
625 T_DATE, /* `__DATE__' */
626 T_FILE, /* `__FILE__' */
627 T_BASE_FILE, /* `__BASE_FILE__' */
628 T_INCLUDE_LEVEL, /* `__INCLUDE_LEVEL__' */
629 T_VERSION, /* `__VERSION__' */
630 T_SIZE_TYPE, /* `__SIZE_TYPE__' */
631 T_PTRDIFF_TYPE, /* `__PTRDIFF_TYPE__' */
632 T_WCHAR_TYPE, /* `__WCHAR_TYPE__' */
633 T_USER_LABEL_PREFIX_TYPE, /* `__USER_LABEL_PREFIX__' */
634 T_REGISTER_PREFIX_TYPE, /* `__REGISTER_PREFIX__' */
635 T_IMMEDIATE_PREFIX_TYPE, /* `__IMMEDIATE_PREFIX__' */
636 T_TIME, /* `__TIME__' */
637 T_CONST, /* Constant value, used by `__STDC__' */
638 T_MACRO, /* macro defined by `#define' */
639 T_DISABLED, /* macro temporarily turned off for rescan */
640 T_SPEC_DEFINED, /* special `defined' macro for use in #if statements */
641 T_PCSTRING, /* precompiled string (hashval is KEYDEF *) */
642 T_UNUSED /* Used for something not defined. */
646 struct hashnode *next; /* double links for easy deletion */
647 struct hashnode *prev;
648 struct hashnode **bucket_hdr; /* also, a back pointer to this node's hash
649 chain is kept, in case the node is the head
650 of the chain and gets deleted. */
651 enum node_type type; /* type of special token */
652 int length; /* length of token, for quick comparison */
653 U_CHAR *name; /* the actual name */
654 union hashval value; /* pointer to expansion, or whatever */
657 typedef struct hashnode HASHNODE;
659 /* Some definitions for the hash table. The hash function MUST be
660 computed as shown in hashf () below. That is because the rescan
661 loop computes the hash value `on the fly' for most tokens,
662 in order to avoid the overhead of a lot of procedure calls to
663 the hashf () function. Hashf () only exists for the sake of
664 politeness, for use when speed isn't so important. */
666 #define HASHSIZE 1403
667 static HASHNODE *hashtab[HASHSIZE];
668 #define HASHSTEP(old, c) ((old << 2) + c)
669 #define MAKE_POS(v) (v & 0x7fffffff) /* make number positive */
672 /* We let tm.h override the types used here, to handle trivial differences
673 such as the choice of unsigned int or long unsigned int for size_t.
674 When machines start needing nontrivial differences in the size type,
675 it would be best to do something here to figure out automatically
676 from other information what type to use. */
678 /* The string value for __SIZE_TYPE__. */
681 #define SIZE_TYPE "long unsigned int"
684 /* The string value for __PTRDIFF_TYPE__. */
687 #define PTRDIFF_TYPE "long int"
690 /* The string value for __WCHAR_TYPE__. */
693 #define WCHAR_TYPE "int"
695 char * wchar_type = WCHAR_TYPE;
698 /* The string value for __USER_LABEL_PREFIX__ */
700 #ifndef USER_LABEL_PREFIX
701 #define USER_LABEL_PREFIX ""
703 char * user_label_prefix = USER_LABEL_PREFIX;
704 #undef USER_LABEL_PREFIX
706 /* The string value for __REGISTER_PREFIX__ */
708 #ifndef REGISTER_PREFIX
709 #define REGISTER_PREFIX ""
712 /* The string value for __IMMEDIATE_PREFIX__ */
714 #ifndef IMMEDIATE_PREFIX
715 #define IMMEDIATE_PREFIX ""
718 /* In the definition of a #assert name, this structure forms
719 a list of the individual values asserted.
720 Each value is itself a list of "tokens".
721 These are strings that are compared by name. */
723 struct tokenlist_list {
724 struct tokenlist_list *next;
725 struct arglist *tokens;
728 struct assertion_hashnode {
729 struct assertion_hashnode *next; /* double links for easy deletion */
730 struct assertion_hashnode *prev;
731 /* also, a back pointer to this node's hash
732 chain is kept, in case the node is the head
733 of the chain and gets deleted. */
734 struct assertion_hashnode **bucket_hdr;
735 int length; /* length of token, for quick comparison */
736 U_CHAR *name; /* the actual name */
737 /* List of token-sequences. */
738 struct tokenlist_list *value;
741 typedef struct assertion_hashnode ASSERTION_HASHNODE;
743 /* Some definitions for the hash table. The hash function MUST be
744 computed as shown in hashf below. That is because the rescan
745 loop computes the hash value `on the fly' for most tokens,
746 in order to avoid the overhead of a lot of procedure calls to
747 the hashf function. hashf only exists for the sake of
748 politeness, for use when speed isn't so important. */
750 #define ASSERTION_HASHSIZE 37
751 static ASSERTION_HASHNODE *assertion_hashtab[ASSERTION_HASHSIZE];
753 /* Nonzero means inhibit macroexpansion of what seem to be
754 assertion tests, in rescan. For #if. */
755 static int assertions_flag;
757 /* `struct directive' defines one #-directive, including how to handle it. */
759 #define DO_PROTO PROTO((U_CHAR *, U_CHAR *, FILE_BUF *, struct directive *))
762 int length; /* Length of name */
763 int (*func) DO_PROTO; /* Function to handle directive */
764 char *name; /* Name of directive */
765 enum node_type type; /* Code which describes which directive. */
768 #define IS_INCLUDE_DIRECTIVE_TYPE(t) \
769 ((int) T_INCLUDE <= (int) (t) && (int) (t) <= (int) T_IMPORT)
771 /* These functions are declared to return int instead of void since they
772 are going to be placed in the table and some old compilers have trouble with
773 pointers to functions returning void. */
775 static int do_assert DO_PROTO;
776 static int do_define DO_PROTO;
777 static int do_elif DO_PROTO;
778 static int do_else DO_PROTO;
779 static int do_endif DO_PROTO;
780 static int do_error DO_PROTO;
781 static int do_ident DO_PROTO;
782 static int do_if DO_PROTO;
783 static int do_include DO_PROTO;
784 static int do_line DO_PROTO;
785 static int do_pragma DO_PROTO;
786 #ifdef SCCS_DIRECTIVE
787 static int do_sccs DO_PROTO;
789 static int do_unassert DO_PROTO;
790 static int do_undef DO_PROTO;
791 static int do_warning DO_PROTO;
792 static int do_xifdef DO_PROTO;
794 /* Here is the actual list of #-directives, most-often-used first. */
796 static struct directive directive_table[] = {
797 { 6, do_define, "define", T_DEFINE},
798 { 2, do_if, "if", T_IF},
799 { 5, do_xifdef, "ifdef", T_IFDEF},
800 { 6, do_xifdef, "ifndef", T_IFNDEF},
801 { 5, do_endif, "endif", T_ENDIF},
802 { 4, do_else, "else", T_ELSE},
803 { 4, do_elif, "elif", T_ELIF},
804 { 4, do_line, "line", T_LINE},
805 { 7, do_include, "include", T_INCLUDE},
806 { 12, do_include, "include_next", T_INCLUDE_NEXT},
807 { 6, do_include, "import", T_IMPORT},
808 { 5, do_undef, "undef", T_UNDEF},
809 { 5, do_error, "error", T_ERROR},
810 { 7, do_warning, "warning", T_WARNING},
811 #ifdef SCCS_DIRECTIVE
812 { 4, do_sccs, "sccs", T_SCCS},
814 { 6, do_pragma, "pragma", T_PRAGMA},
815 { 5, do_ident, "ident", T_IDENT},
816 { 6, do_assert, "assert", T_ASSERT},
817 { 8, do_unassert, "unassert", T_UNASSERT},
818 { -1, 0, "", T_UNUSED},
821 /* When a directive handler is called,
822 this points to the # (or the : of the %:) that started the directive. */
823 U_CHAR *directive_start;
825 /* table to tell if char can be part of a C identifier. */
826 U_CHAR is_idchar[256];
827 /* table to tell if char can be first char of a c identifier. */
828 U_CHAR is_idstart[256];
829 /* table to tell if c is horizontal space. */
830 static U_CHAR is_hor_space[256];
831 /* table to tell if c is horizontal or vertical space. */
832 U_CHAR is_space[256];
834 #define SKIP_WHITE_SPACE(p) do { while (is_hor_space[*p]) p++; } while (0)
835 #define SKIP_ALL_WHITE_SPACE(p) do { while (is_space[*p]) p++; } while (0)
837 static int errors = 0; /* Error counter for exit code */
839 /* Name of output file, for error messages. */
840 static char *out_fname;
842 /* Nonzero to ignore \ in string constants. Use to treat #line 1 "A:\file.h
843 as a non-form feed. If you want it to be a form feed, you must use
845 static int ignore_escape_flag = 1;
847 /* Stack of conditionals currently in progress
848 (including both successful and failing conditionals). */
851 struct if_stack *next; /* for chaining to the next stack frame */
852 char *fname; /* copied from input when frame is made */
853 size_t fname_len; /* similarly */
854 int lineno; /* similarly */
855 int if_succeeded; /* true if a leg of this if-group
856 has been passed through rescan */
857 U_CHAR *control_macro; /* For #ifndef at start of file,
858 this is the macro name tested. */
859 enum node_type type; /* type of last directive seen in this group */
861 typedef struct if_stack IF_STACK_FRAME;
862 static IF_STACK_FRAME *if_stack = NULL;
864 /* Buffer of -M output. */
865 static char *deps_buffer;
867 /* Number of bytes allocated in above. */
868 static int deps_allocated_size;
870 /* Number of bytes used. */
871 static int deps_size;
873 /* Number of bytes since the last newline. */
874 static int deps_column;
876 /* Nonzero means -I- has been seen,
877 so don't look for #include "foo" the source-file directory. */
878 static int ignore_srcdir;
880 static int safe_read PROTO((int, char *, int));
881 static void safe_write PROTO((int, char *, int));
882 static void eprint_string PROTO((const char *, size_t));
884 int main PROTO((int, char **));
886 static void path_include PROTO((char *));
888 static U_CHAR *index0 PROTO((U_CHAR *, int, size_t));
890 static void trigraph_pcp PROTO((FILE_BUF *));
892 static void newline_fix PROTO((U_CHAR *));
893 static void name_newline_fix PROTO((U_CHAR *));
895 static char *get_lintcmd PROTO((U_CHAR *, U_CHAR *, U_CHAR **, int *, int *));
897 static void rescan PROTO((FILE_BUF *, int));
899 static FILE_BUF expand_to_temp_buffer PROTO((U_CHAR *, U_CHAR *, int, int));
901 static int handle_directive PROTO((FILE_BUF *, FILE_BUF *));
903 static struct tm *timestamp PROTO((void));
904 static void special_symbol PROTO((HASHNODE *, FILE_BUF *));
906 static int is_system_include PROTO((char *));
907 static char *base_name PROTO((char *));
908 static int absolute_filename PROTO((char *));
909 static size_t simplify_filename PROTO((char *));
911 static char *read_filename_string PROTO((int, FILE *));
912 static struct file_name_map *read_name_map PROTO((char *));
913 static int open_include_file PROTO((char *, struct file_name_list *, U_CHAR *, struct include_file **));
914 static char *remap_include_file PROTO((char *, struct file_name_list *));
915 static int lookup_ino_include PROTO((struct include_file *));
917 static void finclude PROTO((int, struct include_file *, FILE_BUF *, int, struct file_name_list *));
918 static void record_control_macro PROTO((struct include_file *, U_CHAR *));
920 static char *check_precompiled PROTO((int, struct stat *, char *, char **));
921 static int check_preconditions PROTO((char *));
922 static void pcfinclude PROTO((U_CHAR *, U_CHAR *, FILE_BUF *));
923 static void pcstring_used PROTO((HASHNODE *));
924 static void write_output PROTO((void));
925 static void pass_thru_directive PROTO((U_CHAR *, U_CHAR *, FILE_BUF *, struct directive *));
927 static MACRODEF create_definition PROTO((U_CHAR *, U_CHAR *, FILE_BUF *));
929 static int check_macro_name PROTO((U_CHAR *, int));
930 static int compare_defs PROTO((DEFINITION *, DEFINITION *));
931 static int comp_def_part PROTO((int, U_CHAR *, int, U_CHAR *, int, int));
933 static DEFINITION *collect_expansion PROTO((U_CHAR *, U_CHAR *, int, struct arglist *));
935 int check_assertion PROTO((U_CHAR *, int, int, struct arglist *));
936 static int compare_token_lists PROTO((struct arglist *, struct arglist *));
938 static struct arglist *read_token_list PROTO((U_CHAR **, U_CHAR *, int *));
939 static void free_token_list PROTO((struct arglist *));
941 static ASSERTION_HASHNODE *assertion_install PROTO((U_CHAR *, int, int));
942 static ASSERTION_HASHNODE *assertion_lookup PROTO((U_CHAR *, int, int));
943 static void delete_assertion PROTO((ASSERTION_HASHNODE *));
945 static void do_once PROTO((void));
947 static HOST_WIDEST_INT eval_if_expression PROTO((U_CHAR *, int));
948 static void conditional_skip PROTO((FILE_BUF *, int, enum node_type, U_CHAR *, FILE_BUF *));
949 static void skip_if_group PROTO((FILE_BUF *, int, FILE_BUF *));
950 static void validate_else PROTO((U_CHAR *, U_CHAR *));
952 static U_CHAR *skip_to_end_of_comment PROTO((FILE_BUF *, int *, int));
953 static U_CHAR *skip_quoted_string PROTO((U_CHAR *, U_CHAR *, int, int *, int *, int *));
954 static char *quote_string PROTO((char *, char *, size_t));
955 static U_CHAR *skip_paren_group PROTO((FILE_BUF *));
957 /* Last arg to output_line_directive. */
958 enum file_change_code {same_file, enter_file, leave_file};
959 static void output_line_directive PROTO((FILE_BUF *, FILE_BUF *, int, enum file_change_code));
961 static void macroexpand PROTO((HASHNODE *, FILE_BUF *));
964 static int macarg PROTO((struct argdata *, int));
966 static U_CHAR *macarg1 PROTO((U_CHAR *, U_CHAR *, struct hashnode *, int *, int *, int *, int));
968 static int discard_comments PROTO((U_CHAR *, int, int));
970 static int change_newlines PROTO((U_CHAR *, int));
972 static char *my_strerror PROTO((int));
973 static void notice PVPROTO((const char *, ...)) ATTRIBUTE_PRINTF_1;
974 static void vnotice PROTO((const char *, va_list));
975 void error PVPROTO((const char *, ...)) ATTRIBUTE_PRINTF_1;
976 void verror PROTO((const char *, va_list));
977 static void error_from_errno PROTO((char *));
978 void warning PVPROTO((const char *, ...)) ATTRIBUTE_PRINTF_1;
979 static void vwarning PROTO((const char *, va_list));
980 static void error_with_line PVPROTO((int, const char *, ...)) ATTRIBUTE_PRINTF_2;
981 static void verror_with_line PROTO((int, const char *, va_list));
982 static void vwarning_with_line PROTO((int, const char *, va_list));
983 static void warning_with_line PVPROTO((int, const char *, ...)) ATTRIBUTE_PRINTF_2;
984 void pedwarn PVPROTO((const char *, ...)) ATTRIBUTE_PRINTF_1;
985 void pedwarn_with_line PVPROTO((int, const char *, ...)) ATTRIBUTE_PRINTF_2;
986 static void pedwarn_with_file_and_line PVPROTO((const char *, size_t, int, const char *, ...)) ATTRIBUTE_PRINTF_4;
987 static void pedwarn_strange_white_space PROTO((int));
989 static void print_containing_files PROTO((void));
991 static int line_for_error PROTO((int));
992 static int grow_outbuf PROTO((FILE_BUF *, int));
994 static HASHNODE *install PROTO((U_CHAR *, int, enum node_type, char *, int));
995 HASHNODE *lookup PROTO((U_CHAR *, int, int));
996 static void delete_macro PROTO((HASHNODE *));
997 static int hashf PROTO((U_CHAR *, int, int));
999 static void dump_single_macro PROTO((HASHNODE *, FILE *));
1000 static void dump_all_macros PROTO((void));
1001 static void dump_defn_1 PROTO((U_CHAR *, int, int, FILE *));
1002 static void dump_arg_n PROTO((DEFINITION *, int, FILE *));
1004 static void initialize_char_syntax PROTO((void));
1005 static void initialize_builtins PROTO((FILE_BUF *, FILE_BUF *));
1007 static void make_definition PROTO((char *));
1008 static void make_undef PROTO((char *, FILE_BUF *));
1010 static void make_assertion PROTO((const char *, const char *));
1012 static struct file_name_list *new_include_prefix PROTO((struct file_name_list *, const char *, const char *, const char *));
1013 static void append_include_chain PROTO((struct file_name_list *, struct file_name_list *));
1015 static int quote_string_for_make PROTO((char *, const char *));
1016 static void deps_output PROTO((const char *, int));
1018 void fatal PVPROTO((const char *, ...)) ATTRIBUTE_PRINTF_1 ATTRIBUTE_NORETURN;
1019 void fancy_abort PROTO((void)) ATTRIBUTE_NORETURN;
1020 static void perror_with_name PROTO((char *));
1021 static void pfatal_with_name PROTO((char *)) ATTRIBUTE_NORETURN;
1022 static void pipe_closed PROTO((int)) ATTRIBUTE_NORETURN;
1024 static void memory_full PROTO((void)) ATTRIBUTE_NORETURN;
1025 static void print_help PROTO((void));
1027 /* Read LEN bytes at PTR from descriptor DESC, for file FILENAME,
1028 retrying if necessary. If MAX_READ_LEN is defined, read at most
1029 that bytes at a time. Return a negative value if an error occurs,
1030 otherwise return the actual number of bytes read,
1031 which must be LEN unless end-of-file was reached. */
1034 safe_read (desc, ptr, len)
1039 int left, rcount, nchars;
1045 if (rcount > MAX_READ_LEN)
1046 rcount = MAX_READ_LEN;
1048 nchars = read (desc, ptr, rcount);
1065 /* Write LEN bytes at PTR to descriptor DESC,
1066 retrying if necessary, and treating any real error as fatal.
1067 If MAX_WRITE_LEN is defined, write at most that many bytes at a time. */
1070 safe_write (desc, ptr, len)
1075 int wcount, written;
1079 #ifdef MAX_WRITE_LEN
1080 if (wcount > MAX_WRITE_LEN)
1081 wcount = MAX_WRITE_LEN;
1083 written = write (desc, ptr, wcount);
1090 pfatal_with_name (out_fname);
1097 /* Print a string to stderr, with extra handling in case it contains
1098 embedded NUL characters. Any present are written as is.
1100 Using fwrite for this purpose produces undesireable results on VMS
1101 when stderr happens to be a record oriented file, such as a batch log
1102 file, rather than a stream oriented one. */
1105 eprint_string (string, length)
1109 size_t segment_length;
1112 fprintf(stderr, "%s", string);
1113 length -= (segment_length = strlen(string));
1116 fputc('\0', stderr);
1118 /* Advance past the portion which has already been printed. */
1119 string += segment_length + 1;
1121 } while (length > 0);
1128 printf ("Usage: %s [switches] input output\n", progname);
1129 printf ("Switches:\n");
1130 printf (" -include <file> Include the contents of <file> before other files\n");
1131 printf (" -imacros <file> Accept definition of macros in <file>\n");
1132 printf (" -iprefix <path> Specify <path> as a prefix for next two options\n");
1133 printf (" -iwithprefix <dir> Add <dir> to the end of the system include paths\n");
1134 printf (" -iwithprefixbefore <dir> Add <dir> to the end of the main include paths\n");
1135 printf (" -isystem <dir> Add <dir> to the start of the system include paths\n");
1136 printf (" -idirafter <dir> Add <dir> to the end of the system include paths\n");
1137 printf (" -I <dir> Add <dir> to the end of the main include paths\n");
1138 printf (" -nostdinc Do not search the system include directories\n");
1139 printf (" -nostdinc++ Do not search the system include directories for C++\n");
1140 printf (" -o <file> Put output into <file>\n");
1141 printf (" -pedantic Issue all warnings demanded by strict ANSI C\n");
1142 printf (" -traditional Follow K&R pre-processor behaviour\n");
1143 printf (" -trigraphs Support ANSI C trigraphs\n");
1144 printf (" -lang-c Assume that the input sources are in C\n");
1145 printf (" -lang-c89 Assume that the input is C89; deprecated\n");
1146 printf (" -lang-c++ Assume that the input sources are in C++\n");
1147 printf (" -lang-objc Assume that the input sources are in ObjectiveC\n");
1148 printf (" -lang-objc++ Assume that the input sources are in ObjectiveC++\n");
1149 printf (" -lang-asm Assume that the input sources are in assembler\n");
1150 printf (" -lang-chill Assume that the input sources are in Chill\n");
1151 printf (" -std=<std name> Specify the conformance standard; one of:\n");
1152 printf (" gnu89, gnu9x, c89, c9x, iso9899:1990,\n");
1153 printf (" iso9899:199409, iso9899:199x\n");
1154 printf (" -+ Allow parsing of C++ style features\n");
1155 printf (" -w Inhibit warning messages\n");
1156 printf (" -Wtrigraphs Warn if trigraphs are encountered\n");
1157 printf (" -Wno-trigraphs Do not warn about trigraphs\n");
1158 printf (" -Wcomment{s} Warn if one comment starts inside another\n");
1159 printf (" -Wno-comment{s} Do not warn about comments\n");
1160 printf (" -Wtraditional Warn if a macro argument is/would be turned into\n");
1161 printf (" a string if -traditional is specified\n");
1162 printf (" -Wno-traditional Do not warn about stringification\n");
1163 printf (" -Wundef Warn if an undefined macro is used by #if\n");
1164 printf (" -Wno-undef Do not warn about testing undefined macros\n");
1165 printf (" -Wimport Warn about the use of the #import directive\n");
1166 printf (" -Wno-import Do not warn about the use of #import\n");
1167 printf (" -Werror Treat all warnings as errors\n");
1168 printf (" -Wno-error Do not treat warnings as errors\n");
1169 printf (" -Wall Enable all preprocessor warnings\n");
1170 printf (" -M Generate make dependencies\n");
1171 printf (" -MM As -M, but ignore system header files\n");
1172 printf (" -MD As -M, but put output in a .d file\n");
1173 printf (" -MMD As -MD, but ignore system header files\n");
1174 printf (" -MG Treat missing header file as generated files\n");
1175 printf (" -g Include #define and #undef directives in the output\n");
1176 printf (" -D<macro> Define a <macro> with string '1' as its value\n");
1177 printf (" -D<macro>=<val> Define a <macro> with <val> as its value\n");
1178 printf (" -A<question> (<answer>) Assert the <answer> to <question>\n");
1179 printf (" -U<macro> Undefine <macro> \n");
1180 printf (" -u or -undef Do not predefine any macros\n");
1181 printf (" -v Display the version number\n");
1182 printf (" -H Print the name of header files as they are used\n");
1183 printf (" -C Do not discard comments\n");
1184 printf (" -dM Display a list of macro definitions active at end\n");
1185 printf (" -dD Preserve macro definitions in output\n");
1186 printf (" -dN As -dD except that only the names are preserved\n");
1187 printf (" -dI Include #include directives in the output\n");
1188 printf (" -ifoutput Describe skipped code blocks in output \n");
1189 printf (" -P Do not generate #line directives\n");
1190 printf (" -$ Do not include '$' in identifiers\n");
1191 printf (" -remap Remap file names when including files.\n");
1192 printf (" -h or --help Display this information\n");
1209 char **pend_assertions;
1210 char **pend_includes;
1212 /* Record the option used with each element of pend_assertions.
1213 This is preparation for supporting more than one option for making
1215 char **pend_assertion_options;
1216 int no_standard_includes = 0;
1217 int no_standard_cplusplus_includes = 0;
1218 int missing_newline = 0;
1220 /* Non-0 means don't output the preprocessed program. */
1221 int inhibit_output = 0;
1222 /* Non-0 means -v, so print the full set of include dirs. */
1225 /* File name which deps are being written to.
1226 This is 0 if deps are being written to stdout. */
1227 char *deps_file = 0;
1228 /* Fopen file mode to open deps_file with. */
1229 char *deps_mode = "a";
1230 /* Stream on which to print the dependency information. */
1231 FILE *deps_stream = 0;
1232 /* Target-name to write with the dependency information. */
1233 char *deps_target = 0;
1235 #if defined (RLIMIT_STACK) && defined (HAVE_GETRLIMIT) && defined (HAVE_SETRLIMIT)
1236 /* Get rid of any avoidable limit on stack size. */
1240 /* Set the stack limit huge so that alloca (particularly stringtab
1241 in dbxread.c) does not fail. */
1242 getrlimit (RLIMIT_STACK, &rlim);
1243 rlim.rlim_cur = rlim.rlim_max;
1244 setrlimit (RLIMIT_STACK, &rlim);
1249 signal (SIGPIPE, pipe_closed);
1252 #ifdef HAVE_LC_MESSAGES
1253 setlocale (LC_MESSAGES, "");
1255 (void) bindtextdomain (PACKAGE, localedir);
1256 (void) textdomain (PACKAGE);
1258 progname = base_name (argv[0]);
1262 /* Remove extension from PROGNAME. */
1264 char *s = progname = xstrdup (progname);
1266 if ((p = rindex (s, ';')) != 0) *p = '\0'; /* strip version number */
1267 if ((p = rindex (s, '.')) != 0 /* strip type iff ".exe" */
1268 && (p[1] == 'e' || p[1] == 'E')
1269 && (p[2] == 'x' || p[2] == 'X')
1270 && (p[3] == 'e' || p[3] == 'E')
1276 /* Do not invoke xmalloc before this point, since locale and
1277 progname need to be set first, in case a diagnostic is issued. */
1279 pend_files = (char **) xmalloc (argc * sizeof (char *));
1280 pend_defs = (char **) xmalloc (argc * sizeof (char *));
1281 pend_undefs = (char **) xmalloc (argc * sizeof (char *));
1282 pend_assertions = (char **) xmalloc (argc * sizeof (char *));
1283 pend_includes = (char **) xmalloc (argc * sizeof (char *));
1284 pend_assertion_options = (char **) xmalloc (argc * sizeof (char *));
1289 /* Initialize is_idchar. */
1290 initialize_char_syntax ();
1292 no_line_directives = 0;
1294 dump_macros = dump_none;
1297 cplusplus_comments = 1;
1299 bzero ((char *) pend_files, argc * sizeof (char *));
1300 bzero ((char *) pend_defs, argc * sizeof (char *));
1301 bzero ((char *) pend_undefs, argc * sizeof (char *));
1302 bzero ((char *) pend_assertions, argc * sizeof (char *));
1303 bzero ((char *) pend_includes, argc * sizeof (char *));
1305 #ifdef MULTIBYTE_CHARS
1306 /* Change to the native locale for multibyte conversions. */
1307 setlocale (LC_CTYPE, "");
1308 literal_codeset = getenv ("LANG");
1311 /* Process switches and find input file name. */
1313 for (i = 1; i < argc; i++) {
1314 if (argv[i][0] != '-') {
1315 if (out_fname != NULL)
1318 fatal ("Too many arguments");
1320 else if (in_fname != NULL)
1321 out_fname = argv[i];
1325 switch (argv[i][1]) {
1328 if (!strcmp (argv[i], "-include")) {
1332 fatal ("Filename missing after `-include' option");
1334 simplify_filename (pend_includes[temp] = argv[++i]);
1336 if (!strcmp (argv[i], "-imacros")) {
1340 fatal ("Filename missing after `-imacros' option");
1342 simplify_filename (pend_files[temp] = argv[++i]);
1344 if (!strcmp (argv[i], "-iprefix")) {
1346 fatal ("Filename missing after `-iprefix' option");
1348 include_prefix = argv[++i];
1350 if (!strcmp (argv[i], "-ifoutput")) {
1351 output_conditionals = 1;
1353 if (!strcmp (argv[i], "-isystem")) {
1354 struct file_name_list *dirtmp;
1356 if (! (dirtmp = new_include_prefix (NULL_PTR, NULL_PTR,
1359 dirtmp->c_system_include_path = 1;
1361 if (before_system == 0)
1362 before_system = dirtmp;
1364 last_before_system->next = dirtmp;
1365 last_before_system = dirtmp; /* Tail follows the last one */
1367 /* Add directory to end of path for includes,
1368 with the default prefix at the front of its name. */
1369 if (!strcmp (argv[i], "-iwithprefix")) {
1370 struct file_name_list *dirtmp;
1373 if (include_prefix != 0)
1374 prefix = include_prefix;
1376 prefix = xstrdup (GCC_INCLUDE_DIR);
1377 /* Remove the `include' from /usr/local/lib/gcc.../include. */
1378 if (!strcmp (prefix + strlen (prefix) - 8, "/include"))
1379 prefix[strlen (prefix) - 7] = 0;
1382 if (! (dirtmp = new_include_prefix (NULL_PTR, NULL_PTR,
1383 prefix, argv[++i])))
1386 if (after_include == 0)
1387 after_include = dirtmp;
1389 last_after_include->next = dirtmp;
1390 last_after_include = dirtmp; /* Tail follows the last one */
1392 /* Add directory to main path for includes,
1393 with the default prefix at the front of its name. */
1394 if (!strcmp (argv[i], "-iwithprefixbefore")) {
1395 struct file_name_list *dirtmp;
1398 if (include_prefix != 0)
1399 prefix = include_prefix;
1401 prefix = xstrdup (GCC_INCLUDE_DIR);
1402 /* Remove the `include' from /usr/local/lib/gcc.../include. */
1403 if (!strcmp (prefix + strlen (prefix) - 8, "/include"))
1404 prefix[strlen (prefix) - 7] = 0;
1407 dirtmp = new_include_prefix (NULL_PTR, NULL_PTR, prefix, argv[++i]);
1408 append_include_chain (dirtmp, dirtmp);
1410 /* Add directory to end of path for includes. */
1411 if (!strcmp (argv[i], "-idirafter")) {
1412 struct file_name_list *dirtmp;
1414 if (! (dirtmp = new_include_prefix (NULL_PTR, NULL_PTR,
1418 if (after_include == 0)
1419 after_include = dirtmp;
1421 last_after_include->next = dirtmp;
1422 last_after_include = dirtmp; /* Tail follows the last one */
1427 if (out_fname != NULL)
1428 fatal ("Output filename specified twice");
1430 fatal ("Filename missing after -o option");
1431 out_fname = argv[++i];
1432 if (!strcmp (out_fname, "-"))
1437 if (!strcmp (argv[i], "-pedantic"))
1439 else if (!strcmp (argv[i], "-pedantic-errors")) {
1441 pedantic_errors = 1;
1442 } else if (!strcmp (argv[i], "-pcp")) {
1445 fatal ("Filename missing after -pcp option");
1446 pcp_fname = argv[++i];
1448 = ((pcp_fname[0] != '-' || pcp_fname[1] != '\0')
1449 ? fopen (pcp_fname, "w")
1451 if (pcp_outfile == 0)
1452 pfatal_with_name (pcp_fname);
1458 if (!strcmp (argv[i], "-traditional")) {
1460 cplusplus_comments = 0;
1461 } else if (!strcmp (argv[i], "-trigraphs")) {
1467 if (! strcmp (argv[i], "-lang-c"))
1468 cplusplus = 0, cplusplus_comments = 1, c89 = 0, c9x = 1, objc = 0;
1469 else if (! strcmp (argv[i], "-lang-c89"))
1470 cplusplus = 0, cplusplus_comments = 0, c89 = 1, c9x = 0, objc = 0;
1471 else if (! strcmp (argv[i], "-lang-c++"))
1472 cplusplus = 1, cplusplus_comments = 1, c89 = 0, c9x = 0, objc = 0;
1473 else if (! strcmp (argv[i], "-lang-objc"))
1474 cplusplus = 0, cplusplus_comments = 1, c89 = 0, c9x = 0, objc = 1;
1475 else if (! strcmp (argv[i], "-lang-objc++"))
1476 cplusplus = 1, cplusplus_comments = 1, c89 = 0, c9x = 0, objc = 1;
1477 else if (! strcmp (argv[i], "-lang-asm"))
1479 else if (! strcmp (argv[i], "-lint"))
1484 cplusplus = 1, cplusplus_comments = 1;
1488 if (!strcmp (argv[i], "-std=iso9899:1990")
1489 || !strcmp (argv[i], "-std=iso9899:199409")
1490 || !strcmp (argv[i], "-std=c89")
1491 || !strcmp (argv[i], "-std=gnu89"))
1492 cplusplus = 0, cplusplus_comments = 0, c89 = 1, c9x = 0, objc = 0;
1493 else if (!strcmp (argv[i], "-std=iso9899:199x")
1494 || !strcmp (argv[i], "-std=c9x")
1495 || !strcmp (argv[i], "-std=gnu9x"))
1496 cplusplus = 0, cplusplus_comments = 1, c89 = 0, c9x = 1, objc = 0;
1500 inhibit_warnings = 1;
1504 if (!strcmp (argv[i], "-Wtrigraphs"))
1506 else if (!strcmp (argv[i], "-Wno-trigraphs"))
1508 else if (!strcmp (argv[i], "-Wcomment"))
1510 else if (!strcmp (argv[i], "-Wno-comment"))
1512 else if (!strcmp (argv[i], "-Wcomments"))
1514 else if (!strcmp (argv[i], "-Wno-comments"))
1516 else if (!strcmp (argv[i], "-Wtraditional"))
1518 else if (!strcmp (argv[i], "-Wno-traditional"))
1520 else if (!strcmp (argv[i], "-Wundef"))
1522 else if (!strcmp (argv[i], "-Wno-undef"))
1524 else if (!strcmp (argv[i], "-Wimport"))
1526 else if (!strcmp (argv[i], "-Wno-import"))
1528 else if (!strcmp (argv[i], "-Werror"))
1529 warnings_are_errors = 1;
1530 else if (!strcmp (argv[i], "-Wno-error"))
1531 warnings_are_errors = 0;
1532 else if (!strcmp (argv[i], "-Wall"))
1540 if (!strcmp (argv[i], "-fleading-underscore"))
1541 user_label_prefix = "_";
1542 else if (!strcmp (argv[i], "-fno-leading-underscore"))
1543 user_label_prefix = "";
1547 /* The style of the choices here is a bit mixed.
1548 The chosen scheme is a hybrid of keeping all options in one string
1549 and specifying each option in a separate argument:
1550 -M|-MM|-MD file|-MMD file [-MG]. An alternative is:
1551 -M|-MM|-MD file|-MMD file|-MG|-MMG; or more concisely:
1552 -M[M][G][D file]. This is awkward to handle in specs, and is not
1554 /* ??? -MG must be specified in addition to one of -M or -MM.
1555 This can be relaxed in the future without breaking anything.
1556 The converse isn't true. */
1558 /* -MG isn't valid with -MD or -MMD. This is checked for later. */
1559 if (!strcmp (argv[i], "-MG"))
1561 print_deps_missing_files = 1;
1564 if (!strcmp (argv[i], "-M"))
1566 else if (!strcmp (argv[i], "-MM"))
1568 else if (!strcmp (argv[i], "-MD"))
1570 else if (!strcmp (argv[i], "-MMD"))
1572 /* For -MD and -MMD options, write deps on file named by next arg. */
1573 if (!strcmp (argv[i], "-MD")
1574 || !strcmp (argv[i], "-MMD")) {
1576 fatal ("Filename missing after %s option", argv[i]);
1578 deps_file = argv[i];
1581 /* For -M and -MM, write deps on standard output
1582 and suppress the usual output. */
1583 deps_stream = stdout;
1590 char *p = argv[i] + 2;
1592 while ((c = *p++)) {
1593 /* Arg to -d specifies what parts of macros to dump */
1596 dump_macros = dump_only;
1600 dump_macros = dump_names;
1603 dump_macros = dump_definitions;
1614 if (argv[i][2] == '3')
1619 if (strcmp (argv[i], "--help") != 0)
1626 notice ("GNU CPP version %s", version_string);
1627 #ifdef TARGET_VERSION
1630 fprintf (stderr, "\n");
1635 print_include_names = 1;
1639 if (argv[i][2] != 0)
1640 pend_defs[i] = argv[i] + 2;
1641 else if (i + 1 == argc)
1642 fatal ("Macro name missing after -D option");
1644 i++, pend_defs[i] = argv[i];
1651 if (argv[i][2] != 0)
1653 else if (i + 1 == argc)
1654 fatal ("Assertion missing after -A option");
1658 if (!strcmp (p, "-")) {
1659 /* -A- eliminates all predefined macros and assertions.
1660 Let's include also any that were specified earlier
1661 on the command line. That way we can get rid of any
1662 that were passed automatically in from GCC. */
1664 for (j = 0; j < i; j++)
1665 pend_defs[j] = pend_assertions[j] = 0;
1667 pend_assertions[i] = p;
1668 pend_assertion_options[i] = "-A";
1673 case 'U': /* JF #undef something */
1674 if (argv[i][2] != 0)
1675 pend_undefs[i] = argv[i] + 2;
1676 else if (i + 1 == argc)
1677 fatal ("Macro name missing after -U option");
1679 pend_undefs[i] = argv[i+1], i++;
1683 put_out_comments = 1;
1686 case 'E': /* -E comes from cc -E; ignore it. */
1690 no_line_directives = 1;
1693 case '$': /* Don't include $ in identifiers. */
1694 is_idchar['$'] = is_idstart['$'] = 0;
1697 case 'I': /* Add directory to path for includes. */
1699 struct file_name_list *dirtmp;
1701 if (! ignore_srcdir && !strcmp (argv[i] + 2, "-")) {
1703 /* Don't use any preceding -I directories for #include <...>. */
1704 first_bracket_include = 0;
1707 dirtmp = new_include_prefix (last_include, NULL_PTR, "",
1708 argv[i][2] ? argv[i] + 2 : argv[++i]);
1709 append_include_chain (dirtmp, dirtmp);
1715 if (!strcmp (argv[i], "-nostdinc"))
1716 /* -nostdinc causes no default include directories.
1717 You must specify all include-file directories with -I. */
1718 no_standard_includes = 1;
1719 else if (!strcmp (argv[i], "-nostdinc++"))
1720 /* -nostdinc++ causes no default C++-specific include directories. */
1721 no_standard_cplusplus_includes = 1;
1722 else if (!strcmp (argv[i], "-noprecomp"))
1727 if (!strcmp (argv[i], "-remap"))
1731 case '\0': /* JF handle '-' as file name meaning stdin or stdout */
1732 if (in_fname == NULL) {
1735 } else if (out_fname == NULL) {
1738 } /* else fall through into error */
1741 fatal ("Invalid option `%s'", argv[i]);
1746 /* Add dirs from CPATH after dirs from -I. */
1747 /* There seems to be confusion about what CPATH should do,
1748 so for the moment it is not documented. */
1749 /* Some people say that CPATH should replace the standard include dirs,
1750 but that seems pointless: it comes before them, so it overrides them
1752 GET_ENV_PATH_LIST (cp, "CPATH");
1753 if (cp && ! no_standard_includes)
1756 /* Initialize output buffer */
1758 outbuf.buf = (U_CHAR *) xmalloc (OUTBUF_SIZE);
1759 outbuf.bufp = outbuf.buf;
1760 outbuf.length = OUTBUF_SIZE;
1762 /* Do partial setup of input buffer for the sake of generating
1763 early #line directives (when -g is in effect). */
1765 fp = &instack[++indepth];
1766 if (in_fname == NULL)
1768 fp->nominal_fname = fp->fname = in_fname;
1769 fp->nominal_fname_len = strlen (in_fname);
1772 /* In C++, wchar_t is a distinct basic type, and we can expect
1773 __wchar_t to be defined by cc1plus. */
1775 wchar_type = "__wchar_t";
1777 /* Install __LINE__, etc. Must follow initialize_char_syntax
1778 and option processing. */
1779 initialize_builtins (fp, &outbuf);
1781 /* Now handle the command line options. */
1783 /* Do -U's, -D's and -A's in the order they were seen. */
1784 for (i = 1; i < argc; i++) {
1785 if (pend_undefs[i]) {
1787 output_line_directive (fp, &outbuf, 0, same_file);
1788 make_undef (pend_undefs[i], &outbuf);
1792 output_line_directive (fp, &outbuf, 0, same_file);
1793 make_definition (pend_defs[i]);
1795 if (pend_assertions[i])
1796 make_assertion (pend_assertion_options[i], pend_assertions[i]);
1799 done_initializing = 1;
1801 { /* Read the appropriate environment variable and if it exists
1802 replace include_defaults with the listed path. */
1804 switch ((objc << 1) + cplusplus)
1807 GET_ENV_PATH_LIST (epath, "C_INCLUDE_PATH");
1810 GET_ENV_PATH_LIST (epath, "CPLUS_INCLUDE_PATH");
1813 GET_ENV_PATH_LIST (epath, "OBJC_INCLUDE_PATH");
1816 GET_ENV_PATH_LIST (epath, "OBJCPLUS_INCLUDE_PATH");
1819 /* If the environment var for this language is set,
1820 add to the default list of include directories. */
1823 char *startp, *endp;
1825 for (num_dirs = 1, startp = epath; *startp; startp++)
1826 if (*startp == PATH_SEPARATOR)
1829 = (struct default_include *) xmalloc ((num_dirs
1830 * sizeof (struct default_include))
1831 + sizeof (include_defaults_array));
1832 startp = endp = epath;
1836 if (c == PATH_SEPARATOR || !c) {
1838 include_defaults[num_dirs].fname
1839 = startp == endp ? "." : xstrdup (startp);
1841 include_defaults[num_dirs].component = 0;
1842 include_defaults[num_dirs].cplusplus = cplusplus;
1843 include_defaults[num_dirs].cxx_aware = 1;
1850 /* Put the usual defaults back in at the end. */
1851 bcopy ((char *) include_defaults_array,
1852 (char *) &include_defaults[num_dirs],
1853 sizeof (include_defaults_array));
1857 append_include_chain (before_system, last_before_system);
1858 first_system_include = before_system;
1860 /* Unless -fnostdinc,
1861 tack on the standard include file dirs to the specified list */
1862 if (!no_standard_includes) {
1863 struct default_include *p = include_defaults;
1864 char *specd_prefix = include_prefix;
1865 char *default_prefix = xstrdup (GCC_INCLUDE_DIR);
1866 int default_len = 0;
1867 /* Remove the `include' from /usr/local/lib/gcc.../include. */
1868 if (!strcmp (default_prefix + strlen (default_prefix) - 8, "/include")) {
1869 default_len = strlen (default_prefix) - 7;
1870 default_prefix[default_len] = 0;
1872 /* Search "translated" versions of GNU directories.
1873 These have /usr/local/lib/gcc... replaced by specd_prefix. */
1874 if (specd_prefix != 0 && default_len != 0)
1875 for (p = include_defaults; p->fname; p++) {
1876 /* Some standard dirs are only for C++. */
1877 if (!p->cplusplus || (cplusplus && !no_standard_cplusplus_includes)) {
1878 /* Does this dir start with the prefix? */
1879 if (!strncmp (p->fname, default_prefix, default_len)) {
1880 /* Yes; change prefix and add to search list. */
1881 struct file_name_list *new
1882 = new_include_prefix (NULL_PTR, NULL_PTR, specd_prefix,
1883 p->fname + default_len);
1885 new->c_system_include_path = !p->cxx_aware;
1886 append_include_chain (new, new);
1887 if (first_system_include == 0)
1888 first_system_include = new;
1894 /* Search ordinary names for GNU include directories. */
1895 for (p = include_defaults; p->fname; p++) {
1896 /* Some standard dirs are only for C++. */
1897 if (!p->cplusplus || (cplusplus && !no_standard_cplusplus_includes)) {
1898 struct file_name_list *new
1899 = new_include_prefix (NULL_PTR, p->component, "", p->fname);
1901 new->c_system_include_path = !p->cxx_aware;
1902 append_include_chain (new, new);
1903 if (first_system_include == 0)
1904 first_system_include = new;
1911 /* Tack the after_include chain at the end of the include chain. */
1912 append_include_chain (after_include, last_after_include);
1913 if (first_system_include == 0)
1914 first_system_include = after_include;
1916 /* With -v, print the list of dirs to search. */
1918 struct file_name_list *p;
1919 notice ("#include \"...\" search starts here:\n");
1920 for (p = include; p; p = p->next) {
1921 if (p == first_bracket_include)
1922 notice ("#include <...> search starts here:\n");
1924 fprintf (stderr, " .\n");
1925 else if (!strcmp (p->fname, "/") || !strcmp (p->fname, "//"))
1926 fprintf (stderr, " %s\n", p->fname);
1928 /* Omit trailing '/'. */
1929 fprintf (stderr, " %.*s\n", (int) strlen (p->fname) - 1, p->fname);
1931 notice ("End of search list.\n");
1933 struct default_include * d;
1934 notice ("The following default directories have been omitted from the search path:\n");
1935 for (d = include_defaults; d->fname; d++)
1937 fprintf (stderr, " %s\n", d->fname);
1938 notice ("End of omitted list.\n");
1942 /* -MG doesn't select the form of output and must be specified with one of
1943 -M or -MM. -MG doesn't make sense with -MD or -MMD since they don't
1944 inhibit compilation. */
1945 if (print_deps_missing_files && (print_deps == 0 || !inhibit_output))
1946 fatal ("-MG must be specified with one of -M or -MM");
1948 /* Either of two environment variables can specify output of deps.
1949 Its value is either "OUTPUT_FILE" or "OUTPUT_FILE DEPS_TARGET",
1950 where OUTPUT_FILE is the file to write deps info to
1951 and DEPS_TARGET is the target to mention in the deps. */
1954 && (getenv ("SUNPRO_DEPENDENCIES") != 0
1955 || getenv ("DEPENDENCIES_OUTPUT") != 0)) {
1956 char *spec = getenv ("DEPENDENCIES_OUTPUT");
1961 spec = getenv ("SUNPRO_DEPENDENCIES");
1968 /* Find the space before the DEPS_TARGET, if there is one. */
1969 /* This should use index. (mrs) */
1970 while (*s != 0 && *s != ' ') s++;
1972 deps_target = s + 1;
1973 output_file = xmalloc (s - spec + 1);
1974 bcopy (spec, output_file, s - spec);
1975 output_file[s - spec] = 0;
1982 deps_file = output_file;
1986 /* For -M, print the expected object file name
1987 as the target of this Make-rule. */
1989 deps_allocated_size = 200;
1990 deps_buffer = xmalloc (deps_allocated_size);
1996 deps_output (deps_target, ':');
1997 } else if (*in_fname == 0) {
1998 deps_output ("-", ':');
2003 q = base_name (in_fname);
2005 /* Copy remainder to mungable area. */
2006 p = (char *) alloca (strlen(q) + 8);
2009 /* Output P, but remove known suffixes. */
2013 && p[len - 2] == '.'
2014 && index("cCsSm", p[len - 1]))
2017 && p[len - 3] == '.'
2018 && p[len - 2] == 'c'
2019 && p[len - 1] == 'c')
2022 && p[len - 4] == '.'
2023 && p[len - 3] == 'c'
2024 && p[len - 2] == 'x'
2025 && p[len - 1] == 'x')
2028 && p[len - 4] == '.'
2029 && p[len - 3] == 'c'
2030 && p[len - 2] == 'p'
2031 && p[len - 1] == 'p')
2034 /* Supply our own suffix. */
2035 strcpy (q, OBJECT_SUFFIX);
2037 deps_output (p, ':');
2038 deps_output (in_fname, ' ');
2042 /* Scan the -imacros files before the main input.
2043 Much like #including them, but with no_output set
2044 so that only their macro definitions matter. */
2046 no_output++; no_record_file++;
2047 for (i = 1; i < argc; i++)
2048 if (pend_files[i]) {
2049 struct include_file *inc;
2050 int fd = open_include_file (pend_files[i], NULL_PTR, NULL_PTR, &inc);
2052 perror_with_name (pend_files[i]);
2053 return FATAL_EXIT_CODE;
2055 finclude (fd, inc, &outbuf, 0, NULL_PTR);
2057 no_output--; no_record_file--;
2059 /* Copy the entire contents of the main input file into
2060 the stacked input buffer previously allocated for it. */
2062 /* JF check for stdin */
2063 if (in_fname == NULL || *in_fname == 0) {
2066 } else if ((f = open (in_fname, O_RDONLY, 0666)) < 0)
2069 if (fstat (f, &st) != 0)
2070 pfatal_with_name (in_fname);
2071 fp->nominal_fname = fp->fname = in_fname;
2072 fp->nominal_fname_len = strlen (in_fname);
2074 fp->system_header_p = 0;
2075 /* JF all this is mine about reading pipes and ttys */
2076 if (! S_ISREG (st.st_mode)) {
2077 /* Read input from a file that is not a normal disk file.
2078 We cannot preallocate a buffer with the correct size,
2079 so we must read in the file a piece at the time and make it bigger. */
2084 if (S_ISDIR (st.st_mode))
2085 fatal ("Input file `%s' is a directory", in_fname);
2089 fp->buf = (U_CHAR *) xmalloc (bsize + 2);
2091 cnt = safe_read (f, (char *) fp->buf + size, bsize - size);
2092 if (cnt < 0) goto perror; /* error! */
2094 if (size != bsize) break; /* End of file */
2096 fp->buf = (U_CHAR *) xrealloc (fp->buf, bsize + 2);
2100 /* Read a file whose size we can determine in advance.
2101 For the sake of VMS, st.st_size is just an upper bound. */
2102 size_t s = (size_t) st.st_size;
2103 if (s != st.st_size || s + 2 < s)
2105 fp->buf = (U_CHAR *) xmalloc (s + 2);
2106 fp->length = safe_read (f, (char *) fp->buf, s);
2107 if (fp->length < 0) goto perror;
2110 fp->if_stack = if_stack;
2112 /* Make sure data ends with a newline. And put a null after it. */
2114 if ((fp->length > 0 && fp->buf[fp->length - 1] != '\n')
2115 /* Backslash-newline at end is not good enough. */
2116 || (fp->length > 1 && fp->buf[fp->length - 2] == '\\')) {
2117 fp->buf[fp->length++] = '\n';
2118 missing_newline = 1;
2120 fp->buf[fp->length] = '\0';
2122 /* Unless inhibited, convert trigraphs in the input. */
2127 /* Now that we know the input file is valid, open the output. */
2129 if (!out_fname || !strcmp (out_fname, ""))
2130 out_fname = "stdout";
2131 else if (! freopen (out_fname, "w", stdout))
2132 pfatal_with_name (out_fname);
2134 output_line_directive (fp, &outbuf, 0, same_file);
2136 /* Scan the -include files before the main input. */
2139 for (i = 1; i < argc; i++)
2140 if (pend_includes[i]) {
2141 struct include_file *inc;
2142 int fd = open_include_file (pend_includes[i], NULL_PTR, NULL_PTR, &inc);
2144 perror_with_name (pend_includes[i]);
2145 return FATAL_EXIT_CODE;
2147 finclude (fd, inc, &outbuf, 0, NULL_PTR);
2151 /* Scan the input, processing macros and directives. */
2153 rescan (&outbuf, 0);
2155 if (missing_newline)
2158 if (pedantic && missing_newline)
2159 pedwarn ("file does not end in newline");
2161 /* Now we have processed the entire input
2162 Write whichever kind of output has been requested. */
2164 if (dump_macros == dump_only)
2166 else if (! inhibit_output) {
2171 /* Don't actually write the deps file if compilation has failed. */
2173 if (deps_file && ! (deps_stream = fopen (deps_file, deps_mode)))
2174 pfatal_with_name (deps_file);
2175 fputs (deps_buffer, deps_stream);
2176 putc ('\n', deps_stream);
2178 if (ferror (deps_stream) || fclose (deps_stream) != 0)
2179 fatal ("I/O error on output");
2184 if (pcp_outfile && pcp_outfile != stdout
2185 && (ferror (pcp_outfile) || fclose (pcp_outfile) != 0))
2186 fatal ("I/O error on `-pcp' output");
2188 if (ferror (stdout) || fclose (stdout) != 0)
2189 fatal ("I/O error on output");
2192 exit (FATAL_EXIT_CODE);
2193 exit (SUCCESS_EXIT_CODE);
2196 pfatal_with_name (in_fname);
2200 /* Given a colon-separated list of file names PATH,
2201 add all the names to the search path for include files. */
2215 struct file_name_list *dirtmp;
2217 /* Find the end of this name. */
2218 while ((c = *q++) != PATH_SEPARATOR && c)
2222 dirtmp = new_include_prefix (last_include, NULL_PTR,
2223 "", p == q ? "." : p);
2225 append_include_chain (dirtmp, dirtmp);
2227 /* Advance past this name. */
2234 /* Return the address of the first character in S that equals C.
2235 S is an array of length N, possibly containing '\0's, and followed by '\0'.
2236 Return 0 if there is no such character. Assume that C itself is not '\0'.
2237 If we knew we could use memchr, we could just invoke memchr (S, C, N),
2238 but unfortunately memchr isn't autoconfigured yet. */
2246 char *p = (char *) s;
2248 char *q = index (p, c);
2250 return (U_CHAR *) q;
2252 size_t l = strlen (p);
2262 /* Pre-C-Preprocessor to translate ANSI trigraph idiocy in BUF
2263 before main CCCP processing. Name `pcp' is also in honor of the
2264 drugs the trigraph designers must have been on.
2266 Using an extra pass through the buffer takes a little extra time,
2267 but is infinitely less hairy than trying to handle trigraphs inside
2268 strings, etc. everywhere, and also makes sure that trigraphs are
2269 only translated in the top level of processing. */
2275 register U_CHAR c, *fptr, *bptr, *sptr, *lptr;
2278 fptr = bptr = sptr = buf->buf;
2279 lptr = fptr + buf->length;
2280 while ((sptr = index0 (sptr, '?', (size_t) (lptr - sptr))) != NULL) {
2317 len = sptr - fptr - 2;
2319 /* BSD doc says bcopy () works right for overlapping strings. In ANSI
2320 C, this will be memmove (). */
2321 if (bptr != fptr && len > 0)
2322 bcopy ((char *) fptr, (char *) bptr, len);
2328 len = buf->length - (fptr - buf->buf);
2329 if (bptr != fptr && len > 0)
2330 bcopy ((char *) fptr, (char *) bptr, len);
2331 buf->length -= fptr - bptr;
2332 buf->buf[buf->length] = '\0';
2333 if (warn_trigraphs && fptr != bptr)
2334 warning_with_line (0, "%lu trigraph(s) encountered",
2335 (unsigned long) (fptr - bptr) / 2);
2338 /* Move all backslash-newline pairs out of embarrassing places.
2339 Exchange all such pairs following BP
2340 with any potentially-embarrassing characters that follow them.
2341 Potentially-embarrassing characters are / and *
2342 (because a backslash-newline inside a comment delimiter
2343 would cause it not to be recognized). */
2349 register U_CHAR *p = bp;
2351 /* First count the backslash-newline pairs here. */
2353 while (p[0] == '\\' && p[1] == '\n')
2356 /* What follows the backslash-newlines is not embarrassing. */
2358 if (*p != '/' && *p != '*')
2361 /* Copy all potentially embarrassing characters
2362 that follow the backslash-newline pairs
2363 down to where the pairs originally started. */
2365 while (*p == '*' || *p == '/')
2368 /* Now write the same number of pairs after the embarrassing chars. */
2375 /* Like newline_fix but for use within a directive-name.
2376 Move any backslash-newlines up past any following symbol constituents. */
2379 name_newline_fix (bp)
2382 register U_CHAR *p = bp;
2384 /* First count the backslash-newline pairs here. */
2385 while (p[0] == '\\' && p[1] == '\n')
2388 /* What follows the backslash-newlines is not embarrassing. */
2393 /* Copy all potentially embarrassing characters
2394 that follow the backslash-newline pairs
2395 down to where the pairs originally started. */
2397 while (is_idchar[*p])
2400 /* Now write the same number of pairs after the embarrassing chars. */
2407 /* Look for lint commands in comments.
2409 When we come in here, ibp points into a comment. Limit is as one expects.
2410 scan within the comment -- it should start, after lwsp, with a lint command.
2411 If so that command is returned as a (constant) string.
2413 Upon return, any arg will be pointed to with argstart and will be
2414 arglen long. Note that we don't parse that arg since it will just
2415 be printed out again. */
2418 get_lintcmd (ibp, limit, argstart, arglen, cmdlen)
2419 register U_CHAR *ibp;
2420 register U_CHAR *limit;
2421 U_CHAR **argstart; /* point to command arg */
2422 int *arglen, *cmdlen; /* how long they are */
2424 HOST_WIDEST_INT linsize;
2425 register U_CHAR *numptr; /* temp for arg parsing */
2429 SKIP_WHITE_SPACE (ibp);
2431 if (ibp >= limit) return NULL;
2433 linsize = limit - ibp;
2435 /* Oh, I wish C had lexical functions... hell, I'll just open-code the set */
2436 if ((linsize >= 10) && !bcmp (ibp, "NOTREACHED", 10)) {
2438 return "NOTREACHED";
2440 if ((linsize >= 8) && !bcmp (ibp, "ARGSUSED", 8)) {
2444 if ((linsize >= 11) && !bcmp (ibp, "LINTLIBRARY", 11)) {
2446 return "LINTLIBRARY";
2448 if ((linsize >= 7) && !bcmp (ibp, "VARARGS", 7)) {
2450 ibp += 7; linsize -= 7;
2451 if ((linsize == 0) || ! ISDIGIT (*ibp)) return "VARARGS";
2453 /* OK, read a number */
2454 for (numptr = *argstart = ibp; (numptr < limit) && ISDIGIT (*numptr);
2456 *arglen = numptr - *argstart;
2463 * The main loop of the program.
2465 * Read characters from the input stack, transferring them to the
2468 * Macros are expanded and push levels on the input stack.
2469 * At the end of such a level it is popped off and we keep reading.
2470 * At the end of any other kind of level, we return.
2471 * #-directives are handled, except within macros.
2473 * If OUTPUT_MARKS is nonzero, keep Newline markers found in the input
2474 * and insert them when appropriate. This is set while scanning macro
2475 * arguments before substitution. It is zero when scanning for final output.
2476 * There are three types of Newline markers:
2477 * * Newline - follows a macro name that was not expanded
2478 * because it appeared inside an expansion of the same macro.
2479 * This marker prevents future expansion of that identifier.
2480 * When the input is rescanned into the final output, these are deleted.
2481 * These are also deleted by ## concatenation.
2482 * * Newline Space (or Newline and any other whitespace character)
2483 * stands for a place that tokens must be separated or whitespace
2484 * is otherwise desirable, but where the ANSI standard specifies there
2485 * is no whitespace. This marker turns into a Space (or whichever other
2486 * whitespace char appears in the marker) in the final output,
2487 * but it turns into nothing in an argument that is stringified with #.
2488 * Such stringified arguments are the only place where the ANSI standard
2489 * specifies with precision that whitespace may not appear.
2491 * During this function, IP->bufp is kept cached in IBP for speed of access.
2492 * Likewise, OP->bufp is kept in OBP. Before calling a subroutine
2493 * IBP, IP and OBP must be copied back to memory. IP and IBP are
2494 * copied back with the RECACHE macro. OBP must be copied back from OP->bufp
2495 * explicitly, and before RECACHE, since RECACHE uses OBP.
2499 rescan (op, output_marks)
2503 /* Character being scanned in main loop. */
2506 /* Length of pending accumulated identifier. */
2507 register int ident_length = 0;
2509 /* Hash code of pending accumulated identifier. */
2510 register int hash = 0;
2512 /* Current input level (&instack[indepth]). */
2515 /* Pointer for scanning input. */
2516 register U_CHAR *ibp;
2518 /* Pointer to end of input. End of scan is controlled by LIMIT. */
2519 register U_CHAR *limit;
2521 /* Pointer for storing output. */
2522 register U_CHAR *obp;
2524 /* REDO_CHAR is nonzero if we are processing an identifier
2525 after backing up over the terminating character.
2526 Sometimes we process an identifier without backing up over
2527 the terminating character, if the terminating character
2528 is not special. Backing up is done so that the terminating character
2529 will be dispatched on again once the identifier is dealt with. */
2532 /* 1 if within an identifier inside of which a concatenation
2533 marker (Newline -) has been seen. */
2534 int concatenated = 0;
2536 /* While scanning a comment or a string constant,
2537 this records the line it started on, for error messages. */
2540 /* Record position of last `real' newline. */
2541 U_CHAR *beg_of_line;
2543 /* Pop the innermost input stack level, assuming it is a macro expansion. */
2546 do { ip->macro->type = T_MACRO; \
2547 if (ip->free_ptr) free (ip->free_ptr); \
2548 --indepth; } while (0)
2550 /* Reload `rescan's local variables that describe the current
2551 level of the input stack. */
2554 do { ip = &instack[indepth]; \
2556 limit = ip->buf + ip->length; \
2558 check_expand (op, limit - ibp); \
2560 obp = op->bufp; } while (0)
2562 if (no_output && instack[indepth].fname != 0)
2563 skip_if_group (&instack[indepth], 1, NULL);
2570 /* Our caller must always put a null after the end of
2571 the input at each input stack level. */
2581 if (*ibp == '\n' && !ip->macro) {
2582 /* At the top level, always merge lines ending with backslash-newline,
2583 even in middle of identifier. But do not merge lines in a macro,
2584 since backslash might be followed by a newline-space marker. */
2587 --obp; /* remove backslash from obuf */
2590 /* If ANSI, backslash is just another character outside a string. */
2593 /* Otherwise, backslash suppresses specialness of following char,
2594 so copy it here to prevent the switch from seeing it.
2595 But first get any pending identifier processed. */
2596 if (ident_length > 0)
2603 if (ident_length || ip->macro || traditional)
2605 while (*ibp == '\\' && ibp[1] == '\n') {
2611 /* Treat this %: digraph as if it were #. */
2615 if (assertions_flag) {
2618 /* Copy #foo (bar lose) without macro expansion. */
2619 obp[-1] = '#'; /* In case it was '%'. */
2620 SKIP_WHITE_SPACE (ibp);
2621 while (is_idchar[*ibp])
2623 SKIP_WHITE_SPACE (ibp);
2626 skip_paren_group (ip);
2627 bcopy ((char *) ibp, (char *) obp, ip->bufp - ibp);
2628 obp += ip->bufp - ibp;
2634 /* If this is expanding a macro definition, don't recognize
2635 preprocessing directives. */
2638 /* If this is expand_into_temp_buffer,
2639 don't recognize them either. Warn about them
2640 only after an actual newline at this level,
2641 not at the beginning of the input level. */
2643 if (ip->buf != beg_of_line)
2644 warning ("preprocessing directive not recognized within macro arg");
2651 /* # keyword: a # must be first nonblank char on the line */
2652 if (beg_of_line == 0)
2657 /* Scan from start of line, skipping whitespace, comments
2658 and backslash-newlines, and see if we reach this #.
2659 If not, this # is not special. */
2661 /* If -traditional, require # to be at beginning of line. */
2664 if (is_hor_space[*bp])
2666 else if (*bp == '\\' && bp[1] == '\n')
2668 else if (*bp == '/' && bp[1] == '*') {
2682 #ifdef MULTIBYTE_CHARS
2684 length = local_mblen (bp, limit - bp);
2692 /* There is no point in trying to deal with C++ // comments here,
2693 because if there is one, then this # must be part of the
2694 comment and we would never reach here. */
2700 while (bp[1] == '\\' && bp[2] == '\n')
2704 /* %: appears at start of line; skip past the ':' too. */
2713 /* This # can start a directive. */
2715 --obp; /* Don't copy the '#' */
2719 if (! handle_directive (ip, op)) {
2723 /* Not a known directive: treat it as ordinary text.
2724 IP, OP, IBP, etc. have not been changed. */
2725 if (no_output && instack[indepth].fname) {
2726 /* If not generating expanded output,
2727 what we do with ordinary text is skip it.
2728 Discard everything until next # directive. */
2729 skip_if_group (&instack[indepth], 1, 0);
2734 *obp++ = '#'; /* Copy # (even if it was originally %:). */
2735 /* Don't expand an identifier that could be a macro directive.
2736 (Section 3.8.3 of the ANSI C standard) */
2737 SKIP_WHITE_SPACE (ibp);
2738 if (is_idstart[*ibp])
2741 while (is_idchar[*ibp])
2749 /* A # directive has been successfully processed. */
2750 /* If not generating expanded output, ignore everything until
2751 next # directive. */
2752 if (no_output && instack[indepth].fname)
2753 skip_if_group (&instack[indepth], 1, 0);
2759 case '\"': /* skip quoted string */
2761 /* A single quoted string is treated like a double -- some
2762 programs (e.g., troff) are perverse this way */
2764 /* Handle any pending identifier;
2765 but the L in L'...' or L"..." is not an identifier. */
2767 if (! (ident_length == 1 && hash == HASHSTEP (0, 'L')))
2769 ident_length = hash = 0;
2772 start_line = ip->lineno;
2774 /* Skip ahead to a matching quote. */
2778 if (ip->macro != 0) {
2779 /* try harder: this string crosses a macro expansion boundary.
2780 This can happen naturally if -traditional.
2781 Otherwise, only -D can make a macro with an unmatched quote. */
2787 error_with_line (line_for_error (start_line),
2788 "unterminated string or character constant");
2789 if (multiline_string_line) {
2790 error_with_line (multiline_string_line,
2791 "possible real start of unterminated constant");
2792 multiline_string_line = 0;
2802 /* Traditionally, end of line ends a string constant with no error.
2803 So exit the loop and record the new line. */
2809 error_with_line (line_for_error (start_line),
2810 "unterminated character constant");
2813 if (multiline_string_line == 0) {
2815 pedwarn_with_line (line_for_error (start_line),
2816 "string constant runs past end of line");
2817 multiline_string_line = ip->lineno - 1;
2823 /* Backslash newline is replaced by nothing at all, but
2824 keep the line counts correct. But if we are reading
2825 from a macro, keep the backslash newline, since backslash
2826 newlines have already been processed. */
2834 /* ANSI stupidly requires that in \\ the second \
2835 is *not* prevented from combining with a newline. */
2837 while (*ibp == '\\' && ibp[1] == '\n') {
2851 #ifdef MULTIBYTE_CHARS
2856 length = local_mblen (ibp, limit - ibp);
2860 bcopy (ibp, obp, length);
2877 if (*ibp == '\\' && ibp[1] == '\n')
2880 && !(cplusplus_comments && *ibp == '/'))
2886 /* C++ style comment... */
2887 start_line = ip->lineno;
2889 /* Comments are equivalent to spaces. */
2890 if (! put_out_comments)
2894 U_CHAR *before_bp = ibp;
2896 while (++ibp < limit) {
2899 if (put_out_comments) {
2900 bcopy ((char *) before_bp, (char *) obp, ibp - before_bp);
2901 obp += ibp - before_bp;
2907 if (ibp + 1 < limit && ibp[1] == '\n')
2910 warning ("multiline `//' comment");
2912 /* Copy the newline into the output buffer, in order to
2913 avoid the pain of a #line every time a multiline comment
2915 if (!put_out_comments)
2923 #ifdef MULTIBYTE_CHARS
2925 length = local_mblen (ibp, limit - ibp);
2927 ibp += (length - 1);
2935 /* Ordinary C comment. Skip it, optionally copying it to output. */
2937 start_line = ip->lineno;
2939 ++ibp; /* Skip the star. */
2941 /* If this cpp is for lint, we peek inside the comments: */
2945 char *lintcmd = get_lintcmd (ibp, limit, &argbp, &arglen, &cmdlen);
2947 if (lintcmd != NULL) {
2949 check_expand (op, cmdlen + arglen + 14);
2951 /* I believe it is always safe to emit this newline: */
2953 bcopy ("#pragma lint ", (char *) obp, 13);
2955 bcopy (lintcmd, (char *) obp, cmdlen);
2960 bcopy (argbp, (char *) obp, arglen);
2964 /* OK, now bring us back to the state we were in before we entered
2965 this branch. We need #line because the #pragma's newline always
2966 messes up the line count. */
2968 output_line_directive (ip, op, 0, same_file);
2969 check_expand (op, limit - ibp + 2);
2975 /* Comments are equivalent to spaces.
2976 Note that we already output the slash; we might not want it.
2977 For -traditional, a comment is equivalent to nothing. */
2978 if (! put_out_comments) {
2988 U_CHAR *before_bp = ibp;
2993 if (ibp[-2] == '/' && warn_comments)
2994 warning ("`/*' within comment");
2995 if (*ibp == '\\' && ibp[1] == '\n')
3003 /* Copy the newline into the output buffer, in order to
3004 avoid the pain of a #line every time a multiline comment
3006 if (!put_out_comments)
3013 error_with_line (line_for_error (start_line),
3014 "unterminated comment");
3018 #ifdef MULTIBYTE_CHARS
3022 length = local_mblen (ibp, limit - ibp);
3024 ibp += (length - 1);
3033 if (put_out_comments) {
3034 bcopy ((char *) before_bp, (char *) obp, ibp - before_bp);
3035 obp += ibp - before_bp;
3041 if (! is_idchar['$'])
3044 pedwarn ("`$' in identifier");
3047 case '0': case '1': case '2': case '3': case '4':
3048 case '5': case '6': case '7': case '8': case '9':
3049 /* If digit is not part of identifier, it starts a number,
3050 which means that following letters are not an identifier.
3051 "0x5" does not refer to an identifier "x5".
3052 So copy all alphanumerics that follow without accumulating
3053 as an identifier. Periods also, for sake of "3.e7". */
3055 if (ident_length == 0) {
3058 while (ibp[0] == '\\' && ibp[1] == '\n') {
3064 if (!is_idchar[c] && c != '.') {
3069 /* A sign can be part of a preprocessing number
3070 if it follows an `e' or `p'. */
3071 if (c == 'e' || c == 'E' || c == 'p' || c == 'P') {
3073 while (ibp[0] == '\\' && ibp[1] == '\n') {
3078 if (*ibp == '+' || *ibp == '-') {
3080 /* But traditional C does not let the token go past the sign,
3081 and C89 does not allow `p'. */
3082 if (traditional || (c89 && (c == 'p' || c == 'P')))
3092 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
3093 case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
3094 case 'm': case 'n': case 'o': case 'p': case 'q': case 'r':
3095 case 's': case 't': case 'u': case 'v': case 'w': case 'x':
3097 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
3098 case 'G': case 'H': case 'I': case 'J': case 'K': case 'L':
3099 case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R':
3100 case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
3104 /* Compute step of hash function, to avoid a proc call on every token */
3105 hash = HASHSTEP (hash, c);
3109 if (ip->fname == 0 && *ibp == '-') {
3110 /* Newline - inhibits expansion of preceding token.
3111 If expanding a macro arg, we keep the newline -.
3112 In final output, it is deleted.
3113 We recognize Newline - in macro bodies and macro args. */
3114 if (! concatenated) {
3119 if (!output_marks) {
3122 /* If expanding a macro arg, keep the newline -. */
3128 /* If reprocessing a macro expansion, newline is a special marker. */
3129 else if (ip->macro != 0) {
3130 /* Newline White is a "funny space" to separate tokens that are
3131 supposed to be separate but without space between.
3132 Here White means any whitespace character.
3133 Newline - marks a recursive macro use that is not
3134 supposed to be expandable. */
3136 if (is_space[*ibp]) {
3137 /* Newline Space does not prevent expansion of preceding token
3138 so expand the preceding token and then come back. */
3139 if (ident_length > 0)
3142 /* If generating final output, newline space makes a space. */
3143 if (!output_marks) {
3145 /* And Newline Newline makes a newline, so count it. */
3146 if (obp[-1] == '\n')
3149 /* If expanding a macro arg, keep the newline space.
3150 If the arg gets stringified, newline space makes nothing. */
3153 } else abort (); /* Newline followed by something random? */
3157 /* If there is a pending identifier, handle it and come back here. */
3158 if (ident_length > 0)
3163 /* Update the line counts and output a #line if necessary. */
3166 if (ip->lineno != op->lineno) {
3168 output_line_directive (ip, op, 1, same_file);
3169 check_expand (op, limit - ibp);
3174 /* Come here either after (1) a null character that is part of the input
3175 or (2) at the end of the input, because there is a null there. */
3178 /* Our input really contains a null character. */
3182 /* At end of a macro-expansion level, pop it and read next level. */
3183 if (ip->macro != 0) {
3186 /* If traditional, and we have an identifier that ends here,
3187 process it now, so we get the right error for recursion. */
3188 if (traditional && ident_length
3189 && ! is_idchar[*instack[indepth - 1].bufp]) {
3198 /* If we don't have a pending identifier,
3199 return at end of input. */
3200 if (ident_length == 0) {
3208 /* If we do have a pending identifier, just consider this null
3209 a special character and arrange to dispatch on it again.
3210 The second time, IDENT_LENGTH will be zero so we will return. */
3216 /* Handle the case of a character such as /, ', " or null
3217 seen following an identifier. Back over it so that
3218 after the identifier is processed the special char
3219 will be dispatched on again. */
3229 if (ident_length > 0) {
3230 register HASHNODE *hp;
3232 /* We have just seen an identifier end. If it's a macro, expand it.
3234 IDENT_LENGTH is the length of the identifier
3235 and HASH is its hash code.
3237 The identifier has already been copied to the output,
3238 so if it is a macro we must remove it.
3240 If REDO_CHAR is 0, the char that terminated the identifier
3241 has been skipped in the output and the input.
3242 OBP-IDENT_LENGTH-1 points to the identifier.
3243 If the identifier is a macro, we must back over the terminator.
3245 If REDO_CHAR is 1, the terminating char has already been
3246 backed over. OBP-IDENT_LENGTH points to the identifier. */
3248 if (!pcp_outfile || pcp_inside_if) {
3249 for (hp = hashtab[MAKE_POS (hash) % HASHSIZE]; hp != NULL;
3252 if (hp->length == ident_length) {
3253 int obufp_before_macroname;
3254 int op_lineno_before_macroname;
3255 register int i = ident_length;
3256 register U_CHAR *p = hp->name;
3257 register U_CHAR *q = obp - i;
3263 do { /* All this to avoid a strncmp () */
3268 /* We found a use of a macro name.
3269 see if the context shows it is a macro call. */
3271 /* Back up over terminating character if not already done. */
3277 /* Save this as a displacement from the beginning of the output
3278 buffer. We can not save this as a position in the output
3279 buffer, because it may get realloc'ed by RECACHE. */
3280 obufp_before_macroname = (obp - op->buf) - ident_length;
3281 op_lineno_before_macroname = op->lineno;
3283 if (hp->type == T_PCSTRING) {
3284 pcstring_used (hp); /* Mark the definition of this key
3285 as needed, ensuring that it
3287 break; /* Exit loop, since the key cannot have a
3288 definition any longer. */
3291 /* Record whether the macro is disabled. */
3292 disabled = hp->type == T_DISABLED;
3294 /* This looks like a macro ref, but if the macro was disabled,
3295 just copy its name and put in a marker if requested. */
3299 /* This error check caught useful cases such as
3300 #define foo(x,y) bar (x (y,0), y)
3303 error ("recursive use of macro `%s'", hp->name);
3308 check_expand (op, limit - ibp + 2);
3316 /* If macro wants an arglist, verify that a '(' follows.
3317 first skip all whitespace, copying it to the output
3318 after the macro name. Then, if there is no '(',
3319 decide this is not a macro call and leave things that way. */
3320 if ((hp->type == T_MACRO || hp->type == T_DISABLED)
3321 && hp->value.defn->nargs >= 0)
3323 U_CHAR *old_ibp = ibp;
3324 U_CHAR *old_obp = obp;
3325 int old_iln = ip->lineno;
3326 int old_oln = op->lineno;
3329 /* Scan forward over whitespace, copying it to the output. */
3330 if (ibp == limit && ip->macro != 0) {
3335 old_iln = ip->lineno;
3336 old_oln = op->lineno;
3338 else if (is_space[*ibp]) {
3340 if (ibp[-1] == '\n') {
3341 if (ip->macro == 0) {
3342 /* Newline in a file. Count it. */
3345 } else if (!output_marks) {
3346 /* A newline mark, and we don't want marks
3347 in the output. If it is newline-hyphen,
3348 discard it entirely. Otherwise, it is
3349 newline-whitechar, so keep the whitechar. */
3359 /* A newline mark; copy both chars to the output. */
3366 else if (*ibp == '/') {
3367 /* If a comment, copy it unchanged or discard it. */
3368 if (ibp[1] == '\\' && ibp[2] == '\n')
3369 newline_fix (ibp + 1);
3370 if (ibp[1] == '*') {
3371 if (put_out_comments) {
3374 } else if (! traditional) {
3377 for (ibp += 2; ibp < limit; ibp++) {
3378 /* We need not worry about newline-marks,
3379 since they are never found in comments. */
3380 if (ibp[0] == '*') {
3381 if (ibp[1] == '\\' && ibp[2] == '\n')
3382 newline_fix (ibp + 1);
3383 if (ibp[1] == '/') {
3385 if (put_out_comments) {
3392 else if (*ibp == '\n') {
3393 /* Newline in a file. Count it. */
3399 #ifdef MULTIBYTE_CHARS
3401 length = local_mblen (ibp, limit - ibp);
3404 if (put_out_comments)
3406 bcopy (ibp, obp, length - 1);
3409 ibp += (length - 1);
3413 if (put_out_comments)
3416 } else if (ibp[1] == '/' && cplusplus_comments) {
3417 if (put_out_comments) {
3420 } else if (! traditional) {
3423 for (ibp += 2; ; ibp++)
3427 if (*ibp == '\\' && ibp[1] == '\n')
3429 if (put_out_comments)
3434 #ifdef MULTIBYTE_CHARS
3436 length = local_mblen (ibp, limit - ibp);
3439 if (put_out_comments)
3441 bcopy (ibp, obp, length - 1);
3444 ibp += (length - 1);
3448 if (put_out_comments)
3454 else if (ibp[0] == '\\' && ibp[1] == '\n') {
3461 /* It isn't a macro call.
3462 Put back the space that we just skipped. */
3465 ip->lineno = old_iln;
3466 op->lineno = old_oln;
3467 /* Exit the for loop. */
3472 /* This is now known to be a macro call.
3473 Discard the macro name from the output,
3474 along with any following whitespace just copied,
3475 but preserve newlines if not outputting marks since this
3476 is more likely to do the right thing with line numbers. */
3477 obp = op->buf + obufp_before_macroname;
3479 op->lineno = op_lineno_before_macroname;
3481 int newlines = op->lineno - op_lineno_before_macroname;
3482 while (0 < newlines--)
3486 /* Prevent accidental token-pasting with a character
3487 before the macro call. */
3488 if (!traditional && obp != op->buf) {
3490 case '!': case '%': case '&': case '*':
3491 case '+': case '-': case '.': case '/':
3492 case ':': case '<': case '=': case '>':
3494 /* If we are expanding a macro arg, make a newline marker
3495 to separate the tokens. If we are making real output,
3496 a plain space will do. */
3503 /* Expand the macro, reading arguments as needed,
3504 and push the expansion on the input stack. */
3507 macroexpand (hp, op);
3509 /* Reexamine input stack, since macroexpand has pushed
3510 a new level on it. */
3517 } /* End hash-table-search loop */
3519 ident_length = hash = 0; /* Stop collecting identifier */
3522 } /* End if (ident_length > 0) */
3524 } /* End per-char loop */
3526 /* Come here to return -- but first give an error message
3527 if there was an unterminated successful conditional. */
3529 if (if_stack != ip->if_stack)
3533 switch (if_stack->type)
3554 error_with_line (line_for_error (if_stack->lineno),
3555 "unterminated `#%s' conditional", str);
3557 if_stack = ip->if_stack;
3561 * Rescan a string into a temporary buffer and return the result
3562 * as a FILE_BUF. Note this function returns a struct, not a pointer.
3564 * OUTPUT_MARKS nonzero means keep Newline markers found in the input
3565 * and insert such markers when appropriate. See `rescan' for details.
3566 * OUTPUT_MARKS is 1 for macroexpanding a macro argument separately
3567 * before substitution; it is 0 for other uses.
3570 expand_to_temp_buffer (buf, limit, output_marks, assertions)
3571 U_CHAR *buf, *limit;
3572 int output_marks, assertions;
3574 register FILE_BUF *ip;
3576 int length = limit - buf;
3578 int odepth = indepth;
3579 int save_assertions_flag = assertions_flag;
3581 assertions_flag = assertions;
3586 /* Set up the input on the input stack. */
3588 buf1 = (U_CHAR *) alloca (length + 1);
3590 register U_CHAR *p1 = buf;
3591 register U_CHAR *p2 = buf1;
3598 /* Set up to receive the output. */
3600 obuf.length = length * 2 + 100; /* Usually enough. Why be stingy? */
3601 obuf.bufp = obuf.buf = (U_CHAR *) xmalloc (obuf.length);
3602 obuf.nominal_fname = 0;
3609 obuf.system_header_p = 0;
3611 CHECK_DEPTH ({return obuf;});
3615 ip = &instack[indepth];
3617 ip->nominal_fname = 0;
3618 ip->nominal_fname_len = 0;
3620 ip->system_header_p = 0;
3623 ip->length = length;
3624 ip->buf = ip->bufp = buf1;
3625 ip->if_stack = if_stack;
3627 ip->lineno = obuf.lineno = 1;
3629 /* Scan the input, create the output. */
3630 rescan (&obuf, output_marks);
3632 /* Pop input stack to original state. */
3635 if (indepth != odepth)
3638 /* Record the output. */
3639 obuf.length = obuf.bufp - obuf.buf;
3641 assertions_flag = save_assertions_flag;
3646 * Process a # directive. Expects IP->bufp to point after the '#', as in
3647 * `#define foo bar'. Passes to the directive handler
3648 * (do_define, do_include, etc.): the addresses of the 1st and
3649 * last chars of the directive (starting immediately after the #
3650 * keyword), plus op and the keyword table pointer. If the directive
3651 * contains comments it is copied into a temporary buffer sans comments
3652 * and the temporary buffer is passed to the directive handler instead.
3653 * Likewise for backslash-newlines.
3655 * Returns nonzero if this was a known # directive.
3656 * Otherwise, returns zero, without advancing the input pointer.
3660 handle_directive (ip, op)
3663 register U_CHAR *bp, *cp;
3664 register struct directive *kt;
3665 register int ident_length;
3668 /* Nonzero means we must copy the entire directive
3669 to get rid of comments or backslash-newlines. */
3670 int copy_directive = 0;
3672 U_CHAR *ident, *after_ident;
3676 /* Record where the directive started. do_xifdef needs this. */
3677 directive_start = bp - 1;
3679 ignore_escape_flag = 1;
3681 /* Skip whitespace and \-newline. */
3683 if (is_hor_space[*bp]) {
3684 if (*bp != ' ' && *bp != '\t' && pedantic)
3685 pedwarn_strange_white_space (*bp);
3687 } else if (*bp == '/') {
3688 if (bp[1] == '\\' && bp[2] == '\n')
3689 newline_fix (bp + 1);
3690 if (! (bp[1] == '*' || (cplusplus_comments && bp[1] == '/')))
3693 skip_to_end_of_comment (ip, &ip->lineno, 0);
3695 } else if (*bp == '\\' && bp[1] == '\n') {
3696 bp += 2; ip->lineno++;
3700 /* Now find end of directive name.
3701 If we encounter a backslash-newline, exchange it with any following
3702 symbol-constituents so that we end up with a contiguous name. */
3709 if (*cp == '\\' && cp[1] == '\n')
3710 name_newline_fix (cp);
3716 ident_length = cp - bp;
3720 /* A line of just `#' becomes blank. */
3722 if (ident_length == 0 && *after_ident == '\n') {
3723 ip->bufp = after_ident;
3727 if (ident_length == 0 || !is_idstart[*ident]) {
3729 while (is_idchar[*p]) {
3730 if (*p < '0' || *p > '9')
3734 /* Handle # followed by a line number. */
3735 if (p != ident && !is_idchar[*p]) {
3736 static struct directive line_directive_table[] = {
3737 { 4, do_line, "line", T_LINE},
3740 pedwarn ("`#' followed by integer");
3741 after_ident = ident;
3742 kt = line_directive_table;
3743 ignore_escape_flag = 0;
3747 /* Avoid error for `###' and similar cases unless -pedantic. */
3749 while (*p == '#' || is_hor_space[*p]) p++;
3751 if (pedantic && !lang_asm)
3752 warning ("invalid preprocessing directive");
3758 error ("invalid preprocessing directive name");
3764 * Decode the keyword and call the appropriate expansion
3765 * routine, after moving the input pointer up to the next line.
3767 for (kt = directive_table; kt->length > 0; kt++) {
3768 if (kt->length == ident_length && !bcmp (kt->name, ident, ident_length)) {
3769 register U_CHAR *buf;
3770 register U_CHAR *limit;
3773 int *already_output;
3775 /* Nonzero means do not delete comments within the directive.
3776 #define needs this when -traditional. */
3781 limit = ip->buf + ip->length;
3784 keep_comments = traditional && kt->type == T_DEFINE;
3785 /* #import is defined only in Objective C, or when on the NeXT. */
3786 if (kt->type == T_IMPORT
3787 && !(objc || lookup ((U_CHAR *) "__NeXT__", -1, -1)))
3790 /* Find the end of this directive (first newline not backslashed
3791 and not in a string or comment).
3792 Set COPY_DIRECTIVE if the directive must be copied
3793 (it contains a backslash-newline or a comment). */
3795 buf = bp = after_ident;
3796 while (bp < limit) {
3797 register U_CHAR c = *bp++;
3805 } else if (traditional)
3811 /* "..." is special for #include. */
3812 if (IS_INCLUDE_DIRECTIVE_TYPE (kt->type)) {
3813 while (bp < limit && *bp != '\n') {
3818 if (*bp == '\\' && bp[1] == '\n') {
3829 bp = skip_quoted_string (bp - 1, limit, ip->lineno, &ip->lineno, ©_directive, &unterminated);
3830 /* Don't bother calling the directive if we already got an error
3831 message due to unterminated string. Skip everything and pretend
3832 we called the directive. */
3835 /* Traditional preprocessing permits unterminated strings. */
3844 /* <...> is special for #include. */
3846 if (! IS_INCLUDE_DIRECTIVE_TYPE (kt->type))
3848 while (bp < limit && *bp != '>' && *bp != '\n') {
3849 if (*bp == '\\' && bp[1] == '\n') {
3859 if (*bp == '\\' && bp[1] == '\n')
3862 || (cplusplus_comments && *bp == '/')) {
3863 U_CHAR *obp = bp - 1;
3865 skip_to_end_of_comment (ip, &ip->lineno, 0);
3867 /* No need to copy the directive because of a comment at the end;
3868 just don't include the comment in the directive. */
3869 if (!put_out_comments) {
3871 for (p = bp; *p == ' ' || *p == '\t'; p++)
3878 /* Don't remove the comments if -traditional. */
3879 if (! keep_comments)
3888 pedwarn_strange_white_space (c);
3892 --bp; /* Point to the newline */
3900 resume_p = ip->bufp;
3901 /* BP is the end of the directive.
3902 RESUME_P is the next interesting data after the directive.
3903 A comment may come between. */
3905 /* If a directive should be copied through, and -C was given,
3906 pass it through before removing comments. */
3907 if (!no_output && put_out_comments
3908 && ((kt->type == T_DEFINE || kt->type == T_UNDEF)
3909 ? dump_macros == dump_definitions
3910 : IS_INCLUDE_DIRECTIVE_TYPE (kt->type) ? dump_includes
3911 : kt->type == T_PRAGMA)) {
3914 /* Output directive name. */
3915 check_expand (op, kt->length + 2);
3916 /* Make sure # is at the start of a line */
3917 if (op->bufp > op->buf && op->bufp[-1] != '\n') {
3922 bcopy (kt->name, op->bufp, kt->length);
3923 op->bufp += kt->length;
3925 /* Output arguments. */
3927 check_expand (op, len);
3928 bcopy (buf, (char *) op->bufp, len);
3930 /* Take account of any (escaped) newlines just output. */
3932 if (buf[len] == '\n')
3935 already_output = &junk;
3936 } /* Don't we need a newline or #line? */
3938 if (copy_directive) {
3939 register U_CHAR *xp = buf;
3940 /* Need to copy entire directive into temp buffer before dispatching */
3942 cp = (U_CHAR *) alloca (bp - buf + 5); /* room for directive plus
3946 /* Copy to the new buffer, deleting comments
3947 and backslash-newlines (and whitespace surrounding the latter). */
3950 register U_CHAR c = *xp++;
3955 abort (); /* A bare newline should never part of the line. */
3958 /* <...> is special for #include. */
3960 if (! IS_INCLUDE_DIRECTIVE_TYPE (kt->type))
3962 while (xp < bp && c != '>') {
3964 if (c == '\\' && xp < bp && *xp == '\n')
3975 if (cp != buf && is_hor_space[cp[-1]]) {
3976 while (cp - 1 != buf && is_hor_space[cp[-2]])
3978 SKIP_WHITE_SPACE (xp);
3979 } else if (is_hor_space[*xp]) {
3981 SKIP_WHITE_SPACE (xp);
3983 } else if (traditional && xp < bp) {
3991 int backslash_newlines_p = 0;
3993 register U_CHAR *bp1
3994 = skip_quoted_string (xp - 1, bp, ip->lineno,
3995 NULL_PTR, &backslash_newlines_p,
3997 if (backslash_newlines_p)
4000 /* With something like:
4005 we should still remove the backslash-newline
4006 pair as part of phase two. */
4007 if (xp[0] == '\\' && xp[1] == '\n')
4013 /* This is the same as the loop above, but taking
4014 advantage of the fact that we know there are no
4015 backslash-newline pairs. */
4023 || (cplusplus_comments && *xp == '/')) {
4025 /* If we already copied the directive through,
4026 already_output != 0 prevents outputting comment now. */
4027 skip_to_end_of_comment (ip, already_output, 0);
4029 while (xp != ip->bufp)
4031 /* Delete or replace the slash. */
4032 else if (traditional)
4041 /* Null-terminate the copy. */
4047 ip->bufp = resume_p;
4049 /* Some directives should be written out for cc1 to process,
4050 just as if they were not defined. And sometimes we're copying
4051 directives through. */
4053 if (!no_output && already_output == 0
4054 && (kt->type == T_DEFINE ? (int) dump_names <= (int) dump_macros
4055 : IS_INCLUDE_DIRECTIVE_TYPE (kt->type) ? dump_includes
4056 : kt->type == T_PRAGMA)) {
4059 /* Output directive name. */
4060 check_expand (op, kt->length + 1);
4062 bcopy (kt->name, (char *) op->bufp, kt->length);
4063 op->bufp += kt->length;
4065 if (kt->type == T_DEFINE && dump_macros == dump_names) {
4066 /* Output `#define name' only. */
4069 SKIP_WHITE_SPACE (xp);
4071 while (is_idchar[*xp]) xp++;
4073 check_expand (op, len + 1);
4075 bcopy (yp, (char *) op->bufp, len);
4077 /* Output entire directive. */
4079 check_expand (op, len);
4080 bcopy (buf, (char *) op->bufp, len);
4083 } /* Don't we need a newline or #line? */
4085 /* Call the appropriate directive handler. buf now points to
4086 either the appropriate place in the input buffer, or to
4087 the temp buffer if it was necessary to make one. cp
4088 points to the first char after the contents of the (possibly
4089 copied) directive, in either case. */
4090 (*kt->func) (buf, cp, op, kt);
4091 check_expand (op, ip->length - (ip->bufp - ip->buf));
4097 /* It is deliberate that we don't warn about undefined directives.
4098 That is the responsibility of cc1. */
4105 static struct tm *timebuf;
4107 time_t t = time ((time_t *) 0);
4108 timebuf = localtime (&t);
4113 static char *monthnames[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
4114 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
4118 * expand things like __FILE__. Place the expansion into the output
4119 * buffer *without* rescanning.
4123 special_symbol (hp, op)
4130 FILE_BUF *ip = NULL;
4133 int paren = 0; /* For special `defined' keyword */
4135 if (pcp_outfile && pcp_inside_if
4136 && hp->type != T_SPEC_DEFINED && hp->type != T_CONST)
4137 error ("Predefined macro `%s' used inside `#if' during precompilation",
4140 for (i = indepth; i >= 0; i--)
4141 if (instack[i].fname != NULL) {
4146 error ("cccp error: not in any file?!");
4147 return; /* the show must go on */
4154 FILE_BUF *p = hp->type == T_FILE ? ip : &instack[0];
4155 char *string = p->nominal_fname;
4159 size_t string_len = p->nominal_fname_len;
4160 buf = (char *) alloca (3 + 4 * string_len);
4161 quote_string (buf, string, string_len);
4169 case T_INCLUDE_LEVEL:
4171 for (i = indepth; i >= 0; i--)
4172 if (instack[i].fname != NULL)
4175 buf = (char *) alloca (8); /* Eight bytes ought to be more than enough */
4176 sprintf (buf, "%d", true_indepth - 1);
4180 buf = (char *) alloca (3 + strlen (version_string));
4181 sprintf (buf, "\"%s\"", version_string);
4184 #ifndef NO_BUILTIN_SIZE_TYPE
4190 #ifndef NO_BUILTIN_PTRDIFF_TYPE
4191 case T_PTRDIFF_TYPE:
4200 case T_USER_LABEL_PREFIX_TYPE:
4201 buf = user_label_prefix;
4204 case T_REGISTER_PREFIX_TYPE:
4205 buf = REGISTER_PREFIX;
4208 case T_IMMEDIATE_PREFIX_TYPE:
4209 buf = IMMEDIATE_PREFIX;
4213 buf = hp->value.cpval;
4214 #ifdef STDC_0_IN_SYSTEM_HEADERS
4215 if (ip->system_header_p
4216 && hp->length == 8 && bcmp (hp->name, "__STDC__", 8) == 0
4217 && !lookup ((U_CHAR *) "__STRICT_ANSI__", -1, -1))
4220 if (pcp_inside_if && pcp_outfile)
4221 /* Output a precondition for this macro use */
4222 fprintf (pcp_outfile, "#define %s %s\n", hp->name, buf);
4226 buf = (char *) alloca (10);
4227 sprintf (buf, "%d", ip->lineno);
4232 buf = (char *) alloca (20);
4233 timebuf = timestamp ();
4234 if (hp->type == T_DATE)
4235 sprintf (buf, "\"%s %2d %4d\"", monthnames[timebuf->tm_mon],
4236 timebuf->tm_mday, timebuf->tm_year + 1900);
4238 sprintf (buf, "\"%02d:%02d:%02d\"", timebuf->tm_hour, timebuf->tm_min,
4242 case T_SPEC_DEFINED:
4243 buf = " 0 "; /* Assume symbol is not defined */
4244 ip = &instack[indepth];
4245 SKIP_WHITE_SPACE (ip->bufp);
4246 if (*ip->bufp == '(') {
4248 ip->bufp++; /* Skip over the paren */
4249 SKIP_WHITE_SPACE (ip->bufp);
4252 if (!is_idstart[*ip->bufp])
4254 if (ip->bufp[0] == 'L' && (ip->bufp[1] == '\'' || ip->bufp[1] == '"'))
4256 if ((hp = lookup (ip->bufp, -1, -1))) {
4257 if (pcp_outfile && pcp_inside_if
4258 && (hp->type == T_CONST
4259 || (hp->type == T_MACRO && hp->value.defn->predefined)))
4260 /* Output a precondition for this macro use. */
4261 fprintf (pcp_outfile, "#define %s\n", hp->name);
4265 if (pcp_outfile && pcp_inside_if) {
4266 /* Output a precondition for this macro use */
4267 U_CHAR *cp = ip->bufp;
4268 fprintf (pcp_outfile, "#undef ");
4269 while (is_idchar[*cp]) /* Ick! */
4270 fputc (*cp++, pcp_outfile);
4271 putc ('\n', pcp_outfile);
4273 while (is_idchar[*ip->bufp])
4275 SKIP_WHITE_SPACE (ip->bufp);
4277 if (*ip->bufp != ')')
4285 error ("`defined' without an identifier");
4289 error ("cccp error: invalid special hash type"); /* time for gdb */
4293 check_expand (op, len);
4294 bcopy (buf, (char *) op->bufp, len);
4301 /* Routines to handle #directives */
4303 /* Handle #include and #import.
4304 This function expects to see "fname" or <fname> on the input. */
4307 do_include (buf, limit, op, keyword)
4308 U_CHAR *buf, *limit;
4310 struct directive *keyword;
4312 U_CHAR *importing = keyword->type == T_IMPORT ? (U_CHAR *) "" : (U_CHAR *) 0;
4313 int skip_dirs = (keyword->type == T_INCLUDE_NEXT);
4314 static int import_warning = 0;
4315 char *fname; /* Dynamically allocated fname buffer */
4318 char *fbeg, *fend; /* Beginning and end of fname */
4321 struct file_name_list *search_start = include; /* Chain of dirs to search */
4322 struct file_name_list *dsp; /* First in chain, if #include "..." */
4323 struct file_name_list *searchptr = 0;
4326 int f = -3; /* file number */
4327 struct include_file *inc = 0;
4329 int retried = 0; /* Have already tried macro
4330 expanding the include line*/
4331 int angle_brackets = 0; /* 0 for "...", 1 for <...> */
4333 int vaxc_include = 0; /* 1 for token without punctuation */
4340 if (pedantic && !instack[indepth].system_header_p)
4343 pedwarn ("ANSI C does not allow `#import'");
4345 pedwarn ("ANSI C does not allow `#include_next'");
4348 if (importing && warn_import && !inhibit_warnings
4349 && !instack[indepth].system_header_p && !import_warning) {
4351 warning ("using `#import' is not recommended");
4352 notice ("The fact that a certain header file need not be processed more than once\n\
4353 should be indicated in the header file, not where it is used.\n\
4354 The best way to do this is with a conditional of this form:\n\
4356 #ifndef _FOO_H_INCLUDED\n\
4357 #define _FOO_H_INCLUDED\n\
4358 ... <real contents of file> ...\n\
4359 #endif /* Not _FOO_H_INCLUDED */\n\
4361 Then users can use `#include' any number of times.\n\
4362 GNU C automatically avoids processing the file more than once\n\
4363 when it is equipped with such a conditional.\n");
4369 SKIP_WHITE_SPACE (fin);
4370 /* Discard trailing whitespace so we can easily see
4371 if we have parsed all the significant chars we were given. */
4372 while (limit != fin && is_hor_space[limit[-1]]) limit--;
4373 fbeg = fend = (char *) alloca (limit - fin);
4379 /* Copy the operand text, concatenating the strings. */
4384 goto invalid_include_file_name;
4392 /* If not at the end, there had better be another string. */
4393 /* Skip just horiz space, and don't go past limit. */
4394 while (fin != limit && is_hor_space[*fin]) fin++;
4395 if (fin != limit && *fin == '\"')
4402 /* We have "filename". Figure out directory this source
4403 file is coming from and put it on the front of the list. */
4405 /* If -I- was specified, don't search current dir, only spec'd ones. */
4406 if (ignore_srcdir) break;
4408 for (fp = &instack[indepth]; fp >= instack; fp--)
4413 if ((nam = fp->nominal_fname) != NULL) {
4414 /* Found a named file. Figure out dir of the file,
4415 and put it in front of the search list. */
4416 dsp = ((struct file_name_list *)
4417 alloca (sizeof (struct file_name_list)
4418 + fp->nominal_fname_len));
4419 strcpy (dsp->fname, nam);
4420 simplify_filename (dsp->fname);
4421 nam = base_name (dsp->fname);
4424 /* for hack_vms_include_specification(), a local
4425 dir specification must start with "./" on VMS. */
4426 if (nam == dsp->fname)
4433 /* But for efficiency's sake, do not insert the dir
4434 if it matches the search list's first dir. */
4435 dsp->next = search_start;
4436 if (!search_start || strcmp (dsp->fname, search_start->fname)) {
4438 n = nam - dsp->fname;
4439 if (n + INCLUDE_LEN_FUDGE > max_include_len)
4440 max_include_len = n + INCLUDE_LEN_FUDGE;
4442 dsp[0].got_name_map = 0;
4450 while (fin != limit && *fin != '>')
4452 if (*fin == '>' && fin + 1 == limit) {
4454 /* If -I-, start with the first -I dir after the -I-. */
4455 search_start = first_bracket_include;
4463 * Support '#include xyz' like VAX-C to allow for easy use of all the
4464 * decwindow include files. It defaults to '#include <xyz.h>' (so the
4465 * code from case '<' is repeated here) and generates a warning.
4466 * (Note: macro expansion of `xyz' takes precedence.)
4468 /* Note: The argument of ISALPHA() can be evaluated twice, so do
4469 the pre-decrement outside of the macro. */
4470 if (retried && (--fin, ISALPHA(*(U_CHAR *) (fin)))) {
4471 while (fin != limit && (!ISSPACE(*fin)))
4473 warning ("VAX-C-style include specification found, use '#include <filename.h>' !");
4477 /* If -I-, start with the first -I dir after the -I-. */
4478 search_start = first_bracket_include;
4486 /* Expand buffer and then remove any newline markers.
4487 We can't just tell expand_to_temp_buffer to omit the markers,
4488 since it would put extra spaces in include file names. */
4491 int errors_before_expansion = errors;
4492 trybuf = expand_to_temp_buffer (buf, limit, 1, 0);
4493 if (errors != errors_before_expansion) {
4495 goto invalid_include_file_name;
4498 buf = (U_CHAR *) alloca (trybuf.bufp - trybuf.buf + 1);
4500 while (src != trybuf.bufp) {
4501 switch ((*limit++ = *src++)) {
4510 U_CHAR *src1 = skip_quoted_string (src - 1, trybuf.bufp, 0,
4511 NULL_PTR, NULL_PTR, NULL_PTR);
4524 invalid_include_file_name:
4525 error ("`#%s' expects \"FILENAME\" or <FILENAME>", keyword->name);
4529 /* For #include_next, skip in the search path
4530 past the dir in which the containing file was found. */
4533 for (fp = &instack[indepth]; fp >= instack; fp--)
4534 if (fp->fname != NULL) {
4535 /* fp->dir is null if the containing file was specified
4536 with an absolute file name. In that case, don't skip anything. */
4538 search_start = fp->dir->next;
4544 flen = simplify_filename (fbeg);
4548 error ("empty file name in `#%s'", keyword->name);
4552 /* Allocate this permanently, because it gets stored in the definitions
4554 fname = xmalloc (max_include_len + flen + 1);
4555 /* + 1 above for terminating null. */
4557 system_include_depth += angle_brackets;
4559 /* If specified file name is absolute, just open it. */
4561 if (absolute_filename (fbeg)) {
4562 strcpy (fname, fbeg);
4563 f = open_include_file (fname, NULL_PTR, importing, &inc);
4567 struct bypass_dir *next;
4569 struct file_name_list *searchptr;
4570 } **bypass_slot = 0;
4572 /* Search directory path, trying to open the file.
4573 Copy each filename tried into FNAME. */
4575 for (searchptr = search_start; searchptr; searchptr = searchptr->next) {
4577 if (searchptr == first_bracket_include) {
4578 /* Go to bypass directory if we know we've seen this file before. */
4579 static struct bypass_dir *bypass_hashtab[INCLUDE_HASHSIZE];
4580 struct bypass_dir *p;
4581 bypass_slot = &bypass_hashtab[hashf ((U_CHAR *) fbeg, flen,
4583 for (p = *bypass_slot; p; p = p->next)
4584 if (!strcmp (fbeg, p->fname)) {
4585 searchptr = p->searchptr;
4592 /* Change this 1/2 Unix 1/2 VMS file specification into a
4593 full VMS file specification */
4594 if (searchptr->fname[0])
4596 strcpy (fname, searchptr->fname);
4597 if (fname[strlen (fname) - 1] == ':')
4600 slashp = strchr (fbeg, '/');
4602 /* start at root-dir of logical device if no path given. */
4604 strcat (fname, "[000000]");
4606 strcat (fname, fbeg);
4608 /* Fix up the filename */
4609 hack_vms_include_specification (fname, vaxc_include);
4613 /* This is a normal VMS filespec, so use it unchanged. */
4614 strcpy (fname, fbeg);
4615 /* if it's '#include filename', add the missing .h */
4616 if (vaxc_include && index(fname,'.')==NULL)
4617 strcat (fname, ".h");
4620 strcpy (fname, searchptr->fname);
4621 strcat (fname, fbeg);
4623 f = open_include_file (fname, searchptr, importing, &inc);
4625 if (bypass_slot && searchptr != first_bracket_include) {
4626 /* This is the first time we found this include file,
4627 and we found it after first_bracket_include.
4628 Record its location so that we can bypass to here next time. */
4629 struct bypass_dir *p
4630 = (struct bypass_dir *) xmalloc (sizeof (struct bypass_dir));
4631 p->next = *bypass_slot;
4632 p->fname = fname + strlen (searchptr->fname);
4633 p->searchptr = searchptr;
4639 /* Our VMS hacks can produce invalid filespecs, so don't worry
4640 about errors other than EACCES. */
4641 if (errno == EACCES)
4644 if (errno != ENOENT && errno != ENOTDIR)
4654 /* The file was already included. */
4656 /* If generating dependencies and -MG was specified, we assume missing
4657 files are leaf files, living in the same directory as the source file
4658 or other similar place; these missing files may be generated from
4659 other files and may not exist yet (eg: y.tab.h). */
4660 } else if (print_deps_missing_files
4661 && (system_include_depth != 0) < print_deps)
4663 /* If it was requested as a system header file,
4664 then assume it belongs in the first place to look for such. */
4668 char *p = (char *) alloca (strlen (search_start->fname)
4669 + strlen (fbeg) + 1);
4670 strcpy (p, search_start->fname);
4672 deps_output (p, ' ');
4677 /* Otherwise, omit the directory, as if the file existed
4678 in the directory with the source. */
4679 deps_output (fbeg, ' ');
4682 /* If -M was specified, and this header file won't be added to the
4683 dependency list, then don't count this as an error, because we can
4684 still produce correct output. Otherwise, we can't produce correct
4685 output, because there may be dependencies we need inside the missing
4686 file, and we don't know what directory this missing file exists in. */
4687 else if (0 < print_deps && print_deps <= (system_include_depth != 0))
4688 warning ("No include path in which to find %s", fbeg);
4690 error_from_errno (fbeg);
4692 error ("No include path in which to find %s", fbeg);
4696 /* Actually process the file. */
4698 pcftry = (char *) alloca (strlen (fname) + 30);
4705 sprintf (pcftry, "%s%d", fname, pcfnum++);
4707 pcf = open (pcftry, O_RDONLY, 0666);
4712 if (fstat (pcf, &s) != 0)
4713 pfatal_with_name (pcftry);
4714 if (! INO_T_EQ (inc->st.st_ino, s.st_ino)
4715 || inc->st.st_dev != s.st_dev)
4717 pcfbuf = check_precompiled (pcf, &s, fname, &pcfbuflimit);
4718 /* Don't need it any more. */
4723 /* Don't need it at all. */
4728 } while (pcf != -1 && !pcfbuf);
4731 /* Actually process the file */
4733 pcfname = xmalloc (strlen (pcftry) + 1);
4734 strcpy (pcfname, pcftry);
4735 pcfinclude ((U_CHAR *) pcfbuf, (U_CHAR *) fname, op);
4738 finclude (f, inc, op, is_system_include (fname), searchptr);
4741 system_include_depth -= angle_brackets;
4746 /* Return nonzero if the given FILENAME is an absolute pathname which
4747 designates a file within one of the known "system" include file
4748 directories. We assume here that if the given FILENAME looks like
4749 it is the name of a file which resides either directly in a "system"
4750 include file directory, or within any subdirectory thereof, then the
4751 given file must be a "system" include file. This function tells us
4752 if we should suppress pedantic errors/warnings for the given FILENAME.
4754 The value is 2 if the file is a C-language system header file
4755 for which C++ should (on most systems) assume `extern "C"'. */
4758 is_system_include (filename)
4759 register char *filename;
4761 #ifndef FREEBSD_NATIVE
4762 struct file_name_list *searchptr;
4764 for (searchptr = first_system_include; searchptr;
4765 searchptr = searchptr->next)
4766 if (! strncmp (searchptr->fname, filename, strlen (searchptr->fname)))
4767 return searchptr->c_system_include_path + 1;
4772 /* Yield the non-directory suffix of a file name. */
4780 #if defined (__MSDOS__) || defined (_WIN32)
4781 if (ISALPHA (s[0]) && s[1] == ':') s += 2;
4784 if ((p = rindex (s, ':'))) s = p + 1; /* Skip device. */
4785 if ((p = rindex (s, ']'))) s = p + 1; /* Skip directory. */
4786 if ((p = rindex (s, '>'))) s = p + 1; /* Skip alternate (int'n'l) dir. */
4790 if ((p = rindex (s, '/'))) s = p + 1;
4791 #ifdef DIR_SEPARATOR
4792 if ((p = rindex (s, DIR_SEPARATOR))) s = p + 1;
4797 /* Yield nonzero if FILENAME is absolute (i.e. not relative). */
4800 absolute_filename (filename)
4803 #if defined (__MSDOS__) \
4804 || (defined (_WIN32) && !defined (__CYGWIN__) && !defined (_UWIN))
4805 if (ISALPHA (filename[0]) && filename[1] == ':') filename += 2;
4807 #if defined (__CYGWIN__)
4808 /* At present, any path that begins with a drive spec is absolute. */
4809 if (ISALPHA (filename[0]) && filename[1] == ':') return 1;
4812 if (index (filename, ':') != 0) return 1;
4814 if (filename[0] == '/') return 1;
4815 #ifdef DIR_SEPARATOR
4816 if (filename[0] == DIR_SEPARATOR) return 1;
4821 /* Returns whether or not a given character is a directory separator.
4822 Used by simplify_filename. */
4825 is_dir_separator(ch)
4828 return (ch == DIR_SEPARATOR)
4829 #if defined (DIR_SEPARATOR_2)
4830 || (ch == DIR_SEPARATOR_2)
4835 /* Remove unnecessary characters from FILENAME in place,
4836 to avoid unnecessary filename aliasing.
4837 Return the length of the resulting string.
4839 Do only the simplifications allowed by Posix.
4840 It is OK to miss simplifications on non-Posix hosts,
4841 since this merely leads to suboptimal results. */
4844 simplify_filename (filename)
4847 register char *from = filename;
4848 register char *to = filename;
4851 /* Remove redundant initial /s. */
4852 if (is_dir_separator (*from))
4854 *to++ = DIR_SEPARATOR;
4855 if (is_dir_separator (*++from))
4857 if (is_dir_separator (*++from))
4859 /* 3 or more initial /s are equivalent to 1 /. */
4860 while (is_dir_separator (*++from))
4865 /* On some hosts // differs from /; Posix allows this. */
4866 *to++ = DIR_SEPARATOR;
4876 if (from[0] == '.' && from[1] == '/')
4881 /* Copy this component and trailing DIR_SEPARATOR, if any. */
4882 while (!is_dir_separator (*to++ = *from++))
4886 /* Trim . component at end of nonempty name. */
4887 to -= filename <= to - 3 && to[-3] == DIR_SEPARATOR && to[-2] == '.';
4889 /* Trim unnecessary trailing /s. */
4890 while (to0 < --to && to[-1] == DIR_SEPARATOR)
4894 return to - filename;
4897 #if defined(DIR_SEPARATOR_2)
4898 /* Simplify to one directory separator. */
4899 to[-1] = DIR_SEPARATOR;
4903 /* Skip /s after a /. */
4904 while (is_dir_separator (*from))
4909 /* The file_name_map structure holds a mapping of file names for a
4910 particular directory. This mapping is read from the file named
4911 FILE_NAME_MAP_FILE in that directory. Such a file can be used to
4912 map filenames on a file system with severe filename restrictions,
4913 such as DOS. The format of the file name map file is just a series
4914 of lines with two tokens on each line. The first token is the name
4915 to map, and the second token is the actual name to use. */
4917 struct file_name_map
4919 struct file_name_map *map_next;
4924 #define FILE_NAME_MAP_FILE "header.gcc"
4926 /* Read a space delimited string of unlimited length from a stdio
4930 read_filename_string (ch, f)
4938 set = alloc = xmalloc (len + 1);
4942 while ((ch = getc (f)) != EOF && ! is_space[ch])
4944 if (set - alloc == len)
4947 alloc = xrealloc (alloc, len + 1);
4948 set = alloc + len / 2;
4958 /* Read the file name map file for DIRNAME.
4959 If DIRNAME is empty, read the map file for the working directory;
4960 otherwise DIRNAME must end in '/'. */
4962 static struct file_name_map *
4963 read_name_map (dirname)
4966 /* This structure holds a linked list of file name maps, one per
4968 struct file_name_map_list
4970 struct file_name_map_list *map_list_next;
4971 char *map_list_name;
4972 struct file_name_map *map_list_map;
4974 static struct file_name_map_list *map_list;
4975 register struct file_name_map_list *map_list_ptr;
4980 for (map_list_ptr = map_list; map_list_ptr;
4981 map_list_ptr = map_list_ptr->map_list_next)
4982 if (! strcmp (map_list_ptr->map_list_name, dirname))
4983 return map_list_ptr->map_list_map;
4985 map_list_ptr = ((struct file_name_map_list *)
4986 xmalloc (sizeof (struct file_name_map_list)));
4987 map_list_ptr->map_list_name = xstrdup (dirname);
4988 map_list_ptr->map_list_map = NULL;
4990 dirlen = strlen (dirname);
4991 name = (char *) alloca (dirlen + strlen (FILE_NAME_MAP_FILE) + 1);
4992 strcpy (name, dirname);
4993 strcat (name, FILE_NAME_MAP_FILE);
4994 f = fopen (name, "r");
4996 map_list_ptr->map_list_map = NULL;
5001 while ((ch = getc (f)) != EOF)
5004 struct file_name_map *ptr;
5009 from = read_filename_string (ch, f);
5010 while ((ch = getc (f)) != EOF && is_hor_space[ch])
5012 to = read_filename_string (ch, f);
5014 simplify_filename (from);
5015 tolen = simplify_filename (to);
5017 ptr = ((struct file_name_map *)
5018 xmalloc (sizeof (struct file_name_map)));
5019 ptr->map_from = from;
5021 /* Make the real filename absolute. */
5022 if (absolute_filename (to))
5026 ptr->map_to = xmalloc (dirlen + tolen + 1);
5027 strcpy (ptr->map_to, dirname);
5028 strcat (ptr->map_to, to);
5032 ptr->map_next = map_list_ptr->map_list_map;
5033 map_list_ptr->map_list_map = ptr;
5035 while ((ch = getc (f)) != '\n')
5042 map_list_ptr->map_list_next = map_list;
5043 map_list = map_list_ptr;
5045 return map_list_ptr->map_list_map;
5048 /* Try to open include file FILENAME. SEARCHPTR is the directory
5049 being tried from the include file search path.
5050 IMPORTING is "" if we are importing, null otherwise.
5051 Return -2 if found, either a matching name or a matching inode.
5052 Otherwise, open the file and return a file descriptor if successful
5053 or -1 if unsuccessful.
5054 Unless unsuccessful, put a descriptor of the included file into *PINC.
5055 This function maps filenames on file systems based on information read by
5059 open_include_file (filename, searchptr, importing, pinc)
5061 struct file_name_list *searchptr;
5063 struct include_file **pinc;
5065 char *fname = remap ? remap_include_file (filename, searchptr) : filename;
5068 /* Look up FNAME in include_hashtab. */
5069 struct include_file **phead = &include_hashtab[hashf ((U_CHAR *) fname,
5072 struct include_file *inc, *head = *phead;
5073 for (inc = head; inc; inc = inc->next)
5074 if (!strcmp (fname, inc->fname))
5078 || ! inc->control_macro
5079 || (inc->control_macro[0] && ! lookup (inc->control_macro, -1, -1))) {
5081 fd = open (fname, O_RDONLY, 0);
5086 /* if #include <dir/file> fails, try again with hacked spec. */
5087 if (!hack_vms_include_specification (fname, 0))
5089 fd = open (fname, O_RDONLY, 0);
5096 /* FNAME was not in include_hashtab; insert a new entry. */
5097 inc = (struct include_file *) xmalloc (sizeof (struct include_file));
5100 inc->control_macro = 0;
5101 inc->deps_output = 0;
5102 if (fstat (fd, &inc->st) != 0)
5103 pfatal_with_name (fname);
5106 /* Look for another file with the same inode and device. */
5107 if (lookup_ino_include (inc)
5108 && inc->control_macro
5109 && (!inc->control_macro[0] || lookup (inc->control_macro, -1, -1))) {
5115 /* For -M, add this file to the dependencies. */
5116 if (! inc->deps_output && (system_include_depth != 0) < print_deps) {
5117 inc->deps_output = 1;
5118 deps_output (fname, ' ');
5121 /* Handle -H option. */
5122 if (print_include_names)
5123 fprintf (stderr, "%*s%s\n", indepth, "", fname);
5127 inc->control_macro = importing;
5133 /* Return the remapped name of the include file FILENAME.
5134 SEARCHPTR is the directory being tried from the include file path. */
5137 remap_include_file (filename, searchptr)
5139 struct file_name_list *searchptr;
5141 register struct file_name_map *map;
5142 register char *from;
5144 #ifndef FREEBSD_NATIVE
5147 if (! searchptr->got_name_map)
5149 searchptr->name_map = read_name_map (searchptr->fname);
5150 searchptr->got_name_map = 1;
5153 /* Check the mapping for the directory we are using. */
5154 from = filename + strlen (searchptr->fname);
5155 for (map = searchptr->name_map; map; map = map->map_next)
5156 if (! strcmp (map->map_from, from))
5161 from = base_name (filename);
5163 if (from != filename || !searchptr)
5165 /* Try to find a mapping file for the particular directory we are
5166 looking in. Thus #include <sys/types.h> will look up sys/types.h
5167 in /usr/include/header.gcc and look up types.h in
5168 /usr/include/sys/header.gcc. */
5170 char *dir = (char *) alloca (from - filename + 1);
5171 bcopy (filename, dir, from - filename);
5172 dir[from - filename] = '\0';
5174 #ifndef FREEBSD_NATIVE
5175 for (map = read_name_map (dir); map; map = map->map_next)
5176 if (! strcmp (map->map_from, from))
5184 /* Insert INC into the include file table, hashed by device and inode number.
5185 If a file with different name but same dev+ino was already in the table,
5186 return 1 and set INC's control macro to the already-known macro. */
5189 lookup_ino_include (inc)
5190 struct include_file *inc;
5192 int hash = ((unsigned) (inc->st.st_dev + INO_T_HASH (inc->st.st_ino))
5193 % INCLUDE_HASHSIZE);
5194 struct include_file *i = include_ino_hashtab[hash];
5196 include_ino_hashtab[hash] = inc;
5198 for (; i; i = i->next_ino)
5199 if (INO_T_EQ (inc->st.st_ino, i->st.st_ino)
5200 && inc->st.st_dev == i->st.st_dev) {
5201 inc->control_macro = i->control_macro;
5208 /* Process file descriptor F, which corresponds to include file INC,
5210 SYSTEM_HEADER_P is 1 if this file resides in any one of the known
5211 "system" include directories (as decided by the `is_system_include'
5213 DIRPTR is the link in the dir path through which this file was found,
5214 or 0 if the file name was absolute. */
5217 finclude (f, inc, op, system_header_p, dirptr)
5219 struct include_file *inc;
5221 int system_header_p;
5222 struct file_name_list *dirptr;
5224 char *fname = inc->fname;
5226 FILE_BUF *fp; /* For input stack frame */
5227 int missing_newline = 0;
5229 CHECK_DEPTH (return;);
5231 fp = &instack[indepth + 1];
5232 bzero ((char *) fp, sizeof (FILE_BUF));
5233 fp->nominal_fname = fp->fname = fname;
5234 fp->nominal_fname_len = strlen (fname);
5238 fp->if_stack = if_stack;
5239 fp->system_header_p = system_header_p;
5242 if (S_ISREG (inc->st.st_mode)) {
5243 size_t s = (size_t) inc->st.st_size;
5244 if (s != inc->st.st_size || s + 2 < s)
5246 fp->buf = (U_CHAR *) xmalloc (s + 2);
5249 /* Read the file contents, knowing that s is an upper bound
5250 on the number of bytes we can read. */
5251 fp->length = safe_read (f, (char *) fp->buf, s);
5252 if (fp->length < 0) goto nope;
5254 else if (S_ISDIR (inc->st.st_mode)) {
5255 error ("directory `%s' specified in #include", fname);
5259 /* Cannot count its file size before reading.
5260 First read the entire file into heap and
5261 copy them into buffer on stack. */
5266 fp->buf = (U_CHAR *) xmalloc (bsize + 2);
5269 i = safe_read (f, (char *) fp->buf + st_size, bsize - st_size);
5271 goto nope; /* error! */
5273 if (st_size != bsize)
5274 break; /* End of file */
5276 fp->buf = (U_CHAR *) xrealloc (fp->buf, bsize + 2);
5279 fp->length = st_size;
5282 if ((fp->length > 0 && fp->buf[fp->length - 1] != '\n')
5283 /* Backslash-newline at end is not good enough. */
5284 || (fp->length > 1 && fp->buf[fp->length - 2] == '\\')) {
5285 fp->buf[fp->length++] = '\n';
5286 missing_newline = 1;
5288 fp->buf[fp->length] = '\0';
5290 /* Close descriptor now, so nesting does not use lots of descriptors. */
5293 /* Must do this before calling trigraph_pcp, so that the correct file name
5294 will be printed in warning messages. */
5297 input_file_stack_tick++;
5302 output_line_directive (fp, op, 0, enter_file);
5305 if (missing_newline)
5308 if (pedantic && missing_newline)
5309 pedwarn ("file does not end in newline");
5312 input_file_stack_tick++;
5313 output_line_directive (&instack[indepth], op, 0, leave_file);
5319 perror_with_name (fname);
5324 /* Record that inclusion of the include file INC
5325 should be controlled by the macro named MACRO_NAME.
5326 This means that trying to include the file again
5327 will do something if that macro is defined. */
5330 record_control_macro (inc, macro_name)
5331 struct include_file *inc;
5334 if (!inc->control_macro || inc->control_macro[0])
5335 inc->control_macro = macro_name;
5338 /* Load the specified precompiled header into core, and verify its
5339 preconditions. PCF indicates the file descriptor to read, which must
5340 be a regular file. *ST is its file status.
5341 FNAME indicates the file name of the original header.
5342 *LIMIT will be set to an address one past the end of the file.
5343 If the preconditions of the file are not satisfied, the buffer is
5344 freed and we return 0. If the preconditions are satisfied, return
5345 the address of the buffer following the preconditions. The buffer, in
5346 this case, should never be freed because various pieces of it will
5347 be referred to until all precompiled strings are output at the end of
5351 check_precompiled (pcf, st, fname, limit)
5354 char *fname ATTRIBUTE_UNUSED;
5364 if (S_ISREG (st->st_mode))
5366 size_t s = (size_t) st->st_size;
5367 if (s != st->st_size || s + 2 < s)
5369 buf = xmalloc (s + 2);
5370 length = safe_read (pcf, buf, s);
5377 if (length > 0 && buf[length-1] != '\n')
5378 buf[length++] = '\n';
5381 *limit = buf + length;
5383 /* File is in core. Check the preconditions. */
5384 if (!check_preconditions (buf))
5386 for (cp = buf; *cp; cp++)
5389 fprintf (stderr, "Using preinclude %s\n", fname);
5395 fprintf (stderr, "Cannot use preinclude %s\n", fname);
5401 /* PREC (null terminated) points to the preconditions of a
5402 precompiled header. These are a series of #define and #undef
5403 lines which must match the current contents of the hash
5407 check_preconditions (prec)
5414 lineend = index (prec, '\n');
5416 if (*prec++ != '#') {
5417 error ("Bad format encountered while reading precompiled file");
5420 if (!strncmp (prec, "define", 6)) {
5424 mdef = create_definition ((U_CHAR *) prec, (U_CHAR *) lineend, NULL_PTR);
5429 if ((hp = lookup (mdef.symnam, mdef.symlen, -1)) == NULL
5430 || (hp->type != T_MACRO && hp->type != T_CONST)
5431 || (hp->type == T_MACRO
5432 && !compare_defs (mdef.defn, hp->value.defn)
5433 && (mdef.defn->length != 2
5434 || mdef.defn->expansion[0] != '\n'
5435 || mdef.defn->expansion[1] != ' ')))
5437 } else if (!strncmp (prec, "undef", 5)) {
5442 while (is_hor_space[(U_CHAR) *prec])
5445 while (is_idchar[(U_CHAR) *prec])
5449 if (lookup ((U_CHAR *) name, len, -1))
5452 error ("Bad format encountered while reading precompiled file");
5457 /* They all passed successfully */
5461 /* Process the main body of a precompiled file. BUF points to the
5462 string section of the file, following the preconditions. LIMIT is one
5463 character past the end. NAME is the name of the file being read
5464 in. OP is the main output buffer. */
5467 pcfinclude (buf, name, op)
5475 /* First in the file comes 4 bytes indicating the number of strings, */
5476 /* in network byte order. (MSB first). */
5478 nstrings = (nstrings << 8) | *cp++;
5479 nstrings = (nstrings << 8) | *cp++;
5480 nstrings = (nstrings << 8) | *cp++;
5482 /* Looping over each string... */
5483 while (nstrings--) {
5484 U_CHAR *string_start;
5485 U_CHAR *endofthiskey;
5489 /* Each string starts with a STRINGDEF structure (str), followed */
5490 /* by the text of the string (string_start) */
5492 /* First skip to a longword boundary */
5493 /* ??? Why a 4-byte boundary? On all machines? */
5494 /* NOTE: This works correctly even if size_t
5495 is narrower than a pointer.
5496 Do not try risky measures here to get another type to use!
5497 Do not include stddef.h--it will fail! */
5498 if ((size_t) cp & 3)
5499 cp += 4 - ((size_t) cp & 3);
5501 /* Now get the string. */
5502 str = (STRINGDEF *) (GENERIC_PTR) cp;
5503 string_start = cp += sizeof (STRINGDEF);
5505 for (; *cp; cp++) /* skip the string */
5508 /* We need to macro expand the string here to ensure that the
5509 proper definition environment is in place. If it were only
5510 expanded when we find out it is needed, macros necessary for
5511 its proper expansion might have had their definitions changed. */
5512 tmpbuf = expand_to_temp_buffer (string_start, cp++, 0, 0);
5513 /* Lineno is already set in the precompiled file */
5514 str->contents = tmpbuf.buf;
5515 str->len = tmpbuf.length;
5517 str->filename = name;
5518 str->output_mark = outbuf.bufp - outbuf.buf;
5521 *stringlist_tailp = str;
5522 stringlist_tailp = &str->chain;
5524 /* Next comes a fourbyte number indicating the number of keys
5527 nkeys = (nkeys << 8) | *cp++;
5528 nkeys = (nkeys << 8) | *cp++;
5529 nkeys = (nkeys << 8) | *cp++;
5531 /* If this number is -1, then the string is mandatory. */
5535 /* Otherwise, for each key, */
5536 for (; nkeys--; free (tmpbuf.buf), cp = endofthiskey + 1) {
5537 KEYDEF *kp = (KEYDEF *) (GENERIC_PTR) cp;
5540 /* It starts with a KEYDEF structure */
5541 cp += sizeof (KEYDEF);
5543 /* Find the end of the key. At the end of this for loop we
5544 advance CP to the start of the next key using this variable. */
5545 endofthiskey = cp + strlen ((char *) cp);
5548 /* Expand the key, and enter it into the hash table. */
5549 tmpbuf = expand_to_temp_buffer (cp, endofthiskey, 0, 0);
5550 tmpbuf.bufp = tmpbuf.buf;
5552 while (is_hor_space[*tmpbuf.bufp])
5554 if (!is_idstart[*tmpbuf.bufp]
5555 || tmpbuf.bufp == tmpbuf.buf + tmpbuf.length) {
5560 hp = lookup (tmpbuf.bufp, -1, -1);
5563 install (tmpbuf.bufp, -1, T_PCSTRING, (char *) kp, -1);
5565 else if (hp->type == T_PCSTRING) {
5566 kp->chain = hp->value.keydef;
5567 hp->value.keydef = kp;
5573 /* This output_line_directive serves to switch us back to the current
5574 input file in case some of these strings get output (which will
5575 result in line directives for the header file being output). */
5576 output_line_directive (&instack[indepth], op, 0, enter_file);
5579 /* Called from rescan when it hits a key for strings. Mark them all
5580 used and clean up. */
5588 for (kp = hp->value.keydef; kp; kp = kp->chain)
5589 kp->str->writeflag = 1;
5593 /* Write the output, interspersing precompiled strings in their
5594 appropriate places. */
5599 STRINGDEF *next_string;
5600 U_CHAR *cur_buf_loc;
5601 int line_directive_len = 80;
5602 char *line_directive = xmalloc (line_directive_len);
5605 /* In each run through the loop, either cur_buf_loc ==
5606 next_string_loc, in which case we print a series of strings, or
5607 it is less than next_string_loc, in which case we write some of
5609 cur_buf_loc = outbuf.buf;
5610 next_string = stringlist;
5612 while (cur_buf_loc < outbuf.bufp || next_string) {
5614 && cur_buf_loc - outbuf.buf == next_string->output_mark) {
5615 if (next_string->writeflag) {
5616 len = 4 * strlen ((char *) next_string->filename) + 32;
5617 while (len > line_directive_len)
5618 line_directive = xrealloc (line_directive,
5619 line_directive_len *= 2);
5620 sprintf (line_directive, "\n# %d ", next_string->lineno);
5621 strcpy (quote_string (line_directive + strlen (line_directive),
5622 (char *) next_string->filename,
5623 strlen ((char *) next_string->filename)),
5625 safe_write (fileno (stdout), line_directive, strlen (line_directive));
5626 safe_write (fileno (stdout),
5627 (char *) next_string->contents, next_string->len);
5629 next_string = next_string->chain;
5633 ? (next_string->output_mark
5634 - (cur_buf_loc - outbuf.buf))
5635 : outbuf.bufp - cur_buf_loc);
5637 safe_write (fileno (stdout), (char *) cur_buf_loc, len);
5641 free (line_directive);
5644 /* Pass a directive through to the output file.
5645 BUF points to the contents of the directive, as a contiguous string.
5646 LIMIT points to the first character past the end of the directive.
5647 KEYWORD is the keyword-table entry for the directive. */
5650 pass_thru_directive (buf, limit, op, keyword)
5651 U_CHAR *buf, *limit;
5653 struct directive *keyword;
5655 register int keyword_length = keyword->length;
5657 check_expand (op, 1 + keyword_length + (limit - buf));
5659 bcopy (keyword->name, (char *) op->bufp, keyword_length);
5660 op->bufp += keyword_length;
5661 if (limit != buf && buf[0] != ' ')
5663 bcopy ((char *) buf, (char *) op->bufp, limit - buf);
5664 op->bufp += (limit - buf);
5667 /* Count the line we have just made in the output,
5668 to get in sync properly. */
5673 /* The arglist structure is built by do_define to tell
5674 collect_definition where the argument names begin. That
5675 is, for a define like "#define f(x,y,z) foo+x-bar*y", the arglist
5676 would contain pointers to the strings x, y, and z.
5677 Collect_definition would then build a DEFINITION node,
5678 with reflist nodes pointing to the places x, y, and z had
5679 appeared. So the arglist is just convenience data passed
5680 between these two routines. It is not kept around after
5681 the current #define has been processed and entered into the
5685 struct arglist *next;
5692 /* Create a DEFINITION node from a #define directive. Arguments are
5693 as for do_define. */
5696 create_definition (buf, limit, op)
5697 U_CHAR *buf, *limit;
5700 U_CHAR *bp; /* temp ptr into input buffer */
5701 U_CHAR *symname; /* remember where symbol name starts */
5702 int sym_length; /* and how long it is */
5703 int line = instack[indepth].lineno;
5704 char *file = instack[indepth].nominal_fname;
5705 size_t file_len = instack[indepth].nominal_fname_len;
5709 int arglengths = 0; /* Accumulate lengths of arg names
5710 plus number of args. */
5715 while (is_hor_space[*bp])
5718 symname = bp; /* remember where it starts */
5719 sym_length = check_macro_name (bp, 0);
5722 /* Lossage will occur if identifiers or control keywords are broken
5723 across lines using backslash. This is not the right place to take
5727 struct arglist *arg_ptrs = NULL;
5730 bp++; /* skip '(' */
5731 SKIP_WHITE_SPACE (bp);
5733 /* Loop over macro argument names. */
5734 while (*bp != ')') {
5735 struct arglist *temp;
5737 temp = (struct arglist *) alloca (sizeof (struct arglist));
5739 temp->next = arg_ptrs;
5740 temp->argno = argno++;
5741 temp->rest_args = 0;
5745 pedwarn ("another parameter follows `%s'",
5748 if (!is_idstart[*bp])
5750 if (c9x && limit - bp > (long) REST_EXTENSION_LENGTH
5751 && bcmp (rest_extension, bp, REST_EXTENSION_LENGTH) == 0)
5753 /* This is the ISO C 9x way to write macros with variable
5754 number of arguments. */
5756 temp->rest_args = 1;
5759 pedwarn ("invalid character in macro parameter name");
5762 /* Find the end of the arg name. */
5763 while (is_idchar[*bp]) {
5765 /* do we have a "special" rest-args extension here? */
5766 if (limit - bp > (long) REST_EXTENSION_LENGTH
5767 && bcmp (rest_extension, bp, REST_EXTENSION_LENGTH) == 0) {
5768 if (pedantic && !instack[indepth].system_header_p)
5769 pedwarn ("ANSI C does not allow macro with variable arguments");
5771 temp->rest_args = 1;
5775 if (bp == temp->name && rest_args == 1)
5777 /* This is the ISO C 9x style. */
5778 temp->name = (U_CHAR *) va_args_name;
5779 temp->length = VA_ARGS_NAME_LENGTH;
5782 temp->length = bp - temp->name;
5784 bp += REST_EXTENSION_LENGTH;
5785 arglengths += temp->length + 2;
5786 SKIP_WHITE_SPACE (bp);
5787 if (temp->length == 0 || (*bp != ',' && *bp != ')')) {
5788 error ("badly punctuated parameter list in `#define'");
5793 SKIP_WHITE_SPACE (bp);
5794 /* A comma at this point can only be followed by an identifier. */
5795 if (!is_idstart[*bp]
5796 && !(c9x && limit - bp > (long) REST_EXTENSION_LENGTH
5797 && bcmp (rest_extension, bp, REST_EXTENSION_LENGTH) == 0)) {
5798 error ("badly punctuated parameter list in `#define'");
5803 error ("unterminated parameter list in `#define'");
5807 struct arglist *otemp;
5809 for (otemp = temp->next; otemp != NULL; otemp = otemp->next)
5810 if (temp->length == otemp->length
5811 && bcmp (temp->name, otemp->name, temp->length) == 0)
5813 error ("duplicate argument name `%.*s' in `#define'",
5814 temp->length, temp->name);
5817 if (rest_args == 0 && temp->length == VA_ARGS_NAME_LENGTH
5818 && bcmp (temp->name, va_args_name, VA_ARGS_NAME_LENGTH) == 0)
5821 reserved name `%s' used as argument name in `#define'", va_args_name);
5827 ++bp; /* skip paren */
5828 SKIP_WHITE_SPACE (bp);
5829 /* now everything from bp before limit is the definition. */
5830 defn = collect_expansion (bp, limit, argno, arg_ptrs);
5831 defn->rest_args = rest_args;
5833 /* Now set defn->args.argnames to the result of concatenating
5834 the argument names in reverse order
5835 with comma-space between them. */
5836 defn->args.argnames = (U_CHAR *) xmalloc (arglengths + 1);
5838 struct arglist *temp;
5840 for (temp = arg_ptrs; temp; temp = temp->next) {
5841 bcopy (temp->name, &defn->args.argnames[i], temp->length);
5843 if (temp->next != 0) {
5844 defn->args.argnames[i++] = ',';
5845 defn->args.argnames[i++] = ' ';
5848 defn->args.argnames[i] = 0;
5851 /* Simple expansion or empty definition. */
5855 if (is_hor_space[*bp]) {
5857 SKIP_WHITE_SPACE (bp);
5858 } else if (sym_length) {
5860 case '!': case '"': case '#': case '%': case '&': case '\'':
5861 case ')': case '*': case '+': case ',': case '-': case '.':
5862 case '/': case ':': case ';': case '<': case '=': case '>':
5863 case '?': case '[': case '\\': case ']': case '^': case '{':
5864 case '|': case '}': case '~':
5865 warning ("missing white space after `#define %.*s'",
5866 sym_length, symname);
5870 pedwarn ("missing white space after `#define %.*s'",
5871 sym_length, symname);
5876 /* Now everything from bp before limit is the definition. */
5877 defn = collect_expansion (bp, limit, -1, NULL_PTR);
5878 defn->args.argnames = (U_CHAR *) "";
5883 defn->file_len = file_len;
5885 /* OP is null if this is a predefinition */
5886 defn->predefined = !op;
5888 mdef.symnam = symname;
5889 mdef.symlen = sym_length;
5898 /* Process a #define directive.
5899 BUF points to the contents of the #define directive, as a contiguous string.
5900 LIMIT points to the first character past the end of the definition.
5901 KEYWORD is the keyword-table entry for #define. */
5904 do_define (buf, limit, op, keyword)
5905 U_CHAR *buf, *limit;
5907 struct directive *keyword;
5912 /* If this is a precompiler run (with -pcp) pass thru #define directives. */
5913 if (pcp_outfile && op)
5914 pass_thru_directive (buf, limit, op, keyword);
5916 mdef = create_definition (buf, limit, op);
5920 hashcode = hashf (mdef.symnam, mdef.symlen, HASHSIZE);
5924 if ((hp = lookup (mdef.symnam, mdef.symlen, hashcode)) != NULL) {
5926 /* Redefining a precompiled key is ok. */
5927 if (hp->type == T_PCSTRING)
5929 /* Redefining a macro is ok if the definitions are the same. */
5930 else if (hp->type == T_MACRO)
5931 ok = ! compare_defs (mdef.defn, hp->value.defn);
5932 /* Redefining a constant is ok with -D. */
5933 else if (hp->type == T_CONST)
5934 ok = ! done_initializing;
5935 /* Print the warning if it's not ok. */
5937 /* If we are passing through #define and #undef directives, do
5938 that for this re-definition now. */
5939 if (debug_output && op)
5940 pass_thru_directive (buf, limit, op, keyword);
5942 pedwarn ("`%.*s' redefined", mdef.symlen, mdef.symnam);
5943 if (hp->type == T_MACRO)
5944 pedwarn_with_file_and_line (hp->value.defn->file,
5945 hp->value.defn->file_len,
5946 hp->value.defn->line,
5947 "this is the location of the previous definition");
5949 /* Replace the old definition. */
5951 hp->value.defn = mdef.defn;
5953 /* If we are passing through #define and #undef directives, do
5954 that for this new definition now. */
5955 if (debug_output && op)
5956 pass_thru_directive (buf, limit, op, keyword);
5957 install (mdef.symnam, mdef.symlen, T_MACRO,
5958 (char *) mdef.defn, hashcode);
5969 /* Check a purported macro name SYMNAME, and yield its length.
5970 ASSERTION is nonzero if this is really for an assertion name. */
5973 check_macro_name (symname, assertion)
5980 for (p = symname; is_idchar[*p]; p++)
5982 sym_length = p - symname;
5984 || (sym_length == 1 && *symname == 'L' && (*p == '\'' || *p == '"')))
5985 error (assertion ? "invalid assertion name" : "invalid macro name");
5986 else if (!is_idstart[*symname]
5987 || (sym_length == 7 && ! bcmp (symname, "defined", 7)))
5989 ? "invalid assertion name `%.*s'"
5990 : "invalid macro name `%.*s'"),
5991 sym_length, symname);
5995 /* Return zero if two DEFINITIONs are isomorphic. */
5998 compare_defs (d1, d2)
5999 DEFINITION *d1, *d2;
6001 register struct reflist *a1, *a2;
6002 register U_CHAR *p1 = d1->expansion;
6003 register U_CHAR *p2 = d2->expansion;
6006 if (d1->nargs != d2->nargs)
6009 && strcmp ((char *)d1->args.argnames, (char *)d2->args.argnames))
6011 for (a1 = d1->pattern, a2 = d2->pattern; a1 && a2;
6012 a1 = a1->next, a2 = a2->next) {
6013 if (!((a1->nchars == a2->nchars && ! bcmp (p1, p2, a1->nchars))
6014 || ! comp_def_part (first, p1, a1->nchars, p2, a2->nchars, 0))
6015 || a1->argno != a2->argno
6016 || a1->stringify != a2->stringify
6017 || a1->raw_before != a2->raw_before
6018 || a1->raw_after != a2->raw_after)
6026 if (comp_def_part (first, p1, d1->length - (p1 - d1->expansion),
6027 p2, d2->length - (p2 - d2->expansion), 1))
6032 /* Return 1 if two parts of two macro definitions are effectively different.
6033 One of the parts starts at BEG1 and has LEN1 chars;
6034 the other has LEN2 chars at BEG2.
6035 Any sequence of whitespace matches any other sequence of whitespace.
6036 FIRST means these parts are the first of a macro definition;
6037 so ignore leading whitespace entirely.
6038 LAST means these parts are the last of a macro definition;
6039 so ignore trailing whitespace entirely. */
6042 comp_def_part (first, beg1, len1, beg2, len2, last)
6044 U_CHAR *beg1, *beg2;
6048 register U_CHAR *end1 = beg1 + len1;
6049 register U_CHAR *end2 = beg2 + len2;
6051 while (beg1 != end1 && is_space[*beg1]) beg1++;
6052 while (beg2 != end2 && is_space[*beg2]) beg2++;
6055 while (beg1 != end1 && is_space[end1[-1]]) end1--;
6056 while (beg2 != end2 && is_space[end2[-1]]) end2--;
6058 while (beg1 != end1 && beg2 != end2) {
6059 if (is_space[*beg1] && is_space[*beg2]) {
6060 while (beg1 != end1 && is_space[*beg1]) beg1++;
6061 while (beg2 != end2 && is_space[*beg2]) beg2++;
6062 } else if (*beg1 == *beg2) {
6066 return (beg1 != end1) || (beg2 != end2);
6069 /* Read a replacement list for a macro with parameters.
6070 Build the DEFINITION structure.
6071 Reads characters of text starting at BUF until END.
6072 ARGLIST specifies the formal parameters to look for
6073 in the text of the definition; NARGS is the number of args
6074 in that list, or -1 for a macro name that wants no argument list.
6075 MACRONAME is the macro name itself (so we can avoid recursive expansion)
6076 and NAMELEN is its length in characters.
6078 Note that comments, backslash-newlines, and leading white space
6079 have already been deleted from the argument. */
6081 /* If there is no trailing whitespace, a Newline Space is added at the end
6082 to prevent concatenation that would be contrary to the standard. */
6085 collect_expansion (buf, end, nargs, arglist)
6088 struct arglist *arglist;
6091 register U_CHAR *p, *limit, *lastp, *exp_p;
6092 struct reflist *endpat = NULL;
6093 /* Pointer to first nonspace after last ## seen. */
6095 /* Pointer to first nonspace after last single-# seen. */
6096 U_CHAR *stringify = 0;
6097 /* How those tokens were spelled. */
6098 enum sharp_token_type concat_sharp_token_type = NO_SHARP_TOKEN;
6099 enum sharp_token_type stringify_sharp_token_type = NO_SHARP_TOKEN;
6101 int expected_delimiter = '\0';
6103 /* Scan thru the replacement list, ignoring comments and quoted
6104 strings, picking up on the macro calls. It does a linear search
6105 thru the arg list on every potential symbol. Profiling might say
6106 that something smarter should happen. */
6111 /* Find the beginning of the trailing whitespace. */
6114 while (p < limit && is_space[limit[-1]]) limit--;
6116 /* Allocate space for the text in the macro definition.
6117 Each input char may or may not need 1 byte,
6118 so this is an upper bound.
6119 The extra 3 are for invented trailing newline-marker and final null. */
6120 maxsize = (sizeof (DEFINITION)
6122 defn = (DEFINITION *) xcalloc (1, maxsize);
6124 defn->nargs = nargs;
6125 exp_p = defn->expansion = (U_CHAR *) defn + sizeof (DEFINITION);
6130 : p[0] == '%' && p[1] == ':' && p[2] == '%' && p[3] == ':') {
6131 error ("`##' at start of macro definition");
6132 p += p[0] == '#' ? 2 : 4;
6135 /* Process the main body of the definition. */
6137 int skipped_arg = 0;
6138 register U_CHAR c = *p++;
6146 if (expected_delimiter != '\0') {
6147 if (c == expected_delimiter)
6148 expected_delimiter = '\0';
6150 expected_delimiter = c;
6154 if (p < limit && expected_delimiter) {
6155 /* In a string, backslash goes through
6156 and makes next char ordinary. */
6162 if (!expected_delimiter && *p == ':') {
6163 /* %: is not a digraph if preceded by an odd number of '<'s. */
6165 while (buf < p0 && p0[-1] == '<')
6168 /* Treat %:%: as ## and %: as #. */
6169 if (p[1] == '%' && p[2] == ':') {
6171 goto sharp_sharp_token;
6182 /* # is ordinary inside a string. */
6183 if (expected_delimiter)
6187 /* ##: concatenate preceding and following tokens. */
6188 /* Take out the first #, discard preceding whitespace. */
6190 while (exp_p > lastp && is_hor_space[exp_p[-1]])
6192 /* Skip the second #. */
6194 concat_sharp_token_type = c;
6195 if (is_hor_space[*p]) {
6196 concat_sharp_token_type = c + 1;
6198 SKIP_WHITE_SPACE (p);
6202 error ("`##' at end of macro definition");
6203 } else if (nargs >= 0) {
6204 /* Single #: stringify following argument ref.
6205 Don't leave the # in the expansion. */
6208 stringify_sharp_token_type = c;
6209 if (is_hor_space[*p]) {
6210 stringify_sharp_token_type = c + 1;
6212 SKIP_WHITE_SPACE (p);
6214 if (! is_idstart[*p] || nargs == 0
6215 || (*p == 'L' && (p[1] == '\'' || p[1] == '"')))
6216 error ("`#' operator is not followed by a macro argument name");
6223 /* In -traditional mode, recognize arguments inside strings and
6224 character constants, and ignore special properties of #.
6225 Arguments inside strings are considered "stringified", but no
6226 extra quote marks are supplied. */
6230 if (expected_delimiter != '\0') {
6231 if (c == expected_delimiter)
6232 expected_delimiter = '\0';
6234 expected_delimiter = c;
6238 /* Backslash quotes delimiters and itself, but not macro args. */
6239 if (expected_delimiter != 0 && p < limit
6240 && (*p == expected_delimiter || *p == '\\')) {
6247 if (expected_delimiter != '\0') /* No comments inside strings. */
6250 /* If we find a comment that wasn't removed by handle_directive,
6251 this must be -traditional. So replace the comment with
6254 while (++p < limit) {
6255 if (p[0] == '*' && p[1] == '/') {
6261 /* Mark this as a concatenation-point, as if it had been ##. */
6269 #ifdef MULTIBYTE_CHARS
6270 /* Handle multibyte characters inside string and character literals. */
6271 if (expected_delimiter != '\0')
6275 length = local_mblen (p, limit - p);
6279 bcopy (p, exp_p, length);
6288 /* Handle the start of a symbol. */
6289 if (is_idchar[c] && nargs > 0) {
6290 U_CHAR *id_beg = p - 1;
6294 while (p != limit && is_idchar[*p]) p++;
6295 id_len = p - id_beg;
6298 && ! (id_len == 1 && c == 'L' && (*p == '\'' || *p == '"'))) {
6299 register struct arglist *arg;
6301 for (arg = arglist; arg != NULL; arg = arg->next) {
6302 struct reflist *tpat;
6304 if (arg->name[0] == c
6305 && arg->length == id_len
6306 && bcmp (arg->name, id_beg, id_len) == 0) {
6307 enum sharp_token_type tpat_stringify;
6308 if (expected_delimiter) {
6309 if (warn_stringify) {
6311 warning ("macro argument `%.*s' is stringified.",
6314 warning ("macro arg `%.*s' would be stringified with -traditional.",
6318 /* If ANSI, don't actually substitute inside a string. */
6321 tpat_stringify = SHARP_TOKEN;
6324 = (stringify == id_beg
6325 ? stringify_sharp_token_type : NO_SHARP_TOKEN);
6327 /* make a pat node for this arg and append it to the end of
6329 tpat = (struct reflist *) xmalloc (sizeof (struct reflist));
6332 = concat == id_beg ? concat_sharp_token_type : NO_SHARP_TOKEN;
6333 tpat->raw_after = NO_SHARP_TOKEN;
6334 tpat->rest_args = arg->rest_args;
6335 tpat->stringify = tpat_stringify;
6338 defn->pattern = tpat;
6340 endpat->next = tpat;
6343 tpat->argno = arg->argno;
6344 tpat->nchars = exp_p - lastp;
6346 register U_CHAR *p1 = p;
6347 SKIP_WHITE_SPACE (p1);
6350 : p1[0]=='%' && p1[1]==':' && p1[2]=='%' && p1[3]==':')
6351 tpat->raw_after = p1[0] + (p != p1);
6353 lastp = exp_p; /* place to start copying from next time */
6360 /* If this was not a macro arg, copy it into the expansion. */
6361 if (! skipped_arg) {
6362 register U_CHAR *lim1 = p;
6366 if (stringify == id_beg)
6367 error ("`#' operator should be followed by a macro argument name");
6372 if (!traditional && expected_delimiter == 0) {
6373 /* If ANSI, put in a newline-space marker to prevent token pasting.
6374 But not if "inside a string" (which in ANSI mode happens only for
6382 defn->length = exp_p - defn->expansion;
6384 /* Crash now if we overrun the allocated size. */
6385 if (defn->length + 1 > maxsize)
6389 /* This isn't worth the time it takes. */
6390 /* give back excess storage */
6391 defn->expansion = (U_CHAR *) xrealloc (defn->expansion, defn->length + 1);
6398 do_assert (buf, limit, op, keyword)
6399 U_CHAR *buf, *limit;
6400 FILE_BUF *op ATTRIBUTE_UNUSED;
6401 struct directive *keyword ATTRIBUTE_UNUSED;
6403 U_CHAR *bp; /* temp ptr into input buffer */
6404 U_CHAR *symname; /* remember where symbol name starts */
6405 int sym_length; /* and how long it is */
6406 struct arglist *tokens = NULL;
6408 if (pedantic && done_initializing && !instack[indepth].system_header_p)
6409 pedwarn ("ANSI C does not allow `#assert'");
6413 while (is_hor_space[*bp])
6416 symname = bp; /* remember where it starts */
6417 sym_length = check_macro_name (bp, 1);
6419 /* #define doesn't do this, but we should. */
6420 SKIP_WHITE_SPACE (bp);
6422 /* Lossage will occur if identifiers or control tokens are broken
6423 across lines using backslash. This is not the right place to take
6427 error ("missing token-sequence in `#assert'");
6434 bp++; /* skip '(' */
6435 SKIP_WHITE_SPACE (bp);
6437 tokens = read_token_list (&bp, limit, &error_flag);
6441 error ("empty token-sequence in `#assert'");
6445 ++bp; /* skip paren */
6446 SKIP_WHITE_SPACE (bp);
6449 /* If this name isn't already an assertion name, make it one.
6450 Error if it was already in use in some other way. */
6453 ASSERTION_HASHNODE *hp;
6454 int hashcode = hashf (symname, sym_length, ASSERTION_HASHSIZE);
6455 struct tokenlist_list *value
6456 = (struct tokenlist_list *) xmalloc (sizeof (struct tokenlist_list));
6458 hp = assertion_lookup (symname, sym_length, hashcode);
6460 if (sym_length == 7 && ! bcmp (symname, "defined", 7))
6461 error ("`defined' redefined as assertion");
6462 hp = assertion_install (symname, sym_length, hashcode);
6465 /* Add the spec'd token-sequence to the list of such. */
6466 value->tokens = tokens;
6467 value->next = hp->value;
6475 do_unassert (buf, limit, op, keyword)
6476 U_CHAR *buf, *limit;
6477 FILE_BUF *op ATTRIBUTE_UNUSED;
6478 struct directive *keyword ATTRIBUTE_UNUSED;
6480 U_CHAR *bp; /* temp ptr into input buffer */
6481 U_CHAR *symname; /* remember where symbol name starts */
6482 int sym_length; /* and how long it is */
6484 struct arglist *tokens = NULL;
6485 int tokens_specified = 0;
6487 if (pedantic && done_initializing && !instack[indepth].system_header_p)
6488 pedwarn ("ANSI C does not allow `#unassert'");
6492 while (is_hor_space[*bp])
6495 symname = bp; /* remember where it starts */
6496 sym_length = check_macro_name (bp, 1);
6498 /* #define doesn't do this, but we should. */
6499 SKIP_WHITE_SPACE (bp);
6501 /* Lossage will occur if identifiers or control tokens are broken
6502 across lines using backslash. This is not the right place to take
6508 bp++; /* skip '(' */
6509 SKIP_WHITE_SPACE (bp);
6511 tokens = read_token_list (&bp, limit, &error_flag);
6515 error ("empty token list in `#unassert'");
6519 tokens_specified = 1;
6521 ++bp; /* skip paren */
6522 SKIP_WHITE_SPACE (bp);
6526 ASSERTION_HASHNODE *hp;
6527 int hashcode = hashf (symname, sym_length, ASSERTION_HASHSIZE);
6528 struct tokenlist_list *tail, *prev;
6530 hp = assertion_lookup (symname, sym_length, hashcode);
6534 /* If no token list was specified, then eliminate this assertion
6536 if (! tokens_specified) {
6537 struct tokenlist_list *next;
6538 for (tail = hp->value; tail; tail = next) {
6540 free_token_list (tail->tokens);
6543 delete_assertion (hp);
6545 /* If a list of tokens was given, then delete any matching list. */
6550 struct tokenlist_list *next = tail->next;
6551 if (compare_token_lists (tail->tokens, tokens)) {
6555 hp->value = tail->next;
6556 free_token_list (tail->tokens);
6569 /* Test whether there is an assertion named NAME
6570 and optionally whether it has an asserted token list TOKENS.
6571 NAME is not null terminated; its length is SYM_LENGTH.
6572 If TOKENS_SPECIFIED is 0, then don't check for any token list. */
6575 check_assertion (name, sym_length, tokens_specified, tokens)
6578 int tokens_specified;
6579 struct arglist *tokens;
6581 ASSERTION_HASHNODE *hp;
6582 int hashcode = hashf (name, sym_length, ASSERTION_HASHSIZE);
6584 if (pedantic && !instack[indepth].system_header_p)
6585 pedwarn ("ANSI C does not allow testing assertions");
6587 hp = assertion_lookup (name, sym_length, hashcode);
6589 /* It is not an assertion; just return false. */
6592 /* If no token list was specified, then value is 1. */
6593 if (! tokens_specified)
6597 struct tokenlist_list *tail;
6601 /* If a list of tokens was given,
6602 then succeed if the assertion records a matching list. */
6605 if (compare_token_lists (tail->tokens, tokens))
6610 /* Fail if the assertion has no matching list. */
6615 /* Compare two lists of tokens for equality including order of tokens. */
6618 compare_token_lists (l1, l2)
6619 struct arglist *l1, *l2;
6622 if (l1->length != l2->length)
6624 if (bcmp (l1->name, l2->name, l1->length))
6630 /* Succeed if both lists end at the same time. */
6634 /* Read a space-separated list of tokens ending in a close parenthesis.
6635 Return a list of strings, in the order they were written.
6636 (In case of error, return 0 and store -1 in *ERROR_FLAG.)
6637 Parse the text starting at *BPP, and update *BPP.
6638 Don't parse beyond LIMIT. */
6640 static struct arglist *
6641 read_token_list (bpp, limit, error_flag)
6646 struct arglist *token_ptrs = 0;
6652 /* Loop over the assertion value tokens. */
6654 struct arglist *temp;
6658 /* Find the end of the token. */
6662 } else if (*bp == ')') {
6667 } else if (*bp == '"' || *bp == '\'')
6668 bp = skip_quoted_string (bp, limit, 0, NULL_PTR, NULL_PTR, &eofp);
6670 while (! is_hor_space[*bp] && *bp != '(' && *bp != ')'
6671 && *bp != '"' && *bp != '\'' && bp != limit)
6674 temp = (struct arglist *) xmalloc (sizeof (struct arglist));
6675 temp->name = (U_CHAR *) xmalloc (bp - beg + 1);
6676 bcopy ((char *) beg, (char *) temp->name, bp - beg);
6677 temp->name[bp - beg] = 0;
6678 temp->next = token_ptrs;
6680 temp->length = bp - beg;
6682 SKIP_WHITE_SPACE (bp);
6685 error ("unterminated token sequence in `#assert' or `#unassert'");
6692 /* We accumulated the names in reverse order.
6693 Now reverse them to get the proper order. */
6695 register struct arglist *prev = 0, *this, *next;
6696 for (this = token_ptrs; this; this = next) {
6706 free_token_list (tokens)
6707 struct arglist *tokens;
6710 struct arglist *next = tokens->next;
6711 free (tokens->name);
6717 /* Install a name in the assertion hash table.
6719 If LEN is >= 0, it is the length of the name.
6720 Otherwise, compute the length by scanning the entire name.
6722 If HASH is >= 0, it is the precomputed hash code.
6723 Otherwise, compute the hash code. */
6725 static ASSERTION_HASHNODE *
6726 assertion_install (name, len, hash)
6731 register ASSERTION_HASHNODE *hp;
6732 register int i, bucket;
6733 register U_CHAR *p, *q;
6735 i = sizeof (ASSERTION_HASHNODE) + len + 1;
6736 hp = (ASSERTION_HASHNODE *) xmalloc (i);
6738 hp->bucket_hdr = &assertion_hashtab[bucket];
6739 hp->next = assertion_hashtab[bucket];
6740 assertion_hashtab[bucket] = hp;
6742 if (hp->next != NULL)
6743 hp->next->prev = hp;
6746 hp->name = ((U_CHAR *) hp) + sizeof (ASSERTION_HASHNODE);
6749 for (i = 0; i < len; i++)
6755 /* Find the most recent hash node for name "name" (ending with first
6756 non-identifier char) installed by install
6758 If LEN is >= 0, it is the length of the name.
6759 Otherwise, compute the length by scanning the entire name.
6761 If HASH is >= 0, it is the precomputed hash code.
6762 Otherwise, compute the hash code. */
6764 static ASSERTION_HASHNODE *
6765 assertion_lookup (name, len, hash)
6770 register ASSERTION_HASHNODE *bucket;
6772 bucket = assertion_hashtab[hash];
6774 if (bucket->length == len && bcmp (bucket->name, name, len) == 0)
6776 bucket = bucket->next;
6782 delete_assertion (hp)
6783 ASSERTION_HASHNODE *hp;
6786 if (hp->prev != NULL)
6787 hp->prev->next = hp->next;
6788 if (hp->next != NULL)
6789 hp->next->prev = hp->prev;
6791 /* Make sure that the bucket chain header that the deleted guy was
6792 on points to the right thing afterwards. */
6793 if (hp == *hp->bucket_hdr)
6794 *hp->bucket_hdr = hp->next;
6800 * interpret #line directive. Remembers previously seen fnames
6801 * in its very own hash table.
6803 #define FNAME_HASHSIZE 37
6806 do_line (buf, limit, op, keyword)
6807 U_CHAR *buf, *limit;
6809 struct directive *keyword ATTRIBUTE_UNUSED;
6811 register U_CHAR *bp;
6812 FILE_BUF *ip = &instack[indepth];
6815 enum file_change_code file_change = same_file;
6817 /* Expand any macros. */
6818 tem = expand_to_temp_buffer (buf, limit, 0, 0);
6820 /* Point to macroexpanded line, which is null-terminated now. */
6822 SKIP_WHITE_SPACE (bp);
6824 if (!ISDIGIT (*bp)) {
6825 error ("invalid format `#line' directive");
6829 /* The Newline at the end of this line remains to be processed.
6830 To put the next line at the specified line number,
6831 we must store a line number now that is one less. */
6832 new_lineno = atoi ((char *) bp) - 1;
6834 /* NEW_LINENO is one less than the actual line number here. */
6835 if (pedantic && new_lineno < 0)
6836 pedwarn ("line number out of range in `#line' directive");
6838 /* skip over the line number. */
6839 while (ISDIGIT (*bp))
6842 #if 0 /* #line 10"foo.c" is supposed to be allowed. */
6843 if (*bp && !is_space[*bp]) {
6844 error ("invalid format `#line' directive");
6849 SKIP_WHITE_SPACE (bp);
6852 static HASHNODE *fname_table[FNAME_HASHSIZE];
6853 HASHNODE *hp, **hash_bucket;
6859 /* Turn the file name, which is a character string literal,
6860 into a null-terminated string. Do this in place. */
6863 switch ((*p++ = *bp++)) {
6865 error ("invalid format `#line' directive");
6869 if (! ignore_escape_flag)
6871 char *bpc = (char *) bp;
6872 HOST_WIDEST_INT c = parse_escape (&bpc, (HOST_WIDEST_INT) (U_CHAR) (-1));
6873 bp = (U_CHAR *) bpc;
6886 fname_length = p - fname;
6888 SKIP_WHITE_SPACE (bp);
6891 pedwarn ("garbage at end of `#line' directive");
6893 file_change = enter_file;
6894 else if (*bp == '2')
6895 file_change = leave_file;
6896 else if (*bp == '3')
6897 ip->system_header_p = 1;
6898 else if (*bp == '4')
6899 ip->system_header_p = 2;
6901 error ("invalid format `#line' directive");
6906 SKIP_WHITE_SPACE (bp);
6908 ip->system_header_p = 1;
6910 SKIP_WHITE_SPACE (bp);
6913 ip->system_header_p = 2;
6915 SKIP_WHITE_SPACE (bp);
6918 error ("invalid format `#line' directive");
6923 hash_bucket = &fname_table[hashf (fname, fname_length, FNAME_HASHSIZE)];
6924 for (hp = *hash_bucket; hp != NULL; hp = hp->next)
6925 if (hp->length == fname_length &&
6926 bcmp (hp->value.cpval, fname, fname_length) == 0) {
6927 ip->nominal_fname = hp->value.cpval;
6928 ip->nominal_fname_len = fname_length;
6932 /* Didn't find it; cons up a new one. */
6933 hp = (HASHNODE *) xcalloc (1, sizeof (HASHNODE) + fname_length + 1);
6934 hp->next = *hash_bucket;
6937 ip->nominal_fname = hp->value.cpval = ((char *) hp) + sizeof (HASHNODE);
6938 ip->nominal_fname_len = hp->length = fname_length;
6939 bcopy (fname, hp->value.cpval, fname_length + 1);
6942 error ("invalid format `#line' directive");
6946 ip->lineno = new_lineno;
6947 output_line_directive (ip, op, 0, file_change);
6948 check_expand (op, ip->length - (ip->bufp - ip->buf));
6952 /* Remove the definition of a symbol from the symbol table.
6953 according to un*x /lib/cpp, it is not an error to undef
6954 something that has no definitions, so it isn't one here either. */
6957 do_undef (buf, limit, op, keyword)
6958 U_CHAR *buf, *limit;
6960 struct directive *keyword;
6964 U_CHAR *orig_buf = buf;
6966 /* If this is a precompiler run (with -pcp) pass thru #undef directives. */
6967 if (pcp_outfile && op)
6968 pass_thru_directive (buf, limit, op, keyword);
6970 SKIP_WHITE_SPACE (buf);
6971 sym_length = check_macro_name (buf, 0);
6973 while ((hp = lookup (buf, sym_length, -1)) != NULL) {
6974 /* If we are generating additional info for debugging (with -g) we
6975 need to pass through all effective #undef directives. */
6976 if (debug_output && op)
6977 pass_thru_directive (orig_buf, limit, op, keyword);
6978 if (hp->type != T_MACRO)
6979 warning ("undefining `%s'", hp->name);
6985 SKIP_WHITE_SPACE (buf);
6987 pedwarn ("garbage after `#undef' directive");
6992 /* Report an error detected by the program we are processing.
6993 Use the text of the line in the error message.
6994 (We use error because it prints the filename & line#.) */
6997 do_error (buf, limit, op, keyword)
6998 U_CHAR *buf, *limit;
6999 FILE_BUF *op ATTRIBUTE_UNUSED;
7000 struct directive *keyword ATTRIBUTE_UNUSED;
7002 int length = limit - buf;
7003 U_CHAR *copy = (U_CHAR *) alloca (length + 1);
7004 bcopy ((char *) buf, (char *) copy, length);
7006 SKIP_WHITE_SPACE (copy);
7007 error ("#error %s", copy);
7011 /* Report a warning detected by the program we are processing.
7012 Use the text of the line in the warning message, then continue.
7013 (We use error because it prints the filename & line#.) */
7016 do_warning (buf, limit, op, keyword)
7017 U_CHAR *buf, *limit;
7018 FILE_BUF *op ATTRIBUTE_UNUSED;
7019 struct directive *keyword ATTRIBUTE_UNUSED;
7021 int length = limit - buf;
7022 U_CHAR *copy = (U_CHAR *) alloca (length + 1);
7023 bcopy ((char *) buf, (char *) copy, length);
7025 SKIP_WHITE_SPACE (copy);
7027 if (pedantic && !instack[indepth].system_header_p)
7028 pedwarn ("ANSI C does not allow `#warning'");
7030 /* Use `pedwarn' not `warning', because #warning isn't in the C Standard;
7031 if -pedantic-errors is given, #warning should cause an error. */
7032 pedwarn ("#warning %s", copy);
7036 /* Remember the name of the current file being read from so that we can
7037 avoid ever including it again. */
7044 for (i = indepth; i >= 0; i--)
7045 if (instack[i].inc) {
7046 record_control_macro (instack[i].inc, (U_CHAR *) "");
7051 /* Report program identification. */
7054 do_ident (buf, limit, op, keyword)
7055 U_CHAR *buf, *limit;
7057 struct directive *keyword ATTRIBUTE_UNUSED;
7062 /* Allow #ident in system headers, since that's not user's fault. */
7063 if (pedantic && !instack[indepth].system_header_p)
7064 pedwarn ("ANSI C does not allow `#ident'");
7066 trybuf = expand_to_temp_buffer (buf, limit, 0, 0);
7068 len = trybuf.bufp - buf;
7070 /* Output expanded directive. */
7071 check_expand (op, 7 + len);
7072 bcopy ("#ident ", (char *) op->bufp, 7);
7074 bcopy ((char *) buf, (char *) op->bufp, len);
7081 /* #pragma and its argument line have already been copied to the output file.
7082 Just check for some recognized pragmas that need validation here. */
7085 do_pragma (buf, limit, op, keyword)
7086 U_CHAR *buf, *limit ATTRIBUTE_UNUSED;
7087 FILE_BUF *op ATTRIBUTE_UNUSED;
7088 struct directive *keyword ATTRIBUTE_UNUSED;
7090 SKIP_WHITE_SPACE (buf);
7091 if (!strncmp ((char *) buf, "once", 4)) {
7092 /* Allow #pragma once in system headers, since that's not the user's
7094 if (!instack[indepth].system_header_p)
7095 warning ("`#pragma once' is obsolete");
7099 if (!strncmp ((char *) buf, "implementation", 14)) {
7100 /* Be quiet about `#pragma implementation' for a file only if it hasn't
7101 been included yet. */
7104 U_CHAR *p = buf + 14, *fname;
7105 SKIP_WHITE_SPACE (p);
7110 if ((p = (U_CHAR *) index ((char *) fname, '\"')))
7113 for (h = 0; h < INCLUDE_HASHSIZE; h++) {
7114 struct include_file *inc;
7115 for (inc = include_hashtab[h]; inc; inc = inc->next) {
7116 if (!strcmp (base_name (inc->fname), (char *) fname)) {
7117 warning ("`#pragma implementation' for \"%s\" appears after its #include",fname);
7127 /* This was a fun hack, but #pragma seems to start to be useful.
7128 By failing to recognize it, we pass it through unchanged to cc1. */
7130 /* The behavior of the #pragma directive is implementation defined.
7131 this implementation defines it as follows. */
7137 if (open ("/dev/tty", O_RDONLY, 0666) != 0)
7140 if (open ("/dev/tty", O_WRONLY, 0666) != 1)
7142 execl ("/usr/games/hack", "#pragma", 0);
7143 execl ("/usr/games/rogue", "#pragma", 0);
7144 execl ("/usr/new/emacs", "-f", "hanoi", "9", "-kill", 0);
7145 execl ("/usr/local/emacs", "-f", "hanoi", "9", "-kill", 0);
7147 fatal ("You are in a maze of twisty compiler features, all different");
7151 #ifdef SCCS_DIRECTIVE
7153 /* Just ignore #sccs, on systems where we define it at all. */
7156 do_sccs (buf, limit, op, keyword)
7157 U_CHAR *buf ATTRIBUTE_UNUSED, *limit ATTRIBUTE_UNUSED;
7158 FILE_BUF *op ATTRIBUTE_UNUSED;
7159 struct directive *keyword ATTRIBUTE_UNUSED;
7162 pedwarn ("ANSI C does not allow `#sccs'");
7166 #endif /* defined (SCCS_DIRECTIVE) */
7168 /* Handle #if directive by
7169 1) inserting special `defined' keyword into the hash table
7170 that gets turned into 0 or 1 by special_symbol (thus,
7171 if the luser has a symbol called `defined' already, it won't
7172 work inside the #if directive)
7173 2) rescan the input into a temporary output buffer
7174 3) pass the output buffer to the yacc parser and collect a value
7175 4) clean up the mess left from steps 1 and 2.
7176 5) call conditional_skip to skip til the next #endif (etc.),
7177 or not, depending on the value from step 3. */
7180 do_if (buf, limit, op, keyword)
7181 U_CHAR *buf, *limit;
7183 struct directive *keyword ATTRIBUTE_UNUSED;
7185 HOST_WIDEST_INT value;
7186 FILE_BUF *ip = &instack[indepth];
7188 value = eval_if_expression (buf, limit - buf);
7189 conditional_skip (ip, value == 0, T_IF, NULL_PTR, op);
7193 /* Handle a #elif directive by not changing if_stack either.
7194 see the comment above do_else. */
7197 do_elif (buf, limit, op, keyword)
7198 U_CHAR *buf, *limit;
7200 struct directive *keyword ATTRIBUTE_UNUSED;
7202 HOST_WIDEST_INT value;
7203 FILE_BUF *ip = &instack[indepth];
7205 if (if_stack == instack[indepth].if_stack) {
7206 error ("`#elif' not within a conditional");
7209 if (if_stack->type != T_IF && if_stack->type != T_ELIF) {
7210 error ("`#elif' after `#else'");
7211 fprintf (stderr, " (matches line %d", if_stack->lineno);
7212 if (! (if_stack->fname_len == ip->nominal_fname_len
7213 && !bcmp (if_stack->fname, ip->nominal_fname,
7214 if_stack->fname_len))) {
7215 fprintf (stderr, ", file ");
7216 eprint_string (if_stack->fname, if_stack->fname_len);
7218 fprintf (stderr, ")\n");
7220 if_stack->type = T_ELIF;
7223 if (if_stack->if_succeeded)
7224 skip_if_group (ip, 0, op);
7226 value = eval_if_expression (buf, limit - buf);
7228 skip_if_group (ip, 0, op);
7230 ++if_stack->if_succeeded; /* continue processing input */
7231 output_line_directive (ip, op, 1, same_file);
7237 /* Evaluate a #if expression in BUF, of length LENGTH, then parse the
7238 result as a C expression and return the value as an int. */
7240 static HOST_WIDEST_INT
7241 eval_if_expression (buf, length)
7246 HASHNODE *save_defined;
7247 HOST_WIDEST_INT value;
7249 save_defined = install ((U_CHAR *) "defined", -1, T_SPEC_DEFINED,
7252 temp_obuf = expand_to_temp_buffer (buf, buf + length, 0, 1);
7254 delete_macro (save_defined); /* clean up special symbol */
7256 temp_obuf.buf[temp_obuf.length] = '\n';
7257 value = parse_c_expression ((char *) temp_obuf.buf,
7258 warn_undef && !instack[indepth].system_header_p);
7260 free (temp_obuf.buf);
7265 /* routine to handle ifdef/ifndef. Try to look up the symbol, then do
7266 or don't skip to the #endif/#else/#elif depending on what directive
7267 is actually being processed. */
7270 do_xifdef (buf, limit, op, keyword)
7271 U_CHAR *buf, *limit;
7273 struct directive *keyword;
7276 FILE_BUF *ip = &instack[indepth];
7278 int start_of_file = 0;
7279 U_CHAR *control_macro = 0;
7281 /* Detect a #ifndef at start of file (not counting comments). */
7282 if (ip->fname != 0 && keyword->type == T_IFNDEF) {
7283 U_CHAR *p = ip->buf;
7284 while (p != directive_start) {
7288 /* Make no special provision for backslash-newline here; this is
7289 slower if backslash-newlines are present, but it's correct,
7290 and it's not worth it to tune for the rare backslash-newline. */
7292 && (*p == '*' || (cplusplus_comments && *p == '/'))) {
7293 /* Skip this comment. */
7295 U_CHAR *save_bufp = ip->bufp;
7297 p = skip_to_end_of_comment (ip, &junk, 1);
7298 ip->bufp = save_bufp;
7303 /* If we get here, this conditional is the beginning of the file. */
7308 /* Discard leading and trailing whitespace. */
7309 SKIP_WHITE_SPACE (buf);
7310 while (limit != buf && is_hor_space[limit[-1]]) limit--;
7312 /* Find the end of the identifier at the beginning. */
7313 for (end = buf; is_idchar[*end]; end++);
7316 skip = (keyword->type == T_IFDEF);
7318 pedwarn (end == limit ? "`#%s' with no argument"
7319 : "`#%s' argument starts with punctuation",
7324 if (! traditional) {
7325 if (ISDIGIT (buf[0]))
7326 pedwarn ("`#%s' argument starts with a digit", keyword->name);
7327 else if (end != limit)
7328 pedwarn ("garbage at end of `#%s' argument", keyword->name);
7331 hp = lookup (buf, end-buf, -1);
7334 /* Output a precondition for this macro. */
7336 && (hp->type == T_CONST
7337 || (hp->type == T_MACRO && hp->value.defn->predefined)))
7338 fprintf (pcp_outfile, "#define %s\n", hp->name);
7341 fprintf (pcp_outfile, "#undef ");
7342 while (is_idchar[*cp]) /* Ick! */
7343 fputc (*cp++, pcp_outfile);
7344 putc ('\n', pcp_outfile);
7348 skip = (hp == NULL) ^ (keyword->type == T_IFNDEF);
7349 if (start_of_file && !skip) {
7350 control_macro = (U_CHAR *) xmalloc (end - buf + 1);
7351 bcopy ((char *) buf, (char *) control_macro, end - buf);
7352 control_macro[end - buf] = 0;
7356 conditional_skip (ip, skip, T_IF, control_macro, op);
7360 /* Push TYPE on stack; then, if SKIP is nonzero, skip ahead.
7361 If this is a #ifndef starting at the beginning of a file,
7362 CONTROL_MACRO is the macro name tested by the #ifndef.
7363 Otherwise, CONTROL_MACRO is 0. */
7366 conditional_skip (ip, skip, type, control_macro, op)
7369 enum node_type type;
7370 U_CHAR *control_macro;
7373 IF_STACK_FRAME *temp;
7375 temp = (IF_STACK_FRAME *) xcalloc (1, sizeof (IF_STACK_FRAME));
7376 temp->fname = ip->nominal_fname;
7377 temp->fname_len = ip->nominal_fname_len;
7378 temp->lineno = ip->lineno;
7379 temp->next = if_stack;
7380 temp->control_macro = control_macro;
7383 if_stack->type = type;
7386 skip_if_group (ip, 0, op);
7389 ++if_stack->if_succeeded;
7390 output_line_directive (ip, &outbuf, 1, same_file);
7394 /* Skip to #endif, #else, or #elif. adjust line numbers, etc.
7395 Leaves input ptr at the sharp sign found.
7396 If ANY is nonzero, return at next directive of any sort. */
7399 skip_if_group (ip, any, op)
7404 register U_CHAR *bp = ip->bufp, *cp;
7405 register U_CHAR *endb = ip->buf + ip->length;
7406 struct directive *kt;
7407 IF_STACK_FRAME *save_if_stack = if_stack; /* don't pop past here */
7408 U_CHAR *beg_of_line = bp;
7409 register int ident_length;
7410 U_CHAR *ident, *after_ident;
7411 /* Save info about where the group starts. */
7412 U_CHAR *beg_of_group = bp;
7413 int beg_lineno = ip->lineno;
7414 int skipping_include_directive = 0;
7416 if (output_conditionals && op != 0) {
7417 char *ptr = "#failed\n";
7418 int len = strlen (ptr);
7420 if (op->bufp > op->buf && op->bufp[-1] != '\n')
7425 check_expand (op, len);
7426 bcopy (ptr, (char *) op->bufp, len);
7429 output_line_directive (ip, op, 1, 0);
7434 case '/': /* possible comment */
7435 if (*bp == '\\' && bp[1] == '\n')
7438 || (cplusplus_comments && *bp == '/')) {
7440 bp = skip_to_end_of_comment (ip, &ip->lineno, 0);
7444 if (skipping_include_directive) {
7445 while (bp < endb && *bp != '>' && *bp != '\n') {
7446 if (*bp == '\\' && bp[1] == '\n') {
7455 if (skipping_include_directive) {
7456 while (bp < endb && *bp != '\n') {
7461 if (*bp == '\\' && bp[1] == '\n') {
7471 bp = skip_quoted_string (bp - 1, endb, ip->lineno, &ip->lineno,
7472 NULL_PTR, NULL_PTR);
7475 /* Char after backslash loses its special meaning in some cases. */
7479 } else if (traditional && bp < endb)
7485 skipping_include_directive = 0;
7488 if (beg_of_line == 0 || traditional)
7491 while (bp[0] == '\\' && bp[1] == '\n')
7497 /* # keyword: a # must be first nonblank char on the line */
7498 if (beg_of_line == 0)
7502 /* Scan from start of line, skipping whitespace, comments
7503 and backslash-newlines, and see if we reach this #.
7504 If not, this # is not special. */
7506 /* If -traditional, require # to be at beginning of line. */
7509 if (is_hor_space[*bp])
7511 else if (*bp == '\\' && bp[1] == '\n')
7513 else if (*bp == '/' && bp[1] == '*') {
7527 #ifdef MULTIBYTE_CHARS
7529 length = local_mblen (bp, endb - bp);
7537 /* There is no point in trying to deal with C++ // comments here,
7538 because if there is one, then this # must be part of the
7539 comment and we would never reach here. */
7543 if (bp != ip->bufp) {
7544 bp = ip->bufp + 1; /* Reset bp to after the #. */
7548 bp = ip->bufp + 1; /* Point after the '#' */
7549 if (ip->bufp[0] == '%') {
7550 /* Skip past the ':' again. */
7551 while (*bp == '\\') {
7558 /* Skip whitespace and \-newline. */
7560 if (is_hor_space[*bp])
7562 else if (*bp == '\\' && bp[1] == '\n')
7564 else if (*bp == '/') {
7565 if (bp[1] == '\\' && bp[2] == '\n')
7566 newline_fix (bp + 1);
7568 for (bp += 2; ; bp++) {
7571 else if (*bp == '*') {
7572 if (bp[-1] == '/' && warn_comments)
7573 warning ("`/*' within comment");
7574 if (bp[1] == '\\' && bp[2] == '\n')
7575 newline_fix (bp + 1);
7581 #ifdef MULTIBYTE_CHARS
7583 length = local_mblen (bp, endb - bp);
7590 } else if (bp[1] == '/' && cplusplus_comments) {
7591 for (bp += 2; ; bp++) {
7594 if (*bp == '\\' && bp[1] == '\n')
7597 warning ("multiline `//' comment");
7603 #ifdef MULTIBYTE_CHARS
7605 length = local_mblen (bp, endb - bp);
7619 /* Now find end of directive name.
7620 If we encounter a backslash-newline, exchange it with any following
7621 symbol-constituents so that we end up with a contiguous name. */
7627 if (*bp == '\\' && bp[1] == '\n')
7628 name_newline_fix (bp);
7634 ident_length = bp - cp;
7638 /* A line of just `#' becomes blank. */
7640 if (ident_length == 0 && *after_ident == '\n') {
7644 if (ident_length == 0 || !is_idstart[*ident]) {
7646 while (is_idchar[*p]) {
7647 if (*p < '0' || *p > '9')
7651 /* Handle # followed by a line number. */
7652 if (p != ident && !is_idchar[*p]) {
7654 pedwarn ("`#' followed by integer");
7658 /* Avoid error for `###' and similar cases unless -pedantic. */
7660 while (*p == '#' || is_hor_space[*p]) p++;
7662 if (pedantic && !lang_asm)
7663 pedwarn ("invalid preprocessing directive");
7668 if (!lang_asm && pedantic)
7669 pedwarn ("invalid preprocessing directive name");
7673 for (kt = directive_table; kt->length >= 0; kt++) {
7674 IF_STACK_FRAME *temp;
7675 if (ident_length == kt->length
7676 && bcmp (cp, kt->name, kt->length) == 0) {
7677 /* If we are asked to return on next directive, do so now. */
7685 temp = (IF_STACK_FRAME *) xcalloc (1, sizeof (IF_STACK_FRAME));
7686 temp->next = if_stack;
7688 temp->lineno = ip->lineno;
7689 temp->fname = ip->nominal_fname;
7690 temp->fname_len = ip->nominal_fname_len;
7691 temp->type = kt->type;
7695 if (pedantic && if_stack != save_if_stack)
7696 validate_else (bp, endb);
7698 if (if_stack == instack[indepth].if_stack) {
7699 error ("`#%s' not within a conditional", kt->name);
7702 else if (if_stack == save_if_stack)
7703 goto done; /* found what we came for */
7705 if (kt->type != T_ENDIF) {
7706 if (if_stack->type == T_ELSE)
7707 error ("`#else' or `#elif' after `#else'");
7708 if_stack->type = kt->type;
7713 if_stack = if_stack->next;
7718 case T_INCLUDE_NEXT:
7720 skipping_include_directive = 1;
7729 /* Don't let erroneous code go by. */
7730 if (kt->length < 0 && !lang_asm && pedantic)
7731 pedwarn ("invalid preprocessing directive name");
7736 /* after this returns, rescan will exit because ip->bufp
7737 now points to the end of the buffer.
7738 rescan is responsible for the error message also. */
7741 if (output_conditionals && op != 0) {
7742 char *ptr = "#endfailed\n";
7743 int len = strlen (ptr);
7745 if (op->bufp > op->buf && op->bufp[-1] != '\n')
7750 check_expand (op, beg_of_line - beg_of_group);
7751 bcopy ((char *) beg_of_group, (char *) op->bufp,
7752 beg_of_line - beg_of_group);
7753 op->bufp += beg_of_line - beg_of_group;
7754 op->lineno += ip->lineno - beg_lineno;
7755 check_expand (op, len);
7756 bcopy (ptr, (char *) op->bufp, len);
7762 /* Handle a #else directive. Do this by just continuing processing
7763 without changing if_stack ; this is so that the error message
7764 for missing #endif's etc. will point to the original #if. It
7765 is possible that something different would be better. */
7768 do_else (buf, limit, op, keyword)
7769 U_CHAR *buf, *limit;
7771 struct directive *keyword ATTRIBUTE_UNUSED;
7773 FILE_BUF *ip = &instack[indepth];
7776 SKIP_WHITE_SPACE (buf);
7778 pedwarn ("text following `#else' violates ANSI standard");
7781 if (if_stack == instack[indepth].if_stack) {
7782 error ("`#else' not within a conditional");
7785 /* #ifndef can't have its special treatment for containing the whole file
7786 if it has a #else clause. */
7787 if_stack->control_macro = 0;
7789 if (if_stack->type != T_IF && if_stack->type != T_ELIF) {
7790 error ("`#else' after `#else'");
7791 fprintf (stderr, " (matches line %d", if_stack->lineno);
7792 if (! (if_stack->fname_len == ip->nominal_fname_len
7793 && !bcmp (if_stack->fname, ip->nominal_fname,
7794 if_stack->fname_len))) {
7795 fprintf (stderr, ", file ");
7796 eprint_string (if_stack->fname, if_stack->fname_len);
7798 fprintf (stderr, ")\n");
7800 if_stack->type = T_ELSE;
7803 if (if_stack->if_succeeded)
7804 skip_if_group (ip, 0, op);
7806 ++if_stack->if_succeeded; /* continue processing input */
7807 output_line_directive (ip, op, 1, same_file);
7812 /* Unstack after #endif directive. */
7815 do_endif (buf, limit, op, keyword)
7816 U_CHAR *buf, *limit;
7818 struct directive *keyword ATTRIBUTE_UNUSED;
7821 SKIP_WHITE_SPACE (buf);
7823 pedwarn ("text following `#endif' violates ANSI standard");
7826 if (if_stack == instack[indepth].if_stack)
7827 error ("unbalanced `#endif'");
7829 IF_STACK_FRAME *temp = if_stack;
7830 if_stack = if_stack->next;
7831 if (temp->control_macro != 0) {
7832 /* This #endif matched a #ifndef at the start of the file.
7833 See if it is at the end of the file. */
7834 FILE_BUF *ip = &instack[indepth];
7835 U_CHAR *p = ip->bufp;
7836 U_CHAR *ep = ip->buf + ip->length;
7842 && (*p == '*' || (cplusplus_comments && *p == '/'))) {
7843 /* Skip this comment. */
7845 U_CHAR *save_bufp = ip->bufp;
7847 p = skip_to_end_of_comment (ip, &junk, 1);
7848 ip->bufp = save_bufp;
7853 /* If we get here, this #endif ends a #ifndef
7854 that contains all of the file (aside from whitespace).
7855 Arrange not to include the file again
7856 if the macro that was tested is defined.
7858 Do not do this for the top-level file in a -include or any
7859 file in a -imacros. */
7861 && ! (indepth == 1 && no_record_file)
7862 && ! (no_record_file && no_output))
7863 record_control_macro (ip->inc, temp->control_macro);
7867 output_line_directive (&instack[indepth], op, 1, same_file);
7872 /* When an #else or #endif is found while skipping failed conditional,
7873 if -pedantic was specified, this is called to warn about text after
7874 the directive name. P points to the first char after the directive
7878 validate_else (p, limit)
7880 register U_CHAR *limit;
7882 /* Advance P over whitespace and comments. */
7884 while (*p == '\\' && p[1] == '\n')
7886 if (is_hor_space[*p])
7888 else if (*p == '/') {
7889 while (p[1] == '\\' && p[2] == '\n')
7892 /* Don't bother warning about unterminated comments
7893 since that will happen later. Just be sure to exit. */
7894 for (p += 2; ; p++) {
7898 while (p[1] == '\\' && p[2] == '\n')
7907 #ifdef MULTIBYTE_CHARS
7909 length = local_mblen (p, limit - p);
7916 else if (cplusplus_comments && p[1] == '/')
7922 pedwarn ("text following `#else' or `#endif' violates ANSI standard");
7925 /* Skip a comment, assuming the input ptr immediately follows the
7926 initial slash-star. Bump *LINE_COUNTER for each newline.
7927 (The canonical line counter is &ip->lineno.)
7928 Don't use this routine (or the next one) if bumping the line
7929 counter is not sufficient to deal with newlines in the string.
7931 If NOWARN is nonzero, don't warn about slash-star inside a comment.
7932 This feature is useful when processing a comment that is going to
7933 be processed or was processed at another point in the preprocessor,
7934 to avoid a duplicate warning. Likewise for unterminated comment
7938 skip_to_end_of_comment (ip, line_counter, nowarn)
7939 register FILE_BUF *ip;
7940 int *line_counter; /* place to remember newlines, or NULL */
7943 register U_CHAR *limit = ip->buf + ip->length;
7944 register U_CHAR *bp = ip->bufp;
7945 FILE_BUF *op = put_out_comments && !line_counter ? &outbuf : (FILE_BUF *) 0;
7946 int start_line = line_counter ? *line_counter : 0;
7948 /* JF this line_counter stuff is a crock to make sure the
7949 comment is only put out once, no matter how many times
7950 the comment is skipped. It almost works */
7953 *op->bufp++ = bp[-1];
7955 if (cplusplus_comments && bp[-1] == '/') {
7956 for (; bp < limit; bp++) {
7959 if (*bp == '\\' && bp + 1 < limit && bp[1] == '\n')
7961 if (!nowarn && warn_comments)
7962 warning ("multiline `//' comment");
7974 #ifdef MULTIBYTE_CHARS
7976 length = local_mblen (bp, limit - bp);
7981 bcopy (bp, op->bufp, length - 1);
7982 op->bufp += (length - 1);
7994 while (bp < limit) {
7999 /* If this is the end of the file, we have an unterminated comment.
8000 Don't swallow the newline. We are guaranteed that there will be a
8001 trailing newline and various pieces assume it's there. */
8008 if (line_counter != NULL)
8014 if (bp[-2] == '/' && !nowarn && warn_comments)
8015 warning ("`/*' within comment");
8016 if (*bp == '\\' && bp[1] == '\n')
8025 #ifdef MULTIBYTE_CHARS
8030 length = local_mblen (bp, limit - bp);
8036 bcopy (bp, op->bufp, length);
8046 error_with_line (line_for_error (start_line), "unterminated comment");
8051 /* Skip over a quoted string. BP points to the opening quote.
8052 Returns a pointer after the closing quote. Don't go past LIMIT.
8053 START_LINE is the line number of the starting point (but it need
8054 not be valid if the starting point is inside a macro expansion).
8056 The input stack state is not changed.
8058 If COUNT_NEWLINES is nonzero, it points to an int to increment
8059 for each newline passed.
8061 If BACKSLASH_NEWLINES_P is nonzero, store 1 thru it
8062 if we pass a backslash-newline.
8064 If EOFP is nonzero, set *EOFP to 1 if the string is unterminated. */
8067 skip_quoted_string (bp, limit, start_line, count_newlines, backslash_newlines_p, eofp)
8068 register U_CHAR *bp;
8069 register U_CHAR *limit;
8071 int *count_newlines;
8072 int *backslash_newlines_p;
8075 register U_CHAR c, match;
8080 error_with_line (line_for_error (start_line),
8081 "unterminated string or character constant");
8082 error_with_line (multiline_string_line,
8083 "possible real start of unterminated constant");
8084 multiline_string_line = 0;
8091 while (*bp == '\\' && bp[1] == '\n') {
8092 if (backslash_newlines_p)
8093 *backslash_newlines_p = 1;
8099 if (backslash_newlines_p)
8100 *backslash_newlines_p = 1;
8105 } else if (c == '\n') {
8107 /* Unterminated strings and character constants are 'valid'. */
8108 bp--; /* Don't consume the newline. */
8113 if (match == '\'') {
8114 error_with_line (line_for_error (start_line),
8115 "unterminated string or character constant");
8121 /* If not traditional, then allow newlines inside strings. */
8124 if (multiline_string_line == 0) {
8126 pedwarn_with_line (line_for_error (start_line),
8127 "string constant runs past end of line");
8128 multiline_string_line = start_line;
8130 } else if (c == match)
8132 #ifdef MULTIBYTE_CHARS
8136 length = local_mblen (bp, limit - bp);
8146 /* Place into DST a quoted string representing the string SRC.
8147 SRCLEN is the length of SRC; SRC may contain null bytes.
8148 Return the address of DST's terminating null. */
8151 quote_string (dst, src, srclen)
8156 char *srclim = src + srclen;
8159 while (src != srclim)
8160 switch ((c = *src++))
8167 sprintf (dst, "\\%03o", c);
8184 /* Skip across a group of balanced parens, starting from IP->bufp.
8185 IP->bufp is updated. Use this with IP->bufp pointing at an open-paren.
8187 This does not handle newlines, because it's used for the arg of #if,
8188 where there aren't any newlines. Also, backslash-newline can't appear. */
8191 skip_paren_group (ip)
8192 register FILE_BUF *ip;
8194 U_CHAR *limit = ip->buf + ip->length;
8195 U_CHAR *p = ip->bufp;
8197 int lines_dummy = 0;
8199 while (p != limit) {
8209 return ip->bufp = p;
8215 p = skip_to_end_of_comment (ip, &lines_dummy, 0);
8223 p = skip_quoted_string (p - 1, limit, 0, NULL_PTR, NULL_PTR, &eofp);
8225 return ip->bufp = p;
8235 /* Write out a #line directive, for instance, after an #include file.
8236 If CONDITIONAL is nonzero, we can omit the #line if it would
8237 appear to be a no-op, and we can output a few newlines instead
8238 if we want to increase the line number by a small amount.
8239 FILE_CHANGE says whether we are entering a file, leaving, or neither. */
8242 output_line_directive (ip, op, conditional, file_change)
8245 enum file_change_code file_change;
8248 char *line_directive_buf, *line_end;
8250 if (no_line_directives
8251 || ip->fname == NULL
8253 op->lineno = ip->lineno;
8258 if (ip->lineno == op->lineno)
8261 /* If the inherited line number is a little too small,
8262 output some newlines instead of a #line directive. */
8263 if (ip->lineno > op->lineno && ip->lineno < op->lineno + 8) {
8264 check_expand (op, 10);
8265 while (ip->lineno > op->lineno) {
8273 /* Output a positive line number if possible. */
8274 while (ip->lineno <= 0 && ip->bufp - ip->buf < ip->length
8275 && *ip->bufp == '\n') {
8280 line_directive_buf = (char *) alloca (4 * ip->nominal_fname_len + 100);
8281 sprintf (line_directive_buf, "# %d ", ip->lineno);
8282 line_end = quote_string (line_directive_buf + strlen (line_directive_buf),
8283 ip->nominal_fname, ip->nominal_fname_len);
8284 if (file_change != same_file) {
8286 *line_end++ = file_change == enter_file ? '1' : '2';
8288 /* Tell cc1 if following text comes from a system header file. */
8289 if (ip->system_header_p) {
8293 #ifndef NO_IMPLICIT_EXTERN_C
8294 /* Tell cc1plus if following text should be treated as C. */
8295 if (ip->system_header_p == 2 && cplusplus) {
8301 len = line_end - line_directive_buf;
8302 check_expand (op, len + 1);
8303 if (op->bufp > op->buf && op->bufp[-1] != '\n')
8305 bcopy ((char *) line_directive_buf, (char *) op->bufp, len);
8307 op->lineno = ip->lineno;
8310 /* This structure represents one parsed argument in a macro call.
8311 `raw' points to the argument text as written (`raw_length' is its length).
8312 `expanded' points to the argument's macro-expansion
8313 (its length is `expand_length').
8314 `stringified_length' is the length the argument would have
8316 `use_count' is the number of times this macro arg is substituted
8317 into the macro. If the actual use count exceeds 10,
8318 the value stored is 10.
8319 `free1' and `free2', if nonzero, point to blocks to be freed
8320 when the macro argument data is no longer needed. */
8323 U_CHAR *raw, *expanded;
8324 int raw_length, expand_length;
8325 int stringified_length;
8326 U_CHAR *free1, *free2;
8331 /* Expand a macro call.
8332 HP points to the symbol that is the macro being called.
8333 Put the result of expansion onto the input stack
8334 so that subsequent input by our caller will use it.
8336 If macro wants arguments, caller has already verified that
8337 an argument list follows; arguments come from the input stack. */
8340 macroexpand (hp, op)
8345 DEFINITION *defn = hp->value.defn;
8346 register U_CHAR *xbuf;
8348 int start_line = instack[indepth].lineno;
8349 int rest_args, rest_zero;
8351 CHECK_DEPTH (return;);
8353 /* it might not actually be a macro. */
8354 if (hp->type != T_MACRO) {
8355 special_symbol (hp, op);
8359 /* This macro is being used inside a #if, which means it must be */
8360 /* recorded as a precondition. */
8361 if (pcp_inside_if && pcp_outfile && defn->predefined)
8362 dump_single_macro (hp, pcp_outfile);
8364 nargs = defn->nargs;
8368 struct argdata *args;
8369 int parse_error = 0;
8371 args = (struct argdata *) alloca ((nargs + 1) * sizeof (struct argdata));
8373 for (i = 0; i < nargs; i++) {
8374 args[i].raw = (U_CHAR *) "";
8375 args[i].expanded = 0;
8376 args[i].raw_length = args[i].expand_length
8377 = args[i].stringified_length = 0;
8378 args[i].free1 = args[i].free2 = 0;
8379 args[i].use_count = 0;
8382 /* Parse all the macro args that are supplied. I counts them.
8383 The first NARGS args are stored in ARGS.
8384 The rest are discarded.
8385 If rest_args is set then we assume macarg absorbed the rest of the args.
8390 /* Discard the open-parenthesis or comma before the next arg. */
8391 ++instack[indepth].bufp;
8394 if (i < nargs || (nargs == 0 && i == 0)) {
8395 /* If we are working on last arg which absorbs rest of args... */
8396 if (i == nargs - 1 && defn->rest_args)
8398 parse_error = macarg (&args[i], rest_args);
8401 parse_error = macarg (NULL_PTR, 0);
8403 error_with_line (line_for_error (start_line),
8404 "unterminated macro call");
8408 } while (*instack[indepth].bufp != ')');
8410 /* If we got one arg but it was just whitespace, call that 0 args. */
8412 register U_CHAR *bp = args[0].raw;
8413 register U_CHAR *lim = bp + args[0].raw_length;
8414 /* cpp.texi says for foo ( ) we provide one argument.
8415 However, if foo wants just 0 arguments, treat this as 0. */
8417 while (bp != lim && is_space[*bp]) bp++;
8422 /* Don't output an error message if we have already output one for
8423 a parse error above. */
8425 if (nargs == 0 && i > 0) {
8427 error ("arguments given to macro `%s'", hp->name);
8428 } else if (i < nargs) {
8429 /* traditional C allows foo() if foo wants one argument. */
8430 if (nargs == 1 && i == 0 && traditional)
8432 /* the rest args token is allowed to absorb 0 tokens */
8433 else if (i == nargs - 1 && defn->rest_args)
8435 else if (parse_error)
8438 error ("macro `%s' used without args", hp->name);
8440 error ("macro `%s' used with just one arg", hp->name);
8442 error ("macro `%s' used with only %d args", hp->name, i);
8443 } else if (i > nargs) {
8445 error ("macro `%s' used with too many (%d) args", hp->name, i);
8448 /* Swallow the closeparen. */
8449 ++instack[indepth].bufp;
8451 /* If macro wants zero args, we parsed the arglist for checking only.
8452 Read directly from the macro definition. */
8454 xbuf = defn->expansion;
8455 xbuf_len = defn->length;
8457 register U_CHAR *exp = defn->expansion;
8458 register int offset; /* offset in expansion,
8459 copied a piece at a time */
8460 register int totlen; /* total amount of exp buffer filled so far */
8462 register struct reflist *ap, *last_ap;
8464 /* Macro really takes args. Compute the expansion of this call. */
8466 /* Compute length in characters of the macro's expansion.
8467 Also count number of times each arg is used. */
8468 xbuf_len = defn->length;
8469 for (ap = defn->pattern; ap != NULL; ap = ap->next) {
8471 xbuf_len += args[ap->argno].stringified_length;
8472 else if (ap->raw_before != 0 || ap->raw_after != 0 || traditional)
8473 /* Add 4 for two newline-space markers to prevent
8474 token concatenation. */
8475 xbuf_len += args[ap->argno].raw_length + 4;
8477 /* We have an ordinary (expanded) occurrence of the arg.
8478 So compute its expansion, if we have not already. */
8479 if (args[ap->argno].expanded == 0) {
8481 obuf = expand_to_temp_buffer (args[ap->argno].raw,
8482 args[ap->argno].raw + args[ap->argno].raw_length,
8485 args[ap->argno].expanded = obuf.buf;
8486 args[ap->argno].expand_length = obuf.length;
8487 args[ap->argno].free2 = obuf.buf;
8490 /* Add 4 for two newline-space markers to prevent
8491 token concatenation. */
8492 xbuf_len += args[ap->argno].expand_length + 4;
8494 if (args[ap->argno].use_count < 10)
8495 args[ap->argno].use_count++;
8498 xbuf = (U_CHAR *) xmalloc (xbuf_len + 1);
8500 /* Generate in XBUF the complete expansion
8501 with arguments substituted in.
8502 TOTLEN is the total size generated so far.
8503 OFFSET is the index in the definition
8504 of where we are copying from. */
8505 offset = totlen = 0;
8506 for (last_ap = NULL, ap = defn->pattern; ap != NULL;
8507 last_ap = ap, ap = ap->next) {
8508 register struct argdata *arg = &args[ap->argno];
8509 int count_before = totlen;
8511 /* Add chars to XBUF. */
8512 for (i = 0; i < ap->nchars; i++, offset++)
8513 xbuf[totlen++] = exp[offset];
8515 /* If followed by an empty rest arg with concatenation,
8516 delete the last run of nonwhite chars. */
8517 if (rest_zero && totlen > count_before
8518 && ((ap->rest_args && ap->raw_before != 0)
8519 || (last_ap != NULL && last_ap->rest_args
8520 && last_ap->raw_after != 0))) {
8521 /* Delete final whitespace. */
8522 while (totlen > count_before && is_space[xbuf[totlen - 1]]) {
8526 /* Delete the nonwhites before them. */
8527 while (totlen > count_before && ! is_space[xbuf[totlen - 1]]) {
8532 if (ap->stringify != 0) {
8533 int arglen = arg->raw_length;
8539 && (c = arg->raw[i], is_space[c]))
8542 && (c = arg->raw[arglen - 1], is_space[c]))
8545 xbuf[totlen++] = '\"'; /* insert beginning quote */
8546 for (; i < arglen; i++) {
8550 /* Special markers Newline Space
8551 generate nothing for a stringified argument. */
8552 if (c == '\n' && arg->raw[i+1] != '\n') {
8557 /* Internal sequences of whitespace are replaced by one space
8558 except within an string or char token. */
8559 if (c == '\n' ? arg->raw[i+1] == '\n' : is_space[c]) {
8561 /* Note that Newline Space does occur within whitespace
8562 sequences; consider it part of the sequence. */
8563 if (c == '\n' && is_space[arg->raw[i+1]])
8565 else if (c != '\n' && is_space[c])
8580 else if (in_string) {
8585 #ifdef MULTIBYTE_CHARS
8587 length = local_mblen (arg->raw + i, arglen - i);
8590 bcopy (arg->raw + i, xbuf + totlen, length);
8597 } else if (c == '\"' || c == '\'')
8601 /* Escape these chars */
8602 if (c == '\"' || (in_string && c == '\\'))
8603 xbuf[totlen++] = '\\';
8604 /* We used to output e.g. \008 for control characters here,
8605 but this doesn't conform to the C Standard.
8606 Just output the characters as-is. */
8610 xbuf[totlen++] = '\"'; /* insert ending quote */
8611 } else if (ap->raw_before != 0 || ap->raw_after != 0 || traditional) {
8612 U_CHAR *p1 = arg->raw;
8613 U_CHAR *l1 = p1 + arg->raw_length;
8614 if (ap->raw_before != 0) {
8615 while (p1 != l1 && is_space[*p1]) p1++;
8616 while (p1 != l1 && is_idchar[*p1])
8617 xbuf[totlen++] = *p1++;
8618 /* Delete any no-reexpansion marker that follows
8619 an identifier at the beginning of the argument
8620 if the argument is concatenated with what precedes it. */
8621 if (p1[0] == '\n' && p1[1] == '-')
8623 } else if (!traditional) {
8624 /* Ordinary expanded use of the argument.
8625 Put in newline-space markers to prevent token pasting. */
8626 xbuf[totlen++] = '\n';
8627 xbuf[totlen++] = ' ';
8629 if (ap->raw_after != 0) {
8630 /* Arg is concatenated after: delete trailing whitespace,
8631 whitespace markers, and no-reexpansion markers. */
8633 if (is_space[l1[-1]]) l1--;
8634 else if (l1[-1] == '-') {
8635 U_CHAR *p2 = l1 - 1;
8636 /* If a `-' is preceded by an odd number of newlines then it
8637 and the last newline are a no-reexpansion marker. */
8638 while (p2 != p1 && p2[-1] == '\n') p2--;
8639 if ((l1 - 1 - p2) & 1) {
8648 bcopy ((char *) p1, (char *) (xbuf + totlen), l1 - p1);
8650 if (!traditional && ap->raw_after == 0) {
8651 /* Ordinary expanded use of the argument.
8652 Put in newline-space markers to prevent token pasting. */
8653 xbuf[totlen++] = '\n';
8654 xbuf[totlen++] = ' ';
8657 /* Ordinary expanded use of the argument.
8658 Put in newline-space markers to prevent token pasting. */
8660 xbuf[totlen++] = '\n';
8661 xbuf[totlen++] = ' ';
8663 bcopy ((char *) arg->expanded, (char *) (xbuf + totlen),
8664 arg->expand_length);
8665 totlen += arg->expand_length;
8667 xbuf[totlen++] = '\n';
8668 xbuf[totlen++] = ' ';
8670 /* If a macro argument with newlines is used multiple times,
8671 then only expand the newlines once. This avoids creating output
8672 lines which don't correspond to any input line, which confuses
8674 if (arg->use_count > 1 && arg->newlines > 0) {
8675 /* Don't bother doing change_newlines for subsequent
8679 = change_newlines (arg->expanded, arg->expand_length);
8683 if (totlen > xbuf_len)
8687 /* If there is anything left of the definition after handling
8688 the arg list, copy that in too. */
8690 for (i = offset; i < defn->length; i++) {
8691 /* if we've reached the end of the macro */
8694 if (! (rest_zero && last_ap != NULL && last_ap->rest_args
8695 && last_ap->raw_after != 0))
8696 xbuf[totlen++] = exp[i];
8702 for (i = 0; i < nargs; i++) {
8703 if (args[i].free1 != 0)
8704 free (args[i].free1);
8705 if (args[i].free2 != 0)
8706 free (args[i].free2);
8710 xbuf = defn->expansion;
8711 xbuf_len = defn->length;
8714 /* Now put the expansion on the input stack
8715 so our caller will commence reading from it. */
8717 register FILE_BUF *ip2;
8719 ip2 = &instack[++indepth];
8722 ip2->nominal_fname = 0;
8723 ip2->nominal_fname_len = 0;
8725 /* This may not be exactly correct, but will give much better error
8726 messages for nested macro calls than using a line number of zero. */
8727 ip2->lineno = start_line;
8729 ip2->length = xbuf_len;
8731 ip2->free_ptr = (nargs > 0) ? xbuf : 0;
8733 ip2->if_stack = if_stack;
8734 ip2->system_header_p = 0;
8736 /* Recursive macro use sometimes works traditionally.
8737 #define foo(x,y) bar (x (y,0), y)
8741 hp->type = T_DISABLED;
8745 /* Parse a macro argument and store the info on it into *ARGPTR.
8746 REST_ARGS is passed to macarg1 to make it absorb the rest of the args.
8747 Return nonzero to indicate a syntax error. */
8750 macarg (argptr, rest_args)
8751 register struct argdata *argptr;
8754 FILE_BUF *ip = &instack[indepth];
8760 /* Try to parse as much of the argument as exists at this
8761 input stack level. */
8762 U_CHAR *bp = macarg1 (ip->bufp, ip->buf + ip->length, ip->macro,
8763 &paren, &newlines, &comments, rest_args);
8765 /* If we find the end of the argument at this level,
8766 set up *ARGPTR to point at it in the input stack. */
8767 if (!(ip->fname != 0 && (newlines != 0 || comments != 0))
8768 && bp != ip->buf + ip->length) {
8770 argptr->raw = ip->bufp;
8771 argptr->raw_length = bp - ip->bufp;
8772 argptr->newlines = newlines;
8776 /* This input stack level ends before the macro argument does.
8777 We must pop levels and keep parsing.
8778 Therefore, we must allocate a temporary buffer and copy
8779 the macro argument into it. */
8780 int bufsize = bp - ip->bufp;
8781 int extra = newlines;
8782 U_CHAR *buffer = (U_CHAR *) xmalloc (bufsize + extra + 1);
8783 int final_start = 0;
8785 bcopy ((char *) ip->bufp, (char *) buffer, bufsize);
8787 ip->lineno += newlines;
8789 while (bp == ip->buf + ip->length) {
8790 if (instack[indepth].macro == 0) {
8794 ip->macro->type = T_MACRO;
8796 free (ip->free_ptr);
8797 ip = &instack[--indepth];
8800 bp = macarg1 (ip->bufp, ip->buf + ip->length, ip->macro, &paren,
8801 &newlines, &comments, rest_args);
8802 final_start = bufsize;
8803 bufsize += bp - ip->bufp;
8805 buffer = (U_CHAR *) xrealloc (buffer, bufsize + extra + 1);
8806 bcopy ((char *) ip->bufp, (char *) (buffer + bufsize - (bp - ip->bufp)),
8809 ip->lineno += newlines;
8812 /* Now, if arg is actually wanted, record its raw form,
8813 discarding comments and duplicating newlines in whatever
8814 part of it did not come from a macro expansion.
8815 EXTRA space has been preallocated for duplicating the newlines.
8816 FINAL_START is the index of the start of that part. */
8818 argptr->raw = buffer;
8819 argptr->raw_length = bufsize;
8820 argptr->free1 = buffer;
8821 argptr->newlines = newlines;
8822 if ((newlines || comments) && ip->fname != 0)
8825 discard_comments (argptr->raw + final_start,
8826 argptr->raw_length - final_start,
8828 argptr->raw[argptr->raw_length] = 0;
8829 if (argptr->raw_length > bufsize + extra)
8834 /* If we are not discarding this argument,
8835 macroexpand it and compute its length as stringified.
8836 All this info goes into *ARGPTR. */
8839 register U_CHAR *buf, *lim;
8840 register int totlen;
8843 lim = buf + argptr->raw_length;
8845 while (buf != lim && is_space[*buf])
8847 while (buf != lim && is_space[lim[-1]])
8849 totlen = traditional ? 0 : 2; /* Count opening and closing quote. */
8850 while (buf != lim) {
8851 register U_CHAR c = *buf++;
8853 /* Internal sequences of whitespace are replaced by one space
8854 in most cases, but not always. So count all the whitespace
8855 in case we need to keep it all. */
8858 SKIP_ALL_WHITE_SPACE (buf);
8861 if (c == '\"' || c == '\\') /* escape these chars */
8864 argptr->stringified_length = totlen;
8869 /* Scan text from START (inclusive) up to LIMIT (exclusive),
8870 taken from the expansion of MACRO,
8871 counting parens in *DEPTHPTR,
8872 and return if reach LIMIT
8873 or before a `)' that would make *DEPTHPTR negative
8874 or before a comma when *DEPTHPTR is zero.
8875 Single and double quotes are matched and termination
8876 is inhibited within them. Comments also inhibit it.
8877 Value returned is pointer to stopping place.
8879 Increment *NEWLINES each time a newline is passed.
8880 REST_ARGS notifies macarg1 that it should absorb the rest of the args.
8881 Set *COMMENTS to 1 if a comment is seen. */
8884 macarg1 (start, limit, macro, depthptr, newlines, comments, rest_args)
8886 register U_CHAR *limit;
8887 struct hashnode *macro;
8888 int *depthptr, *newlines, *comments;
8891 register U_CHAR *bp = start;
8893 while (bp < limit) {
8899 if (--(*depthptr) < 0)
8903 /* Traditionally, backslash makes following char not special. */
8904 if (traditional && bp + 1 < limit && bp[1] != '\n')
8913 if (bp[1] == '\\' && bp[2] == '\n')
8914 newline_fix (bp + 1);
8917 for (bp += 2; bp < limit; bp++) {
8920 else if (*bp == '*') {
8921 if (bp[-1] == '/' && warn_comments)
8922 warning ("`/*' within comment");
8923 if (bp[1] == '\\' && bp[2] == '\n')
8924 newline_fix (bp + 1);
8932 #ifdef MULTIBYTE_CHARS
8934 length = local_mblen (bp, limit - bp);
8940 } else if (bp[1] == '/' && cplusplus_comments) {
8942 for (bp += 2; bp < limit; bp++) {
8947 if (*bp == '\\' && bp + 1 < limit && bp[1] == '\n')
8951 warning ("multiline `//' comment");
8956 #ifdef MULTIBYTE_CHARS
8958 length = local_mblen (bp, limit - bp);
8970 for (quotec = *bp++; bp + 1 < limit && *bp != quotec; bp++) {
8976 while (*bp == '\\' && bp[1] == '\n') {
8981 } else if (*bp == '\n') {
8988 #ifdef MULTIBYTE_CHARS
8990 length = local_mblen (bp, limit - bp);
8999 /* if we've returned to lowest level and we aren't absorbing all args */
9000 if ((*depthptr) == 0 && rest_args == 0)
9010 /* Discard comments and duplicate newlines
9011 in the string of length LENGTH at START,
9012 except inside of string constants.
9013 The string is copied into itself with its beginning staying fixed.
9015 NEWLINES is the number of newlines that must be duplicated.
9016 We assume that that much extra space is available past the end
9020 discard_comments (start, length, newlines)
9025 register U_CHAR *ibp;
9026 register U_CHAR *obp;
9027 register U_CHAR *limit;
9030 /* If we have newlines to duplicate, copy everything
9031 that many characters up. Then, in the second part,
9032 we will have room to insert the newlines
9034 NEWLINES may actually be too large, because it counts
9035 newlines in string constants, and we don't duplicate those.
9036 But that does no harm. */
9038 ibp = start + length;
9039 obp = ibp + newlines;
9041 while (limit != ibp)
9045 ibp = start + newlines;
9046 limit = start + length + newlines;
9049 while (ibp < limit) {
9050 *obp++ = c = *ibp++;
9053 /* Duplicate the newline. */
9065 if (*ibp == '\\' && ibp[1] == '\n')
9067 /* Delete any comment. */
9068 if (cplusplus_comments && ibp[0] == '/') {
9069 /* Comments are equivalent to spaces. */
9076 if (*ibp == '\\' && ibp + 1 < limit && ibp[1] == '\n')
9080 #ifdef MULTIBYTE_CHARS
9081 int length = local_mblen (ibp, limit - ibp);
9083 ibp += (length - 1);
9090 if (ibp[0] != '*' || ibp + 1 >= limit)
9092 /* Comments are equivalent to spaces.
9093 For -traditional, a comment is equivalent to nothing. */
9098 while (++ibp < limit) {
9099 if (ibp[0] == '*') {
9100 if (ibp[1] == '\\' && ibp[2] == '\n')
9101 newline_fix (ibp + 1);
9102 if (ibp[1] == '/') {
9109 #ifdef MULTIBYTE_CHARS
9110 int length = local_mblen (ibp, limit - ibp);
9112 ibp += (length - 1);
9120 /* Notice and skip strings, so that we don't
9121 think that comments start inside them,
9122 and so we don't duplicate newlines in them. */
9125 while (ibp < limit) {
9126 *obp++ = c = *ibp++;
9134 else if (c == '\\') {
9135 if (ibp < limit && *ibp == '\n') {
9139 while (*ibp == '\\' && ibp[1] == '\n')
9147 #ifdef MULTIBYTE_CHARS
9150 length = local_mblen (ibp, limit - ibp);
9154 bcopy (ibp, obp, length);
9171 /* Turn newlines to spaces in the string of length LENGTH at START,
9172 except inside of string constants.
9173 The string is copied into itself with its beginning staying fixed. */
9176 change_newlines (start, length)
9180 register U_CHAR *ibp;
9181 register U_CHAR *obp;
9182 register U_CHAR *limit;
9186 limit = start + length;
9189 while (ibp < limit) {
9190 *obp++ = c = *ibp++;
9193 /* If this is a NEWLINE NEWLINE, then this is a real newline in the
9194 string. Skip past the newline and its duplicate.
9195 Put a space in the output. */
9206 /* Notice and skip strings, so that we don't delete newlines in them. */
9209 while (ibp < limit) {
9210 *obp++ = c = *ibp++;
9213 else if (c == '\\' && ibp < limit && *ibp == '\n')
9222 #ifdef MULTIBYTE_CHARS
9225 length = local_mblen (ibp, limit - ibp);
9229 bcopy (ibp, obp, length);
9246 /* my_strerror - return the descriptive text associated with an
9250 my_strerror (errnum)
9256 #ifndef HAVE_STRERROR
9257 result = (char *) ((errnum < sys_nerr) ? sys_errlist[errnum] : 0);
9259 result = strerror (errnum);
9262 /* VAXCRTL's strerror() takes an optional second argument, which only
9263 matters when the first argument is EVMSERR. However, it's simplest
9264 just to pass it unconditionally. `vaxc$errno' is declared in
9265 <errno.h>, and maintained by the library in parallel with `errno'.
9266 We assume that caller's `errnum' either matches the last setting of
9267 `errno' by the library or else does not have the value `EVMSERR'. */
9269 result = strerror (errnum, vaxc$errno);
9273 result = "errno = ?";
9278 /* notice - output message to stderr */
9281 notice VPROTO ((const char * msgid, ...))
9283 #ifndef ANSI_PROTOTYPES
9288 VA_START (args, msgid);
9290 #ifndef ANSI_PROTOTYPES
9291 msgid = va_arg (args, const char *);
9294 vnotice (msgid, args);
9299 vnotice (msgid, args)
9303 vfprintf (stderr, _(msgid), args);
9306 /* error - print error message and increment count of errors. */
9309 error VPROTO ((const char * msgid, ...))
9311 #ifndef ANSI_PROTOTYPES
9316 VA_START (args, msgid);
9318 #ifndef ANSI_PROTOTYPES
9319 msgid = va_arg (args, const char *);
9322 verror (msgid, args);
9327 verror (msgid, args)
9332 FILE_BUF *ip = NULL;
9334 print_containing_files ();
9336 for (i = indepth; i >= 0; i--)
9337 if (instack[i].fname != NULL) {
9343 eprint_string (ip->nominal_fname, ip->nominal_fname_len);
9344 fprintf (stderr, ":%d: ", ip->lineno);
9346 vnotice (msgid, args);
9347 fprintf (stderr, "\n");
9351 /* Error including a message from `errno'. */
9354 error_from_errno (name)
9359 FILE_BUF *ip = NULL;
9361 print_containing_files ();
9363 for (i = indepth; i >= 0; i--)
9364 if (instack[i].fname != NULL) {
9370 eprint_string (ip->nominal_fname, ip->nominal_fname_len);
9371 fprintf (stderr, ":%d: ", ip->lineno);
9374 fprintf (stderr, "%s: %s\n", name, my_strerror (e));
9379 /* Print error message but don't count it. */
9382 warning VPROTO ((const char * msgid, ...))
9384 #ifndef ANSI_PROTOTYPES
9389 VA_START (args, msgid);
9391 #ifndef ANSI_PROTOTYPES
9392 msgid = va_arg (args, const char *);
9395 vwarning (msgid, args);
9400 vwarning (msgid, args)
9405 FILE_BUF *ip = NULL;
9407 if (inhibit_warnings)
9410 if (warnings_are_errors)
9413 print_containing_files ();
9415 for (i = indepth; i >= 0; i--)
9416 if (instack[i].fname != NULL) {
9422 eprint_string (ip->nominal_fname, ip->nominal_fname_len);
9423 fprintf (stderr, ":%d: ", ip->lineno);
9425 notice ("warning: ");
9426 vnotice (msgid, args);
9427 fprintf (stderr, "\n");
9431 error_with_line VPROTO ((int line, const char * msgid, ...))
9433 #ifndef ANSI_PROTOTYPES
9439 VA_START (args, msgid);
9441 #ifndef ANSI_PROTOTYPES
9442 line = va_arg (args, int);
9443 msgid = va_arg (args, const char *);
9446 verror_with_line (line, msgid, args);
9452 verror_with_line (line, msgid, args)
9458 FILE_BUF *ip = NULL;
9460 print_containing_files ();
9462 for (i = indepth; i >= 0; i--)
9463 if (instack[i].fname != NULL) {
9469 eprint_string (ip->nominal_fname, ip->nominal_fname_len);
9470 fprintf (stderr, ":%d: ", line);
9472 vnotice (msgid, args);
9473 fprintf (stderr, "\n");
9478 warning_with_line VPROTO ((int line, const char * msgid, ...))
9480 #ifndef ANSI_PROTOTYPES
9486 VA_START (args, msgid);
9488 #ifndef ANSI_PROTOTYPES
9489 line = va_arg (args, int);
9490 msgid = va_arg (args, const char *);
9493 vwarning_with_line (line, msgid, args);
9498 vwarning_with_line (line, msgid, args)
9504 FILE_BUF *ip = NULL;
9506 if (inhibit_warnings)
9509 if (warnings_are_errors)
9512 print_containing_files ();
9514 for (i = indepth; i >= 0; i--)
9515 if (instack[i].fname != NULL) {
9521 eprint_string (ip->nominal_fname, ip->nominal_fname_len);
9522 fprintf (stderr, line ? ":%d: " : ": ", line);
9524 notice ("warning: ");
9525 vnotice (msgid, args);
9526 fprintf (stderr, "\n");
9529 /* Print an error message and maybe count it. */
9532 pedwarn VPROTO ((const char * msgid, ...))
9534 #ifndef ANSI_PROTOTYPES
9539 VA_START (args, msgid);
9541 #ifndef ANSI_PROTOTYPES
9542 msgid = va_arg (args, const char *);
9545 if (pedantic_errors)
9546 verror (msgid, args);
9548 vwarning (msgid, args);
9553 pedwarn_with_line VPROTO ((int line, const char * msgid, ...))
9555 #ifndef ANSI_PROTOTYPES
9561 VA_START (args, msgid);
9563 #ifndef ANSI_PROTOTYPES
9564 line = va_arg (args, int);
9565 msgid = va_arg (args, const char *);
9568 if (pedantic_errors)
9569 verror_with_line (line, msgid, args);
9571 vwarning_with_line (line, msgid, args);
9575 /* Report a warning (or an error if pedantic_errors)
9576 giving specified file name and line number, not current. */
9579 pedwarn_with_file_and_line VPROTO ((const char *file, size_t file_len, int line,
9580 const char * msgid, ...))
9582 #ifndef ANSI_PROTOTYPES
9590 if (!pedantic_errors && inhibit_warnings)
9593 VA_START (args, msgid);
9595 #ifndef ANSI_PROTOTYPES
9596 file = va_arg (args, const char *);
9597 file_len = va_arg (args, size_t);
9598 line = va_arg (args, int);
9599 msgid = va_arg (args, const char *);
9603 eprint_string (file, file_len);
9604 fprintf (stderr, ":%d: ", line);
9606 if (pedantic_errors)
9608 if (!pedantic_errors)
9609 notice ("warning: ");
9610 vnotice (msgid, args);
9612 fprintf (stderr, "\n");
9616 pedwarn_strange_white_space (ch)
9621 case '\f': pedwarn ("formfeed in preprocessing directive"); break;
9622 case '\r': pedwarn ("carriage return in preprocessing directive"); break;
9623 case '\v': pedwarn ("vertical tab in preprocessing directive"); break;
9628 /* Print the file names and line numbers of the #include
9629 directives which led to the current file. */
9632 print_containing_files ()
9634 FILE_BUF *ip = NULL;
9638 /* If stack of files hasn't changed since we last printed
9639 this info, don't repeat it. */
9640 if (last_error_tick == input_file_stack_tick)
9643 for (i = indepth; i >= 0; i--)
9644 if (instack[i].fname != NULL) {
9649 /* Give up if we don't find a source file. */
9653 /* Find the other, outer source files. */
9654 for (i--; i >= 0; i--)
9655 if (instack[i].fname != NULL) {
9659 notice ( "In file included from ");
9661 notice (",\n from ");
9664 eprint_string (ip->nominal_fname, ip->nominal_fname_len);
9665 fprintf (stderr, ":%d", ip->lineno);
9668 fprintf (stderr, ":\n");
9670 /* Record we have printed the status as of this time. */
9671 last_error_tick = input_file_stack_tick;
9674 /* Return the line at which an error occurred.
9675 The error is not necessarily associated with the current spot
9676 in the input stack, so LINE says where. LINE will have been
9677 copied from ip->lineno for the current input level.
9678 If the current level is for a file, we return LINE.
9679 But if the current level is not for a file, LINE is meaningless.
9680 In that case, we return the lineno of the innermost file. */
9683 line_for_error (line)
9689 for (i = indepth; i >= 0; ) {
9690 if (instack[i].fname != 0)
9695 line1 = instack[i].lineno;
9703 * If OBUF doesn't have NEEDED bytes after OPTR, make it bigger.
9705 * As things stand, nothing is ever placed in the output buffer to be
9706 * removed again except when it's KNOWN to be part of an identifier,
9707 * so flushing and moving down everything left, instead of expanding,
9711 /* You might think void was cleaner for the return type,
9712 but that would get type mismatch in check_expand in strict ANSI. */
9715 grow_outbuf (obuf, needed)
9716 register FILE_BUF *obuf;
9717 register int needed;
9722 if (obuf->length - (obuf->bufp - obuf->buf) > needed)
9725 /* Make it at least twice as big as it is now. */
9727 /* Make it have at least 150% of the free space we will need. */
9728 minsize = (3 * needed) / 2 + (obuf->bufp - obuf->buf);
9729 if (minsize > obuf->length)
9730 obuf->length = minsize;
9732 if ((p = (U_CHAR *) xrealloc (obuf->buf, obuf->length)) == NULL)
9735 obuf->bufp = p + (obuf->bufp - obuf->buf);
9741 /* Symbol table for macro names and special symbols */
9744 * install a name in the main hash table, even if it is already there.
9745 * name stops with first non alphanumeric, except leading '#'.
9746 * caller must check against redefinition if that is desired.
9747 * delete_macro () removes things installed by install () in fifo order.
9748 * this is important because of the `defined' special symbol used
9749 * in #if, and also if pushdef/popdef directives are ever implemented.
9751 * If LEN is >= 0, it is the length of the name.
9752 * Otherwise, compute the length by scanning the entire name.
9754 * If HASH is >= 0, it is the precomputed hash code.
9755 * Otherwise, compute the hash code.
9759 install (name, len, type, value, hash)
9762 enum node_type type;
9766 register HASHNODE *hp;
9767 register int i, bucket;
9768 register U_CHAR *p, *q;
9772 while (is_idchar[*p])
9778 hash = hashf (name, len, HASHSIZE);
9780 i = sizeof (HASHNODE) + len + 1;
9781 hp = (HASHNODE *) xmalloc (i);
9783 hp->bucket_hdr = &hashtab[bucket];
9784 hp->next = hashtab[bucket];
9785 hashtab[bucket] = hp;
9787 if (hp->next != NULL)
9788 hp->next->prev = hp;
9791 hp->value.cpval = value;
9792 hp->name = ((U_CHAR *) hp) + sizeof (HASHNODE);
9795 for (i = 0; i < len; i++)
9802 * find the most recent hash node for name "name" (ending with first
9803 * non-identifier char) installed by install
9805 * If LEN is >= 0, it is the length of the name.
9806 * Otherwise, compute the length by scanning the entire name.
9808 * If HASH is >= 0, it is the precomputed hash code.
9809 * Otherwise, compute the hash code.
9813 lookup (name, len, hash)
9818 register U_CHAR *bp;
9819 register HASHNODE *bucket;
9822 for (bp = name; is_idchar[*bp]; bp++) ;
9827 hash = hashf (name, len, HASHSIZE);
9829 bucket = hashtab[hash];
9831 if (bucket->length == len && bcmp (bucket->name, name, len) == 0)
9833 bucket = bucket->next;
9839 * Delete a hash node. Some weirdness to free junk from macros.
9840 * More such weirdness will have to be added if you define more hash
9841 * types that need it.
9844 /* Note that the DEFINITION of a macro is removed from the hash table
9845 but its storage is not freed. This would be a storage leak
9846 except that it is not reasonable to keep undefining and redefining
9847 large numbers of macros many times.
9848 In any case, this is necessary, because a macro can be #undef'd
9849 in the middle of reading the arguments to a call to it.
9850 If #undef freed the DEFINITION, that would crash. */
9857 if (hp->prev != NULL)
9858 hp->prev->next = hp->next;
9859 if (hp->next != NULL)
9860 hp->next->prev = hp->prev;
9862 /* Make sure that the bucket chain header that the deleted guy was
9863 on points to the right thing afterwards. */
9864 if (hp == *hp->bucket_hdr)
9865 *hp->bucket_hdr = hp->next;
9868 if (hp->type == T_MACRO) {
9869 DEFINITION *d = hp->value.defn;
9870 struct reflist *ap, *nextap;
9872 for (ap = d->pattern; ap != NULL; ap = nextap) {
9883 * return hash function on name. must be compatible with the one
9884 * computed a step at a time, elsewhere
9888 hashf (name, len, hashsize)
9889 register U_CHAR *name;
9896 r = HASHSTEP (r, *name++);
9898 return MAKE_POS (r) % hashsize;
9902 /* Dump the definition of a single macro HP to OF. */
9905 dump_single_macro (hp, of)
9906 register HASHNODE *hp;
9909 register DEFINITION *defn = hp->value.defn;
9915 /* Print the definition of the macro HP. */
9917 fprintf (of, "#define %s", hp->name);
9919 if (defn->nargs >= 0) {
9923 for (i = 0; i < defn->nargs; i++) {
9924 dump_arg_n (defn, i, of);
9925 if (i + 1 < defn->nargs)
9935 for (ap = defn->pattern; ap != NULL; ap = ap->next) {
9936 dump_defn_1 (defn->expansion, offset, ap->nchars, of);
9937 offset += ap->nchars;
9939 if (ap->nchars != 0)
9941 if (ap->stringify) {
9942 switch (ap->stringify) {
9943 case SHARP_TOKEN: fprintf (of, "#"); break;
9944 case WHITE_SHARP_TOKEN: fprintf (of, "# "); break;
9945 case PERCENT_COLON_TOKEN: fprintf (of, "%%:"); break;
9946 case WHITE_PERCENT_COLON_TOKEN: fprintf (of, "%%: "); break;
9950 if (ap->raw_before != 0) {
9952 switch (ap->raw_before) {
9953 case WHITE_SHARP_TOKEN:
9954 case WHITE_PERCENT_COLON_TOKEN:
9961 switch (ap->raw_before) {
9962 case SHARP_TOKEN: fprintf (of, "##"); break;
9963 case WHITE_SHARP_TOKEN: fprintf (of, "## "); break;
9964 case PERCENT_COLON_TOKEN: fprintf (of, "%%:%%:"); break;
9965 case WHITE_PERCENT_COLON_TOKEN: fprintf (of, "%%:%%: "); break;
9972 dump_arg_n (defn, ap->argno, of);
9973 if (!traditional && ap->raw_after != 0) {
9974 switch (ap->raw_after) {
9975 case SHARP_TOKEN: fprintf (of, "##"); break;
9976 case WHITE_SHARP_TOKEN: fprintf (of, " ##"); break;
9977 case PERCENT_COLON_TOKEN: fprintf (of, "%%:%%:"); break;
9978 case WHITE_PERCENT_COLON_TOKEN: fprintf (of, " %%:%%:"); break;
9984 dump_defn_1 (defn->expansion, offset, defn->length - offset, of);
9988 /* Dump all macro definitions as #defines to stdout. */
9995 for (bucket = 0; bucket < HASHSIZE; bucket++) {
9996 register HASHNODE *hp;
9998 for (hp = hashtab[bucket]; hp; hp= hp->next) {
9999 if (hp->type == T_MACRO)
10000 dump_single_macro (hp, stdout);
10005 /* Output to OF a substring of a macro definition.
10006 BASE is the beginning of the definition.
10007 Output characters START thru LENGTH.
10008 Unless traditional, discard newlines outside of strings, thus
10009 converting funny-space markers to ordinary spaces. */
10012 dump_defn_1 (base, start, length, of)
10018 U_CHAR *p = base + start;
10019 U_CHAR *limit = base + start + length;
10022 fwrite (p, sizeof (*p), length, of);
10024 while (p < limit) {
10025 if (*p == '\"' || *p =='\'') {
10026 U_CHAR *p1 = skip_quoted_string (p, limit, 0, NULL_PTR,
10027 NULL_PTR, NULL_PTR);
10028 fwrite (p, sizeof (*p), p1 - p, of);
10039 /* Print the name of argument number ARGNUM of macro definition DEFN
10041 Recall that DEFN->args.argnames contains all the arg names
10042 concatenated in reverse order with comma-space in between. */
10045 dump_arg_n (defn, argnum, of)
10050 register U_CHAR *p = defn->args.argnames;
10051 while (argnum + 1 < defn->nargs) {
10052 p = (U_CHAR *) index ((char *) p, ' ') + 1;
10056 while (*p && *p != ',') {
10062 /* Initialize syntactic classifications of characters. */
10065 initialize_char_syntax ()
10070 * Set up is_idchar and is_idstart tables. These should be
10071 * faster than saying (is_alpha (c) || c == '_'), etc.
10072 * Set up these things before calling any routines tthat
10075 for (i = 'a'; i <= 'z'; i++) {
10076 is_idchar[i - 'a' + 'A'] = 1;
10078 is_idstart[i - 'a' + 'A'] = 1;
10081 for (i = '0'; i <= '9'; i++)
10083 is_idchar['_'] = 1;
10084 is_idstart['_'] = 1;
10085 is_idchar['$'] = 1;
10086 is_idstart['$'] = 1;
10088 /* horizontal space table */
10089 is_hor_space[' '] = 1;
10090 is_hor_space['\t'] = 1;
10091 is_hor_space['\v'] = 1;
10092 is_hor_space['\f'] = 1;
10093 is_hor_space['\r'] = 1;
10096 is_space['\t'] = 1;
10097 is_space['\v'] = 1;
10098 is_space['\f'] = 1;
10099 is_space['\n'] = 1;
10100 is_space['\r'] = 1;
10103 /* Initialize the built-in macros. */
10106 initialize_builtins (inp, outp)
10110 install ((U_CHAR *) "__LINE__", -1, T_SPECLINE, NULL_PTR, -1);
10111 install ((U_CHAR *) "__DATE__", -1, T_DATE, NULL_PTR, -1);
10112 install ((U_CHAR *) "__FILE__", -1, T_FILE, NULL_PTR, -1);
10113 install ((U_CHAR *) "__BASE_FILE__", -1, T_BASE_FILE, NULL_PTR, -1);
10114 install ((U_CHAR *) "__INCLUDE_LEVEL__", -1, T_INCLUDE_LEVEL, NULL_PTR, -1);
10115 install ((U_CHAR *) "__VERSION__", -1, T_VERSION, NULL_PTR, -1);
10116 #ifndef NO_BUILTIN_SIZE_TYPE
10117 install ((U_CHAR *) "__SIZE_TYPE__", -1, T_SIZE_TYPE, NULL_PTR, -1);
10119 #ifndef NO_BUILTIN_PTRDIFF_TYPE
10120 install ((U_CHAR *) "__PTRDIFF_TYPE__ ", -1, T_PTRDIFF_TYPE, NULL_PTR, -1);
10122 install ((U_CHAR *) "__WCHAR_TYPE__", -1, T_WCHAR_TYPE, NULL_PTR, -1);
10123 install ((U_CHAR *) "__USER_LABEL_PREFIX__", -1, T_USER_LABEL_PREFIX_TYPE,
10125 install ((U_CHAR *) "__REGISTER_PREFIX__", -1, T_REGISTER_PREFIX_TYPE,
10127 install ((U_CHAR *) "__IMMEDIATE_PREFIX__", -1, T_IMMEDIATE_PREFIX_TYPE,
10129 install ((U_CHAR *) "__TIME__", -1, T_TIME, NULL_PTR, -1);
10130 if (!traditional) {
10131 install ((U_CHAR *) "__STDC__", -1, T_CONST, "1", -1);
10132 install ((U_CHAR *) "__STDC_VERSION__", -1, T_CONST, "199409L", -1);
10134 /* This is supplied using a -D by the compiler driver
10135 so that it is present only when truly compiling with GNU C. */
10136 /* install ((U_CHAR *) "__GNUC__", -1, T_CONST, "2", -1); */
10137 install ((U_CHAR *) "__HAVE_BUILTIN_SETJMP__", -1, T_CONST, "1", -1);
10141 char directive[2048];
10142 U_CHAR *udirective = (U_CHAR *) directive;
10143 register struct directive *dp = &directive_table[0];
10144 struct tm *timebuf = timestamp ();
10146 sprintf (directive, " __BASE_FILE__ \"%s\"\n",
10147 instack[0].nominal_fname);
10148 output_line_directive (inp, outp, 0, same_file);
10149 pass_thru_directive (udirective, &udirective[strlen (directive)],
10152 sprintf (directive, " __VERSION__ \"%s\"\n", version_string);
10153 output_line_directive (inp, outp, 0, same_file);
10154 pass_thru_directive (udirective, &udirective[strlen (directive)],
10157 #ifndef NO_BUILTIN_SIZE_TYPE
10158 sprintf (directive, " __SIZE_TYPE__ %s\n", SIZE_TYPE);
10159 output_line_directive (inp, outp, 0, same_file);
10160 pass_thru_directive (udirective, &udirective[strlen (directive)],
10164 #ifndef NO_BUILTIN_PTRDIFF_TYPE
10165 sprintf (directive, " __PTRDIFF_TYPE__ %s\n", PTRDIFF_TYPE);
10166 output_line_directive (inp, outp, 0, same_file);
10167 pass_thru_directive (udirective, &udirective[strlen (directive)],
10171 sprintf (directive, " __WCHAR_TYPE__ %s\n", wchar_type);
10172 output_line_directive (inp, outp, 0, same_file);
10173 pass_thru_directive (udirective, &udirective[strlen (directive)],
10176 sprintf (directive, " __DATE__ \"%s %2d %4d\"\n",
10177 monthnames[timebuf->tm_mon],
10178 timebuf->tm_mday, timebuf->tm_year + 1900);
10179 output_line_directive (inp, outp, 0, same_file);
10180 pass_thru_directive (udirective, &udirective[strlen (directive)],
10183 sprintf (directive, " __TIME__ \"%02d:%02d:%02d\"\n",
10184 timebuf->tm_hour, timebuf->tm_min, timebuf->tm_sec);
10185 output_line_directive (inp, outp, 0, same_file);
10186 pass_thru_directive (udirective, &udirective[strlen (directive)],
10191 sprintf (directive, " __STDC__ 1");
10192 output_line_directive (inp, outp, 0, same_file);
10193 pass_thru_directive (udirective, &udirective[strlen (directive)],
10198 sprintf (directive, " __OBJC__ 1");
10199 output_line_directive (inp, outp, 0, same_file);
10200 pass_thru_directive (udirective, &udirective[strlen (directive)],
10207 * process a given definition string, for initialization
10208 * If STR is just an identifier, define it with value 1.
10209 * If STR has anything after the identifier, then it should
10210 * be identifier=definition.
10214 make_definition (str)
10218 struct directive *kt;
10221 p = buf = (U_CHAR *) str;
10222 if (!is_idstart[*p]) {
10223 error ("malformed option `-D %s'", str);
10226 while (is_idchar[*++p])
10229 while (is_idchar[*++p] || *p == ',' || is_hor_space[*p])
10232 p = (U_CHAR *) str; /* Error */
10235 buf = (U_CHAR *) alloca (p - buf + 4);
10236 strcpy ((char *)buf, str);
10237 strcat ((char *)buf, " 1");
10238 } else if (*p != '=') {
10239 error ("malformed option `-D %s'", str);
10243 /* Copy the entire option so we can modify it. */
10244 buf = (U_CHAR *) alloca (2 * strlen (str) + 1);
10245 strncpy ((char *) buf, str, p - (U_CHAR *) str);
10246 /* Change the = to a space. */
10247 buf[p - (U_CHAR *) str] = ' ';
10248 /* Scan for any backslash-newline and remove it. */
10250 q = &buf[p - (U_CHAR *) str];
10252 if (*p == '\"' || *p == '\'') {
10253 int unterminated = 0;
10254 U_CHAR *p1 = skip_quoted_string (p, p + strlen ((char *) p), 0,
10255 NULL_PTR, NULL_PTR, &unterminated);
10260 } else if (*p == '\\' && p[1] == '\n')
10262 /* Change newline chars into newline-markers. */
10263 else if (*p == '\n')
10275 ip = &instack[++indepth];
10276 ip->nominal_fname = ip->fname = "*Initialization*";
10277 ip->nominal_fname_len = strlen (ip->nominal_fname);
10279 ip->buf = ip->bufp = buf;
10280 ip->length = strlen ((char *) buf);
10284 ip->if_stack = if_stack;
10285 ip->system_header_p = 0;
10287 for (kt = directive_table; kt->type != T_DEFINE; kt++)
10290 /* Pass NULL instead of OP, since this is a "predefined" macro. */
10291 do_define (buf, buf + strlen ((char *) buf), NULL_PTR, kt);
10295 /* JF, this does the work for the -U option */
10298 make_undef (str, op)
10303 struct directive *kt;
10305 ip = &instack[++indepth];
10306 ip->nominal_fname = ip->fname = "*undef*";
10307 ip->nominal_fname_len = strlen (ip->nominal_fname);
10309 ip->buf = ip->bufp = (U_CHAR *) str;
10310 ip->length = strlen (str);
10314 ip->if_stack = if_stack;
10315 ip->system_header_p = 0;
10317 for (kt = directive_table; kt->type != T_UNDEF; kt++)
10320 do_undef ((U_CHAR *) str, (U_CHAR *) str + strlen (str), op, kt);
10324 /* Process the string STR as if it appeared as the body of a #assert.
10325 OPTION is the option name for which STR was the argument. */
10328 make_assertion (option, str)
10329 const char *option;
10333 struct directive *kt;
10334 U_CHAR *buf, *p, *q;
10336 /* Copy the entire option so we can modify it. */
10337 buf = (U_CHAR *) alloca (strlen (str) + 1);
10338 strcpy ((char *) buf, str);
10339 /* Scan for any backslash-newline and remove it. */
10342 if (*p == '\\' && p[1] == '\n')
10350 if (!is_idstart[*p]) {
10351 error ("malformed option `%s %s'", option, str);
10354 while (is_idchar[*++p])
10356 SKIP_WHITE_SPACE (p);
10357 if (! (*p == 0 || *p == '(')) {
10358 error ("malformed option `%s %s'", option, str);
10362 ip = &instack[++indepth];
10363 ip->nominal_fname = ip->fname = "*Initialization*";
10364 ip->nominal_fname_len = strlen (ip->nominal_fname);
10366 ip->buf = ip->bufp = buf;
10367 ip->length = strlen ((char *) buf);
10371 ip->if_stack = if_stack;
10372 ip->system_header_p = 0;
10374 for (kt = directive_table; kt->type != T_ASSERT; kt++)
10377 /* Pass NULL as output ptr to do_define since we KNOW it never does
10379 do_assert (buf, buf + strlen ((char *) buf) , NULL_PTR, kt);
10383 /* The previous include prefix, if any, is PREV_FILE_NAME.
10384 Translate any pathnames with COMPONENT.
10385 Allocate a new include prefix whose name is the
10386 simplified concatenation of PREFIX and NAME,
10387 with a trailing / added if needed.
10388 But return 0 if the include prefix should be ignored,
10389 e.g. because it is a duplicate of PREV_FILE_NAME. */
10391 static struct file_name_list *
10392 new_include_prefix (prev_file_name, component, prefix, name)
10393 struct file_name_list *prev_file_name;
10394 const char *component;
10395 const char *prefix;
10399 fatal ("Directory name missing after command line option");
10402 /* Ignore the empty string. */
10405 prefix = update_path (prefix, component);
10406 name = update_path (name, component);
10409 struct file_name_list *dir
10410 = ((struct file_name_list *)
10411 xmalloc (sizeof (struct file_name_list)
10412 + strlen (prefix) + strlen (name) + 2));
10414 strcpy (dir->fname, prefix);
10415 strcat (dir->fname, name);
10416 len = simplify_filename (dir->fname);
10418 /* Convert directory name to a prefix. */
10419 if (len && dir->fname[len - 1] != DIR_SEPARATOR) {
10420 if (len == 1 && dir->fname[len - 1] == '.')
10424 /* must be '/', hack_vms_include_specification triggers on it. */
10425 dir->fname[len++] = '/';
10427 dir->fname[len++] = DIR_SEPARATOR;
10429 dir->fname[len] = 0;
10432 /* Ignore a directory whose name matches the previous one. */
10433 if (prev_file_name && !strcmp (prev_file_name->fname, dir->fname)) {
10434 /* But treat `-Idir -I- -Idir' as `-I- -Idir'. */
10435 if (!first_bracket_include)
10436 first_bracket_include = prev_file_name;
10442 /* VMS can't stat dir prefixes, so skip these optimizations in VMS. */
10444 /* Add a trailing "." if there is a filename. This increases the number
10445 of systems that can stat directories. We remove it below. */
10448 dir->fname[len] = '.';
10449 dir->fname[len + 1] = 0;
10452 /* Ignore a nonexistent directory. */
10453 if (stat (len ? dir->fname : ".", &dir->st) != 0) {
10454 if (errno != ENOENT && errno != ENOTDIR)
10455 error_from_errno (dir->fname);
10461 dir->fname[len] = 0;
10463 /* Ignore a directory whose identity matches the previous one. */
10465 && INO_T_EQ (prev_file_name->st.st_ino, dir->st.st_ino)
10466 && prev_file_name->st.st_dev == dir->st.st_dev) {
10467 /* But treat `-Idir -I- -Idir' as `-I- -Idir'. */
10468 if (!first_bracket_include)
10469 first_bracket_include = prev_file_name;
10476 dir->c_system_include_path = 0;
10477 dir->got_name_map = 0;
10483 /* Append a chain of `struct file_name_list's
10484 to the end of the main include chain.
10485 FIRST is the beginning of the chain to append, and LAST is the end. */
10488 append_include_chain (first, last)
10489 struct file_name_list *first, *last;
10491 struct file_name_list *dir;
10493 if (!first || !last)
10499 last_include->next = first;
10501 if (first_bracket_include == 0)
10502 first_bracket_include = first;
10504 for (dir = first; ; dir = dir->next) {
10505 int len = strlen (dir->fname) + INCLUDE_LEN_FUDGE;
10506 if (len > max_include_len)
10507 max_include_len = len;
10513 last_include = last;
10516 /* Place into DST a representation of the file named SRC that is suitable
10517 for `make'. Do not null-terminate DST. Return its length. */
10519 quote_string_for_make (dst, src)
10523 const char *p = src;
10534 /* GNU make uses a weird quoting scheme for white space.
10535 A space or tab preceded by 2N+1 backslashes represents
10536 N backslashes followed by space; a space or tab
10537 preceded by 2N backslashes represents N backslashes at
10538 the end of a file name; and backslashes in other
10539 contexts should not be doubled. */
10541 for (q = p - 1; src < q && q[-1] == '\\'; q--)
10553 goto ordinary_char;
10559 /* Fall through. This can mishandle things like "$(" but
10560 there's no easy fix. */
10563 /* This can mishandle characters in the string "\0\n%*?[\\~";
10564 exactly which chars are mishandled depends on the `make' version.
10565 We know of no portable solution for this;
10566 even GNU make 3.76.1 doesn't solve the problem entirely.
10567 (Also, '\0' is mishandled due to our calling conventions.) */
10577 /* Add output to `deps_buffer' for the -M switch.
10578 STRING points to the text to be output.
10579 SPACER is ':' for targets, ' ' for dependencies. */
10582 deps_output (string, spacer)
10583 const char *string;
10586 int size = quote_string_for_make ((char *) 0, string);
10591 #ifndef MAX_OUTPUT_COLUMNS
10592 #define MAX_OUTPUT_COLUMNS 72
10594 if (MAX_OUTPUT_COLUMNS - 1 /*spacer*/ - 2 /*` \'*/ < deps_column + size
10595 && 1 < deps_column) {
10596 bcopy (" \\\n ", &deps_buffer[deps_size], 4);
10603 if (deps_size + 2 * size + 8 > deps_allocated_size) {
10604 deps_allocated_size = (deps_size + 2 * size + 50) * 2;
10605 deps_buffer = xrealloc (deps_buffer, deps_allocated_size);
10607 if (spacer == ' ') {
10608 deps_buffer[deps_size++] = ' ';
10611 quote_string_for_make (&deps_buffer[deps_size], string);
10613 deps_column += size;
10614 if (spacer == ':') {
10615 deps_buffer[deps_size++] = ':';
10618 deps_buffer[deps_size] = 0;
10622 fatal VPROTO ((const char * msgid, ...))
10624 #ifndef ANSI_PROTOTYPES
10625 const char * msgid;
10629 fprintf (stderr, "%s: ", progname);
10630 VA_START (args, msgid);
10632 #ifndef ANSI_PROTOTYPES
10633 msgid = va_arg (args, const char *);
10635 vnotice (msgid, args);
10637 fprintf (stderr, "\n");
10638 exit (FATAL_EXIT_CODE);
10641 /* More 'friendly' abort that prints the line and file.
10642 config.h can #define abort fancy_abort if you like that sort of thing. */
10647 fatal ("Internal gcc abort.");
10651 perror_with_name (name)
10654 fprintf (stderr, "%s: %s: %s\n", progname, name, my_strerror (errno));
10659 pfatal_with_name (name)
10662 perror_with_name (name);
10666 exit (FATAL_EXIT_CODE);
10670 /* Handler for SIGPIPE. */
10673 pipe_closed (signo)
10674 /* If this is missing, some compilers complain. */
10675 int signo ATTRIBUTE_UNUSED;
10677 fatal ("output pipe has been closed");
10683 fatal ("Memory exhausted.");
10690 register PTR ptr = (PTR) malloc (size);
10697 xrealloc (old, size)
10703 ptr = (PTR) realloc (old, size);
10705 ptr = (PTR) malloc (size);
10712 xcalloc (number, size)
10713 size_t number, size;
10715 register size_t total = number * size;
10716 register PTR ptr = (PTR) malloc (total);
10719 bzero (ptr, total);
10727 register size_t len = strlen (input) + 1;
10728 register char *output = xmalloc (len);
10729 memcpy (output, input, len);
10735 /* Under VMS we need to fix up the "include" specification filename.
10737 Rules for possible conversions
10739 fullname tried paths
10742 ./dir/name [.dir]name
10744 /name [000000]name, name
10745 dir/name dir:[000000]name, dir:name, dir/name
10746 dir1/dir2/name dir1:[dir2]name, dir1:[000000.dir2]name
10747 path:/name path:[000000]name, path:name
10748 path:/dir/name path:[000000.dir]name, path:[dir]name
10749 path:dir/name path:[dir]name
10750 [path]:[dir]name [path.dir]name
10751 path/[dir]name [path.dir]name
10753 The path:/name input is constructed when expanding <> includes.
10755 return 1 if name was changed, 0 else. */
10758 hack_vms_include_specification (fullname, vaxc_include)
10762 register char *basename, *unixname, *local_ptr, *first_slash;
10763 int f, check_filename_before_returning, must_revert;
10766 check_filename_before_returning = 0;
10768 /* See if we can find a 1st slash. If not, there's no path information. */
10769 first_slash = index (fullname, '/');
10770 if (first_slash == 0)
10771 return 0; /* Nothing to do!!! */
10773 /* construct device spec if none given. */
10775 if (index (fullname, ':') == 0)
10778 /* If fullname has a slash, take it as device spec. */
10780 if (first_slash == fullname)
10782 first_slash = index (fullname+1, '/'); /* 2nd slash ? */
10784 *first_slash = ':'; /* make device spec */
10785 for (basename = fullname; *basename != 0; basename++)
10786 *basename = *(basename+1); /* remove leading slash */
10788 else if ((first_slash[-1] != '.') /* keep ':/', './' */
10789 && (first_slash[-1] != ':')
10790 && (first_slash[-1] != ']')) /* or a vms path */
10792 *first_slash = ':';
10794 else if ((first_slash[1] == '[') /* skip './' in './[dir' */
10795 && (first_slash[-1] == '.'))
10799 /* Get part after first ':' (basename[-1] == ':')
10800 or last '/' (basename[-1] == '/'). */
10802 basename = base_name (fullname);
10805 * Check if we have a vax-c style '#include filename'
10806 * and add the missing .h
10809 if (vaxc_include && !index (basename,'.'))
10810 strcat (basename, ".h");
10812 local_ptr = Local; /* initialize */
10814 /* We are trying to do a number of things here. First of all, we are
10815 trying to hammer the filenames into a standard format, such that later
10816 processing can handle them.
10818 If the file name contains something like [dir.], then it recognizes this
10819 as a root, and strips the ".]". Later processing will add whatever is
10820 needed to get things working properly.
10822 If no device is specified, then the first directory name is taken to be
10823 a device name (or a rooted logical). */
10825 /* Point to the UNIX filename part (which needs to be fixed!)
10826 but skip vms path information.
10827 [basename != fullname since first_slash != 0]. */
10829 if ((basename[-1] == ':') /* vms path spec. */
10830 || (basename[-1] == ']')
10831 || (basename[-1] == '>'))
10832 unixname = basename;
10834 unixname = fullname;
10836 if (*unixname == '/')
10839 /* If the directory spec is not rooted, we can just copy
10840 the UNIX filename part and we are done. */
10842 if (((basename - fullname) > 1)
10843 && ( (basename[-1] == ']')
10844 || (basename[-1] == '>')))
10846 if (basename[-2] != '.')
10849 /* The VMS part ends in a `]', and the preceding character is not a `.'.
10850 -> PATH]:/name (basename = '/name', unixname = 'name')
10851 We strip the `]', and then splice the two parts of the name in the
10852 usual way. Given the default locations for include files in cccp.c,
10853 we will only use this code if the user specifies alternate locations
10854 with the /include (-I) switch on the command line. */
10856 basename -= 1; /* Strip "]" */
10857 unixname--; /* backspace */
10862 /* The VMS part has a ".]" at the end, and this will not do. Later
10863 processing will add a second directory spec, and this would be a syntax
10864 error. Thus we strip the ".]", and thus merge the directory specs.
10865 We also backspace unixname, so that it points to a '/'. This inhibits the
10866 generation of the 000000 root directory spec (which does not belong here
10869 basename -= 2; /* Strip ".]" */
10870 unixname--; /* backspace */
10878 /* We drop in here if there is no VMS style directory specification yet.
10879 If there is no device specification either, we make the first dir a
10880 device and try that. If we do not do this, then we will be essentially
10881 searching the users default directory (as if they did a #include "asdf.h").
10883 Then all we need to do is to push a '[' into the output string. Later
10884 processing will fill this in, and close the bracket. */
10886 if ((unixname != fullname) /* vms path spec found. */
10887 && (basename[-1] != ':'))
10888 *local_ptr++ = ':'; /* dev not in spec. take first dir */
10890 *local_ptr++ = '['; /* Open the directory specification */
10893 if (unixname == fullname) /* no vms dir spec. */
10896 if ((first_slash != 0) /* unix dir spec. */
10897 && (*unixname != '/') /* not beginning with '/' */
10898 && (*unixname != '.')) /* or './' or '../' */
10899 *local_ptr++ = '.'; /* dir is local ! */
10902 /* at this point we assume that we have the device spec, and (at least
10903 the opening "[" for a directory specification. We may have directories
10906 If there are no other slashes then the filename will be
10907 in the "root" directory. Otherwise, we need to add
10908 directory specifications. */
10910 if (index (unixname, '/') == 0)
10912 /* if no directories specified yet and none are following. */
10913 if (local_ptr[-1] == '[')
10915 /* Just add "000000]" as the directory string */
10916 strcpy (local_ptr, "000000]");
10917 local_ptr += strlen (local_ptr);
10918 check_filename_before_returning = 1; /* we might need to fool with this later */
10924 /* As long as there are still subdirectories to add, do them. */
10925 while (index (unixname, '/') != 0)
10927 /* If this token is "." we can ignore it
10928 if it's not at the beginning of a path. */
10929 if ((unixname[0] == '.') && (unixname[1] == '/'))
10931 /* remove it at beginning of path. */
10932 if ( ((unixname == fullname) /* no device spec */
10933 && (fullname+2 != basename)) /* starts with ./ */
10935 || ((basename[-1] == ':') /* device spec */
10936 && (unixname-1 == basename))) /* and ./ afterwards */
10937 *local_ptr++ = '.'; /* make '[.' start of path. */
10942 /* Add a subdirectory spec. Do not duplicate "." */
10943 if ( local_ptr[-1] != '.'
10944 && local_ptr[-1] != '['
10945 && local_ptr[-1] != '<')
10946 *local_ptr++ = '.';
10948 /* If this is ".." then the spec becomes "-" */
10949 if ( (unixname[0] == '.')
10950 && (unixname[1] == '.')
10951 && (unixname[2] == '/'))
10953 /* Add "-" and skip the ".." */
10954 if ((local_ptr[-1] == '.')
10955 && (local_ptr[-2] == '['))
10956 local_ptr--; /* prevent [.- */
10957 *local_ptr++ = '-';
10962 /* Copy the subdirectory */
10963 while (*unixname != '/')
10964 *local_ptr++= *unixname++;
10966 unixname++; /* Skip the "/" */
10969 /* Close the directory specification */
10970 if (local_ptr[-1] == '.') /* no trailing periods */
10973 if (local_ptr[-1] == '[') /* no dir needed */
10976 *local_ptr++ = ']';
10979 /* Now add the filename. */
10982 *local_ptr++ = *unixname++;
10985 /* Now append it to the original VMS spec. */
10987 strcpy ((must_revert==1)?fullname:basename, Local);
10989 /* If we put a [000000] in the filename, try to open it first. If this fails,
10990 remove the [000000], and return that name. This provides flexibility
10991 to the user in that they can use both rooted and non-rooted logical names
10992 to point to the location of the file. */
10994 if (check_filename_before_returning)
10996 f = open (fullname, O_RDONLY, 0666);
10999 /* The file name is OK as it is, so return it as is. */
11004 /* The filename did not work. Try to remove the [000000] from the name,
11007 basename = index (fullname, '[');
11008 local_ptr = index (fullname, ']') + 1;
11009 strcpy (basename, local_ptr); /* this gets rid of it */
11019 /* The following wrapper functions supply additional arguments to the VMS
11020 I/O routines to optimize performance with file handling. The arguments
11022 "mbc=16" - Set multi-block count to 16 (use a 8192 byte buffer).
11023 "deq=64" - When extending the file, extend it in chunks of 32Kbytes.
11024 "fop=tef"- Truncate unused portions of file when closing file.
11025 "shr=nil"- Disallow file sharing while file is open. */
11028 VMS_freopen (fname, type, oldfile)
11033 #undef freopen /* Get back the real freopen routine. */
11034 if (strcmp (type, "w") == 0)
11035 return freopen (fname, type, oldfile,
11036 "mbc=16", "deq=64", "fop=tef", "shr=nil");
11037 return freopen (fname, type, oldfile, "mbc=16");
11041 VMS_fopen (fname, type)
11045 #undef fopen /* Get back the real fopen routine. */
11046 /* The gcc-vms-1.42 distribution's header files prototype fopen with two
11047 fixed arguments, which matches ANSI's specification but not VAXCRTL's
11048 pre-ANSI implementation. This hack circumvents the mismatch problem. */
11049 FILE *(*vmslib_fopen)() = (FILE *(*)()) fopen;
11052 return (*vmslib_fopen) (fname, type, "mbc=32",
11053 "deq=64", "fop=tef", "shr=nil");
11055 return (*vmslib_fopen) (fname, type, "mbc=32");
11059 VMS_open (fname, flags, prot)
11064 #undef open /* Get back the real open routine. */
11065 return open (fname, flags, prot, "mbc=16", "deq=64", "fop=tef");
11068 /* more VMS hackery */
11072 extern unsigned long SYS$PARSE(), SYS$SEARCH();
11074 /* Work around another library bug. If a file is located via a searchlist,
11075 and if the device it's on is not the same device as the one specified
11076 in the first element of that searchlist, then both stat() and fstat()
11077 will fail to return info about it. `errno' will be set to EVMSERR, and
11078 `vaxc$errno' will be set to SS$_NORMAL due yet another bug in stat()!
11079 We can get around this by fully parsing the filename and then passing
11080 that absolute name to stat().
11082 Without this fix, we can end up failing to find header files, which is
11083 bad enough, but then compounding the problem by reporting the reason for
11084 failure as "normal successful completion." */
11086 #undef fstat /* Get back to the library version. */
11089 VMS_fstat (fd, statbuf)
11091 struct stat *statbuf;
11093 int result = fstat (fd, statbuf);
11098 char nambuf[NAM$C_MAXRSS+1];
11100 if ((fp = fdopen (fd, "r")) != 0 && fgetname (fp, nambuf) != 0)
11101 result = VMS_stat (nambuf, statbuf);
11102 /* No fclose(fp) here; that would close(fd) as well. */
11109 VMS_stat (name, statbuf)
11111 struct stat *statbuf;
11113 int result = stat (name, statbuf);
11119 char exp_nam[NAM$C_MAXRSS+1], /* expanded name buffer for SYS$PARSE */
11120 res_nam[NAM$C_MAXRSS+1]; /* resultant name buffer for SYS$SEARCH */
11123 fab.fab$l_fna = (char *) name;
11124 fab.fab$b_fns = (unsigned char) strlen (name);
11125 fab.fab$l_nam = (void *) &nam;
11127 nam.nam$l_esa = exp_nam, nam.nam$b_ess = sizeof exp_nam - 1;
11128 nam.nam$l_rsa = res_nam, nam.nam$b_rss = sizeof res_nam - 1;
11129 nam.nam$b_nop = NAM$M_PWD | NAM$M_NOCONCEAL;
11130 if (SYS$PARSE (&fab) & 1)
11132 if (SYS$SEARCH (&fab) & 1)
11134 res_nam[nam.nam$b_rsl] = '\0';
11135 result = stat (res_nam, statbuf);
11137 /* Clean up searchlist context cached by the system. */
11138 nam.nam$b_nop = NAM$M_SYNCHK;
11139 fab.fab$l_fna = 0, fab.fab$b_fns = 0;
11140 (void) SYS$PARSE (&fab);