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.3 2004/04/07 14:02:40 joerg 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 },
399 { GPLUSPLUS_INCLUDE_DIR2, "G++", 1, 1, 0 },
401 /* This is the dir for fixincludes. Put it just before
402 the files that we fix. */
403 { GCC_INCLUDE_DIR, "GCC", 0, 0, 0 },
404 /* For cross-compilation, this dir name is generated
405 automatically in Makefile.in. */
406 { CROSS_INCLUDE_DIR, "GCC", 0, 0, 0 },
407 #ifdef TOOL_INCLUDE_DIR
408 /* This is another place that the target system's headers might be. */
409 { TOOL_INCLUDE_DIR, "BINUTILS", 0, 0, 0 },
411 #else /* not CROSS_COMPILE */
412 #ifdef LOCAL_INCLUDE_DIR
413 /* This should be /usr/local/include and should come before
414 the fixincludes-fixed header files. */
415 { LOCAL_INCLUDE_DIR, 0, 0, 1, 0 },
417 #ifdef TOOL_INCLUDE_DIR
418 /* This is here ahead of GCC_INCLUDE_DIR because assert.h goes here.
419 Likewise, behind LOCAL_INCLUDE_DIR, where glibc puts its assert.h. */
420 { TOOL_INCLUDE_DIR, "BINUTILS", 0, 0, 0 },
422 /* This is the dir for fixincludes. Put it just before
423 the files that we fix. */
424 { GCC_INCLUDE_DIR, "GCC", 0, 0, 0 },
425 /* Some systems have an extra dir of include files. */
426 #ifdef SYSTEM_INCLUDE_DIR
427 { SYSTEM_INCLUDE_DIR, 0, 0, 0, 0 },
429 #ifndef STANDARD_INCLUDE_COMPONENT
430 #define STANDARD_INCLUDE_COMPONENT 0
432 { STANDARD_INCLUDE_DIR, STANDARD_INCLUDE_COMPONENT, 0, 0, 0 },
433 #endif /* not CROSS_COMPILE */
436 #endif /* no INCLUDE_DEFAULTS */
438 /* The code looks at the defaults through this pointer, rather than through
439 the constant structure above. This pointer gets changed if an environment
440 variable specifies other defaults. */
441 static struct default_include *include_defaults = include_defaults_array;
443 static struct file_name_list *include = 0; /* First dir to search */
444 /* First dir to search for <file> */
445 /* This is the first element to use for #include <...>.
446 If it is 0, use the entire chain for such includes. */
447 static struct file_name_list *first_bracket_include = 0;
448 /* This is the first element in the chain that corresponds to
449 a directory of system header files. */
450 static struct file_name_list *first_system_include = 0;
451 static struct file_name_list *last_include = 0; /* Last in chain */
453 /* Chain of include directories to put at the end of the other chain. */
454 static struct file_name_list *after_include = 0;
455 static struct file_name_list *last_after_include = 0; /* Last in chain */
457 /* Chain to put at the start of the system include files. */
458 static struct file_name_list *before_system = 0;
459 static struct file_name_list *last_before_system = 0; /* Last in chain */
461 /* Directory prefix that should replace `/usr' in the standard
462 include file directories. */
463 static char *include_prefix;
465 /* Maintain and search list of included files. */
467 struct include_file {
468 struct include_file *next; /* for include_hashtab */
469 struct include_file *next_ino; /* for include_ino_hashtab */
471 /* If the following is the empty string, it means #pragma once
472 was seen in this include file, or #import was applied to the file.
473 Otherwise, if it is nonzero, it is a macro name.
474 Don't include the file again if that macro is defined. */
475 U_CHAR *control_macro;
476 /* Nonzero if the dependency on this include file has been output. */
481 /* Hash tables of files already included with #include or #import.
482 include_hashtab is by full name; include_ino_hashtab is by inode number. */
484 #define INCLUDE_HASHSIZE 61
485 static struct include_file *include_hashtab[INCLUDE_HASHSIZE];
486 static struct include_file *include_ino_hashtab[INCLUDE_HASHSIZE];
488 /* Global list of strings read in from precompiled files. This list
489 is kept in the order the strings are read in, with new strings being
490 added at the end through stringlist_tailp. We use this list to output
491 the strings at the end of the run.
493 static STRINGDEF *stringlist;
494 static STRINGDEF **stringlist_tailp = &stringlist;
497 /* Structure returned by create_definition */
498 typedef struct macrodef MACRODEF;
501 struct definition *defn;
506 enum sharp_token_type {
507 NO_SHARP_TOKEN = 0, /* token not present */
509 SHARP_TOKEN = '#', /* token spelled with # only */
510 WHITE_SHARP_TOKEN, /* token spelled with # and white space */
512 PERCENT_COLON_TOKEN = '%', /* token spelled with %: only */
513 WHITE_PERCENT_COLON_TOKEN /* token spelled with %: and white space */
516 /* Structure allocated for every #define. For a simple replacement
519 nargs = -1, the `pattern' list is null, and the expansion is just
520 the replacement text. Nargs = 0 means a functionlike macro with no args,
522 #define getchar() getc (stdin) .
523 When there are args, the expansion is the replacement text with the
524 args squashed out, and the reflist is a list describing how to
525 build the output from the input: e.g., "3 chars, then the 1st arg,
526 then 9 chars, then the 3rd arg, then 0 chars, then the 2nd arg".
527 The chars here come from the expansion. Whatever is left of the
528 expansion after the last arg-occurrence is copied after that arg.
529 Note that the reflist can be arbitrarily long---
530 its length depends on the number of times the arguments appear in
531 the replacement text, not how many args there are. Example:
532 #define f(x) x+x+x+x+x+x+x would have replacement text "++++++" and
534 { (0, 1), (1, 1), (1, 1), ..., (1, 1), NULL }
535 where (x, y) means (nchars, argno). */
537 typedef struct definition DEFINITION;
540 int length; /* length of expansion string */
541 int predefined; /* True if the macro was builtin or */
542 /* came from the command line */
544 int line; /* Line number of definition */
545 char *file; /* File of definition */
546 size_t file_len; /* Length of file (which can contain NULs) */
547 char rest_args; /* Nonzero if last arg. absorbs the rest */
549 struct reflist *next;
551 enum sharp_token_type stringify; /* set if a # operator before arg */
552 enum sharp_token_type raw_before; /* set if a ## operator before arg */
553 enum sharp_token_type raw_after; /* set if a ## operator after arg */
555 char rest_args; /* Nonzero if this arg. absorbs the rest */
556 int nchars; /* Number of literal chars to copy before
557 this arg occurrence. */
558 int argno; /* Number of arg to substitute (origin-0) */
561 /* Names of macro args, concatenated in reverse order
562 with comma-space between them.
563 The only use of this is that we warn on redefinition
564 if this differs between the old and new definitions. */
569 /* different kinds of things that can appear in the value field
570 of a hash node. Actually, this may be useless now. */
578 * special extension string that can be added to the last macro argument to
579 * allow it to absorb the "rest" of the arguments when expanded. Ex:
580 * #define wow(a, b...) process (b, a, b)
581 * { wow (1, 2, 3); } -> { process (2, 3, 1, 2, 3); }
582 * { wow (one, two); } -> { process (two, one, two); }
583 * if this "rest_arg" is used with the concat token '##' and if it is not
584 * supplied then the token attached to with ## will not be outputted. Ex:
585 * #define wow (a, b...) process (b ## , a, ## b)
586 * { wow (1, 2); } -> { process (2, 1, 2); }
587 * { wow (one); } -> { process (one); {
589 static char rest_extension[] = "...";
590 #define REST_EXTENSION_LENGTH (sizeof (rest_extension) - 1)
592 /* This is the implicit parameter name when using variable number of
593 parameters for macros using the ISO C 9x extension. */
594 static char va_args_name[] = "__VA_ARGS__";
595 #define VA_ARGS_NAME_LENGTH (sizeof (va_args_name) - 1)
597 /* The structure of a node in the hash table. The hash table
598 has entries for all tokens defined by #define directives (type T_MACRO),
599 plus some special tokens like __LINE__ (these each have their own
600 type, and the appropriate code is run when that type of node is seen.
601 It does not contain control words like "#define", which are recognized
602 by a separate piece of code. */
604 /* different flavors of hash nodes --- also used in keyword table */
606 T_DEFINE = 1, /* the `#define' keyword */
607 T_INCLUDE, /* the `#include' keyword */
608 T_INCLUDE_NEXT, /* the `#include_next' keyword */
609 T_IMPORT, /* the `#import' keyword */
610 T_IFDEF, /* the `#ifdef' keyword */
611 T_IFNDEF, /* the `#ifndef' keyword */
612 T_IF, /* the `#if' keyword */
613 T_ELSE, /* `#else' */
614 T_PRAGMA, /* `#pragma' */
615 T_ELIF, /* `#elif' */
616 T_UNDEF, /* `#undef' */
617 T_LINE, /* `#line' */
618 T_ERROR, /* `#error' */
619 T_WARNING, /* `#warning' */
620 T_ENDIF, /* `#endif' */
621 T_SCCS, /* `#sccs', used on system V. */
622 T_IDENT, /* `#ident', used on system V. */
623 T_ASSERT, /* `#assert', taken from system V. */
624 T_UNASSERT, /* `#unassert', taken from system V. */
625 T_SPECLINE, /* special symbol `__LINE__' */
626 T_DATE, /* `__DATE__' */
627 T_FILE, /* `__FILE__' */
628 T_BASE_FILE, /* `__BASE_FILE__' */
629 T_INCLUDE_LEVEL, /* `__INCLUDE_LEVEL__' */
630 T_VERSION, /* `__VERSION__' */
631 T_SIZE_TYPE, /* `__SIZE_TYPE__' */
632 T_PTRDIFF_TYPE, /* `__PTRDIFF_TYPE__' */
633 T_WCHAR_TYPE, /* `__WCHAR_TYPE__' */
634 T_USER_LABEL_PREFIX_TYPE, /* `__USER_LABEL_PREFIX__' */
635 T_REGISTER_PREFIX_TYPE, /* `__REGISTER_PREFIX__' */
636 T_IMMEDIATE_PREFIX_TYPE, /* `__IMMEDIATE_PREFIX__' */
637 T_TIME, /* `__TIME__' */
638 T_CONST, /* Constant value, used by `__STDC__' */
639 T_MACRO, /* macro defined by `#define' */
640 T_DISABLED, /* macro temporarily turned off for rescan */
641 T_SPEC_DEFINED, /* special `defined' macro for use in #if statements */
642 T_PCSTRING, /* precompiled string (hashval is KEYDEF *) */
643 T_UNUSED /* Used for something not defined. */
647 struct hashnode *next; /* double links for easy deletion */
648 struct hashnode *prev;
649 struct hashnode **bucket_hdr; /* also, a back pointer to this node's hash
650 chain is kept, in case the node is the head
651 of the chain and gets deleted. */
652 enum node_type type; /* type of special token */
653 int length; /* length of token, for quick comparison */
654 U_CHAR *name; /* the actual name */
655 union hashval value; /* pointer to expansion, or whatever */
658 typedef struct hashnode HASHNODE;
660 /* Some definitions for the hash table. The hash function MUST be
661 computed as shown in hashf () below. That is because the rescan
662 loop computes the hash value `on the fly' for most tokens,
663 in order to avoid the overhead of a lot of procedure calls to
664 the hashf () function. Hashf () only exists for the sake of
665 politeness, for use when speed isn't so important. */
667 #define HASHSIZE 1403
668 static HASHNODE *hashtab[HASHSIZE];
669 #define HASHSTEP(old, c) ((old << 2) + c)
670 #define MAKE_POS(v) (v & 0x7fffffff) /* make number positive */
673 /* We let tm.h override the types used here, to handle trivial differences
674 such as the choice of unsigned int or long unsigned int for size_t.
675 When machines start needing nontrivial differences in the size type,
676 it would be best to do something here to figure out automatically
677 from other information what type to use. */
679 /* The string value for __SIZE_TYPE__. */
682 #define SIZE_TYPE "long unsigned int"
685 /* The string value for __PTRDIFF_TYPE__. */
688 #define PTRDIFF_TYPE "long int"
691 /* The string value for __WCHAR_TYPE__. */
694 #define WCHAR_TYPE "int"
696 char * wchar_type = WCHAR_TYPE;
699 /* The string value for __USER_LABEL_PREFIX__ */
701 #ifndef USER_LABEL_PREFIX
702 #define USER_LABEL_PREFIX ""
704 char * user_label_prefix = USER_LABEL_PREFIX;
705 #undef USER_LABEL_PREFIX
707 /* The string value for __REGISTER_PREFIX__ */
709 #ifndef REGISTER_PREFIX
710 #define REGISTER_PREFIX ""
713 /* The string value for __IMMEDIATE_PREFIX__ */
715 #ifndef IMMEDIATE_PREFIX
716 #define IMMEDIATE_PREFIX ""
719 /* In the definition of a #assert name, this structure forms
720 a list of the individual values asserted.
721 Each value is itself a list of "tokens".
722 These are strings that are compared by name. */
724 struct tokenlist_list {
725 struct tokenlist_list *next;
726 struct arglist *tokens;
729 struct assertion_hashnode {
730 struct assertion_hashnode *next; /* double links for easy deletion */
731 struct assertion_hashnode *prev;
732 /* also, a back pointer to this node's hash
733 chain is kept, in case the node is the head
734 of the chain and gets deleted. */
735 struct assertion_hashnode **bucket_hdr;
736 int length; /* length of token, for quick comparison */
737 U_CHAR *name; /* the actual name */
738 /* List of token-sequences. */
739 struct tokenlist_list *value;
742 typedef struct assertion_hashnode ASSERTION_HASHNODE;
744 /* Some definitions for the hash table. The hash function MUST be
745 computed as shown in hashf below. That is because the rescan
746 loop computes the hash value `on the fly' for most tokens,
747 in order to avoid the overhead of a lot of procedure calls to
748 the hashf function. hashf only exists for the sake of
749 politeness, for use when speed isn't so important. */
751 #define ASSERTION_HASHSIZE 37
752 static ASSERTION_HASHNODE *assertion_hashtab[ASSERTION_HASHSIZE];
754 /* Nonzero means inhibit macroexpansion of what seem to be
755 assertion tests, in rescan. For #if. */
756 static int assertions_flag;
758 /* `struct directive' defines one #-directive, including how to handle it. */
760 #define DO_PROTO PROTO((U_CHAR *, U_CHAR *, FILE_BUF *, struct directive *))
763 int length; /* Length of name */
764 int (*func) DO_PROTO; /* Function to handle directive */
765 char *name; /* Name of directive */
766 enum node_type type; /* Code which describes which directive. */
769 #define IS_INCLUDE_DIRECTIVE_TYPE(t) \
770 ((int) T_INCLUDE <= (int) (t) && (int) (t) <= (int) T_IMPORT)
772 /* These functions are declared to return int instead of void since they
773 are going to be placed in the table and some old compilers have trouble with
774 pointers to functions returning void. */
776 static int do_assert DO_PROTO;
777 static int do_define DO_PROTO;
778 static int do_elif DO_PROTO;
779 static int do_else DO_PROTO;
780 static int do_endif DO_PROTO;
781 static int do_error DO_PROTO;
782 static int do_ident DO_PROTO;
783 static int do_if DO_PROTO;
784 static int do_include DO_PROTO;
785 static int do_line DO_PROTO;
786 static int do_pragma DO_PROTO;
787 #ifdef SCCS_DIRECTIVE
788 static int do_sccs DO_PROTO;
790 static int do_unassert DO_PROTO;
791 static int do_undef DO_PROTO;
792 static int do_warning DO_PROTO;
793 static int do_xifdef DO_PROTO;
795 /* Here is the actual list of #-directives, most-often-used first. */
797 static struct directive directive_table[] = {
798 { 6, do_define, "define", T_DEFINE},
799 { 2, do_if, "if", T_IF},
800 { 5, do_xifdef, "ifdef", T_IFDEF},
801 { 6, do_xifdef, "ifndef", T_IFNDEF},
802 { 5, do_endif, "endif", T_ENDIF},
803 { 4, do_else, "else", T_ELSE},
804 { 4, do_elif, "elif", T_ELIF},
805 { 4, do_line, "line", T_LINE},
806 { 7, do_include, "include", T_INCLUDE},
807 { 12, do_include, "include_next", T_INCLUDE_NEXT},
808 { 6, do_include, "import", T_IMPORT},
809 { 5, do_undef, "undef", T_UNDEF},
810 { 5, do_error, "error", T_ERROR},
811 { 7, do_warning, "warning", T_WARNING},
812 #ifdef SCCS_DIRECTIVE
813 { 4, do_sccs, "sccs", T_SCCS},
815 { 6, do_pragma, "pragma", T_PRAGMA},
816 { 5, do_ident, "ident", T_IDENT},
817 { 6, do_assert, "assert", T_ASSERT},
818 { 8, do_unassert, "unassert", T_UNASSERT},
819 { -1, 0, "", T_UNUSED},
822 /* When a directive handler is called,
823 this points to the # (or the : of the %:) that started the directive. */
824 U_CHAR *directive_start;
826 /* table to tell if char can be part of a C identifier. */
827 U_CHAR is_idchar[256];
828 /* table to tell if char can be first char of a c identifier. */
829 U_CHAR is_idstart[256];
830 /* table to tell if c is horizontal space. */
831 static U_CHAR is_hor_space[256];
832 /* table to tell if c is horizontal or vertical space. */
833 U_CHAR is_space[256];
835 #define SKIP_WHITE_SPACE(p) do { while (is_hor_space[*p]) p++; } while (0)
836 #define SKIP_ALL_WHITE_SPACE(p) do { while (is_space[*p]) p++; } while (0)
838 static int errors = 0; /* Error counter for exit code */
840 /* Name of output file, for error messages. */
841 static char *out_fname;
843 /* Nonzero to ignore \ in string constants. Use to treat #line 1 "A:\file.h
844 as a non-form feed. If you want it to be a form feed, you must use
846 static int ignore_escape_flag = 1;
848 /* Stack of conditionals currently in progress
849 (including both successful and failing conditionals). */
852 struct if_stack *next; /* for chaining to the next stack frame */
853 char *fname; /* copied from input when frame is made */
854 size_t fname_len; /* similarly */
855 int lineno; /* similarly */
856 int if_succeeded; /* true if a leg of this if-group
857 has been passed through rescan */
858 U_CHAR *control_macro; /* For #ifndef at start of file,
859 this is the macro name tested. */
860 enum node_type type; /* type of last directive seen in this group */
862 typedef struct if_stack IF_STACK_FRAME;
863 static IF_STACK_FRAME *if_stack = NULL;
865 /* Buffer of -M output. */
866 static char *deps_buffer;
868 /* Number of bytes allocated in above. */
869 static int deps_allocated_size;
871 /* Number of bytes used. */
872 static int deps_size;
874 /* Number of bytes since the last newline. */
875 static int deps_column;
877 /* Nonzero means -I- has been seen,
878 so don't look for #include "foo" the source-file directory. */
879 static int ignore_srcdir;
881 static int safe_read PROTO((int, char *, int));
882 static void safe_write PROTO((int, char *, int));
883 static void eprint_string PROTO((const char *, size_t));
885 int main PROTO((int, char **));
887 static void path_include PROTO((char *));
889 static U_CHAR *index0 PROTO((U_CHAR *, int, size_t));
891 static void trigraph_pcp PROTO((FILE_BUF *));
893 static void newline_fix PROTO((U_CHAR *));
894 static void name_newline_fix PROTO((U_CHAR *));
896 static char *get_lintcmd PROTO((U_CHAR *, U_CHAR *, U_CHAR **, int *, int *));
898 static void rescan PROTO((FILE_BUF *, int));
900 static FILE_BUF expand_to_temp_buffer PROTO((U_CHAR *, U_CHAR *, int, int));
902 static int handle_directive PROTO((FILE_BUF *, FILE_BUF *));
904 static struct tm *timestamp PROTO((void));
905 static void special_symbol PROTO((HASHNODE *, FILE_BUF *));
907 static int is_system_include PROTO((char *));
908 static char *base_name PROTO((char *));
909 static int absolute_filename PROTO((char *));
910 static size_t simplify_filename PROTO((char *));
912 static char *read_filename_string PROTO((int, FILE *));
913 static struct file_name_map *read_name_map PROTO((char *));
914 static int open_include_file PROTO((char *, struct file_name_list *, U_CHAR *, struct include_file **));
915 static char *remap_include_file PROTO((char *, struct file_name_list *));
916 static int lookup_ino_include PROTO((struct include_file *));
918 static void finclude PROTO((int, struct include_file *, FILE_BUF *, int, struct file_name_list *));
919 static void record_control_macro PROTO((struct include_file *, U_CHAR *));
921 static char *check_precompiled PROTO((int, struct stat *, char *, char **));
922 static int check_preconditions PROTO((char *));
923 static void pcfinclude PROTO((U_CHAR *, U_CHAR *, FILE_BUF *));
924 static void pcstring_used PROTO((HASHNODE *));
925 static void write_output PROTO((void));
926 static void pass_thru_directive PROTO((U_CHAR *, U_CHAR *, FILE_BUF *, struct directive *));
928 static MACRODEF create_definition PROTO((U_CHAR *, U_CHAR *, FILE_BUF *));
930 static int check_macro_name PROTO((U_CHAR *, int));
931 static int compare_defs PROTO((DEFINITION *, DEFINITION *));
932 static int comp_def_part PROTO((int, U_CHAR *, int, U_CHAR *, int, int));
934 static DEFINITION *collect_expansion PROTO((U_CHAR *, U_CHAR *, int, struct arglist *));
936 int check_assertion PROTO((U_CHAR *, int, int, struct arglist *));
937 static int compare_token_lists PROTO((struct arglist *, struct arglist *));
939 static struct arglist *read_token_list PROTO((U_CHAR **, U_CHAR *, int *));
940 static void free_token_list PROTO((struct arglist *));
942 static ASSERTION_HASHNODE *assertion_install PROTO((U_CHAR *, int, int));
943 static ASSERTION_HASHNODE *assertion_lookup PROTO((U_CHAR *, int, int));
944 static void delete_assertion PROTO((ASSERTION_HASHNODE *));
946 static void do_once PROTO((void));
948 static HOST_WIDEST_INT eval_if_expression PROTO((U_CHAR *, int));
949 static void conditional_skip PROTO((FILE_BUF *, int, enum node_type, U_CHAR *, FILE_BUF *));
950 static void skip_if_group PROTO((FILE_BUF *, int, FILE_BUF *));
951 static void validate_else PROTO((U_CHAR *, U_CHAR *));
953 static U_CHAR *skip_to_end_of_comment PROTO((FILE_BUF *, int *, int));
954 static U_CHAR *skip_quoted_string PROTO((U_CHAR *, U_CHAR *, int, int *, int *, int *));
955 static char *quote_string PROTO((char *, char *, size_t));
956 static U_CHAR *skip_paren_group PROTO((FILE_BUF *));
958 /* Last arg to output_line_directive. */
959 enum file_change_code {same_file, enter_file, leave_file};
960 static void output_line_directive PROTO((FILE_BUF *, FILE_BUF *, int, enum file_change_code));
962 static void macroexpand PROTO((HASHNODE *, FILE_BUF *));
965 static int macarg PROTO((struct argdata *, int));
967 static U_CHAR *macarg1 PROTO((U_CHAR *, U_CHAR *, struct hashnode *, int *, int *, int *, int));
969 static int discard_comments PROTO((U_CHAR *, int, int));
971 static int change_newlines PROTO((U_CHAR *, int));
973 static char *my_strerror PROTO((int));
974 static void notice PVPROTO((const char *, ...)) ATTRIBUTE_PRINTF_1;
975 static void vnotice PROTO((const char *, va_list));
976 void error PVPROTO((const char *, ...)) ATTRIBUTE_PRINTF_1;
977 void verror PROTO((const char *, va_list));
978 static void error_from_errno PROTO((char *));
979 void warning PVPROTO((const char *, ...)) ATTRIBUTE_PRINTF_1;
980 static void vwarning PROTO((const char *, va_list));
981 static void error_with_line PVPROTO((int, const char *, ...)) ATTRIBUTE_PRINTF_2;
982 static void verror_with_line PROTO((int, const char *, va_list));
983 static void vwarning_with_line PROTO((int, const char *, va_list));
984 static void warning_with_line PVPROTO((int, const char *, ...)) ATTRIBUTE_PRINTF_2;
985 void pedwarn PVPROTO((const char *, ...)) ATTRIBUTE_PRINTF_1;
986 void pedwarn_with_line PVPROTO((int, const char *, ...)) ATTRIBUTE_PRINTF_2;
987 static void pedwarn_with_file_and_line PVPROTO((const char *, size_t, int, const char *, ...)) ATTRIBUTE_PRINTF_4;
988 static void pedwarn_strange_white_space PROTO((int));
990 static void print_containing_files PROTO((void));
992 static int line_for_error PROTO((int));
993 static int grow_outbuf PROTO((FILE_BUF *, int));
995 static HASHNODE *install PROTO((U_CHAR *, int, enum node_type, char *, int));
996 HASHNODE *lookup PROTO((U_CHAR *, int, int));
997 static void delete_macro PROTO((HASHNODE *));
998 static int hashf PROTO((U_CHAR *, int, int));
1000 static void dump_single_macro PROTO((HASHNODE *, FILE *));
1001 static void dump_all_macros PROTO((void));
1002 static void dump_defn_1 PROTO((U_CHAR *, int, int, FILE *));
1003 static void dump_arg_n PROTO((DEFINITION *, int, FILE *));
1005 static void initialize_char_syntax PROTO((void));
1006 static void initialize_builtins PROTO((FILE_BUF *, FILE_BUF *));
1008 static void make_definition PROTO((char *));
1009 static void make_undef PROTO((char *, FILE_BUF *));
1011 static void make_assertion PROTO((const char *, const char *));
1013 static struct file_name_list *new_include_prefix PROTO((struct file_name_list *, const char *, const char *, const char *));
1014 static void append_include_chain PROTO((struct file_name_list *, struct file_name_list *));
1016 static int quote_string_for_make PROTO((char *, const char *));
1017 static void deps_output PROTO((const char *, int));
1019 void fatal PVPROTO((const char *, ...)) ATTRIBUTE_PRINTF_1 ATTRIBUTE_NORETURN;
1020 void fancy_abort PROTO((void)) ATTRIBUTE_NORETURN;
1021 static void perror_with_name PROTO((char *));
1022 static void pfatal_with_name PROTO((char *)) ATTRIBUTE_NORETURN;
1023 static void pipe_closed PROTO((int)) ATTRIBUTE_NORETURN;
1025 static void memory_full PROTO((void)) ATTRIBUTE_NORETURN;
1026 static void print_help PROTO((void));
1028 /* Read LEN bytes at PTR from descriptor DESC, for file FILENAME,
1029 retrying if necessary. If MAX_READ_LEN is defined, read at most
1030 that bytes at a time. Return a negative value if an error occurs,
1031 otherwise return the actual number of bytes read,
1032 which must be LEN unless end-of-file was reached. */
1035 safe_read (desc, ptr, len)
1040 int left, rcount, nchars;
1046 if (rcount > MAX_READ_LEN)
1047 rcount = MAX_READ_LEN;
1049 nchars = read (desc, ptr, rcount);
1066 /* Write LEN bytes at PTR to descriptor DESC,
1067 retrying if necessary, and treating any real error as fatal.
1068 If MAX_WRITE_LEN is defined, write at most that many bytes at a time. */
1071 safe_write (desc, ptr, len)
1076 int wcount, written;
1080 #ifdef MAX_WRITE_LEN
1081 if (wcount > MAX_WRITE_LEN)
1082 wcount = MAX_WRITE_LEN;
1084 written = write (desc, ptr, wcount);
1091 pfatal_with_name (out_fname);
1098 /* Print a string to stderr, with extra handling in case it contains
1099 embedded NUL characters. Any present are written as is.
1101 Using fwrite for this purpose produces undesireable results on VMS
1102 when stderr happens to be a record oriented file, such as a batch log
1103 file, rather than a stream oriented one. */
1106 eprint_string (string, length)
1110 size_t segment_length;
1113 fprintf(stderr, "%s", string);
1114 length -= (segment_length = strlen(string));
1117 fputc('\0', stderr);
1119 /* Advance past the portion which has already been printed. */
1120 string += segment_length + 1;
1122 } while (length > 0);
1129 printf ("Usage: %s [switches] input output\n", progname);
1130 printf ("Switches:\n");
1131 printf (" -include <file> Include the contents of <file> before other files\n");
1132 printf (" -imacros <file> Accept definition of macros in <file>\n");
1133 printf (" -iprefix <path> Specify <path> as a prefix for next two options\n");
1134 printf (" -iwithprefix <dir> Add <dir> to the end of the system include paths\n");
1135 printf (" -iwithprefixbefore <dir> Add <dir> to the end of the main include paths\n");
1136 printf (" -isystem <dir> Add <dir> to the start of the system include paths\n");
1137 printf (" -idirafter <dir> Add <dir> to the end of the system include paths\n");
1138 printf (" -I <dir> Add <dir> to the end of the main include paths\n");
1139 printf (" -nostdinc Do not search the system include directories\n");
1140 printf (" -nostdinc++ Do not search the system include directories for C++\n");
1141 printf (" -o <file> Put output into <file>\n");
1142 printf (" -pedantic Issue all warnings demanded by strict ANSI C\n");
1143 printf (" -traditional Follow K&R pre-processor behaviour\n");
1144 printf (" -trigraphs Support ANSI C trigraphs\n");
1145 printf (" -lang-c Assume that the input sources are in C\n");
1146 printf (" -lang-c89 Assume that the input is C89; deprecated\n");
1147 printf (" -lang-c++ Assume that the input sources are in C++\n");
1148 printf (" -lang-objc Assume that the input sources are in ObjectiveC\n");
1149 printf (" -lang-objc++ Assume that the input sources are in ObjectiveC++\n");
1150 printf (" -lang-asm Assume that the input sources are in assembler\n");
1151 printf (" -lang-chill Assume that the input sources are in Chill\n");
1152 printf (" -std=<std name> Specify the conformance standard; one of:\n");
1153 printf (" gnu89, gnu9x, c89, c9x, iso9899:1990,\n");
1154 printf (" iso9899:199409, iso9899:199x\n");
1155 printf (" -+ Allow parsing of C++ style features\n");
1156 printf (" -w Inhibit warning messages\n");
1157 printf (" -Wtrigraphs Warn if trigraphs are encountered\n");
1158 printf (" -Wno-trigraphs Do not warn about trigraphs\n");
1159 printf (" -Wcomment{s} Warn if one comment starts inside another\n");
1160 printf (" -Wno-comment{s} Do not warn about comments\n");
1161 printf (" -Wtraditional Warn if a macro argument is/would be turned into\n");
1162 printf (" a string if -traditional is specified\n");
1163 printf (" -Wno-traditional Do not warn about stringification\n");
1164 printf (" -Wundef Warn if an undefined macro is used by #if\n");
1165 printf (" -Wno-undef Do not warn about testing undefined macros\n");
1166 printf (" -Wimport Warn about the use of the #import directive\n");
1167 printf (" -Wno-import Do not warn about the use of #import\n");
1168 printf (" -Werror Treat all warnings as errors\n");
1169 printf (" -Wno-error Do not treat warnings as errors\n");
1170 printf (" -Wall Enable all preprocessor warnings\n");
1171 printf (" -M Generate make dependencies\n");
1172 printf (" -MM As -M, but ignore system header files\n");
1173 printf (" -MD As -M, but put output in a .d file\n");
1174 printf (" -MMD As -MD, but ignore system header files\n");
1175 printf (" -MG Treat missing header file as generated files\n");
1176 printf (" -g Include #define and #undef directives in the output\n");
1177 printf (" -D<macro> Define a <macro> with string '1' as its value\n");
1178 printf (" -D<macro>=<val> Define a <macro> with <val> as its value\n");
1179 printf (" -A<question> (<answer>) Assert the <answer> to <question>\n");
1180 printf (" -U<macro> Undefine <macro> \n");
1181 printf (" -u or -undef Do not predefine any macros\n");
1182 printf (" -v Display the version number\n");
1183 printf (" -H Print the name of header files as they are used\n");
1184 printf (" -C Do not discard comments\n");
1185 printf (" -dM Display a list of macro definitions active at end\n");
1186 printf (" -dD Preserve macro definitions in output\n");
1187 printf (" -dN As -dD except that only the names are preserved\n");
1188 printf (" -dI Include #include directives in the output\n");
1189 printf (" -ifoutput Describe skipped code blocks in output \n");
1190 printf (" -P Do not generate #line directives\n");
1191 printf (" -$ Do not include '$' in identifiers\n");
1192 printf (" -remap Remap file names when including files.\n");
1193 printf (" -h or --help Display this information\n");
1210 char **pend_assertions;
1211 char **pend_includes;
1213 /* Record the option used with each element of pend_assertions.
1214 This is preparation for supporting more than one option for making
1216 char **pend_assertion_options;
1217 int no_standard_includes = 0;
1218 int no_standard_cplusplus_includes = 0;
1219 int missing_newline = 0;
1221 /* Non-0 means don't output the preprocessed program. */
1222 int inhibit_output = 0;
1223 /* Non-0 means -v, so print the full set of include dirs. */
1226 /* File name which deps are being written to.
1227 This is 0 if deps are being written to stdout. */
1228 char *deps_file = 0;
1229 /* Fopen file mode to open deps_file with. */
1230 char *deps_mode = "a";
1231 /* Stream on which to print the dependency information. */
1232 FILE *deps_stream = 0;
1233 /* Target-name to write with the dependency information. */
1234 char *deps_target = 0;
1236 #if defined (RLIMIT_STACK) && defined (HAVE_GETRLIMIT) && defined (HAVE_SETRLIMIT)
1237 /* Get rid of any avoidable limit on stack size. */
1241 /* Set the stack limit huge so that alloca (particularly stringtab
1242 in dbxread.c) does not fail. */
1243 getrlimit (RLIMIT_STACK, &rlim);
1244 rlim.rlim_cur = rlim.rlim_max;
1245 setrlimit (RLIMIT_STACK, &rlim);
1250 signal (SIGPIPE, pipe_closed);
1253 #ifdef HAVE_LC_MESSAGES
1254 setlocale (LC_MESSAGES, "");
1256 (void) bindtextdomain (PACKAGE, localedir);
1257 (void) textdomain (PACKAGE);
1259 progname = base_name (argv[0]);
1263 /* Remove extension from PROGNAME. */
1265 char *s = progname = xstrdup (progname);
1267 if ((p = rindex (s, ';')) != 0) *p = '\0'; /* strip version number */
1268 if ((p = rindex (s, '.')) != 0 /* strip type iff ".exe" */
1269 && (p[1] == 'e' || p[1] == 'E')
1270 && (p[2] == 'x' || p[2] == 'X')
1271 && (p[3] == 'e' || p[3] == 'E')
1277 /* Do not invoke xmalloc before this point, since locale and
1278 progname need to be set first, in case a diagnostic is issued. */
1280 pend_files = (char **) xmalloc (argc * sizeof (char *));
1281 pend_defs = (char **) xmalloc (argc * sizeof (char *));
1282 pend_undefs = (char **) xmalloc (argc * sizeof (char *));
1283 pend_assertions = (char **) xmalloc (argc * sizeof (char *));
1284 pend_includes = (char **) xmalloc (argc * sizeof (char *));
1285 pend_assertion_options = (char **) xmalloc (argc * sizeof (char *));
1290 /* Initialize is_idchar. */
1291 initialize_char_syntax ();
1293 no_line_directives = 0;
1295 dump_macros = dump_none;
1298 cplusplus_comments = 1;
1300 bzero ((char *) pend_files, argc * sizeof (char *));
1301 bzero ((char *) pend_defs, argc * sizeof (char *));
1302 bzero ((char *) pend_undefs, argc * sizeof (char *));
1303 bzero ((char *) pend_assertions, argc * sizeof (char *));
1304 bzero ((char *) pend_includes, argc * sizeof (char *));
1306 #ifdef MULTIBYTE_CHARS
1307 /* Change to the native locale for multibyte conversions. */
1308 setlocale (LC_CTYPE, "");
1309 literal_codeset = getenv ("LANG");
1312 /* Process switches and find input file name. */
1314 for (i = 1; i < argc; i++) {
1315 if (argv[i][0] != '-') {
1316 if (out_fname != NULL)
1319 fatal ("Too many arguments");
1321 else if (in_fname != NULL)
1322 out_fname = argv[i];
1326 switch (argv[i][1]) {
1329 if (!strcmp (argv[i], "-include")) {
1333 fatal ("Filename missing after `-include' option");
1335 simplify_filename (pend_includes[temp] = argv[++i]);
1337 if (!strcmp (argv[i], "-imacros")) {
1341 fatal ("Filename missing after `-imacros' option");
1343 simplify_filename (pend_files[temp] = argv[++i]);
1345 if (!strcmp (argv[i], "-iprefix")) {
1347 fatal ("Filename missing after `-iprefix' option");
1349 include_prefix = argv[++i];
1351 if (!strcmp (argv[i], "-ifoutput")) {
1352 output_conditionals = 1;
1354 if (!strcmp (argv[i], "-isystem")) {
1355 struct file_name_list *dirtmp;
1357 if (! (dirtmp = new_include_prefix (NULL_PTR, NULL_PTR,
1360 dirtmp->c_system_include_path = 1;
1362 if (before_system == 0)
1363 before_system = dirtmp;
1365 last_before_system->next = dirtmp;
1366 last_before_system = dirtmp; /* Tail follows the last one */
1368 /* Add directory to end of path for includes,
1369 with the default prefix at the front of its name. */
1370 if (!strcmp (argv[i], "-iwithprefix")) {
1371 struct file_name_list *dirtmp;
1374 if (include_prefix != 0)
1375 prefix = include_prefix;
1377 prefix = xstrdup (GCC_INCLUDE_DIR);
1378 /* Remove the `include' from /usr/local/lib/gcc.../include. */
1379 if (!strcmp (prefix + strlen (prefix) - 8, "/include"))
1380 prefix[strlen (prefix) - 7] = 0;
1383 if (! (dirtmp = new_include_prefix (NULL_PTR, NULL_PTR,
1384 prefix, argv[++i])))
1387 if (after_include == 0)
1388 after_include = dirtmp;
1390 last_after_include->next = dirtmp;
1391 last_after_include = dirtmp; /* Tail follows the last one */
1393 /* Add directory to main path for includes,
1394 with the default prefix at the front of its name. */
1395 if (!strcmp (argv[i], "-iwithprefixbefore")) {
1396 struct file_name_list *dirtmp;
1399 if (include_prefix != 0)
1400 prefix = include_prefix;
1402 prefix = xstrdup (GCC_INCLUDE_DIR);
1403 /* Remove the `include' from /usr/local/lib/gcc.../include. */
1404 if (!strcmp (prefix + strlen (prefix) - 8, "/include"))
1405 prefix[strlen (prefix) - 7] = 0;
1408 dirtmp = new_include_prefix (NULL_PTR, NULL_PTR, prefix, argv[++i]);
1409 append_include_chain (dirtmp, dirtmp);
1411 /* Add directory to end of path for includes. */
1412 if (!strcmp (argv[i], "-idirafter")) {
1413 struct file_name_list *dirtmp;
1415 if (! (dirtmp = new_include_prefix (NULL_PTR, NULL_PTR,
1419 if (after_include == 0)
1420 after_include = dirtmp;
1422 last_after_include->next = dirtmp;
1423 last_after_include = dirtmp; /* Tail follows the last one */
1428 if (out_fname != NULL)
1429 fatal ("Output filename specified twice");
1431 fatal ("Filename missing after -o option");
1432 out_fname = argv[++i];
1433 if (!strcmp (out_fname, "-"))
1438 if (!strcmp (argv[i], "-pedantic"))
1440 else if (!strcmp (argv[i], "-pedantic-errors")) {
1442 pedantic_errors = 1;
1443 } else if (!strcmp (argv[i], "-pcp")) {
1446 fatal ("Filename missing after -pcp option");
1447 pcp_fname = argv[++i];
1449 = ((pcp_fname[0] != '-' || pcp_fname[1] != '\0')
1450 ? fopen (pcp_fname, "w")
1452 if (pcp_outfile == 0)
1453 pfatal_with_name (pcp_fname);
1459 if (!strcmp (argv[i], "-traditional")) {
1461 cplusplus_comments = 0;
1462 } else if (!strcmp (argv[i], "-trigraphs")) {
1468 if (! strcmp (argv[i], "-lang-c"))
1469 cplusplus = 0, cplusplus_comments = 1, c89 = 0, c9x = 1, objc = 0;
1470 else if (! strcmp (argv[i], "-lang-c89"))
1471 cplusplus = 0, cplusplus_comments = 0, c89 = 1, c9x = 0, objc = 0;
1472 else if (! strcmp (argv[i], "-lang-c++"))
1473 cplusplus = 1, cplusplus_comments = 1, c89 = 0, c9x = 0, objc = 0;
1474 else if (! strcmp (argv[i], "-lang-objc"))
1475 cplusplus = 0, cplusplus_comments = 1, c89 = 0, c9x = 0, objc = 1;
1476 else if (! strcmp (argv[i], "-lang-objc++"))
1477 cplusplus = 1, cplusplus_comments = 1, c89 = 0, c9x = 0, objc = 1;
1478 else if (! strcmp (argv[i], "-lang-asm"))
1480 else if (! strcmp (argv[i], "-lint"))
1485 cplusplus = 1, cplusplus_comments = 1;
1489 if (!strcmp (argv[i], "-std=iso9899:1990")
1490 || !strcmp (argv[i], "-std=iso9899:199409")
1491 || !strcmp (argv[i], "-std=c89")
1492 || !strcmp (argv[i], "-std=gnu89"))
1493 cplusplus = 0, cplusplus_comments = 0, c89 = 1, c9x = 0, objc = 0;
1494 else if (!strcmp (argv[i], "-std=iso9899:199x")
1495 || !strcmp (argv[i], "-std=c9x")
1496 || !strcmp (argv[i], "-std=gnu9x"))
1497 cplusplus = 0, cplusplus_comments = 1, c89 = 0, c9x = 1, objc = 0;
1501 inhibit_warnings = 1;
1505 if (!strcmp (argv[i], "-Wtrigraphs"))
1507 else if (!strcmp (argv[i], "-Wno-trigraphs"))
1509 else if (!strcmp (argv[i], "-Wcomment"))
1511 else if (!strcmp (argv[i], "-Wno-comment"))
1513 else if (!strcmp (argv[i], "-Wcomments"))
1515 else if (!strcmp (argv[i], "-Wno-comments"))
1517 else if (!strcmp (argv[i], "-Wtraditional"))
1519 else if (!strcmp (argv[i], "-Wno-traditional"))
1521 else if (!strcmp (argv[i], "-Wundef"))
1523 else if (!strcmp (argv[i], "-Wno-undef"))
1525 else if (!strcmp (argv[i], "-Wimport"))
1527 else if (!strcmp (argv[i], "-Wno-import"))
1529 else if (!strcmp (argv[i], "-Werror"))
1530 warnings_are_errors = 1;
1531 else if (!strcmp (argv[i], "-Wno-error"))
1532 warnings_are_errors = 0;
1533 else if (!strcmp (argv[i], "-Wall"))
1541 if (!strcmp (argv[i], "-fleading-underscore"))
1542 user_label_prefix = "_";
1543 else if (!strcmp (argv[i], "-fno-leading-underscore"))
1544 user_label_prefix = "";
1548 /* The style of the choices here is a bit mixed.
1549 The chosen scheme is a hybrid of keeping all options in one string
1550 and specifying each option in a separate argument:
1551 -M|-MM|-MD file|-MMD file [-MG]. An alternative is:
1552 -M|-MM|-MD file|-MMD file|-MG|-MMG; or more concisely:
1553 -M[M][G][D file]. This is awkward to handle in specs, and is not
1555 /* ??? -MG must be specified in addition to one of -M or -MM.
1556 This can be relaxed in the future without breaking anything.
1557 The converse isn't true. */
1559 /* -MG isn't valid with -MD or -MMD. This is checked for later. */
1560 if (!strcmp (argv[i], "-MG"))
1562 print_deps_missing_files = 1;
1565 if (!strcmp (argv[i], "-M"))
1567 else if (!strcmp (argv[i], "-MM"))
1569 else if (!strcmp (argv[i], "-MD"))
1571 else if (!strcmp (argv[i], "-MMD"))
1573 /* For -MD and -MMD options, write deps on file named by next arg. */
1574 if (!strcmp (argv[i], "-MD")
1575 || !strcmp (argv[i], "-MMD")) {
1577 fatal ("Filename missing after %s option", argv[i]);
1579 deps_file = argv[i];
1582 /* For -M and -MM, write deps on standard output
1583 and suppress the usual output. */
1584 deps_stream = stdout;
1591 char *p = argv[i] + 2;
1593 while ((c = *p++)) {
1594 /* Arg to -d specifies what parts of macros to dump */
1597 dump_macros = dump_only;
1601 dump_macros = dump_names;
1604 dump_macros = dump_definitions;
1615 if (argv[i][2] == '3')
1620 if (strcmp (argv[i], "--help") != 0)
1627 notice ("GNU CPP version %s", version_string);
1628 #ifdef TARGET_VERSION
1631 fprintf (stderr, "\n");
1636 print_include_names = 1;
1640 if (argv[i][2] != 0)
1641 pend_defs[i] = argv[i] + 2;
1642 else if (i + 1 == argc)
1643 fatal ("Macro name missing after -D option");
1645 i++, pend_defs[i] = argv[i];
1652 if (argv[i][2] != 0)
1654 else if (i + 1 == argc)
1655 fatal ("Assertion missing after -A option");
1659 if (!strcmp (p, "-")) {
1660 /* -A- eliminates all predefined macros and assertions.
1661 Let's include also any that were specified earlier
1662 on the command line. That way we can get rid of any
1663 that were passed automatically in from GCC. */
1665 for (j = 0; j < i; j++)
1666 pend_defs[j] = pend_assertions[j] = 0;
1668 pend_assertions[i] = p;
1669 pend_assertion_options[i] = "-A";
1674 case 'U': /* JF #undef something */
1675 if (argv[i][2] != 0)
1676 pend_undefs[i] = argv[i] + 2;
1677 else if (i + 1 == argc)
1678 fatal ("Macro name missing after -U option");
1680 pend_undefs[i] = argv[i+1], i++;
1684 put_out_comments = 1;
1687 case 'E': /* -E comes from cc -E; ignore it. */
1691 no_line_directives = 1;
1694 case '$': /* Don't include $ in identifiers. */
1695 is_idchar['$'] = is_idstart['$'] = 0;
1698 case 'I': /* Add directory to path for includes. */
1700 struct file_name_list *dirtmp;
1702 if (! ignore_srcdir && !strcmp (argv[i] + 2, "-")) {
1704 /* Don't use any preceding -I directories for #include <...>. */
1705 first_bracket_include = 0;
1708 dirtmp = new_include_prefix (last_include, NULL_PTR, "",
1709 argv[i][2] ? argv[i] + 2 : argv[++i]);
1710 append_include_chain (dirtmp, dirtmp);
1716 if (!strcmp (argv[i], "-nostdinc"))
1717 /* -nostdinc causes no default include directories.
1718 You must specify all include-file directories with -I. */
1719 no_standard_includes = 1;
1720 else if (!strcmp (argv[i], "-nostdinc++"))
1721 /* -nostdinc++ causes no default C++-specific include directories. */
1722 no_standard_cplusplus_includes = 1;
1723 else if (!strcmp (argv[i], "-noprecomp"))
1728 if (!strcmp (argv[i], "-remap"))
1732 case '\0': /* JF handle '-' as file name meaning stdin or stdout */
1733 if (in_fname == NULL) {
1736 } else if (out_fname == NULL) {
1739 } /* else fall through into error */
1742 fatal ("Invalid option `%s'", argv[i]);
1747 /* Add dirs from CPATH after dirs from -I. */
1748 /* There seems to be confusion about what CPATH should do,
1749 so for the moment it is not documented. */
1750 /* Some people say that CPATH should replace the standard include dirs,
1751 but that seems pointless: it comes before them, so it overrides them
1753 GET_ENV_PATH_LIST (cp, "CPATH");
1754 if (cp && ! no_standard_includes)
1757 /* Initialize output buffer */
1759 outbuf.buf = (U_CHAR *) xmalloc (OUTBUF_SIZE);
1760 outbuf.bufp = outbuf.buf;
1761 outbuf.length = OUTBUF_SIZE;
1763 /* Do partial setup of input buffer for the sake of generating
1764 early #line directives (when -g is in effect). */
1766 fp = &instack[++indepth];
1767 if (in_fname == NULL)
1769 fp->nominal_fname = fp->fname = in_fname;
1770 fp->nominal_fname_len = strlen (in_fname);
1773 /* In C++, wchar_t is a distinct basic type, and we can expect
1774 __wchar_t to be defined by cc1plus. */
1776 wchar_type = "__wchar_t";
1778 /* Install __LINE__, etc. Must follow initialize_char_syntax
1779 and option processing. */
1780 initialize_builtins (fp, &outbuf);
1782 /* Now handle the command line options. */
1784 /* Do -U's, -D's and -A's in the order they were seen. */
1785 for (i = 1; i < argc; i++) {
1786 if (pend_undefs[i]) {
1788 output_line_directive (fp, &outbuf, 0, same_file);
1789 make_undef (pend_undefs[i], &outbuf);
1793 output_line_directive (fp, &outbuf, 0, same_file);
1794 make_definition (pend_defs[i]);
1796 if (pend_assertions[i])
1797 make_assertion (pend_assertion_options[i], pend_assertions[i]);
1800 done_initializing = 1;
1802 { /* Read the appropriate environment variable and if it exists
1803 replace include_defaults with the listed path. */
1805 switch ((objc << 1) + cplusplus)
1808 GET_ENV_PATH_LIST (epath, "C_INCLUDE_PATH");
1811 GET_ENV_PATH_LIST (epath, "CPLUS_INCLUDE_PATH");
1814 GET_ENV_PATH_LIST (epath, "OBJC_INCLUDE_PATH");
1817 GET_ENV_PATH_LIST (epath, "OBJCPLUS_INCLUDE_PATH");
1820 /* If the environment var for this language is set,
1821 add to the default list of include directories. */
1824 char *startp, *endp;
1826 for (num_dirs = 1, startp = epath; *startp; startp++)
1827 if (*startp == PATH_SEPARATOR)
1830 = (struct default_include *) xmalloc ((num_dirs
1831 * sizeof (struct default_include))
1832 + sizeof (include_defaults_array));
1833 startp = endp = epath;
1837 if (c == PATH_SEPARATOR || !c) {
1839 include_defaults[num_dirs].fname
1840 = startp == endp ? "." : xstrdup (startp);
1842 include_defaults[num_dirs].component = 0;
1843 include_defaults[num_dirs].cplusplus = cplusplus;
1844 include_defaults[num_dirs].cxx_aware = 1;
1851 /* Put the usual defaults back in at the end. */
1852 bcopy ((char *) include_defaults_array,
1853 (char *) &include_defaults[num_dirs],
1854 sizeof (include_defaults_array));
1858 append_include_chain (before_system, last_before_system);
1859 first_system_include = before_system;
1861 /* Unless -fnostdinc,
1862 tack on the standard include file dirs to the specified list */
1863 if (!no_standard_includes) {
1864 struct default_include *p = include_defaults;
1865 char *specd_prefix = include_prefix;
1866 char *default_prefix = xstrdup (GCC_INCLUDE_DIR);
1867 int default_len = 0;
1868 /* Remove the `include' from /usr/local/lib/gcc.../include. */
1869 if (!strcmp (default_prefix + strlen (default_prefix) - 8, "/include")) {
1870 default_len = strlen (default_prefix) - 7;
1871 default_prefix[default_len] = 0;
1873 /* Search "translated" versions of GNU directories.
1874 These have /usr/local/lib/gcc... replaced by specd_prefix. */
1875 if (specd_prefix != 0 && default_len != 0)
1876 for (p = include_defaults; p->fname; p++) {
1877 /* Some standard dirs are only for C++. */
1878 if (!p->cplusplus || (cplusplus && !no_standard_cplusplus_includes)) {
1879 /* Does this dir start with the prefix? */
1880 if (!strncmp (p->fname, default_prefix, default_len)) {
1881 /* Yes; change prefix and add to search list. */
1882 struct file_name_list *new
1883 = new_include_prefix (NULL_PTR, NULL_PTR, specd_prefix,
1884 p->fname + default_len);
1886 new->c_system_include_path = !p->cxx_aware;
1887 append_include_chain (new, new);
1888 if (first_system_include == 0)
1889 first_system_include = new;
1895 /* Search ordinary names for GNU include directories. */
1896 for (p = include_defaults; p->fname; p++) {
1897 /* Some standard dirs are only for C++. */
1898 if (!p->cplusplus || (cplusplus && !no_standard_cplusplus_includes)) {
1899 struct file_name_list *new
1900 = new_include_prefix (NULL_PTR, p->component, "", p->fname);
1902 new->c_system_include_path = !p->cxx_aware;
1903 append_include_chain (new, new);
1904 if (first_system_include == 0)
1905 first_system_include = new;
1912 /* Tack the after_include chain at the end of the include chain. */
1913 append_include_chain (after_include, last_after_include);
1914 if (first_system_include == 0)
1915 first_system_include = after_include;
1917 /* With -v, print the list of dirs to search. */
1919 struct file_name_list *p;
1920 notice ("#include \"...\" search starts here:\n");
1921 for (p = include; p; p = p->next) {
1922 if (p == first_bracket_include)
1923 notice ("#include <...> search starts here:\n");
1925 fprintf (stderr, " .\n");
1926 else if (!strcmp (p->fname, "/") || !strcmp (p->fname, "//"))
1927 fprintf (stderr, " %s\n", p->fname);
1929 /* Omit trailing '/'. */
1930 fprintf (stderr, " %.*s\n", (int) strlen (p->fname) - 1, p->fname);
1932 notice ("End of search list.\n");
1934 struct default_include * d;
1935 notice ("The following default directories have been omitted from the search path:\n");
1936 for (d = include_defaults; d->fname; d++)
1938 fprintf (stderr, " %s\n", d->fname);
1939 notice ("End of omitted list.\n");
1943 /* -MG doesn't select the form of output and must be specified with one of
1944 -M or -MM. -MG doesn't make sense with -MD or -MMD since they don't
1945 inhibit compilation. */
1946 if (print_deps_missing_files && (print_deps == 0 || !inhibit_output))
1947 fatal ("-MG must be specified with one of -M or -MM");
1949 /* Either of two environment variables can specify output of deps.
1950 Its value is either "OUTPUT_FILE" or "OUTPUT_FILE DEPS_TARGET",
1951 where OUTPUT_FILE is the file to write deps info to
1952 and DEPS_TARGET is the target to mention in the deps. */
1955 && (getenv ("SUNPRO_DEPENDENCIES") != 0
1956 || getenv ("DEPENDENCIES_OUTPUT") != 0)) {
1957 char *spec = getenv ("DEPENDENCIES_OUTPUT");
1962 spec = getenv ("SUNPRO_DEPENDENCIES");
1969 /* Find the space before the DEPS_TARGET, if there is one. */
1970 /* This should use index. (mrs) */
1971 while (*s != 0 && *s != ' ') s++;
1973 deps_target = s + 1;
1974 output_file = xmalloc (s - spec + 1);
1975 bcopy (spec, output_file, s - spec);
1976 output_file[s - spec] = 0;
1983 deps_file = output_file;
1987 /* For -M, print the expected object file name
1988 as the target of this Make-rule. */
1990 deps_allocated_size = 200;
1991 deps_buffer = xmalloc (deps_allocated_size);
1997 deps_output (deps_target, ':');
1998 } else if (*in_fname == 0) {
1999 deps_output ("-", ':');
2004 q = base_name (in_fname);
2006 /* Copy remainder to mungable area. */
2007 p = (char *) alloca (strlen(q) + 8);
2010 /* Output P, but remove known suffixes. */
2014 && p[len - 2] == '.'
2015 && index("cCsSm", p[len - 1]))
2018 && p[len - 3] == '.'
2019 && p[len - 2] == 'c'
2020 && p[len - 1] == 'c')
2023 && p[len - 4] == '.'
2024 && p[len - 3] == 'c'
2025 && p[len - 2] == 'x'
2026 && p[len - 1] == 'x')
2029 && p[len - 4] == '.'
2030 && p[len - 3] == 'c'
2031 && p[len - 2] == 'p'
2032 && p[len - 1] == 'p')
2035 /* Supply our own suffix. */
2036 strcpy (q, OBJECT_SUFFIX);
2038 deps_output (p, ':');
2039 deps_output (in_fname, ' ');
2043 /* Scan the -imacros files before the main input.
2044 Much like #including them, but with no_output set
2045 so that only their macro definitions matter. */
2047 no_output++; no_record_file++;
2048 for (i = 1; i < argc; i++)
2049 if (pend_files[i]) {
2050 struct include_file *inc;
2051 int fd = open_include_file (pend_files[i], NULL_PTR, NULL_PTR, &inc);
2053 perror_with_name (pend_files[i]);
2054 return FATAL_EXIT_CODE;
2056 finclude (fd, inc, &outbuf, 0, NULL_PTR);
2058 no_output--; no_record_file--;
2060 /* Copy the entire contents of the main input file into
2061 the stacked input buffer previously allocated for it. */
2063 /* JF check for stdin */
2064 if (in_fname == NULL || *in_fname == 0) {
2067 } else if ((f = open (in_fname, O_RDONLY, 0666)) < 0)
2070 if (fstat (f, &st) != 0)
2071 pfatal_with_name (in_fname);
2072 fp->nominal_fname = fp->fname = in_fname;
2073 fp->nominal_fname_len = strlen (in_fname);
2075 fp->system_header_p = 0;
2076 /* JF all this is mine about reading pipes and ttys */
2077 if (! S_ISREG (st.st_mode)) {
2078 /* Read input from a file that is not a normal disk file.
2079 We cannot preallocate a buffer with the correct size,
2080 so we must read in the file a piece at the time and make it bigger. */
2085 if (S_ISDIR (st.st_mode))
2086 fatal ("Input file `%s' is a directory", in_fname);
2090 fp->buf = (U_CHAR *) xmalloc (bsize + 2);
2092 cnt = safe_read (f, (char *) fp->buf + size, bsize - size);
2093 if (cnt < 0) goto perror; /* error! */
2095 if (size != bsize) break; /* End of file */
2097 fp->buf = (U_CHAR *) xrealloc (fp->buf, bsize + 2);
2101 /* Read a file whose size we can determine in advance.
2102 For the sake of VMS, st.st_size is just an upper bound. */
2103 size_t s = (size_t) st.st_size;
2104 if (s != st.st_size || s + 2 < s)
2106 fp->buf = (U_CHAR *) xmalloc (s + 2);
2107 fp->length = safe_read (f, (char *) fp->buf, s);
2108 if (fp->length < 0) goto perror;
2111 fp->if_stack = if_stack;
2113 /* Make sure data ends with a newline. And put a null after it. */
2115 if ((fp->length > 0 && fp->buf[fp->length - 1] != '\n')
2116 /* Backslash-newline at end is not good enough. */
2117 || (fp->length > 1 && fp->buf[fp->length - 2] == '\\')) {
2118 fp->buf[fp->length++] = '\n';
2119 missing_newline = 1;
2121 fp->buf[fp->length] = '\0';
2123 /* Unless inhibited, convert trigraphs in the input. */
2128 /* Now that we know the input file is valid, open the output. */
2130 if (!out_fname || !strcmp (out_fname, ""))
2131 out_fname = "stdout";
2132 else if (! freopen (out_fname, "w", stdout))
2133 pfatal_with_name (out_fname);
2135 output_line_directive (fp, &outbuf, 0, same_file);
2137 /* Scan the -include files before the main input. */
2140 for (i = 1; i < argc; i++)
2141 if (pend_includes[i]) {
2142 struct include_file *inc;
2143 int fd = open_include_file (pend_includes[i], NULL_PTR, NULL_PTR, &inc);
2145 perror_with_name (pend_includes[i]);
2146 return FATAL_EXIT_CODE;
2148 finclude (fd, inc, &outbuf, 0, NULL_PTR);
2152 /* Scan the input, processing macros and directives. */
2154 rescan (&outbuf, 0);
2156 if (missing_newline)
2159 if (pedantic && missing_newline)
2160 pedwarn ("file does not end in newline");
2162 /* Now we have processed the entire input
2163 Write whichever kind of output has been requested. */
2165 if (dump_macros == dump_only)
2167 else if (! inhibit_output) {
2172 /* Don't actually write the deps file if compilation has failed. */
2174 if (deps_file && ! (deps_stream = fopen (deps_file, deps_mode)))
2175 pfatal_with_name (deps_file);
2176 fputs (deps_buffer, deps_stream);
2177 putc ('\n', deps_stream);
2179 if (ferror (deps_stream) || fclose (deps_stream) != 0)
2180 fatal ("I/O error on output");
2185 if (pcp_outfile && pcp_outfile != stdout
2186 && (ferror (pcp_outfile) || fclose (pcp_outfile) != 0))
2187 fatal ("I/O error on `-pcp' output");
2189 if (ferror (stdout) || fclose (stdout) != 0)
2190 fatal ("I/O error on output");
2193 exit (FATAL_EXIT_CODE);
2194 exit (SUCCESS_EXIT_CODE);
2197 pfatal_with_name (in_fname);
2201 /* Given a colon-separated list of file names PATH,
2202 add all the names to the search path for include files. */
2216 struct file_name_list *dirtmp;
2218 /* Find the end of this name. */
2219 while ((c = *q++) != PATH_SEPARATOR && c)
2223 dirtmp = new_include_prefix (last_include, NULL_PTR,
2224 "", p == q ? "." : p);
2226 append_include_chain (dirtmp, dirtmp);
2228 /* Advance past this name. */
2235 /* Return the address of the first character in S that equals C.
2236 S is an array of length N, possibly containing '\0's, and followed by '\0'.
2237 Return 0 if there is no such character. Assume that C itself is not '\0'.
2238 If we knew we could use memchr, we could just invoke memchr (S, C, N),
2239 but unfortunately memchr isn't autoconfigured yet. */
2247 char *p = (char *) s;
2249 char *q = index (p, c);
2251 return (U_CHAR *) q;
2253 size_t l = strlen (p);
2263 /* Pre-C-Preprocessor to translate ANSI trigraph idiocy in BUF
2264 before main CCCP processing. Name `pcp' is also in honor of the
2265 drugs the trigraph designers must have been on.
2267 Using an extra pass through the buffer takes a little extra time,
2268 but is infinitely less hairy than trying to handle trigraphs inside
2269 strings, etc. everywhere, and also makes sure that trigraphs are
2270 only translated in the top level of processing. */
2276 register U_CHAR c, *fptr, *bptr, *sptr, *lptr;
2279 fptr = bptr = sptr = buf->buf;
2280 lptr = fptr + buf->length;
2281 while ((sptr = index0 (sptr, '?', (size_t) (lptr - sptr))) != NULL) {
2318 len = sptr - fptr - 2;
2320 /* BSD doc says bcopy () works right for overlapping strings. In ANSI
2321 C, this will be memmove (). */
2322 if (bptr != fptr && len > 0)
2323 bcopy ((char *) fptr, (char *) bptr, len);
2329 len = buf->length - (fptr - buf->buf);
2330 if (bptr != fptr && len > 0)
2331 bcopy ((char *) fptr, (char *) bptr, len);
2332 buf->length -= fptr - bptr;
2333 buf->buf[buf->length] = '\0';
2334 if (warn_trigraphs && fptr != bptr)
2335 warning_with_line (0, "%lu trigraph(s) encountered",
2336 (unsigned long) (fptr - bptr) / 2);
2339 /* Move all backslash-newline pairs out of embarrassing places.
2340 Exchange all such pairs following BP
2341 with any potentially-embarrassing characters that follow them.
2342 Potentially-embarrassing characters are / and *
2343 (because a backslash-newline inside a comment delimiter
2344 would cause it not to be recognized). */
2350 register U_CHAR *p = bp;
2352 /* First count the backslash-newline pairs here. */
2354 while (p[0] == '\\' && p[1] == '\n')
2357 /* What follows the backslash-newlines is not embarrassing. */
2359 if (*p != '/' && *p != '*')
2362 /* Copy all potentially embarrassing characters
2363 that follow the backslash-newline pairs
2364 down to where the pairs originally started. */
2366 while (*p == '*' || *p == '/')
2369 /* Now write the same number of pairs after the embarrassing chars. */
2376 /* Like newline_fix but for use within a directive-name.
2377 Move any backslash-newlines up past any following symbol constituents. */
2380 name_newline_fix (bp)
2383 register U_CHAR *p = bp;
2385 /* First count the backslash-newline pairs here. */
2386 while (p[0] == '\\' && p[1] == '\n')
2389 /* What follows the backslash-newlines is not embarrassing. */
2394 /* Copy all potentially embarrassing characters
2395 that follow the backslash-newline pairs
2396 down to where the pairs originally started. */
2398 while (is_idchar[*p])
2401 /* Now write the same number of pairs after the embarrassing chars. */
2408 /* Look for lint commands in comments.
2410 When we come in here, ibp points into a comment. Limit is as one expects.
2411 scan within the comment -- it should start, after lwsp, with a lint command.
2412 If so that command is returned as a (constant) string.
2414 Upon return, any arg will be pointed to with argstart and will be
2415 arglen long. Note that we don't parse that arg since it will just
2416 be printed out again. */
2419 get_lintcmd (ibp, limit, argstart, arglen, cmdlen)
2420 register U_CHAR *ibp;
2421 register U_CHAR *limit;
2422 U_CHAR **argstart; /* point to command arg */
2423 int *arglen, *cmdlen; /* how long they are */
2425 HOST_WIDEST_INT linsize;
2426 register U_CHAR *numptr; /* temp for arg parsing */
2430 SKIP_WHITE_SPACE (ibp);
2432 if (ibp >= limit) return NULL;
2434 linsize = limit - ibp;
2436 /* Oh, I wish C had lexical functions... hell, I'll just open-code the set */
2437 if ((linsize >= 10) && !bcmp (ibp, "NOTREACHED", 10)) {
2439 return "NOTREACHED";
2441 if ((linsize >= 8) && !bcmp (ibp, "ARGSUSED", 8)) {
2445 if ((linsize >= 11) && !bcmp (ibp, "LINTLIBRARY", 11)) {
2447 return "LINTLIBRARY";
2449 if ((linsize >= 7) && !bcmp (ibp, "VARARGS", 7)) {
2451 ibp += 7; linsize -= 7;
2452 if ((linsize == 0) || ! ISDIGIT (*ibp)) return "VARARGS";
2454 /* OK, read a number */
2455 for (numptr = *argstart = ibp; (numptr < limit) && ISDIGIT (*numptr);
2457 *arglen = numptr - *argstart;
2464 * The main loop of the program.
2466 * Read characters from the input stack, transferring them to the
2469 * Macros are expanded and push levels on the input stack.
2470 * At the end of such a level it is popped off and we keep reading.
2471 * At the end of any other kind of level, we return.
2472 * #-directives are handled, except within macros.
2474 * If OUTPUT_MARKS is nonzero, keep Newline markers found in the input
2475 * and insert them when appropriate. This is set while scanning macro
2476 * arguments before substitution. It is zero when scanning for final output.
2477 * There are three types of Newline markers:
2478 * * Newline - follows a macro name that was not expanded
2479 * because it appeared inside an expansion of the same macro.
2480 * This marker prevents future expansion of that identifier.
2481 * When the input is rescanned into the final output, these are deleted.
2482 * These are also deleted by ## concatenation.
2483 * * Newline Space (or Newline and any other whitespace character)
2484 * stands for a place that tokens must be separated or whitespace
2485 * is otherwise desirable, but where the ANSI standard specifies there
2486 * is no whitespace. This marker turns into a Space (or whichever other
2487 * whitespace char appears in the marker) in the final output,
2488 * but it turns into nothing in an argument that is stringified with #.
2489 * Such stringified arguments are the only place where the ANSI standard
2490 * specifies with precision that whitespace may not appear.
2492 * During this function, IP->bufp is kept cached in IBP for speed of access.
2493 * Likewise, OP->bufp is kept in OBP. Before calling a subroutine
2494 * IBP, IP and OBP must be copied back to memory. IP and IBP are
2495 * copied back with the RECACHE macro. OBP must be copied back from OP->bufp
2496 * explicitly, and before RECACHE, since RECACHE uses OBP.
2500 rescan (op, output_marks)
2504 /* Character being scanned in main loop. */
2507 /* Length of pending accumulated identifier. */
2508 register int ident_length = 0;
2510 /* Hash code of pending accumulated identifier. */
2511 register int hash = 0;
2513 /* Current input level (&instack[indepth]). */
2516 /* Pointer for scanning input. */
2517 register U_CHAR *ibp;
2519 /* Pointer to end of input. End of scan is controlled by LIMIT. */
2520 register U_CHAR *limit;
2522 /* Pointer for storing output. */
2523 register U_CHAR *obp;
2525 /* REDO_CHAR is nonzero if we are processing an identifier
2526 after backing up over the terminating character.
2527 Sometimes we process an identifier without backing up over
2528 the terminating character, if the terminating character
2529 is not special. Backing up is done so that the terminating character
2530 will be dispatched on again once the identifier is dealt with. */
2533 /* 1 if within an identifier inside of which a concatenation
2534 marker (Newline -) has been seen. */
2535 int concatenated = 0;
2537 /* While scanning a comment or a string constant,
2538 this records the line it started on, for error messages. */
2541 /* Record position of last `real' newline. */
2542 U_CHAR *beg_of_line;
2544 /* Pop the innermost input stack level, assuming it is a macro expansion. */
2547 do { ip->macro->type = T_MACRO; \
2548 if (ip->free_ptr) free (ip->free_ptr); \
2549 --indepth; } while (0)
2551 /* Reload `rescan's local variables that describe the current
2552 level of the input stack. */
2555 do { ip = &instack[indepth]; \
2557 limit = ip->buf + ip->length; \
2559 check_expand (op, limit - ibp); \
2561 obp = op->bufp; } while (0)
2563 if (no_output && instack[indepth].fname != 0)
2564 skip_if_group (&instack[indepth], 1, NULL);
2571 /* Our caller must always put a null after the end of
2572 the input at each input stack level. */
2582 if (*ibp == '\n' && !ip->macro) {
2583 /* At the top level, always merge lines ending with backslash-newline,
2584 even in middle of identifier. But do not merge lines in a macro,
2585 since backslash might be followed by a newline-space marker. */
2588 --obp; /* remove backslash from obuf */
2591 /* If ANSI, backslash is just another character outside a string. */
2594 /* Otherwise, backslash suppresses specialness of following char,
2595 so copy it here to prevent the switch from seeing it.
2596 But first get any pending identifier processed. */
2597 if (ident_length > 0)
2604 if (ident_length || ip->macro || traditional)
2606 while (*ibp == '\\' && ibp[1] == '\n') {
2612 /* Treat this %: digraph as if it were #. */
2616 if (assertions_flag) {
2619 /* Copy #foo (bar lose) without macro expansion. */
2620 obp[-1] = '#'; /* In case it was '%'. */
2621 SKIP_WHITE_SPACE (ibp);
2622 while (is_idchar[*ibp])
2624 SKIP_WHITE_SPACE (ibp);
2627 skip_paren_group (ip);
2628 bcopy ((char *) ibp, (char *) obp, ip->bufp - ibp);
2629 obp += ip->bufp - ibp;
2635 /* If this is expanding a macro definition, don't recognize
2636 preprocessing directives. */
2639 /* If this is expand_into_temp_buffer,
2640 don't recognize them either. Warn about them
2641 only after an actual newline at this level,
2642 not at the beginning of the input level. */
2644 if (ip->buf != beg_of_line)
2645 warning ("preprocessing directive not recognized within macro arg");
2652 /* # keyword: a # must be first nonblank char on the line */
2653 if (beg_of_line == 0)
2658 /* Scan from start of line, skipping whitespace, comments
2659 and backslash-newlines, and see if we reach this #.
2660 If not, this # is not special. */
2662 /* If -traditional, require # to be at beginning of line. */
2665 if (is_hor_space[*bp])
2667 else if (*bp == '\\' && bp[1] == '\n')
2669 else if (*bp == '/' && bp[1] == '*') {
2683 #ifdef MULTIBYTE_CHARS
2685 length = local_mblen (bp, limit - bp);
2693 /* There is no point in trying to deal with C++ // comments here,
2694 because if there is one, then this # must be part of the
2695 comment and we would never reach here. */
2701 while (bp[1] == '\\' && bp[2] == '\n')
2705 /* %: appears at start of line; skip past the ':' too. */
2714 /* This # can start a directive. */
2716 --obp; /* Don't copy the '#' */
2720 if (! handle_directive (ip, op)) {
2724 /* Not a known directive: treat it as ordinary text.
2725 IP, OP, IBP, etc. have not been changed. */
2726 if (no_output && instack[indepth].fname) {
2727 /* If not generating expanded output,
2728 what we do with ordinary text is skip it.
2729 Discard everything until next # directive. */
2730 skip_if_group (&instack[indepth], 1, 0);
2735 *obp++ = '#'; /* Copy # (even if it was originally %:). */
2736 /* Don't expand an identifier that could be a macro directive.
2737 (Section 3.8.3 of the ANSI C standard) */
2738 SKIP_WHITE_SPACE (ibp);
2739 if (is_idstart[*ibp])
2742 while (is_idchar[*ibp])
2750 /* A # directive has been successfully processed. */
2751 /* If not generating expanded output, ignore everything until
2752 next # directive. */
2753 if (no_output && instack[indepth].fname)
2754 skip_if_group (&instack[indepth], 1, 0);
2760 case '\"': /* skip quoted string */
2762 /* A single quoted string is treated like a double -- some
2763 programs (e.g., troff) are perverse this way */
2765 /* Handle any pending identifier;
2766 but the L in L'...' or L"..." is not an identifier. */
2768 if (! (ident_length == 1 && hash == HASHSTEP (0, 'L')))
2770 ident_length = hash = 0;
2773 start_line = ip->lineno;
2775 /* Skip ahead to a matching quote. */
2779 if (ip->macro != 0) {
2780 /* try harder: this string crosses a macro expansion boundary.
2781 This can happen naturally if -traditional.
2782 Otherwise, only -D can make a macro with an unmatched quote. */
2788 error_with_line (line_for_error (start_line),
2789 "unterminated string or character constant");
2790 if (multiline_string_line) {
2791 error_with_line (multiline_string_line,
2792 "possible real start of unterminated constant");
2793 multiline_string_line = 0;
2803 /* Traditionally, end of line ends a string constant with no error.
2804 So exit the loop and record the new line. */
2810 error_with_line (line_for_error (start_line),
2811 "unterminated character constant");
2814 if (multiline_string_line == 0) {
2816 pedwarn_with_line (line_for_error (start_line),
2817 "string constant runs past end of line");
2818 multiline_string_line = ip->lineno - 1;
2824 /* Backslash newline is replaced by nothing at all, but
2825 keep the line counts correct. But if we are reading
2826 from a macro, keep the backslash newline, since backslash
2827 newlines have already been processed. */
2835 /* ANSI stupidly requires that in \\ the second \
2836 is *not* prevented from combining with a newline. */
2838 while (*ibp == '\\' && ibp[1] == '\n') {
2852 #ifdef MULTIBYTE_CHARS
2857 length = local_mblen (ibp, limit - ibp);
2861 bcopy (ibp, obp, length);
2878 if (*ibp == '\\' && ibp[1] == '\n')
2881 && !(cplusplus_comments && *ibp == '/'))
2887 /* C++ style comment... */
2888 start_line = ip->lineno;
2890 /* Comments are equivalent to spaces. */
2891 if (! put_out_comments)
2895 U_CHAR *before_bp = ibp;
2897 while (++ibp < limit) {
2900 if (put_out_comments) {
2901 bcopy ((char *) before_bp, (char *) obp, ibp - before_bp);
2902 obp += ibp - before_bp;
2908 if (ibp + 1 < limit && ibp[1] == '\n')
2911 warning ("multiline `//' comment");
2913 /* Copy the newline into the output buffer, in order to
2914 avoid the pain of a #line every time a multiline comment
2916 if (!put_out_comments)
2924 #ifdef MULTIBYTE_CHARS
2926 length = local_mblen (ibp, limit - ibp);
2928 ibp += (length - 1);
2936 /* Ordinary C comment. Skip it, optionally copying it to output. */
2938 start_line = ip->lineno;
2940 ++ibp; /* Skip the star. */
2942 /* If this cpp is for lint, we peek inside the comments: */
2946 char *lintcmd = get_lintcmd (ibp, limit, &argbp, &arglen, &cmdlen);
2948 if (lintcmd != NULL) {
2950 check_expand (op, cmdlen + arglen + 14);
2952 /* I believe it is always safe to emit this newline: */
2954 bcopy ("#pragma lint ", (char *) obp, 13);
2956 bcopy (lintcmd, (char *) obp, cmdlen);
2961 bcopy (argbp, (char *) obp, arglen);
2965 /* OK, now bring us back to the state we were in before we entered
2966 this branch. We need #line because the #pragma's newline always
2967 messes up the line count. */
2969 output_line_directive (ip, op, 0, same_file);
2970 check_expand (op, limit - ibp + 2);
2976 /* Comments are equivalent to spaces.
2977 Note that we already output the slash; we might not want it.
2978 For -traditional, a comment is equivalent to nothing. */
2979 if (! put_out_comments) {
2989 U_CHAR *before_bp = ibp;
2994 if (ibp[-2] == '/' && warn_comments)
2995 warning ("`/*' within comment");
2996 if (*ibp == '\\' && ibp[1] == '\n')
3004 /* Copy the newline into the output buffer, in order to
3005 avoid the pain of a #line every time a multiline comment
3007 if (!put_out_comments)
3014 error_with_line (line_for_error (start_line),
3015 "unterminated comment");
3019 #ifdef MULTIBYTE_CHARS
3023 length = local_mblen (ibp, limit - ibp);
3025 ibp += (length - 1);
3034 if (put_out_comments) {
3035 bcopy ((char *) before_bp, (char *) obp, ibp - before_bp);
3036 obp += ibp - before_bp;
3042 if (! is_idchar['$'])
3045 pedwarn ("`$' in identifier");
3048 case '0': case '1': case '2': case '3': case '4':
3049 case '5': case '6': case '7': case '8': case '9':
3050 /* If digit is not part of identifier, it starts a number,
3051 which means that following letters are not an identifier.
3052 "0x5" does not refer to an identifier "x5".
3053 So copy all alphanumerics that follow without accumulating
3054 as an identifier. Periods also, for sake of "3.e7". */
3056 if (ident_length == 0) {
3059 while (ibp[0] == '\\' && ibp[1] == '\n') {
3065 if (!is_idchar[c] && c != '.') {
3070 /* A sign can be part of a preprocessing number
3071 if it follows an `e' or `p'. */
3072 if (c == 'e' || c == 'E' || c == 'p' || c == 'P') {
3074 while (ibp[0] == '\\' && ibp[1] == '\n') {
3079 if (*ibp == '+' || *ibp == '-') {
3081 /* But traditional C does not let the token go past the sign,
3082 and C89 does not allow `p'. */
3083 if (traditional || (c89 && (c == 'p' || c == 'P')))
3093 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
3094 case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
3095 case 'm': case 'n': case 'o': case 'p': case 'q': case 'r':
3096 case 's': case 't': case 'u': case 'v': case 'w': case 'x':
3098 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
3099 case 'G': case 'H': case 'I': case 'J': case 'K': case 'L':
3100 case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R':
3101 case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
3105 /* Compute step of hash function, to avoid a proc call on every token */
3106 hash = HASHSTEP (hash, c);
3110 if (ip->fname == 0 && *ibp == '-') {
3111 /* Newline - inhibits expansion of preceding token.
3112 If expanding a macro arg, we keep the newline -.
3113 In final output, it is deleted.
3114 We recognize Newline - in macro bodies and macro args. */
3115 if (! concatenated) {
3120 if (!output_marks) {
3123 /* If expanding a macro arg, keep the newline -. */
3129 /* If reprocessing a macro expansion, newline is a special marker. */
3130 else if (ip->macro != 0) {
3131 /* Newline White is a "funny space" to separate tokens that are
3132 supposed to be separate but without space between.
3133 Here White means any whitespace character.
3134 Newline - marks a recursive macro use that is not
3135 supposed to be expandable. */
3137 if (is_space[*ibp]) {
3138 /* Newline Space does not prevent expansion of preceding token
3139 so expand the preceding token and then come back. */
3140 if (ident_length > 0)
3143 /* If generating final output, newline space makes a space. */
3144 if (!output_marks) {
3146 /* And Newline Newline makes a newline, so count it. */
3147 if (obp[-1] == '\n')
3150 /* If expanding a macro arg, keep the newline space.
3151 If the arg gets stringified, newline space makes nothing. */
3154 } else abort (); /* Newline followed by something random? */
3158 /* If there is a pending identifier, handle it and come back here. */
3159 if (ident_length > 0)
3164 /* Update the line counts and output a #line if necessary. */
3167 if (ip->lineno != op->lineno) {
3169 output_line_directive (ip, op, 1, same_file);
3170 check_expand (op, limit - ibp);
3175 /* Come here either after (1) a null character that is part of the input
3176 or (2) at the end of the input, because there is a null there. */
3179 /* Our input really contains a null character. */
3183 /* At end of a macro-expansion level, pop it and read next level. */
3184 if (ip->macro != 0) {
3187 /* If traditional, and we have an identifier that ends here,
3188 process it now, so we get the right error for recursion. */
3189 if (traditional && ident_length
3190 && ! is_idchar[*instack[indepth - 1].bufp]) {
3199 /* If we don't have a pending identifier,
3200 return at end of input. */
3201 if (ident_length == 0) {
3209 /* If we do have a pending identifier, just consider this null
3210 a special character and arrange to dispatch on it again.
3211 The second time, IDENT_LENGTH will be zero so we will return. */
3217 /* Handle the case of a character such as /, ', " or null
3218 seen following an identifier. Back over it so that
3219 after the identifier is processed the special char
3220 will be dispatched on again. */
3230 if (ident_length > 0) {
3231 register HASHNODE *hp;
3233 /* We have just seen an identifier end. If it's a macro, expand it.
3235 IDENT_LENGTH is the length of the identifier
3236 and HASH is its hash code.
3238 The identifier has already been copied to the output,
3239 so if it is a macro we must remove it.
3241 If REDO_CHAR is 0, the char that terminated the identifier
3242 has been skipped in the output and the input.
3243 OBP-IDENT_LENGTH-1 points to the identifier.
3244 If the identifier is a macro, we must back over the terminator.
3246 If REDO_CHAR is 1, the terminating char has already been
3247 backed over. OBP-IDENT_LENGTH points to the identifier. */
3249 if (!pcp_outfile || pcp_inside_if) {
3250 for (hp = hashtab[MAKE_POS (hash) % HASHSIZE]; hp != NULL;
3253 if (hp->length == ident_length) {
3254 int obufp_before_macroname;
3255 int op_lineno_before_macroname;
3256 register int i = ident_length;
3257 register U_CHAR *p = hp->name;
3258 register U_CHAR *q = obp - i;
3264 do { /* All this to avoid a strncmp () */
3269 /* We found a use of a macro name.
3270 see if the context shows it is a macro call. */
3272 /* Back up over terminating character if not already done. */
3278 /* Save this as a displacement from the beginning of the output
3279 buffer. We can not save this as a position in the output
3280 buffer, because it may get realloc'ed by RECACHE. */
3281 obufp_before_macroname = (obp - op->buf) - ident_length;
3282 op_lineno_before_macroname = op->lineno;
3284 if (hp->type == T_PCSTRING) {
3285 pcstring_used (hp); /* Mark the definition of this key
3286 as needed, ensuring that it
3288 break; /* Exit loop, since the key cannot have a
3289 definition any longer. */
3292 /* Record whether the macro is disabled. */
3293 disabled = hp->type == T_DISABLED;
3295 /* This looks like a macro ref, but if the macro was disabled,
3296 just copy its name and put in a marker if requested. */
3300 /* This error check caught useful cases such as
3301 #define foo(x,y) bar (x (y,0), y)
3304 error ("recursive use of macro `%s'", hp->name);
3309 check_expand (op, limit - ibp + 2);
3317 /* If macro wants an arglist, verify that a '(' follows.
3318 first skip all whitespace, copying it to the output
3319 after the macro name. Then, if there is no '(',
3320 decide this is not a macro call and leave things that way. */
3321 if ((hp->type == T_MACRO || hp->type == T_DISABLED)
3322 && hp->value.defn->nargs >= 0)
3324 U_CHAR *old_ibp = ibp;
3325 U_CHAR *old_obp = obp;
3326 int old_iln = ip->lineno;
3327 int old_oln = op->lineno;
3330 /* Scan forward over whitespace, copying it to the output. */
3331 if (ibp == limit && ip->macro != 0) {
3336 old_iln = ip->lineno;
3337 old_oln = op->lineno;
3339 else if (is_space[*ibp]) {
3341 if (ibp[-1] == '\n') {
3342 if (ip->macro == 0) {
3343 /* Newline in a file. Count it. */
3346 } else if (!output_marks) {
3347 /* A newline mark, and we don't want marks
3348 in the output. If it is newline-hyphen,
3349 discard it entirely. Otherwise, it is
3350 newline-whitechar, so keep the whitechar. */
3360 /* A newline mark; copy both chars to the output. */
3367 else if (*ibp == '/') {
3368 /* If a comment, copy it unchanged or discard it. */
3369 if (ibp[1] == '\\' && ibp[2] == '\n')
3370 newline_fix (ibp + 1);
3371 if (ibp[1] == '*') {
3372 if (put_out_comments) {
3375 } else if (! traditional) {
3378 for (ibp += 2; ibp < limit; ibp++) {
3379 /* We need not worry about newline-marks,
3380 since they are never found in comments. */
3381 if (ibp[0] == '*') {
3382 if (ibp[1] == '\\' && ibp[2] == '\n')
3383 newline_fix (ibp + 1);
3384 if (ibp[1] == '/') {
3386 if (put_out_comments) {
3393 else if (*ibp == '\n') {
3394 /* Newline in a file. Count it. */
3400 #ifdef MULTIBYTE_CHARS
3402 length = local_mblen (ibp, limit - ibp);
3405 if (put_out_comments)
3407 bcopy (ibp, obp, length - 1);
3410 ibp += (length - 1);
3414 if (put_out_comments)
3417 } else if (ibp[1] == '/' && cplusplus_comments) {
3418 if (put_out_comments) {
3421 } else if (! traditional) {
3424 for (ibp += 2; ; ibp++)
3428 if (*ibp == '\\' && ibp[1] == '\n')
3430 if (put_out_comments)
3435 #ifdef MULTIBYTE_CHARS
3437 length = local_mblen (ibp, limit - ibp);
3440 if (put_out_comments)
3442 bcopy (ibp, obp, length - 1);
3445 ibp += (length - 1);
3449 if (put_out_comments)
3455 else if (ibp[0] == '\\' && ibp[1] == '\n') {
3462 /* It isn't a macro call.
3463 Put back the space that we just skipped. */
3466 ip->lineno = old_iln;
3467 op->lineno = old_oln;
3468 /* Exit the for loop. */
3473 /* This is now known to be a macro call.
3474 Discard the macro name from the output,
3475 along with any following whitespace just copied,
3476 but preserve newlines if not outputting marks since this
3477 is more likely to do the right thing with line numbers. */
3478 obp = op->buf + obufp_before_macroname;
3480 op->lineno = op_lineno_before_macroname;
3482 int newlines = op->lineno - op_lineno_before_macroname;
3483 while (0 < newlines--)
3487 /* Prevent accidental token-pasting with a character
3488 before the macro call. */
3489 if (!traditional && obp != op->buf) {
3491 case '!': case '%': case '&': case '*':
3492 case '+': case '-': case '.': case '/':
3493 case ':': case '<': case '=': case '>':
3495 /* If we are expanding a macro arg, make a newline marker
3496 to separate the tokens. If we are making real output,
3497 a plain space will do. */
3504 /* Expand the macro, reading arguments as needed,
3505 and push the expansion on the input stack. */
3508 macroexpand (hp, op);
3510 /* Reexamine input stack, since macroexpand has pushed
3511 a new level on it. */
3518 } /* End hash-table-search loop */
3520 ident_length = hash = 0; /* Stop collecting identifier */
3523 } /* End if (ident_length > 0) */
3525 } /* End per-char loop */
3527 /* Come here to return -- but first give an error message
3528 if there was an unterminated successful conditional. */
3530 if (if_stack != ip->if_stack)
3534 switch (if_stack->type)
3555 error_with_line (line_for_error (if_stack->lineno),
3556 "unterminated `#%s' conditional", str);
3558 if_stack = ip->if_stack;
3562 * Rescan a string into a temporary buffer and return the result
3563 * as a FILE_BUF. Note this function returns a struct, not a pointer.
3565 * OUTPUT_MARKS nonzero means keep Newline markers found in the input
3566 * and insert such markers when appropriate. See `rescan' for details.
3567 * OUTPUT_MARKS is 1 for macroexpanding a macro argument separately
3568 * before substitution; it is 0 for other uses.
3571 expand_to_temp_buffer (buf, limit, output_marks, assertions)
3572 U_CHAR *buf, *limit;
3573 int output_marks, assertions;
3575 register FILE_BUF *ip;
3577 int length = limit - buf;
3579 int odepth = indepth;
3580 int save_assertions_flag = assertions_flag;
3582 assertions_flag = assertions;
3587 /* Set up the input on the input stack. */
3589 buf1 = (U_CHAR *) alloca (length + 1);
3591 register U_CHAR *p1 = buf;
3592 register U_CHAR *p2 = buf1;
3599 /* Set up to receive the output. */
3601 obuf.length = length * 2 + 100; /* Usually enough. Why be stingy? */
3602 obuf.bufp = obuf.buf = (U_CHAR *) xmalloc (obuf.length);
3603 obuf.nominal_fname = 0;
3610 obuf.system_header_p = 0;
3612 CHECK_DEPTH ({return obuf;});
3616 ip = &instack[indepth];
3618 ip->nominal_fname = 0;
3619 ip->nominal_fname_len = 0;
3621 ip->system_header_p = 0;
3624 ip->length = length;
3625 ip->buf = ip->bufp = buf1;
3626 ip->if_stack = if_stack;
3628 ip->lineno = obuf.lineno = 1;
3630 /* Scan the input, create the output. */
3631 rescan (&obuf, output_marks);
3633 /* Pop input stack to original state. */
3636 if (indepth != odepth)
3639 /* Record the output. */
3640 obuf.length = obuf.bufp - obuf.buf;
3642 assertions_flag = save_assertions_flag;
3647 * Process a # directive. Expects IP->bufp to point after the '#', as in
3648 * `#define foo bar'. Passes to the directive handler
3649 * (do_define, do_include, etc.): the addresses of the 1st and
3650 * last chars of the directive (starting immediately after the #
3651 * keyword), plus op and the keyword table pointer. If the directive
3652 * contains comments it is copied into a temporary buffer sans comments
3653 * and the temporary buffer is passed to the directive handler instead.
3654 * Likewise for backslash-newlines.
3656 * Returns nonzero if this was a known # directive.
3657 * Otherwise, returns zero, without advancing the input pointer.
3661 handle_directive (ip, op)
3664 register U_CHAR *bp, *cp;
3665 register struct directive *kt;
3666 register int ident_length;
3669 /* Nonzero means we must copy the entire directive
3670 to get rid of comments or backslash-newlines. */
3671 int copy_directive = 0;
3673 U_CHAR *ident, *after_ident;
3677 /* Record where the directive started. do_xifdef needs this. */
3678 directive_start = bp - 1;
3680 ignore_escape_flag = 1;
3682 /* Skip whitespace and \-newline. */
3684 if (is_hor_space[*bp]) {
3685 if (*bp != ' ' && *bp != '\t' && pedantic)
3686 pedwarn_strange_white_space (*bp);
3688 } else if (*bp == '/') {
3689 if (bp[1] == '\\' && bp[2] == '\n')
3690 newline_fix (bp + 1);
3691 if (! (bp[1] == '*' || (cplusplus_comments && bp[1] == '/')))
3694 skip_to_end_of_comment (ip, &ip->lineno, 0);
3696 } else if (*bp == '\\' && bp[1] == '\n') {
3697 bp += 2; ip->lineno++;
3701 /* Now find end of directive name.
3702 If we encounter a backslash-newline, exchange it with any following
3703 symbol-constituents so that we end up with a contiguous name. */
3710 if (*cp == '\\' && cp[1] == '\n')
3711 name_newline_fix (cp);
3717 ident_length = cp - bp;
3721 /* A line of just `#' becomes blank. */
3723 if (ident_length == 0 && *after_ident == '\n') {
3724 ip->bufp = after_ident;
3728 if (ident_length == 0 || !is_idstart[*ident]) {
3730 while (is_idchar[*p]) {
3731 if (*p < '0' || *p > '9')
3735 /* Handle # followed by a line number. */
3736 if (p != ident && !is_idchar[*p]) {
3737 static struct directive line_directive_table[] = {
3738 { 4, do_line, "line", T_LINE},
3741 pedwarn ("`#' followed by integer");
3742 after_ident = ident;
3743 kt = line_directive_table;
3744 ignore_escape_flag = 0;
3748 /* Avoid error for `###' and similar cases unless -pedantic. */
3750 while (*p == '#' || is_hor_space[*p]) p++;
3752 if (pedantic && !lang_asm)
3753 warning ("invalid preprocessing directive");
3759 error ("invalid preprocessing directive name");
3765 * Decode the keyword and call the appropriate expansion
3766 * routine, after moving the input pointer up to the next line.
3768 for (kt = directive_table; kt->length > 0; kt++) {
3769 if (kt->length == ident_length && !bcmp (kt->name, ident, ident_length)) {
3770 register U_CHAR *buf;
3771 register U_CHAR *limit;
3774 int *already_output;
3776 /* Nonzero means do not delete comments within the directive.
3777 #define needs this when -traditional. */
3782 limit = ip->buf + ip->length;
3785 keep_comments = traditional && kt->type == T_DEFINE;
3786 /* #import is defined only in Objective C, or when on the NeXT. */
3787 if (kt->type == T_IMPORT
3788 && !(objc || lookup ((U_CHAR *) "__NeXT__", -1, -1)))
3791 /* Find the end of this directive (first newline not backslashed
3792 and not in a string or comment).
3793 Set COPY_DIRECTIVE if the directive must be copied
3794 (it contains a backslash-newline or a comment). */
3796 buf = bp = after_ident;
3797 while (bp < limit) {
3798 register U_CHAR c = *bp++;
3806 } else if (traditional)
3812 /* "..." is special for #include. */
3813 if (IS_INCLUDE_DIRECTIVE_TYPE (kt->type)) {
3814 while (bp < limit && *bp != '\n') {
3819 if (*bp == '\\' && bp[1] == '\n') {
3830 bp = skip_quoted_string (bp - 1, limit, ip->lineno, &ip->lineno, ©_directive, &unterminated);
3831 /* Don't bother calling the directive if we already got an error
3832 message due to unterminated string. Skip everything and pretend
3833 we called the directive. */
3836 /* Traditional preprocessing permits unterminated strings. */
3845 /* <...> is special for #include. */
3847 if (! IS_INCLUDE_DIRECTIVE_TYPE (kt->type))
3849 while (bp < limit && *bp != '>' && *bp != '\n') {
3850 if (*bp == '\\' && bp[1] == '\n') {
3860 if (*bp == '\\' && bp[1] == '\n')
3863 || (cplusplus_comments && *bp == '/')) {
3864 U_CHAR *obp = bp - 1;
3866 skip_to_end_of_comment (ip, &ip->lineno, 0);
3868 /* No need to copy the directive because of a comment at the end;
3869 just don't include the comment in the directive. */
3870 if (!put_out_comments) {
3872 for (p = bp; *p == ' ' || *p == '\t'; p++)
3879 /* Don't remove the comments if -traditional. */
3880 if (! keep_comments)
3889 pedwarn_strange_white_space (c);
3893 --bp; /* Point to the newline */
3901 resume_p = ip->bufp;
3902 /* BP is the end of the directive.
3903 RESUME_P is the next interesting data after the directive.
3904 A comment may come between. */
3906 /* If a directive should be copied through, and -C was given,
3907 pass it through before removing comments. */
3908 if (!no_output && put_out_comments
3909 && ((kt->type == T_DEFINE || kt->type == T_UNDEF)
3910 ? dump_macros == dump_definitions
3911 : IS_INCLUDE_DIRECTIVE_TYPE (kt->type) ? dump_includes
3912 : kt->type == T_PRAGMA)) {
3915 /* Output directive name. */
3916 check_expand (op, kt->length + 2);
3917 /* Make sure # is at the start of a line */
3918 if (op->bufp > op->buf && op->bufp[-1] != '\n') {
3923 bcopy (kt->name, op->bufp, kt->length);
3924 op->bufp += kt->length;
3926 /* Output arguments. */
3928 check_expand (op, len);
3929 bcopy (buf, (char *) op->bufp, len);
3931 /* Take account of any (escaped) newlines just output. */
3933 if (buf[len] == '\n')
3936 already_output = &junk;
3937 } /* Don't we need a newline or #line? */
3939 if (copy_directive) {
3940 register U_CHAR *xp = buf;
3941 /* Need to copy entire directive into temp buffer before dispatching */
3943 cp = (U_CHAR *) alloca (bp - buf + 5); /* room for directive plus
3947 /* Copy to the new buffer, deleting comments
3948 and backslash-newlines (and whitespace surrounding the latter). */
3951 register U_CHAR c = *xp++;
3956 abort (); /* A bare newline should never part of the line. */
3959 /* <...> is special for #include. */
3961 if (! IS_INCLUDE_DIRECTIVE_TYPE (kt->type))
3963 while (xp < bp && c != '>') {
3965 if (c == '\\' && xp < bp && *xp == '\n')
3976 if (cp != buf && is_hor_space[cp[-1]]) {
3977 while (cp - 1 != buf && is_hor_space[cp[-2]])
3979 SKIP_WHITE_SPACE (xp);
3980 } else if (is_hor_space[*xp]) {
3982 SKIP_WHITE_SPACE (xp);
3984 } else if (traditional && xp < bp) {
3992 int backslash_newlines_p = 0;
3994 register U_CHAR *bp1
3995 = skip_quoted_string (xp - 1, bp, ip->lineno,
3996 NULL_PTR, &backslash_newlines_p,
3998 if (backslash_newlines_p)
4001 /* With something like:
4006 we should still remove the backslash-newline
4007 pair as part of phase two. */
4008 if (xp[0] == '\\' && xp[1] == '\n')
4014 /* This is the same as the loop above, but taking
4015 advantage of the fact that we know there are no
4016 backslash-newline pairs. */
4024 || (cplusplus_comments && *xp == '/')) {
4026 /* If we already copied the directive through,
4027 already_output != 0 prevents outputting comment now. */
4028 skip_to_end_of_comment (ip, already_output, 0);
4030 while (xp != ip->bufp)
4032 /* Delete or replace the slash. */
4033 else if (traditional)
4042 /* Null-terminate the copy. */
4048 ip->bufp = resume_p;
4050 /* Some directives should be written out for cc1 to process,
4051 just as if they were not defined. And sometimes we're copying
4052 directives through. */
4054 if (!no_output && already_output == 0
4055 && (kt->type == T_DEFINE ? (int) dump_names <= (int) dump_macros
4056 : IS_INCLUDE_DIRECTIVE_TYPE (kt->type) ? dump_includes
4057 : kt->type == T_PRAGMA)) {
4060 /* Output directive name. */
4061 check_expand (op, kt->length + 1);
4063 bcopy (kt->name, (char *) op->bufp, kt->length);
4064 op->bufp += kt->length;
4066 if (kt->type == T_DEFINE && dump_macros == dump_names) {
4067 /* Output `#define name' only. */
4070 SKIP_WHITE_SPACE (xp);
4072 while (is_idchar[*xp]) xp++;
4074 check_expand (op, len + 1);
4076 bcopy (yp, (char *) op->bufp, len);
4078 /* Output entire directive. */
4080 check_expand (op, len);
4081 bcopy (buf, (char *) op->bufp, len);
4084 } /* Don't we need a newline or #line? */
4086 /* Call the appropriate directive handler. buf now points to
4087 either the appropriate place in the input buffer, or to
4088 the temp buffer if it was necessary to make one. cp
4089 points to the first char after the contents of the (possibly
4090 copied) directive, in either case. */
4091 (*kt->func) (buf, cp, op, kt);
4092 check_expand (op, ip->length - (ip->bufp - ip->buf));
4098 /* It is deliberate that we don't warn about undefined directives.
4099 That is the responsibility of cc1. */
4106 static struct tm *timebuf;
4108 time_t t = time ((time_t *) 0);
4109 timebuf = localtime (&t);
4114 static char *monthnames[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
4115 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
4119 * expand things like __FILE__. Place the expansion into the output
4120 * buffer *without* rescanning.
4124 special_symbol (hp, op)
4131 FILE_BUF *ip = NULL;
4134 int paren = 0; /* For special `defined' keyword */
4136 if (pcp_outfile && pcp_inside_if
4137 && hp->type != T_SPEC_DEFINED && hp->type != T_CONST)
4138 error ("Predefined macro `%s' used inside `#if' during precompilation",
4141 for (i = indepth; i >= 0; i--)
4142 if (instack[i].fname != NULL) {
4147 error ("cccp error: not in any file?!");
4148 return; /* the show must go on */
4155 FILE_BUF *p = hp->type == T_FILE ? ip : &instack[0];
4156 char *string = p->nominal_fname;
4160 size_t string_len = p->nominal_fname_len;
4161 buf = (char *) alloca (3 + 4 * string_len);
4162 quote_string (buf, string, string_len);
4170 case T_INCLUDE_LEVEL:
4172 for (i = indepth; i >= 0; i--)
4173 if (instack[i].fname != NULL)
4176 buf = (char *) alloca (8); /* Eight bytes ought to be more than enough */
4177 sprintf (buf, "%d", true_indepth - 1);
4181 buf = (char *) alloca (3 + strlen (version_string));
4182 sprintf (buf, "\"%s\"", version_string);
4185 #ifndef NO_BUILTIN_SIZE_TYPE
4191 #ifndef NO_BUILTIN_PTRDIFF_TYPE
4192 case T_PTRDIFF_TYPE:
4201 case T_USER_LABEL_PREFIX_TYPE:
4202 buf = user_label_prefix;
4205 case T_REGISTER_PREFIX_TYPE:
4206 buf = REGISTER_PREFIX;
4209 case T_IMMEDIATE_PREFIX_TYPE:
4210 buf = IMMEDIATE_PREFIX;
4214 buf = hp->value.cpval;
4215 #ifdef STDC_0_IN_SYSTEM_HEADERS
4216 if (ip->system_header_p
4217 && hp->length == 8 && bcmp (hp->name, "__STDC__", 8) == 0
4218 && !lookup ((U_CHAR *) "__STRICT_ANSI__", -1, -1))
4221 if (pcp_inside_if && pcp_outfile)
4222 /* Output a precondition for this macro use */
4223 fprintf (pcp_outfile, "#define %s %s\n", hp->name, buf);
4227 buf = (char *) alloca (10);
4228 sprintf (buf, "%d", ip->lineno);
4233 buf = (char *) alloca (20);
4234 timebuf = timestamp ();
4235 if (hp->type == T_DATE)
4236 sprintf (buf, "\"%s %2d %4d\"", monthnames[timebuf->tm_mon],
4237 timebuf->tm_mday, timebuf->tm_year + 1900);
4239 sprintf (buf, "\"%02d:%02d:%02d\"", timebuf->tm_hour, timebuf->tm_min,
4243 case T_SPEC_DEFINED:
4244 buf = " 0 "; /* Assume symbol is not defined */
4245 ip = &instack[indepth];
4246 SKIP_WHITE_SPACE (ip->bufp);
4247 if (*ip->bufp == '(') {
4249 ip->bufp++; /* Skip over the paren */
4250 SKIP_WHITE_SPACE (ip->bufp);
4253 if (!is_idstart[*ip->bufp])
4255 if (ip->bufp[0] == 'L' && (ip->bufp[1] == '\'' || ip->bufp[1] == '"'))
4257 if ((hp = lookup (ip->bufp, -1, -1))) {
4258 if (pcp_outfile && pcp_inside_if
4259 && (hp->type == T_CONST
4260 || (hp->type == T_MACRO && hp->value.defn->predefined)))
4261 /* Output a precondition for this macro use. */
4262 fprintf (pcp_outfile, "#define %s\n", hp->name);
4266 if (pcp_outfile && pcp_inside_if) {
4267 /* Output a precondition for this macro use */
4268 U_CHAR *cp = ip->bufp;
4269 fprintf (pcp_outfile, "#undef ");
4270 while (is_idchar[*cp]) /* Ick! */
4271 fputc (*cp++, pcp_outfile);
4272 putc ('\n', pcp_outfile);
4274 while (is_idchar[*ip->bufp])
4276 SKIP_WHITE_SPACE (ip->bufp);
4278 if (*ip->bufp != ')')
4286 error ("`defined' without an identifier");
4290 error ("cccp error: invalid special hash type"); /* time for gdb */
4294 check_expand (op, len);
4295 bcopy (buf, (char *) op->bufp, len);
4302 /* Routines to handle #directives */
4304 /* Handle #include and #import.
4305 This function expects to see "fname" or <fname> on the input. */
4308 do_include (buf, limit, op, keyword)
4309 U_CHAR *buf, *limit;
4311 struct directive *keyword;
4313 U_CHAR *importing = keyword->type == T_IMPORT ? (U_CHAR *) "" : (U_CHAR *) 0;
4314 int skip_dirs = (keyword->type == T_INCLUDE_NEXT);
4315 static int import_warning = 0;
4316 char *fname; /* Dynamically allocated fname buffer */
4319 char *fbeg, *fend; /* Beginning and end of fname */
4322 struct file_name_list *search_start = include; /* Chain of dirs to search */
4323 struct file_name_list *dsp; /* First in chain, if #include "..." */
4324 struct file_name_list *searchptr = 0;
4327 int f = -3; /* file number */
4328 struct include_file *inc = 0;
4330 int retried = 0; /* Have already tried macro
4331 expanding the include line*/
4332 int angle_brackets = 0; /* 0 for "...", 1 for <...> */
4334 int vaxc_include = 0; /* 1 for token without punctuation */
4341 if (pedantic && !instack[indepth].system_header_p)
4344 pedwarn ("ANSI C does not allow `#import'");
4346 pedwarn ("ANSI C does not allow `#include_next'");
4349 if (importing && warn_import && !inhibit_warnings
4350 && !instack[indepth].system_header_p && !import_warning) {
4352 warning ("using `#import' is not recommended");
4353 notice ("The fact that a certain header file need not be processed more than once\n\
4354 should be indicated in the header file, not where it is used.\n\
4355 The best way to do this is with a conditional of this form:\n\
4357 #ifndef _FOO_H_INCLUDED\n\
4358 #define _FOO_H_INCLUDED\n\
4359 ... <real contents of file> ...\n\
4360 #endif /* Not _FOO_H_INCLUDED */\n\
4362 Then users can use `#include' any number of times.\n\
4363 GNU C automatically avoids processing the file more than once\n\
4364 when it is equipped with such a conditional.\n");
4370 SKIP_WHITE_SPACE (fin);
4371 /* Discard trailing whitespace so we can easily see
4372 if we have parsed all the significant chars we were given. */
4373 while (limit != fin && is_hor_space[limit[-1]]) limit--;
4374 fbeg = fend = (char *) alloca (limit - fin);
4380 /* Copy the operand text, concatenating the strings. */
4385 goto invalid_include_file_name;
4393 /* If not at the end, there had better be another string. */
4394 /* Skip just horiz space, and don't go past limit. */
4395 while (fin != limit && is_hor_space[*fin]) fin++;
4396 if (fin != limit && *fin == '\"')
4403 /* We have "filename". Figure out directory this source
4404 file is coming from and put it on the front of the list. */
4406 /* If -I- was specified, don't search current dir, only spec'd ones. */
4407 if (ignore_srcdir) break;
4409 for (fp = &instack[indepth]; fp >= instack; fp--)
4414 if ((nam = fp->nominal_fname) != NULL) {
4415 /* Found a named file. Figure out dir of the file,
4416 and put it in front of the search list. */
4417 dsp = ((struct file_name_list *)
4418 alloca (sizeof (struct file_name_list)
4419 + fp->nominal_fname_len));
4420 strcpy (dsp->fname, nam);
4421 simplify_filename (dsp->fname);
4422 nam = base_name (dsp->fname);
4425 /* for hack_vms_include_specification(), a local
4426 dir specification must start with "./" on VMS. */
4427 if (nam == dsp->fname)
4434 /* But for efficiency's sake, do not insert the dir
4435 if it matches the search list's first dir. */
4436 dsp->next = search_start;
4437 if (!search_start || strcmp (dsp->fname, search_start->fname)) {
4439 n = nam - dsp->fname;
4440 if (n + INCLUDE_LEN_FUDGE > max_include_len)
4441 max_include_len = n + INCLUDE_LEN_FUDGE;
4443 dsp[0].got_name_map = 0;
4451 while (fin != limit && *fin != '>')
4453 if (*fin == '>' && fin + 1 == limit) {
4455 /* If -I-, start with the first -I dir after the -I-. */
4456 search_start = first_bracket_include;
4464 * Support '#include xyz' like VAX-C to allow for easy use of all the
4465 * decwindow include files. It defaults to '#include <xyz.h>' (so the
4466 * code from case '<' is repeated here) and generates a warning.
4467 * (Note: macro expansion of `xyz' takes precedence.)
4469 /* Note: The argument of ISALPHA() can be evaluated twice, so do
4470 the pre-decrement outside of the macro. */
4471 if (retried && (--fin, ISALPHA(*(U_CHAR *) (fin)))) {
4472 while (fin != limit && (!ISSPACE(*fin)))
4474 warning ("VAX-C-style include specification found, use '#include <filename.h>' !");
4478 /* If -I-, start with the first -I dir after the -I-. */
4479 search_start = first_bracket_include;
4487 /* Expand buffer and then remove any newline markers.
4488 We can't just tell expand_to_temp_buffer to omit the markers,
4489 since it would put extra spaces in include file names. */
4492 int errors_before_expansion = errors;
4493 trybuf = expand_to_temp_buffer (buf, limit, 1, 0);
4494 if (errors != errors_before_expansion) {
4496 goto invalid_include_file_name;
4499 buf = (U_CHAR *) alloca (trybuf.bufp - trybuf.buf + 1);
4501 while (src != trybuf.bufp) {
4502 switch ((*limit++ = *src++)) {
4511 U_CHAR *src1 = skip_quoted_string (src - 1, trybuf.bufp, 0,
4512 NULL_PTR, NULL_PTR, NULL_PTR);
4525 invalid_include_file_name:
4526 error ("`#%s' expects \"FILENAME\" or <FILENAME>", keyword->name);
4530 /* For #include_next, skip in the search path
4531 past the dir in which the containing file was found. */
4534 for (fp = &instack[indepth]; fp >= instack; fp--)
4535 if (fp->fname != NULL) {
4536 /* fp->dir is null if the containing file was specified
4537 with an absolute file name. In that case, don't skip anything. */
4539 search_start = fp->dir->next;
4545 flen = simplify_filename (fbeg);
4549 error ("empty file name in `#%s'", keyword->name);
4553 /* Allocate this permanently, because it gets stored in the definitions
4555 fname = xmalloc (max_include_len + flen + 1);
4556 /* + 1 above for terminating null. */
4558 system_include_depth += angle_brackets;
4560 /* If specified file name is absolute, just open it. */
4562 if (absolute_filename (fbeg)) {
4563 strcpy (fname, fbeg);
4564 f = open_include_file (fname, NULL_PTR, importing, &inc);
4568 struct bypass_dir *next;
4570 struct file_name_list *searchptr;
4571 } **bypass_slot = 0;
4573 /* Search directory path, trying to open the file.
4574 Copy each filename tried into FNAME. */
4576 for (searchptr = search_start; searchptr; searchptr = searchptr->next) {
4578 if (searchptr == first_bracket_include) {
4579 /* Go to bypass directory if we know we've seen this file before. */
4580 static struct bypass_dir *bypass_hashtab[INCLUDE_HASHSIZE];
4581 struct bypass_dir *p;
4582 bypass_slot = &bypass_hashtab[hashf ((U_CHAR *) fbeg, flen,
4584 for (p = *bypass_slot; p; p = p->next)
4585 if (!strcmp (fbeg, p->fname)) {
4586 searchptr = p->searchptr;
4593 /* Change this 1/2 Unix 1/2 VMS file specification into a
4594 full VMS file specification */
4595 if (searchptr->fname[0])
4597 strcpy (fname, searchptr->fname);
4598 if (fname[strlen (fname) - 1] == ':')
4601 slashp = strchr (fbeg, '/');
4603 /* start at root-dir of logical device if no path given. */
4605 strcat (fname, "[000000]");
4607 strcat (fname, fbeg);
4609 /* Fix up the filename */
4610 hack_vms_include_specification (fname, vaxc_include);
4614 /* This is a normal VMS filespec, so use it unchanged. */
4615 strcpy (fname, fbeg);
4616 /* if it's '#include filename', add the missing .h */
4617 if (vaxc_include && index(fname,'.')==NULL)
4618 strcat (fname, ".h");
4621 strcpy (fname, searchptr->fname);
4622 strcat (fname, fbeg);
4624 f = open_include_file (fname, searchptr, importing, &inc);
4626 if (bypass_slot && searchptr != first_bracket_include) {
4627 /* This is the first time we found this include file,
4628 and we found it after first_bracket_include.
4629 Record its location so that we can bypass to here next time. */
4630 struct bypass_dir *p
4631 = (struct bypass_dir *) xmalloc (sizeof (struct bypass_dir));
4632 p->next = *bypass_slot;
4633 p->fname = fname + strlen (searchptr->fname);
4634 p->searchptr = searchptr;
4640 /* Our VMS hacks can produce invalid filespecs, so don't worry
4641 about errors other than EACCES. */
4642 if (errno == EACCES)
4645 if (errno != ENOENT && errno != ENOTDIR)
4655 /* The file was already included. */
4657 /* If generating dependencies and -MG was specified, we assume missing
4658 files are leaf files, living in the same directory as the source file
4659 or other similar place; these missing files may be generated from
4660 other files and may not exist yet (eg: y.tab.h). */
4661 } else if (print_deps_missing_files
4662 && (system_include_depth != 0) < print_deps)
4664 /* If it was requested as a system header file,
4665 then assume it belongs in the first place to look for such. */
4669 char *p = (char *) alloca (strlen (search_start->fname)
4670 + strlen (fbeg) + 1);
4671 strcpy (p, search_start->fname);
4673 deps_output (p, ' ');
4678 /* Otherwise, omit the directory, as if the file existed
4679 in the directory with the source. */
4680 deps_output (fbeg, ' ');
4683 /* If -M was specified, and this header file won't be added to the
4684 dependency list, then don't count this as an error, because we can
4685 still produce correct output. Otherwise, we can't produce correct
4686 output, because there may be dependencies we need inside the missing
4687 file, and we don't know what directory this missing file exists in. */
4688 else if (0 < print_deps && print_deps <= (system_include_depth != 0))
4689 warning ("No include path in which to find %s", fbeg);
4691 error_from_errno (fbeg);
4693 error ("No include path in which to find %s", fbeg);
4697 /* Actually process the file. */
4699 pcftry = (char *) alloca (strlen (fname) + 30);
4706 sprintf (pcftry, "%s%d", fname, pcfnum++);
4708 pcf = open (pcftry, O_RDONLY, 0666);
4713 if (fstat (pcf, &s) != 0)
4714 pfatal_with_name (pcftry);
4715 if (! INO_T_EQ (inc->st.st_ino, s.st_ino)
4716 || inc->st.st_dev != s.st_dev)
4718 pcfbuf = check_precompiled (pcf, &s, fname, &pcfbuflimit);
4719 /* Don't need it any more. */
4724 /* Don't need it at all. */
4729 } while (pcf != -1 && !pcfbuf);
4732 /* Actually process the file */
4734 pcfname = xmalloc (strlen (pcftry) + 1);
4735 strcpy (pcfname, pcftry);
4736 pcfinclude ((U_CHAR *) pcfbuf, (U_CHAR *) fname, op);
4739 finclude (f, inc, op, is_system_include (fname), searchptr);
4742 system_include_depth -= angle_brackets;
4747 /* Return nonzero if the given FILENAME is an absolute pathname which
4748 designates a file within one of the known "system" include file
4749 directories. We assume here that if the given FILENAME looks like
4750 it is the name of a file which resides either directly in a "system"
4751 include file directory, or within any subdirectory thereof, then the
4752 given file must be a "system" include file. This function tells us
4753 if we should suppress pedantic errors/warnings for the given FILENAME.
4755 The value is 2 if the file is a C-language system header file
4756 for which C++ should (on most systems) assume `extern "C"'. */
4759 is_system_include (filename)
4760 register char *filename;
4762 #ifndef FREEBSD_NATIVE
4763 struct file_name_list *searchptr;
4765 for (searchptr = first_system_include; searchptr;
4766 searchptr = searchptr->next)
4767 if (! strncmp (searchptr->fname, filename, strlen (searchptr->fname)))
4768 return searchptr->c_system_include_path + 1;
4773 /* Yield the non-directory suffix of a file name. */
4781 #if defined (__MSDOS__) || defined (_WIN32)
4782 if (ISALPHA (s[0]) && s[1] == ':') s += 2;
4785 if ((p = rindex (s, ':'))) s = p + 1; /* Skip device. */
4786 if ((p = rindex (s, ']'))) s = p + 1; /* Skip directory. */
4787 if ((p = rindex (s, '>'))) s = p + 1; /* Skip alternate (int'n'l) dir. */
4791 if ((p = rindex (s, '/'))) s = p + 1;
4792 #ifdef DIR_SEPARATOR
4793 if ((p = rindex (s, DIR_SEPARATOR))) s = p + 1;
4798 /* Yield nonzero if FILENAME is absolute (i.e. not relative). */
4801 absolute_filename (filename)
4804 #if defined (__MSDOS__) \
4805 || (defined (_WIN32) && !defined (__CYGWIN__) && !defined (_UWIN))
4806 if (ISALPHA (filename[0]) && filename[1] == ':') filename += 2;
4808 #if defined (__CYGWIN__)
4809 /* At present, any path that begins with a drive spec is absolute. */
4810 if (ISALPHA (filename[0]) && filename[1] == ':') return 1;
4813 if (index (filename, ':') != 0) return 1;
4815 if (filename[0] == '/') return 1;
4816 #ifdef DIR_SEPARATOR
4817 if (filename[0] == DIR_SEPARATOR) return 1;
4822 /* Returns whether or not a given character is a directory separator.
4823 Used by simplify_filename. */
4826 is_dir_separator(ch)
4829 return (ch == DIR_SEPARATOR)
4830 #if defined (DIR_SEPARATOR_2)
4831 || (ch == DIR_SEPARATOR_2)
4836 /* Remove unnecessary characters from FILENAME in place,
4837 to avoid unnecessary filename aliasing.
4838 Return the length of the resulting string.
4840 Do only the simplifications allowed by Posix.
4841 It is OK to miss simplifications on non-Posix hosts,
4842 since this merely leads to suboptimal results. */
4845 simplify_filename (filename)
4848 register char *from = filename;
4849 register char *to = filename;
4852 /* Remove redundant initial /s. */
4853 if (is_dir_separator (*from))
4855 *to++ = DIR_SEPARATOR;
4856 if (is_dir_separator (*++from))
4858 if (is_dir_separator (*++from))
4860 /* 3 or more initial /s are equivalent to 1 /. */
4861 while (is_dir_separator (*++from))
4866 /* On some hosts // differs from /; Posix allows this. */
4867 *to++ = DIR_SEPARATOR;
4877 if (from[0] == '.' && from[1] == '/')
4882 /* Copy this component and trailing DIR_SEPARATOR, if any. */
4883 while (!is_dir_separator (*to++ = *from++))
4887 /* Trim . component at end of nonempty name. */
4888 to -= filename <= to - 3 && to[-3] == DIR_SEPARATOR && to[-2] == '.';
4890 /* Trim unnecessary trailing /s. */
4891 while (to0 < --to && to[-1] == DIR_SEPARATOR)
4895 return to - filename;
4898 #if defined(DIR_SEPARATOR_2)
4899 /* Simplify to one directory separator. */
4900 to[-1] = DIR_SEPARATOR;
4904 /* Skip /s after a /. */
4905 while (is_dir_separator (*from))
4910 /* The file_name_map structure holds a mapping of file names for a
4911 particular directory. This mapping is read from the file named
4912 FILE_NAME_MAP_FILE in that directory. Such a file can be used to
4913 map filenames on a file system with severe filename restrictions,
4914 such as DOS. The format of the file name map file is just a series
4915 of lines with two tokens on each line. The first token is the name
4916 to map, and the second token is the actual name to use. */
4918 struct file_name_map
4920 struct file_name_map *map_next;
4925 #define FILE_NAME_MAP_FILE "header.gcc"
4927 /* Read a space delimited string of unlimited length from a stdio
4931 read_filename_string (ch, f)
4939 set = alloc = xmalloc (len + 1);
4943 while ((ch = getc (f)) != EOF && ! is_space[ch])
4945 if (set - alloc == len)
4948 alloc = xrealloc (alloc, len + 1);
4949 set = alloc + len / 2;
4959 /* Read the file name map file for DIRNAME.
4960 If DIRNAME is empty, read the map file for the working directory;
4961 otherwise DIRNAME must end in '/'. */
4963 static struct file_name_map *
4964 read_name_map (dirname)
4967 /* This structure holds a linked list of file name maps, one per
4969 struct file_name_map_list
4971 struct file_name_map_list *map_list_next;
4972 char *map_list_name;
4973 struct file_name_map *map_list_map;
4975 static struct file_name_map_list *map_list;
4976 register struct file_name_map_list *map_list_ptr;
4981 for (map_list_ptr = map_list; map_list_ptr;
4982 map_list_ptr = map_list_ptr->map_list_next)
4983 if (! strcmp (map_list_ptr->map_list_name, dirname))
4984 return map_list_ptr->map_list_map;
4986 map_list_ptr = ((struct file_name_map_list *)
4987 xmalloc (sizeof (struct file_name_map_list)));
4988 map_list_ptr->map_list_name = xstrdup (dirname);
4989 map_list_ptr->map_list_map = NULL;
4991 dirlen = strlen (dirname);
4992 name = (char *) alloca (dirlen + strlen (FILE_NAME_MAP_FILE) + 1);
4993 strcpy (name, dirname);
4994 strcat (name, FILE_NAME_MAP_FILE);
4995 f = fopen (name, "r");
4997 map_list_ptr->map_list_map = NULL;
5002 while ((ch = getc (f)) != EOF)
5005 struct file_name_map *ptr;
5010 from = read_filename_string (ch, f);
5011 while ((ch = getc (f)) != EOF && is_hor_space[ch])
5013 to = read_filename_string (ch, f);
5015 simplify_filename (from);
5016 tolen = simplify_filename (to);
5018 ptr = ((struct file_name_map *)
5019 xmalloc (sizeof (struct file_name_map)));
5020 ptr->map_from = from;
5022 /* Make the real filename absolute. */
5023 if (absolute_filename (to))
5027 ptr->map_to = xmalloc (dirlen + tolen + 1);
5028 strcpy (ptr->map_to, dirname);
5029 strcat (ptr->map_to, to);
5033 ptr->map_next = map_list_ptr->map_list_map;
5034 map_list_ptr->map_list_map = ptr;
5036 while ((ch = getc (f)) != '\n')
5043 map_list_ptr->map_list_next = map_list;
5044 map_list = map_list_ptr;
5046 return map_list_ptr->map_list_map;
5049 /* Try to open include file FILENAME. SEARCHPTR is the directory
5050 being tried from the include file search path.
5051 IMPORTING is "" if we are importing, null otherwise.
5052 Return -2 if found, either a matching name or a matching inode.
5053 Otherwise, open the file and return a file descriptor if successful
5054 or -1 if unsuccessful.
5055 Unless unsuccessful, put a descriptor of the included file into *PINC.
5056 This function maps filenames on file systems based on information read by
5060 open_include_file (filename, searchptr, importing, pinc)
5062 struct file_name_list *searchptr;
5064 struct include_file **pinc;
5066 char *fname = remap ? remap_include_file (filename, searchptr) : filename;
5069 /* Look up FNAME in include_hashtab. */
5070 struct include_file **phead = &include_hashtab[hashf ((U_CHAR *) fname,
5073 struct include_file *inc, *head = *phead;
5074 for (inc = head; inc; inc = inc->next)
5075 if (!strcmp (fname, inc->fname))
5079 || ! inc->control_macro
5080 || (inc->control_macro[0] && ! lookup (inc->control_macro, -1, -1))) {
5082 fd = open (fname, O_RDONLY, 0);
5087 /* if #include <dir/file> fails, try again with hacked spec. */
5088 if (!hack_vms_include_specification (fname, 0))
5090 fd = open (fname, O_RDONLY, 0);
5097 /* FNAME was not in include_hashtab; insert a new entry. */
5098 inc = (struct include_file *) xmalloc (sizeof (struct include_file));
5101 inc->control_macro = 0;
5102 inc->deps_output = 0;
5103 if (fstat (fd, &inc->st) != 0)
5104 pfatal_with_name (fname);
5107 /* Look for another file with the same inode and device. */
5108 if (lookup_ino_include (inc)
5109 && inc->control_macro
5110 && (!inc->control_macro[0] || lookup (inc->control_macro, -1, -1))) {
5116 /* For -M, add this file to the dependencies. */
5117 if (! inc->deps_output && (system_include_depth != 0) < print_deps) {
5118 inc->deps_output = 1;
5119 deps_output (fname, ' ');
5122 /* Handle -H option. */
5123 if (print_include_names)
5124 fprintf (stderr, "%*s%s\n", indepth, "", fname);
5128 inc->control_macro = importing;
5134 /* Return the remapped name of the include file FILENAME.
5135 SEARCHPTR is the directory being tried from the include file path. */
5138 remap_include_file (filename, searchptr)
5140 struct file_name_list *searchptr;
5142 register struct file_name_map *map;
5143 register char *from;
5145 #ifndef FREEBSD_NATIVE
5148 if (! searchptr->got_name_map)
5150 searchptr->name_map = read_name_map (searchptr->fname);
5151 searchptr->got_name_map = 1;
5154 /* Check the mapping for the directory we are using. */
5155 from = filename + strlen (searchptr->fname);
5156 for (map = searchptr->name_map; map; map = map->map_next)
5157 if (! strcmp (map->map_from, from))
5162 from = base_name (filename);
5164 if (from != filename || !searchptr)
5166 /* Try to find a mapping file for the particular directory we are
5167 looking in. Thus #include <sys/types.h> will look up sys/types.h
5168 in /usr/include/header.gcc and look up types.h in
5169 /usr/include/sys/header.gcc. */
5171 char *dir = (char *) alloca (from - filename + 1);
5172 bcopy (filename, dir, from - filename);
5173 dir[from - filename] = '\0';
5175 #ifndef FREEBSD_NATIVE
5176 for (map = read_name_map (dir); map; map = map->map_next)
5177 if (! strcmp (map->map_from, from))
5185 /* Insert INC into the include file table, hashed by device and inode number.
5186 If a file with different name but same dev+ino was already in the table,
5187 return 1 and set INC's control macro to the already-known macro. */
5190 lookup_ino_include (inc)
5191 struct include_file *inc;
5193 int hash = ((unsigned) (inc->st.st_dev + INO_T_HASH (inc->st.st_ino))
5194 % INCLUDE_HASHSIZE);
5195 struct include_file *i = include_ino_hashtab[hash];
5197 include_ino_hashtab[hash] = inc;
5199 for (; i; i = i->next_ino)
5200 if (INO_T_EQ (inc->st.st_ino, i->st.st_ino)
5201 && inc->st.st_dev == i->st.st_dev) {
5202 inc->control_macro = i->control_macro;
5209 /* Process file descriptor F, which corresponds to include file INC,
5211 SYSTEM_HEADER_P is 1 if this file resides in any one of the known
5212 "system" include directories (as decided by the `is_system_include'
5214 DIRPTR is the link in the dir path through which this file was found,
5215 or 0 if the file name was absolute. */
5218 finclude (f, inc, op, system_header_p, dirptr)
5220 struct include_file *inc;
5222 int system_header_p;
5223 struct file_name_list *dirptr;
5225 char *fname = inc->fname;
5227 FILE_BUF *fp; /* For input stack frame */
5228 int missing_newline = 0;
5230 CHECK_DEPTH (return;);
5232 fp = &instack[indepth + 1];
5233 bzero ((char *) fp, sizeof (FILE_BUF));
5234 fp->nominal_fname = fp->fname = fname;
5235 fp->nominal_fname_len = strlen (fname);
5239 fp->if_stack = if_stack;
5240 fp->system_header_p = system_header_p;
5243 if (S_ISREG (inc->st.st_mode)) {
5244 size_t s = (size_t) inc->st.st_size;
5245 if (s != inc->st.st_size || s + 2 < s)
5247 fp->buf = (U_CHAR *) xmalloc (s + 2);
5250 /* Read the file contents, knowing that s is an upper bound
5251 on the number of bytes we can read. */
5252 fp->length = safe_read (f, (char *) fp->buf, s);
5253 if (fp->length < 0) goto nope;
5255 else if (S_ISDIR (inc->st.st_mode)) {
5256 error ("directory `%s' specified in #include", fname);
5260 /* Cannot count its file size before reading.
5261 First read the entire file into heap and
5262 copy them into buffer on stack. */
5267 fp->buf = (U_CHAR *) xmalloc (bsize + 2);
5270 i = safe_read (f, (char *) fp->buf + st_size, bsize - st_size);
5272 goto nope; /* error! */
5274 if (st_size != bsize)
5275 break; /* End of file */
5277 fp->buf = (U_CHAR *) xrealloc (fp->buf, bsize + 2);
5280 fp->length = st_size;
5283 if ((fp->length > 0 && fp->buf[fp->length - 1] != '\n')
5284 /* Backslash-newline at end is not good enough. */
5285 || (fp->length > 1 && fp->buf[fp->length - 2] == '\\')) {
5286 fp->buf[fp->length++] = '\n';
5287 missing_newline = 1;
5289 fp->buf[fp->length] = '\0';
5291 /* Close descriptor now, so nesting does not use lots of descriptors. */
5294 /* Must do this before calling trigraph_pcp, so that the correct file name
5295 will be printed in warning messages. */
5298 input_file_stack_tick++;
5303 output_line_directive (fp, op, 0, enter_file);
5306 if (missing_newline)
5309 if (pedantic && missing_newline)
5310 pedwarn ("file does not end in newline");
5313 input_file_stack_tick++;
5314 output_line_directive (&instack[indepth], op, 0, leave_file);
5320 perror_with_name (fname);
5325 /* Record that inclusion of the include file INC
5326 should be controlled by the macro named MACRO_NAME.
5327 This means that trying to include the file again
5328 will do something if that macro is defined. */
5331 record_control_macro (inc, macro_name)
5332 struct include_file *inc;
5335 if (!inc->control_macro || inc->control_macro[0])
5336 inc->control_macro = macro_name;
5339 /* Load the specified precompiled header into core, and verify its
5340 preconditions. PCF indicates the file descriptor to read, which must
5341 be a regular file. *ST is its file status.
5342 FNAME indicates the file name of the original header.
5343 *LIMIT will be set to an address one past the end of the file.
5344 If the preconditions of the file are not satisfied, the buffer is
5345 freed and we return 0. If the preconditions are satisfied, return
5346 the address of the buffer following the preconditions. The buffer, in
5347 this case, should never be freed because various pieces of it will
5348 be referred to until all precompiled strings are output at the end of
5352 check_precompiled (pcf, st, fname, limit)
5355 char *fname ATTRIBUTE_UNUSED;
5365 if (S_ISREG (st->st_mode))
5367 size_t s = (size_t) st->st_size;
5368 if (s != st->st_size || s + 2 < s)
5370 buf = xmalloc (s + 2);
5371 length = safe_read (pcf, buf, s);
5378 if (length > 0 && buf[length-1] != '\n')
5379 buf[length++] = '\n';
5382 *limit = buf + length;
5384 /* File is in core. Check the preconditions. */
5385 if (!check_preconditions (buf))
5387 for (cp = buf; *cp; cp++)
5390 fprintf (stderr, "Using preinclude %s\n", fname);
5396 fprintf (stderr, "Cannot use preinclude %s\n", fname);
5402 /* PREC (null terminated) points to the preconditions of a
5403 precompiled header. These are a series of #define and #undef
5404 lines which must match the current contents of the hash
5408 check_preconditions (prec)
5415 lineend = index (prec, '\n');
5417 if (*prec++ != '#') {
5418 error ("Bad format encountered while reading precompiled file");
5421 if (!strncmp (prec, "define", 6)) {
5425 mdef = create_definition ((U_CHAR *) prec, (U_CHAR *) lineend, NULL_PTR);
5430 if ((hp = lookup (mdef.symnam, mdef.symlen, -1)) == NULL
5431 || (hp->type != T_MACRO && hp->type != T_CONST)
5432 || (hp->type == T_MACRO
5433 && !compare_defs (mdef.defn, hp->value.defn)
5434 && (mdef.defn->length != 2
5435 || mdef.defn->expansion[0] != '\n'
5436 || mdef.defn->expansion[1] != ' ')))
5438 } else if (!strncmp (prec, "undef", 5)) {
5443 while (is_hor_space[(U_CHAR) *prec])
5446 while (is_idchar[(U_CHAR) *prec])
5450 if (lookup ((U_CHAR *) name, len, -1))
5453 error ("Bad format encountered while reading precompiled file");
5458 /* They all passed successfully */
5462 /* Process the main body of a precompiled file. BUF points to the
5463 string section of the file, following the preconditions. LIMIT is one
5464 character past the end. NAME is the name of the file being read
5465 in. OP is the main output buffer. */
5468 pcfinclude (buf, name, op)
5476 /* First in the file comes 4 bytes indicating the number of strings, */
5477 /* in network byte order. (MSB first). */
5479 nstrings = (nstrings << 8) | *cp++;
5480 nstrings = (nstrings << 8) | *cp++;
5481 nstrings = (nstrings << 8) | *cp++;
5483 /* Looping over each string... */
5484 while (nstrings--) {
5485 U_CHAR *string_start;
5486 U_CHAR *endofthiskey;
5490 /* Each string starts with a STRINGDEF structure (str), followed */
5491 /* by the text of the string (string_start) */
5493 /* First skip to a longword boundary */
5494 /* ??? Why a 4-byte boundary? On all machines? */
5495 /* NOTE: This works correctly even if size_t
5496 is narrower than a pointer.
5497 Do not try risky measures here to get another type to use!
5498 Do not include stddef.h--it will fail! */
5499 if ((size_t) cp & 3)
5500 cp += 4 - ((size_t) cp & 3);
5502 /* Now get the string. */
5503 str = (STRINGDEF *) (GENERIC_PTR) cp;
5504 string_start = cp += sizeof (STRINGDEF);
5506 for (; *cp; cp++) /* skip the string */
5509 /* We need to macro expand the string here to ensure that the
5510 proper definition environment is in place. If it were only
5511 expanded when we find out it is needed, macros necessary for
5512 its proper expansion might have had their definitions changed. */
5513 tmpbuf = expand_to_temp_buffer (string_start, cp++, 0, 0);
5514 /* Lineno is already set in the precompiled file */
5515 str->contents = tmpbuf.buf;
5516 str->len = tmpbuf.length;
5518 str->filename = name;
5519 str->output_mark = outbuf.bufp - outbuf.buf;
5522 *stringlist_tailp = str;
5523 stringlist_tailp = &str->chain;
5525 /* Next comes a fourbyte number indicating the number of keys
5528 nkeys = (nkeys << 8) | *cp++;
5529 nkeys = (nkeys << 8) | *cp++;
5530 nkeys = (nkeys << 8) | *cp++;
5532 /* If this number is -1, then the string is mandatory. */
5536 /* Otherwise, for each key, */
5537 for (; nkeys--; free (tmpbuf.buf), cp = endofthiskey + 1) {
5538 KEYDEF *kp = (KEYDEF *) (GENERIC_PTR) cp;
5541 /* It starts with a KEYDEF structure */
5542 cp += sizeof (KEYDEF);
5544 /* Find the end of the key. At the end of this for loop we
5545 advance CP to the start of the next key using this variable. */
5546 endofthiskey = cp + strlen ((char *) cp);
5549 /* Expand the key, and enter it into the hash table. */
5550 tmpbuf = expand_to_temp_buffer (cp, endofthiskey, 0, 0);
5551 tmpbuf.bufp = tmpbuf.buf;
5553 while (is_hor_space[*tmpbuf.bufp])
5555 if (!is_idstart[*tmpbuf.bufp]
5556 || tmpbuf.bufp == tmpbuf.buf + tmpbuf.length) {
5561 hp = lookup (tmpbuf.bufp, -1, -1);
5564 install (tmpbuf.bufp, -1, T_PCSTRING, (char *) kp, -1);
5566 else if (hp->type == T_PCSTRING) {
5567 kp->chain = hp->value.keydef;
5568 hp->value.keydef = kp;
5574 /* This output_line_directive serves to switch us back to the current
5575 input file in case some of these strings get output (which will
5576 result in line directives for the header file being output). */
5577 output_line_directive (&instack[indepth], op, 0, enter_file);
5580 /* Called from rescan when it hits a key for strings. Mark them all
5581 used and clean up. */
5589 for (kp = hp->value.keydef; kp; kp = kp->chain)
5590 kp->str->writeflag = 1;
5594 /* Write the output, interspersing precompiled strings in their
5595 appropriate places. */
5600 STRINGDEF *next_string;
5601 U_CHAR *cur_buf_loc;
5602 int line_directive_len = 80;
5603 char *line_directive = xmalloc (line_directive_len);
5606 /* In each run through the loop, either cur_buf_loc ==
5607 next_string_loc, in which case we print a series of strings, or
5608 it is less than next_string_loc, in which case we write some of
5610 cur_buf_loc = outbuf.buf;
5611 next_string = stringlist;
5613 while (cur_buf_loc < outbuf.bufp || next_string) {
5615 && cur_buf_loc - outbuf.buf == next_string->output_mark) {
5616 if (next_string->writeflag) {
5617 len = 4 * strlen ((char *) next_string->filename) + 32;
5618 while (len > line_directive_len)
5619 line_directive = xrealloc (line_directive,
5620 line_directive_len *= 2);
5621 sprintf (line_directive, "\n# %d ", next_string->lineno);
5622 strcpy (quote_string (line_directive + strlen (line_directive),
5623 (char *) next_string->filename,
5624 strlen ((char *) next_string->filename)),
5626 safe_write (fileno (stdout), line_directive, strlen (line_directive));
5627 safe_write (fileno (stdout),
5628 (char *) next_string->contents, next_string->len);
5630 next_string = next_string->chain;
5634 ? (next_string->output_mark
5635 - (cur_buf_loc - outbuf.buf))
5636 : outbuf.bufp - cur_buf_loc);
5638 safe_write (fileno (stdout), (char *) cur_buf_loc, len);
5642 free (line_directive);
5645 /* Pass a directive through to the output file.
5646 BUF points to the contents of the directive, as a contiguous string.
5647 LIMIT points to the first character past the end of the directive.
5648 KEYWORD is the keyword-table entry for the directive. */
5651 pass_thru_directive (buf, limit, op, keyword)
5652 U_CHAR *buf, *limit;
5654 struct directive *keyword;
5656 register int keyword_length = keyword->length;
5658 check_expand (op, 1 + keyword_length + (limit - buf));
5660 bcopy (keyword->name, (char *) op->bufp, keyword_length);
5661 op->bufp += keyword_length;
5662 if (limit != buf && buf[0] != ' ')
5664 bcopy ((char *) buf, (char *) op->bufp, limit - buf);
5665 op->bufp += (limit - buf);
5668 /* Count the line we have just made in the output,
5669 to get in sync properly. */
5674 /* The arglist structure is built by do_define to tell
5675 collect_definition where the argument names begin. That
5676 is, for a define like "#define f(x,y,z) foo+x-bar*y", the arglist
5677 would contain pointers to the strings x, y, and z.
5678 Collect_definition would then build a DEFINITION node,
5679 with reflist nodes pointing to the places x, y, and z had
5680 appeared. So the arglist is just convenience data passed
5681 between these two routines. It is not kept around after
5682 the current #define has been processed and entered into the
5686 struct arglist *next;
5693 /* Create a DEFINITION node from a #define directive. Arguments are
5694 as for do_define. */
5697 create_definition (buf, limit, op)
5698 U_CHAR *buf, *limit;
5701 U_CHAR *bp; /* temp ptr into input buffer */
5702 U_CHAR *symname; /* remember where symbol name starts */
5703 int sym_length; /* and how long it is */
5704 int line = instack[indepth].lineno;
5705 char *file = instack[indepth].nominal_fname;
5706 size_t file_len = instack[indepth].nominal_fname_len;
5710 int arglengths = 0; /* Accumulate lengths of arg names
5711 plus number of args. */
5716 while (is_hor_space[*bp])
5719 symname = bp; /* remember where it starts */
5720 sym_length = check_macro_name (bp, 0);
5723 /* Lossage will occur if identifiers or control keywords are broken
5724 across lines using backslash. This is not the right place to take
5728 struct arglist *arg_ptrs = NULL;
5731 bp++; /* skip '(' */
5732 SKIP_WHITE_SPACE (bp);
5734 /* Loop over macro argument names. */
5735 while (*bp != ')') {
5736 struct arglist *temp;
5738 temp = (struct arglist *) alloca (sizeof (struct arglist));
5740 temp->next = arg_ptrs;
5741 temp->argno = argno++;
5742 temp->rest_args = 0;
5746 pedwarn ("another parameter follows `%s'",
5749 if (!is_idstart[*bp])
5751 if (c9x && limit - bp > (long) REST_EXTENSION_LENGTH
5752 && bcmp (rest_extension, bp, REST_EXTENSION_LENGTH) == 0)
5754 /* This is the ISO C 9x way to write macros with variable
5755 number of arguments. */
5757 temp->rest_args = 1;
5760 pedwarn ("invalid character in macro parameter name");
5763 /* Find the end of the arg name. */
5764 while (is_idchar[*bp]) {
5766 /* do we have a "special" rest-args extension here? */
5767 if (limit - bp > (long) REST_EXTENSION_LENGTH
5768 && bcmp (rest_extension, bp, REST_EXTENSION_LENGTH) == 0) {
5769 if (pedantic && !instack[indepth].system_header_p)
5770 pedwarn ("ANSI C does not allow macro with variable arguments");
5772 temp->rest_args = 1;
5776 if (bp == temp->name && rest_args == 1)
5778 /* This is the ISO C 9x style. */
5779 temp->name = (U_CHAR *) va_args_name;
5780 temp->length = VA_ARGS_NAME_LENGTH;
5783 temp->length = bp - temp->name;
5785 bp += REST_EXTENSION_LENGTH;
5786 arglengths += temp->length + 2;
5787 SKIP_WHITE_SPACE (bp);
5788 if (temp->length == 0 || (*bp != ',' && *bp != ')')) {
5789 error ("badly punctuated parameter list in `#define'");
5794 SKIP_WHITE_SPACE (bp);
5795 /* A comma at this point can only be followed by an identifier. */
5796 if (!is_idstart[*bp]
5797 && !(c9x && limit - bp > (long) REST_EXTENSION_LENGTH
5798 && bcmp (rest_extension, bp, REST_EXTENSION_LENGTH) == 0)) {
5799 error ("badly punctuated parameter list in `#define'");
5804 error ("unterminated parameter list in `#define'");
5808 struct arglist *otemp;
5810 for (otemp = temp->next; otemp != NULL; otemp = otemp->next)
5811 if (temp->length == otemp->length
5812 && bcmp (temp->name, otemp->name, temp->length) == 0)
5814 error ("duplicate argument name `%.*s' in `#define'",
5815 temp->length, temp->name);
5818 if (rest_args == 0 && temp->length == VA_ARGS_NAME_LENGTH
5819 && bcmp (temp->name, va_args_name, VA_ARGS_NAME_LENGTH) == 0)
5822 reserved name `%s' used as argument name in `#define'", va_args_name);
5828 ++bp; /* skip paren */
5829 SKIP_WHITE_SPACE (bp);
5830 /* now everything from bp before limit is the definition. */
5831 defn = collect_expansion (bp, limit, argno, arg_ptrs);
5832 defn->rest_args = rest_args;
5834 /* Now set defn->args.argnames to the result of concatenating
5835 the argument names in reverse order
5836 with comma-space between them. */
5837 defn->args.argnames = (U_CHAR *) xmalloc (arglengths + 1);
5839 struct arglist *temp;
5841 for (temp = arg_ptrs; temp; temp = temp->next) {
5842 bcopy (temp->name, &defn->args.argnames[i], temp->length);
5844 if (temp->next != 0) {
5845 defn->args.argnames[i++] = ',';
5846 defn->args.argnames[i++] = ' ';
5849 defn->args.argnames[i] = 0;
5852 /* Simple expansion or empty definition. */
5856 if (is_hor_space[*bp]) {
5858 SKIP_WHITE_SPACE (bp);
5859 } else if (sym_length) {
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 '\\': case ']': case '^': case '{':
5865 case '|': case '}': case '~':
5866 warning ("missing white space after `#define %.*s'",
5867 sym_length, symname);
5871 pedwarn ("missing white space after `#define %.*s'",
5872 sym_length, symname);
5877 /* Now everything from bp before limit is the definition. */
5878 defn = collect_expansion (bp, limit, -1, NULL_PTR);
5879 defn->args.argnames = (U_CHAR *) "";
5884 defn->file_len = file_len;
5886 /* OP is null if this is a predefinition */
5887 defn->predefined = !op;
5889 mdef.symnam = symname;
5890 mdef.symlen = sym_length;
5899 /* Process a #define directive.
5900 BUF points to the contents of the #define directive, as a contiguous string.
5901 LIMIT points to the first character past the end of the definition.
5902 KEYWORD is the keyword-table entry for #define. */
5905 do_define (buf, limit, op, keyword)
5906 U_CHAR *buf, *limit;
5908 struct directive *keyword;
5913 /* If this is a precompiler run (with -pcp) pass thru #define directives. */
5914 if (pcp_outfile && op)
5915 pass_thru_directive (buf, limit, op, keyword);
5917 mdef = create_definition (buf, limit, op);
5921 hashcode = hashf (mdef.symnam, mdef.symlen, HASHSIZE);
5925 if ((hp = lookup (mdef.symnam, mdef.symlen, hashcode)) != NULL) {
5927 /* Redefining a precompiled key is ok. */
5928 if (hp->type == T_PCSTRING)
5930 /* Redefining a macro is ok if the definitions are the same. */
5931 else if (hp->type == T_MACRO)
5932 ok = ! compare_defs (mdef.defn, hp->value.defn);
5933 /* Redefining a constant is ok with -D. */
5934 else if (hp->type == T_CONST)
5935 ok = ! done_initializing;
5936 /* Print the warning if it's not ok. */
5938 /* If we are passing through #define and #undef directives, do
5939 that for this re-definition now. */
5940 if (debug_output && op)
5941 pass_thru_directive (buf, limit, op, keyword);
5943 pedwarn ("`%.*s' redefined", mdef.symlen, mdef.symnam);
5944 if (hp->type == T_MACRO)
5945 pedwarn_with_file_and_line (hp->value.defn->file,
5946 hp->value.defn->file_len,
5947 hp->value.defn->line,
5948 "this is the location of the previous definition");
5950 /* Replace the old definition. */
5952 hp->value.defn = mdef.defn;
5954 /* If we are passing through #define and #undef directives, do
5955 that for this new definition now. */
5956 if (debug_output && op)
5957 pass_thru_directive (buf, limit, op, keyword);
5958 install (mdef.symnam, mdef.symlen, T_MACRO,
5959 (char *) mdef.defn, hashcode);
5970 /* Check a purported macro name SYMNAME, and yield its length.
5971 ASSERTION is nonzero if this is really for an assertion name. */
5974 check_macro_name (symname, assertion)
5981 for (p = symname; is_idchar[*p]; p++)
5983 sym_length = p - symname;
5985 || (sym_length == 1 && *symname == 'L' && (*p == '\'' || *p == '"')))
5986 error (assertion ? "invalid assertion name" : "invalid macro name");
5987 else if (!is_idstart[*symname]
5988 || (sym_length == 7 && ! bcmp (symname, "defined", 7)))
5990 ? "invalid assertion name `%.*s'"
5991 : "invalid macro name `%.*s'"),
5992 sym_length, symname);
5996 /* Return zero if two DEFINITIONs are isomorphic. */
5999 compare_defs (d1, d2)
6000 DEFINITION *d1, *d2;
6002 register struct reflist *a1, *a2;
6003 register U_CHAR *p1 = d1->expansion;
6004 register U_CHAR *p2 = d2->expansion;
6007 if (d1->nargs != d2->nargs)
6010 && strcmp ((char *)d1->args.argnames, (char *)d2->args.argnames))
6012 for (a1 = d1->pattern, a2 = d2->pattern; a1 && a2;
6013 a1 = a1->next, a2 = a2->next) {
6014 if (!((a1->nchars == a2->nchars && ! bcmp (p1, p2, a1->nchars))
6015 || ! comp_def_part (first, p1, a1->nchars, p2, a2->nchars, 0))
6016 || a1->argno != a2->argno
6017 || a1->stringify != a2->stringify
6018 || a1->raw_before != a2->raw_before
6019 || a1->raw_after != a2->raw_after)
6027 if (comp_def_part (first, p1, d1->length - (p1 - d1->expansion),
6028 p2, d2->length - (p2 - d2->expansion), 1))
6033 /* Return 1 if two parts of two macro definitions are effectively different.
6034 One of the parts starts at BEG1 and has LEN1 chars;
6035 the other has LEN2 chars at BEG2.
6036 Any sequence of whitespace matches any other sequence of whitespace.
6037 FIRST means these parts are the first of a macro definition;
6038 so ignore leading whitespace entirely.
6039 LAST means these parts are the last of a macro definition;
6040 so ignore trailing whitespace entirely. */
6043 comp_def_part (first, beg1, len1, beg2, len2, last)
6045 U_CHAR *beg1, *beg2;
6049 register U_CHAR *end1 = beg1 + len1;
6050 register U_CHAR *end2 = beg2 + len2;
6052 while (beg1 != end1 && is_space[*beg1]) beg1++;
6053 while (beg2 != end2 && is_space[*beg2]) beg2++;
6056 while (beg1 != end1 && is_space[end1[-1]]) end1--;
6057 while (beg2 != end2 && is_space[end2[-1]]) end2--;
6059 while (beg1 != end1 && beg2 != end2) {
6060 if (is_space[*beg1] && is_space[*beg2]) {
6061 while (beg1 != end1 && is_space[*beg1]) beg1++;
6062 while (beg2 != end2 && is_space[*beg2]) beg2++;
6063 } else if (*beg1 == *beg2) {
6067 return (beg1 != end1) || (beg2 != end2);
6070 /* Read a replacement list for a macro with parameters.
6071 Build the DEFINITION structure.
6072 Reads characters of text starting at BUF until END.
6073 ARGLIST specifies the formal parameters to look for
6074 in the text of the definition; NARGS is the number of args
6075 in that list, or -1 for a macro name that wants no argument list.
6076 MACRONAME is the macro name itself (so we can avoid recursive expansion)
6077 and NAMELEN is its length in characters.
6079 Note that comments, backslash-newlines, and leading white space
6080 have already been deleted from the argument. */
6082 /* If there is no trailing whitespace, a Newline Space is added at the end
6083 to prevent concatenation that would be contrary to the standard. */
6086 collect_expansion (buf, end, nargs, arglist)
6089 struct arglist *arglist;
6092 register U_CHAR *p, *limit, *lastp, *exp_p;
6093 struct reflist *endpat = NULL;
6094 /* Pointer to first nonspace after last ## seen. */
6096 /* Pointer to first nonspace after last single-# seen. */
6097 U_CHAR *stringify = 0;
6098 /* How those tokens were spelled. */
6099 enum sharp_token_type concat_sharp_token_type = NO_SHARP_TOKEN;
6100 enum sharp_token_type stringify_sharp_token_type = NO_SHARP_TOKEN;
6102 int expected_delimiter = '\0';
6104 /* Scan thru the replacement list, ignoring comments and quoted
6105 strings, picking up on the macro calls. It does a linear search
6106 thru the arg list on every potential symbol. Profiling might say
6107 that something smarter should happen. */
6112 /* Find the beginning of the trailing whitespace. */
6115 while (p < limit && is_space[limit[-1]]) limit--;
6117 /* Allocate space for the text in the macro definition.
6118 Each input char may or may not need 1 byte,
6119 so this is an upper bound.
6120 The extra 3 are for invented trailing newline-marker and final null. */
6121 maxsize = (sizeof (DEFINITION)
6123 defn = (DEFINITION *) xcalloc (1, maxsize);
6125 defn->nargs = nargs;
6126 exp_p = defn->expansion = (U_CHAR *) defn + sizeof (DEFINITION);
6131 : p[0] == '%' && p[1] == ':' && p[2] == '%' && p[3] == ':') {
6132 error ("`##' at start of macro definition");
6133 p += p[0] == '#' ? 2 : 4;
6136 /* Process the main body of the definition. */
6138 int skipped_arg = 0;
6139 register U_CHAR c = *p++;
6147 if (expected_delimiter != '\0') {
6148 if (c == expected_delimiter)
6149 expected_delimiter = '\0';
6151 expected_delimiter = c;
6155 if (p < limit && expected_delimiter) {
6156 /* In a string, backslash goes through
6157 and makes next char ordinary. */
6163 if (!expected_delimiter && *p == ':') {
6164 /* %: is not a digraph if preceded by an odd number of '<'s. */
6166 while (buf < p0 && p0[-1] == '<')
6169 /* Treat %:%: as ## and %: as #. */
6170 if (p[1] == '%' && p[2] == ':') {
6172 goto sharp_sharp_token;
6183 /* # is ordinary inside a string. */
6184 if (expected_delimiter)
6188 /* ##: concatenate preceding and following tokens. */
6189 /* Take out the first #, discard preceding whitespace. */
6191 while (exp_p > lastp && is_hor_space[exp_p[-1]])
6193 /* Skip the second #. */
6195 concat_sharp_token_type = c;
6196 if (is_hor_space[*p]) {
6197 concat_sharp_token_type = c + 1;
6199 SKIP_WHITE_SPACE (p);
6203 error ("`##' at end of macro definition");
6204 } else if (nargs >= 0) {
6205 /* Single #: stringify following argument ref.
6206 Don't leave the # in the expansion. */
6209 stringify_sharp_token_type = c;
6210 if (is_hor_space[*p]) {
6211 stringify_sharp_token_type = c + 1;
6213 SKIP_WHITE_SPACE (p);
6215 if (! is_idstart[*p] || nargs == 0
6216 || (*p == 'L' && (p[1] == '\'' || p[1] == '"')))
6217 error ("`#' operator is not followed by a macro argument name");
6224 /* In -traditional mode, recognize arguments inside strings and
6225 character constants, and ignore special properties of #.
6226 Arguments inside strings are considered "stringified", but no
6227 extra quote marks are supplied. */
6231 if (expected_delimiter != '\0') {
6232 if (c == expected_delimiter)
6233 expected_delimiter = '\0';
6235 expected_delimiter = c;
6239 /* Backslash quotes delimiters and itself, but not macro args. */
6240 if (expected_delimiter != 0 && p < limit
6241 && (*p == expected_delimiter || *p == '\\')) {
6248 if (expected_delimiter != '\0') /* No comments inside strings. */
6251 /* If we find a comment that wasn't removed by handle_directive,
6252 this must be -traditional. So replace the comment with
6255 while (++p < limit) {
6256 if (p[0] == '*' && p[1] == '/') {
6262 /* Mark this as a concatenation-point, as if it had been ##. */
6270 #ifdef MULTIBYTE_CHARS
6271 /* Handle multibyte characters inside string and character literals. */
6272 if (expected_delimiter != '\0')
6276 length = local_mblen (p, limit - p);
6280 bcopy (p, exp_p, length);
6289 /* Handle the start of a symbol. */
6290 if (is_idchar[c] && nargs > 0) {
6291 U_CHAR *id_beg = p - 1;
6295 while (p != limit && is_idchar[*p]) p++;
6296 id_len = p - id_beg;
6299 && ! (id_len == 1 && c == 'L' && (*p == '\'' || *p == '"'))) {
6300 register struct arglist *arg;
6302 for (arg = arglist; arg != NULL; arg = arg->next) {
6303 struct reflist *tpat;
6305 if (arg->name[0] == c
6306 && arg->length == id_len
6307 && bcmp (arg->name, id_beg, id_len) == 0) {
6308 enum sharp_token_type tpat_stringify;
6309 if (expected_delimiter) {
6310 if (warn_stringify) {
6312 warning ("macro argument `%.*s' is stringified.",
6315 warning ("macro arg `%.*s' would be stringified with -traditional.",
6319 /* If ANSI, don't actually substitute inside a string. */
6322 tpat_stringify = SHARP_TOKEN;
6325 = (stringify == id_beg
6326 ? stringify_sharp_token_type : NO_SHARP_TOKEN);
6328 /* make a pat node for this arg and append it to the end of
6330 tpat = (struct reflist *) xmalloc (sizeof (struct reflist));
6333 = concat == id_beg ? concat_sharp_token_type : NO_SHARP_TOKEN;
6334 tpat->raw_after = NO_SHARP_TOKEN;
6335 tpat->rest_args = arg->rest_args;
6336 tpat->stringify = tpat_stringify;
6339 defn->pattern = tpat;
6341 endpat->next = tpat;
6344 tpat->argno = arg->argno;
6345 tpat->nchars = exp_p - lastp;
6347 register U_CHAR *p1 = p;
6348 SKIP_WHITE_SPACE (p1);
6351 : p1[0]=='%' && p1[1]==':' && p1[2]=='%' && p1[3]==':')
6352 tpat->raw_after = p1[0] + (p != p1);
6354 lastp = exp_p; /* place to start copying from next time */
6361 /* If this was not a macro arg, copy it into the expansion. */
6362 if (! skipped_arg) {
6363 register U_CHAR *lim1 = p;
6367 if (stringify == id_beg)
6368 error ("`#' operator should be followed by a macro argument name");
6373 if (!traditional && expected_delimiter == 0) {
6374 /* If ANSI, put in a newline-space marker to prevent token pasting.
6375 But not if "inside a string" (which in ANSI mode happens only for
6383 defn->length = exp_p - defn->expansion;
6385 /* Crash now if we overrun the allocated size. */
6386 if (defn->length + 1 > maxsize)
6390 /* This isn't worth the time it takes. */
6391 /* give back excess storage */
6392 defn->expansion = (U_CHAR *) xrealloc (defn->expansion, defn->length + 1);
6399 do_assert (buf, limit, op, keyword)
6400 U_CHAR *buf, *limit;
6401 FILE_BUF *op ATTRIBUTE_UNUSED;
6402 struct directive *keyword ATTRIBUTE_UNUSED;
6404 U_CHAR *bp; /* temp ptr into input buffer */
6405 U_CHAR *symname; /* remember where symbol name starts */
6406 int sym_length; /* and how long it is */
6407 struct arglist *tokens = NULL;
6409 if (pedantic && done_initializing && !instack[indepth].system_header_p)
6410 pedwarn ("ANSI C does not allow `#assert'");
6414 while (is_hor_space[*bp])
6417 symname = bp; /* remember where it starts */
6418 sym_length = check_macro_name (bp, 1);
6420 /* #define doesn't do this, but we should. */
6421 SKIP_WHITE_SPACE (bp);
6423 /* Lossage will occur if identifiers or control tokens are broken
6424 across lines using backslash. This is not the right place to take
6428 error ("missing token-sequence in `#assert'");
6435 bp++; /* skip '(' */
6436 SKIP_WHITE_SPACE (bp);
6438 tokens = read_token_list (&bp, limit, &error_flag);
6442 error ("empty token-sequence in `#assert'");
6446 ++bp; /* skip paren */
6447 SKIP_WHITE_SPACE (bp);
6450 /* If this name isn't already an assertion name, make it one.
6451 Error if it was already in use in some other way. */
6454 ASSERTION_HASHNODE *hp;
6455 int hashcode = hashf (symname, sym_length, ASSERTION_HASHSIZE);
6456 struct tokenlist_list *value
6457 = (struct tokenlist_list *) xmalloc (sizeof (struct tokenlist_list));
6459 hp = assertion_lookup (symname, sym_length, hashcode);
6461 if (sym_length == 7 && ! bcmp (symname, "defined", 7))
6462 error ("`defined' redefined as assertion");
6463 hp = assertion_install (symname, sym_length, hashcode);
6466 /* Add the spec'd token-sequence to the list of such. */
6467 value->tokens = tokens;
6468 value->next = hp->value;
6476 do_unassert (buf, limit, op, keyword)
6477 U_CHAR *buf, *limit;
6478 FILE_BUF *op ATTRIBUTE_UNUSED;
6479 struct directive *keyword ATTRIBUTE_UNUSED;
6481 U_CHAR *bp; /* temp ptr into input buffer */
6482 U_CHAR *symname; /* remember where symbol name starts */
6483 int sym_length; /* and how long it is */
6485 struct arglist *tokens = NULL;
6486 int tokens_specified = 0;
6488 if (pedantic && done_initializing && !instack[indepth].system_header_p)
6489 pedwarn ("ANSI C does not allow `#unassert'");
6493 while (is_hor_space[*bp])
6496 symname = bp; /* remember where it starts */
6497 sym_length = check_macro_name (bp, 1);
6499 /* #define doesn't do this, but we should. */
6500 SKIP_WHITE_SPACE (bp);
6502 /* Lossage will occur if identifiers or control tokens are broken
6503 across lines using backslash. This is not the right place to take
6509 bp++; /* skip '(' */
6510 SKIP_WHITE_SPACE (bp);
6512 tokens = read_token_list (&bp, limit, &error_flag);
6516 error ("empty token list in `#unassert'");
6520 tokens_specified = 1;
6522 ++bp; /* skip paren */
6523 SKIP_WHITE_SPACE (bp);
6527 ASSERTION_HASHNODE *hp;
6528 int hashcode = hashf (symname, sym_length, ASSERTION_HASHSIZE);
6529 struct tokenlist_list *tail, *prev;
6531 hp = assertion_lookup (symname, sym_length, hashcode);
6535 /* If no token list was specified, then eliminate this assertion
6537 if (! tokens_specified) {
6538 struct tokenlist_list *next;
6539 for (tail = hp->value; tail; tail = next) {
6541 free_token_list (tail->tokens);
6544 delete_assertion (hp);
6546 /* If a list of tokens was given, then delete any matching list. */
6551 struct tokenlist_list *next = tail->next;
6552 if (compare_token_lists (tail->tokens, tokens)) {
6556 hp->value = tail->next;
6557 free_token_list (tail->tokens);
6570 /* Test whether there is an assertion named NAME
6571 and optionally whether it has an asserted token list TOKENS.
6572 NAME is not null terminated; its length is SYM_LENGTH.
6573 If TOKENS_SPECIFIED is 0, then don't check for any token list. */
6576 check_assertion (name, sym_length, tokens_specified, tokens)
6579 int tokens_specified;
6580 struct arglist *tokens;
6582 ASSERTION_HASHNODE *hp;
6583 int hashcode = hashf (name, sym_length, ASSERTION_HASHSIZE);
6585 if (pedantic && !instack[indepth].system_header_p)
6586 pedwarn ("ANSI C does not allow testing assertions");
6588 hp = assertion_lookup (name, sym_length, hashcode);
6590 /* It is not an assertion; just return false. */
6593 /* If no token list was specified, then value is 1. */
6594 if (! tokens_specified)
6598 struct tokenlist_list *tail;
6602 /* If a list of tokens was given,
6603 then succeed if the assertion records a matching list. */
6606 if (compare_token_lists (tail->tokens, tokens))
6611 /* Fail if the assertion has no matching list. */
6616 /* Compare two lists of tokens for equality including order of tokens. */
6619 compare_token_lists (l1, l2)
6620 struct arglist *l1, *l2;
6623 if (l1->length != l2->length)
6625 if (bcmp (l1->name, l2->name, l1->length))
6631 /* Succeed if both lists end at the same time. */
6635 /* Read a space-separated list of tokens ending in a close parenthesis.
6636 Return a list of strings, in the order they were written.
6637 (In case of error, return 0 and store -1 in *ERROR_FLAG.)
6638 Parse the text starting at *BPP, and update *BPP.
6639 Don't parse beyond LIMIT. */
6641 static struct arglist *
6642 read_token_list (bpp, limit, error_flag)
6647 struct arglist *token_ptrs = 0;
6653 /* Loop over the assertion value tokens. */
6655 struct arglist *temp;
6659 /* Find the end of the token. */
6663 } else if (*bp == ')') {
6668 } else if (*bp == '"' || *bp == '\'')
6669 bp = skip_quoted_string (bp, limit, 0, NULL_PTR, NULL_PTR, &eofp);
6671 while (! is_hor_space[*bp] && *bp != '(' && *bp != ')'
6672 && *bp != '"' && *bp != '\'' && bp != limit)
6675 temp = (struct arglist *) xmalloc (sizeof (struct arglist));
6676 temp->name = (U_CHAR *) xmalloc (bp - beg + 1);
6677 bcopy ((char *) beg, (char *) temp->name, bp - beg);
6678 temp->name[bp - beg] = 0;
6679 temp->next = token_ptrs;
6681 temp->length = bp - beg;
6683 SKIP_WHITE_SPACE (bp);
6686 error ("unterminated token sequence in `#assert' or `#unassert'");
6693 /* We accumulated the names in reverse order.
6694 Now reverse them to get the proper order. */
6696 register struct arglist *prev = 0, *this, *next;
6697 for (this = token_ptrs; this; this = next) {
6707 free_token_list (tokens)
6708 struct arglist *tokens;
6711 struct arglist *next = tokens->next;
6712 free (tokens->name);
6718 /* Install a name in the assertion hash table.
6720 If LEN is >= 0, it is the length of the name.
6721 Otherwise, compute the length by scanning the entire name.
6723 If HASH is >= 0, it is the precomputed hash code.
6724 Otherwise, compute the hash code. */
6726 static ASSERTION_HASHNODE *
6727 assertion_install (name, len, hash)
6732 register ASSERTION_HASHNODE *hp;
6733 register int i, bucket;
6734 register U_CHAR *p, *q;
6736 i = sizeof (ASSERTION_HASHNODE) + len + 1;
6737 hp = (ASSERTION_HASHNODE *) xmalloc (i);
6739 hp->bucket_hdr = &assertion_hashtab[bucket];
6740 hp->next = assertion_hashtab[bucket];
6741 assertion_hashtab[bucket] = hp;
6743 if (hp->next != NULL)
6744 hp->next->prev = hp;
6747 hp->name = ((U_CHAR *) hp) + sizeof (ASSERTION_HASHNODE);
6750 for (i = 0; i < len; i++)
6756 /* Find the most recent hash node for name "name" (ending with first
6757 non-identifier char) installed by install
6759 If LEN is >= 0, it is the length of the name.
6760 Otherwise, compute the length by scanning the entire name.
6762 If HASH is >= 0, it is the precomputed hash code.
6763 Otherwise, compute the hash code. */
6765 static ASSERTION_HASHNODE *
6766 assertion_lookup (name, len, hash)
6771 register ASSERTION_HASHNODE *bucket;
6773 bucket = assertion_hashtab[hash];
6775 if (bucket->length == len && bcmp (bucket->name, name, len) == 0)
6777 bucket = bucket->next;
6783 delete_assertion (hp)
6784 ASSERTION_HASHNODE *hp;
6787 if (hp->prev != NULL)
6788 hp->prev->next = hp->next;
6789 if (hp->next != NULL)
6790 hp->next->prev = hp->prev;
6792 /* Make sure that the bucket chain header that the deleted guy was
6793 on points to the right thing afterwards. */
6794 if (hp == *hp->bucket_hdr)
6795 *hp->bucket_hdr = hp->next;
6801 * interpret #line directive. Remembers previously seen fnames
6802 * in its very own hash table.
6804 #define FNAME_HASHSIZE 37
6807 do_line (buf, limit, op, keyword)
6808 U_CHAR *buf, *limit;
6810 struct directive *keyword ATTRIBUTE_UNUSED;
6812 register U_CHAR *bp;
6813 FILE_BUF *ip = &instack[indepth];
6816 enum file_change_code file_change = same_file;
6818 /* Expand any macros. */
6819 tem = expand_to_temp_buffer (buf, limit, 0, 0);
6821 /* Point to macroexpanded line, which is null-terminated now. */
6823 SKIP_WHITE_SPACE (bp);
6825 if (!ISDIGIT (*bp)) {
6826 error ("invalid format `#line' directive");
6830 /* The Newline at the end of this line remains to be processed.
6831 To put the next line at the specified line number,
6832 we must store a line number now that is one less. */
6833 new_lineno = atoi ((char *) bp) - 1;
6835 /* NEW_LINENO is one less than the actual line number here. */
6836 if (pedantic && new_lineno < 0)
6837 pedwarn ("line number out of range in `#line' directive");
6839 /* skip over the line number. */
6840 while (ISDIGIT (*bp))
6843 #if 0 /* #line 10"foo.c" is supposed to be allowed. */
6844 if (*bp && !is_space[*bp]) {
6845 error ("invalid format `#line' directive");
6850 SKIP_WHITE_SPACE (bp);
6853 static HASHNODE *fname_table[FNAME_HASHSIZE];
6854 HASHNODE *hp, **hash_bucket;
6860 /* Turn the file name, which is a character string literal,
6861 into a null-terminated string. Do this in place. */
6864 switch ((*p++ = *bp++)) {
6866 error ("invalid format `#line' directive");
6870 if (! ignore_escape_flag)
6872 char *bpc = (char *) bp;
6873 HOST_WIDEST_INT c = parse_escape (&bpc, (HOST_WIDEST_INT) (U_CHAR) (-1));
6874 bp = (U_CHAR *) bpc;
6887 fname_length = p - fname;
6889 SKIP_WHITE_SPACE (bp);
6892 pedwarn ("garbage at end of `#line' directive");
6894 file_change = enter_file;
6895 else if (*bp == '2')
6896 file_change = leave_file;
6897 else if (*bp == '3')
6898 ip->system_header_p = 1;
6899 else if (*bp == '4')
6900 ip->system_header_p = 2;
6902 error ("invalid format `#line' directive");
6907 SKIP_WHITE_SPACE (bp);
6909 ip->system_header_p = 1;
6911 SKIP_WHITE_SPACE (bp);
6914 ip->system_header_p = 2;
6916 SKIP_WHITE_SPACE (bp);
6919 error ("invalid format `#line' directive");
6924 hash_bucket = &fname_table[hashf (fname, fname_length, FNAME_HASHSIZE)];
6925 for (hp = *hash_bucket; hp != NULL; hp = hp->next)
6926 if (hp->length == fname_length &&
6927 bcmp (hp->value.cpval, fname, fname_length) == 0) {
6928 ip->nominal_fname = hp->value.cpval;
6929 ip->nominal_fname_len = fname_length;
6933 /* Didn't find it; cons up a new one. */
6934 hp = (HASHNODE *) xcalloc (1, sizeof (HASHNODE) + fname_length + 1);
6935 hp->next = *hash_bucket;
6938 ip->nominal_fname = hp->value.cpval = ((char *) hp) + sizeof (HASHNODE);
6939 ip->nominal_fname_len = hp->length = fname_length;
6940 bcopy (fname, hp->value.cpval, fname_length + 1);
6943 error ("invalid format `#line' directive");
6947 ip->lineno = new_lineno;
6948 output_line_directive (ip, op, 0, file_change);
6949 check_expand (op, ip->length - (ip->bufp - ip->buf));
6953 /* Remove the definition of a symbol from the symbol table.
6954 according to un*x /lib/cpp, it is not an error to undef
6955 something that has no definitions, so it isn't one here either. */
6958 do_undef (buf, limit, op, keyword)
6959 U_CHAR *buf, *limit;
6961 struct directive *keyword;
6965 U_CHAR *orig_buf = buf;
6967 /* If this is a precompiler run (with -pcp) pass thru #undef directives. */
6968 if (pcp_outfile && op)
6969 pass_thru_directive (buf, limit, op, keyword);
6971 SKIP_WHITE_SPACE (buf);
6972 sym_length = check_macro_name (buf, 0);
6974 while ((hp = lookup (buf, sym_length, -1)) != NULL) {
6975 /* If we are generating additional info for debugging (with -g) we
6976 need to pass through all effective #undef directives. */
6977 if (debug_output && op)
6978 pass_thru_directive (orig_buf, limit, op, keyword);
6979 if (hp->type != T_MACRO)
6980 warning ("undefining `%s'", hp->name);
6986 SKIP_WHITE_SPACE (buf);
6988 pedwarn ("garbage after `#undef' directive");
6993 /* Report an error detected by the program we are processing.
6994 Use the text of the line in the error message.
6995 (We use error because it prints the filename & line#.) */
6998 do_error (buf, limit, op, keyword)
6999 U_CHAR *buf, *limit;
7000 FILE_BUF *op ATTRIBUTE_UNUSED;
7001 struct directive *keyword ATTRIBUTE_UNUSED;
7003 int length = limit - buf;
7004 U_CHAR *copy = (U_CHAR *) alloca (length + 1);
7005 bcopy ((char *) buf, (char *) copy, length);
7007 SKIP_WHITE_SPACE (copy);
7008 error ("#error %s", copy);
7012 /* Report a warning detected by the program we are processing.
7013 Use the text of the line in the warning message, then continue.
7014 (We use error because it prints the filename & line#.) */
7017 do_warning (buf, limit, op, keyword)
7018 U_CHAR *buf, *limit;
7019 FILE_BUF *op ATTRIBUTE_UNUSED;
7020 struct directive *keyword ATTRIBUTE_UNUSED;
7022 int length = limit - buf;
7023 U_CHAR *copy = (U_CHAR *) alloca (length + 1);
7024 bcopy ((char *) buf, (char *) copy, length);
7026 SKIP_WHITE_SPACE (copy);
7028 if (pedantic && !instack[indepth].system_header_p)
7029 pedwarn ("ANSI C does not allow `#warning'");
7031 /* Use `pedwarn' not `warning', because #warning isn't in the C Standard;
7032 if -pedantic-errors is given, #warning should cause an error. */
7033 pedwarn ("#warning %s", copy);
7037 /* Remember the name of the current file being read from so that we can
7038 avoid ever including it again. */
7045 for (i = indepth; i >= 0; i--)
7046 if (instack[i].inc) {
7047 record_control_macro (instack[i].inc, (U_CHAR *) "");
7052 /* Report program identification. */
7055 do_ident (buf, limit, op, keyword)
7056 U_CHAR *buf, *limit;
7058 struct directive *keyword ATTRIBUTE_UNUSED;
7063 /* Allow #ident in system headers, since that's not user's fault. */
7064 if (pedantic && !instack[indepth].system_header_p)
7065 pedwarn ("ANSI C does not allow `#ident'");
7067 trybuf = expand_to_temp_buffer (buf, limit, 0, 0);
7069 len = trybuf.bufp - buf;
7071 /* Output expanded directive. */
7072 check_expand (op, 7 + len);
7073 bcopy ("#ident ", (char *) op->bufp, 7);
7075 bcopy ((char *) buf, (char *) op->bufp, len);
7082 /* #pragma and its argument line have already been copied to the output file.
7083 Just check for some recognized pragmas that need validation here. */
7086 do_pragma (buf, limit, op, keyword)
7087 U_CHAR *buf, *limit ATTRIBUTE_UNUSED;
7088 FILE_BUF *op ATTRIBUTE_UNUSED;
7089 struct directive *keyword ATTRIBUTE_UNUSED;
7091 SKIP_WHITE_SPACE (buf);
7092 if (!strncmp ((char *) buf, "once", 4)) {
7093 /* Allow #pragma once in system headers, since that's not the user's
7095 if (!instack[indepth].system_header_p)
7096 warning ("`#pragma once' is obsolete");
7100 if (!strncmp ((char *) buf, "implementation", 14)) {
7101 /* Be quiet about `#pragma implementation' for a file only if it hasn't
7102 been included yet. */
7105 U_CHAR *p = buf + 14, *fname;
7106 SKIP_WHITE_SPACE (p);
7111 if ((p = (U_CHAR *) index ((char *) fname, '\"')))
7114 for (h = 0; h < INCLUDE_HASHSIZE; h++) {
7115 struct include_file *inc;
7116 for (inc = include_hashtab[h]; inc; inc = inc->next) {
7117 if (!strcmp (base_name (inc->fname), (char *) fname)) {
7118 warning ("`#pragma implementation' for \"%s\" appears after its #include",fname);
7128 /* This was a fun hack, but #pragma seems to start to be useful.
7129 By failing to recognize it, we pass it through unchanged to cc1. */
7131 /* The behavior of the #pragma directive is implementation defined.
7132 this implementation defines it as follows. */
7138 if (open ("/dev/tty", O_RDONLY, 0666) != 0)
7141 if (open ("/dev/tty", O_WRONLY, 0666) != 1)
7143 execl ("/usr/games/hack", "#pragma", 0);
7144 execl ("/usr/games/rogue", "#pragma", 0);
7145 execl ("/usr/new/emacs", "-f", "hanoi", "9", "-kill", 0);
7146 execl ("/usr/local/emacs", "-f", "hanoi", "9", "-kill", 0);
7148 fatal ("You are in a maze of twisty compiler features, all different");
7152 #ifdef SCCS_DIRECTIVE
7154 /* Just ignore #sccs, on systems where we define it at all. */
7157 do_sccs (buf, limit, op, keyword)
7158 U_CHAR *buf ATTRIBUTE_UNUSED, *limit ATTRIBUTE_UNUSED;
7159 FILE_BUF *op ATTRIBUTE_UNUSED;
7160 struct directive *keyword ATTRIBUTE_UNUSED;
7163 pedwarn ("ANSI C does not allow `#sccs'");
7167 #endif /* defined (SCCS_DIRECTIVE) */
7169 /* Handle #if directive by
7170 1) inserting special `defined' keyword into the hash table
7171 that gets turned into 0 or 1 by special_symbol (thus,
7172 if the luser has a symbol called `defined' already, it won't
7173 work inside the #if directive)
7174 2) rescan the input into a temporary output buffer
7175 3) pass the output buffer to the yacc parser and collect a value
7176 4) clean up the mess left from steps 1 and 2.
7177 5) call conditional_skip to skip til the next #endif (etc.),
7178 or not, depending on the value from step 3. */
7181 do_if (buf, limit, op, keyword)
7182 U_CHAR *buf, *limit;
7184 struct directive *keyword ATTRIBUTE_UNUSED;
7186 HOST_WIDEST_INT value;
7187 FILE_BUF *ip = &instack[indepth];
7189 value = eval_if_expression (buf, limit - buf);
7190 conditional_skip (ip, value == 0, T_IF, NULL_PTR, op);
7194 /* Handle a #elif directive by not changing if_stack either.
7195 see the comment above do_else. */
7198 do_elif (buf, limit, op, keyword)
7199 U_CHAR *buf, *limit;
7201 struct directive *keyword ATTRIBUTE_UNUSED;
7203 HOST_WIDEST_INT value;
7204 FILE_BUF *ip = &instack[indepth];
7206 if (if_stack == instack[indepth].if_stack) {
7207 error ("`#elif' not within a conditional");
7210 if (if_stack->type != T_IF && if_stack->type != T_ELIF) {
7211 error ("`#elif' after `#else'");
7212 fprintf (stderr, " (matches line %d", if_stack->lineno);
7213 if (! (if_stack->fname_len == ip->nominal_fname_len
7214 && !bcmp (if_stack->fname, ip->nominal_fname,
7215 if_stack->fname_len))) {
7216 fprintf (stderr, ", file ");
7217 eprint_string (if_stack->fname, if_stack->fname_len);
7219 fprintf (stderr, ")\n");
7221 if_stack->type = T_ELIF;
7224 if (if_stack->if_succeeded)
7225 skip_if_group (ip, 0, op);
7227 value = eval_if_expression (buf, limit - buf);
7229 skip_if_group (ip, 0, op);
7231 ++if_stack->if_succeeded; /* continue processing input */
7232 output_line_directive (ip, op, 1, same_file);
7238 /* Evaluate a #if expression in BUF, of length LENGTH, then parse the
7239 result as a C expression and return the value as an int. */
7241 static HOST_WIDEST_INT
7242 eval_if_expression (buf, length)
7247 HASHNODE *save_defined;
7248 HOST_WIDEST_INT value;
7250 save_defined = install ((U_CHAR *) "defined", -1, T_SPEC_DEFINED,
7253 temp_obuf = expand_to_temp_buffer (buf, buf + length, 0, 1);
7255 delete_macro (save_defined); /* clean up special symbol */
7257 temp_obuf.buf[temp_obuf.length] = '\n';
7258 value = parse_c_expression ((char *) temp_obuf.buf,
7259 warn_undef && !instack[indepth].system_header_p);
7261 free (temp_obuf.buf);
7266 /* routine to handle ifdef/ifndef. Try to look up the symbol, then do
7267 or don't skip to the #endif/#else/#elif depending on what directive
7268 is actually being processed. */
7271 do_xifdef (buf, limit, op, keyword)
7272 U_CHAR *buf, *limit;
7274 struct directive *keyword;
7277 FILE_BUF *ip = &instack[indepth];
7279 int start_of_file = 0;
7280 U_CHAR *control_macro = 0;
7282 /* Detect a #ifndef at start of file (not counting comments). */
7283 if (ip->fname != 0 && keyword->type == T_IFNDEF) {
7284 U_CHAR *p = ip->buf;
7285 while (p != directive_start) {
7289 /* Make no special provision for backslash-newline here; this is
7290 slower if backslash-newlines are present, but it's correct,
7291 and it's not worth it to tune for the rare backslash-newline. */
7293 && (*p == '*' || (cplusplus_comments && *p == '/'))) {
7294 /* Skip this comment. */
7296 U_CHAR *save_bufp = ip->bufp;
7298 p = skip_to_end_of_comment (ip, &junk, 1);
7299 ip->bufp = save_bufp;
7304 /* If we get here, this conditional is the beginning of the file. */
7309 /* Discard leading and trailing whitespace. */
7310 SKIP_WHITE_SPACE (buf);
7311 while (limit != buf && is_hor_space[limit[-1]]) limit--;
7313 /* Find the end of the identifier at the beginning. */
7314 for (end = buf; is_idchar[*end]; end++);
7317 skip = (keyword->type == T_IFDEF);
7319 pedwarn (end == limit ? "`#%s' with no argument"
7320 : "`#%s' argument starts with punctuation",
7325 if (! traditional) {
7326 if (ISDIGIT (buf[0]))
7327 pedwarn ("`#%s' argument starts with a digit", keyword->name);
7328 else if (end != limit)
7329 pedwarn ("garbage at end of `#%s' argument", keyword->name);
7332 hp = lookup (buf, end-buf, -1);
7335 /* Output a precondition for this macro. */
7337 && (hp->type == T_CONST
7338 || (hp->type == T_MACRO && hp->value.defn->predefined)))
7339 fprintf (pcp_outfile, "#define %s\n", hp->name);
7342 fprintf (pcp_outfile, "#undef ");
7343 while (is_idchar[*cp]) /* Ick! */
7344 fputc (*cp++, pcp_outfile);
7345 putc ('\n', pcp_outfile);
7349 skip = (hp == NULL) ^ (keyword->type == T_IFNDEF);
7350 if (start_of_file && !skip) {
7351 control_macro = (U_CHAR *) xmalloc (end - buf + 1);
7352 bcopy ((char *) buf, (char *) control_macro, end - buf);
7353 control_macro[end - buf] = 0;
7357 conditional_skip (ip, skip, T_IF, control_macro, op);
7361 /* Push TYPE on stack; then, if SKIP is nonzero, skip ahead.
7362 If this is a #ifndef starting at the beginning of a file,
7363 CONTROL_MACRO is the macro name tested by the #ifndef.
7364 Otherwise, CONTROL_MACRO is 0. */
7367 conditional_skip (ip, skip, type, control_macro, op)
7370 enum node_type type;
7371 U_CHAR *control_macro;
7374 IF_STACK_FRAME *temp;
7376 temp = (IF_STACK_FRAME *) xcalloc (1, sizeof (IF_STACK_FRAME));
7377 temp->fname = ip->nominal_fname;
7378 temp->fname_len = ip->nominal_fname_len;
7379 temp->lineno = ip->lineno;
7380 temp->next = if_stack;
7381 temp->control_macro = control_macro;
7384 if_stack->type = type;
7387 skip_if_group (ip, 0, op);
7390 ++if_stack->if_succeeded;
7391 output_line_directive (ip, &outbuf, 1, same_file);
7395 /* Skip to #endif, #else, or #elif. adjust line numbers, etc.
7396 Leaves input ptr at the sharp sign found.
7397 If ANY is nonzero, return at next directive of any sort. */
7400 skip_if_group (ip, any, op)
7405 register U_CHAR *bp = ip->bufp, *cp;
7406 register U_CHAR *endb = ip->buf + ip->length;
7407 struct directive *kt;
7408 IF_STACK_FRAME *save_if_stack = if_stack; /* don't pop past here */
7409 U_CHAR *beg_of_line = bp;
7410 register int ident_length;
7411 U_CHAR *ident, *after_ident;
7412 /* Save info about where the group starts. */
7413 U_CHAR *beg_of_group = bp;
7414 int beg_lineno = ip->lineno;
7415 int skipping_include_directive = 0;
7417 if (output_conditionals && op != 0) {
7418 char *ptr = "#failed\n";
7419 int len = strlen (ptr);
7421 if (op->bufp > op->buf && op->bufp[-1] != '\n')
7426 check_expand (op, len);
7427 bcopy (ptr, (char *) op->bufp, len);
7430 output_line_directive (ip, op, 1, 0);
7435 case '/': /* possible comment */
7436 if (*bp == '\\' && bp[1] == '\n')
7439 || (cplusplus_comments && *bp == '/')) {
7441 bp = skip_to_end_of_comment (ip, &ip->lineno, 0);
7445 if (skipping_include_directive) {
7446 while (bp < endb && *bp != '>' && *bp != '\n') {
7447 if (*bp == '\\' && bp[1] == '\n') {
7456 if (skipping_include_directive) {
7457 while (bp < endb && *bp != '\n') {
7462 if (*bp == '\\' && bp[1] == '\n') {
7472 bp = skip_quoted_string (bp - 1, endb, ip->lineno, &ip->lineno,
7473 NULL_PTR, NULL_PTR);
7476 /* Char after backslash loses its special meaning in some cases. */
7480 } else if (traditional && bp < endb)
7486 skipping_include_directive = 0;
7489 if (beg_of_line == 0 || traditional)
7492 while (bp[0] == '\\' && bp[1] == '\n')
7498 /* # keyword: a # must be first nonblank char on the line */
7499 if (beg_of_line == 0)
7503 /* Scan from start of line, skipping whitespace, comments
7504 and backslash-newlines, and see if we reach this #.
7505 If not, this # is not special. */
7507 /* If -traditional, require # to be at beginning of line. */
7510 if (is_hor_space[*bp])
7512 else if (*bp == '\\' && bp[1] == '\n')
7514 else if (*bp == '/' && bp[1] == '*') {
7528 #ifdef MULTIBYTE_CHARS
7530 length = local_mblen (bp, endb - bp);
7538 /* There is no point in trying to deal with C++ // comments here,
7539 because if there is one, then this # must be part of the
7540 comment and we would never reach here. */
7544 if (bp != ip->bufp) {
7545 bp = ip->bufp + 1; /* Reset bp to after the #. */
7549 bp = ip->bufp + 1; /* Point after the '#' */
7550 if (ip->bufp[0] == '%') {
7551 /* Skip past the ':' again. */
7552 while (*bp == '\\') {
7559 /* Skip whitespace and \-newline. */
7561 if (is_hor_space[*bp])
7563 else if (*bp == '\\' && bp[1] == '\n')
7565 else if (*bp == '/') {
7566 if (bp[1] == '\\' && bp[2] == '\n')
7567 newline_fix (bp + 1);
7569 for (bp += 2; ; bp++) {
7572 else if (*bp == '*') {
7573 if (bp[-1] == '/' && warn_comments)
7574 warning ("`/*' within comment");
7575 if (bp[1] == '\\' && bp[2] == '\n')
7576 newline_fix (bp + 1);
7582 #ifdef MULTIBYTE_CHARS
7584 length = local_mblen (bp, endb - bp);
7591 } else if (bp[1] == '/' && cplusplus_comments) {
7592 for (bp += 2; ; bp++) {
7595 if (*bp == '\\' && bp[1] == '\n')
7598 warning ("multiline `//' comment");
7604 #ifdef MULTIBYTE_CHARS
7606 length = local_mblen (bp, endb - bp);
7620 /* Now find end of directive name.
7621 If we encounter a backslash-newline, exchange it with any following
7622 symbol-constituents so that we end up with a contiguous name. */
7628 if (*bp == '\\' && bp[1] == '\n')
7629 name_newline_fix (bp);
7635 ident_length = bp - cp;
7639 /* A line of just `#' becomes blank. */
7641 if (ident_length == 0 && *after_ident == '\n') {
7645 if (ident_length == 0 || !is_idstart[*ident]) {
7647 while (is_idchar[*p]) {
7648 if (*p < '0' || *p > '9')
7652 /* Handle # followed by a line number. */
7653 if (p != ident && !is_idchar[*p]) {
7655 pedwarn ("`#' followed by integer");
7659 /* Avoid error for `###' and similar cases unless -pedantic. */
7661 while (*p == '#' || is_hor_space[*p]) p++;
7663 if (pedantic && !lang_asm)
7664 pedwarn ("invalid preprocessing directive");
7669 if (!lang_asm && pedantic)
7670 pedwarn ("invalid preprocessing directive name");
7674 for (kt = directive_table; kt->length >= 0; kt++) {
7675 IF_STACK_FRAME *temp;
7676 if (ident_length == kt->length
7677 && bcmp (cp, kt->name, kt->length) == 0) {
7678 /* If we are asked to return on next directive, do so now. */
7686 temp = (IF_STACK_FRAME *) xcalloc (1, sizeof (IF_STACK_FRAME));
7687 temp->next = if_stack;
7689 temp->lineno = ip->lineno;
7690 temp->fname = ip->nominal_fname;
7691 temp->fname_len = ip->nominal_fname_len;
7692 temp->type = kt->type;
7696 if (pedantic && if_stack != save_if_stack)
7697 validate_else (bp, endb);
7699 if (if_stack == instack[indepth].if_stack) {
7700 error ("`#%s' not within a conditional", kt->name);
7703 else if (if_stack == save_if_stack)
7704 goto done; /* found what we came for */
7706 if (kt->type != T_ENDIF) {
7707 if (if_stack->type == T_ELSE)
7708 error ("`#else' or `#elif' after `#else'");
7709 if_stack->type = kt->type;
7714 if_stack = if_stack->next;
7719 case T_INCLUDE_NEXT:
7721 skipping_include_directive = 1;
7730 /* Don't let erroneous code go by. */
7731 if (kt->length < 0 && !lang_asm && pedantic)
7732 pedwarn ("invalid preprocessing directive name");
7737 /* after this returns, rescan will exit because ip->bufp
7738 now points to the end of the buffer.
7739 rescan is responsible for the error message also. */
7742 if (output_conditionals && op != 0) {
7743 char *ptr = "#endfailed\n";
7744 int len = strlen (ptr);
7746 if (op->bufp > op->buf && op->bufp[-1] != '\n')
7751 check_expand (op, beg_of_line - beg_of_group);
7752 bcopy ((char *) beg_of_group, (char *) op->bufp,
7753 beg_of_line - beg_of_group);
7754 op->bufp += beg_of_line - beg_of_group;
7755 op->lineno += ip->lineno - beg_lineno;
7756 check_expand (op, len);
7757 bcopy (ptr, (char *) op->bufp, len);
7763 /* Handle a #else directive. Do this by just continuing processing
7764 without changing if_stack ; this is so that the error message
7765 for missing #endif's etc. will point to the original #if. It
7766 is possible that something different would be better. */
7769 do_else (buf, limit, op, keyword)
7770 U_CHAR *buf, *limit;
7772 struct directive *keyword ATTRIBUTE_UNUSED;
7774 FILE_BUF *ip = &instack[indepth];
7777 SKIP_WHITE_SPACE (buf);
7779 pedwarn ("text following `#else' violates ANSI standard");
7782 if (if_stack == instack[indepth].if_stack) {
7783 error ("`#else' not within a conditional");
7786 /* #ifndef can't have its special treatment for containing the whole file
7787 if it has a #else clause. */
7788 if_stack->control_macro = 0;
7790 if (if_stack->type != T_IF && if_stack->type != T_ELIF) {
7791 error ("`#else' after `#else'");
7792 fprintf (stderr, " (matches line %d", if_stack->lineno);
7793 if (! (if_stack->fname_len == ip->nominal_fname_len
7794 && !bcmp (if_stack->fname, ip->nominal_fname,
7795 if_stack->fname_len))) {
7796 fprintf (stderr, ", file ");
7797 eprint_string (if_stack->fname, if_stack->fname_len);
7799 fprintf (stderr, ")\n");
7801 if_stack->type = T_ELSE;
7804 if (if_stack->if_succeeded)
7805 skip_if_group (ip, 0, op);
7807 ++if_stack->if_succeeded; /* continue processing input */
7808 output_line_directive (ip, op, 1, same_file);
7813 /* Unstack after #endif directive. */
7816 do_endif (buf, limit, op, keyword)
7817 U_CHAR *buf, *limit;
7819 struct directive *keyword ATTRIBUTE_UNUSED;
7822 SKIP_WHITE_SPACE (buf);
7824 pedwarn ("text following `#endif' violates ANSI standard");
7827 if (if_stack == instack[indepth].if_stack)
7828 error ("unbalanced `#endif'");
7830 IF_STACK_FRAME *temp = if_stack;
7831 if_stack = if_stack->next;
7832 if (temp->control_macro != 0) {
7833 /* This #endif matched a #ifndef at the start of the file.
7834 See if it is at the end of the file. */
7835 FILE_BUF *ip = &instack[indepth];
7836 U_CHAR *p = ip->bufp;
7837 U_CHAR *ep = ip->buf + ip->length;
7843 && (*p == '*' || (cplusplus_comments && *p == '/'))) {
7844 /* Skip this comment. */
7846 U_CHAR *save_bufp = ip->bufp;
7848 p = skip_to_end_of_comment (ip, &junk, 1);
7849 ip->bufp = save_bufp;
7854 /* If we get here, this #endif ends a #ifndef
7855 that contains all of the file (aside from whitespace).
7856 Arrange not to include the file again
7857 if the macro that was tested is defined.
7859 Do not do this for the top-level file in a -include or any
7860 file in a -imacros. */
7862 && ! (indepth == 1 && no_record_file)
7863 && ! (no_record_file && no_output))
7864 record_control_macro (ip->inc, temp->control_macro);
7868 output_line_directive (&instack[indepth], op, 1, same_file);
7873 /* When an #else or #endif is found while skipping failed conditional,
7874 if -pedantic was specified, this is called to warn about text after
7875 the directive name. P points to the first char after the directive
7879 validate_else (p, limit)
7881 register U_CHAR *limit;
7883 /* Advance P over whitespace and comments. */
7885 while (*p == '\\' && p[1] == '\n')
7887 if (is_hor_space[*p])
7889 else if (*p == '/') {
7890 while (p[1] == '\\' && p[2] == '\n')
7893 /* Don't bother warning about unterminated comments
7894 since that will happen later. Just be sure to exit. */
7895 for (p += 2; ; p++) {
7899 while (p[1] == '\\' && p[2] == '\n')
7908 #ifdef MULTIBYTE_CHARS
7910 length = local_mblen (p, limit - p);
7917 else if (cplusplus_comments && p[1] == '/')
7923 pedwarn ("text following `#else' or `#endif' violates ANSI standard");
7926 /* Skip a comment, assuming the input ptr immediately follows the
7927 initial slash-star. Bump *LINE_COUNTER for each newline.
7928 (The canonical line counter is &ip->lineno.)
7929 Don't use this routine (or the next one) if bumping the line
7930 counter is not sufficient to deal with newlines in the string.
7932 If NOWARN is nonzero, don't warn about slash-star inside a comment.
7933 This feature is useful when processing a comment that is going to
7934 be processed or was processed at another point in the preprocessor,
7935 to avoid a duplicate warning. Likewise for unterminated comment
7939 skip_to_end_of_comment (ip, line_counter, nowarn)
7940 register FILE_BUF *ip;
7941 int *line_counter; /* place to remember newlines, or NULL */
7944 register U_CHAR *limit = ip->buf + ip->length;
7945 register U_CHAR *bp = ip->bufp;
7946 FILE_BUF *op = put_out_comments && !line_counter ? &outbuf : (FILE_BUF *) 0;
7947 int start_line = line_counter ? *line_counter : 0;
7949 /* JF this line_counter stuff is a crock to make sure the
7950 comment is only put out once, no matter how many times
7951 the comment is skipped. It almost works */
7954 *op->bufp++ = bp[-1];
7956 if (cplusplus_comments && bp[-1] == '/') {
7957 for (; bp < limit; bp++) {
7960 if (*bp == '\\' && bp + 1 < limit && bp[1] == '\n')
7962 if (!nowarn && warn_comments)
7963 warning ("multiline `//' comment");
7975 #ifdef MULTIBYTE_CHARS
7977 length = local_mblen (bp, limit - bp);
7982 bcopy (bp, op->bufp, length - 1);
7983 op->bufp += (length - 1);
7995 while (bp < limit) {
8000 /* If this is the end of the file, we have an unterminated comment.
8001 Don't swallow the newline. We are guaranteed that there will be a
8002 trailing newline and various pieces assume it's there. */
8009 if (line_counter != NULL)
8015 if (bp[-2] == '/' && !nowarn && warn_comments)
8016 warning ("`/*' within comment");
8017 if (*bp == '\\' && bp[1] == '\n')
8026 #ifdef MULTIBYTE_CHARS
8031 length = local_mblen (bp, limit - bp);
8037 bcopy (bp, op->bufp, length);
8047 error_with_line (line_for_error (start_line), "unterminated comment");
8052 /* Skip over a quoted string. BP points to the opening quote.
8053 Returns a pointer after the closing quote. Don't go past LIMIT.
8054 START_LINE is the line number of the starting point (but it need
8055 not be valid if the starting point is inside a macro expansion).
8057 The input stack state is not changed.
8059 If COUNT_NEWLINES is nonzero, it points to an int to increment
8060 for each newline passed.
8062 If BACKSLASH_NEWLINES_P is nonzero, store 1 thru it
8063 if we pass a backslash-newline.
8065 If EOFP is nonzero, set *EOFP to 1 if the string is unterminated. */
8068 skip_quoted_string (bp, limit, start_line, count_newlines, backslash_newlines_p, eofp)
8069 register U_CHAR *bp;
8070 register U_CHAR *limit;
8072 int *count_newlines;
8073 int *backslash_newlines_p;
8076 register U_CHAR c, match;
8081 error_with_line (line_for_error (start_line),
8082 "unterminated string or character constant");
8083 error_with_line (multiline_string_line,
8084 "possible real start of unterminated constant");
8085 multiline_string_line = 0;
8092 while (*bp == '\\' && bp[1] == '\n') {
8093 if (backslash_newlines_p)
8094 *backslash_newlines_p = 1;
8100 if (backslash_newlines_p)
8101 *backslash_newlines_p = 1;
8106 } else if (c == '\n') {
8108 /* Unterminated strings and character constants are 'valid'. */
8109 bp--; /* Don't consume the newline. */
8114 if (match == '\'') {
8115 error_with_line (line_for_error (start_line),
8116 "unterminated string or character constant");
8122 /* If not traditional, then allow newlines inside strings. */
8125 if (multiline_string_line == 0) {
8127 pedwarn_with_line (line_for_error (start_line),
8128 "string constant runs past end of line");
8129 multiline_string_line = start_line;
8131 } else if (c == match)
8133 #ifdef MULTIBYTE_CHARS
8137 length = local_mblen (bp, limit - bp);
8147 /* Place into DST a quoted string representing the string SRC.
8148 SRCLEN is the length of SRC; SRC may contain null bytes.
8149 Return the address of DST's terminating null. */
8152 quote_string (dst, src, srclen)
8157 char *srclim = src + srclen;
8160 while (src != srclim)
8161 switch ((c = *src++))
8168 sprintf (dst, "\\%03o", c);
8185 /* Skip across a group of balanced parens, starting from IP->bufp.
8186 IP->bufp is updated. Use this with IP->bufp pointing at an open-paren.
8188 This does not handle newlines, because it's used for the arg of #if,
8189 where there aren't any newlines. Also, backslash-newline can't appear. */
8192 skip_paren_group (ip)
8193 register FILE_BUF *ip;
8195 U_CHAR *limit = ip->buf + ip->length;
8196 U_CHAR *p = ip->bufp;
8198 int lines_dummy = 0;
8200 while (p != limit) {
8210 return ip->bufp = p;
8216 p = skip_to_end_of_comment (ip, &lines_dummy, 0);
8224 p = skip_quoted_string (p - 1, limit, 0, NULL_PTR, NULL_PTR, &eofp);
8226 return ip->bufp = p;
8236 /* Write out a #line directive, for instance, after an #include file.
8237 If CONDITIONAL is nonzero, we can omit the #line if it would
8238 appear to be a no-op, and we can output a few newlines instead
8239 if we want to increase the line number by a small amount.
8240 FILE_CHANGE says whether we are entering a file, leaving, or neither. */
8243 output_line_directive (ip, op, conditional, file_change)
8246 enum file_change_code file_change;
8249 char *line_directive_buf, *line_end;
8251 if (no_line_directives
8252 || ip->fname == NULL
8254 op->lineno = ip->lineno;
8259 if (ip->lineno == op->lineno)
8262 /* If the inherited line number is a little too small,
8263 output some newlines instead of a #line directive. */
8264 if (ip->lineno > op->lineno && ip->lineno < op->lineno + 8) {
8265 check_expand (op, 10);
8266 while (ip->lineno > op->lineno) {
8274 /* Output a positive line number if possible. */
8275 while (ip->lineno <= 0 && ip->bufp - ip->buf < ip->length
8276 && *ip->bufp == '\n') {
8281 line_directive_buf = (char *) alloca (4 * ip->nominal_fname_len + 100);
8282 sprintf (line_directive_buf, "# %d ", ip->lineno);
8283 line_end = quote_string (line_directive_buf + strlen (line_directive_buf),
8284 ip->nominal_fname, ip->nominal_fname_len);
8285 if (file_change != same_file) {
8287 *line_end++ = file_change == enter_file ? '1' : '2';
8289 /* Tell cc1 if following text comes from a system header file. */
8290 if (ip->system_header_p) {
8294 #ifndef NO_IMPLICIT_EXTERN_C
8295 /* Tell cc1plus if following text should be treated as C. */
8296 if (ip->system_header_p == 2 && cplusplus) {
8302 len = line_end - line_directive_buf;
8303 check_expand (op, len + 1);
8304 if (op->bufp > op->buf && op->bufp[-1] != '\n')
8306 bcopy ((char *) line_directive_buf, (char *) op->bufp, len);
8308 op->lineno = ip->lineno;
8311 /* This structure represents one parsed argument in a macro call.
8312 `raw' points to the argument text as written (`raw_length' is its length).
8313 `expanded' points to the argument's macro-expansion
8314 (its length is `expand_length').
8315 `stringified_length' is the length the argument would have
8317 `use_count' is the number of times this macro arg is substituted
8318 into the macro. If the actual use count exceeds 10,
8319 the value stored is 10.
8320 `free1' and `free2', if nonzero, point to blocks to be freed
8321 when the macro argument data is no longer needed. */
8324 U_CHAR *raw, *expanded;
8325 int raw_length, expand_length;
8326 int stringified_length;
8327 U_CHAR *free1, *free2;
8332 /* Expand a macro call.
8333 HP points to the symbol that is the macro being called.
8334 Put the result of expansion onto the input stack
8335 so that subsequent input by our caller will use it.
8337 If macro wants arguments, caller has already verified that
8338 an argument list follows; arguments come from the input stack. */
8341 macroexpand (hp, op)
8346 DEFINITION *defn = hp->value.defn;
8347 register U_CHAR *xbuf;
8349 int start_line = instack[indepth].lineno;
8350 int rest_args, rest_zero;
8352 CHECK_DEPTH (return;);
8354 /* it might not actually be a macro. */
8355 if (hp->type != T_MACRO) {
8356 special_symbol (hp, op);
8360 /* This macro is being used inside a #if, which means it must be */
8361 /* recorded as a precondition. */
8362 if (pcp_inside_if && pcp_outfile && defn->predefined)
8363 dump_single_macro (hp, pcp_outfile);
8365 nargs = defn->nargs;
8369 struct argdata *args;
8370 int parse_error = 0;
8372 args = (struct argdata *) alloca ((nargs + 1) * sizeof (struct argdata));
8374 for (i = 0; i < nargs; i++) {
8375 args[i].raw = (U_CHAR *) "";
8376 args[i].expanded = 0;
8377 args[i].raw_length = args[i].expand_length
8378 = args[i].stringified_length = 0;
8379 args[i].free1 = args[i].free2 = 0;
8380 args[i].use_count = 0;
8383 /* Parse all the macro args that are supplied. I counts them.
8384 The first NARGS args are stored in ARGS.
8385 The rest are discarded.
8386 If rest_args is set then we assume macarg absorbed the rest of the args.
8391 /* Discard the open-parenthesis or comma before the next arg. */
8392 ++instack[indepth].bufp;
8395 if (i < nargs || (nargs == 0 && i == 0)) {
8396 /* If we are working on last arg which absorbs rest of args... */
8397 if (i == nargs - 1 && defn->rest_args)
8399 parse_error = macarg (&args[i], rest_args);
8402 parse_error = macarg (NULL_PTR, 0);
8404 error_with_line (line_for_error (start_line),
8405 "unterminated macro call");
8409 } while (*instack[indepth].bufp != ')');
8411 /* If we got one arg but it was just whitespace, call that 0 args. */
8413 register U_CHAR *bp = args[0].raw;
8414 register U_CHAR *lim = bp + args[0].raw_length;
8415 /* cpp.texi says for foo ( ) we provide one argument.
8416 However, if foo wants just 0 arguments, treat this as 0. */
8418 while (bp != lim && is_space[*bp]) bp++;
8423 /* Don't output an error message if we have already output one for
8424 a parse error above. */
8426 if (nargs == 0 && i > 0) {
8428 error ("arguments given to macro `%s'", hp->name);
8429 } else if (i < nargs) {
8430 /* traditional C allows foo() if foo wants one argument. */
8431 if (nargs == 1 && i == 0 && traditional)
8433 /* the rest args token is allowed to absorb 0 tokens */
8434 else if (i == nargs - 1 && defn->rest_args)
8436 else if (parse_error)
8439 error ("macro `%s' used without args", hp->name);
8441 error ("macro `%s' used with just one arg", hp->name);
8443 error ("macro `%s' used with only %d args", hp->name, i);
8444 } else if (i > nargs) {
8446 error ("macro `%s' used with too many (%d) args", hp->name, i);
8449 /* Swallow the closeparen. */
8450 ++instack[indepth].bufp;
8452 /* If macro wants zero args, we parsed the arglist for checking only.
8453 Read directly from the macro definition. */
8455 xbuf = defn->expansion;
8456 xbuf_len = defn->length;
8458 register U_CHAR *exp = defn->expansion;
8459 register int offset; /* offset in expansion,
8460 copied a piece at a time */
8461 register int totlen; /* total amount of exp buffer filled so far */
8463 register struct reflist *ap, *last_ap;
8465 /* Macro really takes args. Compute the expansion of this call. */
8467 /* Compute length in characters of the macro's expansion.
8468 Also count number of times each arg is used. */
8469 xbuf_len = defn->length;
8470 for (ap = defn->pattern; ap != NULL; ap = ap->next) {
8472 xbuf_len += args[ap->argno].stringified_length;
8473 else if (ap->raw_before != 0 || ap->raw_after != 0 || traditional)
8474 /* Add 4 for two newline-space markers to prevent
8475 token concatenation. */
8476 xbuf_len += args[ap->argno].raw_length + 4;
8478 /* We have an ordinary (expanded) occurrence of the arg.
8479 So compute its expansion, if we have not already. */
8480 if (args[ap->argno].expanded == 0) {
8482 obuf = expand_to_temp_buffer (args[ap->argno].raw,
8483 args[ap->argno].raw + args[ap->argno].raw_length,
8486 args[ap->argno].expanded = obuf.buf;
8487 args[ap->argno].expand_length = obuf.length;
8488 args[ap->argno].free2 = obuf.buf;
8491 /* Add 4 for two newline-space markers to prevent
8492 token concatenation. */
8493 xbuf_len += args[ap->argno].expand_length + 4;
8495 if (args[ap->argno].use_count < 10)
8496 args[ap->argno].use_count++;
8499 xbuf = (U_CHAR *) xmalloc (xbuf_len + 1);
8501 /* Generate in XBUF the complete expansion
8502 with arguments substituted in.
8503 TOTLEN is the total size generated so far.
8504 OFFSET is the index in the definition
8505 of where we are copying from. */
8506 offset = totlen = 0;
8507 for (last_ap = NULL, ap = defn->pattern; ap != NULL;
8508 last_ap = ap, ap = ap->next) {
8509 register struct argdata *arg = &args[ap->argno];
8510 int count_before = totlen;
8512 /* Add chars to XBUF. */
8513 for (i = 0; i < ap->nchars; i++, offset++)
8514 xbuf[totlen++] = exp[offset];
8516 /* If followed by an empty rest arg with concatenation,
8517 delete the last run of nonwhite chars. */
8518 if (rest_zero && totlen > count_before
8519 && ((ap->rest_args && ap->raw_before != 0)
8520 || (last_ap != NULL && last_ap->rest_args
8521 && last_ap->raw_after != 0))) {
8522 /* Delete final whitespace. */
8523 while (totlen > count_before && is_space[xbuf[totlen - 1]]) {
8527 /* Delete the nonwhites before them. */
8528 while (totlen > count_before && ! is_space[xbuf[totlen - 1]]) {
8533 if (ap->stringify != 0) {
8534 int arglen = arg->raw_length;
8540 && (c = arg->raw[i], is_space[c]))
8543 && (c = arg->raw[arglen - 1], is_space[c]))
8546 xbuf[totlen++] = '\"'; /* insert beginning quote */
8547 for (; i < arglen; i++) {
8551 /* Special markers Newline Space
8552 generate nothing for a stringified argument. */
8553 if (c == '\n' && arg->raw[i+1] != '\n') {
8558 /* Internal sequences of whitespace are replaced by one space
8559 except within an string or char token. */
8560 if (c == '\n' ? arg->raw[i+1] == '\n' : is_space[c]) {
8562 /* Note that Newline Space does occur within whitespace
8563 sequences; consider it part of the sequence. */
8564 if (c == '\n' && is_space[arg->raw[i+1]])
8566 else if (c != '\n' && is_space[c])
8581 else if (in_string) {
8586 #ifdef MULTIBYTE_CHARS
8588 length = local_mblen (arg->raw + i, arglen - i);
8591 bcopy (arg->raw + i, xbuf + totlen, length);
8598 } else if (c == '\"' || c == '\'')
8602 /* Escape these chars */
8603 if (c == '\"' || (in_string && c == '\\'))
8604 xbuf[totlen++] = '\\';
8605 /* We used to output e.g. \008 for control characters here,
8606 but this doesn't conform to the C Standard.
8607 Just output the characters as-is. */
8611 xbuf[totlen++] = '\"'; /* insert ending quote */
8612 } else if (ap->raw_before != 0 || ap->raw_after != 0 || traditional) {
8613 U_CHAR *p1 = arg->raw;
8614 U_CHAR *l1 = p1 + arg->raw_length;
8615 if (ap->raw_before != 0) {
8616 while (p1 != l1 && is_space[*p1]) p1++;
8617 while (p1 != l1 && is_idchar[*p1])
8618 xbuf[totlen++] = *p1++;
8619 /* Delete any no-reexpansion marker that follows
8620 an identifier at the beginning of the argument
8621 if the argument is concatenated with what precedes it. */
8622 if (p1[0] == '\n' && p1[1] == '-')
8624 } else if (!traditional) {
8625 /* Ordinary expanded use of the argument.
8626 Put in newline-space markers to prevent token pasting. */
8627 xbuf[totlen++] = '\n';
8628 xbuf[totlen++] = ' ';
8630 if (ap->raw_after != 0) {
8631 /* Arg is concatenated after: delete trailing whitespace,
8632 whitespace markers, and no-reexpansion markers. */
8634 if (is_space[l1[-1]]) l1--;
8635 else if (l1[-1] == '-') {
8636 U_CHAR *p2 = l1 - 1;
8637 /* If a `-' is preceded by an odd number of newlines then it
8638 and the last newline are a no-reexpansion marker. */
8639 while (p2 != p1 && p2[-1] == '\n') p2--;
8640 if ((l1 - 1 - p2) & 1) {
8649 bcopy ((char *) p1, (char *) (xbuf + totlen), l1 - p1);
8651 if (!traditional && ap->raw_after == 0) {
8652 /* Ordinary expanded use of the argument.
8653 Put in newline-space markers to prevent token pasting. */
8654 xbuf[totlen++] = '\n';
8655 xbuf[totlen++] = ' ';
8658 /* Ordinary expanded use of the argument.
8659 Put in newline-space markers to prevent token pasting. */
8661 xbuf[totlen++] = '\n';
8662 xbuf[totlen++] = ' ';
8664 bcopy ((char *) arg->expanded, (char *) (xbuf + totlen),
8665 arg->expand_length);
8666 totlen += arg->expand_length;
8668 xbuf[totlen++] = '\n';
8669 xbuf[totlen++] = ' ';
8671 /* If a macro argument with newlines is used multiple times,
8672 then only expand the newlines once. This avoids creating output
8673 lines which don't correspond to any input line, which confuses
8675 if (arg->use_count > 1 && arg->newlines > 0) {
8676 /* Don't bother doing change_newlines for subsequent
8680 = change_newlines (arg->expanded, arg->expand_length);
8684 if (totlen > xbuf_len)
8688 /* If there is anything left of the definition after handling
8689 the arg list, copy that in too. */
8691 for (i = offset; i < defn->length; i++) {
8692 /* if we've reached the end of the macro */
8695 if (! (rest_zero && last_ap != NULL && last_ap->rest_args
8696 && last_ap->raw_after != 0))
8697 xbuf[totlen++] = exp[i];
8703 for (i = 0; i < nargs; i++) {
8704 if (args[i].free1 != 0)
8705 free (args[i].free1);
8706 if (args[i].free2 != 0)
8707 free (args[i].free2);
8711 xbuf = defn->expansion;
8712 xbuf_len = defn->length;
8715 /* Now put the expansion on the input stack
8716 so our caller will commence reading from it. */
8718 register FILE_BUF *ip2;
8720 ip2 = &instack[++indepth];
8723 ip2->nominal_fname = 0;
8724 ip2->nominal_fname_len = 0;
8726 /* This may not be exactly correct, but will give much better error
8727 messages for nested macro calls than using a line number of zero. */
8728 ip2->lineno = start_line;
8730 ip2->length = xbuf_len;
8732 ip2->free_ptr = (nargs > 0) ? xbuf : 0;
8734 ip2->if_stack = if_stack;
8735 ip2->system_header_p = 0;
8737 /* Recursive macro use sometimes works traditionally.
8738 #define foo(x,y) bar (x (y,0), y)
8742 hp->type = T_DISABLED;
8746 /* Parse a macro argument and store the info on it into *ARGPTR.
8747 REST_ARGS is passed to macarg1 to make it absorb the rest of the args.
8748 Return nonzero to indicate a syntax error. */
8751 macarg (argptr, rest_args)
8752 register struct argdata *argptr;
8755 FILE_BUF *ip = &instack[indepth];
8761 /* Try to parse as much of the argument as exists at this
8762 input stack level. */
8763 U_CHAR *bp = macarg1 (ip->bufp, ip->buf + ip->length, ip->macro,
8764 &paren, &newlines, &comments, rest_args);
8766 /* If we find the end of the argument at this level,
8767 set up *ARGPTR to point at it in the input stack. */
8768 if (!(ip->fname != 0 && (newlines != 0 || comments != 0))
8769 && bp != ip->buf + ip->length) {
8771 argptr->raw = ip->bufp;
8772 argptr->raw_length = bp - ip->bufp;
8773 argptr->newlines = newlines;
8777 /* This input stack level ends before the macro argument does.
8778 We must pop levels and keep parsing.
8779 Therefore, we must allocate a temporary buffer and copy
8780 the macro argument into it. */
8781 int bufsize = bp - ip->bufp;
8782 int extra = newlines;
8783 U_CHAR *buffer = (U_CHAR *) xmalloc (bufsize + extra + 1);
8784 int final_start = 0;
8786 bcopy ((char *) ip->bufp, (char *) buffer, bufsize);
8788 ip->lineno += newlines;
8790 while (bp == ip->buf + ip->length) {
8791 if (instack[indepth].macro == 0) {
8795 ip->macro->type = T_MACRO;
8797 free (ip->free_ptr);
8798 ip = &instack[--indepth];
8801 bp = macarg1 (ip->bufp, ip->buf + ip->length, ip->macro, &paren,
8802 &newlines, &comments, rest_args);
8803 final_start = bufsize;
8804 bufsize += bp - ip->bufp;
8806 buffer = (U_CHAR *) xrealloc (buffer, bufsize + extra + 1);
8807 bcopy ((char *) ip->bufp, (char *) (buffer + bufsize - (bp - ip->bufp)),
8810 ip->lineno += newlines;
8813 /* Now, if arg is actually wanted, record its raw form,
8814 discarding comments and duplicating newlines in whatever
8815 part of it did not come from a macro expansion.
8816 EXTRA space has been preallocated for duplicating the newlines.
8817 FINAL_START is the index of the start of that part. */
8819 argptr->raw = buffer;
8820 argptr->raw_length = bufsize;
8821 argptr->free1 = buffer;
8822 argptr->newlines = newlines;
8823 if ((newlines || comments) && ip->fname != 0)
8826 discard_comments (argptr->raw + final_start,
8827 argptr->raw_length - final_start,
8829 argptr->raw[argptr->raw_length] = 0;
8830 if (argptr->raw_length > bufsize + extra)
8835 /* If we are not discarding this argument,
8836 macroexpand it and compute its length as stringified.
8837 All this info goes into *ARGPTR. */
8840 register U_CHAR *buf, *lim;
8841 register int totlen;
8844 lim = buf + argptr->raw_length;
8846 while (buf != lim && is_space[*buf])
8848 while (buf != lim && is_space[lim[-1]])
8850 totlen = traditional ? 0 : 2; /* Count opening and closing quote. */
8851 while (buf != lim) {
8852 register U_CHAR c = *buf++;
8854 /* Internal sequences of whitespace are replaced by one space
8855 in most cases, but not always. So count all the whitespace
8856 in case we need to keep it all. */
8859 SKIP_ALL_WHITE_SPACE (buf);
8862 if (c == '\"' || c == '\\') /* escape these chars */
8865 argptr->stringified_length = totlen;
8870 /* Scan text from START (inclusive) up to LIMIT (exclusive),
8871 taken from the expansion of MACRO,
8872 counting parens in *DEPTHPTR,
8873 and return if reach LIMIT
8874 or before a `)' that would make *DEPTHPTR negative
8875 or before a comma when *DEPTHPTR is zero.
8876 Single and double quotes are matched and termination
8877 is inhibited within them. Comments also inhibit it.
8878 Value returned is pointer to stopping place.
8880 Increment *NEWLINES each time a newline is passed.
8881 REST_ARGS notifies macarg1 that it should absorb the rest of the args.
8882 Set *COMMENTS to 1 if a comment is seen. */
8885 macarg1 (start, limit, macro, depthptr, newlines, comments, rest_args)
8887 register U_CHAR *limit;
8888 struct hashnode *macro;
8889 int *depthptr, *newlines, *comments;
8892 register U_CHAR *bp = start;
8894 while (bp < limit) {
8900 if (--(*depthptr) < 0)
8904 /* Traditionally, backslash makes following char not special. */
8905 if (traditional && bp + 1 < limit && bp[1] != '\n')
8914 if (bp[1] == '\\' && bp[2] == '\n')
8915 newline_fix (bp + 1);
8918 for (bp += 2; bp < limit; bp++) {
8921 else if (*bp == '*') {
8922 if (bp[-1] == '/' && warn_comments)
8923 warning ("`/*' within comment");
8924 if (bp[1] == '\\' && bp[2] == '\n')
8925 newline_fix (bp + 1);
8933 #ifdef MULTIBYTE_CHARS
8935 length = local_mblen (bp, limit - bp);
8941 } else if (bp[1] == '/' && cplusplus_comments) {
8943 for (bp += 2; bp < limit; bp++) {
8948 if (*bp == '\\' && bp + 1 < limit && bp[1] == '\n')
8952 warning ("multiline `//' comment");
8957 #ifdef MULTIBYTE_CHARS
8959 length = local_mblen (bp, limit - bp);
8971 for (quotec = *bp++; bp + 1 < limit && *bp != quotec; bp++) {
8977 while (*bp == '\\' && bp[1] == '\n') {
8982 } else if (*bp == '\n') {
8989 #ifdef MULTIBYTE_CHARS
8991 length = local_mblen (bp, limit - bp);
9000 /* if we've returned to lowest level and we aren't absorbing all args */
9001 if ((*depthptr) == 0 && rest_args == 0)
9011 /* Discard comments and duplicate newlines
9012 in the string of length LENGTH at START,
9013 except inside of string constants.
9014 The string is copied into itself with its beginning staying fixed.
9016 NEWLINES is the number of newlines that must be duplicated.
9017 We assume that that much extra space is available past the end
9021 discard_comments (start, length, newlines)
9026 register U_CHAR *ibp;
9027 register U_CHAR *obp;
9028 register U_CHAR *limit;
9031 /* If we have newlines to duplicate, copy everything
9032 that many characters up. Then, in the second part,
9033 we will have room to insert the newlines
9035 NEWLINES may actually be too large, because it counts
9036 newlines in string constants, and we don't duplicate those.
9037 But that does no harm. */
9039 ibp = start + length;
9040 obp = ibp + newlines;
9042 while (limit != ibp)
9046 ibp = start + newlines;
9047 limit = start + length + newlines;
9050 while (ibp < limit) {
9051 *obp++ = c = *ibp++;
9054 /* Duplicate the newline. */
9066 if (*ibp == '\\' && ibp[1] == '\n')
9068 /* Delete any comment. */
9069 if (cplusplus_comments && ibp[0] == '/') {
9070 /* Comments are equivalent to spaces. */
9077 if (*ibp == '\\' && ibp + 1 < limit && ibp[1] == '\n')
9081 #ifdef MULTIBYTE_CHARS
9082 int length = local_mblen (ibp, limit - ibp);
9084 ibp += (length - 1);
9091 if (ibp[0] != '*' || ibp + 1 >= limit)
9093 /* Comments are equivalent to spaces.
9094 For -traditional, a comment is equivalent to nothing. */
9099 while (++ibp < limit) {
9100 if (ibp[0] == '*') {
9101 if (ibp[1] == '\\' && ibp[2] == '\n')
9102 newline_fix (ibp + 1);
9103 if (ibp[1] == '/') {
9110 #ifdef MULTIBYTE_CHARS
9111 int length = local_mblen (ibp, limit - ibp);
9113 ibp += (length - 1);
9121 /* Notice and skip strings, so that we don't
9122 think that comments start inside them,
9123 and so we don't duplicate newlines in them. */
9126 while (ibp < limit) {
9127 *obp++ = c = *ibp++;
9135 else if (c == '\\') {
9136 if (ibp < limit && *ibp == '\n') {
9140 while (*ibp == '\\' && ibp[1] == '\n')
9148 #ifdef MULTIBYTE_CHARS
9151 length = local_mblen (ibp, limit - ibp);
9155 bcopy (ibp, obp, length);
9172 /* Turn newlines to spaces in the string of length LENGTH at START,
9173 except inside of string constants.
9174 The string is copied into itself with its beginning staying fixed. */
9177 change_newlines (start, length)
9181 register U_CHAR *ibp;
9182 register U_CHAR *obp;
9183 register U_CHAR *limit;
9187 limit = start + length;
9190 while (ibp < limit) {
9191 *obp++ = c = *ibp++;
9194 /* If this is a NEWLINE NEWLINE, then this is a real newline in the
9195 string. Skip past the newline and its duplicate.
9196 Put a space in the output. */
9207 /* Notice and skip strings, so that we don't delete newlines in them. */
9210 while (ibp < limit) {
9211 *obp++ = c = *ibp++;
9214 else if (c == '\\' && ibp < limit && *ibp == '\n')
9223 #ifdef MULTIBYTE_CHARS
9226 length = local_mblen (ibp, limit - ibp);
9230 bcopy (ibp, obp, length);
9247 /* my_strerror - return the descriptive text associated with an
9251 my_strerror (errnum)
9257 #ifndef HAVE_STRERROR
9258 result = (char *) ((errnum < sys_nerr) ? sys_errlist[errnum] : 0);
9260 result = strerror (errnum);
9263 /* VAXCRTL's strerror() takes an optional second argument, which only
9264 matters when the first argument is EVMSERR. However, it's simplest
9265 just to pass it unconditionally. `vaxc$errno' is declared in
9266 <errno.h>, and maintained by the library in parallel with `errno'.
9267 We assume that caller's `errnum' either matches the last setting of
9268 `errno' by the library or else does not have the value `EVMSERR'. */
9270 result = strerror (errnum, vaxc$errno);
9274 result = "errno = ?";
9279 /* notice - output message to stderr */
9282 notice VPROTO ((const char * msgid, ...))
9284 #ifndef ANSI_PROTOTYPES
9289 VA_START (args, msgid);
9291 #ifndef ANSI_PROTOTYPES
9292 msgid = va_arg (args, const char *);
9295 vnotice (msgid, args);
9300 vnotice (msgid, args)
9304 vfprintf (stderr, _(msgid), args);
9307 /* error - print error message and increment count of errors. */
9310 error VPROTO ((const char * msgid, ...))
9312 #ifndef ANSI_PROTOTYPES
9317 VA_START (args, msgid);
9319 #ifndef ANSI_PROTOTYPES
9320 msgid = va_arg (args, const char *);
9323 verror (msgid, args);
9328 verror (msgid, args)
9333 FILE_BUF *ip = NULL;
9335 print_containing_files ();
9337 for (i = indepth; i >= 0; i--)
9338 if (instack[i].fname != NULL) {
9344 eprint_string (ip->nominal_fname, ip->nominal_fname_len);
9345 fprintf (stderr, ":%d: ", ip->lineno);
9347 vnotice (msgid, args);
9348 fprintf (stderr, "\n");
9352 /* Error including a message from `errno'. */
9355 error_from_errno (name)
9360 FILE_BUF *ip = NULL;
9362 print_containing_files ();
9364 for (i = indepth; i >= 0; i--)
9365 if (instack[i].fname != NULL) {
9371 eprint_string (ip->nominal_fname, ip->nominal_fname_len);
9372 fprintf (stderr, ":%d: ", ip->lineno);
9375 fprintf (stderr, "%s: %s\n", name, my_strerror (e));
9380 /* Print error message but don't count it. */
9383 warning VPROTO ((const char * msgid, ...))
9385 #ifndef ANSI_PROTOTYPES
9390 VA_START (args, msgid);
9392 #ifndef ANSI_PROTOTYPES
9393 msgid = va_arg (args, const char *);
9396 vwarning (msgid, args);
9401 vwarning (msgid, args)
9406 FILE_BUF *ip = NULL;
9408 if (inhibit_warnings)
9411 if (warnings_are_errors)
9414 print_containing_files ();
9416 for (i = indepth; i >= 0; i--)
9417 if (instack[i].fname != NULL) {
9423 eprint_string (ip->nominal_fname, ip->nominal_fname_len);
9424 fprintf (stderr, ":%d: ", ip->lineno);
9426 notice ("warning: ");
9427 vnotice (msgid, args);
9428 fprintf (stderr, "\n");
9432 error_with_line VPROTO ((int line, const char * msgid, ...))
9434 #ifndef ANSI_PROTOTYPES
9440 VA_START (args, msgid);
9442 #ifndef ANSI_PROTOTYPES
9443 line = va_arg (args, int);
9444 msgid = va_arg (args, const char *);
9447 verror_with_line (line, msgid, args);
9453 verror_with_line (line, msgid, args)
9459 FILE_BUF *ip = NULL;
9461 print_containing_files ();
9463 for (i = indepth; i >= 0; i--)
9464 if (instack[i].fname != NULL) {
9470 eprint_string (ip->nominal_fname, ip->nominal_fname_len);
9471 fprintf (stderr, ":%d: ", line);
9473 vnotice (msgid, args);
9474 fprintf (stderr, "\n");
9479 warning_with_line VPROTO ((int line, const char * msgid, ...))
9481 #ifndef ANSI_PROTOTYPES
9487 VA_START (args, msgid);
9489 #ifndef ANSI_PROTOTYPES
9490 line = va_arg (args, int);
9491 msgid = va_arg (args, const char *);
9494 vwarning_with_line (line, msgid, args);
9499 vwarning_with_line (line, msgid, args)
9505 FILE_BUF *ip = NULL;
9507 if (inhibit_warnings)
9510 if (warnings_are_errors)
9513 print_containing_files ();
9515 for (i = indepth; i >= 0; i--)
9516 if (instack[i].fname != NULL) {
9522 eprint_string (ip->nominal_fname, ip->nominal_fname_len);
9523 fprintf (stderr, line ? ":%d: " : ": ", line);
9525 notice ("warning: ");
9526 vnotice (msgid, args);
9527 fprintf (stderr, "\n");
9530 /* Print an error message and maybe count it. */
9533 pedwarn VPROTO ((const char * msgid, ...))
9535 #ifndef ANSI_PROTOTYPES
9540 VA_START (args, msgid);
9542 #ifndef ANSI_PROTOTYPES
9543 msgid = va_arg (args, const char *);
9546 if (pedantic_errors)
9547 verror (msgid, args);
9549 vwarning (msgid, args);
9554 pedwarn_with_line VPROTO ((int line, const char * msgid, ...))
9556 #ifndef ANSI_PROTOTYPES
9562 VA_START (args, msgid);
9564 #ifndef ANSI_PROTOTYPES
9565 line = va_arg (args, int);
9566 msgid = va_arg (args, const char *);
9569 if (pedantic_errors)
9570 verror_with_line (line, msgid, args);
9572 vwarning_with_line (line, msgid, args);
9576 /* Report a warning (or an error if pedantic_errors)
9577 giving specified file name and line number, not current. */
9580 pedwarn_with_file_and_line VPROTO ((const char *file, size_t file_len, int line,
9581 const char * msgid, ...))
9583 #ifndef ANSI_PROTOTYPES
9591 if (!pedantic_errors && inhibit_warnings)
9594 VA_START (args, msgid);
9596 #ifndef ANSI_PROTOTYPES
9597 file = va_arg (args, const char *);
9598 file_len = va_arg (args, size_t);
9599 line = va_arg (args, int);
9600 msgid = va_arg (args, const char *);
9604 eprint_string (file, file_len);
9605 fprintf (stderr, ":%d: ", line);
9607 if (pedantic_errors)
9609 if (!pedantic_errors)
9610 notice ("warning: ");
9611 vnotice (msgid, args);
9613 fprintf (stderr, "\n");
9617 pedwarn_strange_white_space (ch)
9622 case '\f': pedwarn ("formfeed in preprocessing directive"); break;
9623 case '\r': pedwarn ("carriage return in preprocessing directive"); break;
9624 case '\v': pedwarn ("vertical tab in preprocessing directive"); break;
9629 /* Print the file names and line numbers of the #include
9630 directives which led to the current file. */
9633 print_containing_files ()
9635 FILE_BUF *ip = NULL;
9639 /* If stack of files hasn't changed since we last printed
9640 this info, don't repeat it. */
9641 if (last_error_tick == input_file_stack_tick)
9644 for (i = indepth; i >= 0; i--)
9645 if (instack[i].fname != NULL) {
9650 /* Give up if we don't find a source file. */
9654 /* Find the other, outer source files. */
9655 for (i--; i >= 0; i--)
9656 if (instack[i].fname != NULL) {
9660 notice ( "In file included from ");
9662 notice (",\n from ");
9665 eprint_string (ip->nominal_fname, ip->nominal_fname_len);
9666 fprintf (stderr, ":%d", ip->lineno);
9669 fprintf (stderr, ":\n");
9671 /* Record we have printed the status as of this time. */
9672 last_error_tick = input_file_stack_tick;
9675 /* Return the line at which an error occurred.
9676 The error is not necessarily associated with the current spot
9677 in the input stack, so LINE says where. LINE will have been
9678 copied from ip->lineno for the current input level.
9679 If the current level is for a file, we return LINE.
9680 But if the current level is not for a file, LINE is meaningless.
9681 In that case, we return the lineno of the innermost file. */
9684 line_for_error (line)
9690 for (i = indepth; i >= 0; ) {
9691 if (instack[i].fname != 0)
9696 line1 = instack[i].lineno;
9704 * If OBUF doesn't have NEEDED bytes after OPTR, make it bigger.
9706 * As things stand, nothing is ever placed in the output buffer to be
9707 * removed again except when it's KNOWN to be part of an identifier,
9708 * so flushing and moving down everything left, instead of expanding,
9712 /* You might think void was cleaner for the return type,
9713 but that would get type mismatch in check_expand in strict ANSI. */
9716 grow_outbuf (obuf, needed)
9717 register FILE_BUF *obuf;
9718 register int needed;
9723 if (obuf->length - (obuf->bufp - obuf->buf) > needed)
9726 /* Make it at least twice as big as it is now. */
9728 /* Make it have at least 150% of the free space we will need. */
9729 minsize = (3 * needed) / 2 + (obuf->bufp - obuf->buf);
9730 if (minsize > obuf->length)
9731 obuf->length = minsize;
9733 if ((p = (U_CHAR *) xrealloc (obuf->buf, obuf->length)) == NULL)
9736 obuf->bufp = p + (obuf->bufp - obuf->buf);
9742 /* Symbol table for macro names and special symbols */
9745 * install a name in the main hash table, even if it is already there.
9746 * name stops with first non alphanumeric, except leading '#'.
9747 * caller must check against redefinition if that is desired.
9748 * delete_macro () removes things installed by install () in fifo order.
9749 * this is important because of the `defined' special symbol used
9750 * in #if, and also if pushdef/popdef directives are ever implemented.
9752 * If LEN is >= 0, it is the length of the name.
9753 * Otherwise, compute the length by scanning the entire name.
9755 * If HASH is >= 0, it is the precomputed hash code.
9756 * Otherwise, compute the hash code.
9760 install (name, len, type, value, hash)
9763 enum node_type type;
9767 register HASHNODE *hp;
9768 register int i, bucket;
9769 register U_CHAR *p, *q;
9773 while (is_idchar[*p])
9779 hash = hashf (name, len, HASHSIZE);
9781 i = sizeof (HASHNODE) + len + 1;
9782 hp = (HASHNODE *) xmalloc (i);
9784 hp->bucket_hdr = &hashtab[bucket];
9785 hp->next = hashtab[bucket];
9786 hashtab[bucket] = hp;
9788 if (hp->next != NULL)
9789 hp->next->prev = hp;
9792 hp->value.cpval = value;
9793 hp->name = ((U_CHAR *) hp) + sizeof (HASHNODE);
9796 for (i = 0; i < len; i++)
9803 * find the most recent hash node for name "name" (ending with first
9804 * non-identifier char) installed by install
9806 * If LEN is >= 0, it is the length of the name.
9807 * Otherwise, compute the length by scanning the entire name.
9809 * If HASH is >= 0, it is the precomputed hash code.
9810 * Otherwise, compute the hash code.
9814 lookup (name, len, hash)
9819 register U_CHAR *bp;
9820 register HASHNODE *bucket;
9823 for (bp = name; is_idchar[*bp]; bp++) ;
9828 hash = hashf (name, len, HASHSIZE);
9830 bucket = hashtab[hash];
9832 if (bucket->length == len && bcmp (bucket->name, name, len) == 0)
9834 bucket = bucket->next;
9840 * Delete a hash node. Some weirdness to free junk from macros.
9841 * More such weirdness will have to be added if you define more hash
9842 * types that need it.
9845 /* Note that the DEFINITION of a macro is removed from the hash table
9846 but its storage is not freed. This would be a storage leak
9847 except that it is not reasonable to keep undefining and redefining
9848 large numbers of macros many times.
9849 In any case, this is necessary, because a macro can be #undef'd
9850 in the middle of reading the arguments to a call to it.
9851 If #undef freed the DEFINITION, that would crash. */
9858 if (hp->prev != NULL)
9859 hp->prev->next = hp->next;
9860 if (hp->next != NULL)
9861 hp->next->prev = hp->prev;
9863 /* Make sure that the bucket chain header that the deleted guy was
9864 on points to the right thing afterwards. */
9865 if (hp == *hp->bucket_hdr)
9866 *hp->bucket_hdr = hp->next;
9869 if (hp->type == T_MACRO) {
9870 DEFINITION *d = hp->value.defn;
9871 struct reflist *ap, *nextap;
9873 for (ap = d->pattern; ap != NULL; ap = nextap) {
9884 * return hash function on name. must be compatible with the one
9885 * computed a step at a time, elsewhere
9889 hashf (name, len, hashsize)
9890 register U_CHAR *name;
9897 r = HASHSTEP (r, *name++);
9899 return MAKE_POS (r) % hashsize;
9903 /* Dump the definition of a single macro HP to OF. */
9906 dump_single_macro (hp, of)
9907 register HASHNODE *hp;
9910 register DEFINITION *defn = hp->value.defn;
9916 /* Print the definition of the macro HP. */
9918 fprintf (of, "#define %s", hp->name);
9920 if (defn->nargs >= 0) {
9924 for (i = 0; i < defn->nargs; i++) {
9925 dump_arg_n (defn, i, of);
9926 if (i + 1 < defn->nargs)
9936 for (ap = defn->pattern; ap != NULL; ap = ap->next) {
9937 dump_defn_1 (defn->expansion, offset, ap->nchars, of);
9938 offset += ap->nchars;
9940 if (ap->nchars != 0)
9942 if (ap->stringify) {
9943 switch (ap->stringify) {
9944 case SHARP_TOKEN: fprintf (of, "#"); break;
9945 case WHITE_SHARP_TOKEN: fprintf (of, "# "); break;
9946 case PERCENT_COLON_TOKEN: fprintf (of, "%%:"); break;
9947 case WHITE_PERCENT_COLON_TOKEN: fprintf (of, "%%: "); break;
9951 if (ap->raw_before != 0) {
9953 switch (ap->raw_before) {
9954 case WHITE_SHARP_TOKEN:
9955 case WHITE_PERCENT_COLON_TOKEN:
9962 switch (ap->raw_before) {
9963 case SHARP_TOKEN: fprintf (of, "##"); break;
9964 case WHITE_SHARP_TOKEN: fprintf (of, "## "); break;
9965 case PERCENT_COLON_TOKEN: fprintf (of, "%%:%%:"); break;
9966 case WHITE_PERCENT_COLON_TOKEN: fprintf (of, "%%:%%: "); break;
9973 dump_arg_n (defn, ap->argno, of);
9974 if (!traditional && ap->raw_after != 0) {
9975 switch (ap->raw_after) {
9976 case SHARP_TOKEN: fprintf (of, "##"); break;
9977 case WHITE_SHARP_TOKEN: fprintf (of, " ##"); break;
9978 case PERCENT_COLON_TOKEN: fprintf (of, "%%:%%:"); break;
9979 case WHITE_PERCENT_COLON_TOKEN: fprintf (of, " %%:%%:"); break;
9985 dump_defn_1 (defn->expansion, offset, defn->length - offset, of);
9989 /* Dump all macro definitions as #defines to stdout. */
9996 for (bucket = 0; bucket < HASHSIZE; bucket++) {
9997 register HASHNODE *hp;
9999 for (hp = hashtab[bucket]; hp; hp= hp->next) {
10000 if (hp->type == T_MACRO)
10001 dump_single_macro (hp, stdout);
10006 /* Output to OF a substring of a macro definition.
10007 BASE is the beginning of the definition.
10008 Output characters START thru LENGTH.
10009 Unless traditional, discard newlines outside of strings, thus
10010 converting funny-space markers to ordinary spaces. */
10013 dump_defn_1 (base, start, length, of)
10019 U_CHAR *p = base + start;
10020 U_CHAR *limit = base + start + length;
10023 fwrite (p, sizeof (*p), length, of);
10025 while (p < limit) {
10026 if (*p == '\"' || *p =='\'') {
10027 U_CHAR *p1 = skip_quoted_string (p, limit, 0, NULL_PTR,
10028 NULL_PTR, NULL_PTR);
10029 fwrite (p, sizeof (*p), p1 - p, of);
10040 /* Print the name of argument number ARGNUM of macro definition DEFN
10042 Recall that DEFN->args.argnames contains all the arg names
10043 concatenated in reverse order with comma-space in between. */
10046 dump_arg_n (defn, argnum, of)
10051 register U_CHAR *p = defn->args.argnames;
10052 while (argnum + 1 < defn->nargs) {
10053 p = (U_CHAR *) index ((char *) p, ' ') + 1;
10057 while (*p && *p != ',') {
10063 /* Initialize syntactic classifications of characters. */
10066 initialize_char_syntax ()
10071 * Set up is_idchar and is_idstart tables. These should be
10072 * faster than saying (is_alpha (c) || c == '_'), etc.
10073 * Set up these things before calling any routines tthat
10076 for (i = 'a'; i <= 'z'; i++) {
10077 is_idchar[i - 'a' + 'A'] = 1;
10079 is_idstart[i - 'a' + 'A'] = 1;
10082 for (i = '0'; i <= '9'; i++)
10084 is_idchar['_'] = 1;
10085 is_idstart['_'] = 1;
10086 is_idchar['$'] = 1;
10087 is_idstart['$'] = 1;
10089 /* horizontal space table */
10090 is_hor_space[' '] = 1;
10091 is_hor_space['\t'] = 1;
10092 is_hor_space['\v'] = 1;
10093 is_hor_space['\f'] = 1;
10094 is_hor_space['\r'] = 1;
10097 is_space['\t'] = 1;
10098 is_space['\v'] = 1;
10099 is_space['\f'] = 1;
10100 is_space['\n'] = 1;
10101 is_space['\r'] = 1;
10104 /* Initialize the built-in macros. */
10107 initialize_builtins (inp, outp)
10111 install ((U_CHAR *) "__LINE__", -1, T_SPECLINE, NULL_PTR, -1);
10112 install ((U_CHAR *) "__DATE__", -1, T_DATE, NULL_PTR, -1);
10113 install ((U_CHAR *) "__FILE__", -1, T_FILE, NULL_PTR, -1);
10114 install ((U_CHAR *) "__BASE_FILE__", -1, T_BASE_FILE, NULL_PTR, -1);
10115 install ((U_CHAR *) "__INCLUDE_LEVEL__", -1, T_INCLUDE_LEVEL, NULL_PTR, -1);
10116 install ((U_CHAR *) "__VERSION__", -1, T_VERSION, NULL_PTR, -1);
10117 #ifndef NO_BUILTIN_SIZE_TYPE
10118 install ((U_CHAR *) "__SIZE_TYPE__", -1, T_SIZE_TYPE, NULL_PTR, -1);
10120 #ifndef NO_BUILTIN_PTRDIFF_TYPE
10121 install ((U_CHAR *) "__PTRDIFF_TYPE__ ", -1, T_PTRDIFF_TYPE, NULL_PTR, -1);
10123 install ((U_CHAR *) "__WCHAR_TYPE__", -1, T_WCHAR_TYPE, NULL_PTR, -1);
10124 install ((U_CHAR *) "__USER_LABEL_PREFIX__", -1, T_USER_LABEL_PREFIX_TYPE,
10126 install ((U_CHAR *) "__REGISTER_PREFIX__", -1, T_REGISTER_PREFIX_TYPE,
10128 install ((U_CHAR *) "__IMMEDIATE_PREFIX__", -1, T_IMMEDIATE_PREFIX_TYPE,
10130 install ((U_CHAR *) "__TIME__", -1, T_TIME, NULL_PTR, -1);
10131 if (!traditional) {
10132 install ((U_CHAR *) "__STDC__", -1, T_CONST, "1", -1);
10133 install ((U_CHAR *) "__STDC_VERSION__", -1, T_CONST, "199409L", -1);
10135 /* This is supplied using a -D by the compiler driver
10136 so that it is present only when truly compiling with GNU C. */
10137 /* install ((U_CHAR *) "__GNUC__", -1, T_CONST, "2", -1); */
10138 install ((U_CHAR *) "__HAVE_BUILTIN_SETJMP__", -1, T_CONST, "1", -1);
10142 char directive[2048];
10143 U_CHAR *udirective = (U_CHAR *) directive;
10144 register struct directive *dp = &directive_table[0];
10145 struct tm *timebuf = timestamp ();
10147 sprintf (directive, " __BASE_FILE__ \"%s\"\n",
10148 instack[0].nominal_fname);
10149 output_line_directive (inp, outp, 0, same_file);
10150 pass_thru_directive (udirective, &udirective[strlen (directive)],
10153 sprintf (directive, " __VERSION__ \"%s\"\n", version_string);
10154 output_line_directive (inp, outp, 0, same_file);
10155 pass_thru_directive (udirective, &udirective[strlen (directive)],
10158 #ifndef NO_BUILTIN_SIZE_TYPE
10159 sprintf (directive, " __SIZE_TYPE__ %s\n", SIZE_TYPE);
10160 output_line_directive (inp, outp, 0, same_file);
10161 pass_thru_directive (udirective, &udirective[strlen (directive)],
10165 #ifndef NO_BUILTIN_PTRDIFF_TYPE
10166 sprintf (directive, " __PTRDIFF_TYPE__ %s\n", PTRDIFF_TYPE);
10167 output_line_directive (inp, outp, 0, same_file);
10168 pass_thru_directive (udirective, &udirective[strlen (directive)],
10172 sprintf (directive, " __WCHAR_TYPE__ %s\n", wchar_type);
10173 output_line_directive (inp, outp, 0, same_file);
10174 pass_thru_directive (udirective, &udirective[strlen (directive)],
10177 sprintf (directive, " __DATE__ \"%s %2d %4d\"\n",
10178 monthnames[timebuf->tm_mon],
10179 timebuf->tm_mday, timebuf->tm_year + 1900);
10180 output_line_directive (inp, outp, 0, same_file);
10181 pass_thru_directive (udirective, &udirective[strlen (directive)],
10184 sprintf (directive, " __TIME__ \"%02d:%02d:%02d\"\n",
10185 timebuf->tm_hour, timebuf->tm_min, timebuf->tm_sec);
10186 output_line_directive (inp, outp, 0, same_file);
10187 pass_thru_directive (udirective, &udirective[strlen (directive)],
10192 sprintf (directive, " __STDC__ 1");
10193 output_line_directive (inp, outp, 0, same_file);
10194 pass_thru_directive (udirective, &udirective[strlen (directive)],
10199 sprintf (directive, " __OBJC__ 1");
10200 output_line_directive (inp, outp, 0, same_file);
10201 pass_thru_directive (udirective, &udirective[strlen (directive)],
10208 * process a given definition string, for initialization
10209 * If STR is just an identifier, define it with value 1.
10210 * If STR has anything after the identifier, then it should
10211 * be identifier=definition.
10215 make_definition (str)
10219 struct directive *kt;
10222 p = buf = (U_CHAR *) str;
10223 if (!is_idstart[*p]) {
10224 error ("malformed option `-D %s'", str);
10227 while (is_idchar[*++p])
10230 while (is_idchar[*++p] || *p == ',' || is_hor_space[*p])
10233 p = (U_CHAR *) str; /* Error */
10236 buf = (U_CHAR *) alloca (p - buf + 4);
10237 strcpy ((char *)buf, str);
10238 strcat ((char *)buf, " 1");
10239 } else if (*p != '=') {
10240 error ("malformed option `-D %s'", str);
10244 /* Copy the entire option so we can modify it. */
10245 buf = (U_CHAR *) alloca (2 * strlen (str) + 1);
10246 strncpy ((char *) buf, str, p - (U_CHAR *) str);
10247 /* Change the = to a space. */
10248 buf[p - (U_CHAR *) str] = ' ';
10249 /* Scan for any backslash-newline and remove it. */
10251 q = &buf[p - (U_CHAR *) str];
10253 if (*p == '\"' || *p == '\'') {
10254 int unterminated = 0;
10255 U_CHAR *p1 = skip_quoted_string (p, p + strlen ((char *) p), 0,
10256 NULL_PTR, NULL_PTR, &unterminated);
10261 } else if (*p == '\\' && p[1] == '\n')
10263 /* Change newline chars into newline-markers. */
10264 else if (*p == '\n')
10276 ip = &instack[++indepth];
10277 ip->nominal_fname = ip->fname = "*Initialization*";
10278 ip->nominal_fname_len = strlen (ip->nominal_fname);
10280 ip->buf = ip->bufp = buf;
10281 ip->length = strlen ((char *) buf);
10285 ip->if_stack = if_stack;
10286 ip->system_header_p = 0;
10288 for (kt = directive_table; kt->type != T_DEFINE; kt++)
10291 /* Pass NULL instead of OP, since this is a "predefined" macro. */
10292 do_define (buf, buf + strlen ((char *) buf), NULL_PTR, kt);
10296 /* JF, this does the work for the -U option */
10299 make_undef (str, op)
10304 struct directive *kt;
10306 ip = &instack[++indepth];
10307 ip->nominal_fname = ip->fname = "*undef*";
10308 ip->nominal_fname_len = strlen (ip->nominal_fname);
10310 ip->buf = ip->bufp = (U_CHAR *) str;
10311 ip->length = strlen (str);
10315 ip->if_stack = if_stack;
10316 ip->system_header_p = 0;
10318 for (kt = directive_table; kt->type != T_UNDEF; kt++)
10321 do_undef ((U_CHAR *) str, (U_CHAR *) str + strlen (str), op, kt);
10325 /* Process the string STR as if it appeared as the body of a #assert.
10326 OPTION is the option name for which STR was the argument. */
10329 make_assertion (option, str)
10330 const char *option;
10334 struct directive *kt;
10335 U_CHAR *buf, *p, *q;
10337 /* Copy the entire option so we can modify it. */
10338 buf = (U_CHAR *) alloca (strlen (str) + 1);
10339 strcpy ((char *) buf, str);
10340 /* Scan for any backslash-newline and remove it. */
10343 if (*p == '\\' && p[1] == '\n')
10351 if (!is_idstart[*p]) {
10352 error ("malformed option `%s %s'", option, str);
10355 while (is_idchar[*++p])
10357 SKIP_WHITE_SPACE (p);
10358 if (! (*p == 0 || *p == '(')) {
10359 error ("malformed option `%s %s'", option, str);
10363 ip = &instack[++indepth];
10364 ip->nominal_fname = ip->fname = "*Initialization*";
10365 ip->nominal_fname_len = strlen (ip->nominal_fname);
10367 ip->buf = ip->bufp = buf;
10368 ip->length = strlen ((char *) buf);
10372 ip->if_stack = if_stack;
10373 ip->system_header_p = 0;
10375 for (kt = directive_table; kt->type != T_ASSERT; kt++)
10378 /* Pass NULL as output ptr to do_define since we KNOW it never does
10380 do_assert (buf, buf + strlen ((char *) buf) , NULL_PTR, kt);
10384 /* The previous include prefix, if any, is PREV_FILE_NAME.
10385 Translate any pathnames with COMPONENT.
10386 Allocate a new include prefix whose name is the
10387 simplified concatenation of PREFIX and NAME,
10388 with a trailing / added if needed.
10389 But return 0 if the include prefix should be ignored,
10390 e.g. because it is a duplicate of PREV_FILE_NAME. */
10392 static struct file_name_list *
10393 new_include_prefix (prev_file_name, component, prefix, name)
10394 struct file_name_list *prev_file_name;
10395 const char *component;
10396 const char *prefix;
10400 fatal ("Directory name missing after command line option");
10403 /* Ignore the empty string. */
10406 prefix = update_path (prefix, component);
10407 name = update_path (name, component);
10410 struct file_name_list *dir
10411 = ((struct file_name_list *)
10412 xmalloc (sizeof (struct file_name_list)
10413 + strlen (prefix) + strlen (name) + 2));
10415 strcpy (dir->fname, prefix);
10416 strcat (dir->fname, name);
10417 len = simplify_filename (dir->fname);
10419 /* Convert directory name to a prefix. */
10420 if (len && dir->fname[len - 1] != DIR_SEPARATOR) {
10421 if (len == 1 && dir->fname[len - 1] == '.')
10425 /* must be '/', hack_vms_include_specification triggers on it. */
10426 dir->fname[len++] = '/';
10428 dir->fname[len++] = DIR_SEPARATOR;
10430 dir->fname[len] = 0;
10433 /* Ignore a directory whose name matches the previous one. */
10434 if (prev_file_name && !strcmp (prev_file_name->fname, dir->fname)) {
10435 /* But treat `-Idir -I- -Idir' as `-I- -Idir'. */
10436 if (!first_bracket_include)
10437 first_bracket_include = prev_file_name;
10443 /* VMS can't stat dir prefixes, so skip these optimizations in VMS. */
10445 /* Add a trailing "." if there is a filename. This increases the number
10446 of systems that can stat directories. We remove it below. */
10449 dir->fname[len] = '.';
10450 dir->fname[len + 1] = 0;
10453 /* Ignore a nonexistent directory. */
10454 if (stat (len ? dir->fname : ".", &dir->st) != 0) {
10455 if (errno != ENOENT && errno != ENOTDIR)
10456 error_from_errno (dir->fname);
10462 dir->fname[len] = 0;
10464 /* Ignore a directory whose identity matches the previous one. */
10466 && INO_T_EQ (prev_file_name->st.st_ino, dir->st.st_ino)
10467 && prev_file_name->st.st_dev == dir->st.st_dev) {
10468 /* But treat `-Idir -I- -Idir' as `-I- -Idir'. */
10469 if (!first_bracket_include)
10470 first_bracket_include = prev_file_name;
10477 dir->c_system_include_path = 0;
10478 dir->got_name_map = 0;
10484 /* Append a chain of `struct file_name_list's
10485 to the end of the main include chain.
10486 FIRST is the beginning of the chain to append, and LAST is the end. */
10489 append_include_chain (first, last)
10490 struct file_name_list *first, *last;
10492 struct file_name_list *dir;
10494 if (!first || !last)
10500 last_include->next = first;
10502 if (first_bracket_include == 0)
10503 first_bracket_include = first;
10505 for (dir = first; ; dir = dir->next) {
10506 int len = strlen (dir->fname) + INCLUDE_LEN_FUDGE;
10507 if (len > max_include_len)
10508 max_include_len = len;
10514 last_include = last;
10517 /* Place into DST a representation of the file named SRC that is suitable
10518 for `make'. Do not null-terminate DST. Return its length. */
10520 quote_string_for_make (dst, src)
10524 const char *p = src;
10535 /* GNU make uses a weird quoting scheme for white space.
10536 A space or tab preceded by 2N+1 backslashes represents
10537 N backslashes followed by space; a space or tab
10538 preceded by 2N backslashes represents N backslashes at
10539 the end of a file name; and backslashes in other
10540 contexts should not be doubled. */
10542 for (q = p - 1; src < q && q[-1] == '\\'; q--)
10554 goto ordinary_char;
10560 /* Fall through. This can mishandle things like "$(" but
10561 there's no easy fix. */
10564 /* This can mishandle characters in the string "\0\n%*?[\\~";
10565 exactly which chars are mishandled depends on the `make' version.
10566 We know of no portable solution for this;
10567 even GNU make 3.76.1 doesn't solve the problem entirely.
10568 (Also, '\0' is mishandled due to our calling conventions.) */
10578 /* Add output to `deps_buffer' for the -M switch.
10579 STRING points to the text to be output.
10580 SPACER is ':' for targets, ' ' for dependencies. */
10583 deps_output (string, spacer)
10584 const char *string;
10587 int size = quote_string_for_make ((char *) 0, string);
10592 #ifndef MAX_OUTPUT_COLUMNS
10593 #define MAX_OUTPUT_COLUMNS 72
10595 if (MAX_OUTPUT_COLUMNS - 1 /*spacer*/ - 2 /*` \'*/ < deps_column + size
10596 && 1 < deps_column) {
10597 bcopy (" \\\n ", &deps_buffer[deps_size], 4);
10604 if (deps_size + 2 * size + 8 > deps_allocated_size) {
10605 deps_allocated_size = (deps_size + 2 * size + 50) * 2;
10606 deps_buffer = xrealloc (deps_buffer, deps_allocated_size);
10608 if (spacer == ' ') {
10609 deps_buffer[deps_size++] = ' ';
10612 quote_string_for_make (&deps_buffer[deps_size], string);
10614 deps_column += size;
10615 if (spacer == ':') {
10616 deps_buffer[deps_size++] = ':';
10619 deps_buffer[deps_size] = 0;
10623 fatal VPROTO ((const char * msgid, ...))
10625 #ifndef ANSI_PROTOTYPES
10626 const char * msgid;
10630 fprintf (stderr, "%s: ", progname);
10631 VA_START (args, msgid);
10633 #ifndef ANSI_PROTOTYPES
10634 msgid = va_arg (args, const char *);
10636 vnotice (msgid, args);
10638 fprintf (stderr, "\n");
10639 exit (FATAL_EXIT_CODE);
10642 /* More 'friendly' abort that prints the line and file.
10643 config.h can #define abort fancy_abort if you like that sort of thing. */
10648 fatal ("Internal gcc abort.");
10652 perror_with_name (name)
10655 fprintf (stderr, "%s: %s: %s\n", progname, name, my_strerror (errno));
10660 pfatal_with_name (name)
10663 perror_with_name (name);
10667 exit (FATAL_EXIT_CODE);
10671 /* Handler for SIGPIPE. */
10674 pipe_closed (signo)
10675 /* If this is missing, some compilers complain. */
10676 int signo ATTRIBUTE_UNUSED;
10678 fatal ("output pipe has been closed");
10684 fatal ("Memory exhausted.");
10691 register PTR ptr = (PTR) malloc (size);
10698 xrealloc (old, size)
10704 ptr = (PTR) realloc (old, size);
10706 ptr = (PTR) malloc (size);
10713 xcalloc (number, size)
10714 size_t number, size;
10716 register size_t total = number * size;
10717 register PTR ptr = (PTR) malloc (total);
10720 bzero (ptr, total);
10728 register size_t len = strlen (input) + 1;
10729 register char *output = xmalloc (len);
10730 memcpy (output, input, len);
10736 /* Under VMS we need to fix up the "include" specification filename.
10738 Rules for possible conversions
10740 fullname tried paths
10743 ./dir/name [.dir]name
10745 /name [000000]name, name
10746 dir/name dir:[000000]name, dir:name, dir/name
10747 dir1/dir2/name dir1:[dir2]name, dir1:[000000.dir2]name
10748 path:/name path:[000000]name, path:name
10749 path:/dir/name path:[000000.dir]name, path:[dir]name
10750 path:dir/name path:[dir]name
10751 [path]:[dir]name [path.dir]name
10752 path/[dir]name [path.dir]name
10754 The path:/name input is constructed when expanding <> includes.
10756 return 1 if name was changed, 0 else. */
10759 hack_vms_include_specification (fullname, vaxc_include)
10763 register char *basename, *unixname, *local_ptr, *first_slash;
10764 int f, check_filename_before_returning, must_revert;
10767 check_filename_before_returning = 0;
10769 /* See if we can find a 1st slash. If not, there's no path information. */
10770 first_slash = index (fullname, '/');
10771 if (first_slash == 0)
10772 return 0; /* Nothing to do!!! */
10774 /* construct device spec if none given. */
10776 if (index (fullname, ':') == 0)
10779 /* If fullname has a slash, take it as device spec. */
10781 if (first_slash == fullname)
10783 first_slash = index (fullname+1, '/'); /* 2nd slash ? */
10785 *first_slash = ':'; /* make device spec */
10786 for (basename = fullname; *basename != 0; basename++)
10787 *basename = *(basename+1); /* remove leading slash */
10789 else if ((first_slash[-1] != '.') /* keep ':/', './' */
10790 && (first_slash[-1] != ':')
10791 && (first_slash[-1] != ']')) /* or a vms path */
10793 *first_slash = ':';
10795 else if ((first_slash[1] == '[') /* skip './' in './[dir' */
10796 && (first_slash[-1] == '.'))
10800 /* Get part after first ':' (basename[-1] == ':')
10801 or last '/' (basename[-1] == '/'). */
10803 basename = base_name (fullname);
10806 * Check if we have a vax-c style '#include filename'
10807 * and add the missing .h
10810 if (vaxc_include && !index (basename,'.'))
10811 strcat (basename, ".h");
10813 local_ptr = Local; /* initialize */
10815 /* We are trying to do a number of things here. First of all, we are
10816 trying to hammer the filenames into a standard format, such that later
10817 processing can handle them.
10819 If the file name contains something like [dir.], then it recognizes this
10820 as a root, and strips the ".]". Later processing will add whatever is
10821 needed to get things working properly.
10823 If no device is specified, then the first directory name is taken to be
10824 a device name (or a rooted logical). */
10826 /* Point to the UNIX filename part (which needs to be fixed!)
10827 but skip vms path information.
10828 [basename != fullname since first_slash != 0]. */
10830 if ((basename[-1] == ':') /* vms path spec. */
10831 || (basename[-1] == ']')
10832 || (basename[-1] == '>'))
10833 unixname = basename;
10835 unixname = fullname;
10837 if (*unixname == '/')
10840 /* If the directory spec is not rooted, we can just copy
10841 the UNIX filename part and we are done. */
10843 if (((basename - fullname) > 1)
10844 && ( (basename[-1] == ']')
10845 || (basename[-1] == '>')))
10847 if (basename[-2] != '.')
10850 /* The VMS part ends in a `]', and the preceding character is not a `.'.
10851 -> PATH]:/name (basename = '/name', unixname = 'name')
10852 We strip the `]', and then splice the two parts of the name in the
10853 usual way. Given the default locations for include files in cccp.c,
10854 we will only use this code if the user specifies alternate locations
10855 with the /include (-I) switch on the command line. */
10857 basename -= 1; /* Strip "]" */
10858 unixname--; /* backspace */
10863 /* The VMS part has a ".]" at the end, and this will not do. Later
10864 processing will add a second directory spec, and this would be a syntax
10865 error. Thus we strip the ".]", and thus merge the directory specs.
10866 We also backspace unixname, so that it points to a '/'. This inhibits the
10867 generation of the 000000 root directory spec (which does not belong here
10870 basename -= 2; /* Strip ".]" */
10871 unixname--; /* backspace */
10879 /* We drop in here if there is no VMS style directory specification yet.
10880 If there is no device specification either, we make the first dir a
10881 device and try that. If we do not do this, then we will be essentially
10882 searching the users default directory (as if they did a #include "asdf.h").
10884 Then all we need to do is to push a '[' into the output string. Later
10885 processing will fill this in, and close the bracket. */
10887 if ((unixname != fullname) /* vms path spec found. */
10888 && (basename[-1] != ':'))
10889 *local_ptr++ = ':'; /* dev not in spec. take first dir */
10891 *local_ptr++ = '['; /* Open the directory specification */
10894 if (unixname == fullname) /* no vms dir spec. */
10897 if ((first_slash != 0) /* unix dir spec. */
10898 && (*unixname != '/') /* not beginning with '/' */
10899 && (*unixname != '.')) /* or './' or '../' */
10900 *local_ptr++ = '.'; /* dir is local ! */
10903 /* at this point we assume that we have the device spec, and (at least
10904 the opening "[" for a directory specification. We may have directories
10907 If there are no other slashes then the filename will be
10908 in the "root" directory. Otherwise, we need to add
10909 directory specifications. */
10911 if (index (unixname, '/') == 0)
10913 /* if no directories specified yet and none are following. */
10914 if (local_ptr[-1] == '[')
10916 /* Just add "000000]" as the directory string */
10917 strcpy (local_ptr, "000000]");
10918 local_ptr += strlen (local_ptr);
10919 check_filename_before_returning = 1; /* we might need to fool with this later */
10925 /* As long as there are still subdirectories to add, do them. */
10926 while (index (unixname, '/') != 0)
10928 /* If this token is "." we can ignore it
10929 if it's not at the beginning of a path. */
10930 if ((unixname[0] == '.') && (unixname[1] == '/'))
10932 /* remove it at beginning of path. */
10933 if ( ((unixname == fullname) /* no device spec */
10934 && (fullname+2 != basename)) /* starts with ./ */
10936 || ((basename[-1] == ':') /* device spec */
10937 && (unixname-1 == basename))) /* and ./ afterwards */
10938 *local_ptr++ = '.'; /* make '[.' start of path. */
10943 /* Add a subdirectory spec. Do not duplicate "." */
10944 if ( local_ptr[-1] != '.'
10945 && local_ptr[-1] != '['
10946 && local_ptr[-1] != '<')
10947 *local_ptr++ = '.';
10949 /* If this is ".." then the spec becomes "-" */
10950 if ( (unixname[0] == '.')
10951 && (unixname[1] == '.')
10952 && (unixname[2] == '/'))
10954 /* Add "-" and skip the ".." */
10955 if ((local_ptr[-1] == '.')
10956 && (local_ptr[-2] == '['))
10957 local_ptr--; /* prevent [.- */
10958 *local_ptr++ = '-';
10963 /* Copy the subdirectory */
10964 while (*unixname != '/')
10965 *local_ptr++= *unixname++;
10967 unixname++; /* Skip the "/" */
10970 /* Close the directory specification */
10971 if (local_ptr[-1] == '.') /* no trailing periods */
10974 if (local_ptr[-1] == '[') /* no dir needed */
10977 *local_ptr++ = ']';
10980 /* Now add the filename. */
10983 *local_ptr++ = *unixname++;
10986 /* Now append it to the original VMS spec. */
10988 strcpy ((must_revert==1)?fullname:basename, Local);
10990 /* If we put a [000000] in the filename, try to open it first. If this fails,
10991 remove the [000000], and return that name. This provides flexibility
10992 to the user in that they can use both rooted and non-rooted logical names
10993 to point to the location of the file. */
10995 if (check_filename_before_returning)
10997 f = open (fullname, O_RDONLY, 0666);
11000 /* The file name is OK as it is, so return it as is. */
11005 /* The filename did not work. Try to remove the [000000] from the name,
11008 basename = index (fullname, '[');
11009 local_ptr = index (fullname, ']') + 1;
11010 strcpy (basename, local_ptr); /* this gets rid of it */
11020 /* The following wrapper functions supply additional arguments to the VMS
11021 I/O routines to optimize performance with file handling. The arguments
11023 "mbc=16" - Set multi-block count to 16 (use a 8192 byte buffer).
11024 "deq=64" - When extending the file, extend it in chunks of 32Kbytes.
11025 "fop=tef"- Truncate unused portions of file when closing file.
11026 "shr=nil"- Disallow file sharing while file is open. */
11029 VMS_freopen (fname, type, oldfile)
11034 #undef freopen /* Get back the real freopen routine. */
11035 if (strcmp (type, "w") == 0)
11036 return freopen (fname, type, oldfile,
11037 "mbc=16", "deq=64", "fop=tef", "shr=nil");
11038 return freopen (fname, type, oldfile, "mbc=16");
11042 VMS_fopen (fname, type)
11046 #undef fopen /* Get back the real fopen routine. */
11047 /* The gcc-vms-1.42 distribution's header files prototype fopen with two
11048 fixed arguments, which matches ANSI's specification but not VAXCRTL's
11049 pre-ANSI implementation. This hack circumvents the mismatch problem. */
11050 FILE *(*vmslib_fopen)() = (FILE *(*)()) fopen;
11053 return (*vmslib_fopen) (fname, type, "mbc=32",
11054 "deq=64", "fop=tef", "shr=nil");
11056 return (*vmslib_fopen) (fname, type, "mbc=32");
11060 VMS_open (fname, flags, prot)
11065 #undef open /* Get back the real open routine. */
11066 return open (fname, flags, prot, "mbc=16", "deq=64", "fop=tef");
11069 /* more VMS hackery */
11073 extern unsigned long SYS$PARSE(), SYS$SEARCH();
11075 /* Work around another library bug. If a file is located via a searchlist,
11076 and if the device it's on is not the same device as the one specified
11077 in the first element of that searchlist, then both stat() and fstat()
11078 will fail to return info about it. `errno' will be set to EVMSERR, and
11079 `vaxc$errno' will be set to SS$_NORMAL due yet another bug in stat()!
11080 We can get around this by fully parsing the filename and then passing
11081 that absolute name to stat().
11083 Without this fix, we can end up failing to find header files, which is
11084 bad enough, but then compounding the problem by reporting the reason for
11085 failure as "normal successful completion." */
11087 #undef fstat /* Get back to the library version. */
11090 VMS_fstat (fd, statbuf)
11092 struct stat *statbuf;
11094 int result = fstat (fd, statbuf);
11099 char nambuf[NAM$C_MAXRSS+1];
11101 if ((fp = fdopen (fd, "r")) != 0 && fgetname (fp, nambuf) != 0)
11102 result = VMS_stat (nambuf, statbuf);
11103 /* No fclose(fp) here; that would close(fd) as well. */
11110 VMS_stat (name, statbuf)
11112 struct stat *statbuf;
11114 int result = stat (name, statbuf);
11120 char exp_nam[NAM$C_MAXRSS+1], /* expanded name buffer for SYS$PARSE */
11121 res_nam[NAM$C_MAXRSS+1]; /* resultant name buffer for SYS$SEARCH */
11124 fab.fab$l_fna = (char *) name;
11125 fab.fab$b_fns = (unsigned char) strlen (name);
11126 fab.fab$l_nam = (void *) &nam;
11128 nam.nam$l_esa = exp_nam, nam.nam$b_ess = sizeof exp_nam - 1;
11129 nam.nam$l_rsa = res_nam, nam.nam$b_rss = sizeof res_nam - 1;
11130 nam.nam$b_nop = NAM$M_PWD | NAM$M_NOCONCEAL;
11131 if (SYS$PARSE (&fab) & 1)
11133 if (SYS$SEARCH (&fab) & 1)
11135 res_nam[nam.nam$b_rsl] = '\0';
11136 result = stat (res_nam, statbuf);
11138 /* Clean up searchlist context cached by the system. */
11139 nam.nam$b_nop = NAM$M_SYNCHK;
11140 fab.fab$l_fna = 0, fab.fab$b_fns = 0;
11141 (void) SYS$PARSE (&fab);