]> git.ipfire.org Git - thirdparty/gcc.git/blob - gcc/cccp.c
system.h (CTYPE_CONV, [...]): New macros.
[thirdparty/gcc.git] / gcc / cccp.c
1 /* C Compatible Compiler Preprocessor (CCCP)
2 Copyright (C) 1986, 87, 89, 92-98, 1999 Free Software Foundation, Inc.
3 Written by Paul Rubin, June 1986
4 Adapted to ANSI C, Richard Stallman, Jan 1987
5
6 This program is free software; you can redistribute it and/or modify it
7 under the terms of the GNU General Public License as published by the
8 Free Software Foundation; either version 2, or (at your option) any
9 later version.
10
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with this program; if not, write to the Free Software
18 Foundation, 59 Temple Place - Suite 330,
19 Boston, MA 02111-1307, USA. */
20
21 #include "config.h"
22
23 #include "system.h"
24 #include <signal.h>
25
26 #ifdef HAVE_SYS_RESOURCE_H
27 # include <sys/resource.h>
28 #endif
29
30 typedef unsigned char U_CHAR;
31
32 #include "pcp.h"
33 #include "intl.h"
34 #include "prefix.h"
35
36 #ifdef MULTIBYTE_CHARS
37 #include "mbchar.h"
38 #include <locale.h>
39 #endif /* MULTIBYTE_CHARS */
40
41 #ifndef GET_ENV_PATH_LIST
42 #define GET_ENV_PATH_LIST(VAR,NAME) do { (VAR) = getenv (NAME); } while (0)
43 #endif
44
45 #ifndef STANDARD_INCLUDE_DIR
46 # define STANDARD_INCLUDE_DIR "/usr/include"
47 #endif
48
49 /* By default, colon separates directories in a path. */
50 #ifndef PATH_SEPARATOR
51 # define PATH_SEPARATOR ':'
52 #endif
53
54 /* By default, a slash separates directory names. */
55 #ifndef DIR_SEPARATOR
56 # define DIR_SEPARATOR '/'
57 #endif
58
59 /* By default, the suffix for object files is ".o". */
60 #ifdef OBJECT_SUFFIX
61 # define HAVE_OBJECT_SUFFIX
62 #else
63 # define OBJECT_SUFFIX ".o"
64 #endif
65
66 /* VMS-specific definitions */
67 #ifdef VMS
68 #include <descrip.h>
69 #include <ssdef.h>
70 #include <syidef.h>
71 #define open(fname,mode,prot) VMS_open (fname,mode,prot)
72 #define fopen(fname,mode) VMS_fopen (fname,mode)
73 #define freopen(fname,mode,ofile) VMS_freopen (fname,mode,ofile)
74 #define fstat(fd,stbuf) VMS_fstat (fd,stbuf)
75 #define fwrite(ptr,size,nitems,stream) VMS_fwrite (ptr,size,nitems,stream)
76 static int VMS_fstat (), VMS_stat ();
77 static int VMS_open ();
78 static FILE *VMS_fopen ();
79 static FILE *VMS_freopen ();
80 static size_t VMS_fwrite ();
81 static void hack_vms_include_specification ();
82 #define INO_T_EQ(a, b) (!bcmp((char *) &(a), (char *) &(b), sizeof (a)))
83 #define INO_T_HASH(a) 0
84 #define INCLUDE_LEN_FUDGE 12 /* leave room for VMS syntax conversion */
85 #endif /* VMS */
86
87 /* Windows does not natively support inodes, and neither does MSDOS. */
88 #if (defined (_WIN32) && ! defined (__CYGWIN__) && ! defined (_UWIN)) \
89 || defined (__MSDOS__)
90 #define INO_T_EQ(a, b) 0
91 #endif
92
93 #ifndef INO_T_EQ
94 #define INO_T_EQ(a, b) ((a) == (b))
95 #endif
96
97 #ifndef INO_T_HASH
98 #define INO_T_HASH(a) (a)
99 #endif
100
101 #ifndef INCLUDE_LEN_FUDGE
102 #define INCLUDE_LEN_FUDGE 0
103 #endif
104
105 /* External declarations. */
106
107 extern char *version_string;
108 HOST_WIDEST_INT parse_escape PROTO((char **, HOST_WIDEST_INT));
109 HOST_WIDEST_INT parse_c_expression PROTO((char *, int));
110 \f
111 /* Name under which this program was invoked. */
112
113 static char *progname;
114
115 /* Nonzero means use extra default include directories for C++. */
116
117 static int cplusplus;
118
119 /* Nonzero means handle cplusplus style comments */
120
121 static int cplusplus_comments;
122
123 /* Nonzero means handle #import, for objective C. */
124
125 static int objc;
126
127 /* Nonzero means this is an assembly file, and allow
128 unknown directives, which could be comments. */
129
130 static int lang_asm;
131
132 /* Current maximum length of directory names in the search path
133 for include files. (Altered as we get more of them.) */
134
135 static int max_include_len;
136
137 /* Nonzero means turn NOTREACHED into #pragma NOTREACHED etc */
138
139 static int for_lint = 0;
140
141 /* Nonzero means copy comments into the output file. */
142
143 static int put_out_comments = 0;
144
145 /* Nonzero means don't process the ANSI trigraph sequences. */
146
147 static int no_trigraphs = 0;
148
149 /* Nonzero means print the names of included files rather than
150 the preprocessed output. 1 means just the #include "...",
151 2 means #include <...> as well. */
152
153 static int print_deps = 0;
154
155 /* Nonzero if missing .h files in -M output are assumed to be generated
156 files and not errors. */
157
158 static int print_deps_missing_files = 0;
159
160 /* Nonzero means print names of header files (-H). */
161
162 static int print_include_names = 0;
163
164 /* Nonzero means don't output line number information. */
165
166 static int no_line_directives;
167
168 /* Nonzero means output the text in failing conditionals,
169 inside #failed ... #endfailed. */
170
171 static int output_conditionals;
172
173 /* dump_only means inhibit output of the preprocessed text
174 and instead output the definitions of all user-defined
175 macros in a form suitable for use as input to cccp.
176 dump_names means pass #define and the macro name through to output.
177 dump_definitions means pass the whole definition (plus #define) through
178 */
179
180 static enum {dump_none, dump_only, dump_names, dump_definitions}
181 dump_macros = dump_none;
182
183 /* Nonzero means pass all #define and #undef directives which we actually
184 process through to the output stream. This feature is used primarily
185 to allow cc1 to record the #defines and #undefs for the sake of
186 debuggers which understand about preprocessor macros, but it may
187 also be useful with -E to figure out how symbols are defined, and
188 where they are defined. */
189 static int debug_output = 0;
190
191 /* Nonzero means pass #include lines through to the output,
192 even if they are ifdefed out. */
193 static int dump_includes;
194
195 /* Nonzero indicates special processing used by the pcp program. The
196 special effects of this mode are:
197
198 Inhibit all macro expansion, except those inside #if directives.
199
200 Process #define directives normally, and output their contents
201 to the output file.
202
203 Output preconditions to pcp_outfile indicating all the relevant
204 preconditions for use of this file in a later cpp run.
205 */
206 static FILE *pcp_outfile;
207
208 /* Nonzero means we are inside an IF during a -pcp run. In this mode
209 macro expansion is done, and preconditions are output for all macro
210 uses requiring them. */
211 static int pcp_inside_if;
212
213 /* Nonzero means never to include precompiled files.
214 This is 1 since there's no way now to make precompiled files,
215 so it's not worth testing for them. */
216 static int no_precomp = 1;
217
218 /* Nonzero means give all the error messages the ANSI standard requires. */
219
220 int pedantic;
221
222 /* Nonzero means try to make failure to fit ANSI C an error. */
223
224 static int pedantic_errors;
225
226 /* Nonzero means don't print warning messages. -w. */
227
228 static int inhibit_warnings = 0;
229
230 /* Nonzero means warn if slash-star appears in a slash-star comment,
231 or if newline-backslash appears in a slash-slash comment. */
232
233 static int warn_comments;
234
235 /* Nonzero means warn if a macro argument is (or would be)
236 stringified with -traditional. */
237
238 static int warn_stringify;
239
240 /* Nonzero means warn if there are any trigraphs. */
241
242 static int warn_trigraphs;
243
244 /* Nonzero means warn if undefined identifiers are evaluated in an #if. */
245
246 static int warn_undef;
247
248 /* Nonzero means warn if we find white space where it doesn't belong. */
249
250 static int warn_white_space;
251
252 /* Nonzero means warn if #import is used. */
253
254 static int warn_import = 1;
255
256 /* Nonzero means turn warnings into errors. */
257
258 static int warnings_are_errors;
259
260 /* Nonzero means try to imitate old fashioned non-ANSI preprocessor. */
261
262 int traditional;
263
264 /* Nonzero for the 1989 C Standard, including corrigenda and amendments. */
265
266 int c89;
267
268 /* Nonzero for the 199x C Standard. */
269
270 int c9x;
271
272 /* Nonzero causes output not to be done,
273 but directives such as #define that have side effects
274 are still obeyed. */
275
276 static int no_output;
277
278 /* Nonzero means we should look for header.gcc files that remap file names. */
279 static int remap;
280
281 /* Nonzero means this file was included with a -imacros or -include
282 command line and should not be recorded as an include file. */
283
284 static int no_record_file;
285
286 /* Nonzero means that we have finished processing the command line options.
287 This flag is used to decide whether or not to issue certain errors
288 and/or warnings. */
289
290 static int done_initializing = 0;
291
292 /* Line where a newline was first seen in a string constant. */
293
294 static int multiline_string_line = 0;
295 \f
296 /* I/O buffer structure.
297 The `fname' field is nonzero for source files and #include files
298 and for the dummy text used for -D and -U.
299 It is zero for rescanning results of macro expansion
300 and for expanding macro arguments. */
301 #define INPUT_STACK_MAX 400
302 static struct file_buf {
303 char *fname;
304 /* Filename specified with #line directive. */
305 char *nominal_fname;
306 /* The length of nominal_fname, which may contain embedded NULs. */
307 size_t nominal_fname_len;
308 /* Include file description. */
309 struct include_file *inc;
310 /* Record where in the search path this file was found.
311 For #include_next. */
312 struct file_name_list *dir;
313 int lineno;
314 int length;
315 U_CHAR *buf;
316 U_CHAR *bufp;
317 /* Macro that this level is the expansion of.
318 Included so that we can reenable the macro
319 at the end of this level. */
320 struct hashnode *macro;
321 /* Value of if_stack at start of this file.
322 Used to prohibit unmatched #endif (etc) in an include file. */
323 struct if_stack *if_stack;
324 /* Object to be freed at end of input at this level. */
325 U_CHAR *free_ptr;
326 /* True if this is a system header file; see is_system_include. */
327 char system_header_p;
328 } instack[INPUT_STACK_MAX];
329
330 static int last_error_tick; /* Incremented each time we print it. */
331 static int input_file_stack_tick; /* Incremented when the status changes. */
332
333 /* Current nesting level of input sources.
334 `instack[indepth]' is the level currently being read. */
335 static int indepth = -1;
336 #define CHECK_DEPTH(code) \
337 if (indepth >= (INPUT_STACK_MAX - 1)) \
338 { \
339 error_with_line (line_for_error (instack[indepth].lineno), \
340 "macro or `#include' recursion too deep"); \
341 code; \
342 }
343
344 /* Current depth in #include directives that use <...>. */
345 static int system_include_depth = 0;
346
347 typedef struct file_buf FILE_BUF;
348
349 /* The output buffer. Its LENGTH field is the amount of room allocated
350 for the buffer, not the number of chars actually present. To get
351 that, subtract outbuf.buf from outbuf.bufp. */
352
353 #define OUTBUF_SIZE 10 /* initial size of output buffer */
354 static FILE_BUF outbuf;
355
356 /* Grow output buffer OBUF points at
357 so it can hold at least NEEDED more chars. */
358
359 #define check_expand(OBUF, NEEDED) \
360 (((OBUF)->length - ((OBUF)->bufp - (OBUF)->buf) <= (NEEDED)) \
361 ? grow_outbuf ((OBUF), (NEEDED)) : 0)
362
363 struct file_name_list
364 {
365 struct file_name_list *next;
366 /* If the following is 1, it is a C-language system include
367 directory. */
368 int c_system_include_path;
369 /* Mapping of file names for this directory. */
370 struct file_name_map *name_map;
371 /* Non-zero if name_map is valid. */
372 int got_name_map;
373 /* The include directory status. */
374 struct stat st;
375 /* The include prefix: "" denotes the working directory,
376 otherwise fname must end in '/'.
377 The actual size is dynamically allocated. */
378 char fname[1];
379 };
380
381 /* #include "file" looks in source file dir, then stack. */
382 /* #include <file> just looks in the stack. */
383 /* -I directories are added to the end, then the defaults are added. */
384 /* The */
385 static struct default_include {
386 char *fname; /* The name of the directory. */
387 char *component; /* The component containing the directory */
388 int cplusplus; /* Only look here if we're compiling C++. */
389 int cxx_aware; /* Includes in this directory don't need to
390 be wrapped in extern "C" when compiling
391 C++. */
392 int included; /* Set if the directory is acceptable. */
393 } include_defaults_array[]
394 #ifdef INCLUDE_DEFAULTS
395 = INCLUDE_DEFAULTS;
396 #else
397 = {
398 /* Pick up GNU C++ specific include files. */
399 { GPLUSPLUS_INCLUDE_DIR, "G++", 1, 1, 0 },
400 #ifdef CROSS_COMPILE
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 },
410 #endif
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 },
416 #endif
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 },
421 #endif
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 },
428 #endif
429 #ifndef STANDARD_INCLUDE_COMPONENT
430 #define STANDARD_INCLUDE_COMPONENT 0
431 #endif
432 { STANDARD_INCLUDE_DIR, STANDARD_INCLUDE_COMPONENT, 0, 0, 0 },
433 #endif /* not CROSS_COMPILE */
434 { 0, 0, 0, 0, 0 }
435 };
436 #endif /* no INCLUDE_DEFAULTS */
437
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;
442
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 */
452
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 */
456
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 */
460
461 /* Directory prefix that should replace `/usr' in the standard
462 include file directories. */
463 static char *include_prefix;
464
465 /* Maintain and search list of included files. */
466
467 struct include_file {
468 struct include_file *next; /* for include_hashtab */
469 struct include_file *next_ino; /* for include_ino_hashtab */
470 char *fname;
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. */
477 int deps_output;
478 struct stat st;
479 };
480
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. */
483
484 #define INCLUDE_HASHSIZE 61
485 static struct include_file *include_hashtab[INCLUDE_HASHSIZE];
486 static struct include_file *include_ino_hashtab[INCLUDE_HASHSIZE];
487
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.
492 */
493 static STRINGDEF *stringlist;
494 static STRINGDEF **stringlist_tailp = &stringlist;
495
496
497 /* Structure returned by create_definition */
498 typedef struct macrodef MACRODEF;
499 struct macrodef
500 {
501 struct definition *defn;
502 U_CHAR *symnam;
503 int symlen;
504 };
505 \f
506 enum sharp_token_type {
507 NO_SHARP_TOKEN = 0, /* token not present */
508
509 SHARP_TOKEN = '#', /* token spelled with # only */
510 WHITE_SHARP_TOKEN, /* token spelled with # and white space */
511
512 PERCENT_COLON_TOKEN = '%', /* token spelled with %: only */
513 WHITE_PERCENT_COLON_TOKEN /* token spelled with %: and white space */
514 };
515
516 /* Structure allocated for every #define. For a simple replacement
517 such as
518 #define foo bar ,
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,
521 e.g.,
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
533 pattern list
534 { (0, 1), (1, 1), (1, 1), ..., (1, 1), NULL }
535 where (x, y) means (nchars, argno). */
536
537 typedef struct definition DEFINITION;
538 struct definition {
539 int nargs;
540 int length; /* length of expansion string */
541 int predefined; /* True if the macro was builtin or */
542 /* came from the command line */
543 U_CHAR *expansion;
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 */
548 struct reflist {
549 struct reflist *next;
550
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 */
554
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) */
559 } *pattern;
560 union {
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. */
565 U_CHAR *argnames;
566 } args;
567 };
568
569 /* different kinds of things that can appear in the value field
570 of a hash node. Actually, this may be useless now. */
571 union hashval {
572 char *cpval;
573 DEFINITION *defn;
574 KEYDEF *keydef;
575 };
576
577 /*
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); {
588 */
589 static char rest_extension[] = "...";
590 #define REST_EXTENSION_LENGTH (sizeof (rest_extension) - 1)
591
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)
596
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. */
603
604 /* different flavors of hash nodes --- also used in keyword table */
605 enum node_type {
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_POISON, /* defined with `#pragma poison' */
644 T_UNUSED /* Used for something not defined. */
645 };
646
647 struct hashnode {
648 struct hashnode *next; /* double links for easy deletion */
649 struct hashnode *prev;
650 struct hashnode **bucket_hdr; /* also, a back pointer to this node's hash
651 chain is kept, in case the node is the head
652 of the chain and gets deleted. */
653 enum node_type type; /* type of special token */
654 int length; /* length of token, for quick comparison */
655 U_CHAR *name; /* the actual name */
656 union hashval value; /* pointer to expansion, or whatever */
657 };
658
659 typedef struct hashnode HASHNODE;
660
661 /* Some definitions for the hash table. The hash function MUST be
662 computed as shown in hashf () below. That is because the rescan
663 loop computes the hash value `on the fly' for most tokens,
664 in order to avoid the overhead of a lot of procedure calls to
665 the hashf () function. Hashf () only exists for the sake of
666 politeness, for use when speed isn't so important. */
667
668 #define HASHSIZE 1403
669 static HASHNODE *hashtab[HASHSIZE];
670 #define HASHSTEP(old, c) ((old << 2) + c)
671 #define MAKE_POS(v) (v & 0x7fffffff) /* make number positive */
672
673 \f
674 /* We let tm.h override the types used here, to handle trivial differences
675 such as the choice of unsigned int or long unsigned int for size_t.
676 When machines start needing nontrivial differences in the size type,
677 it would be best to do something here to figure out automatically
678 from other information what type to use. */
679
680 /* The string value for __SIZE_TYPE__. */
681
682 #ifndef SIZE_TYPE
683 #define SIZE_TYPE "long unsigned int"
684 #endif
685
686 /* The string value for __PTRDIFF_TYPE__. */
687
688 #ifndef PTRDIFF_TYPE
689 #define PTRDIFF_TYPE "long int"
690 #endif
691
692 /* The string value for __WCHAR_TYPE__. */
693
694 #ifndef WCHAR_TYPE
695 #define WCHAR_TYPE "int"
696 #endif
697 char * wchar_type = WCHAR_TYPE;
698 #undef WCHAR_TYPE
699
700 /* The string value for __USER_LABEL_PREFIX__ */
701
702 #ifndef USER_LABEL_PREFIX
703 #define USER_LABEL_PREFIX ""
704 #endif
705 char * user_label_prefix = USER_LABEL_PREFIX;
706 #undef USER_LABEL_PREFIX
707
708 /* The string value for __REGISTER_PREFIX__ */
709
710 #ifndef REGISTER_PREFIX
711 #define REGISTER_PREFIX ""
712 #endif
713
714 /* The string value for __IMMEDIATE_PREFIX__ */
715
716 #ifndef IMMEDIATE_PREFIX
717 #define IMMEDIATE_PREFIX ""
718 #endif
719 \f
720 /* In the definition of a #assert name, this structure forms
721 a list of the individual values asserted.
722 Each value is itself a list of "tokens".
723 These are strings that are compared by name. */
724
725 struct tokenlist_list {
726 struct tokenlist_list *next;
727 struct arglist *tokens;
728 };
729
730 struct assertion_hashnode {
731 struct assertion_hashnode *next; /* double links for easy deletion */
732 struct assertion_hashnode *prev;
733 /* also, a back pointer to this node's hash
734 chain is kept, in case the node is the head
735 of the chain and gets deleted. */
736 struct assertion_hashnode **bucket_hdr;
737 int length; /* length of token, for quick comparison */
738 U_CHAR *name; /* the actual name */
739 /* List of token-sequences. */
740 struct tokenlist_list *value;
741 };
742
743 typedef struct assertion_hashnode ASSERTION_HASHNODE;
744
745 /* Some definitions for the hash table. The hash function MUST be
746 computed as shown in hashf below. That is because the rescan
747 loop computes the hash value `on the fly' for most tokens,
748 in order to avoid the overhead of a lot of procedure calls to
749 the hashf function. hashf only exists for the sake of
750 politeness, for use when speed isn't so important. */
751
752 #define ASSERTION_HASHSIZE 37
753 static ASSERTION_HASHNODE *assertion_hashtab[ASSERTION_HASHSIZE];
754
755 /* Nonzero means inhibit macroexpansion of what seem to be
756 assertion tests, in rescan. For #if. */
757 static int assertions_flag;
758 \f
759 /* `struct directive' defines one #-directive, including how to handle it. */
760
761 #define DO_PROTO PROTO((U_CHAR *, U_CHAR *, FILE_BUF *, struct directive *))
762
763 struct directive {
764 int length; /* Length of name */
765 int (*func) DO_PROTO; /* Function to handle directive */
766 char *name; /* Name of directive */
767 enum node_type type; /* Code which describes which directive. */
768 };
769
770 #define IS_INCLUDE_DIRECTIVE_TYPE(t) \
771 ((int) T_INCLUDE <= (int) (t) && (int) (t) <= (int) T_IMPORT)
772
773 /* These functions are declared to return int instead of void since they
774 are going to be placed in the table and some old compilers have trouble with
775 pointers to functions returning void. */
776
777 static int do_assert DO_PROTO;
778 static int do_define DO_PROTO;
779 static int do_elif DO_PROTO;
780 static int do_else DO_PROTO;
781 static int do_endif DO_PROTO;
782 static int do_error DO_PROTO;
783 static int do_ident DO_PROTO;
784 static int do_if DO_PROTO;
785 static int do_include DO_PROTO;
786 static int do_line DO_PROTO;
787 static int do_pragma DO_PROTO;
788 #ifdef SCCS_DIRECTIVE
789 static int do_sccs DO_PROTO;
790 #endif
791 static int do_unassert DO_PROTO;
792 static int do_undef DO_PROTO;
793 static int do_xifdef DO_PROTO;
794
795 /* Here is the actual list of #-directives, most-often-used first. */
796
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_error, "warning", T_WARNING},
812 #ifdef SCCS_DIRECTIVE
813 { 4, do_sccs, "sccs", T_SCCS},
814 #endif
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},
820 };
821
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;
825
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];
834
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)
837
838 static int errors = 0; /* Error counter for exit code */
839
840 /* Name of output file, for error messages. */
841 static char *out_fname;
842
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
845 # 1 "\f". */
846 static int ignore_escape_flag = 1;
847
848 /* Stack of conditionals currently in progress
849 (including both successful and failing conditionals). */
850
851 struct if_stack {
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 */
861 };
862 typedef struct if_stack IF_STACK_FRAME;
863 static IF_STACK_FRAME *if_stack = NULL;
864
865 /* Buffer of -M output. */
866 static char *deps_buffer;
867
868 /* Number of bytes allocated in above. */
869 static int deps_allocated_size;
870
871 /* Number of bytes used. */
872 static int deps_size;
873
874 /* Number of bytes since the last newline. */
875 static int deps_column;
876
877 /* Nonzero means -I- has been seen,
878 so don't look for #include "foo" the source-file directory. */
879 static int ignore_srcdir;
880 \f
881 static int safe_read PROTO((int, char *, int));
882 static void safe_write PROTO((int, char *, int));
883
884 int main PROTO((int, char **));
885
886 static void path_include PROTO((char *));
887
888 static U_CHAR *index0 PROTO((U_CHAR *, int, size_t));
889
890 static void trigraph_pcp PROTO((FILE_BUF *));
891 static void check_white_space PROTO((FILE_BUF *));
892
893 static void newline_fix PROTO((U_CHAR *));
894 static void name_newline_fix PROTO((U_CHAR *));
895
896 static char *get_lintcmd PROTO((U_CHAR *, U_CHAR *, U_CHAR **, int *, int *));
897
898 static void rescan PROTO((FILE_BUF *, int));
899
900 static FILE_BUF expand_to_temp_buffer PROTO((U_CHAR *, U_CHAR *, int, int));
901
902 static int handle_directive PROTO((FILE_BUF *, FILE_BUF *));
903
904 static struct tm *timestamp PROTO((void));
905 static void special_symbol PROTO((HASHNODE *, FILE_BUF *));
906
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 *));
911
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 *));
917
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 *));
920
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 *));
927
928 static MACRODEF create_definition PROTO((U_CHAR *, U_CHAR *, FILE_BUF *));
929
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));
933
934 static DEFINITION *collect_expansion PROTO((U_CHAR *, U_CHAR *, int, struct arglist *));
935
936 int check_assertion PROTO((U_CHAR *, int, int, struct arglist *));
937 static int compare_token_lists PROTO((struct arglist *, struct arglist *));
938
939 static struct arglist *read_token_list PROTO((U_CHAR **, U_CHAR *, int *));
940 static void free_token_list PROTO((struct arglist *));
941
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 *));
945
946 static void do_once PROTO((void));
947
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 *));
952
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 *));
957
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));
961
962 static void macroexpand PROTO((HASHNODE *, FILE_BUF *));
963
964 struct argdata;
965 static int macarg PROTO((struct argdata *, int));
966
967 static U_CHAR *macarg1 PROTO((U_CHAR *, U_CHAR *, struct hashnode *, int *, int *, int *, int));
968
969 static int discard_comments PROTO((U_CHAR *, int, int));
970
971 static void change_newlines PROTO((struct argdata *));
972
973 static void notice PVPROTO((const char *, ...)) ATTRIBUTE_PRINTF_1;
974 static void vnotice PROTO((const char *, va_list));
975 void error PVPROTO((const char *, ...)) ATTRIBUTE_PRINTF_1;
976 void verror PROTO((const char *, va_list));
977 static void error_from_errno PROTO((char *));
978 void warning PVPROTO((const char *, ...)) ATTRIBUTE_PRINTF_1;
979 static void vwarning PROTO((const char *, va_list));
980 static void error_with_line PVPROTO((int, const char *, ...)) ATTRIBUTE_PRINTF_2;
981 static void verror_with_line PROTO((int, const char *, va_list));
982 static void vwarning_with_line PROTO((int, const char *, va_list));
983 static void warning_with_line PVPROTO((int, const char *, ...)) ATTRIBUTE_PRINTF_2;
984 void pedwarn PVPROTO((const char *, ...)) ATTRIBUTE_PRINTF_1;
985 void pedwarn_with_line PVPROTO((int, const char *, ...)) ATTRIBUTE_PRINTF_2;
986 static void pedwarn_with_file_and_line PVPROTO((const char *, size_t, int, const char *, ...)) ATTRIBUTE_PRINTF_4;
987 static void pedwarn_strange_white_space PROTO((int));
988
989 static void print_containing_files PROTO((void));
990
991 static int line_for_error PROTO((int));
992 static int grow_outbuf PROTO((FILE_BUF *, int));
993
994 static HASHNODE *install PROTO((U_CHAR *, int, enum node_type, char *, int));
995 HASHNODE *lookup PROTO((U_CHAR *, int, int));
996 static void delete_macro PROTO((HASHNODE *));
997 static int hashf PROTO((U_CHAR *, int, int));
998
999 static void dump_single_macro PROTO((HASHNODE *, FILE *));
1000 static void dump_all_macros PROTO((void));
1001 static void dump_defn_1 PROTO((U_CHAR *, int, int, FILE *));
1002 static void dump_arg_n PROTO((DEFINITION *, int, FILE *));
1003
1004 static void initialize_char_syntax PROTO((void));
1005 static void initialize_builtins PROTO((FILE_BUF *, FILE_BUF *));
1006
1007 static void make_definition PROTO((char *));
1008 static void make_undef PROTO((char *, FILE_BUF *));
1009
1010 static void make_assertion PROTO((const char *, const char *));
1011
1012 static struct file_name_list *new_include_prefix PROTO((struct file_name_list *, const char *, const char *, const char *));
1013 static void append_include_chain PROTO((struct file_name_list *, struct file_name_list *));
1014
1015 static int quote_string_for_make PROTO((char *, const char *));
1016 static void deps_output PROTO((const char *, int));
1017
1018 void fatal PVPROTO((const char *, ...)) ATTRIBUTE_PRINTF_1 ATTRIBUTE_NORETURN;
1019 void fancy_abort PROTO((void)) ATTRIBUTE_NORETURN;
1020 static void perror_with_name PROTO((char *));
1021 static void pfatal_with_name PROTO((char *)) ATTRIBUTE_NORETURN;
1022 static void pipe_closed PROTO((int)) ATTRIBUTE_NORETURN;
1023
1024 static void memory_full PROTO((void)) ATTRIBUTE_NORETURN;
1025 static void print_help PROTO((void));
1026 \f
1027 /* Read LEN bytes at PTR from descriptor DESC, for file FILENAME,
1028 retrying if necessary. If MAX_READ_LEN is defined, read at most
1029 that bytes at a time. Return a negative value if an error occurs,
1030 otherwise return the actual number of bytes read,
1031 which must be LEN unless end-of-file was reached. */
1032
1033 static int
1034 safe_read (desc, ptr, len)
1035 int desc;
1036 char *ptr;
1037 int len;
1038 {
1039 int left, rcount, nchars;
1040
1041 left = len;
1042 while (left > 0) {
1043 rcount = left;
1044 #ifdef MAX_READ_LEN
1045 if (rcount > MAX_READ_LEN)
1046 rcount = MAX_READ_LEN;
1047 #endif
1048 nchars = read (desc, ptr, rcount);
1049 if (nchars < 0)
1050 {
1051 #ifdef EINTR
1052 if (errno == EINTR)
1053 continue;
1054 #endif
1055 return nchars;
1056 }
1057 if (nchars == 0)
1058 break;
1059 ptr += nchars;
1060 left -= nchars;
1061 }
1062 return len - left;
1063 }
1064
1065 /* Write LEN bytes at PTR to descriptor DESC,
1066 retrying if necessary, and treating any real error as fatal.
1067 If MAX_WRITE_LEN is defined, write at most that many bytes at a time. */
1068
1069 static void
1070 safe_write (desc, ptr, len)
1071 int desc;
1072 char *ptr;
1073 int len;
1074 {
1075 int wcount, written;
1076
1077 while (len > 0) {
1078 wcount = len;
1079 #ifdef MAX_WRITE_LEN
1080 if (wcount > MAX_WRITE_LEN)
1081 wcount = MAX_WRITE_LEN;
1082 #endif
1083 written = write (desc, ptr, wcount);
1084 if (written < 0)
1085 {
1086 #ifdef EINTR
1087 if (errno == EINTR)
1088 continue;
1089 #endif
1090 pfatal_with_name (out_fname);
1091 }
1092 ptr += written;
1093 len -= written;
1094 }
1095 }
1096
1097 \f
1098 static void
1099 print_help ()
1100 {
1101 printf ("Usage: %s [switches] input output\n", progname);
1102 printf ("Switches:\n");
1103 printf (" -include <file> Include the contents of <file> before other files\n");
1104 printf (" -imacros <file> Accept definition of macros in <file>\n");
1105 printf (" -iprefix <path> Specify <path> as a prefix for next two options\n");
1106 printf (" -iwithprefix <dir> Add <dir> to the end of the system include paths\n");
1107 printf (" -iwithprefixbefore <dir> Add <dir> to the end of the main include paths\n");
1108 printf (" -isystem <dir> Add <dir> to the start of the system include paths\n");
1109 printf (" -idirafter <dir> Add <dir> to the end of the system include paths\n");
1110 printf (" -I <dir> Add <dir> to the end of the main include paths\n");
1111 printf (" -nostdinc Do not search the system include directories\n");
1112 printf (" -nostdinc++ Do not search the system include directories for C++\n");
1113 printf (" -o <file> Put output into <file>\n");
1114 printf (" -pedantic Issue all warnings demanded by strict ANSI C\n");
1115 printf (" -traditional Follow K&R pre-processor behaviour\n");
1116 printf (" -trigraphs Support ANSI C trigraphs\n");
1117 printf (" -lang-c Assume that the input sources are in C\n");
1118 printf (" -lang-c89 Assume that the input is C89; depricated\n");
1119 printf (" -lang-c++ Assume that the input sources are in C++\n");
1120 printf (" -lang-objc Assume that the input sources are in ObjectiveC\n");
1121 printf (" -lang-objc++ Assume that the input sources are in ObjectiveC++\n");
1122 printf (" -lang-asm Assume that the input sources are in assembler\n");
1123 printf (" -lang-chill Assume that the input sources are in Chill\n");
1124 printf (" -std=<std name> Specify the conformance standard; one of:\n");
1125 printf (" gnu89, gnu9x, c89, c9x, iso9899:1990,\n");
1126 printf (" iso9899:199409, iso9899:199x\n");
1127 printf (" -+ Allow parsing of C++ style features\n");
1128 printf (" -w Inhibit warning messages\n");
1129 printf (" -Wtrigraphs Warn if trigraphs are encountered\n");
1130 printf (" -Wno-trigraphs Do not warn about trigraphs\n");
1131 printf (" -Wcomment{s} Warn if one comment starts inside another\n");
1132 printf (" -Wno-comment{s} Do not warn about comments\n");
1133 printf (" -Wtraditional Warn if a macro argument is/would be turned into\n");
1134 printf (" a string if -traditional is specified\n");
1135 printf (" -Wno-traditional Do not warn about stringification\n");
1136 printf (" -Wundef Warn if an undefined macro is used by #if\n");
1137 printf (" -Wno-undef Do not warn about testing undefined macros\n");
1138 printf (" -Wimport Warn about the use of the #import directive\n");
1139 printf (" -Wno-import Do not warn about the use of #import\n");
1140 printf (" -Werror Treat all warnings as errors\n");
1141 printf (" -Wno-error Do not treat warnings as errors\n");
1142 printf (" -Wall Enable all preprocessor warnings\n");
1143 printf (" -M Generate make dependencies\n");
1144 printf (" -MM As -M, but ignore system header files\n");
1145 printf (" -MD As -M, but put output in a .d file\n");
1146 printf (" -MMD As -MD, but ignore system header files\n");
1147 printf (" -MG Treat missing header file as generated files\n");
1148 printf (" -g Include #define and #undef directives in the output\n");
1149 printf (" -D<macro> Define a <macro> with string '1' as its value\n");
1150 printf (" -D<macro>=<val> Define a <macro> with <val> as its value\n");
1151 printf (" -A<question> (<answer>) Assert the <answer> to <question>\n");
1152 printf (" -U<macro> Undefine <macro> \n");
1153 printf (" -u or -undef Do not predefine any macros\n");
1154 printf (" -v Display the version number\n");
1155 printf (" -H Print the name of header files as they are used\n");
1156 printf (" -C Do not discard comments\n");
1157 printf (" -dM Display a list of macro definitions active at end\n");
1158 printf (" -dD Preserve macro definitions in output\n");
1159 printf (" -dN As -dD except that only the names are preserved\n");
1160 printf (" -dI Include #include directives in the output\n");
1161 printf (" -ifoutput Describe skipped code blocks in output \n");
1162 printf (" -P Do not generate #line directives\n");
1163 printf (" -$ Do not include '$' in identifiers\n");
1164 printf (" -remap Remap file names when including files.\n");
1165 printf (" -h or --help Display this information\n");
1166 }
1167 \f
1168 int
1169 main (argc, argv)
1170 int argc;
1171 char **argv;
1172 {
1173 struct stat st;
1174 char *in_fname;
1175 char *cp;
1176 int f, i;
1177 FILE_BUF *fp;
1178
1179 char **pend_files;
1180 char **pend_defs;
1181 char **pend_undefs;
1182 char **pend_assertions;
1183 char **pend_includes;
1184
1185 /* Record the option used with each element of pend_assertions.
1186 This is preparation for supporting more than one option for making
1187 an assertion. */
1188 char **pend_assertion_options;
1189 int no_standard_includes = 0;
1190 int no_standard_cplusplus_includes = 0;
1191 int missing_newline = 0;
1192
1193 /* Non-0 means don't output the preprocessed program. */
1194 int inhibit_output = 0;
1195 /* Non-0 means -v, so print the full set of include dirs. */
1196 int verbose = 0;
1197
1198 /* File name which deps are being written to.
1199 This is 0 if deps are being written to stdout. */
1200 char *deps_file = 0;
1201 /* Fopen file mode to open deps_file with. */
1202 char *deps_mode = "a";
1203 /* Stream on which to print the dependency information. */
1204 FILE *deps_stream = 0;
1205 /* Target-name to write with the dependency information. */
1206 char *deps_target = 0;
1207
1208 #if defined (RLIMIT_STACK) && defined (HAVE_GETRLIMIT) && defined (HAVE_SETRLIMIT)
1209 /* Get rid of any avoidable limit on stack size. */
1210 {
1211 struct rlimit rlim;
1212
1213 /* Set the stack limit huge so that alloca (particularly stringtab
1214 in dbxread.c) does not fail. */
1215 getrlimit (RLIMIT_STACK, &rlim);
1216 rlim.rlim_cur = rlim.rlim_max;
1217 setrlimit (RLIMIT_STACK, &rlim);
1218 }
1219 #endif
1220
1221 #ifdef SIGPIPE
1222 signal (SIGPIPE, pipe_closed);
1223 #endif
1224
1225 #ifdef HAVE_LC_MESSAGES
1226 setlocale (LC_MESSAGES, "");
1227 #endif
1228 (void) bindtextdomain (PACKAGE, localedir);
1229 (void) textdomain (PACKAGE);
1230
1231 progname = base_name (argv[0]);
1232
1233 #ifdef VMS
1234 {
1235 /* Remove extension from PROGNAME. */
1236 char *p;
1237 char *s = progname = xstrdup (progname);
1238
1239 if ((p = rindex (s, ';')) != 0) *p = '\0'; /* strip version number */
1240 if ((p = rindex (s, '.')) != 0 /* strip type iff ".exe" */
1241 && (p[1] == 'e' || p[1] == 'E')
1242 && (p[2] == 'x' || p[2] == 'X')
1243 && (p[3] == 'e' || p[3] == 'E')
1244 && !p[4])
1245 *p = '\0';
1246 }
1247 #endif
1248
1249 /* Do not invoke xmalloc before this point, since locale and
1250 progname need to be set first, in case a diagnostic is issued. */
1251
1252 pend_files = (char **) xmalloc (argc * sizeof (char *));
1253 pend_defs = (char **) xmalloc (argc * sizeof (char *));
1254 pend_undefs = (char **) xmalloc (argc * sizeof (char *));
1255 pend_assertions = (char **) xmalloc (argc * sizeof (char *));
1256 pend_includes = (char **) xmalloc (argc * sizeof (char *));
1257 pend_assertion_options = (char **) xmalloc (argc * sizeof (char *));
1258
1259 in_fname = NULL;
1260 out_fname = NULL;
1261
1262 /* Initialize is_idchar. */
1263 initialize_char_syntax ();
1264
1265 no_line_directives = 0;
1266 no_trigraphs = 1;
1267 dump_macros = dump_none;
1268 no_output = 0;
1269 cplusplus = 0;
1270 cplusplus_comments = 1;
1271
1272 bzero ((char *) pend_files, argc * sizeof (char *));
1273 bzero ((char *) pend_defs, argc * sizeof (char *));
1274 bzero ((char *) pend_undefs, argc * sizeof (char *));
1275 bzero ((char *) pend_assertions, argc * sizeof (char *));
1276 bzero ((char *) pend_includes, argc * sizeof (char *));
1277
1278 #ifdef MULTIBYTE_CHARS
1279 /* Change to the native locale for multibyte conversions. */
1280 setlocale (LC_CTYPE, "");
1281 literal_codeset = getenv ("LANG");
1282 #endif
1283
1284 /* Process switches and find input file name. */
1285
1286 for (i = 1; i < argc; i++) {
1287 if (argv[i][0] != '-') {
1288 if (out_fname != NULL)
1289 {
1290 print_help ();
1291 fatal ("Too many arguments");
1292 }
1293 else if (in_fname != NULL)
1294 out_fname = argv[i];
1295 else
1296 in_fname = argv[i];
1297 } else {
1298 switch (argv[i][1]) {
1299
1300 case 'i':
1301 if (!strcmp (argv[i], "-include")) {
1302 if (i + 1 == argc)
1303 fatal ("Filename missing after `-include' option");
1304 else {
1305 i++;
1306 simplify_filename (pend_includes[i] = argv[i]);
1307 }
1308 }
1309 if (!strcmp (argv[i], "-imacros")) {
1310 if (i + 1 == argc)
1311 fatal ("Filename missing after `-imacros' option");
1312 else {
1313 i++;
1314 simplify_filename (pend_files[i] = argv[i]);
1315 }
1316 }
1317 if (!strcmp (argv[i], "-iprefix")) {
1318 if (i + 1 == argc)
1319 fatal ("Filename missing after `-iprefix' option");
1320 else
1321 include_prefix = argv[++i];
1322 }
1323 if (!strcmp (argv[i], "-ifoutput")) {
1324 output_conditionals = 1;
1325 }
1326 if (!strcmp (argv[i], "-isystem")) {
1327 struct file_name_list *dirtmp;
1328
1329 if (! (dirtmp = new_include_prefix (NULL_PTR, NULL_PTR,
1330 "", argv[++i])))
1331 break;
1332 dirtmp->c_system_include_path = 1;
1333
1334 if (before_system == 0)
1335 before_system = dirtmp;
1336 else
1337 last_before_system->next = dirtmp;
1338 last_before_system = dirtmp; /* Tail follows the last one */
1339 }
1340 /* Add directory to end of path for includes,
1341 with the default prefix at the front of its name. */
1342 if (!strcmp (argv[i], "-iwithprefix")) {
1343 struct file_name_list *dirtmp;
1344 char *prefix;
1345
1346 if (include_prefix != 0)
1347 prefix = include_prefix;
1348 else {
1349 prefix = xstrdup (GCC_INCLUDE_DIR);
1350 /* Remove the `include' from /usr/local/lib/gcc.../include. */
1351 if (!strcmp (prefix + strlen (prefix) - 8, "/include"))
1352 prefix[strlen (prefix) - 7] = 0;
1353 }
1354
1355 if (! (dirtmp = new_include_prefix (NULL_PTR, NULL_PTR,
1356 prefix, argv[++i])))
1357 break;
1358
1359 if (after_include == 0)
1360 after_include = dirtmp;
1361 else
1362 last_after_include->next = dirtmp;
1363 last_after_include = dirtmp; /* Tail follows the last one */
1364 }
1365 /* Add directory to main path for includes,
1366 with the default prefix at the front of its name. */
1367 if (!strcmp (argv[i], "-iwithprefixbefore")) {
1368 struct file_name_list *dirtmp;
1369 char *prefix;
1370
1371 if (include_prefix != 0)
1372 prefix = include_prefix;
1373 else {
1374 prefix = xstrdup (GCC_INCLUDE_DIR);
1375 /* Remove the `include' from /usr/local/lib/gcc.../include. */
1376 if (!strcmp (prefix + strlen (prefix) - 8, "/include"))
1377 prefix[strlen (prefix) - 7] = 0;
1378 }
1379
1380 dirtmp = new_include_prefix (NULL_PTR, NULL_PTR, prefix, argv[++i]);
1381 append_include_chain (dirtmp, dirtmp);
1382 }
1383 /* Add directory to end of path for includes. */
1384 if (!strcmp (argv[i], "-idirafter")) {
1385 struct file_name_list *dirtmp;
1386
1387 if (! (dirtmp = new_include_prefix (NULL_PTR, NULL_PTR,
1388 "", argv[++i])))
1389 break;
1390
1391 if (after_include == 0)
1392 after_include = dirtmp;
1393 else
1394 last_after_include->next = dirtmp;
1395 last_after_include = dirtmp; /* Tail follows the last one */
1396 }
1397 break;
1398
1399 case 'o':
1400 if (out_fname != NULL)
1401 fatal ("Output filename specified twice");
1402 if (i + 1 == argc)
1403 fatal ("Filename missing after -o option");
1404 out_fname = argv[++i];
1405 if (!strcmp (out_fname, "-"))
1406 out_fname = "";
1407 break;
1408
1409 case 'p':
1410 if (!strcmp (argv[i], "-pedantic"))
1411 pedantic = 1;
1412 else if (!strcmp (argv[i], "-pedantic-errors")) {
1413 pedantic = 1;
1414 pedantic_errors = 1;
1415 } else if (!strcmp (argv[i], "-pcp")) {
1416 char *pcp_fname;
1417 if (i + 1 == argc)
1418 fatal ("Filename missing after -pcp option");
1419 pcp_fname = argv[++i];
1420 pcp_outfile
1421 = ((pcp_fname[0] != '-' || pcp_fname[1] != '\0')
1422 ? fopen (pcp_fname, "w")
1423 : stdout);
1424 if (pcp_outfile == 0)
1425 pfatal_with_name (pcp_fname);
1426 no_precomp = 1;
1427 }
1428 break;
1429
1430 case 't':
1431 if (!strcmp (argv[i], "-traditional")) {
1432 traditional = 1;
1433 cplusplus_comments = 0;
1434 } else if (!strcmp (argv[i], "-trigraphs")) {
1435 no_trigraphs = 0;
1436 }
1437 break;
1438
1439 case 'l':
1440 if (! strcmp (argv[i], "-lang-c"))
1441 cplusplus = 0, cplusplus_comments = 1, c89 = 0, c9x = 1, objc = 0;
1442 else if (! strcmp (argv[i], "-lang-c89"))
1443 cplusplus = 0, cplusplus_comments = 0, c89 = 1, c9x = 0, objc = 0;
1444 else if (! strcmp (argv[i], "-lang-c++"))
1445 cplusplus = 1, cplusplus_comments = 1, c89 = 0, c9x = 0, objc = 0;
1446 else if (! strcmp (argv[i], "-lang-objc"))
1447 cplusplus = 0, cplusplus_comments = 1, c89 = 0, c9x = 0, objc = 1;
1448 else if (! strcmp (argv[i], "-lang-objc++"))
1449 cplusplus = 1, cplusplus_comments = 1, c89 = 0, c9x = 0, objc = 1;
1450 else if (! strcmp (argv[i], "-lang-asm"))
1451 lang_asm = 1;
1452 else if (! strcmp (argv[i], "-lint"))
1453 for_lint = 1;
1454 break;
1455
1456 case '+':
1457 cplusplus = 1, cplusplus_comments = 1;
1458 break;
1459
1460 case 's':
1461 if (!strcmp (argv[i], "-std=iso9899:1990")
1462 || !strcmp (argv[i], "-std=iso9899:199409")
1463 || !strcmp (argv[i], "-std=c89")
1464 || !strcmp (argv[i], "-std=gnu89"))
1465 cplusplus = 0, cplusplus_comments = 0, c89 = 1, c9x = 0, objc = 0;
1466 else if (!strcmp (argv[i], "-std=iso9899:199x")
1467 || !strcmp (argv[i], "-std=c9x")
1468 || !strcmp (argv[i], "-std=gnu9x"))
1469 cplusplus = 0, cplusplus_comments = 1, c89 = 0, c9x = 1, objc = 0;
1470 break;
1471
1472 case 'w':
1473 inhibit_warnings = 1;
1474 break;
1475
1476 case 'W':
1477 if (!strcmp (argv[i], "-Wtrigraphs"))
1478 warn_trigraphs = 1;
1479 else if (!strcmp (argv[i], "-Wno-trigraphs"))
1480 warn_trigraphs = 0;
1481 else if (!strcmp (argv[i], "-Wcomment"))
1482 warn_comments = 1;
1483 else if (!strcmp (argv[i], "-Wno-comment"))
1484 warn_comments = 0;
1485 else if (!strcmp (argv[i], "-Wcomments"))
1486 warn_comments = 1;
1487 else if (!strcmp (argv[i], "-Wno-comments"))
1488 warn_comments = 0;
1489 else if (!strcmp (argv[i], "-Wtraditional"))
1490 warn_stringify = 1;
1491 else if (!strcmp (argv[i], "-Wno-traditional"))
1492 warn_stringify = 0;
1493 else if (!strcmp (argv[i], "-Wwhite-space"))
1494 warn_white_space = 1;
1495 else if (!strcmp (argv[i], "-Wno-white-space"))
1496 warn_white_space = 0;
1497 else if (!strcmp (argv[i], "-Wundef"))
1498 warn_undef = 1;
1499 else if (!strcmp (argv[i], "-Wno-undef"))
1500 warn_undef = 0;
1501 else if (!strcmp (argv[i], "-Wimport"))
1502 warn_import = 1;
1503 else if (!strcmp (argv[i], "-Wno-import"))
1504 warn_import = 0;
1505 else if (!strcmp (argv[i], "-Werror"))
1506 warnings_are_errors = 1;
1507 else if (!strcmp (argv[i], "-Wno-error"))
1508 warnings_are_errors = 0;
1509 else if (!strcmp (argv[i], "-Wall"))
1510 {
1511 warn_trigraphs = 1;
1512 warn_comments = 1;
1513 warn_white_space = 1;
1514 }
1515 break;
1516
1517 case 'f':
1518 if (!strcmp (argv[i], "-fleading-underscore"))
1519 user_label_prefix = "_";
1520 else if (!strcmp (argv[i], "-fno-leading-underscore"))
1521 user_label_prefix = "";
1522 break;
1523
1524 case 'M':
1525 /* The style of the choices here is a bit mixed.
1526 The chosen scheme is a hybrid of keeping all options in one string
1527 and specifying each option in a separate argument:
1528 -M|-MM|-MD file|-MMD file [-MG]. An alternative is:
1529 -M|-MM|-MD file|-MMD file|-MG|-MMG; or more concisely:
1530 -M[M][G][D file]. This is awkward to handle in specs, and is not
1531 as extensible. */
1532 /* ??? -MG must be specified in addition to one of -M or -MM.
1533 This can be relaxed in the future without breaking anything.
1534 The converse isn't true. */
1535
1536 /* -MG isn't valid with -MD or -MMD. This is checked for later. */
1537 if (!strcmp (argv[i], "-MG"))
1538 {
1539 print_deps_missing_files = 1;
1540 break;
1541 }
1542 if (!strcmp (argv[i], "-M"))
1543 print_deps = 2;
1544 else if (!strcmp (argv[i], "-MM"))
1545 print_deps = 1;
1546 else if (!strcmp (argv[i], "-MD"))
1547 print_deps = 2;
1548 else if (!strcmp (argv[i], "-MMD"))
1549 print_deps = 1;
1550 /* For -MD and -MMD options, write deps on file named by next arg. */
1551 if (!strcmp (argv[i], "-MD")
1552 || !strcmp (argv[i], "-MMD")) {
1553 if (i + 1 == argc)
1554 fatal ("Filename missing after %s option", argv[i]);
1555 i++;
1556 deps_file = argv[i];
1557 deps_mode = "w";
1558 } else {
1559 /* For -M and -MM, write deps on standard output
1560 and suppress the usual output. */
1561 deps_stream = stdout;
1562 inhibit_output = 1;
1563 }
1564 break;
1565
1566 case 'd':
1567 {
1568 char *p = argv[i] + 2;
1569 char c;
1570 while ((c = *p++)) {
1571 /* Arg to -d specifies what parts of macros to dump */
1572 switch (c) {
1573 case 'M':
1574 dump_macros = dump_only;
1575 no_output = 1;
1576 break;
1577 case 'N':
1578 dump_macros = dump_names;
1579 break;
1580 case 'D':
1581 dump_macros = dump_definitions;
1582 break;
1583 case 'I':
1584 dump_includes = 1;
1585 break;
1586 }
1587 }
1588 }
1589 break;
1590
1591 case 'g':
1592 if (argv[i][2] == '3')
1593 debug_output = 1;
1594 break;
1595
1596 case '-':
1597 if (strcmp (argv[i], "--help") != 0)
1598 return i;
1599 print_help ();
1600 exit (0);
1601 break;
1602
1603 case 'v':
1604 notice ("GNU CPP version %s", version_string);
1605 #ifdef TARGET_VERSION
1606 TARGET_VERSION;
1607 #endif
1608 fprintf (stderr, "\n");
1609 verbose = 1;
1610 break;
1611
1612 case 'H':
1613 print_include_names = 1;
1614 break;
1615
1616 case 'D':
1617 if (argv[i][2] != 0)
1618 pend_defs[i] = argv[i] + 2;
1619 else if (i + 1 == argc)
1620 fatal ("Macro name missing after -D option");
1621 else
1622 i++, pend_defs[i] = argv[i];
1623 break;
1624
1625 case 'A':
1626 {
1627 char *p;
1628
1629 if (argv[i][2] != 0)
1630 p = argv[i] + 2;
1631 else if (i + 1 == argc)
1632 fatal ("Assertion missing after -A option");
1633 else
1634 p = argv[++i];
1635
1636 if (!strcmp (p, "-")) {
1637 /* -A- eliminates all predefined macros and assertions.
1638 Let's include also any that were specified earlier
1639 on the command line. That way we can get rid of any
1640 that were passed automatically in from GCC. */
1641 int j;
1642 for (j = 0; j < i; j++)
1643 pend_defs[j] = pend_assertions[j] = 0;
1644 } else {
1645 pend_assertions[i] = p;
1646 pend_assertion_options[i] = "-A";
1647 }
1648 }
1649 break;
1650
1651 case 'U': /* JF #undef something */
1652 if (argv[i][2] != 0)
1653 pend_undefs[i] = argv[i] + 2;
1654 else if (i + 1 == argc)
1655 fatal ("Macro name missing after -U option");
1656 else
1657 pend_undefs[i] = argv[i+1], i++;
1658 break;
1659
1660 case 'C':
1661 put_out_comments = 1;
1662 break;
1663
1664 case 'E': /* -E comes from cc -E; ignore it. */
1665 break;
1666
1667 case 'P':
1668 no_line_directives = 1;
1669 break;
1670
1671 case '$': /* Don't include $ in identifiers. */
1672 is_idchar['$'] = is_idstart['$'] = 0;
1673 break;
1674
1675 case 'I': /* Add directory to path for includes. */
1676 {
1677 struct file_name_list *dirtmp;
1678 char *dir = argv[i][2] ? argv[i] + 2 : argv[++i];
1679
1680 if (! ignore_srcdir && !strcmp (dir, "-")) {
1681 ignore_srcdir = 1;
1682 /* Don't use any preceding -I directories for #include <...>. */
1683 first_bracket_include = 0;
1684 }
1685 else {
1686 dirtmp = new_include_prefix (last_include, NULL_PTR, "", dir);
1687 append_include_chain (dirtmp, dirtmp);
1688 }
1689 }
1690 break;
1691
1692 case 'n':
1693 if (!strcmp (argv[i], "-nostdinc"))
1694 /* -nostdinc causes no default include directories.
1695 You must specify all include-file directories with -I. */
1696 no_standard_includes = 1;
1697 else if (!strcmp (argv[i], "-nostdinc++"))
1698 /* -nostdinc++ causes no default C++-specific include directories. */
1699 no_standard_cplusplus_includes = 1;
1700 else if (!strcmp (argv[i], "-noprecomp"))
1701 no_precomp = 1;
1702 break;
1703
1704 case 'r':
1705 if (!strcmp (argv[i], "-remap"))
1706 remap = 1;
1707 break;
1708
1709 case '\0': /* JF handle '-' as file name meaning stdin or stdout */
1710 if (in_fname == NULL) {
1711 in_fname = "";
1712 break;
1713 } else if (out_fname == NULL) {
1714 out_fname = "";
1715 break;
1716 } /* else fall through into error */
1717
1718 default:
1719 fatal ("Invalid option `%s'", argv[i]);
1720 }
1721 }
1722 }
1723
1724 /* Add dirs from CPATH after dirs from -I. */
1725 /* There seems to be confusion about what CPATH should do,
1726 so for the moment it is not documented. */
1727 /* Some people say that CPATH should replace the standard include dirs,
1728 but that seems pointless: it comes before them, so it overrides them
1729 anyway. */
1730 GET_ENV_PATH_LIST (cp, "CPATH");
1731 if (cp && ! no_standard_includes)
1732 path_include (cp);
1733
1734 /* Initialize output buffer */
1735
1736 outbuf.buf = (U_CHAR *) xmalloc (OUTBUF_SIZE);
1737 outbuf.bufp = outbuf.buf;
1738 outbuf.length = OUTBUF_SIZE;
1739
1740 /* Do partial setup of input buffer for the sake of generating
1741 early #line directives (when -g is in effect). */
1742
1743 fp = &instack[++indepth];
1744 if (in_fname == NULL)
1745 in_fname = "";
1746 fp->nominal_fname = fp->fname = in_fname;
1747 fp->nominal_fname_len = strlen (in_fname);
1748 fp->lineno = 0;
1749
1750 /* In C++, wchar_t is a distinct basic type, and we can expect
1751 __wchar_t to be defined by cc1plus. */
1752 if (cplusplus)
1753 wchar_type = "__wchar_t";
1754
1755 /* Install __LINE__, etc. Must follow initialize_char_syntax
1756 and option processing. */
1757 initialize_builtins (fp, &outbuf);
1758
1759 /* Now handle the command line options. */
1760
1761 /* Do -U's, -D's and -A's in the order they were seen. */
1762 for (i = 1; i < argc; i++) {
1763 if (pend_undefs[i]) {
1764 if (debug_output)
1765 output_line_directive (fp, &outbuf, 0, same_file);
1766 make_undef (pend_undefs[i], &outbuf);
1767 }
1768 if (pend_defs[i]) {
1769 if (debug_output)
1770 output_line_directive (fp, &outbuf, 0, same_file);
1771 make_definition (pend_defs[i]);
1772 }
1773 if (pend_assertions[i])
1774 make_assertion (pend_assertion_options[i], pend_assertions[i]);
1775 }
1776
1777 done_initializing = 1;
1778
1779 { /* Read the appropriate environment variable and if it exists
1780 replace include_defaults with the listed path. */
1781 char *epath = 0;
1782 switch ((objc << 1) + cplusplus)
1783 {
1784 case 0:
1785 GET_ENV_PATH_LIST (epath, "C_INCLUDE_PATH");
1786 break;
1787 case 1:
1788 GET_ENV_PATH_LIST (epath, "CPLUS_INCLUDE_PATH");
1789 break;
1790 case 2:
1791 GET_ENV_PATH_LIST (epath, "OBJC_INCLUDE_PATH");
1792 break;
1793 case 3:
1794 GET_ENV_PATH_LIST (epath, "OBJCPLUS_INCLUDE_PATH");
1795 break;
1796 }
1797 /* If the environment var for this language is set,
1798 add to the default list of include directories. */
1799 if (epath) {
1800 int num_dirs;
1801 char *startp, *endp;
1802
1803 for (num_dirs = 1, startp = epath; *startp; startp++)
1804 if (*startp == PATH_SEPARATOR)
1805 num_dirs++;
1806 include_defaults
1807 = (struct default_include *) xmalloc ((num_dirs
1808 * sizeof (struct default_include))
1809 + sizeof (include_defaults_array));
1810 startp = endp = epath;
1811 num_dirs = 0;
1812 while (1) {
1813 char c = *endp++;
1814 if (c == PATH_SEPARATOR || !c) {
1815 endp[-1] = 0;
1816 include_defaults[num_dirs].fname
1817 = startp == endp ? "." : xstrdup (startp);
1818 endp[-1] = c;
1819 include_defaults[num_dirs].component = 0;
1820 include_defaults[num_dirs].cplusplus = cplusplus;
1821 include_defaults[num_dirs].cxx_aware = 1;
1822 num_dirs++;
1823 if (!c)
1824 break;
1825 startp = endp;
1826 }
1827 }
1828 /* Put the usual defaults back in at the end. */
1829 bcopy ((char *) include_defaults_array,
1830 (char *) &include_defaults[num_dirs],
1831 sizeof (include_defaults_array));
1832 }
1833 }
1834
1835 append_include_chain (before_system, last_before_system);
1836 first_system_include = before_system;
1837
1838 /* Unless -fnostdinc,
1839 tack on the standard include file dirs to the specified list */
1840 if (!no_standard_includes) {
1841 struct default_include *p = include_defaults;
1842 char *specd_prefix = include_prefix;
1843 char *default_prefix = xstrdup (GCC_INCLUDE_DIR);
1844 int default_len = 0;
1845 /* Remove the `include' from /usr/local/lib/gcc.../include. */
1846 if (!strcmp (default_prefix + strlen (default_prefix) - 8, "/include")) {
1847 default_len = strlen (default_prefix) - 7;
1848 default_prefix[default_len] = 0;
1849 }
1850 /* Search "translated" versions of GNU directories.
1851 These have /usr/local/lib/gcc... replaced by specd_prefix. */
1852 if (specd_prefix != 0 && default_len != 0)
1853 for (p = include_defaults; p->fname; p++) {
1854 /* Some standard dirs are only for C++. */
1855 if (!p->cplusplus || (cplusplus && !no_standard_cplusplus_includes)) {
1856 /* Does this dir start with the prefix? */
1857 if (!strncmp (p->fname, default_prefix, default_len)) {
1858 /* Yes; change prefix and add to search list. */
1859 struct file_name_list *new
1860 = new_include_prefix (NULL_PTR, NULL_PTR, specd_prefix,
1861 p->fname + default_len);
1862 if (new) {
1863 new->c_system_include_path = !p->cxx_aware;
1864 append_include_chain (new, new);
1865 if (first_system_include == 0)
1866 first_system_include = new;
1867 p->included = 1;
1868 }
1869 }
1870 }
1871 }
1872 /* Search ordinary names for GNU include directories. */
1873 for (p = include_defaults; p->fname; p++) {
1874 /* Some standard dirs are only for C++. */
1875 if (!p->cplusplus || (cplusplus && !no_standard_cplusplus_includes)) {
1876 struct file_name_list *new
1877 = new_include_prefix (NULL_PTR, p->component, "", p->fname);
1878 if (new) {
1879 new->c_system_include_path = !p->cxx_aware;
1880 append_include_chain (new, new);
1881 if (first_system_include == 0)
1882 first_system_include = new;
1883 p->included = 1;
1884 }
1885 }
1886 }
1887 }
1888
1889 /* Tack the after_include chain at the end of the include chain. */
1890 append_include_chain (after_include, last_after_include);
1891 if (first_system_include == 0)
1892 first_system_include = after_include;
1893
1894 /* With -v, print the list of dirs to search. */
1895 if (verbose) {
1896 struct file_name_list *p;
1897 notice ("#include \"...\" search starts here:\n");
1898 for (p = include; p; p = p->next) {
1899 if (p == first_bracket_include)
1900 notice ("#include <...> search starts here:\n");
1901 if (!p->fname[0])
1902 fprintf (stderr, " .\n");
1903 else if (!strcmp (p->fname, "/") || !strcmp (p->fname, "//"))
1904 fprintf (stderr, " %s\n", p->fname);
1905 else
1906 /* Omit trailing '/'. */
1907 fprintf (stderr, " %.*s\n", (int) strlen (p->fname) - 1, p->fname);
1908 }
1909 notice ("End of search list.\n");
1910 {
1911 struct default_include * d;
1912 notice ("The following default directories have been omitted from the search path:\n");
1913 for (d = include_defaults; d->fname; d++)
1914 if (! d->included)
1915 fprintf (stderr, " %s\n", d->fname);
1916 notice ("End of omitted list.\n");
1917 }
1918 }
1919
1920 /* -MG doesn't select the form of output and must be specified with one of
1921 -M or -MM. -MG doesn't make sense with -MD or -MMD since they don't
1922 inhibit compilation. */
1923 if (print_deps_missing_files && (print_deps == 0 || !inhibit_output))
1924 fatal ("-MG must be specified with one of -M or -MM");
1925
1926 /* Either of two environment variables can specify output of deps.
1927 Its value is either "OUTPUT_FILE" or "OUTPUT_FILE DEPS_TARGET",
1928 where OUTPUT_FILE is the file to write deps info to
1929 and DEPS_TARGET is the target to mention in the deps. */
1930
1931 if (print_deps == 0
1932 && (getenv ("SUNPRO_DEPENDENCIES") != 0
1933 || getenv ("DEPENDENCIES_OUTPUT") != 0)) {
1934 char *spec = getenv ("DEPENDENCIES_OUTPUT");
1935 char *s;
1936 char *output_file;
1937
1938 if (spec == 0) {
1939 spec = getenv ("SUNPRO_DEPENDENCIES");
1940 print_deps = 2;
1941 }
1942 else
1943 print_deps = 1;
1944
1945 /* Find the space before the DEPS_TARGET, if there is one. */
1946 s = index (spec, ' ');
1947 if (s) {
1948 deps_target = s + 1;
1949 output_file = xmalloc (s - spec + 1);
1950 bcopy (spec, output_file, s - spec);
1951 output_file[s - spec] = 0;
1952 } else {
1953 deps_target = 0;
1954 output_file = spec;
1955 }
1956
1957 deps_file = output_file;
1958 deps_mode = "a";
1959 }
1960
1961 /* For -M, print the expected object file name
1962 as the target of this Make-rule. */
1963 if (print_deps) {
1964 deps_allocated_size = 200;
1965 deps_buffer = xmalloc (deps_allocated_size);
1966 deps_buffer[0] = 0;
1967 deps_size = 0;
1968 deps_column = 0;
1969
1970 if (deps_target) {
1971 deps_output (deps_target, ':');
1972 } else if (*in_fname == 0) {
1973 deps_output ("-", ':');
1974 } else {
1975 char *p, *q;
1976 int len;
1977
1978 q = base_name (in_fname);
1979
1980 /* Copy remainder to mungable area. */
1981 p = (char *) alloca (strlen(q) + 8);
1982 strcpy (p, q);
1983
1984 /* Output P, but remove known suffixes. */
1985 len = strlen (p);
1986 q = p + len;
1987 if (len >= 2
1988 && p[len - 2] == '.'
1989 && index("cCsSm", p[len - 1]))
1990 q = p + (len - 2);
1991 else if (len >= 3
1992 && p[len - 3] == '.'
1993 && p[len - 2] == 'c'
1994 && p[len - 1] == 'c')
1995 q = p + (len - 3);
1996 else if (len >= 4
1997 && p[len - 4] == '.'
1998 && p[len - 3] == 'c'
1999 && p[len - 2] == 'x'
2000 && p[len - 1] == 'x')
2001 q = p + (len - 4);
2002 else if (len >= 4
2003 && p[len - 4] == '.'
2004 && p[len - 3] == 'c'
2005 && p[len - 2] == 'p'
2006 && p[len - 1] == 'p')
2007 q = p + (len - 4);
2008
2009 /* Supply our own suffix. */
2010 strcpy (q, OBJECT_SUFFIX);
2011
2012 deps_output (p, ':');
2013 }
2014
2015 deps_output (in_fname, ' ');
2016 }
2017
2018 /* Scan the -imacros files before the main input.
2019 Much like #including them, but with no_output set
2020 so that only their macro definitions matter. */
2021
2022 no_output++; no_record_file++;
2023 for (i = 1; i < argc; i++)
2024 if (pend_files[i]) {
2025 struct include_file *inc;
2026 int fd = open_include_file (pend_files[i], NULL_PTR, NULL_PTR, &inc);
2027 if (fd < 0) {
2028 perror_with_name (pend_files[i]);
2029 return FATAL_EXIT_CODE;
2030 }
2031 finclude (fd, inc, &outbuf, 0, NULL_PTR);
2032 }
2033 no_output--; no_record_file--;
2034
2035 /* Copy the entire contents of the main input file into
2036 the stacked input buffer previously allocated for it. */
2037
2038 /* JF check for stdin */
2039 if (in_fname == NULL || *in_fname == 0) {
2040 in_fname = "";
2041 f = 0;
2042 } else if ((f = open (in_fname, O_RDONLY, 0666)) < 0)
2043 goto perror;
2044
2045 if (fstat (f, &st) != 0)
2046 pfatal_with_name (in_fname);
2047 fp->nominal_fname = fp->fname = in_fname;
2048 fp->nominal_fname_len = strlen (in_fname);
2049 fp->lineno = 1;
2050 fp->system_header_p = 0;
2051 /* JF all this is mine about reading pipes and ttys */
2052 if (! S_ISREG (st.st_mode)) {
2053 /* Read input from a file that is not a normal disk file.
2054 We cannot preallocate a buffer with the correct size,
2055 so we must read in the file a piece at the time and make it bigger. */
2056 int size;
2057 int bsize;
2058 int cnt;
2059
2060 if (S_ISDIR (st.st_mode))
2061 fatal ("Input file `%s' is a directory", in_fname);
2062
2063 bsize = 2000;
2064 size = 0;
2065 fp->buf = (U_CHAR *) xmalloc (bsize + 2);
2066 for (;;) {
2067 cnt = safe_read (f, (char *) fp->buf + size, bsize - size);
2068 if (cnt < 0) goto perror; /* error! */
2069 size += cnt;
2070 if (size != bsize) break; /* End of file */
2071 bsize *= 2;
2072 fp->buf = (U_CHAR *) xrealloc (fp->buf, bsize + 2);
2073 }
2074 fp->length = size;
2075 } else {
2076 /* Read a file whose size we can determine in advance.
2077 For the sake of VMS, st.st_size is just an upper bound. */
2078 size_t s = (size_t) st.st_size;
2079 if (s != st.st_size || s + 2 < s)
2080 memory_full ();
2081 fp->buf = (U_CHAR *) xmalloc (s + 2);
2082 fp->length = safe_read (f, (char *) fp->buf, s);
2083 if (fp->length < 0) goto perror;
2084 }
2085 fp->bufp = fp->buf;
2086 fp->if_stack = if_stack;
2087
2088 /* Make sure data ends with a newline. And put a null after it. */
2089
2090 if ((fp->length > 0 && fp->buf[fp->length - 1] != '\n')
2091 /* Backslash-newline at end is not good enough. */
2092 || (fp->length > 1 && fp->buf[fp->length - 2] == '\\')) {
2093 fp->buf[fp->length++] = '\n';
2094 missing_newline = 1;
2095 }
2096 fp->buf[fp->length] = '\0';
2097
2098 /* Unless inhibited, convert trigraphs in the input. */
2099
2100 if (!no_trigraphs)
2101 trigraph_pcp (fp);
2102
2103 if (warn_white_space)
2104 check_white_space (fp);
2105
2106 /* Now that we know the input file is valid, open the output. */
2107
2108 if (!out_fname || !strcmp (out_fname, ""))
2109 out_fname = "stdout";
2110 else if (! freopen (out_fname, "w", stdout))
2111 pfatal_with_name (out_fname);
2112
2113 output_line_directive (fp, &outbuf, 0, same_file);
2114
2115 /* Scan the -include files before the main input. */
2116
2117 no_record_file++;
2118 for (i = 1; i < argc; i++)
2119 if (pend_includes[i]) {
2120 struct include_file *inc;
2121 int fd = open_include_file (pend_includes[i], NULL_PTR, NULL_PTR, &inc);
2122 if (fd < 0) {
2123 perror_with_name (pend_includes[i]);
2124 return FATAL_EXIT_CODE;
2125 }
2126 finclude (fd, inc, &outbuf, 0, NULL_PTR);
2127 }
2128 no_record_file--;
2129
2130 /* Scan the input, processing macros and directives. */
2131
2132 rescan (&outbuf, 0);
2133
2134 if (missing_newline)
2135 fp->lineno--;
2136
2137 if (pedantic && missing_newline)
2138 pedwarn ("file does not end in newline");
2139
2140 /* Now we have processed the entire input
2141 Write whichever kind of output has been requested. */
2142
2143 if (dump_macros == dump_only)
2144 dump_all_macros ();
2145 else if (! inhibit_output) {
2146 write_output ();
2147 }
2148
2149 if (print_deps) {
2150 /* Don't actually write the deps file if compilation has failed. */
2151 if (errors == 0) {
2152 if (deps_file && ! (deps_stream = fopen (deps_file, deps_mode)))
2153 pfatal_with_name (deps_file);
2154 fputs (deps_buffer, deps_stream);
2155 putc ('\n', deps_stream);
2156 if (deps_file) {
2157 if (ferror (deps_stream) || fclose (deps_stream) != 0)
2158 fatal ("I/O error on output");
2159 }
2160 }
2161 }
2162
2163 if (pcp_outfile && pcp_outfile != stdout
2164 && (ferror (pcp_outfile) || fclose (pcp_outfile) != 0))
2165 fatal ("I/O error on `-pcp' output");
2166
2167 if (ferror (stdout) || fclose (stdout) != 0)
2168 fatal ("I/O error on output");
2169
2170 if (errors)
2171 exit (FATAL_EXIT_CODE);
2172 exit (SUCCESS_EXIT_CODE);
2173
2174 perror:
2175 pfatal_with_name (in_fname);
2176 return 0;
2177 }
2178 \f
2179 /* Given a colon-separated list of file names PATH,
2180 add all the names to the search path for include files. */
2181
2182 static void
2183 path_include (path)
2184 char *path;
2185 {
2186 char *p;
2187
2188 p = path;
2189
2190 if (*p)
2191 while (1) {
2192 char *q = p;
2193 char c;
2194 struct file_name_list *dirtmp;
2195
2196 /* Find the end of this name. */
2197 while ((c = *q++) != PATH_SEPARATOR && c)
2198 continue;
2199
2200 q[-1] = 0;
2201 dirtmp = new_include_prefix (last_include, NULL_PTR,
2202 "", p == q ? "." : p);
2203 q[-1] = c;
2204 append_include_chain (dirtmp, dirtmp);
2205
2206 /* Advance past this name. */
2207 p = q;
2208 if (! c)
2209 break;
2210 }
2211 }
2212 \f
2213 /* Return the address of the first character in S that equals C.
2214 S is an array of length N, possibly containing '\0's, and followed by '\0'.
2215 Return 0 if there is no such character. Assume that C itself is not '\0'.
2216 If we knew we could use memchr, we could just invoke memchr (S, C, N),
2217 but unfortunately memchr isn't autoconfigured yet. */
2218
2219 static U_CHAR *
2220 index0 (s, c, n)
2221 U_CHAR *s;
2222 int c;
2223 size_t n;
2224 {
2225 char *p = (char *) s;
2226 for (;;) {
2227 char *q = index (p, c);
2228 if (q)
2229 return (U_CHAR *) q;
2230 else {
2231 size_t l = strlen (p);
2232 if (l == n)
2233 return 0;
2234 l++;
2235 p += l;
2236 n -= l;
2237 }
2238 }
2239 }
2240 \f
2241 /* Pre-C-Preprocessor to translate ANSI trigraph idiocy in BUF
2242 before main CCCP processing. Name `pcp' is also in honor of the
2243 drugs the trigraph designers must have been on.
2244
2245 Using an extra pass through the buffer takes a little extra time,
2246 but is infinitely less hairy than trying to handle trigraphs inside
2247 strings, etc. everywhere, and also makes sure that trigraphs are
2248 only translated in the top level of processing. */
2249
2250 static void
2251 trigraph_pcp (buf)
2252 FILE_BUF *buf;
2253 {
2254 register U_CHAR c, *fptr, *bptr, *sptr, *lptr;
2255 int len;
2256
2257 fptr = bptr = sptr = buf->buf;
2258 lptr = fptr + buf->length;
2259 while ((sptr = index0 (sptr, '?', (size_t) (lptr - sptr))) != NULL) {
2260 if (*++sptr != '?')
2261 continue;
2262 switch (*++sptr) {
2263 case '=':
2264 c = '#';
2265 break;
2266 case '(':
2267 c = '[';
2268 break;
2269 case '/':
2270 c = '\\';
2271 break;
2272 case ')':
2273 c = ']';
2274 break;
2275 case '\'':
2276 c = '^';
2277 break;
2278 case '<':
2279 c = '{';
2280 break;
2281 case '!':
2282 c = '|';
2283 break;
2284 case '>':
2285 c = '}';
2286 break;
2287 case '-':
2288 c = '~';
2289 break;
2290 case '?':
2291 sptr--;
2292 continue;
2293 default:
2294 continue;
2295 }
2296 len = sptr - fptr - 2;
2297
2298 /* BSD doc says bcopy () works right for overlapping strings. In ANSI
2299 C, this will be memmove (). */
2300 if (bptr != fptr && len > 0)
2301 bcopy ((char *) fptr, (char *) bptr, len);
2302
2303 bptr += len;
2304 *bptr++ = c;
2305 fptr = ++sptr;
2306 }
2307 len = buf->length - (fptr - buf->buf);
2308 if (bptr != fptr && len > 0)
2309 bcopy ((char *) fptr, (char *) bptr, len);
2310 buf->length -= fptr - bptr;
2311 buf->buf[buf->length] = '\0';
2312 if (warn_trigraphs && fptr != bptr)
2313 warning_with_line (0, "%lu trigraph(s) encountered",
2314 (unsigned long) (fptr - bptr) / 2);
2315 }
2316
2317 /* Warn about white space between backslash and end of line. */
2318
2319 static void
2320 check_white_space (buf)
2321 FILE_BUF *buf;
2322 {
2323 register U_CHAR *sptr = buf->buf;
2324 register U_CHAR *lptr = sptr + buf->length;
2325 register U_CHAR *nptr;
2326 int line = 0;
2327
2328 nptr = sptr = buf->buf;
2329 lptr = sptr + buf->length;
2330 for (nptr = sptr;
2331 (nptr = index0 (nptr, '\n', (size_t) (lptr - nptr))) != NULL;
2332 nptr ++) {
2333 register U_CHAR *p = nptr;
2334 line++;
2335 for (p = nptr; sptr < p; p--) {
2336 if (! is_hor_space[p[-1]]) {
2337 if (p[-1] == '\\' && p != nptr)
2338 warning_with_line (line,
2339 "`\\' followed by white space at end of line");
2340 break;
2341 }
2342 }
2343 }
2344 }
2345 \f
2346 /* Move all backslash-newline pairs out of embarrassing places.
2347 Exchange all such pairs following BP
2348 with any potentially-embarrassing characters that follow them.
2349 Potentially-embarrassing characters are / and *
2350 (because a backslash-newline inside a comment delimiter
2351 would cause it not to be recognized).
2352 We assume that *BP == '\\'. */
2353
2354 static void
2355 newline_fix (bp)
2356 U_CHAR *bp;
2357 {
2358 register U_CHAR *p = bp;
2359
2360 /* First count the backslash-newline pairs here. */
2361 do {
2362 if (p[1] != '\n')
2363 break;
2364 p += 2;
2365 } while (*p == '\\');
2366
2367 /* What follows the backslash-newlines is not embarrassing. */
2368
2369 if (*p != '/' && *p != '*')
2370 /* What follows the backslash-newlines is not embarrassing. */
2371 return;
2372
2373 /* Copy all potentially embarrassing characters
2374 that follow the backslash-newline pairs
2375 down to where the pairs originally started. */
2376 do
2377 *bp++ = *p++;
2378 while (*p == '*' || *p == '/');
2379
2380 /* Now write the same number of pairs after the embarrassing chars. */
2381 while (bp < p) {
2382 *bp++ = '\\';
2383 *bp++ = '\n';
2384 }
2385 }
2386
2387 /* Like newline_fix but for use within a directive-name.
2388 Move any backslash-newlines up past any following symbol constituents. */
2389
2390 static void
2391 name_newline_fix (bp)
2392 U_CHAR *bp;
2393 {
2394 register U_CHAR *p = bp;
2395
2396 /* First count the backslash-newline pairs here. */
2397 do {
2398 if (p[1] != '\n')
2399 break;
2400 p += 2;
2401 } while (*p == '\\');
2402
2403 /* What follows the backslash-newlines is not embarrassing. */
2404
2405 if (!is_idchar[*p])
2406 /* What follows the backslash-newlines is not embarrassing. */
2407 return;
2408
2409 /* Copy all potentially embarrassing characters
2410 that follow the backslash-newline pairs
2411 down to where the pairs originally started. */
2412 do
2413 *bp++ = *p++;
2414 while (is_idchar[*p]);
2415
2416 /* Now write the same number of pairs after the embarrassing chars. */
2417 while (bp < p) {
2418 *bp++ = '\\';
2419 *bp++ = '\n';
2420 }
2421 }
2422 \f
2423 /* Look for lint commands in comments.
2424
2425 When we come in here, ibp points into a comment. Limit is as one expects.
2426 scan within the comment -- it should start, after lwsp, with a lint command.
2427 If so that command is returned as a (constant) string.
2428
2429 Upon return, any arg will be pointed to with argstart and will be
2430 arglen long. Note that we don't parse that arg since it will just
2431 be printed out again. */
2432
2433 static char *
2434 get_lintcmd (ibp, limit, argstart, arglen, cmdlen)
2435 register U_CHAR *ibp;
2436 register U_CHAR *limit;
2437 U_CHAR **argstart; /* point to command arg */
2438 int *arglen, *cmdlen; /* how long they are */
2439 {
2440 HOST_WIDEST_INT linsize;
2441 register U_CHAR *numptr; /* temp for arg parsing */
2442
2443 *arglen = 0;
2444
2445 SKIP_WHITE_SPACE (ibp);
2446
2447 if (ibp >= limit) return NULL;
2448
2449 linsize = limit - ibp;
2450
2451 /* Oh, I wish C had lexical functions... hell, I'll just open-code the set */
2452 if ((linsize >= 10) && !bcmp (ibp, "NOTREACHED", 10)) {
2453 *cmdlen = 10;
2454 return "NOTREACHED";
2455 }
2456 if ((linsize >= 8) && !bcmp (ibp, "ARGSUSED", 8)) {
2457 *cmdlen = 8;
2458 return "ARGSUSED";
2459 }
2460 if ((linsize >= 11) && !bcmp (ibp, "LINTLIBRARY", 11)) {
2461 *cmdlen = 11;
2462 return "LINTLIBRARY";
2463 }
2464 if ((linsize >= 7) && !bcmp (ibp, "VARARGS", 7)) {
2465 *cmdlen = 7;
2466 ibp += 7; linsize -= 7;
2467 if ((linsize == 0) || ! ISDIGIT (*ibp)) return "VARARGS";
2468
2469 /* OK, read a number */
2470 for (numptr = *argstart = ibp; (numptr < limit) && ISDIGIT (*numptr);
2471 numptr++);
2472 *arglen = numptr - *argstart;
2473 return "VARARGS";
2474 }
2475 return NULL;
2476 }
2477 \f
2478 /*
2479 * The main loop of the program.
2480 *
2481 * Read characters from the input stack, transferring them to the
2482 * output buffer OP.
2483 *
2484 * Macros are expanded and push levels on the input stack.
2485 * At the end of such a level it is popped off and we keep reading.
2486 * At the end of any other kind of level, we return.
2487 * #-directives are handled, except within macros.
2488 *
2489 * If OUTPUT_MARKS is nonzero, keep Newline markers found in the input
2490 * and insert them when appropriate. This is set while scanning macro
2491 * arguments before substitution. It is zero when scanning for final output.
2492 * There are two types of Newline markers:
2493 * * Newline - follows a macro name that was not expanded
2494 * because it appeared inside an expansion of the same macro.
2495 * This marker prevents future expansion of that identifier.
2496 * When the input is rescanned into the final output, these are deleted.
2497 * These are also deleted by ## concatenation.
2498 * * Newline Space (or Newline and any other whitespace character)
2499 * stands for a place that tokens must be separated or whitespace
2500 * is otherwise desirable, but where the ANSI standard specifies there
2501 * is no whitespace. This marker turns into a Space (or whichever other
2502 * whitespace char appears in the marker) in the final output,
2503 * but it turns into nothing in an argument that is stringified with #.
2504 * Such stringified arguments are the only place where the ANSI standard
2505 * specifies with precision that whitespace may not appear.
2506 *
2507 * During this function, IP->bufp is kept cached in IBP for speed of access.
2508 * Likewise, OP->bufp is kept in OBP. Before calling a subroutine
2509 * IBP, IP and OBP must be copied back to memory. IP and IBP are
2510 * copied back with the RECACHE macro. OBP must be copied back from OP->bufp
2511 * explicitly, and before RECACHE, since RECACHE uses OBP.
2512 */
2513
2514 static void
2515 rescan (op, output_marks)
2516 FILE_BUF *op;
2517 int output_marks;
2518 {
2519 /* Character being scanned in main loop. */
2520 register U_CHAR c;
2521
2522 /* Length of pending accumulated identifier. */
2523 register int ident_length = 0;
2524
2525 /* Hash code of pending accumulated identifier. */
2526 register int hash = 0;
2527
2528 /* Current input level (&instack[indepth]). */
2529 FILE_BUF *ip;
2530
2531 /* Pointer for scanning input. */
2532 register U_CHAR *ibp;
2533
2534 /* Pointer to end of input. End of scan is controlled by LIMIT. */
2535 register U_CHAR *limit;
2536
2537 /* Pointer for storing output. */
2538 register U_CHAR *obp;
2539
2540 /* REDO_CHAR is nonzero if we are processing an identifier
2541 after backing up over the terminating character.
2542 Sometimes we process an identifier without backing up over
2543 the terminating character, if the terminating character
2544 is not special. Backing up is done so that the terminating character
2545 will be dispatched on again once the identifier is dealt with. */
2546 int redo_char = 0;
2547
2548 /* 1 if within an identifier inside of which a concatenation
2549 marker (Newline -) has been seen. */
2550 int concatenated = 0;
2551
2552 /* While scanning a comment or a string constant,
2553 this records the line it started on, for error messages. */
2554 int start_line;
2555
2556 /* Record position of last `real' newline. */
2557 U_CHAR *beg_of_line;
2558
2559 /* Pop the innermost input stack level, assuming it is a macro expansion. */
2560
2561 #define POPMACRO \
2562 do { ip->macro->type = T_MACRO; \
2563 if (ip->free_ptr) free (ip->free_ptr); \
2564 --indepth; } while (0)
2565
2566 /* Reload `rescan's local variables that describe the current
2567 level of the input stack. */
2568
2569 #define RECACHE \
2570 do { ip = &instack[indepth]; \
2571 ibp = ip->bufp; \
2572 limit = ip->buf + ip->length; \
2573 op->bufp = obp; \
2574 check_expand (op, limit - ibp); \
2575 beg_of_line = 0; \
2576 obp = op->bufp; } while (0)
2577
2578 if (no_output && instack[indepth].fname != 0)
2579 skip_if_group (&instack[indepth], 1, NULL);
2580
2581 obp = op->bufp;
2582 RECACHE;
2583
2584 beg_of_line = ibp;
2585
2586 /* Our caller must always put a null after the end of
2587 the input at each input stack level. */
2588 if (*limit != 0)
2589 abort ();
2590
2591 while (1) {
2592 c = *ibp++;
2593 *obp++ = c;
2594
2595 switch (c) {
2596 case '\\':
2597 if (*ibp == '\n' && !ip->macro) {
2598 /* At the top level, always merge lines ending with backslash-newline,
2599 even in middle of identifier. But do not merge lines in a macro,
2600 since backslash might be followed by a newline-space marker. */
2601 ++ibp;
2602 ++ip->lineno;
2603 --obp; /* remove backslash from obuf */
2604 break;
2605 }
2606 /* If ANSI, backslash is just another character outside a string. */
2607 if (!traditional)
2608 goto randomchar;
2609 /* Otherwise, backslash suppresses specialness of following char,
2610 so copy it here to prevent the switch from seeing it.
2611 But first get any pending identifier processed. */
2612 if (ident_length > 0)
2613 goto specialchar;
2614 if (ibp < limit)
2615 *obp++ = *ibp++;
2616 break;
2617
2618 case '%':
2619 if (ident_length || ip->macro || traditional)
2620 goto randomchar;
2621 while (*ibp == '\\' && ibp[1] == '\n') {
2622 ibp += 2;
2623 ++ip->lineno;
2624 }
2625 if (*ibp != ':')
2626 break;
2627 /* Treat this %: digraph as if it were #. */
2628 /* Fall through. */
2629
2630 case '#':
2631 if (assertions_flag) {
2632 if (ident_length)
2633 goto specialchar;
2634 /* Copy #foo (bar lose) without macro expansion. */
2635 obp[-1] = '#'; /* In case it was '%'. */
2636 SKIP_WHITE_SPACE (ibp);
2637 while (is_idchar[*ibp])
2638 *obp++ = *ibp++;
2639 SKIP_WHITE_SPACE (ibp);
2640 if (*ibp == '(') {
2641 ip->bufp = ibp;
2642 skip_paren_group (ip);
2643 bcopy ((char *) ibp, (char *) obp, ip->bufp - ibp);
2644 obp += ip->bufp - ibp;
2645 ibp = ip->bufp;
2646 }
2647 break;
2648 }
2649
2650 /* If this is expanding a macro definition, don't recognize
2651 preprocessing directives. */
2652 if (ip->macro != 0)
2653 goto randomchar;
2654 /* If this is expand_into_temp_buffer,
2655 don't recognize them either. Warn about them
2656 only after an actual newline at this level,
2657 not at the beginning of the input level. */
2658 if (! ip->fname) {
2659 if (ip->buf != beg_of_line)
2660 warning ("preprocessing directive not recognized within macro arg");
2661 goto randomchar;
2662 }
2663 if (ident_length)
2664 goto specialchar;
2665
2666
2667 /* # keyword: a # must be first nonblank char on the line */
2668 if (beg_of_line == 0)
2669 goto randomchar;
2670 {
2671 U_CHAR *bp;
2672
2673 /* Scan from start of line, skipping whitespace, comments
2674 and backslash-newlines, and see if we reach this #.
2675 If not, this # is not special. */
2676 bp = beg_of_line;
2677 /* If -traditional, require # to be at beginning of line. */
2678 if (!traditional) {
2679 while (1) {
2680 if (is_hor_space[*bp])
2681 bp++;
2682 else if (*bp == '\\' && bp[1] == '\n')
2683 bp += 2;
2684 else if (*bp == '/' && bp[1] == '*') {
2685 bp += 2;
2686 while (1)
2687 {
2688 if (*bp == '*')
2689 {
2690 if (bp[1] == '/')
2691 {
2692 bp += 2;
2693 break;
2694 }
2695 }
2696 else
2697 {
2698 #ifdef MULTIBYTE_CHARS
2699 int length;
2700 length = local_mblen (bp, limit - bp);
2701 if (length > 1)
2702 bp += (length - 1);
2703 #endif
2704 }
2705 bp++;
2706 }
2707 }
2708 /* There is no point in trying to deal with C++ // comments here,
2709 because if there is one, then this # must be part of the
2710 comment and we would never reach here. */
2711 else break;
2712 }
2713 if (c == '%') {
2714 if (bp[0] != '%')
2715 break;
2716 while (bp[1] == '\\' && bp[2] == '\n')
2717 bp += 2;
2718 if (bp + 1 != ibp)
2719 break;
2720 /* %: appears at start of line; skip past the ':' too. */
2721 bp++;
2722 ibp++;
2723 }
2724 }
2725 if (bp + 1 != ibp)
2726 goto randomchar;
2727 }
2728
2729 /* This # can start a directive. */
2730
2731 --obp; /* Don't copy the '#' */
2732
2733 ip->bufp = ibp;
2734 op->bufp = obp;
2735 if (! handle_directive (ip, op)) {
2736 #ifdef USE_C_ALLOCA
2737 alloca (0);
2738 #endif
2739 /* Not a known directive: treat it as ordinary text.
2740 IP, OP, IBP, etc. have not been changed. */
2741 if (no_output && instack[indepth].fname) {
2742 /* If not generating expanded output,
2743 what we do with ordinary text is skip it.
2744 Discard everything until next # directive. */
2745 skip_if_group (&instack[indepth], 1, 0);
2746 RECACHE;
2747 beg_of_line = ibp;
2748 break;
2749 }
2750 *obp++ = '#'; /* Copy # (even if it was originally %:). */
2751 /* Don't expand an identifier that could be a macro directive.
2752 (Section 3.8.3 of the ANSI C standard) */
2753 SKIP_WHITE_SPACE (ibp);
2754 if (is_idstart[*ibp])
2755 {
2756 *obp++ = *ibp++;
2757 while (is_idchar[*ibp])
2758 *obp++ = *ibp++;
2759 }
2760 goto randomchar;
2761 }
2762 #ifdef USE_C_ALLOCA
2763 alloca (0);
2764 #endif
2765 /* A # directive has been successfully processed. */
2766 /* If not generating expanded output, ignore everything until
2767 next # directive. */
2768 if (no_output && instack[indepth].fname)
2769 skip_if_group (&instack[indepth], 1, 0);
2770 obp = op->bufp;
2771 RECACHE;
2772 beg_of_line = ibp;
2773 break;
2774
2775 case '\"': /* skip quoted string */
2776 case '\'':
2777 /* A single quoted string is treated like a double -- some
2778 programs (e.g., troff) are perverse this way */
2779
2780 /* Handle any pending identifier;
2781 but the L in L'...' or L"..." is not an identifier. */
2782 if (ident_length) {
2783 if (! (ident_length == 1 && hash == HASHSTEP (0, 'L')))
2784 goto specialchar;
2785 ident_length = hash = 0;
2786 }
2787
2788 start_line = ip->lineno;
2789
2790 /* Skip ahead to a matching quote. */
2791
2792 while (1) {
2793 if (ibp >= limit) {
2794 if (ip->macro != 0) {
2795 /* try harder: this string crosses a macro expansion boundary.
2796 This can happen naturally if -traditional.
2797 Otherwise, only -D can make a macro with an unmatched quote. */
2798 POPMACRO;
2799 RECACHE;
2800 continue;
2801 }
2802 if (!traditional) {
2803 error_with_line (line_for_error (start_line),
2804 "unterminated string or character constant");
2805 if (multiline_string_line) {
2806 error_with_line (multiline_string_line,
2807 "possible real start of unterminated constant");
2808 multiline_string_line = 0;
2809 }
2810 }
2811 break;
2812 }
2813 *obp++ = *ibp;
2814 switch (*ibp++) {
2815 case '\n':
2816 if (warn_white_space && ip->fname && is_hor_space[ibp[-2]])
2817 warning ("white space at end of line in string");
2818 ++ip->lineno;
2819 ++op->lineno;
2820 /* Traditionally, end of line ends a string constant with no error.
2821 So exit the loop and record the new line. */
2822 if (traditional) {
2823 beg_of_line = ibp;
2824 goto while2end;
2825 }
2826 if (c == '\'') {
2827 error_with_line (line_for_error (start_line),
2828 "unterminated character constant");
2829 goto while2end;
2830 }
2831 if (multiline_string_line == 0) {
2832 if (pedantic)
2833 pedwarn_with_line (line_for_error (start_line),
2834 "string constant runs past end of line");
2835 multiline_string_line = ip->lineno - 1;
2836 }
2837 break;
2838
2839 case '\\':
2840 if (*ibp == '\n') {
2841 /* Backslash newline is replaced by nothing at all, but
2842 keep the line counts correct. But if we are reading
2843 from a macro, keep the backslash newline, since backslash
2844 newlines have already been processed. */
2845 if (ip->macro) {
2846 *obp++ = '\n';
2847 ++op->lineno;
2848 } else
2849 --obp;
2850 ++ibp;
2851 ++ip->lineno;
2852 } else {
2853 /* ANSI stupidly requires that in \\ the second \
2854 is *not* prevented from combining with a newline. */
2855 if (!ip->macro) {
2856 while (*ibp == '\\' && ibp[1] == '\n') {
2857 *obp++ = *ibp++;
2858 *obp++ = *ibp++;
2859 ++ip->lineno;
2860 ++op->lineno;
2861 }
2862 }
2863 *obp++ = *ibp++;
2864 }
2865 break;
2866
2867 case '\"':
2868 case '\'':
2869 if (ibp[-1] == c)
2870 goto while2end;
2871 break;
2872 #ifdef MULTIBYTE_CHARS
2873 default:
2874 {
2875 int length;
2876 --ibp;
2877 length = local_mblen (ibp, limit - ibp);
2878 if (length > 0)
2879 {
2880 --obp;
2881 bcopy (ibp, obp, length);
2882 obp += length;
2883 ibp += length;
2884 }
2885 else
2886 ++ibp;
2887 }
2888 break;
2889 #endif
2890 }
2891 }
2892 while2end:
2893 break;
2894
2895 case '/':
2896 if (ip->macro != 0)
2897 goto randomchar;
2898 if (*ibp == '\\')
2899 newline_fix (ibp);
2900 if (*ibp != '*'
2901 && !(cplusplus_comments && *ibp == '/'))
2902 goto randomchar;
2903 if (ident_length)
2904 goto specialchar;
2905
2906 if (*ibp == '/') {
2907 /* C++ style comment... */
2908 start_line = ip->lineno;
2909
2910 /* Comments are equivalent to spaces. */
2911 if (! put_out_comments)
2912 obp[-1] = ' ';
2913
2914 {
2915 U_CHAR *before_bp = ibp;
2916
2917 while (++ibp < limit) {
2918 if (*ibp == '\n')
2919 {
2920 if (put_out_comments) {
2921 bcopy ((char *) before_bp, (char *) obp, ibp - before_bp);
2922 obp += ibp - before_bp;
2923 }
2924 break;
2925 }
2926 if (*ibp == '\\')
2927 {
2928 if (ibp + 1 < limit && ibp[1] == '\n')
2929 {
2930 if (warn_comments)
2931 warning ("multiline `//' comment");
2932 ++ip->lineno;
2933 /* Copy the newline into the output buffer, in order to
2934 avoid the pain of a #line every time a multiline comment
2935 is seen. */
2936 if (!put_out_comments)
2937 *obp++ = '\n';
2938 ++op->lineno;
2939 ++ibp;
2940 }
2941 }
2942 else
2943 {
2944 #ifdef MULTIBYTE_CHARS
2945 int length;
2946 length = local_mblen (ibp, limit - ibp);
2947 if (length > 1)
2948 ibp += (length - 1);
2949 #endif
2950 }
2951 }
2952 break;
2953 }
2954 }
2955
2956 /* Ordinary C comment. Skip it, optionally copying it to output. */
2957
2958 start_line = ip->lineno;
2959
2960 ++ibp; /* Skip the star. */
2961
2962 /* If this cpp is for lint, we peek inside the comments: */
2963 if (for_lint) {
2964 U_CHAR *argbp;
2965 int cmdlen, arglen;
2966 char *lintcmd = get_lintcmd (ibp, limit, &argbp, &arglen, &cmdlen);
2967
2968 if (lintcmd != NULL) {
2969 op->bufp = obp;
2970 check_expand (op, cmdlen + arglen + 14);
2971 obp = op->bufp;
2972 /* I believe it is always safe to emit this newline: */
2973 obp[-1] = '\n';
2974 bcopy ("#pragma lint ", (char *) obp, 13);
2975 obp += 13;
2976 bcopy (lintcmd, (char *) obp, cmdlen);
2977 obp += cmdlen;
2978
2979 if (arglen != 0) {
2980 *(obp++) = ' ';
2981 bcopy (argbp, (char *) obp, arglen);
2982 obp += arglen;
2983 }
2984
2985 /* OK, now bring us back to the state we were in before we entered
2986 this branch. We need #line because the #pragma's newline always
2987 messes up the line count. */
2988 op->bufp = obp;
2989 output_line_directive (ip, op, 0, same_file);
2990 check_expand (op, limit - ibp + 2);
2991 obp = op->bufp;
2992 *(obp++) = '/';
2993 }
2994 }
2995
2996 /* Comments are equivalent to spaces.
2997 Note that we already output the slash; we might not want it.
2998 For -traditional, a comment is equivalent to nothing. */
2999 if (! put_out_comments) {
3000 if (traditional)
3001 obp--;
3002 else
3003 obp[-1] = ' ';
3004 }
3005 else
3006 *obp++ = '*';
3007
3008 {
3009 U_CHAR *before_bp = ibp;
3010
3011 for (;;) {
3012 switch (*ibp++) {
3013 case '*':
3014 if (ibp[-2] == '/' && warn_comments)
3015 warning ("`/*' within comment");
3016 if (*ibp == '\\')
3017 newline_fix (ibp);
3018 if (*ibp == '/')
3019 goto comment_end;
3020 break;
3021
3022 case '\n':
3023 ++ip->lineno;
3024 /* Copy the newline into the output buffer, in order to
3025 avoid the pain of a #line every time a multiline comment
3026 is seen. */
3027 if (!put_out_comments)
3028 *obp++ = '\n';
3029 ++op->lineno;
3030 break;
3031
3032 case 0:
3033 if (limit < ibp) {
3034 error_with_line (line_for_error (start_line),
3035 "unterminated comment");
3036 goto limit_reached;
3037 }
3038 break;
3039 #ifdef MULTIBYTE_CHARS
3040 default:
3041 {
3042 int length;
3043 length = local_mblen (ibp, limit - ibp);
3044 if (length > 1)
3045 ibp += (length - 1);
3046 }
3047 break;
3048 #endif
3049 }
3050 }
3051 comment_end:
3052
3053 ibp++;
3054 if (put_out_comments) {
3055 bcopy ((char *) before_bp, (char *) obp, ibp - before_bp);
3056 obp += ibp - before_bp;
3057 }
3058 }
3059 break;
3060
3061 case '$':
3062 if (! is_idchar['$'])
3063 goto randomchar;
3064 if (pedantic)
3065 pedwarn ("`$' in identifier");
3066 goto letter;
3067
3068 case '0': case '1': case '2': case '3': case '4':
3069 case '5': case '6': case '7': case '8': case '9':
3070 /* If digit is not part of identifier, it starts a number,
3071 which means that following letters are not an identifier.
3072 "0x5" does not refer to an identifier "x5".
3073 So copy all alphanumerics that follow without accumulating
3074 as an identifier. Periods also, for sake of "3.e7". */
3075
3076 if (ident_length == 0) {
3077 for (;;) {
3078 if (!ip->macro) {
3079 while (ibp[0] == '\\' && ibp[1] == '\n') {
3080 ++ip->lineno;
3081 ibp += 2;
3082 }
3083 }
3084 c = *ibp++;
3085 if (!is_idchar[c] && c != '.') {
3086 --ibp;
3087 break;
3088 }
3089 *obp++ = c;
3090 /* A sign can be part of a preprocessing number
3091 if it follows an `e' or `p'. */
3092 if (c == 'e' || c == 'E' || c == 'p' || c == 'P') {
3093 if (!ip->macro) {
3094 while (ibp[0] == '\\' && ibp[1] == '\n') {
3095 ++ip->lineno;
3096 ibp += 2;
3097 }
3098 }
3099 if (*ibp == '+' || *ibp == '-') {
3100 *obp++ = *ibp++;
3101 /* But traditional C does not let the token go past the sign,
3102 and C89 does not allow `p'. */
3103 if (traditional || (c89 && (c == 'p' || c == 'P')))
3104 break;
3105 }
3106 }
3107 }
3108 break;
3109 }
3110 /* fall through */
3111
3112 case '_':
3113 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
3114 case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
3115 case 'm': case 'n': case 'o': case 'p': case 'q': case 'r':
3116 case 's': case 't': case 'u': case 'v': case 'w': case 'x':
3117 case 'y': case 'z':
3118 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
3119 case 'G': case 'H': case 'I': case 'J': case 'K': case 'L':
3120 case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R':
3121 case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
3122 case 'Y': case 'Z':
3123 letter:
3124 ident_length++;
3125 /* Compute step of hash function, to avoid a proc call on every token */
3126 hash = HASHSTEP (hash, c);
3127 break;
3128
3129 case '\n':
3130 if (ip->fname == 0 && *ibp == '-') {
3131 /* Newline - inhibits expansion of preceding token.
3132 If expanding a macro arg, we keep the newline -.
3133 In final output, it is deleted.
3134 We recognize Newline - in macro bodies and macro args. */
3135 if (! concatenated) {
3136 ident_length = 0;
3137 hash = 0;
3138 }
3139 ibp++;
3140 if (!output_marks) {
3141 obp--;
3142 } else {
3143 /* If expanding a macro arg, keep the newline -. */
3144 *obp++ = '-';
3145 }
3146 break;
3147 }
3148
3149 /* If reprocessing a macro expansion, newline is a special marker. */
3150 else if (ip->macro != 0) {
3151 /* Newline White is a "funny space" to separate tokens that are
3152 supposed to be separate but without space between.
3153 Here White means any whitespace character.
3154 Newline - marks a recursive macro use that is not
3155 supposed to be expandable. */
3156
3157 if (is_space[*ibp]) {
3158 /* Newline Space does not prevent expansion of preceding token
3159 so expand the preceding token and then come back. */
3160 if (ident_length > 0)
3161 goto specialchar;
3162
3163 /* If generating final output, newline space makes a space. */
3164 if (!output_marks) {
3165 obp[-1] = *ibp++;
3166 /* And Newline Newline makes a newline, so count it. */
3167 if (obp[-1] == '\n')
3168 op->lineno++;
3169 } else {
3170 /* If expanding a macro arg, keep the newline space.
3171 If the arg gets stringified, newline space makes nothing. */
3172 *obp++ = *ibp++;
3173 }
3174 } else abort (); /* Newline followed by something random? */
3175 break;
3176 }
3177
3178 /* If there is a pending identifier, handle it and come back here. */
3179 if (ident_length > 0)
3180 goto specialchar;
3181
3182 beg_of_line = ibp;
3183
3184 /* Update the line counts and output a #line if necessary. */
3185 ++ip->lineno;
3186 ++op->lineno;
3187 if (ip->lineno != op->lineno) {
3188 op->bufp = obp;
3189 output_line_directive (ip, op, 1, same_file);
3190 check_expand (op, limit - ibp);
3191 obp = op->bufp;
3192 }
3193 break;
3194
3195 /* Come here either after (1) a null character that is part of the input
3196 or (2) at the end of the input, because there is a null there. */
3197 case 0:
3198 if (ibp <= limit)
3199 /* Our input really contains a null character. */
3200 goto randomchar;
3201
3202 limit_reached:
3203 /* At end of a macro-expansion level, pop it and read next level. */
3204 if (ip->macro != 0) {
3205 obp--;
3206 ibp--;
3207 /* If traditional, and we have an identifier that ends here,
3208 process it now, so we get the right error for recursion. */
3209 if (traditional && ident_length
3210 && ! is_idchar[*instack[indepth - 1].bufp]) {
3211 redo_char = 1;
3212 goto randomchar;
3213 }
3214 POPMACRO;
3215 RECACHE;
3216 break;
3217 }
3218
3219 /* If we don't have a pending identifier,
3220 return at end of input. */
3221 if (ident_length == 0) {
3222 obp--;
3223 ibp--;
3224 op->bufp = obp;
3225 ip->bufp = ibp;
3226 goto ending;
3227 }
3228
3229 /* If we do have a pending identifier, just consider this null
3230 a special character and arrange to dispatch on it again.
3231 The second time, IDENT_LENGTH will be zero so we will return. */
3232
3233 /* Fall through */
3234
3235 specialchar:
3236
3237 /* Handle the case of a character such as /, ', " or null
3238 seen following an identifier. Back over it so that
3239 after the identifier is processed the special char
3240 will be dispatched on again. */
3241
3242 ibp--;
3243 obp--;
3244 redo_char = 1;
3245
3246 default:
3247
3248 randomchar:
3249
3250 if (ident_length > 0) {
3251 register HASHNODE *hp;
3252
3253 /* We have just seen an identifier end. If it's a macro, expand it.
3254
3255 IDENT_LENGTH is the length of the identifier
3256 and HASH is its hash code.
3257
3258 The identifier has already been copied to the output,
3259 so if it is a macro we must remove it.
3260
3261 If REDO_CHAR is 0, the char that terminated the identifier
3262 has been skipped in the output and the input.
3263 OBP-IDENT_LENGTH-1 points to the identifier.
3264 If the identifier is a macro, we must back over the terminator.
3265
3266 If REDO_CHAR is 1, the terminating char has already been
3267 backed over. OBP-IDENT_LENGTH points to the identifier. */
3268
3269 if (!pcp_outfile || pcp_inside_if) {
3270 for (hp = hashtab[MAKE_POS (hash) % HASHSIZE]; hp != NULL;
3271 hp = hp->next) {
3272
3273 if (hp->length == ident_length) {
3274 int obufp_before_macroname;
3275 int op_lineno_before_macroname;
3276 register int i = ident_length;
3277 register U_CHAR *p = hp->name;
3278 register U_CHAR *q = obp - i;
3279 int disabled;
3280
3281 if (! redo_char)
3282 q--;
3283
3284 do { /* All this to avoid a strncmp () */
3285 if (*p++ != *q++)
3286 goto hashcollision;
3287 } while (--i);
3288
3289 /* We found a use of a macro name.
3290 see if the context shows it is a macro call. */
3291
3292 /* Back up over terminating character if not already done. */
3293 if (! redo_char) {
3294 ibp--;
3295 obp--;
3296 }
3297
3298 /* Save this as a displacement from the beginning of the output
3299 buffer. We can not save this as a position in the output
3300 buffer, because it may get realloc'ed by RECACHE. */
3301 obufp_before_macroname = (obp - op->buf) - ident_length;
3302 op_lineno_before_macroname = op->lineno;
3303
3304 if (hp->type == T_PCSTRING) {
3305 pcstring_used (hp); /* Mark the definition of this key
3306 as needed, ensuring that it
3307 will be output. */
3308 break; /* Exit loop, since the key cannot have a
3309 definition any longer. */
3310 }
3311
3312 /* Record whether the macro is disabled. */
3313 disabled = hp->type == T_DISABLED;
3314
3315 /* This looks like a macro ref, but if the macro was disabled,
3316 just copy its name and put in a marker if requested. */
3317
3318 if (disabled) {
3319 #if 0
3320 /* This error check caught useful cases such as
3321 #define foo(x,y) bar (x (y,0), y)
3322 foo (foo, baz) */
3323 if (traditional)
3324 error ("recursive use of macro `%s'", hp->name);
3325 #endif
3326
3327 if (output_marks) {
3328 check_expand (op, limit - ibp + 2);
3329 *obp++ = '\n';
3330 *obp++ = '-';
3331 }
3332 break;
3333 }
3334
3335 /* If macro wants an arglist, verify that a '(' follows.
3336 first skip all whitespace, copying it to the output
3337 after the macro name. Then, if there is no '(',
3338 decide this is not a macro call and leave things that way. */
3339 if ((hp->type == T_MACRO || hp->type == T_DISABLED)
3340 && hp->value.defn->nargs >= 0)
3341 {
3342 U_CHAR *old_ibp = ibp;
3343 U_CHAR *old_obp = obp;
3344 int old_iln = ip->lineno;
3345 int old_oln = op->lineno;
3346
3347 while (1) {
3348 /* Scan forward over whitespace, copying it to the output. */
3349 if (ibp == limit && ip->macro != 0) {
3350 POPMACRO;
3351 RECACHE;
3352 old_ibp = ibp;
3353 old_obp = obp;
3354 old_iln = ip->lineno;
3355 old_oln = op->lineno;
3356 }
3357 else if (is_space[*ibp]) {
3358 *obp++ = *ibp++;
3359 if (ibp[-1] == '\n') {
3360 if (ip->macro == 0) {
3361 /* Newline in a file. Count it. */
3362 ++ip->lineno;
3363 ++op->lineno;
3364 } else if (!output_marks) {
3365 /* A newline mark, and we don't want marks
3366 in the output. If it is newline-hyphen,
3367 discard it entirely. Otherwise, it is
3368 newline-whitechar, so keep the whitechar. */
3369 obp--;
3370 if (*ibp == '-')
3371 ibp++;
3372 else {
3373 if (*ibp == '\n')
3374 ++op->lineno;
3375 *obp++ = *ibp++;
3376 }
3377 } else {
3378 /* A newline mark; copy both chars to the output. */
3379 *obp++ = *ibp++;
3380 }
3381 }
3382 }
3383 else if (ip->macro)
3384 break;
3385 else if (*ibp == '/') {
3386 /* If a comment, copy it unchanged or discard it. */
3387 if (ibp[1] == '\\')
3388 newline_fix (ibp + 1);
3389 if (ibp[1] == '*') {
3390 if (put_out_comments) {
3391 *obp++ = '/';
3392 *obp++ = '*';
3393 } else if (! traditional) {
3394 *obp++ = ' ';
3395 }
3396 for (ibp += 2; ibp < limit; ibp++) {
3397 /* We need not worry about newline-marks,
3398 since they are never found in comments. */
3399 if (ibp[0] == '*') {
3400 if (ibp[1] == '\\')
3401 newline_fix (ibp + 1);
3402 if (ibp[1] == '/') {
3403 ibp += 2;
3404 if (put_out_comments) {
3405 *obp++ = '*';
3406 *obp++ = '/';
3407 }
3408 break;
3409 }
3410 }
3411 else if (*ibp == '\n') {
3412 /* Newline in a file. Count it. */
3413 ++ip->lineno;
3414 ++op->lineno;
3415 }
3416 else
3417 {
3418 #ifdef MULTIBYTE_CHARS
3419 int length;
3420 length = local_mblen (ibp, limit - ibp);
3421 if (length > 1)
3422 {
3423 if (put_out_comments)
3424 {
3425 bcopy (ibp, obp, length - 1);
3426 obp += length - 1;
3427 }
3428 ibp += (length - 1);
3429 }
3430 #endif
3431 }
3432 if (put_out_comments)
3433 *obp++ = *ibp;
3434 }
3435 } else if (ibp[1] == '/' && cplusplus_comments) {
3436 if (put_out_comments) {
3437 *obp++ = '/';
3438 *obp++ = '/';
3439 } else if (! traditional) {
3440 *obp++ = ' ';
3441 }
3442 for (ibp += 2; ; ibp++)
3443 {
3444 if (*ibp == '\n')
3445 break;
3446 if (*ibp == '\\' && ibp[1] == '\n')
3447 {
3448 if (put_out_comments)
3449 *obp++ = *ibp++;
3450 }
3451 else
3452 {
3453 #ifdef MULTIBYTE_CHARS
3454 int length;
3455 length = local_mblen (ibp, limit - ibp);
3456 if (length > 1)
3457 {
3458 if (put_out_comments)
3459 {
3460 bcopy (ibp, obp, length - 1);
3461 obp += length - 1;
3462 }
3463 ibp += (length - 1);
3464 }
3465 #endif
3466 }
3467 if (put_out_comments)
3468 *obp++ = *ibp;
3469 }
3470 } else
3471 break;
3472 }
3473 else if (ibp[0] == '\\' && ibp[1] == '\n') {
3474 ibp += 2;
3475 ++ip->lineno;
3476 }
3477 else break;
3478 }
3479 if (*ibp != '(') {
3480 /* It isn't a macro call.
3481 Put back the space that we just skipped. */
3482 ibp = old_ibp;
3483 obp = old_obp;
3484 ip->lineno = old_iln;
3485 op->lineno = old_oln;
3486 /* Exit the for loop. */
3487 break;
3488 }
3489 }
3490
3491 /* This is now known to be a macro call.
3492 Discard the macro name from the output,
3493 along with any following whitespace just copied,
3494 but preserve newlines if not outputting marks since this
3495 is more likely to do the right thing with line numbers. */
3496 obp = op->buf + obufp_before_macroname;
3497 if (output_marks)
3498 op->lineno = op_lineno_before_macroname;
3499 else {
3500 int newlines = op->lineno - op_lineno_before_macroname;
3501 while (0 < newlines--)
3502 *obp++ = '\n';
3503 }
3504
3505 /* Prevent accidental token-pasting with a character
3506 before the macro call. */
3507 if (!traditional && obp != op->buf) {
3508 switch (obp[-1]) {
3509 case '!': case '%': case '&': case '*':
3510 case '+': case '-': case '.': case '/':
3511 case ':': case '<': case '=': case '>':
3512 case '^': case '|':
3513 /* If we are expanding a macro arg, make a newline marker
3514 to separate the tokens. If we are making real output,
3515 a plain space will do. */
3516 if (output_marks)
3517 *obp++ = '\n';
3518 *obp++ = ' ';
3519 }
3520 }
3521
3522 /* Expand the macro, reading arguments as needed,
3523 and push the expansion on the input stack. */
3524 ip->bufp = ibp;
3525 op->bufp = obp;
3526 macroexpand (hp, op);
3527
3528 /* Reexamine input stack, since macroexpand has pushed
3529 a new level on it. */
3530 obp = op->bufp;
3531 RECACHE;
3532 break;
3533 }
3534 hashcollision:
3535 ;
3536 } /* End hash-table-search loop */
3537 }
3538 ident_length = hash = 0; /* Stop collecting identifier */
3539 redo_char = 0;
3540 concatenated = 0;
3541 } /* End if (ident_length > 0) */
3542 } /* End switch */
3543 } /* End per-char loop */
3544
3545 /* Come here to return -- but first give an error message
3546 if there was an unterminated successful conditional. */
3547 ending:
3548 if (if_stack != ip->if_stack)
3549 {
3550 char *str;
3551
3552 switch (if_stack->type)
3553 {
3554 case T_IF:
3555 str = "if";
3556 break;
3557 case T_IFDEF:
3558 str = "ifdef";
3559 break;
3560 case T_IFNDEF:
3561 str = "ifndef";
3562 break;
3563 case T_ELSE:
3564 str = "else";
3565 break;
3566 case T_ELIF:
3567 str = "elif";
3568 break;
3569 default:
3570 abort ();
3571 }
3572
3573 error_with_line (line_for_error (if_stack->lineno),
3574 "unterminated `#%s' conditional", str);
3575 }
3576 if_stack = ip->if_stack;
3577 }
3578 \f
3579 /*
3580 * Rescan a string into a temporary buffer and return the result
3581 * as a FILE_BUF. Note this function returns a struct, not a pointer.
3582 *
3583 * OUTPUT_MARKS nonzero means keep Newline markers found in the input
3584 * and insert such markers when appropriate. See `rescan' for details.
3585 * OUTPUT_MARKS is 1 for macroexpanding a macro argument separately
3586 * before substitution; it is 0 for other uses.
3587 */
3588 static FILE_BUF
3589 expand_to_temp_buffer (buf, limit, output_marks, assertions)
3590 U_CHAR *buf, *limit;
3591 int output_marks, assertions;
3592 {
3593 register FILE_BUF *ip;
3594 FILE_BUF obuf;
3595 int length = limit - buf;
3596 U_CHAR *buf1;
3597 int odepth = indepth;
3598 int save_assertions_flag = assertions_flag;
3599
3600 assertions_flag = assertions;
3601
3602 if (length < 0)
3603 abort ();
3604
3605 /* Set up the input on the input stack. */
3606
3607 buf1 = (U_CHAR *) alloca (length + 1);
3608 {
3609 register U_CHAR *p1 = buf;
3610 register U_CHAR *p2 = buf1;
3611
3612 while (p1 != limit)
3613 *p2++ = *p1++;
3614 }
3615 buf1[length] = 0;
3616
3617 /* Set up to receive the output. */
3618
3619 obuf.length = length * 2 + 100; /* Usually enough. Why be stingy? */
3620 obuf.bufp = obuf.buf = (U_CHAR *) xmalloc (obuf.length);
3621 obuf.nominal_fname = 0;
3622 obuf.inc = 0;
3623 obuf.dir = 0;
3624 obuf.fname = 0;
3625 obuf.macro = 0;
3626 obuf.if_stack = 0;
3627 obuf.free_ptr = 0;
3628 obuf.system_header_p = 0;
3629
3630 CHECK_DEPTH ({return obuf;});
3631
3632 ++indepth;
3633
3634 ip = &instack[indepth];
3635 ip->fname = 0;
3636 ip->nominal_fname = 0;
3637 ip->nominal_fname_len = 0;
3638 ip->inc = 0;
3639 ip->system_header_p = 0;
3640 ip->macro = 0;
3641 ip->free_ptr = 0;
3642 ip->length = length;
3643 ip->buf = ip->bufp = buf1;
3644 ip->if_stack = if_stack;
3645
3646 ip->lineno = obuf.lineno = 1;
3647
3648 /* Scan the input, create the output. */
3649 rescan (&obuf, output_marks);
3650
3651 /* Pop input stack to original state. */
3652 --indepth;
3653
3654 if (indepth != odepth)
3655 abort ();
3656
3657 assertions_flag = save_assertions_flag;
3658 return obuf;
3659 }
3660 \f
3661 /*
3662 * Process a # directive. Expects IP->bufp to point after the '#', as in
3663 * `#define foo bar'. Passes to the directive handler
3664 * (do_define, do_include, etc.): the addresses of the 1st and
3665 * last chars of the directive (starting immediately after the #
3666 * keyword), plus op and the keyword table pointer. If the directive
3667 * contains comments it is copied into a temporary buffer sans comments
3668 * and the temporary buffer is passed to the directive handler instead.
3669 * Likewise for backslash-newlines.
3670 *
3671 * Returns nonzero if this was a known # directive.
3672 * Otherwise, returns zero, without advancing the input pointer.
3673 */
3674
3675 static int
3676 handle_directive (ip, op)
3677 FILE_BUF *ip, *op;
3678 {
3679 register U_CHAR *bp, *cp;
3680 register struct directive *kt;
3681 register int ident_length;
3682 U_CHAR *resume_p;
3683
3684 /* Nonzero means we must copy the entire directive
3685 to get rid of comments or backslash-newlines. */
3686 int copy_directive = 0;
3687
3688 U_CHAR *ident, *after_ident;
3689
3690 bp = ip->bufp;
3691
3692 /* Record where the directive started. do_xifdef needs this. */
3693 directive_start = bp - 1;
3694
3695 ignore_escape_flag = 1;
3696
3697 /* Skip whitespace and \-newline. */
3698 while (1) {
3699 if (is_hor_space[*bp]) {
3700 if (*bp != ' ' && *bp != '\t' && pedantic)
3701 pedwarn_strange_white_space (*bp);
3702 bp++;
3703 } else if (*bp == '/') {
3704 if (bp[1] == '\\')
3705 newline_fix (bp + 1);
3706 if (! (bp[1] == '*' || (cplusplus_comments && bp[1] == '/')))
3707 break;
3708 ip->bufp = bp + 2;
3709 skip_to_end_of_comment (ip, &ip->lineno, 0);
3710 bp = ip->bufp;
3711 } else if (*bp == '\\' && bp[1] == '\n') {
3712 bp += 2; ip->lineno++;
3713 } else break;
3714 }
3715
3716 /* Now find end of directive name.
3717 If we encounter a backslash-newline, exchange it with any following
3718 symbol-constituents so that we end up with a contiguous name. */
3719
3720 cp = bp;
3721 while (1) {
3722 if (is_idchar[*cp])
3723 cp++;
3724 else {
3725 if (*cp == '\\')
3726 name_newline_fix (cp);
3727 if (is_idchar[*cp])
3728 cp++;
3729 else break;
3730 }
3731 }
3732 ident_length = cp - bp;
3733 ident = bp;
3734 after_ident = cp;
3735
3736 /* A line of just `#' becomes blank. */
3737
3738 if (ident_length == 0 && *after_ident == '\n') {
3739 ip->bufp = after_ident;
3740 return 1;
3741 }
3742
3743 if (ident_length == 0 || !is_idstart[*ident]) {
3744 U_CHAR *p = ident;
3745 while (is_idchar[*p]) {
3746 if (*p < '0' || *p > '9')
3747 break;
3748 p++;
3749 }
3750 /* Handle # followed by a line number. */
3751 if (p != ident && !is_idchar[*p]) {
3752 static struct directive line_directive_table[] = {
3753 { 4, do_line, "line", T_LINE},
3754 };
3755 if (pedantic)
3756 pedwarn ("`#' followed by integer");
3757 after_ident = ident;
3758 kt = line_directive_table;
3759 ignore_escape_flag = 0;
3760 goto old_linenum;
3761 }
3762
3763 /* Avoid error for `###' and similar cases unless -pedantic. */
3764 if (p == ident) {
3765 while (*p == '#' || is_hor_space[*p]) p++;
3766 if (*p == '\n') {
3767 if (pedantic && !lang_asm)
3768 warning ("invalid preprocessing directive");
3769 return 0;
3770 }
3771 }
3772
3773 if (!lang_asm)
3774 error ("invalid preprocessing directive name");
3775
3776 return 0;
3777 }
3778
3779 /*
3780 * Decode the keyword and call the appropriate expansion
3781 * routine, after moving the input pointer up to the next line.
3782 */
3783 for (kt = directive_table; kt->length > 0; kt++) {
3784 if (kt->length == ident_length && !bcmp (kt->name, ident, ident_length)) {
3785 register U_CHAR *buf;
3786 register U_CHAR *limit;
3787 int unterminated;
3788 int junk;
3789 int *already_output;
3790
3791 /* Nonzero means do not delete comments within the directive.
3792 #define needs this when -traditional. */
3793 int keep_comments;
3794
3795 old_linenum:
3796
3797 limit = ip->buf + ip->length;
3798 unterminated = 0;
3799 already_output = 0;
3800 keep_comments = traditional && kt->type == T_DEFINE;
3801 /* #import is defined only in Objective C, or when on the NeXT. */
3802 if (kt->type == T_IMPORT
3803 && !(objc || lookup ((U_CHAR *) "__NeXT__", -1, -1)))
3804 break;
3805
3806 /* Find the end of this directive (first newline not backslashed
3807 and not in a string or comment).
3808 Set COPY_DIRECTIVE if the directive must be copied
3809 (it contains a backslash-newline or a comment). */
3810
3811 buf = bp = after_ident;
3812 while (bp < limit) {
3813 register U_CHAR c = *bp++;
3814 switch (c) {
3815 case '\\':
3816 if (*bp == '\n') {
3817 ip->lineno++;
3818 copy_directive = 1;
3819 bp++;
3820 } else if (traditional && bp < limit)
3821 bp++;
3822 break;
3823
3824 case '"':
3825 /* "..." is special for #include. */
3826 if (IS_INCLUDE_DIRECTIVE_TYPE (kt->type)) {
3827 while (bp < limit && *bp != '\n') {
3828 if (*bp == '"') {
3829 bp++;
3830 break;
3831 }
3832 if (*bp == '\\' && bp[1] == '\n') {
3833 ip->lineno++;
3834 copy_directive = 1;
3835 bp++;
3836 }
3837 bp++;
3838 }
3839 break;
3840 }
3841 /* Fall through. */
3842 case '\'':
3843 bp = skip_quoted_string (bp - 1, limit, ip->lineno, &ip->lineno, &copy_directive, &unterminated);
3844 /* Don't bother calling the directive if we already got an error
3845 message due to unterminated string. Skip everything and pretend
3846 we called the directive. */
3847 if (unterminated) {
3848 if (traditional) {
3849 /* Traditional preprocessing permits unterminated strings. */
3850 ip->bufp = bp;
3851 goto endloop1;
3852 }
3853 ip->bufp = bp;
3854 return 1;
3855 }
3856 break;
3857
3858 /* <...> is special for #include. */
3859 case '<':
3860 if (! IS_INCLUDE_DIRECTIVE_TYPE (kt->type))
3861 break;
3862 while (bp < limit && *bp != '>' && *bp != '\n') {
3863 if (*bp == '\\' && bp[1] == '\n') {
3864 ip->lineno++;
3865 copy_directive = 1;
3866 bp++;
3867 }
3868 bp++;
3869 }
3870 break;
3871
3872 case '/':
3873 if (*bp == '\\')
3874 newline_fix (bp);
3875 if (*bp == '*'
3876 || (cplusplus_comments && *bp == '/')) {
3877 U_CHAR *obp = bp - 1;
3878 ip->bufp = bp + 1;
3879 skip_to_end_of_comment (ip, &ip->lineno, 0);
3880 bp = ip->bufp;
3881 /* No need to copy the directive because of a comment at the end;
3882 just don't include the comment in the directive. */
3883 if (!put_out_comments) {
3884 U_CHAR *p;
3885 for (p = bp; *p == ' ' || *p == '\t'; p++)
3886 continue;
3887 if (*p == '\n') {
3888 bp = obp;
3889 goto endloop1;
3890 }
3891 }
3892 /* Don't remove the comments if -traditional. */
3893 if (! keep_comments)
3894 copy_directive++;
3895 }
3896 break;
3897
3898 case '\f':
3899 case '\r':
3900 case '\v':
3901 if (pedantic)
3902 pedwarn_strange_white_space (c);
3903 break;
3904
3905 case '\n':
3906 --bp; /* Point to the newline */
3907 ip->bufp = bp;
3908 goto endloop1;
3909 }
3910 }
3911 ip->bufp = bp;
3912
3913 endloop1:
3914 resume_p = ip->bufp;
3915 /* BP is the end of the directive.
3916 RESUME_P is the next interesting data after the directive.
3917 A comment may come between. */
3918
3919 /* If a directive should be copied through, and -C was given,
3920 pass it through before removing comments. */
3921 if (!no_output && put_out_comments
3922 && ((kt->type == T_DEFINE || kt->type == T_UNDEF)
3923 ? dump_macros == dump_definitions
3924 : IS_INCLUDE_DIRECTIVE_TYPE (kt->type) ? dump_includes
3925 : kt->type == T_PRAGMA)) {
3926 int len;
3927
3928 /* Output directive name. */
3929 check_expand (op, kt->length + 2);
3930 /* Make sure # is at the start of a line */
3931 if (op->bufp > op->buf && op->bufp[-1] != '\n') {
3932 op->lineno++;
3933 *op->bufp++ = '\n';
3934 }
3935 *op->bufp++ = '#';
3936 bcopy (kt->name, op->bufp, kt->length);
3937 op->bufp += kt->length;
3938
3939 /* Output arguments. */
3940 len = (bp - buf);
3941 check_expand (op, len);
3942 bcopy (buf, (char *) op->bufp, len);
3943 op->bufp += len;
3944 /* Take account of any (escaped) newlines just output. */
3945 while (--len >= 0)
3946 if (buf[len] == '\n')
3947 op->lineno++;
3948
3949 already_output = &junk;
3950 } /* Don't we need a newline or #line? */
3951
3952 if (copy_directive) {
3953 register U_CHAR *xp = buf;
3954 /* Need to copy entire directive into temp buffer before dispatching */
3955
3956 /* room for directive plus some slop */
3957 cp = (U_CHAR *) alloca (2 * (bp - buf) + 5);
3958 buf = cp;
3959
3960 /* Copy to the new buffer, deleting comments
3961 and backslash-newlines (and whitespace surrounding the latter
3962 if outside of char and string constants). */
3963
3964 while (xp < bp) {
3965 register U_CHAR c = *xp++;
3966 *cp++ = c;
3967
3968 switch (c) {
3969 case '\n':
3970 abort (); /* A bare newline should never part of the line. */
3971 break;
3972
3973 /* <...> is special for #include. */
3974 case '<':
3975 if (! IS_INCLUDE_DIRECTIVE_TYPE (kt->type))
3976 break;
3977 while (xp < bp && c != '>') {
3978 c = *xp++;
3979 if (c == '\\' && xp < bp && *xp == '\n')
3980 xp++;
3981 else
3982 *cp++ = c;
3983 }
3984 break;
3985
3986 case '\\':
3987 if (*xp == '\n') {
3988 xp++;
3989 cp--;
3990 if (cp != buf && is_hor_space[cp[-1]]) {
3991 while (cp - 1 != buf && is_hor_space[cp[-2]])
3992 cp--;
3993 SKIP_WHITE_SPACE (xp);
3994 } else if (is_hor_space[*xp]) {
3995 *cp++ = *xp++;
3996 SKIP_WHITE_SPACE (xp);
3997 }
3998 } else if (traditional && xp < bp) {
3999 *cp++ = *xp++;
4000 }
4001 break;
4002
4003 case '\'':
4004 case '\"':
4005 {
4006 int backslash_newlines_p;
4007
4008 register U_CHAR *bp1
4009 = skip_quoted_string (xp - 1, bp, ip->lineno,
4010 NULL_PTR, &backslash_newlines_p,
4011 NULL_PTR);
4012 if (backslash_newlines_p)
4013 while (xp != bp1)
4014 {
4015 /* With something like:
4016
4017 #define X "a\
4018 b"
4019
4020 we should still remove the backslash-newline
4021 pair as part of phase two. */
4022 if (xp[0] == '\\' && xp[1] == '\n')
4023 xp += 2;
4024 else
4025 *cp++ = *xp++;
4026 }
4027 else
4028 /* This is the same as the loop above, but taking
4029 advantage of the fact that we know there are no
4030 backslash-newline pairs. */
4031 while (xp != bp1)
4032 *cp++ = *xp++;
4033 }
4034 break;
4035
4036 case '/':
4037 if (*xp == '*'
4038 || (cplusplus_comments && *xp == '/')) {
4039 ip->bufp = xp + 1;
4040 /* If we already copied the directive through,
4041 already_output != 0 prevents outputting comment now. */
4042 skip_to_end_of_comment (ip, already_output, 0);
4043 if (keep_comments)
4044 while (xp != ip->bufp)
4045 *cp++ = *xp++;
4046 /* Delete or replace the slash. */
4047 else if (traditional)
4048 cp--;
4049 else
4050 cp[-1] = ' ';
4051 xp = ip->bufp;
4052 }
4053 }
4054 }
4055
4056 /* Null-terminate the copy. */
4057
4058 *cp = 0;
4059 } else
4060 cp = bp;
4061
4062 ip->bufp = resume_p;
4063
4064 /* Some directives should be written out for cc1 to process,
4065 just as if they were not defined. And sometimes we're copying
4066 directives through. */
4067
4068 if (!no_output && already_output == 0
4069 && ((kt->type == T_DEFINE || kt->type == T_UNDEF)
4070 ? (int) dump_names <= (int) dump_macros
4071 : IS_INCLUDE_DIRECTIVE_TYPE (kt->type) ? dump_includes
4072 : kt->type == T_PRAGMA)) {
4073 int len;
4074
4075 /* Output directive name. */
4076 check_expand (op, kt->length + 1);
4077 *op->bufp++ = '#';
4078 bcopy (kt->name, (char *) op->bufp, kt->length);
4079 op->bufp += kt->length;
4080
4081 if (kt->type == T_DEFINE && dump_macros == dump_names) {
4082 /* Output `#define name' only. */
4083 U_CHAR *xp = buf;
4084 U_CHAR *yp;
4085 SKIP_WHITE_SPACE (xp);
4086 yp = xp;
4087 while (is_idchar[*xp]) xp++;
4088 len = (xp - yp);
4089 check_expand (op, len + 1);
4090 *op->bufp++ = ' ';
4091 bcopy (yp, (char *) op->bufp, len);
4092 } else {
4093 /* Output entire directive. */
4094 len = (cp - buf);
4095 check_expand (op, len);
4096 bcopy (buf, (char *) op->bufp, len);
4097 }
4098 op->bufp += len;
4099 }
4100
4101 /* Call the appropriate directive handler. buf now points to
4102 either the appropriate place in the input buffer, or to
4103 the temp buffer if it was necessary to make one. cp
4104 points to the first char after the contents of the (possibly
4105 copied) directive, in either case. */
4106 (*kt->func) (buf, cp, op, kt);
4107 check_expand (op, ip->length - (ip->bufp - ip->buf));
4108
4109 return 1;
4110 }
4111 }
4112
4113 /* It is deliberate that we don't warn about undefined directives.
4114 That is the responsibility of cc1. */
4115 return 0;
4116 }
4117 \f
4118 static struct tm *
4119 timestamp ()
4120 {
4121 static struct tm tmbuf;
4122 if (! tmbuf.tm_mday) {
4123 time_t t = time ((time_t *) 0);
4124 struct tm *tm = localtime (&t);
4125 if (tm)
4126 tmbuf = *tm;
4127 else {
4128 /* Use 0000-01-01 00:00:00 if local time is not available. */
4129 tmbuf.tm_year = -1900;
4130 tmbuf.tm_mday = 1;
4131 }
4132 }
4133 return &tmbuf;
4134 }
4135
4136 static char *monthnames[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
4137 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
4138 };
4139
4140 /*
4141 * expand things like __FILE__. Place the expansion into the output
4142 * buffer *without* rescanning.
4143 */
4144
4145 static void
4146 special_symbol (hp, op)
4147 HASHNODE *hp;
4148 FILE_BUF *op;
4149 {
4150 char *buf;
4151 int i, len;
4152 int true_indepth;
4153 FILE_BUF *ip = NULL;
4154 struct tm *timebuf;
4155
4156 int paren = 0; /* For special `defined' keyword */
4157
4158 if (pcp_outfile && pcp_inside_if
4159 && hp->type != T_SPEC_DEFINED && hp->type != T_CONST)
4160 error ("Predefined macro `%s' used inside `#if' during precompilation",
4161 hp->name);
4162
4163 for (i = indepth; i >= 0; i--)
4164 if (instack[i].fname != NULL) {
4165 ip = &instack[i];
4166 break;
4167 }
4168 if (ip == NULL) {
4169 error ("cccp error: not in any file?!");
4170 return; /* the show must go on */
4171 }
4172
4173 switch (hp->type) {
4174 case T_FILE:
4175 case T_BASE_FILE:
4176 {
4177 FILE_BUF *p = hp->type == T_FILE ? ip : &instack[0];
4178 char *string = p->nominal_fname;
4179
4180 if (string)
4181 {
4182 size_t string_len = p->nominal_fname_len;
4183 buf = (char *) alloca (3 + 4 * string_len);
4184 quote_string (buf, string, string_len);
4185 }
4186 else
4187 buf = "\"\"";
4188
4189 break;
4190 }
4191
4192 case T_INCLUDE_LEVEL:
4193 true_indepth = 0;
4194 for (i = indepth; i >= 0; i--)
4195 if (instack[i].fname != NULL)
4196 true_indepth++;
4197
4198 buf = (char *) alloca (8); /* Eight bytes ought to be more than enough */
4199 sprintf (buf, "%d", true_indepth - 1);
4200 break;
4201
4202 case T_VERSION:
4203 buf = (char *) alloca (3 + strlen (version_string));
4204 sprintf (buf, "\"%s\"", version_string);
4205 break;
4206
4207 #ifndef NO_BUILTIN_SIZE_TYPE
4208 case T_SIZE_TYPE:
4209 buf = SIZE_TYPE;
4210 break;
4211 #endif
4212
4213 #ifndef NO_BUILTIN_PTRDIFF_TYPE
4214 case T_PTRDIFF_TYPE:
4215 buf = PTRDIFF_TYPE;
4216 break;
4217 #endif
4218
4219 case T_WCHAR_TYPE:
4220 buf = wchar_type;
4221 break;
4222
4223 case T_USER_LABEL_PREFIX_TYPE:
4224 buf = user_label_prefix;
4225 break;
4226
4227 case T_REGISTER_PREFIX_TYPE:
4228 buf = REGISTER_PREFIX;
4229 break;
4230
4231 case T_IMMEDIATE_PREFIX_TYPE:
4232 buf = IMMEDIATE_PREFIX;
4233 break;
4234
4235 case T_CONST:
4236 buf = hp->value.cpval;
4237 #ifdef STDC_0_IN_SYSTEM_HEADERS
4238 if (ip->system_header_p
4239 && hp->length == 8 && bcmp (hp->name, "__STDC__", 8) == 0
4240 && !lookup ((U_CHAR *) "__STRICT_ANSI__", -1, -1))
4241 buf = "0";
4242 #endif
4243 if (pcp_inside_if && pcp_outfile)
4244 /* Output a precondition for this macro use */
4245 fprintf (pcp_outfile, "#define %s %s\n", hp->name, buf);
4246 break;
4247
4248 case T_SPECLINE:
4249 buf = (char *) alloca (10);
4250 sprintf (buf, "%d", ip->lineno);
4251 break;
4252
4253 case T_DATE:
4254 case T_TIME:
4255 buf = (char *) alloca (20);
4256 timebuf = timestamp ();
4257 if (hp->type == T_DATE)
4258 sprintf (buf, "\"%s %2d %4d\"", monthnames[timebuf->tm_mon],
4259 timebuf->tm_mday, timebuf->tm_year + 1900);
4260 else
4261 sprintf (buf, "\"%02d:%02d:%02d\"", timebuf->tm_hour, timebuf->tm_min,
4262 timebuf->tm_sec);
4263 break;
4264
4265 case T_SPEC_DEFINED:
4266 buf = " 0 "; /* Assume symbol is not defined */
4267 ip = &instack[indepth];
4268 SKIP_WHITE_SPACE (ip->bufp);
4269 if (*ip->bufp == '(') {
4270 paren++;
4271 ip->bufp++; /* Skip over the paren */
4272 SKIP_WHITE_SPACE (ip->bufp);
4273 }
4274
4275 if (!is_idstart[*ip->bufp])
4276 goto oops;
4277 if (ip->bufp[0] == 'L' && (ip->bufp[1] == '\'' || ip->bufp[1] == '"'))
4278 goto oops;
4279 if ((hp = lookup (ip->bufp, -1, -1))) {
4280 if (pcp_outfile && pcp_inside_if
4281 && (hp->type == T_CONST
4282 || (hp->type == T_MACRO && hp->value.defn->predefined)))
4283 /* Output a precondition for this macro use. */
4284 fprintf (pcp_outfile, "#define %s\n", hp->name);
4285 if (hp->type == T_POISON) {
4286 error("attempt to use poisoned `%s'.", hp->name);
4287 buf = " 0 ";
4288 } else {
4289 buf = " 1 ";
4290 }
4291 }
4292 else
4293 if (pcp_outfile && pcp_inside_if) {
4294 /* Output a precondition for this macro use */
4295 U_CHAR *cp = ip->bufp;
4296 fprintf (pcp_outfile, "#undef ");
4297 while (is_idchar[*cp]) /* Ick! */
4298 fputc (*cp++, pcp_outfile);
4299 putc ('\n', pcp_outfile);
4300 }
4301 while (is_idchar[*ip->bufp])
4302 ++ip->bufp;
4303 SKIP_WHITE_SPACE (ip->bufp);
4304 if (paren) {
4305 if (*ip->bufp != ')')
4306 goto oops;
4307 ++ip->bufp;
4308 }
4309 break;
4310
4311 case T_POISON:
4312 error("attempt to use poisoned `%s'.", hp->name);
4313 buf = " 0 "; /* Consider poisoned symbol to not be defined */
4314 break;
4315
4316 oops:
4317
4318 error ("`defined' without an identifier");
4319 break;
4320
4321 default:
4322 error ("cccp error: invalid special hash type"); /* time for gdb */
4323 abort ();
4324 }
4325 len = strlen (buf);
4326 check_expand (op, len);
4327 bcopy (buf, (char *) op->bufp, len);
4328 op->bufp += len;
4329
4330 return;
4331 }
4332
4333 \f
4334 /* Routines to handle #directives */
4335
4336 /* Handle #include and #import.
4337 This function expects to see "fname" or <fname> on the input. */
4338
4339 static int
4340 do_include (buf, limit, op, keyword)
4341 U_CHAR *buf, *limit;
4342 FILE_BUF *op;
4343 struct directive *keyword;
4344 {
4345 U_CHAR *importing = keyword->type == T_IMPORT ? (U_CHAR *) "" : (U_CHAR *) 0;
4346 int skip_dirs = (keyword->type == T_INCLUDE_NEXT);
4347 static int import_warning = 0;
4348 char *fname; /* Dynamically allocated fname buffer */
4349 char *pcftry;
4350 char *pcfname;
4351 char *fbeg, *fend; /* Beginning and end of fname */
4352 U_CHAR *fin;
4353
4354 struct file_name_list *search_start = include; /* Chain of dirs to search */
4355 struct file_name_list *dsp; /* First in chain, if #include "..." */
4356 struct file_name_list *searchptr = 0;
4357 size_t flen;
4358
4359 int f = -3; /* file number */
4360 struct include_file *inc = 0;
4361
4362 int retried = 0; /* Have already tried macro
4363 expanding the include line*/
4364 int angle_brackets = 0; /* 0 for "...", 1 for <...> */
4365 #ifdef VMS
4366 int vaxc_include = 0; /* 1 for token without punctuation */
4367 #endif
4368 int pcf = -1;
4369 char *pcfbuf;
4370 char *pcfbuflimit;
4371 int pcfnum;
4372
4373 if (pedantic && !instack[indepth].system_header_p)
4374 {
4375 if (importing)
4376 pedwarn ("ANSI C does not allow `#import'");
4377 if (skip_dirs)
4378 pedwarn ("ANSI C does not allow `#include_next'");
4379 }
4380
4381 if (importing && warn_import && !inhibit_warnings
4382 && !instack[indepth].system_header_p && !import_warning) {
4383 import_warning = 1;
4384 warning ("using `#import' is not recommended");
4385 notice ("The fact that a certain header file need not be processed more than once\n\
4386 should be indicated in the header file, not where it is used.\n\
4387 The best way to do this is with a conditional of this form:\n\
4388 \n\
4389 #ifndef _FOO_H_INCLUDED\n\
4390 #define _FOO_H_INCLUDED\n\
4391 ... <real contents of file> ...\n\
4392 #endif /* Not _FOO_H_INCLUDED */\n\
4393 \n\
4394 Then users can use `#include' any number of times.\n\
4395 GNU C automatically avoids processing the file more than once\n\
4396 when it is equipped with such a conditional.\n");
4397 }
4398
4399 get_filename:
4400
4401 fin = buf;
4402 SKIP_WHITE_SPACE (fin);
4403 /* Discard trailing whitespace so we can easily see
4404 if we have parsed all the significant chars we were given. */
4405 while (limit != fin && is_hor_space[limit[-1]]) limit--;
4406 fbeg = fend = (char *) alloca (limit - fin);
4407
4408 switch (*fin++) {
4409 case '\"':
4410 {
4411 FILE_BUF *fp;
4412 /* Copy the operand text, concatenating the strings. */
4413 {
4414 for (;;) {
4415 for (;;) {
4416 if (fin == limit)
4417 goto invalid_include_file_name;
4418 *fend = *fin++;
4419 if (*fend == '"')
4420 break;
4421 fend++;
4422 }
4423 if (fin == limit)
4424 break;
4425 /* If not at the end, there had better be another string. */
4426 /* Skip just horiz space, and don't go past limit. */
4427 while (fin != limit && is_hor_space[*fin]) fin++;
4428 if (fin != limit && *fin == '\"')
4429 fin++;
4430 else
4431 goto fail;
4432 }
4433 }
4434
4435 /* We have "filename". Figure out directory this source
4436 file is coming from and put it on the front of the list. */
4437
4438 /* If -I- was specified, don't search current dir, only spec'd ones. */
4439 if (ignore_srcdir) break;
4440
4441 for (fp = &instack[indepth]; fp >= instack; fp--)
4442 {
4443 int n;
4444 char *nam;
4445
4446 if ((nam = fp->nominal_fname) != NULL) {
4447 /* Found a named file. Figure out dir of the file,
4448 and put it in front of the search list. */
4449 dsp = ((struct file_name_list *)
4450 alloca (sizeof (struct file_name_list)
4451 + fp->nominal_fname_len));
4452 strcpy (dsp->fname, nam);
4453 simplify_filename (dsp->fname);
4454 nam = base_name (dsp->fname);
4455 *nam = 0;
4456 #ifdef VMS
4457 /* for hack_vms_include_specification(), a local
4458 dir specification must start with "./" on VMS. */
4459 if (nam == dsp->fname)
4460 {
4461 *nam++ = '.';
4462 *nam++ = '/';
4463 *nam = 0;
4464 }
4465 #endif
4466 /* But for efficiency's sake, do not insert the dir
4467 if it matches the search list's first dir. */
4468 dsp->next = search_start;
4469 if (!search_start || strcmp (dsp->fname, search_start->fname)) {
4470 search_start = dsp;
4471 n = nam - dsp->fname;
4472 if (n + INCLUDE_LEN_FUDGE > max_include_len)
4473 max_include_len = n + INCLUDE_LEN_FUDGE;
4474 }
4475 dsp[0].got_name_map = 0;
4476 break;
4477 }
4478 }
4479 break;
4480 }
4481
4482 case '<':
4483 while (fin != limit && *fin != '>')
4484 *fend++ = *fin++;
4485 if (*fin == '>' && fin + 1 == limit) {
4486 angle_brackets = 1;
4487 /* If -I-, start with the first -I dir after the -I-. */
4488 search_start = first_bracket_include;
4489 break;
4490 }
4491 goto fail;
4492
4493 default:
4494 #ifdef VMS
4495 /*
4496 * Support '#include xyz' like VAX-C to allow for easy use of all the
4497 * decwindow include files. It defaults to '#include <xyz.h>' (so the
4498 * code from case '<' is repeated here) and generates a warning.
4499 * (Note: macro expansion of `xyz' takes precedence.)
4500 */
4501 /* Note: The argument of ISALPHA() can be evaluated twice, so do
4502 the pre-decrement outside of the macro. */
4503 if (retried && (--fin, ISALPHA(*(U_CHAR *) (fin)))) {
4504 while (fin != limit && (!ISSPACE(*fin)))
4505 *fend++ = *fin++;
4506 warning ("VAX-C-style include specification found, use '#include <filename.h>' !");
4507 vaxc_include = 1;
4508 if (fin == limit) {
4509 angle_brackets = 1;
4510 /* If -I-, start with the first -I dir after the -I-. */
4511 search_start = first_bracket_include;
4512 break;
4513 }
4514 }
4515 #endif
4516
4517 fail:
4518 if (! retried) {
4519 /* Expand buffer and then remove any newline markers.
4520 We can't just tell expand_to_temp_buffer to omit the markers,
4521 since it would put extra spaces in include file names. */
4522 FILE_BUF trybuf;
4523 U_CHAR *src;
4524 int errors_before_expansion = errors;
4525 trybuf = expand_to_temp_buffer (buf, limit, 1, 0);
4526 if (errors != errors_before_expansion) {
4527 free (trybuf.buf);
4528 goto invalid_include_file_name;
4529 }
4530 src = trybuf.buf;
4531 buf = (U_CHAR *) alloca (trybuf.bufp - trybuf.buf + 1);
4532 limit = buf;
4533 while (src != trybuf.bufp) {
4534 switch ((*limit++ = *src++)) {
4535 case '\n':
4536 limit--;
4537 src++;
4538 break;
4539
4540 case '\'':
4541 case '\"':
4542 {
4543 U_CHAR *src1 = skip_quoted_string (src - 1, trybuf.bufp, 0,
4544 NULL_PTR, NULL_PTR, NULL_PTR);
4545 while (src != src1)
4546 *limit++ = *src++;
4547 }
4548 break;
4549 }
4550 }
4551 *limit = 0;
4552 free (trybuf.buf);
4553 retried = 1;
4554 goto get_filename;
4555 }
4556
4557 invalid_include_file_name:
4558 error ("`#%s' expects \"FILENAME\" or <FILENAME>", keyword->name);
4559 return 0;
4560 }
4561
4562 /* For #include_next, skip in the search path
4563 past the dir in which the containing file was found. */
4564 if (skip_dirs) {
4565 FILE_BUF *fp;
4566 for (fp = &instack[indepth]; fp >= instack; fp--)
4567 if (fp->fname != NULL) {
4568 /* fp->dir is null if the containing file was specified
4569 with an absolute file name. In that case, don't skip anything. */
4570 if (fp->dir)
4571 search_start = fp->dir->next;
4572 break;
4573 }
4574 }
4575
4576 *fend = 0;
4577 flen = simplify_filename (fbeg);
4578
4579 if (flen == 0)
4580 {
4581 error ("empty file name in `#%s'", keyword->name);
4582 return 0;
4583 }
4584
4585 /* Allocate this permanently, because it gets stored in the definitions
4586 of macros. */
4587 fname = xmalloc (max_include_len + flen + 1);
4588 /* + 1 above for terminating null. */
4589
4590 system_include_depth += angle_brackets;
4591
4592 /* If specified file name is absolute, just open it. */
4593
4594 if (absolute_filename (fbeg)) {
4595 strcpy (fname, fbeg);
4596 f = open_include_file (fname, NULL_PTR, importing, &inc);
4597 } else {
4598
4599 struct bypass_dir {
4600 struct bypass_dir *next;
4601 char *fname;
4602 struct file_name_list *searchptr;
4603 } **bypass_slot = 0;
4604
4605 /* Search directory path, trying to open the file.
4606 Copy each filename tried into FNAME. */
4607
4608 for (searchptr = search_start; searchptr; searchptr = searchptr->next) {
4609
4610 if (searchptr == first_bracket_include) {
4611 /* Go to bypass directory if we know we've seen this file before. */
4612 static struct bypass_dir *bypass_hashtab[INCLUDE_HASHSIZE];
4613 struct bypass_dir *p;
4614 bypass_slot = &bypass_hashtab[hashf ((U_CHAR *) fbeg, flen,
4615 INCLUDE_HASHSIZE)];
4616 for (p = *bypass_slot; p; p = p->next)
4617 if (!strcmp (fbeg, p->fname)) {
4618 searchptr = p->searchptr;
4619 bypass_slot = 0;
4620 break;
4621 }
4622 }
4623
4624 #ifdef VMS
4625 /* Change this 1/2 Unix 1/2 VMS file specification into a
4626 full VMS file specification */
4627 if (searchptr->fname[0])
4628 {
4629 strcpy (fname, searchptr->fname);
4630 if (fname[strlen (fname) - 1] == ':')
4631 {
4632 char *slashp;
4633 slashp = strchr (fbeg, '/');
4634
4635 /* start at root-dir of logical device if no path given. */
4636 if (slashp == 0)
4637 strcat (fname, "[000000]");
4638 }
4639 strcat (fname, fbeg);
4640
4641 /* Fix up the filename */
4642 hack_vms_include_specification (fname, vaxc_include);
4643 }
4644 else
4645 {
4646 /* This is a normal VMS filespec, so use it unchanged. */
4647 strcpy (fname, fbeg);
4648 /* if it's '#include filename', add the missing .h */
4649 if (vaxc_include && index(fname,'.')==NULL)
4650 strcat (fname, ".h");
4651 }
4652 #else
4653 strcpy (fname, searchptr->fname);
4654 strcat (fname, fbeg);
4655 #endif /* VMS */
4656 f = open_include_file (fname, searchptr, importing, &inc);
4657 if (f != -1) {
4658 if (bypass_slot && searchptr != first_bracket_include) {
4659 /* This is the first time we found this include file,
4660 and we found it after first_bracket_include.
4661 Record its location so that we can bypass to here next time. */
4662 struct bypass_dir *p
4663 = (struct bypass_dir *) xmalloc (sizeof (struct bypass_dir));
4664 p->next = *bypass_slot;
4665 p->fname = fname + strlen (searchptr->fname);
4666 p->searchptr = searchptr;
4667 *bypass_slot = p;
4668 }
4669 break;
4670 }
4671 #ifdef VMS
4672 /* Our VMS hacks can produce invalid filespecs, so don't worry
4673 about errors other than EACCES. */
4674 if (errno == EACCES)
4675 break;
4676 #else
4677 if (errno != ENOENT && errno != ENOTDIR)
4678 break;
4679 #endif
4680 }
4681 }
4682
4683
4684 if (f < 0) {
4685
4686 if (f == -2) {
4687 /* The file was already included. */
4688
4689 /* If generating dependencies and -MG was specified, we assume missing
4690 files are leaf files, living in the same directory as the source file
4691 or other similar place; these missing files may be generated from
4692 other files and may not exist yet (eg: y.tab.h). */
4693 } else if (print_deps_missing_files
4694 && (system_include_depth != 0) < print_deps)
4695 {
4696 /* If it was requested as a system header file,
4697 then assume it belongs in the first place to look for such. */
4698 if (angle_brackets)
4699 {
4700 if (search_start) {
4701 char *p = (char *) alloca (strlen (search_start->fname)
4702 + strlen (fbeg) + 1);
4703 strcpy (p, search_start->fname);
4704 strcat (p, fbeg);
4705 deps_output (p, ' ');
4706 }
4707 }
4708 else
4709 {
4710 /* Otherwise, omit the directory, as if the file existed
4711 in the directory with the source. */
4712 deps_output (fbeg, ' ');
4713 }
4714 }
4715 /* If -M was specified, and this header file won't be added to the
4716 dependency list, then don't count this as an error, because we can
4717 still produce correct output. Otherwise, we can't produce correct
4718 output, because there may be dependencies we need inside the missing
4719 file, and we don't know what directory this missing file exists in. */
4720 else if (0 < print_deps && print_deps <= (system_include_depth != 0))
4721 warning ("No include path in which to find %s", fbeg);
4722 else if (f != -3)
4723 error_from_errno (fbeg);
4724 else
4725 error ("No include path in which to find %s", fbeg);
4726
4727 } else {
4728
4729 /* Actually process the file. */
4730
4731 pcftry = (char *) alloca (strlen (fname) + 30);
4732 pcfbuf = 0;
4733 pcfnum = 0;
4734
4735 if (!no_precomp)
4736 {
4737 do {
4738 sprintf (pcftry, "%s%d", fname, pcfnum++);
4739
4740 pcf = open (pcftry, O_RDONLY, 0666);
4741 if (pcf != -1)
4742 {
4743 struct stat s;
4744
4745 if (fstat (pcf, &s) != 0)
4746 pfatal_with_name (pcftry);
4747 if (! INO_T_EQ (inc->st.st_ino, s.st_ino)
4748 || inc->st.st_dev != s.st_dev)
4749 {
4750 pcfbuf = check_precompiled (pcf, &s, fname, &pcfbuflimit);
4751 /* Don't need it any more. */
4752 close (pcf);
4753 }
4754 else
4755 {
4756 /* Don't need it at all. */
4757 close (pcf);
4758 break;
4759 }
4760 }
4761 } while (pcf != -1 && !pcfbuf);
4762 }
4763
4764 /* Actually process the file */
4765 if (pcfbuf) {
4766 pcfname = xstrdup (pcftry);
4767 pcfinclude ((U_CHAR *) pcfbuf, (U_CHAR *) fname, op);
4768 }
4769 else
4770 finclude (f, inc, op, is_system_include (fname), searchptr);
4771 }
4772
4773 system_include_depth -= angle_brackets;
4774
4775 return 0;
4776 }
4777
4778 /* Return nonzero if the given FILENAME is an absolute pathname which
4779 designates a file within one of the known "system" include file
4780 directories. We assume here that if the given FILENAME looks like
4781 it is the name of a file which resides either directly in a "system"
4782 include file directory, or within any subdirectory thereof, then the
4783 given file must be a "system" include file. This function tells us
4784 if we should suppress pedantic errors/warnings for the given FILENAME.
4785
4786 The value is 2 if the file is a C-language system header file
4787 for which C++ should (on most systems) assume `extern "C"'. */
4788
4789 static int
4790 is_system_include (filename)
4791 register char *filename;
4792 {
4793 struct file_name_list *searchptr;
4794
4795 for (searchptr = first_system_include; searchptr;
4796 searchptr = searchptr->next)
4797 if (! strncmp (searchptr->fname, filename, strlen (searchptr->fname)))
4798 return searchptr->c_system_include_path + 1;
4799 return 0;
4800 }
4801 \f
4802 /* Yield the non-directory suffix of a file name. */
4803
4804 static char *
4805 base_name (fname)
4806 char *fname;
4807 {
4808 char *s = fname;
4809 char *p;
4810 #if defined (__MSDOS__) || defined (_WIN32)
4811 if (ISALPHA (s[0]) && s[1] == ':') s += 2;
4812 #endif
4813 #ifdef VMS
4814 if ((p = rindex (s, ':'))) s = p + 1; /* Skip device. */
4815 if ((p = rindex (s, ']'))) s = p + 1; /* Skip directory. */
4816 if ((p = rindex (s, '>'))) s = p + 1; /* Skip alternate (int'n'l) dir. */
4817 if (s != fname)
4818 return s;
4819 #endif
4820 if ((p = rindex (s, '/'))) s = p + 1;
4821 #ifdef DIR_SEPARATOR
4822 if ((p = rindex (s, DIR_SEPARATOR))) s = p + 1;
4823 #endif
4824 return s;
4825 }
4826
4827 /* Yield nonzero if FILENAME is absolute (i.e. not relative). */
4828
4829 static int
4830 absolute_filename (filename)
4831 char *filename;
4832 {
4833 #if defined (__MSDOS__) \
4834 || (defined (_WIN32) && !defined (__CYGWIN__) && !defined (_UWIN))
4835 if (ISALPHA (filename[0]) && filename[1] == ':') filename += 2;
4836 #endif
4837 #if defined (__CYGWIN__)
4838 /* At present, any path that begins with a drive spec is absolute. */
4839 if (ISALPHA (filename[0]) && filename[1] == ':') return 1;
4840 #endif
4841 #ifdef VMS
4842 if (index (filename, ':') != 0) return 1;
4843 #endif
4844 if (filename[0] == '/') return 1;
4845 #ifdef DIR_SEPARATOR
4846 if (filename[0] == DIR_SEPARATOR) return 1;
4847 #endif
4848 return 0;
4849 }
4850
4851 /* Returns whether or not a given character is a directory separator.
4852 Used by simplify_filename. */
4853 static inline
4854 int
4855 is_dir_separator(ch)
4856 char ch;
4857 {
4858 return (ch == DIR_SEPARATOR)
4859 #if defined (DIR_SEPARATOR_2)
4860 || (ch == DIR_SEPARATOR_2)
4861 #endif
4862 ;
4863 }
4864
4865 /* Remove unnecessary characters from FILENAME in place,
4866 to avoid unnecessary filename aliasing.
4867 Return the length of the resulting string.
4868
4869 Do only the simplifications allowed by Posix.
4870 It is OK to miss simplifications on non-Posix hosts,
4871 since this merely leads to suboptimal results. */
4872
4873 static size_t
4874 simplify_filename (filename)
4875 char *filename;
4876 {
4877 register char *from = filename;
4878 register char *to = filename;
4879 char *to0;
4880
4881 /* Remove redundant initial /s. */
4882 if (is_dir_separator (*from))
4883 {
4884 *to++ = DIR_SEPARATOR;
4885 if (is_dir_separator (*++from))
4886 {
4887 if (is_dir_separator (*++from))
4888 {
4889 /* 3 or more initial /s are equivalent to 1 /. */
4890 while (is_dir_separator (*++from))
4891 continue;
4892 }
4893 else
4894 {
4895 /* On some hosts // differs from /; Posix allows this. */
4896 *to++ = DIR_SEPARATOR;
4897 }
4898 }
4899 }
4900
4901 to0 = to;
4902
4903 for (;;)
4904 {
4905 #ifndef VMS
4906 if (from[0] == '.' && from[1] == '/')
4907 from += 2;
4908 else
4909 #endif
4910 {
4911 /* Copy this component and trailing DIR_SEPARATOR, if any. */
4912 while (!is_dir_separator (*to++ = *from++))
4913 {
4914 if (!to[-1])
4915 {
4916 /* Trim . component at end of nonempty name. */
4917 to -= filename <= to - 3 && to[-3] == DIR_SEPARATOR && to[-2] == '.';
4918
4919 /* Trim unnecessary trailing /s. */
4920 while (to0 < --to && to[-1] == DIR_SEPARATOR)
4921 continue;
4922
4923 *to = 0;
4924 return to - filename;
4925 }
4926 }
4927 #if defined(DIR_SEPARATOR_2)
4928 /* Simplify to one directory separator. */
4929 to[-1] = DIR_SEPARATOR;
4930 #endif
4931 }
4932
4933 /* Skip /s after a /. */
4934 while (is_dir_separator (*from))
4935 from++;
4936 }
4937 }
4938 \f
4939 /* The file_name_map structure holds a mapping of file names for a
4940 particular directory. This mapping is read from the file named
4941 FILE_NAME_MAP_FILE in that directory. Such a file can be used to
4942 map filenames on a file system with severe filename restrictions,
4943 such as DOS. The format of the file name map file is just a series
4944 of lines with two tokens on each line. The first token is the name
4945 to map, and the second token is the actual name to use. */
4946
4947 struct file_name_map
4948 {
4949 struct file_name_map *map_next;
4950 char *map_from;
4951 char *map_to;
4952 };
4953
4954 #define FILE_NAME_MAP_FILE "header.gcc"
4955
4956 /* Read a space delimited string of unlimited length from a stdio
4957 file. */
4958
4959 static char *
4960 read_filename_string (ch, f)
4961 int ch;
4962 FILE *f;
4963 {
4964 char *alloc, *set;
4965 int len;
4966
4967 len = 20;
4968 set = alloc = xmalloc (len + 1);
4969 if (! is_space[ch])
4970 {
4971 *set++ = ch;
4972 while ((ch = getc (f)) != EOF && ! is_space[ch])
4973 {
4974 if (set - alloc == len)
4975 {
4976 len *= 2;
4977 alloc = xrealloc (alloc, len + 1);
4978 set = alloc + len / 2;
4979 }
4980 *set++ = ch;
4981 }
4982 }
4983 *set = '\0';
4984 ungetc (ch, f);
4985 return alloc;
4986 }
4987
4988 /* Read the file name map file for DIRNAME.
4989 If DIRNAME is empty, read the map file for the working directory;
4990 otherwise DIRNAME must end in '/'. */
4991
4992 static struct file_name_map *
4993 read_name_map (dirname)
4994 char *dirname;
4995 {
4996 /* This structure holds a linked list of file name maps, one per
4997 directory. */
4998 struct file_name_map_list
4999 {
5000 struct file_name_map_list *map_list_next;
5001 char *map_list_name;
5002 struct file_name_map *map_list_map;
5003 };
5004 static struct file_name_map_list *map_list;
5005 register struct file_name_map_list *map_list_ptr;
5006 char *name;
5007 FILE *f;
5008 size_t dirlen;
5009
5010 for (map_list_ptr = map_list; map_list_ptr;
5011 map_list_ptr = map_list_ptr->map_list_next)
5012 if (! strcmp (map_list_ptr->map_list_name, dirname))
5013 return map_list_ptr->map_list_map;
5014
5015 map_list_ptr = ((struct file_name_map_list *)
5016 xmalloc (sizeof (struct file_name_map_list)));
5017 map_list_ptr->map_list_name = xstrdup (dirname);
5018 map_list_ptr->map_list_map = NULL;
5019
5020 dirlen = strlen (dirname);
5021 name = (char *) alloca (dirlen + strlen (FILE_NAME_MAP_FILE) + 1);
5022 strcpy (name, dirname);
5023 strcat (name, FILE_NAME_MAP_FILE);
5024 f = fopen (name, "r");
5025 if (!f)
5026 map_list_ptr->map_list_map = NULL;
5027 else
5028 {
5029 int ch;
5030
5031 while ((ch = getc (f)) != EOF)
5032 {
5033 char *from, *to;
5034 struct file_name_map *ptr;
5035 size_t tolen;
5036
5037 if (is_space[ch])
5038 continue;
5039 from = read_filename_string (ch, f);
5040 while ((ch = getc (f)) != EOF && is_hor_space[ch])
5041 ;
5042 to = read_filename_string (ch, f);
5043
5044 simplify_filename (from);
5045 tolen = simplify_filename (to);
5046
5047 ptr = ((struct file_name_map *)
5048 xmalloc (sizeof (struct file_name_map)));
5049 ptr->map_from = from;
5050
5051 /* Make the real filename absolute. */
5052 if (absolute_filename (to))
5053 ptr->map_to = to;
5054 else
5055 {
5056 ptr->map_to = xmalloc (dirlen + tolen + 1);
5057 strcpy (ptr->map_to, dirname);
5058 strcat (ptr->map_to, to);
5059 free (to);
5060 }
5061
5062 ptr->map_next = map_list_ptr->map_list_map;
5063 map_list_ptr->map_list_map = ptr;
5064
5065 while ((ch = getc (f)) != '\n')
5066 if (ch == EOF)
5067 break;
5068 }
5069 fclose (f);
5070 }
5071
5072 map_list_ptr->map_list_next = map_list;
5073 map_list = map_list_ptr;
5074
5075 return map_list_ptr->map_list_map;
5076 }
5077
5078 /* Try to open include file FILENAME. SEARCHPTR is the directory
5079 being tried from the include file search path.
5080 IMPORTING is "" if we are importing, null otherwise.
5081 Return -2 if found, either a matching name or a matching inode.
5082 Otherwise, open the file and return a file descriptor if successful
5083 or -1 if unsuccessful.
5084 Unless unsuccessful, put a descriptor of the included file into *PINC.
5085 This function maps filenames on file systems based on information read by
5086 read_name_map. */
5087
5088 static int
5089 open_include_file (filename, searchptr, importing, pinc)
5090 char *filename;
5091 struct file_name_list *searchptr;
5092 U_CHAR *importing;
5093 struct include_file **pinc;
5094 {
5095 char *fname = remap ? remap_include_file (filename, searchptr) : filename;
5096 int fd = -2;
5097
5098 /* Look up FNAME in include_hashtab. */
5099 struct include_file **phead = &include_hashtab[hashf ((U_CHAR *) fname,
5100 strlen (fname),
5101 INCLUDE_HASHSIZE)];
5102 struct include_file *inc, *head = *phead;
5103 for (inc = head; inc; inc = inc->next)
5104 if (!strcmp (fname, inc->fname))
5105 break;
5106
5107 if (!inc
5108 || ! inc->control_macro
5109 || (inc->control_macro[0] && ! lookup (inc->control_macro, -1, -1))) {
5110
5111 fd = open (fname, O_RDONLY, 0);
5112
5113 if (fd < 0)
5114 {
5115 #ifdef VMS
5116 /* if #include <dir/file> fails, try again with hacked spec. */
5117 if (!hack_vms_include_specification (fname, 0))
5118 return fd;
5119 fd = open (fname, O_RDONLY, 0);
5120 if (fd < 0)
5121 #endif
5122 return fd;
5123 }
5124
5125 if (!inc) {
5126 /* FNAME was not in include_hashtab; insert a new entry. */
5127 inc = (struct include_file *) xmalloc (sizeof (struct include_file));
5128 inc->next = head;
5129 inc->fname = fname;
5130 inc->control_macro = 0;
5131 inc->deps_output = 0;
5132 if (fstat (fd, &inc->st) != 0)
5133 pfatal_with_name (fname);
5134 *phead = inc;
5135
5136 /* Look for another file with the same inode and device. */
5137 if (lookup_ino_include (inc)
5138 && inc->control_macro
5139 && (!inc->control_macro[0] || lookup (inc->control_macro, -1, -1))) {
5140 close (fd);
5141 fd = -2;
5142 }
5143 }
5144
5145 /* For -M, add this file to the dependencies. */
5146 if (! inc->deps_output && (system_include_depth != 0) < print_deps) {
5147 inc->deps_output = 1;
5148 deps_output (fname, ' ');
5149 }
5150
5151 /* Handle -H option. */
5152 if (print_include_names)
5153 fprintf (stderr, "%*s%s\n", indepth, "", fname);
5154 }
5155
5156 if (importing)
5157 inc->control_macro = importing;
5158
5159 *pinc = inc;
5160 return fd;
5161 }
5162
5163 /* Return the remapped name of the include file FILENAME.
5164 SEARCHPTR is the directory being tried from the include file path. */
5165
5166 static char *
5167 remap_include_file (filename, searchptr)
5168 char *filename;
5169 struct file_name_list *searchptr;
5170 {
5171 register struct file_name_map *map;
5172 register char *from;
5173
5174 if (searchptr)
5175 {
5176 if (! searchptr->got_name_map)
5177 {
5178 searchptr->name_map = read_name_map (searchptr->fname);
5179 searchptr->got_name_map = 1;
5180 }
5181
5182 /* Check the mapping for the directory we are using. */
5183 from = filename + strlen (searchptr->fname);
5184 for (map = searchptr->name_map; map; map = map->map_next)
5185 if (! strcmp (map->map_from, from))
5186 return map->map_to;
5187 }
5188
5189 from = base_name (filename);
5190
5191 if (from != filename || !searchptr)
5192 {
5193 /* Try to find a mapping file for the particular directory we are
5194 looking in. Thus #include <sys/types.h> will look up sys/types.h
5195 in /usr/include/header.gcc and look up types.h in
5196 /usr/include/sys/header.gcc. */
5197
5198 char *dir = (char *) alloca (from - filename + 1);
5199 bcopy (filename, dir, from - filename);
5200 dir[from - filename] = '\0';
5201
5202 for (map = read_name_map (dir); map; map = map->map_next)
5203 if (! strcmp (map->map_from, from))
5204 return map->map_to;
5205 }
5206
5207 return filename;
5208 }
5209
5210 /* Insert INC into the include file table, hashed by device and inode number.
5211 If a file with different name but same dev+ino was already in the table,
5212 return 1 and set INC's control macro to the already-known macro. */
5213
5214 static int
5215 lookup_ino_include (inc)
5216 struct include_file *inc;
5217 {
5218 int hash = ((unsigned) (inc->st.st_dev + INO_T_HASH (inc->st.st_ino))
5219 % INCLUDE_HASHSIZE);
5220 struct include_file *i = include_ino_hashtab[hash];
5221 inc->next_ino = i;
5222 include_ino_hashtab[hash] = inc;
5223
5224 for (; i; i = i->next_ino)
5225 if (INO_T_EQ (inc->st.st_ino, i->st.st_ino)
5226 && inc->st.st_dev == i->st.st_dev) {
5227 inc->control_macro = i->control_macro;
5228 return 1;
5229 }
5230
5231 return 0;
5232 }
5233 \f
5234 /* Process file descriptor F, which corresponds to include file INC,
5235 with output to OP.
5236 SYSTEM_HEADER_P is 1 if this file resides in any one of the known
5237 "system" include directories (as decided by the `is_system_include'
5238 function above).
5239 DIRPTR is the link in the dir path through which this file was found,
5240 or 0 if the file name was absolute. */
5241
5242 static void
5243 finclude (f, inc, op, system_header_p, dirptr)
5244 int f;
5245 struct include_file *inc;
5246 FILE_BUF *op;
5247 int system_header_p;
5248 struct file_name_list *dirptr;
5249 {
5250 char *fname = inc->fname;
5251 int i;
5252 FILE_BUF *fp; /* For input stack frame */
5253 int missing_newline = 0;
5254
5255 CHECK_DEPTH (return;);
5256
5257 fp = &instack[indepth + 1];
5258 bzero ((char *) fp, sizeof (FILE_BUF));
5259 fp->nominal_fname = fp->fname = fname;
5260 fp->nominal_fname_len = strlen (fname);
5261 fp->inc = inc;
5262 fp->length = 0;
5263 fp->lineno = 1;
5264 fp->if_stack = if_stack;
5265 fp->system_header_p = system_header_p;
5266 fp->dir = dirptr;
5267
5268 if (S_ISREG (inc->st.st_mode)) {
5269 size_t s = (size_t) inc->st.st_size;
5270 if (s != inc->st.st_size || s + 2 < s)
5271 memory_full ();
5272 fp->buf = (U_CHAR *) xmalloc (s + 2);
5273 fp->bufp = fp->buf;
5274
5275 /* Read the file contents, knowing that s is an upper bound
5276 on the number of bytes we can read. */
5277 fp->length = safe_read (f, (char *) fp->buf, s);
5278 if (fp->length < 0) goto nope;
5279 }
5280 else if (S_ISDIR (inc->st.st_mode)) {
5281 error ("directory `%s' specified in #include", fname);
5282 close (f);
5283 return;
5284 } else {
5285 /* Cannot count its file size before reading.
5286 First read the entire file into heap and
5287 copy them into buffer on stack. */
5288
5289 int bsize = 2000;
5290 int st_size = 0;
5291
5292 fp->buf = (U_CHAR *) xmalloc (bsize + 2);
5293
5294 for (;;) {
5295 i = safe_read (f, (char *) fp->buf + st_size, bsize - st_size);
5296 if (i < 0)
5297 goto nope; /* error! */
5298 st_size += i;
5299 if (st_size != bsize)
5300 break; /* End of file */
5301 bsize *= 2;
5302 fp->buf = (U_CHAR *) xrealloc (fp->buf, bsize + 2);
5303 }
5304 fp->bufp = fp->buf;
5305 fp->length = st_size;
5306 }
5307
5308 if ((fp->length > 0 && fp->buf[fp->length - 1] != '\n')
5309 /* Backslash-newline at end is not good enough. */
5310 || (fp->length > 1 && fp->buf[fp->length - 2] == '\\')) {
5311 fp->buf[fp->length++] = '\n';
5312 missing_newline = 1;
5313 }
5314 fp->buf[fp->length] = '\0';
5315
5316 /* Close descriptor now, so nesting does not use lots of descriptors. */
5317 close (f);
5318
5319 /* Must do this before calling trigraph_pcp, so that the correct file name
5320 will be printed in warning messages. */
5321
5322 indepth++;
5323 input_file_stack_tick++;
5324
5325 if (!no_trigraphs)
5326 trigraph_pcp (fp);
5327
5328 if (warn_white_space)
5329 check_white_space (fp);
5330
5331 output_line_directive (fp, op, 0, enter_file);
5332 rescan (op, 0);
5333
5334 if (missing_newline)
5335 fp->lineno--;
5336
5337 if (pedantic && missing_newline)
5338 pedwarn ("file does not end in newline");
5339
5340 indepth--;
5341 input_file_stack_tick++;
5342 output_line_directive (&instack[indepth], op, 0, leave_file);
5343 free (fp->buf);
5344 return;
5345
5346 nope:
5347
5348 perror_with_name (fname);
5349 close (f);
5350 free (fp->buf);
5351 }
5352
5353 /* Record that inclusion of the include file INC
5354 should be controlled by the macro named MACRO_NAME.
5355 This means that trying to include the file again
5356 will do something if that macro is defined. */
5357
5358 static void
5359 record_control_macro (inc, macro_name)
5360 struct include_file *inc;
5361 U_CHAR *macro_name;
5362 {
5363 if (!inc->control_macro || inc->control_macro[0])
5364 inc->control_macro = macro_name;
5365 }
5366 \f
5367 /* Load the specified precompiled header into core, and verify its
5368 preconditions. PCF indicates the file descriptor to read, which must
5369 be a regular file. *ST is its file status.
5370 FNAME indicates the file name of the original header.
5371 *LIMIT will be set to an address one past the end of the file.
5372 If the preconditions of the file are not satisfied, the buffer is
5373 freed and we return 0. If the preconditions are satisfied, return
5374 the address of the buffer following the preconditions. The buffer, in
5375 this case, should never be freed because various pieces of it will
5376 be referred to until all precompiled strings are output at the end of
5377 the run. */
5378
5379 static char *
5380 check_precompiled (pcf, st, fname, limit)
5381 int pcf;
5382 struct stat *st;
5383 char *fname ATTRIBUTE_UNUSED;
5384 char **limit;
5385 {
5386 int length = 0;
5387 char *buf;
5388 char *cp;
5389
5390 if (pcp_outfile)
5391 return 0;
5392
5393 if (S_ISREG (st->st_mode))
5394 {
5395 size_t s = (size_t) st->st_size;
5396 if (s != st->st_size || s + 2 < s)
5397 memory_full ();
5398 buf = xmalloc (s + 2);
5399 length = safe_read (pcf, buf, s);
5400 if (length < 0)
5401 goto nope;
5402 }
5403 else
5404 abort ();
5405
5406 if (length > 0 && buf[length-1] != '\n')
5407 buf[length++] = '\n';
5408 buf[length] = '\0';
5409
5410 *limit = buf + length;
5411
5412 /* File is in core. Check the preconditions. */
5413 if (!check_preconditions (buf))
5414 goto nope;
5415 for (cp = buf; *cp; cp++)
5416 ;
5417 #ifdef DEBUG_PCP
5418 fprintf (stderr, "Using preinclude %s\n", fname);
5419 #endif
5420 return cp + 1;
5421
5422 nope:
5423 #ifdef DEBUG_PCP
5424 fprintf (stderr, "Cannot use preinclude %s\n", fname);
5425 #endif
5426 free (buf);
5427 return 0;
5428 }
5429
5430 /* PREC (null terminated) points to the preconditions of a
5431 precompiled header. These are a series of #define and #undef
5432 lines which must match the current contents of the hash
5433 table. */
5434
5435 static int
5436 check_preconditions (prec)
5437 char *prec;
5438 {
5439 MACRODEF mdef;
5440 char *lineend;
5441
5442 while (*prec) {
5443 lineend = index (prec, '\n');
5444
5445 if (*prec++ != '#') {
5446 error ("Bad format encountered while reading precompiled file");
5447 return 0;
5448 }
5449 if (!strncmp (prec, "define", 6)) {
5450 HASHNODE *hp;
5451
5452 prec += 6;
5453 mdef = create_definition ((U_CHAR *) prec, (U_CHAR *) lineend, NULL_PTR);
5454
5455 if (mdef.defn == 0)
5456 abort ();
5457
5458 if ((hp = lookup (mdef.symnam, mdef.symlen, -1)) == NULL
5459 || (hp->type != T_MACRO && hp->type != T_CONST)
5460 || (hp->type == T_MACRO
5461 && !compare_defs (mdef.defn, hp->value.defn)
5462 && (mdef.defn->length != 2
5463 || mdef.defn->expansion[0] != '\n'
5464 || mdef.defn->expansion[1] != ' ')))
5465 return 0;
5466 } else if (!strncmp (prec, "undef", 5)) {
5467 char *name;
5468 int len;
5469
5470 prec += 5;
5471 while (is_hor_space[(U_CHAR) *prec])
5472 prec++;
5473 name = prec;
5474 while (is_idchar[(U_CHAR) *prec])
5475 prec++;
5476 len = prec - name;
5477
5478 if (lookup ((U_CHAR *) name, len, -1))
5479 return 0;
5480 } else {
5481 error ("Bad format encountered while reading precompiled file");
5482 return 0;
5483 }
5484 prec = lineend + 1;
5485 }
5486 /* They all passed successfully */
5487 return 1;
5488 }
5489
5490 /* Process the main body of a precompiled file. BUF points to the
5491 string section of the file, following the preconditions. LIMIT is one
5492 character past the end. NAME is the name of the file being read
5493 in. OP is the main output buffer. */
5494
5495 static void
5496 pcfinclude (buf, name, op)
5497 U_CHAR *buf, *name;
5498 FILE_BUF *op;
5499 {
5500 FILE_BUF tmpbuf;
5501 int nstrings;
5502 U_CHAR *cp = buf;
5503
5504 /* First in the file comes 4 bytes indicating the number of strings, */
5505 /* in network byte order. (MSB first). */
5506 nstrings = *cp++;
5507 nstrings = (nstrings << 8) | *cp++;
5508 nstrings = (nstrings << 8) | *cp++;
5509 nstrings = (nstrings << 8) | *cp++;
5510
5511 /* Looping over each string... */
5512 while (nstrings--) {
5513 U_CHAR *string_start;
5514 U_CHAR *endofthiskey;
5515 STRINGDEF *str;
5516 int nkeys;
5517
5518 /* Each string starts with a STRINGDEF structure (str), followed */
5519 /* by the text of the string (string_start) */
5520
5521 /* First skip to a longword boundary */
5522 /* ??? Why a 4-byte boundary? On all machines? */
5523 /* NOTE: This works correctly even if size_t
5524 is narrower than a pointer.
5525 Do not try risky measures here to get another type to use!
5526 Do not include stddef.h--it will fail! */
5527 if ((size_t) cp & 3)
5528 cp += 4 - ((size_t) cp & 3);
5529
5530 /* Now get the string. */
5531 str = (STRINGDEF *) (PTR) cp;
5532 string_start = cp += sizeof (STRINGDEF);
5533
5534 for (; *cp; cp++) /* skip the string */
5535 ;
5536
5537 /* We need to macro expand the string here to ensure that the
5538 proper definition environment is in place. If it were only
5539 expanded when we find out it is needed, macros necessary for
5540 its proper expansion might have had their definitions changed. */
5541 tmpbuf = expand_to_temp_buffer (string_start, cp++, 0, 0);
5542 /* Lineno is already set in the precompiled file */
5543 str->contents = tmpbuf.buf;
5544 str->len = tmpbuf.bufp - tmpbuf.buf;
5545 str->writeflag = 0;
5546 str->filename = name;
5547 str->output_mark = outbuf.bufp - outbuf.buf;
5548
5549 str->chain = 0;
5550 *stringlist_tailp = str;
5551 stringlist_tailp = &str->chain;
5552
5553 /* Next comes a fourbyte number indicating the number of keys
5554 for this string. */
5555 nkeys = *cp++;
5556 nkeys = (nkeys << 8) | *cp++;
5557 nkeys = (nkeys << 8) | *cp++;
5558 nkeys = (nkeys << 8) | *cp++;
5559
5560 /* If this number is -1, then the string is mandatory. */
5561 if (nkeys == -1)
5562 str->writeflag = 1;
5563 else
5564 /* Otherwise, for each key, */
5565 for (; nkeys--; free (tmpbuf.buf), cp = endofthiskey + 1) {
5566 KEYDEF *kp = (KEYDEF *) (PTR) cp;
5567 HASHNODE *hp;
5568 U_CHAR *bp;
5569
5570 /* It starts with a KEYDEF structure */
5571 cp += sizeof (KEYDEF);
5572
5573 /* Find the end of the key. At the end of this for loop we
5574 advance CP to the start of the next key using this variable. */
5575 endofthiskey = cp + strlen ((char *) cp);
5576 kp->str = str;
5577
5578 /* Expand the key, and enter it into the hash table. */
5579 tmpbuf = expand_to_temp_buffer (cp, endofthiskey, 0, 0);
5580 bp = tmpbuf.buf;
5581
5582 while (is_hor_space[*bp])
5583 bp++;
5584 if (!is_idstart[*bp] || bp == tmpbuf.bufp) {
5585 str->writeflag = 1;
5586 continue;
5587 }
5588
5589 hp = lookup (bp, -1, -1);
5590 if (hp == NULL) {
5591 kp->chain = 0;
5592 install (bp, -1, T_PCSTRING, (char *) kp, -1);
5593 }
5594 else if (hp->type == T_PCSTRING) {
5595 kp->chain = hp->value.keydef;
5596 hp->value.keydef = kp;
5597 }
5598 else
5599 str->writeflag = 1;
5600 }
5601 }
5602 /* This output_line_directive serves to switch us back to the current
5603 input file in case some of these strings get output (which will
5604 result in line directives for the header file being output). */
5605 output_line_directive (&instack[indepth], op, 0, enter_file);
5606 }
5607
5608 /* Called from rescan when it hits a key for strings. Mark them all
5609 used and clean up. */
5610
5611 static void
5612 pcstring_used (hp)
5613 HASHNODE *hp;
5614 {
5615 KEYDEF *kp;
5616
5617 for (kp = hp->value.keydef; kp; kp = kp->chain)
5618 kp->str->writeflag = 1;
5619 delete_macro (hp);
5620 }
5621
5622 /* Write the output, interspersing precompiled strings in their
5623 appropriate places. */
5624
5625 static void
5626 write_output ()
5627 {
5628 STRINGDEF *next_string;
5629 U_CHAR *cur_buf_loc;
5630 int line_directive_len = 80;
5631 char *line_directive = xmalloc (line_directive_len);
5632 int len;
5633
5634 /* In each run through the loop, either cur_buf_loc ==
5635 next_string_loc, in which case we print a series of strings, or
5636 it is less than next_string_loc, in which case we write some of
5637 the buffer. */
5638 cur_buf_loc = outbuf.buf;
5639 next_string = stringlist;
5640
5641 while (cur_buf_loc < outbuf.bufp || next_string) {
5642 if (next_string
5643 && cur_buf_loc - outbuf.buf == next_string->output_mark) {
5644 if (next_string->writeflag) {
5645 len = 4 * strlen ((char *) next_string->filename) + 32;
5646 while (len > line_directive_len)
5647 line_directive = xrealloc (line_directive,
5648 line_directive_len *= 2);
5649 sprintf (line_directive, "\n# %d ", next_string->lineno);
5650 strcpy (quote_string (line_directive + strlen (line_directive),
5651 (char *) next_string->filename,
5652 strlen ((char *) next_string->filename)),
5653 "\n");
5654 safe_write (fileno (stdout), line_directive, strlen (line_directive));
5655 safe_write (fileno (stdout),
5656 (char *) next_string->contents, next_string->len);
5657 }
5658 next_string = next_string->chain;
5659 }
5660 else {
5661 len = (next_string
5662 ? (next_string->output_mark
5663 - (cur_buf_loc - outbuf.buf))
5664 : outbuf.bufp - cur_buf_loc);
5665
5666 safe_write (fileno (stdout), (char *) cur_buf_loc, len);
5667 cur_buf_loc += len;
5668 }
5669 }
5670 free (line_directive);
5671 }
5672
5673 /* Pass a directive through to the output file.
5674 BUF points to the contents of the directive, as a contiguous string.
5675 LIMIT points to the first character past the end of the directive.
5676 KEYWORD is the keyword-table entry for the directive. */
5677
5678 static void
5679 pass_thru_directive (buf, limit, op, keyword)
5680 U_CHAR *buf, *limit;
5681 FILE_BUF *op;
5682 struct directive *keyword;
5683 {
5684 register int keyword_length = keyword->length;
5685
5686 check_expand (op, 1 + keyword_length + (limit - buf));
5687 *op->bufp++ = '#';
5688 bcopy (keyword->name, (char *) op->bufp, keyword_length);
5689 op->bufp += keyword_length;
5690 if (limit != buf && buf[0] != ' ')
5691 *op->bufp++ = ' ';
5692 bcopy ((char *) buf, (char *) op->bufp, limit - buf);
5693 op->bufp += (limit - buf);
5694 #if 0
5695 *op->bufp++ = '\n';
5696 /* Count the line we have just made in the output,
5697 to get in sync properly. */
5698 op->lineno++;
5699 #endif
5700 }
5701 \f
5702 /* The arglist structure is built by do_define to tell
5703 collect_definition where the argument names begin. That
5704 is, for a define like "#define f(x,y,z) foo+x-bar*y", the arglist
5705 would contain pointers to the strings x, y, and z.
5706 Collect_definition would then build a DEFINITION node,
5707 with reflist nodes pointing to the places x, y, and z had
5708 appeared. So the arglist is just convenience data passed
5709 between these two routines. It is not kept around after
5710 the current #define has been processed and entered into the
5711 hash table. */
5712
5713 struct arglist {
5714 struct arglist *next;
5715 U_CHAR *name;
5716 int length;
5717 int argno;
5718 char rest_args;
5719 };
5720
5721 /* Create a DEFINITION node from a #define directive. Arguments are
5722 as for do_define. */
5723
5724 static MACRODEF
5725 create_definition (buf, limit, op)
5726 U_CHAR *buf, *limit;
5727 FILE_BUF *op;
5728 {
5729 U_CHAR *bp; /* temp ptr into input buffer */
5730 U_CHAR *symname; /* remember where symbol name starts */
5731 int sym_length; /* and how long it is */
5732 int line = instack[indepth].lineno;
5733 char *file = instack[indepth].nominal_fname;
5734 size_t file_len = instack[indepth].nominal_fname_len;
5735 int rest_args = 0;
5736
5737 DEFINITION *defn;
5738 int arglengths = 0; /* Accumulate lengths of arg names
5739 plus number of args. */
5740 MACRODEF mdef;
5741
5742 bp = buf;
5743
5744 while (is_hor_space[*bp])
5745 bp++;
5746
5747 symname = bp; /* remember where it starts */
5748 sym_length = check_macro_name (bp, 0);
5749 bp += sym_length;
5750
5751 /* Lossage will occur if identifiers or control keywords are broken
5752 across lines using backslash. This is not the right place to take
5753 care of that. */
5754
5755 if (*bp == '(') {
5756 struct arglist *arg_ptrs = NULL;
5757 int argno = 0;
5758
5759 bp++; /* skip '(' */
5760 SKIP_WHITE_SPACE (bp);
5761
5762 /* Loop over macro argument names. */
5763 while (*bp != ')') {
5764 struct arglist *temp;
5765
5766 temp = (struct arglist *) alloca (sizeof (struct arglist));
5767 temp->name = bp;
5768 temp->next = arg_ptrs;
5769 temp->argno = argno++;
5770 temp->rest_args = 0;
5771 arg_ptrs = temp;
5772
5773 if (rest_args)
5774 pedwarn ("another parameter follows `%s'",
5775 rest_extension);
5776
5777 if (!is_idstart[*bp])
5778 {
5779 if (c9x && limit - bp > (long) REST_EXTENSION_LENGTH
5780 && bcmp (rest_extension, bp, REST_EXTENSION_LENGTH) == 0)
5781 {
5782 /* This is the ISO C 9x way to write macros with variable
5783 number of arguments. */
5784 rest_args = 1;
5785 temp->rest_args = 1;
5786 }
5787 else
5788 pedwarn ("invalid character in macro parameter name");
5789 }
5790
5791 /* Find the end of the arg name. */
5792 while (is_idchar[*bp]) {
5793 bp++;
5794 /* do we have a "special" rest-args extension here? */
5795 if (limit - bp > (long) REST_EXTENSION_LENGTH
5796 && bcmp (rest_extension, bp, REST_EXTENSION_LENGTH) == 0) {
5797 if (pedantic && !instack[indepth].system_header_p)
5798 pedwarn ("ANSI C does not allow macro with variable arguments");
5799 rest_args = 1;
5800 temp->rest_args = 1;
5801 break;
5802 }
5803 }
5804 if (bp == temp->name && rest_args == 1)
5805 {
5806 /* This is the ISO C 9x style. */
5807 temp->name = (U_CHAR *) va_args_name;
5808 temp->length = VA_ARGS_NAME_LENGTH;
5809 }
5810 else
5811 temp->length = bp - temp->name;
5812 if (rest_args == 1)
5813 bp += REST_EXTENSION_LENGTH;
5814 arglengths += temp->length + 2;
5815 SKIP_WHITE_SPACE (bp);
5816 if (temp->length == 0 || (*bp != ',' && *bp != ')')) {
5817 error ("badly punctuated parameter list in `#define'");
5818 goto nope;
5819 }
5820 if (*bp == ',') {
5821 bp++;
5822 SKIP_WHITE_SPACE (bp);
5823 /* A comma at this point can only be followed by an identifier. */
5824 if (!is_idstart[*bp]
5825 && !(c9x && limit - bp > (long) REST_EXTENSION_LENGTH
5826 && bcmp (rest_extension, bp, REST_EXTENSION_LENGTH) == 0)) {
5827 error ("badly punctuated parameter list in `#define'");
5828 goto nope;
5829 }
5830 }
5831 if (bp >= limit) {
5832 error ("unterminated parameter list in `#define'");
5833 goto nope;
5834 }
5835 {
5836 struct arglist *otemp;
5837
5838 for (otemp = temp->next; otemp != NULL; otemp = otemp->next)
5839 if (temp->length == otemp->length
5840 && bcmp (temp->name, otemp->name, temp->length) == 0)
5841 {
5842 error ("duplicate argument name `%.*s' in `#define'",
5843 temp->length, temp->name);
5844 goto nope;
5845 }
5846 if (rest_args == 0 && temp->length == VA_ARGS_NAME_LENGTH
5847 && bcmp (temp->name, va_args_name, VA_ARGS_NAME_LENGTH) == 0)
5848 {
5849 error ("\
5850 reserved name `%s' used as argument name in `#define'", va_args_name);
5851 goto nope;
5852 }
5853 }
5854 }
5855
5856 ++bp; /* skip paren */
5857 SKIP_WHITE_SPACE (bp);
5858 /* now everything from bp before limit is the definition. */
5859 defn = collect_expansion (bp, limit, argno, arg_ptrs);
5860 defn->rest_args = rest_args;
5861
5862 /* Now set defn->args.argnames to the result of concatenating
5863 the argument names in reverse order
5864 with comma-space between them. */
5865 defn->args.argnames = (U_CHAR *) xmalloc (arglengths + 1);
5866 {
5867 struct arglist *temp;
5868 int i = 0;
5869 for (temp = arg_ptrs; temp; temp = temp->next) {
5870 bcopy (temp->name, &defn->args.argnames[i], temp->length);
5871 i += temp->length;
5872 if (temp->next != 0) {
5873 defn->args.argnames[i++] = ',';
5874 defn->args.argnames[i++] = ' ';
5875 }
5876 }
5877 defn->args.argnames[i] = 0;
5878 }
5879 } else {
5880 /* Simple expansion or empty definition. */
5881
5882 if (bp < limit)
5883 {
5884 if (is_hor_space[*bp]) {
5885 bp++;
5886 SKIP_WHITE_SPACE (bp);
5887 } else if (sym_length) {
5888 switch (*bp) {
5889 case '!': case '"': case '#': case '%': case '&': case '\'':
5890 case ')': case '*': case '+': case ',': case '-': case '.':
5891 case '/': case ':': case ';': case '<': case '=': case '>':
5892 case '?': case '[': case '\\': case ']': case '^': case '{':
5893 case '|': case '}': case '~':
5894 warning ("missing white space after `#define %.*s'",
5895 sym_length, symname);
5896 break;
5897
5898 default:
5899 pedwarn ("missing white space after `#define %.*s'",
5900 sym_length, symname);
5901 break;
5902 }
5903 }
5904 }
5905 /* Now everything from bp before limit is the definition. */
5906 defn = collect_expansion (bp, limit, -1, NULL_PTR);
5907 defn->args.argnames = (U_CHAR *) "";
5908 }
5909
5910 defn->line = line;
5911 defn->file = file;
5912 defn->file_len = file_len;
5913
5914 /* OP is null if this is a predefinition */
5915 defn->predefined = !op;
5916 mdef.defn = defn;
5917 mdef.symnam = symname;
5918 mdef.symlen = sym_length;
5919
5920 return mdef;
5921
5922 nope:
5923 mdef.defn = 0;
5924 return mdef;
5925 }
5926
5927 /* Process a #define directive.
5928 BUF points to the contents of the #define directive, as a contiguous string.
5929 LIMIT points to the first character past the end of the definition.
5930 KEYWORD is the keyword-table entry for #define. */
5931
5932 static int
5933 do_define (buf, limit, op, keyword)
5934 U_CHAR *buf, *limit;
5935 FILE_BUF *op;
5936 struct directive *keyword;
5937 {
5938 int hashcode;
5939 MACRODEF mdef;
5940 enum node_type newtype = keyword->type == T_DEFINE ? T_MACRO : T_POISON;
5941
5942 /* If this is a precompiler run (with -pcp) pass thru #define directives. */
5943 if (pcp_outfile && op)
5944 pass_thru_directive (buf, limit, op, keyword);
5945
5946 mdef = create_definition (buf, limit, op);
5947 if (mdef.defn == 0)
5948 goto nope;
5949
5950 hashcode = hashf (mdef.symnam, mdef.symlen, HASHSIZE);
5951
5952 {
5953 HASHNODE *hp;
5954 if ((hp = lookup (mdef.symnam, mdef.symlen, hashcode)) != NULL) {
5955 int ok = 0;
5956 /* Redefining a precompiled key is ok. */
5957 if (hp->type == T_PCSTRING)
5958 ok = 1;
5959 /* Redefining a poisoned identifier is even worse than `not ok'. */
5960 else if (hp->type == T_POISON)
5961 ok = -1;
5962 /* Poisoning anything else is not ok.
5963 The poison should always come first. */
5964 else if (newtype == T_POISON)
5965 ok = 0;
5966 /* Redefining a macro is ok if the definitions are the same. */
5967 else if (hp->type == T_MACRO)
5968 ok = ! compare_defs (mdef.defn, hp->value.defn);
5969 /* Redefining a constant is ok with -D. */
5970 else if (hp->type == T_CONST)
5971 ok = ! done_initializing;
5972
5973 /* Print the warning or error if it's not ok. */
5974 if (ok <= 0)
5975 {
5976 /* If we are passing through #define and #undef directives, do
5977 that for this re-definition now. */
5978 if (debug_output && op)
5979 pass_thru_directive (buf, limit, op, keyword);
5980
5981 if (hp->type == T_POISON)
5982 error ("redefining poisoned `%.*s'", mdef.symlen, mdef.symnam);
5983 else
5984 pedwarn ("`%.*s' redefined", mdef.symlen, mdef.symnam);
5985 if (hp->type == T_MACRO)
5986 pedwarn_with_file_and_line (hp->value.defn->file,
5987 hp->value.defn->file_len,
5988 hp->value.defn->line,
5989 "this is the location of the previous definition");
5990 }
5991 if (hp->type != T_POISON)
5992 {
5993 /* Replace the old definition. */
5994 hp->type = newtype;
5995 hp->value.defn = mdef.defn;
5996 }
5997 } else {
5998 /* If we are passing through #define and #undef directives, do
5999 that for this new definition now. */
6000 if (debug_output && op)
6001 pass_thru_directive (buf, limit, op, keyword);
6002 install (mdef.symnam, mdef.symlen, newtype,
6003 (char *) mdef.defn, hashcode);
6004 }
6005 }
6006
6007 return 0;
6008
6009 nope:
6010
6011 return 1;
6012 }
6013 \f
6014 /* Check a purported macro name SYMNAME, and yield its length.
6015 ASSERTION is nonzero if this is really for an assertion name. */
6016
6017 static int
6018 check_macro_name (symname, assertion)
6019 U_CHAR *symname;
6020 int assertion;
6021 {
6022 U_CHAR *p;
6023 int sym_length;
6024
6025 for (p = symname; is_idchar[*p]; p++)
6026 ;
6027 sym_length = p - symname;
6028 if (sym_length == 0
6029 || (sym_length == 1 && *symname == 'L' && (*p == '\'' || *p == '"')))
6030 error (assertion ? "invalid assertion name" : "invalid macro name");
6031 else if (!is_idstart[*symname]
6032 || (sym_length == 7 && ! bcmp (symname, "defined", 7)))
6033 error ((assertion
6034 ? "invalid assertion name `%.*s'"
6035 : "invalid macro name `%.*s'"),
6036 sym_length, symname);
6037 return sym_length;
6038 }
6039
6040 /* Return zero if two DEFINITIONs are isomorphic. */
6041
6042 static int
6043 compare_defs (d1, d2)
6044 DEFINITION *d1, *d2;
6045 {
6046 register struct reflist *a1, *a2;
6047 register U_CHAR *p1 = d1->expansion;
6048 register U_CHAR *p2 = d2->expansion;
6049 int first = 1;
6050
6051 if (d1->nargs != d2->nargs)
6052 return 1;
6053 if (pedantic
6054 && strcmp ((char *)d1->args.argnames, (char *)d2->args.argnames))
6055 return 1;
6056 for (a1 = d1->pattern, a2 = d2->pattern; a1 && a2;
6057 a1 = a1->next, a2 = a2->next) {
6058 if (!((a1->nchars == a2->nchars && ! bcmp (p1, p2, a1->nchars))
6059 || ! comp_def_part (first, p1, a1->nchars, p2, a2->nchars, 0))
6060 || a1->argno != a2->argno
6061 || a1->stringify != a2->stringify
6062 || a1->raw_before != a2->raw_before
6063 || a1->raw_after != a2->raw_after)
6064 return 1;
6065 first = 0;
6066 p1 += a1->nchars;
6067 p2 += a2->nchars;
6068 }
6069 if (a1 != a2)
6070 return 1;
6071 if (comp_def_part (first, p1, d1->length - (p1 - d1->expansion),
6072 p2, d2->length - (p2 - d2->expansion), 1))
6073 return 1;
6074 return 0;
6075 }
6076
6077 /* Return 1 if two parts of two macro definitions are effectively different.
6078 One of the parts starts at BEG1 and has LEN1 chars;
6079 the other has LEN2 chars at BEG2.
6080 Any sequence of whitespace matches any other sequence of whitespace.
6081 FIRST means these parts are the first of a macro definition;
6082 so ignore leading whitespace entirely.
6083 LAST means these parts are the last of a macro definition;
6084 so ignore trailing whitespace entirely. */
6085
6086 static int
6087 comp_def_part (first, beg1, len1, beg2, len2, last)
6088 int first;
6089 U_CHAR *beg1, *beg2;
6090 int len1, len2;
6091 int last;
6092 {
6093 register U_CHAR *end1 = beg1 + len1;
6094 register U_CHAR *end2 = beg2 + len2;
6095 if (first) {
6096 while (beg1 != end1 && is_space[*beg1]) beg1++;
6097 while (beg2 != end2 && is_space[*beg2]) beg2++;
6098 }
6099 if (last) {
6100 while (beg1 != end1 && is_space[end1[-1]]) end1--;
6101 while (beg2 != end2 && is_space[end2[-1]]) end2--;
6102 }
6103 while (beg1 != end1 && beg2 != end2) {
6104 if (is_space[*beg1] && is_space[*beg2]) {
6105 while (beg1 != end1 && is_space[*beg1]) beg1++;
6106 while (beg2 != end2 && is_space[*beg2]) beg2++;
6107 } else if (*beg1 == *beg2) {
6108 beg1++; beg2++;
6109 } else break;
6110 }
6111 return (beg1 != end1) || (beg2 != end2);
6112 }
6113 \f
6114 /* Read a replacement list for a macro with parameters.
6115 Build the DEFINITION structure.
6116 Reads characters of text starting at BUF until END.
6117 ARGLIST specifies the formal parameters to look for
6118 in the text of the definition; NARGS is the number of args
6119 in that list, or -1 for a macro name that wants no argument list.
6120 MACRONAME is the macro name itself (so we can avoid recursive expansion)
6121 and NAMELEN is its length in characters.
6122
6123 Note that comments, backslash-newlines, and leading white space
6124 have already been deleted from the argument. */
6125
6126 /* If there is no trailing whitespace, a Newline Space is added at the end
6127 to prevent concatenation that would be contrary to the standard. */
6128
6129 static DEFINITION *
6130 collect_expansion (buf, end, nargs, arglist)
6131 U_CHAR *buf, *end;
6132 int nargs;
6133 struct arglist *arglist;
6134 {
6135 DEFINITION *defn;
6136 register U_CHAR *p, *limit, *lastp, *exp_p;
6137 struct reflist *endpat = NULL;
6138 /* Pointer to first nonspace after last ## seen. */
6139 U_CHAR *concat = 0;
6140 /* Pointer to first nonspace after last single-# seen. */
6141 U_CHAR *stringify = 0;
6142 /* How those tokens were spelled. */
6143 enum sharp_token_type concat_sharp_token_type = NO_SHARP_TOKEN;
6144 enum sharp_token_type stringify_sharp_token_type = NO_SHARP_TOKEN;
6145 int maxsize;
6146 int expected_delimiter = '\0';
6147
6148 /* Scan thru the replacement list, ignoring comments and quoted
6149 strings, picking up on the macro calls. It does a linear search
6150 thru the arg list on every potential symbol. Profiling might say
6151 that something smarter should happen. */
6152
6153 if (end < buf)
6154 abort ();
6155
6156 /* Find the beginning of the trailing whitespace. */
6157 limit = end;
6158 p = buf;
6159 while (p < limit && is_space[limit[-1]]) limit--;
6160
6161 /* Allocate space for the text in the macro definition.
6162 Each input char may or may not need 1 byte,
6163 so this is an upper bound.
6164 The extra 3 are for invented trailing newline-marker and final null. */
6165 maxsize = (sizeof (DEFINITION)
6166 + (limit - p) + 3);
6167 defn = (DEFINITION *) xcalloc (1, maxsize);
6168
6169 defn->nargs = nargs;
6170 exp_p = defn->expansion = (U_CHAR *) defn + sizeof (DEFINITION);
6171 lastp = exp_p;
6172
6173 if (p[0] == '#'
6174 ? p[1] == '#'
6175 : p[0] == '%' && p[1] == ':' && p[2] == '%' && p[3] == ':') {
6176 error ("`##' at start of macro definition");
6177 p += p[0] == '#' ? 2 : 4;
6178 }
6179
6180 /* Process the main body of the definition. */
6181 while (p < limit) {
6182 int skipped_arg = 0;
6183 register U_CHAR c = *p++;
6184
6185 *exp_p++ = c;
6186
6187 if (!traditional) {
6188 switch (c) {
6189 case '\'':
6190 case '\"':
6191 if (expected_delimiter != '\0') {
6192 if (c == expected_delimiter)
6193 expected_delimiter = '\0';
6194 } else
6195 expected_delimiter = c;
6196 break;
6197
6198 case '\\':
6199 if (expected_delimiter) {
6200 /* In a string, backslash goes through
6201 and makes next char ordinary. */
6202 *exp_p++ = *p++;
6203 }
6204 break;
6205
6206 case '%':
6207 if (!expected_delimiter && *p == ':') {
6208 /* %: is not a digraph if preceded by an odd number of '<'s. */
6209 U_CHAR *p0 = p - 1;
6210 while (buf < p0 && p0[-1] == '<')
6211 p0--;
6212 if ((p - p0) & 1) {
6213 /* Treat %:%: as ## and %: as #. */
6214 if (p[1] == '%' && p[2] == ':') {
6215 p += 2;
6216 goto sharp_sharp_token;
6217 }
6218 if (nargs >= 0) {
6219 p++;
6220 goto sharp_token;
6221 }
6222 }
6223 }
6224 break;
6225
6226 case '#':
6227 /* # is ordinary inside a string. */
6228 if (expected_delimiter)
6229 break;
6230 if (*p == '#') {
6231 sharp_sharp_token:
6232 /* ##: concatenate preceding and following tokens. */
6233 /* Take out the first #, discard preceding whitespace. */
6234 exp_p--;
6235 while (exp_p > lastp && is_hor_space[exp_p[-1]])
6236 --exp_p;
6237 /* Skip the second #. */
6238 p++;
6239 concat_sharp_token_type = c;
6240 if (is_hor_space[*p]) {
6241 concat_sharp_token_type = c + 1;
6242 p++;
6243 SKIP_WHITE_SPACE (p);
6244 }
6245 concat = p;
6246 if (p == limit)
6247 error ("`##' at end of macro definition");
6248 } else if (nargs >= 0) {
6249 /* Single #: stringify following argument ref.
6250 Don't leave the # in the expansion. */
6251 sharp_token:
6252 exp_p--;
6253 stringify_sharp_token_type = c;
6254 if (is_hor_space[*p]) {
6255 stringify_sharp_token_type = c + 1;
6256 p++;
6257 SKIP_WHITE_SPACE (p);
6258 }
6259 if (! is_idstart[*p] || nargs == 0
6260 || (*p == 'L' && (p[1] == '\'' || p[1] == '"')))
6261 error ("`#' operator is not followed by a macro argument name");
6262 else
6263 stringify = p;
6264 }
6265 break;
6266 }
6267 } else {
6268 /* In -traditional mode, recognize arguments inside strings and
6269 character constants, and ignore special properties of #.
6270 Arguments inside strings are considered "stringified", but no
6271 extra quote marks are supplied. */
6272 switch (c) {
6273 case '\'':
6274 case '\"':
6275 if (expected_delimiter != '\0') {
6276 if (c == expected_delimiter)
6277 expected_delimiter = '\0';
6278 } else
6279 expected_delimiter = c;
6280 break;
6281
6282 case '\\':
6283 /* Backslash quotes delimiters and itself, but not macro args. */
6284 if (expected_delimiter != 0 && p < limit
6285 && (*p == expected_delimiter || *p == '\\')) {
6286 *exp_p++ = *p++;
6287 continue;
6288 }
6289 break;
6290
6291 case '/':
6292 if (expected_delimiter != '\0') /* No comments inside strings. */
6293 break;
6294 if (*p == '*') {
6295 /* If we find a comment that wasn't removed by handle_directive,
6296 this must be -traditional. So replace the comment with
6297 nothing at all. */
6298 exp_p--;
6299 while (++p < limit) {
6300 if (p[0] == '*' && p[1] == '/') {
6301 p += 2;
6302 break;
6303 }
6304 }
6305 #if 0
6306 /* Mark this as a concatenation-point, as if it had been ##. */
6307 concat = p;
6308 #endif
6309 }
6310 break;
6311 }
6312 }
6313
6314 #ifdef MULTIBYTE_CHARS
6315 /* Handle multibyte characters inside string and character literals. */
6316 if (expected_delimiter != '\0')
6317 {
6318 int length;
6319 --p;
6320 length = local_mblen (p, limit - p);
6321 if (length > 1)
6322 {
6323 --exp_p;
6324 bcopy (p, exp_p, length);
6325 p += length;
6326 exp_p += length;
6327 continue;
6328 }
6329 ++p;
6330 }
6331 #endif
6332
6333 /* Handle the start of a symbol. */
6334 if (is_idchar[c] && nargs > 0) {
6335 U_CHAR *id_beg = p - 1;
6336 int id_len;
6337
6338 --exp_p;
6339 while (p != limit && is_idchar[*p]) p++;
6340 id_len = p - id_beg;
6341
6342 if (is_idstart[c]
6343 && ! (id_len == 1 && c == 'L' && (*p == '\'' || *p == '"'))) {
6344 register struct arglist *arg;
6345
6346 for (arg = arglist; arg != NULL; arg = arg->next) {
6347 struct reflist *tpat;
6348
6349 if (arg->name[0] == c
6350 && arg->length == id_len
6351 && bcmp (arg->name, id_beg, id_len) == 0) {
6352 enum sharp_token_type tpat_stringify;
6353 if (expected_delimiter) {
6354 if (warn_stringify) {
6355 if (traditional) {
6356 warning ("macro argument `%.*s' is stringified.",
6357 id_len, arg->name);
6358 } else {
6359 warning ("macro arg `%.*s' would be stringified with -traditional.",
6360 id_len, arg->name);
6361 }
6362 }
6363 /* If ANSI, don't actually substitute inside a string. */
6364 if (!traditional)
6365 break;
6366 tpat_stringify = SHARP_TOKEN;
6367 } else {
6368 tpat_stringify
6369 = (stringify == id_beg
6370 ? stringify_sharp_token_type : NO_SHARP_TOKEN);
6371 }
6372 /* make a pat node for this arg and append it to the end of
6373 the pat list */
6374 tpat = (struct reflist *) xmalloc (sizeof (struct reflist));
6375 tpat->next = NULL;
6376 tpat->raw_before
6377 = concat == id_beg ? concat_sharp_token_type : NO_SHARP_TOKEN;
6378 tpat->raw_after = NO_SHARP_TOKEN;
6379 tpat->rest_args = arg->rest_args;
6380 tpat->stringify = tpat_stringify;
6381
6382 if (endpat == NULL)
6383 defn->pattern = tpat;
6384 else
6385 endpat->next = tpat;
6386 endpat = tpat;
6387
6388 tpat->argno = arg->argno;
6389 tpat->nchars = exp_p - lastp;
6390 {
6391 register U_CHAR *p1 = p;
6392 SKIP_WHITE_SPACE (p1);
6393 if (p1[0]=='#'
6394 ? p1[1]=='#'
6395 : p1[0]=='%' && p1[1]==':' && p1[2]=='%' && p1[3]==':')
6396 tpat->raw_after = p1[0] + (p != p1);
6397 }
6398 lastp = exp_p; /* place to start copying from next time */
6399 skipped_arg = 1;
6400 break;
6401 }
6402 }
6403 }
6404
6405 /* If this was not a macro arg, copy it into the expansion. */
6406 if (! skipped_arg) {
6407 register U_CHAR *lim1 = p;
6408 p = id_beg;
6409 while (p != lim1)
6410 *exp_p++ = *p++;
6411 if (stringify == id_beg)
6412 error ("`#' operator should be followed by a macro argument name");
6413 }
6414 }
6415 }
6416
6417 if (!traditional && expected_delimiter == 0) {
6418 /* If ANSI, put in a newline-space marker to prevent token pasting.
6419 But not if "inside a string" (which in ANSI mode happens only for
6420 -D option). */
6421 *exp_p++ = '\n';
6422 *exp_p++ = ' ';
6423 }
6424
6425 *exp_p = '\0';
6426
6427 defn->length = exp_p - defn->expansion;
6428
6429 /* Crash now if we overrun the allocated size. */
6430 if (defn->length + 1 > maxsize)
6431 abort ();
6432
6433 #if 0
6434 /* This isn't worth the time it takes. */
6435 /* give back excess storage */
6436 defn->expansion = (U_CHAR *) xrealloc (defn->expansion, defn->length + 1);
6437 #endif
6438
6439 return defn;
6440 }
6441 \f
6442 static int
6443 do_assert (buf, limit, op, keyword)
6444 U_CHAR *buf, *limit;
6445 FILE_BUF *op ATTRIBUTE_UNUSED;
6446 struct directive *keyword ATTRIBUTE_UNUSED;
6447 {
6448 U_CHAR *bp; /* temp ptr into input buffer */
6449 U_CHAR *symname; /* remember where symbol name starts */
6450 int sym_length; /* and how long it is */
6451 struct arglist *tokens = NULL;
6452
6453 if (pedantic && done_initializing && !instack[indepth].system_header_p)
6454 pedwarn ("ANSI C does not allow `#assert'");
6455
6456 bp = buf;
6457
6458 while (is_hor_space[*bp])
6459 bp++;
6460
6461 symname = bp; /* remember where it starts */
6462 sym_length = check_macro_name (bp, 1);
6463 bp += sym_length;
6464 /* #define doesn't do this, but we should. */
6465 SKIP_WHITE_SPACE (bp);
6466
6467 /* Lossage will occur if identifiers or control tokens are broken
6468 across lines using backslash. This is not the right place to take
6469 care of that. */
6470
6471 if (*bp != '(') {
6472 error ("missing token-sequence in `#assert'");
6473 return 1;
6474 }
6475
6476 {
6477 int error_flag = 0;
6478
6479 bp++; /* skip '(' */
6480 SKIP_WHITE_SPACE (bp);
6481
6482 tokens = read_token_list (&bp, limit, &error_flag);
6483 if (error_flag)
6484 return 1;
6485 if (tokens == 0) {
6486 error ("empty token-sequence in `#assert'");
6487 return 1;
6488 }
6489
6490 ++bp; /* skip paren */
6491 SKIP_WHITE_SPACE (bp);
6492 }
6493
6494 /* If this name isn't already an assertion name, make it one.
6495 Error if it was already in use in some other way. */
6496
6497 {
6498 ASSERTION_HASHNODE *hp;
6499 int hashcode = hashf (symname, sym_length, ASSERTION_HASHSIZE);
6500 struct tokenlist_list *value
6501 = (struct tokenlist_list *) xmalloc (sizeof (struct tokenlist_list));
6502
6503 hp = assertion_lookup (symname, sym_length, hashcode);
6504 if (hp == NULL) {
6505 if (sym_length == 7 && ! bcmp (symname, "defined", 7))
6506 error ("`defined' redefined as assertion");
6507 hp = assertion_install (symname, sym_length, hashcode);
6508 }
6509
6510 /* Add the spec'd token-sequence to the list of such. */
6511 value->tokens = tokens;
6512 value->next = hp->value;
6513 hp->value = value;
6514 }
6515
6516 return 0;
6517 }
6518 \f
6519 static int
6520 do_unassert (buf, limit, op, keyword)
6521 U_CHAR *buf, *limit;
6522 FILE_BUF *op ATTRIBUTE_UNUSED;
6523 struct directive *keyword ATTRIBUTE_UNUSED;
6524 {
6525 U_CHAR *bp; /* temp ptr into input buffer */
6526 U_CHAR *symname; /* remember where symbol name starts */
6527 int sym_length; /* and how long it is */
6528
6529 struct arglist *tokens = NULL;
6530 int tokens_specified = 0;
6531
6532 if (pedantic && done_initializing && !instack[indepth].system_header_p)
6533 pedwarn ("ANSI C does not allow `#unassert'");
6534
6535 bp = buf;
6536
6537 while (is_hor_space[*bp])
6538 bp++;
6539
6540 symname = bp; /* remember where it starts */
6541 sym_length = check_macro_name (bp, 1);
6542 bp += sym_length;
6543 /* #define doesn't do this, but we should. */
6544 SKIP_WHITE_SPACE (bp);
6545
6546 /* Lossage will occur if identifiers or control tokens are broken
6547 across lines using backslash. This is not the right place to take
6548 care of that. */
6549
6550 if (*bp == '(') {
6551 int error_flag = 0;
6552
6553 bp++; /* skip '(' */
6554 SKIP_WHITE_SPACE (bp);
6555
6556 tokens = read_token_list (&bp, limit, &error_flag);
6557 if (error_flag)
6558 return 1;
6559 if (tokens == 0) {
6560 error ("empty token list in `#unassert'");
6561 return 1;
6562 }
6563
6564 tokens_specified = 1;
6565
6566 ++bp; /* skip paren */
6567 SKIP_WHITE_SPACE (bp);
6568 }
6569
6570 {
6571 ASSERTION_HASHNODE *hp;
6572 int hashcode = hashf (symname, sym_length, ASSERTION_HASHSIZE);
6573 struct tokenlist_list *tail, *prev;
6574
6575 hp = assertion_lookup (symname, sym_length, hashcode);
6576 if (hp == NULL)
6577 return 1;
6578
6579 /* If no token list was specified, then eliminate this assertion
6580 entirely. */
6581 if (! tokens_specified) {
6582 struct tokenlist_list *next;
6583 for (tail = hp->value; tail; tail = next) {
6584 next = tail->next;
6585 free_token_list (tail->tokens);
6586 free (tail);
6587 }
6588 delete_assertion (hp);
6589 } else {
6590 /* If a list of tokens was given, then delete any matching list. */
6591
6592 tail = hp->value;
6593 prev = 0;
6594 while (tail) {
6595 struct tokenlist_list *next = tail->next;
6596 if (compare_token_lists (tail->tokens, tokens)) {
6597 if (prev)
6598 prev->next = next;
6599 else
6600 hp->value = tail->next;
6601 free_token_list (tail->tokens);
6602 free (tail);
6603 } else {
6604 prev = tail;
6605 }
6606 tail = next;
6607 }
6608 }
6609 }
6610
6611 return 0;
6612 }
6613 \f
6614 /* Test whether there is an assertion named NAME
6615 and optionally whether it has an asserted token list TOKENS.
6616 NAME is not null terminated; its length is SYM_LENGTH.
6617 If TOKENS_SPECIFIED is 0, then don't check for any token list. */
6618
6619 int
6620 check_assertion (name, sym_length, tokens_specified, tokens)
6621 U_CHAR *name;
6622 int sym_length;
6623 int tokens_specified;
6624 struct arglist *tokens;
6625 {
6626 ASSERTION_HASHNODE *hp;
6627 int hashcode = hashf (name, sym_length, ASSERTION_HASHSIZE);
6628
6629 if (pedantic && !instack[indepth].system_header_p)
6630 pedwarn ("ANSI C does not allow testing assertions");
6631
6632 hp = assertion_lookup (name, sym_length, hashcode);
6633 if (hp == NULL)
6634 /* It is not an assertion; just return false. */
6635 return 0;
6636
6637 /* If no token list was specified, then value is 1. */
6638 if (! tokens_specified)
6639 return 1;
6640
6641 {
6642 struct tokenlist_list *tail;
6643
6644 tail = hp->value;
6645
6646 /* If a list of tokens was given,
6647 then succeed if the assertion records a matching list. */
6648
6649 while (tail) {
6650 if (compare_token_lists (tail->tokens, tokens))
6651 return 1;
6652 tail = tail->next;
6653 }
6654
6655 /* Fail if the assertion has no matching list. */
6656 return 0;
6657 }
6658 }
6659
6660 /* Compare two lists of tokens for equality including order of tokens. */
6661
6662 static int
6663 compare_token_lists (l1, l2)
6664 struct arglist *l1, *l2;
6665 {
6666 while (l1 && l2) {
6667 if (l1->length != l2->length)
6668 return 0;
6669 if (bcmp (l1->name, l2->name, l1->length))
6670 return 0;
6671 l1 = l1->next;
6672 l2 = l2->next;
6673 }
6674
6675 /* Succeed if both lists end at the same time. */
6676 return l1 == l2;
6677 }
6678 \f
6679 /* Read a space-separated list of tokens ending in a close parenthesis.
6680 Return a list of strings, in the order they were written.
6681 (In case of error, return 0 and store -1 in *ERROR_FLAG.)
6682 Parse the text starting at *BPP, and update *BPP.
6683 Don't parse beyond LIMIT. */
6684
6685 static struct arglist *
6686 read_token_list (bpp, limit, error_flag)
6687 U_CHAR **bpp;
6688 U_CHAR *limit;
6689 int *error_flag;
6690 {
6691 struct arglist *token_ptrs = 0;
6692 U_CHAR *bp = *bpp;
6693 int depth = 1;
6694
6695 *error_flag = 0;
6696
6697 /* Loop over the assertion value tokens. */
6698 while (depth > 0) {
6699 struct arglist *temp;
6700 int eofp = 0;
6701 U_CHAR *beg = bp;
6702
6703 /* Find the end of the token. */
6704 if (*bp == '(') {
6705 bp++;
6706 depth++;
6707 } else if (*bp == ')') {
6708 depth--;
6709 if (depth == 0)
6710 break;
6711 bp++;
6712 } else if (*bp == '"' || *bp == '\'')
6713 bp = skip_quoted_string (bp, limit, 0, NULL_PTR, NULL_PTR, &eofp);
6714 else
6715 while (! is_hor_space[*bp] && *bp != '(' && *bp != ')'
6716 && *bp != '"' && *bp != '\'' && bp != limit)
6717 bp++;
6718
6719 temp = (struct arglist *) xmalloc (sizeof (struct arglist));
6720 temp->name = (U_CHAR *) xmalloc (bp - beg + 1);
6721 bcopy ((char *) beg, (char *) temp->name, bp - beg);
6722 temp->name[bp - beg] = 0;
6723 temp->next = token_ptrs;
6724 token_ptrs = temp;
6725 temp->length = bp - beg;
6726
6727 SKIP_WHITE_SPACE (bp);
6728
6729 if (bp >= limit) {
6730 error ("unterminated token sequence in `#assert' or `#unassert'");
6731 *error_flag = -1;
6732 return 0;
6733 }
6734 }
6735 *bpp = bp;
6736
6737 /* We accumulated the names in reverse order.
6738 Now reverse them to get the proper order. */
6739 {
6740 register struct arglist *prev = 0, *this, *next;
6741 for (this = token_ptrs; this; this = next) {
6742 next = this->next;
6743 this->next = prev;
6744 prev = this;
6745 }
6746 return prev;
6747 }
6748 }
6749
6750 static void
6751 free_token_list (tokens)
6752 struct arglist *tokens;
6753 {
6754 while (tokens) {
6755 struct arglist *next = tokens->next;
6756 free (tokens->name);
6757 free (tokens);
6758 tokens = next;
6759 }
6760 }
6761 \f
6762 /* Install a name in the assertion hash table.
6763
6764 If LEN is >= 0, it is the length of the name.
6765 Otherwise, compute the length by scanning the entire name.
6766
6767 If HASH is >= 0, it is the precomputed hash code.
6768 Otherwise, compute the hash code. */
6769
6770 static ASSERTION_HASHNODE *
6771 assertion_install (name, len, hash)
6772 U_CHAR *name;
6773 int len;
6774 int hash;
6775 {
6776 register ASSERTION_HASHNODE *hp;
6777 register int i, bucket;
6778 register U_CHAR *p, *q;
6779
6780 i = sizeof (ASSERTION_HASHNODE) + len + 1;
6781 hp = (ASSERTION_HASHNODE *) xmalloc (i);
6782 bucket = hash;
6783 hp->bucket_hdr = &assertion_hashtab[bucket];
6784 hp->next = assertion_hashtab[bucket];
6785 assertion_hashtab[bucket] = hp;
6786 hp->prev = NULL;
6787 if (hp->next != NULL)
6788 hp->next->prev = hp;
6789 hp->length = len;
6790 hp->value = 0;
6791 hp->name = ((U_CHAR *) hp) + sizeof (ASSERTION_HASHNODE);
6792 p = hp->name;
6793 q = name;
6794 for (i = 0; i < len; i++)
6795 *p++ = *q++;
6796 hp->name[len] = 0;
6797 return hp;
6798 }
6799
6800 /* Find the most recent hash node for name "name" (ending with first
6801 non-identifier char) installed by install
6802
6803 If LEN is >= 0, it is the length of the name.
6804 Otherwise, compute the length by scanning the entire name.
6805
6806 If HASH is >= 0, it is the precomputed hash code.
6807 Otherwise, compute the hash code. */
6808
6809 static ASSERTION_HASHNODE *
6810 assertion_lookup (name, len, hash)
6811 U_CHAR *name;
6812 int len;
6813 int hash;
6814 {
6815 register ASSERTION_HASHNODE *bucket;
6816
6817 bucket = assertion_hashtab[hash];
6818 while (bucket) {
6819 if (bucket->length == len && bcmp (bucket->name, name, len) == 0)
6820 return bucket;
6821 bucket = bucket->next;
6822 }
6823 return NULL;
6824 }
6825
6826 static void
6827 delete_assertion (hp)
6828 ASSERTION_HASHNODE *hp;
6829 {
6830
6831 if (hp->prev != NULL)
6832 hp->prev->next = hp->next;
6833 if (hp->next != NULL)
6834 hp->next->prev = hp->prev;
6835
6836 /* Make sure that the bucket chain header that the deleted guy was
6837 on points to the right thing afterwards. */
6838 if (hp == *hp->bucket_hdr)
6839 *hp->bucket_hdr = hp->next;
6840
6841 free (hp);
6842 }
6843 \f
6844 /*
6845 * interpret #line directive. Remembers previously seen fnames
6846 * in its very own hash table.
6847 */
6848 #define FNAME_HASHSIZE 37
6849
6850 static int
6851 do_line (buf, limit, op, keyword)
6852 U_CHAR *buf, *limit;
6853 FILE_BUF *op;
6854 struct directive *keyword ATTRIBUTE_UNUSED;
6855 {
6856 register U_CHAR *bp;
6857 FILE_BUF *ip = &instack[indepth];
6858 FILE_BUF tem;
6859 int new_lineno;
6860 enum file_change_code file_change = same_file;
6861
6862 /* Expand any macros. */
6863 tem = expand_to_temp_buffer (buf, limit, 0, 0);
6864
6865 /* Point to macroexpanded line, which is null-terminated now. */
6866 bp = tem.buf;
6867 limit = tem.bufp;
6868 SKIP_WHITE_SPACE (bp);
6869
6870 if (!ISDIGIT (*bp)) {
6871 error ("invalid format `#line' directive");
6872 return 0;
6873 }
6874
6875 /* The Newline at the end of this line remains to be processed.
6876 To put the next line at the specified line number,
6877 we must store a line number now that is one less. */
6878 new_lineno = atoi ((char *) bp) - 1;
6879
6880 /* NEW_LINENO is one less than the actual line number here. */
6881 if (pedantic && new_lineno < 0)
6882 pedwarn ("line number out of range in `#line' directive");
6883
6884 /* skip over the line number. */
6885 while (ISDIGIT (*bp))
6886 bp++;
6887
6888 #if 0 /* #line 10"foo.c" is supposed to be allowed. */
6889 if (*bp && !is_space[*bp]) {
6890 error ("invalid format `#line' directive");
6891 return;
6892 }
6893 #endif
6894
6895 SKIP_WHITE_SPACE (bp);
6896
6897 if (*bp == '\"') {
6898 static HASHNODE *fname_table[FNAME_HASHSIZE];
6899 HASHNODE *hp, **hash_bucket;
6900 U_CHAR *fname, *p;
6901 int fname_length;
6902
6903 fname = ++bp;
6904
6905 /* Turn the file name, which is a character string literal,
6906 into a null-terminated string. Do this in place. */
6907 p = bp;
6908 for (;;)
6909 switch ((*p++ = *bp++)) {
6910 case '\\':
6911 if (! ignore_escape_flag)
6912 {
6913 char *bpc = (char *) bp;
6914 HOST_WIDEST_INT c = parse_escape (&bpc, (HOST_WIDEST_INT) (U_CHAR) (-1));
6915 bp = (U_CHAR *) bpc;
6916 if (c < 0)
6917 p--;
6918 else
6919 p[-1] = c;
6920 }
6921 break;
6922
6923 case '\"':
6924 *--p = 0;
6925 goto fname_done;
6926 }
6927 fname_done:
6928 fname_length = p - fname;
6929
6930 SKIP_WHITE_SPACE (bp);
6931 if (*bp) {
6932 if (pedantic)
6933 pedwarn ("garbage at end of `#line' directive");
6934 if (*bp == '1')
6935 file_change = enter_file;
6936 else if (*bp == '2')
6937 file_change = leave_file;
6938 else if (*bp == '3')
6939 ip->system_header_p = 1;
6940 else if (*bp == '4')
6941 ip->system_header_p = 2;
6942 else {
6943 error ("invalid format `#line' directive");
6944 return 0;
6945 }
6946
6947 bp++;
6948 SKIP_WHITE_SPACE (bp);
6949 if (*bp == '3') {
6950 ip->system_header_p = 1;
6951 bp++;
6952 SKIP_WHITE_SPACE (bp);
6953 }
6954 if (*bp == '4') {
6955 ip->system_header_p = 2;
6956 bp++;
6957 SKIP_WHITE_SPACE (bp);
6958 }
6959 if (*bp) {
6960 error ("invalid format `#line' directive");
6961 return 0;
6962 }
6963 }
6964
6965 hash_bucket = &fname_table[hashf (fname, fname_length, FNAME_HASHSIZE)];
6966 for (hp = *hash_bucket; hp != NULL; hp = hp->next)
6967 if (hp->length == fname_length &&
6968 bcmp (hp->value.cpval, fname, fname_length) == 0) {
6969 ip->nominal_fname = hp->value.cpval;
6970 ip->nominal_fname_len = fname_length;
6971 break;
6972 }
6973 if (hp == 0) {
6974 /* Didn't find it; cons up a new one. */
6975 hp = (HASHNODE *) xcalloc (1, sizeof (HASHNODE) + fname_length + 1);
6976 hp->next = *hash_bucket;
6977 *hash_bucket = hp;
6978
6979 ip->nominal_fname = hp->value.cpval = ((char *) hp) + sizeof (HASHNODE);
6980 ip->nominal_fname_len = hp->length = fname_length;
6981 bcopy (fname, hp->value.cpval, fname_length + 1);
6982 }
6983 } else if (*bp) {
6984 error ("invalid format `#line' directive");
6985 return 0;
6986 }
6987
6988 ip->lineno = new_lineno;
6989 output_line_directive (ip, op, 0, file_change);
6990 check_expand (op, ip->length - (ip->bufp - ip->buf));
6991 return 0;
6992 }
6993
6994 /* Remove the definition of a symbol from the symbol table.
6995 according to un*x /lib/cpp, it is not an error to undef
6996 something that has no definitions, so it isn't one here either. */
6997
6998 static int
6999 do_undef (buf, limit, op, keyword)
7000 U_CHAR *buf, *limit;
7001 FILE_BUF *op;
7002 struct directive *keyword;
7003 {
7004 int sym_length;
7005 HASHNODE *hp;
7006 U_CHAR *orig_buf = buf;
7007
7008 /* If this is a precompiler run (with -pcp) pass thru #undef directives. */
7009 if (pcp_outfile && op)
7010 pass_thru_directive (buf, limit, op, keyword);
7011
7012 SKIP_WHITE_SPACE (buf);
7013 sym_length = check_macro_name (buf, 0);
7014
7015 while ((hp = lookup (buf, sym_length, -1)) != NULL) {
7016 /* If we are generating additional info for debugging (with -g) we
7017 need to pass through all effective #undef directives. */
7018 if (debug_output && op)
7019 pass_thru_directive (orig_buf, limit, op, keyword);
7020 if (hp->type == T_POISON)
7021 error ("cannot undefine poisoned `%s'", hp->name);
7022 else {
7023 if (hp->type != T_MACRO)
7024 warning ("undefining `%s'", hp->name);
7025 delete_macro (hp);
7026 }
7027 }
7028
7029 if (pedantic) {
7030 buf += sym_length;
7031 SKIP_WHITE_SPACE (buf);
7032 if (buf != limit)
7033 pedwarn ("garbage after `#undef' directive");
7034 }
7035 return 0;
7036 }
7037 \f
7038
7039 /* Report an error detected by the program we are processing.
7040 Use the text of the line in the error message. */
7041
7042 static int
7043 do_error (buf, limit, op, keyword)
7044 U_CHAR *buf, *limit;
7045 FILE_BUF *op ATTRIBUTE_UNUSED;
7046 struct directive *keyword;
7047 {
7048 int length = limit - buf;
7049 U_CHAR *copy = (U_CHAR *) alloca (length + 1);
7050 bcopy ((char *) buf, (char *) copy, length);
7051 copy[length] = 0;
7052 SKIP_WHITE_SPACE (copy);
7053
7054 switch (keyword->type) {
7055 case T_ERROR:
7056 error ("#error %s", copy);
7057 break;
7058
7059 case T_WARNING:
7060 if (pedantic && !instack[indepth].system_header_p)
7061 pedwarn ("ANSI C does not allow `#warning'");
7062 warning ("#warning %s", copy);
7063 break;
7064
7065 default:
7066 abort ();
7067 }
7068
7069 return 0;
7070 }
7071 /* Remember the name of the current file being read from so that we can
7072 avoid ever including it again. */
7073
7074 static void
7075 do_once ()
7076 {
7077 int i;
7078
7079 for (i = indepth; i >= 0; i--)
7080 if (instack[i].inc) {
7081 record_control_macro (instack[i].inc, (U_CHAR *) "");
7082 break;
7083 }
7084 }
7085
7086 /* Report program identification. */
7087
7088 static int
7089 do_ident (buf, limit, op, keyword)
7090 U_CHAR *buf, *limit;
7091 FILE_BUF *op;
7092 struct directive *keyword ATTRIBUTE_UNUSED;
7093 {
7094 FILE_BUF trybuf;
7095 int len;
7096
7097 /* Allow #ident in system headers, since that's not user's fault. */
7098 if (pedantic && !instack[indepth].system_header_p)
7099 pedwarn ("ANSI C does not allow `#ident'");
7100
7101 trybuf = expand_to_temp_buffer (buf, limit, 0, 0);
7102 buf = trybuf.buf;
7103 len = trybuf.bufp - buf;
7104
7105 /* Output expanded directive. */
7106 check_expand (op, 7 + len);
7107 bcopy ("#ident ", (char *) op->bufp, 7);
7108 op->bufp += 7;
7109 bcopy ((char *) buf, (char *) op->bufp, len);
7110 op->bufp += len;
7111
7112 free (buf);
7113 return 0;
7114 }
7115
7116 /* #pragma and its argument line have already been copied to the output file.
7117 Just check for some recognized pragmas that need validation here. */
7118
7119 static int
7120 do_pragma (buf, limit, op, keyword)
7121 U_CHAR *buf, *limit;
7122 FILE_BUF *op;
7123 struct directive *keyword;
7124 {
7125 SKIP_WHITE_SPACE (buf);
7126 if (!strncmp ((char *) buf, "once", 4)) {
7127 /* Allow #pragma once in system headers, since that's not the user's
7128 fault. */
7129 if (!instack[indepth].system_header_p)
7130 warning ("`#pragma once' is obsolete");
7131 do_once ();
7132 }
7133
7134 if (!strncmp (buf, "poison", 6)) {
7135 /* Poison these symbols so that all subsequent usage produces an
7136 error message. */
7137 U_CHAR *p = buf + 6;
7138
7139 SKIP_WHITE_SPACE (p);
7140 while (p < limit)
7141 {
7142 U_CHAR *end = p;
7143
7144 while (end < limit && is_idchar[*end])
7145 end++;
7146 if (end < limit && !is_space[*end])
7147 {
7148 error ("invalid #pragma poison");
7149 return 0;
7150 }
7151 do_define(p, end, op, keyword);
7152 p = end;
7153 SKIP_WHITE_SPACE (p);
7154 }
7155 }
7156
7157 if (!strncmp ((char *) buf, "implementation", 14)) {
7158 /* Be quiet about `#pragma implementation' for a file only if it hasn't
7159 been included yet. */
7160
7161 int h;
7162 U_CHAR *p = buf + 14, *fname;
7163 SKIP_WHITE_SPACE (p);
7164 if (*p != '\"')
7165 return 0;
7166
7167 fname = p + 1;
7168 p = skip_quoted_string (p, limit, 0, NULL_PTR, NULL_PTR, NULL_PTR);
7169 if (p[-1] == '"')
7170 *--p = '\0';
7171
7172 for (h = 0; h < INCLUDE_HASHSIZE; h++) {
7173 struct include_file *inc;
7174 for (inc = include_hashtab[h]; inc; inc = inc->next) {
7175 if (!strcmp (base_name (inc->fname), (char *) fname)) {
7176 warning ("`#pragma implementation' for \"%s\" appears after its #include",fname);
7177 return 0;
7178 }
7179 }
7180 }
7181 }
7182 return 0;
7183 }
7184
7185 #if 0
7186 /* This was a fun hack, but #pragma seems to start to be useful.
7187 By failing to recognize it, we pass it through unchanged to cc1. */
7188
7189 /* The behavior of the #pragma directive is implementation defined.
7190 this implementation defines it as follows. */
7191
7192 static int
7193 do_pragma ()
7194 {
7195 close (0);
7196 if (open ("/dev/tty", O_RDONLY, 0666) != 0)
7197 goto nope;
7198 close (1);
7199 if (open ("/dev/tty", O_WRONLY, 0666) != 1)
7200 goto nope;
7201 execl ("/usr/games/hack", "#pragma", 0);
7202 execl ("/usr/games/rogue", "#pragma", 0);
7203 execl ("/usr/new/emacs", "-f", "hanoi", "9", "-kill", 0);
7204 execl ("/usr/local/emacs", "-f", "hanoi", "9", "-kill", 0);
7205 nope:
7206 fatal ("You are in a maze of twisty compiler features, all different");
7207 }
7208 #endif
7209
7210 #ifdef SCCS_DIRECTIVE
7211
7212 /* Just ignore #sccs, on systems where we define it at all. */
7213
7214 static int
7215 do_sccs (buf, limit, op, keyword)
7216 U_CHAR *buf ATTRIBUTE_UNUSED, *limit ATTRIBUTE_UNUSED;
7217 FILE_BUF *op ATTRIBUTE_UNUSED;
7218 struct directive *keyword ATTRIBUTE_UNUSED;
7219 {
7220 if (pedantic)
7221 pedwarn ("ANSI C does not allow `#sccs'");
7222 return 0;
7223 }
7224
7225 #endif /* defined (SCCS_DIRECTIVE) */
7226 \f
7227 /* Handle #if directive by
7228 1) inserting special `defined' keyword into the hash table
7229 that gets turned into 0 or 1 by special_symbol (thus,
7230 if the luser has a symbol called `defined' already, it won't
7231 work inside the #if directive)
7232 2) rescan the input into a temporary output buffer
7233 3) pass the output buffer to the yacc parser and collect a value
7234 4) clean up the mess left from steps 1 and 2.
7235 5) call conditional_skip to skip til the next #endif (etc.),
7236 or not, depending on the value from step 3. */
7237
7238 static int
7239 do_if (buf, limit, op, keyword)
7240 U_CHAR *buf, *limit;
7241 FILE_BUF *op;
7242 struct directive *keyword ATTRIBUTE_UNUSED;
7243 {
7244 HOST_WIDEST_INT value;
7245 FILE_BUF *ip = &instack[indepth];
7246
7247 value = eval_if_expression (buf, limit - buf);
7248 conditional_skip (ip, value == 0, T_IF, NULL_PTR, op);
7249 return 0;
7250 }
7251
7252 /* Handle a #elif directive by not changing if_stack either.
7253 see the comment above do_else. */
7254
7255 static int
7256 do_elif (buf, limit, op, keyword)
7257 U_CHAR *buf, *limit;
7258 FILE_BUF *op;
7259 struct directive *keyword ATTRIBUTE_UNUSED;
7260 {
7261 HOST_WIDEST_INT value;
7262 FILE_BUF *ip = &instack[indepth];
7263
7264 if (if_stack == instack[indepth].if_stack) {
7265 error ("`#elif' not within a conditional");
7266 return 0;
7267 } else {
7268 if (if_stack->type != T_IF && if_stack->type != T_ELIF) {
7269 error ("`#elif' after `#else'");
7270 fprintf (stderr, " (matches line %d", if_stack->lineno);
7271 if (! (if_stack->fname_len == ip->nominal_fname_len
7272 && !bcmp (if_stack->fname, ip->nominal_fname,
7273 if_stack->fname_len))) {
7274 fprintf (stderr, ", file ");
7275 fwrite (if_stack->fname, sizeof if_stack->fname[0],
7276 if_stack->fname_len, stderr);
7277 }
7278 fprintf (stderr, ")\n");
7279 }
7280 if_stack->type = T_ELIF;
7281 }
7282
7283 if (if_stack->if_succeeded)
7284 skip_if_group (ip, 0, op);
7285 else {
7286 value = eval_if_expression (buf, limit - buf);
7287 if (value == 0)
7288 skip_if_group (ip, 0, op);
7289 else {
7290 ++if_stack->if_succeeded; /* continue processing input */
7291 output_line_directive (ip, op, 1, same_file);
7292 }
7293 }
7294 return 0;
7295 }
7296
7297 /* Evaluate a #if expression in BUF, of length LENGTH, then parse the
7298 result as a C expression and return the value as an int. */
7299
7300 static HOST_WIDEST_INT
7301 eval_if_expression (buf, length)
7302 U_CHAR *buf;
7303 int length;
7304 {
7305 FILE_BUF temp_obuf;
7306 HASHNODE *save_defined;
7307 HOST_WIDEST_INT value;
7308
7309 save_defined = install ((U_CHAR *) "defined", -1, T_SPEC_DEFINED,
7310 NULL_PTR, -1);
7311 pcp_inside_if = 1;
7312 temp_obuf = expand_to_temp_buffer (buf, buf + length, 0, 1);
7313 pcp_inside_if = 0;
7314 delete_macro (save_defined); /* clean up special symbol */
7315
7316 *temp_obuf.bufp = '\n';
7317 value = parse_c_expression ((char *) temp_obuf.buf,
7318 warn_undef && !instack[indepth].system_header_p);
7319
7320 free (temp_obuf.buf);
7321
7322 return value;
7323 }
7324
7325 /* routine to handle ifdef/ifndef. Try to look up the symbol, then do
7326 or don't skip to the #endif/#else/#elif depending on what directive
7327 is actually being processed. */
7328
7329 static int
7330 do_xifdef (buf, limit, op, keyword)
7331 U_CHAR *buf, *limit;
7332 FILE_BUF *op;
7333 struct directive *keyword;
7334 {
7335 int skip;
7336 FILE_BUF *ip = &instack[indepth];
7337 U_CHAR *end;
7338 int start_of_file = 0;
7339 U_CHAR *control_macro = 0;
7340
7341 /* Detect a #ifndef at start of file (not counting comments). */
7342 if (ip->fname != 0 && keyword->type == T_IFNDEF) {
7343 U_CHAR *p = ip->buf;
7344 while (p != directive_start) {
7345 U_CHAR c = *p++;
7346 if (is_space[c])
7347 ;
7348 /* Make no special provision for backslash-newline here; this is
7349 slower if backslash-newlines are present, but it's correct,
7350 and it's not worth it to tune for the rare backslash-newline. */
7351 else if (c == '/'
7352 && (*p == '*' || (cplusplus_comments && *p == '/'))) {
7353 /* Skip this comment. */
7354 int junk = 0;
7355 U_CHAR *save_bufp = ip->bufp;
7356 ip->bufp = p + 1;
7357 p = skip_to_end_of_comment (ip, &junk, 1);
7358 ip->bufp = save_bufp;
7359 } else {
7360 goto fail;
7361 }
7362 }
7363 /* If we get here, this conditional is the beginning of the file. */
7364 start_of_file = 1;
7365 fail: ;
7366 }
7367
7368 /* Discard leading and trailing whitespace. */
7369 SKIP_WHITE_SPACE (buf);
7370 while (limit != buf && is_hor_space[limit[-1]]) limit--;
7371
7372 /* Find the end of the identifier at the beginning. */
7373 for (end = buf; is_idchar[*end]; end++);
7374
7375 if (end == buf) {
7376 skip = (keyword->type == T_IFDEF);
7377 if (! traditional)
7378 pedwarn (end == limit ? "`#%s' with no argument"
7379 : "`#%s' argument starts with punctuation",
7380 keyword->name);
7381 } else {
7382 HASHNODE *hp;
7383
7384 if (! traditional) {
7385 if (ISDIGIT (buf[0]))
7386 pedwarn ("`#%s' argument starts with a digit", keyword->name);
7387 else if (end != limit)
7388 pedwarn ("garbage at end of `#%s' argument", keyword->name);
7389 }
7390
7391 hp = lookup (buf, end-buf, -1);
7392
7393 if (pcp_outfile) {
7394 /* Output a precondition for this macro. */
7395 if (hp
7396 && (hp->type == T_CONST
7397 || (hp->type == T_MACRO && hp->value.defn->predefined)))
7398 fprintf (pcp_outfile, "#define %s\n", hp->name);
7399 else {
7400 U_CHAR *cp = buf;
7401 fprintf (pcp_outfile, "#undef ");
7402 while (is_idchar[*cp]) /* Ick! */
7403 fputc (*cp++, pcp_outfile);
7404 putc ('\n', pcp_outfile);
7405 }
7406 }
7407
7408 if ((hp != NULL) && (hp->type == T_POISON)) {
7409 error("attempt to use poisoned `%s'.", hp->name);
7410 hp = NULL;
7411 }
7412 skip = (hp == NULL) ^ (keyword->type == T_IFNDEF);
7413 if (start_of_file && !skip) {
7414 control_macro = (U_CHAR *) xmalloc (end - buf + 1);
7415 bcopy ((char *) buf, (char *) control_macro, end - buf);
7416 control_macro[end - buf] = 0;
7417 }
7418 }
7419
7420 conditional_skip (ip, skip, T_IF, control_macro, op);
7421 return 0;
7422 }
7423
7424 /* Push TYPE on stack; then, if SKIP is nonzero, skip ahead.
7425 If this is a #ifndef starting at the beginning of a file,
7426 CONTROL_MACRO is the macro name tested by the #ifndef.
7427 Otherwise, CONTROL_MACRO is 0. */
7428
7429 static void
7430 conditional_skip (ip, skip, type, control_macro, op)
7431 FILE_BUF *ip;
7432 int skip;
7433 enum node_type type;
7434 U_CHAR *control_macro;
7435 FILE_BUF *op;
7436 {
7437 IF_STACK_FRAME *temp;
7438
7439 temp = (IF_STACK_FRAME *) xcalloc (1, sizeof (IF_STACK_FRAME));
7440 temp->fname = ip->nominal_fname;
7441 temp->fname_len = ip->nominal_fname_len;
7442 temp->lineno = ip->lineno;
7443 temp->next = if_stack;
7444 temp->control_macro = control_macro;
7445 if_stack = temp;
7446
7447 if_stack->type = type;
7448
7449 if (skip != 0) {
7450 skip_if_group (ip, 0, op);
7451 return;
7452 } else {
7453 ++if_stack->if_succeeded;
7454 output_line_directive (ip, &outbuf, 1, same_file);
7455 }
7456 }
7457
7458 /* Skip to #endif, #else, or #elif. adjust line numbers, etc.
7459 Leaves input ptr at the sharp sign found.
7460 If ANY is nonzero, return at next directive of any sort. */
7461
7462 static void
7463 skip_if_group (ip, any, op)
7464 FILE_BUF *ip;
7465 int any;
7466 FILE_BUF *op;
7467 {
7468 register U_CHAR *bp = ip->bufp, *cp;
7469 register U_CHAR *endb = ip->buf + ip->length;
7470 struct directive *kt;
7471 IF_STACK_FRAME *save_if_stack = if_stack; /* don't pop past here */
7472 U_CHAR *beg_of_line = bp;
7473 register int ident_length;
7474 U_CHAR *ident, *after_ident;
7475 /* Save info about where the group starts. */
7476 U_CHAR *beg_of_group = bp;
7477 int beg_lineno = ip->lineno;
7478 int skipping_include_directive = 0;
7479
7480 if (output_conditionals && op != 0) {
7481 char *ptr = "#failed\n";
7482 int len = strlen (ptr);
7483
7484 if (op->bufp > op->buf && op->bufp[-1] != '\n')
7485 {
7486 *op->bufp++ = '\n';
7487 op->lineno++;
7488 }
7489 check_expand (op, len);
7490 bcopy (ptr, (char *) op->bufp, len);
7491 op->bufp += len;
7492 op->lineno++;
7493 output_line_directive (ip, op, 1, 0);
7494 }
7495
7496 while (bp < endb) {
7497 switch (*bp++) {
7498 case '/': /* possible comment */
7499 if (*bp == '\\')
7500 newline_fix (bp);
7501 if (*bp == '*'
7502 || (cplusplus_comments && *bp == '/')) {
7503 ip->bufp = ++bp;
7504 bp = skip_to_end_of_comment (ip, &ip->lineno, 0);
7505 }
7506 break;
7507 case '<':
7508 if (skipping_include_directive) {
7509 while (bp < endb && *bp != '>' && *bp != '\n') {
7510 if (*bp == '\\' && bp[1] == '\n') {
7511 ip->lineno++;
7512 bp++;
7513 }
7514 bp++;
7515 }
7516 }
7517 break;
7518 case '\"':
7519 if (skipping_include_directive) {
7520 while (bp < endb && *bp != '\n') {
7521 if (*bp == '"') {
7522 bp++;
7523 break;
7524 }
7525 if (*bp == '\\' && bp[1] == '\n') {
7526 ip->lineno++;
7527 bp++;
7528 }
7529 bp++;
7530 }
7531 break;
7532 }
7533 /* Fall through. */
7534 case '\'':
7535 bp = skip_quoted_string (bp - 1, endb, ip->lineno, &ip->lineno,
7536 NULL_PTR, NULL_PTR);
7537 break;
7538 case '\\':
7539 /* Char after backslash loses its special meaning in some cases. */
7540 if (*bp == '\n') {
7541 ++ip->lineno;
7542 bp++;
7543 } else if (traditional && bp < endb)
7544 bp++;
7545 break;
7546 case '\n':
7547 ++ip->lineno;
7548 beg_of_line = bp;
7549 skipping_include_directive = 0;
7550 break;
7551 case '%':
7552 if (beg_of_line == 0 || traditional)
7553 break;
7554 ip->bufp = bp - 1;
7555 while (bp[0] == '\\' && bp[1] == '\n')
7556 bp += 2;
7557 if (*bp == ':')
7558 goto sharp_token;
7559 break;
7560 case '#':
7561 /* # keyword: a # must be first nonblank char on the line */
7562 if (beg_of_line == 0)
7563 break;
7564 ip->bufp = bp - 1;
7565 sharp_token:
7566 /* Scan from start of line, skipping whitespace, comments
7567 and backslash-newlines, and see if we reach this #.
7568 If not, this # is not special. */
7569 bp = beg_of_line;
7570 /* If -traditional, require # to be at beginning of line. */
7571 if (!traditional) {
7572 while (1) {
7573 if (is_hor_space[*bp])
7574 bp++;
7575 else if (*bp == '\\' && bp[1] == '\n')
7576 bp += 2;
7577 else if (*bp == '/' && bp[1] == '*') {
7578 bp += 2;
7579 while (1)
7580 {
7581 if (*bp == '*')
7582 {
7583 if (bp[1] == '/')
7584 {
7585 bp += 2;
7586 break;
7587 }
7588 }
7589 else
7590 {
7591 #ifdef MULTIBYTE_CHARS
7592 int length;
7593 length = local_mblen (bp, endb - bp);
7594 if (length > 1)
7595 bp += (length - 1);
7596 #endif
7597 }
7598 bp++;
7599 }
7600 }
7601 /* There is no point in trying to deal with C++ // comments here,
7602 because if there is one, then this # must be part of the
7603 comment and we would never reach here. */
7604 else break;
7605 }
7606 }
7607 if (bp != ip->bufp) {
7608 bp = ip->bufp + 1; /* Reset bp to after the #. */
7609 break;
7610 }
7611
7612 bp = ip->bufp + 1; /* Point after the '#' */
7613 if (ip->bufp[0] == '%') {
7614 /* Skip past the ':' again. */
7615 while (*bp == '\\') {
7616 ip->lineno++;
7617 bp += 2;
7618 }
7619 bp++;
7620 }
7621
7622 /* Skip whitespace and \-newline. */
7623 while (1) {
7624 if (is_hor_space[*bp])
7625 bp++;
7626 else if (*bp == '\\' && bp[1] == '\n')
7627 bp += 2;
7628 else if (*bp == '/') {
7629 if (bp[1] == '\\')
7630 newline_fix (bp + 1);
7631 if (bp[1] == '*') {
7632 for (bp += 2; ; bp++) {
7633 if (*bp == '\n')
7634 ip->lineno++;
7635 else if (*bp == '*') {
7636 if (bp[-1] == '/' && warn_comments)
7637 warning ("`/*' within comment");
7638 if (bp[1] == '\\')
7639 newline_fix (bp + 1);
7640 if (bp[1] == '/')
7641 break;
7642 }
7643 else
7644 {
7645 #ifdef MULTIBYTE_CHARS
7646 int length;
7647 length = local_mblen (bp, endb - bp);
7648 if (length > 1)
7649 bp += (length - 1);
7650 #endif
7651 }
7652 }
7653 bp += 2;
7654 } else if (bp[1] == '/' && cplusplus_comments) {
7655 for (bp += 2; ; bp++) {
7656 if (*bp == '\n')
7657 break;
7658 if (*bp == '\\' && bp[1] == '\n')
7659 {
7660 if (warn_comments)
7661 warning ("multiline `//' comment");
7662 ip->lineno++;
7663 bp++;
7664 }
7665 else
7666 {
7667 #ifdef MULTIBYTE_CHARS
7668 int length;
7669 length = local_mblen (bp, endb - bp);
7670 if (length > 1)
7671 bp += (length - 1);
7672 #endif
7673 }
7674 }
7675 } else
7676 break;
7677 } else
7678 break;
7679 }
7680
7681 cp = bp;
7682
7683 /* Now find end of directive name.
7684 If we encounter a backslash-newline, exchange it with any following
7685 symbol-constituents so that we end up with a contiguous name. */
7686
7687 while (1) {
7688 if (is_idchar[*bp])
7689 bp++;
7690 else {
7691 if (*bp == '\\')
7692 name_newline_fix (bp);
7693 if (is_idchar[*bp])
7694 bp++;
7695 else break;
7696 }
7697 }
7698 ident_length = bp - cp;
7699 ident = cp;
7700 after_ident = bp;
7701
7702 /* A line of just `#' becomes blank. */
7703
7704 if (ident_length == 0 && *after_ident == '\n') {
7705 continue;
7706 }
7707
7708 if (ident_length == 0 || !is_idstart[*ident]) {
7709 U_CHAR *p = ident;
7710 while (is_idchar[*p]) {
7711 if (*p < '0' || *p > '9')
7712 break;
7713 p++;
7714 }
7715 /* Handle # followed by a line number. */
7716 if (p != ident && !is_idchar[*p]) {
7717 if (pedantic)
7718 pedwarn ("`#' followed by integer");
7719 continue;
7720 }
7721
7722 /* Avoid error for `###' and similar cases unless -pedantic. */
7723 if (p == ident) {
7724 while (*p == '#' || is_hor_space[*p]) p++;
7725 if (*p == '\n') {
7726 if (pedantic && !lang_asm)
7727 pedwarn ("invalid preprocessing directive");
7728 continue;
7729 }
7730 }
7731
7732 if (!lang_asm && pedantic)
7733 pedwarn ("invalid preprocessing directive name");
7734 continue;
7735 }
7736
7737 for (kt = directive_table; kt->length >= 0; kt++) {
7738 IF_STACK_FRAME *temp;
7739 if (ident_length == kt->length
7740 && bcmp (cp, kt->name, kt->length) == 0) {
7741 /* If we are asked to return on next directive, do so now. */
7742 if (any)
7743 goto done;
7744
7745 switch (kt->type) {
7746 case T_IF:
7747 case T_IFDEF:
7748 case T_IFNDEF:
7749 temp = (IF_STACK_FRAME *) xcalloc (1, sizeof (IF_STACK_FRAME));
7750 temp->next = if_stack;
7751 if_stack = temp;
7752 temp->lineno = ip->lineno;
7753 temp->fname = ip->nominal_fname;
7754 temp->fname_len = ip->nominal_fname_len;
7755 temp->type = kt->type;
7756 break;
7757 case T_ELSE:
7758 case T_ENDIF:
7759 if (pedantic && if_stack != save_if_stack)
7760 validate_else (bp, endb);
7761 case T_ELIF:
7762 if (if_stack == instack[indepth].if_stack) {
7763 error ("`#%s' not within a conditional", kt->name);
7764 break;
7765 }
7766 else if (if_stack == save_if_stack)
7767 goto done; /* found what we came for */
7768
7769 if (kt->type != T_ENDIF) {
7770 if (if_stack->type == T_ELSE)
7771 error ("`#else' or `#elif' after `#else'");
7772 if_stack->type = kt->type;
7773 break;
7774 }
7775
7776 temp = if_stack;
7777 if_stack = if_stack->next;
7778 free (temp);
7779 break;
7780
7781 case T_INCLUDE:
7782 case T_INCLUDE_NEXT:
7783 case T_IMPORT:
7784 skipping_include_directive = 1;
7785 break;
7786
7787 default:
7788 break;
7789 }
7790 break;
7791 }
7792 }
7793 /* Don't let erroneous code go by. */
7794 if (kt->length < 0 && !lang_asm && pedantic)
7795 pedwarn ("invalid preprocessing directive name");
7796 }
7797 }
7798
7799 ip->bufp = bp;
7800 /* after this returns, rescan will exit because ip->bufp
7801 now points to the end of the buffer.
7802 rescan is responsible for the error message also. */
7803
7804 done:
7805 if (output_conditionals && op != 0) {
7806 char *ptr = "#endfailed\n";
7807 int len = strlen (ptr);
7808
7809 if (op->bufp > op->buf && op->bufp[-1] != '\n')
7810 {
7811 *op->bufp++ = '\n';
7812 op->lineno++;
7813 }
7814 check_expand (op, beg_of_line - beg_of_group);
7815 bcopy ((char *) beg_of_group, (char *) op->bufp,
7816 beg_of_line - beg_of_group);
7817 op->bufp += beg_of_line - beg_of_group;
7818 op->lineno += ip->lineno - beg_lineno;
7819 check_expand (op, len);
7820 bcopy (ptr, (char *) op->bufp, len);
7821 op->bufp += len;
7822 op->lineno++;
7823 }
7824 }
7825
7826 /* Handle a #else directive. Do this by just continuing processing
7827 without changing if_stack ; this is so that the error message
7828 for missing #endif's etc. will point to the original #if. It
7829 is possible that something different would be better. */
7830
7831 static int
7832 do_else (buf, limit, op, keyword)
7833 U_CHAR *buf, *limit;
7834 FILE_BUF *op;
7835 struct directive *keyword ATTRIBUTE_UNUSED;
7836 {
7837 FILE_BUF *ip = &instack[indepth];
7838
7839 if (pedantic) {
7840 SKIP_WHITE_SPACE (buf);
7841 if (buf != limit)
7842 pedwarn ("text following `#else' violates ANSI standard");
7843 }
7844
7845 if (if_stack == instack[indepth].if_stack) {
7846 error ("`#else' not within a conditional");
7847 return 0;
7848 } else {
7849 /* #ifndef can't have its special treatment for containing the whole file
7850 if it has a #else clause. */
7851 if_stack->control_macro = 0;
7852
7853 if (if_stack->type != T_IF && if_stack->type != T_ELIF) {
7854 error ("`#else' after `#else'");
7855 fprintf (stderr, " (matches line %d", if_stack->lineno);
7856 if (! (if_stack->fname_len == ip->nominal_fname_len
7857 && !bcmp (if_stack->fname, ip->nominal_fname,
7858 if_stack->fname_len))) {
7859 fprintf (stderr, ", file ");
7860 fwrite (if_stack->fname, sizeof if_stack->fname[0],
7861 if_stack->fname_len, stderr);
7862 }
7863 fprintf (stderr, ")\n");
7864 }
7865 if_stack->type = T_ELSE;
7866 }
7867
7868 if (if_stack->if_succeeded)
7869 skip_if_group (ip, 0, op);
7870 else {
7871 ++if_stack->if_succeeded; /* continue processing input */
7872 output_line_directive (ip, op, 1, same_file);
7873 }
7874 return 0;
7875 }
7876
7877 /* Unstack after #endif directive. */
7878
7879 static int
7880 do_endif (buf, limit, op, keyword)
7881 U_CHAR *buf, *limit;
7882 FILE_BUF *op;
7883 struct directive *keyword ATTRIBUTE_UNUSED;
7884 {
7885 if (pedantic) {
7886 SKIP_WHITE_SPACE (buf);
7887 if (buf != limit)
7888 pedwarn ("text following `#endif' violates ANSI standard");
7889 }
7890
7891 if (if_stack == instack[indepth].if_stack)
7892 error ("unbalanced `#endif'");
7893 else {
7894 IF_STACK_FRAME *temp = if_stack;
7895 if_stack = if_stack->next;
7896 if (temp->control_macro != 0) {
7897 /* This #endif matched a #ifndef at the start of the file.
7898 See if it is at the end of the file. */
7899 FILE_BUF *ip = &instack[indepth];
7900 U_CHAR *p = ip->bufp;
7901 U_CHAR *ep = ip->buf + ip->length;
7902
7903 while (p != ep) {
7904 U_CHAR c = *p++;
7905 if (!is_space[c]) {
7906 if (c == '/'
7907 && (*p == '*' || (cplusplus_comments && *p == '/'))) {
7908 /* Skip this comment. */
7909 int junk = 0;
7910 U_CHAR *save_bufp = ip->bufp;
7911 ip->bufp = p + 1;
7912 p = skip_to_end_of_comment (ip, &junk, 1);
7913 ip->bufp = save_bufp;
7914 } else
7915 goto fail;
7916 }
7917 }
7918 /* If we get here, this #endif ends a #ifndef
7919 that contains all of the file (aside from whitespace).
7920 Arrange not to include the file again
7921 if the macro that was tested is defined.
7922
7923 Do not do this for the top-level file in a -include or any
7924 file in a -imacros. */
7925 if (indepth != 0
7926 && ! (indepth == 1 && no_record_file)
7927 && ! (no_record_file && no_output))
7928 record_control_macro (ip->inc, temp->control_macro);
7929 fail: ;
7930 }
7931 free (temp);
7932 output_line_directive (&instack[indepth], op, 1, same_file);
7933 }
7934 return 0;
7935 }
7936
7937 /* When an #else or #endif is found while skipping failed conditional,
7938 if -pedantic was specified, this is called to warn about text after
7939 the directive name. P points to the first char after the directive
7940 name. */
7941
7942 static void
7943 validate_else (p, limit)
7944 register U_CHAR *p;
7945 register U_CHAR *limit;
7946 {
7947 /* Advance P over whitespace and comments. */
7948 while (1) {
7949 while (*p == '\\' && p[1] == '\n')
7950 p += 2;
7951 if (is_hor_space[*p])
7952 p++;
7953 else if (*p == '/') {
7954 while (p[1] == '\\' && p[2] == '\n')
7955 p += 2;
7956 if (p[1] == '*') {
7957 /* Don't bother warning about unterminated comments
7958 since that will happen later. Just be sure to exit. */
7959 for (p += 2; ; p++) {
7960 if (p == limit)
7961 return;
7962 if (*p == '*') {
7963 while (p[1] == '\\' && p[2] == '\n')
7964 p += 2;
7965 if (p[1] == '/') {
7966 p += 2;
7967 break;
7968 }
7969 }
7970 else
7971 {
7972 #ifdef MULTIBYTE_CHARS
7973 int length;
7974 length = local_mblen (p, limit - p);
7975 if (length > 1)
7976 p += (length - 1);
7977 #endif
7978 }
7979 }
7980 }
7981 else if (cplusplus_comments && p[1] == '/')
7982 return;
7983 else break;
7984 } else break;
7985 }
7986 if (*p != '\n')
7987 pedwarn ("text following `#else' or `#endif' violates ANSI standard");
7988 }
7989 \f
7990 /* Skip a comment, assuming the input ptr immediately follows the
7991 initial slash-star. Bump *LINE_COUNTER for each newline.
7992 (The canonical line counter is &ip->lineno.)
7993 Don't use this routine (or the next one) if bumping the line
7994 counter is not sufficient to deal with newlines in the string.
7995
7996 If NOWARN is nonzero, don't warn about slash-star inside a comment.
7997 This feature is useful when processing a comment that is going to
7998 be processed or was processed at another point in the preprocessor,
7999 to avoid a duplicate warning. Likewise for unterminated comment
8000 errors. */
8001
8002 static U_CHAR *
8003 skip_to_end_of_comment (ip, line_counter, nowarn)
8004 register FILE_BUF *ip;
8005 int *line_counter; /* place to remember newlines, or NULL */
8006 int nowarn;
8007 {
8008 register U_CHAR *limit = ip->buf + ip->length;
8009 register U_CHAR *bp = ip->bufp;
8010 FILE_BUF *op = put_out_comments && !line_counter ? &outbuf : (FILE_BUF *) 0;
8011 int start_line = line_counter ? *line_counter : 0;
8012
8013 /* JF this line_counter stuff is a crock to make sure the
8014 comment is only put out once, no matter how many times
8015 the comment is skipped. It almost works */
8016 if (op) {
8017 *op->bufp++ = '/';
8018 *op->bufp++ = bp[-1];
8019 }
8020 if (cplusplus_comments && bp[-1] == '/') {
8021 for (; bp < limit; bp++) {
8022 if (*bp == '\n')
8023 break;
8024 if (*bp == '\\' && bp + 1 < limit && bp[1] == '\n')
8025 {
8026 if (!nowarn && warn_comments)
8027 warning ("multiline `//' comment");
8028 if (line_counter)
8029 ++*line_counter;
8030 if (op)
8031 {
8032 ++op->lineno;
8033 *op->bufp++ = *bp;
8034 }
8035 ++bp;
8036 }
8037 else
8038 {
8039 #ifdef MULTIBYTE_CHARS
8040 int length;
8041 length = local_mblen (bp, limit - bp);
8042 if (length > 1)
8043 {
8044 if (op)
8045 {
8046 bcopy (bp, op->bufp, length - 1);
8047 op->bufp += (length - 1);
8048 }
8049 bp += (length - 1);
8050 }
8051 #endif
8052 }
8053 if (op)
8054 *op->bufp++ = *bp;
8055 }
8056 ip->bufp = bp;
8057 return bp;
8058 }
8059 while (bp < limit) {
8060 if (op)
8061 *op->bufp++ = *bp;
8062 switch (*bp++) {
8063 case '\n':
8064 /* If this is the end of the file, we have an unterminated comment.
8065 Don't swallow the newline. We are guaranteed that there will be a
8066 trailing newline and various pieces assume it's there. */
8067 if (bp == limit)
8068 {
8069 --bp;
8070 --limit;
8071 break;
8072 }
8073 if (line_counter != NULL)
8074 ++*line_counter;
8075 if (op)
8076 ++op->lineno;
8077 break;
8078 case '*':
8079 if (bp[-2] == '/' && !nowarn && warn_comments)
8080 warning ("`/*' within comment");
8081 if (*bp == '\\')
8082 newline_fix (bp);
8083 if (*bp == '/') {
8084 if (op)
8085 *op->bufp++ = '/';
8086 ip->bufp = ++bp;
8087 return bp;
8088 }
8089 break;
8090 #ifdef MULTIBYTE_CHARS
8091 default:
8092 {
8093 int length;
8094 bp--;
8095 length = local_mblen (bp, limit - bp);
8096 if (length <= 0)
8097 length = 1;
8098 if (op)
8099 {
8100 op->bufp--;
8101 bcopy (bp, op->bufp, length);
8102 op->bufp += length;
8103 }
8104 bp += length;
8105 }
8106 #endif
8107 }
8108 }
8109
8110 if (!nowarn)
8111 error_with_line (line_for_error (start_line), "unterminated comment");
8112 ip->bufp = bp;
8113 return bp;
8114 }
8115
8116 /* Skip over a quoted string. BP points to the opening quote.
8117 Returns a pointer after the closing quote. Don't go past LIMIT.
8118 START_LINE is the line number of the starting point (but it need
8119 not be valid if the starting point is inside a macro expansion).
8120
8121 The input stack state is not changed.
8122
8123 If COUNT_NEWLINES is nonzero, it points to an int to increment
8124 for each newline passed; also, warn about any white space
8125 just before line end.
8126
8127 If BACKSLASH_NEWLINES_P is nonzero, store 1 thru it
8128 if we pass a backslash-newline.
8129
8130 If EOFP is nonzero, set *EOFP to 1 if the string is unterminated. */
8131
8132 static U_CHAR *
8133 skip_quoted_string (bp, limit, start_line, count_newlines, backslash_newlines_p, eofp)
8134 register U_CHAR *bp;
8135 register U_CHAR *limit;
8136 int start_line;
8137 int *count_newlines;
8138 int *backslash_newlines_p;
8139 int *eofp;
8140 {
8141 register U_CHAR c, match;
8142
8143 match = *bp++;
8144 while (1) {
8145 if (bp >= limit) {
8146 error_with_line (line_for_error (start_line),
8147 "unterminated string or character constant");
8148 error_with_line (multiline_string_line,
8149 "possible real start of unterminated constant");
8150 multiline_string_line = 0;
8151 if (eofp)
8152 *eofp = 1;
8153 break;
8154 }
8155 c = *bp++;
8156 if (c == '\\') {
8157 while (*bp == '\\' && bp[1] == '\n') {
8158 if (backslash_newlines_p)
8159 *backslash_newlines_p = 1;
8160 if (count_newlines)
8161 ++*count_newlines;
8162 bp += 2;
8163 }
8164 if (*bp == '\n') {
8165 if (backslash_newlines_p)
8166 *backslash_newlines_p = 1;
8167 if (count_newlines)
8168 ++*count_newlines;
8169 }
8170 bp++;
8171 } else if (c == '\n') {
8172 if (traditional) {
8173 /* Unterminated strings and character constants are 'valid'. */
8174 bp--; /* Don't consume the newline. */
8175 if (eofp)
8176 *eofp = 1;
8177 break;
8178 }
8179 if (match == '\'') {
8180 error_with_line (line_for_error (start_line),
8181 "unterminated character constant");
8182 bp--;
8183 if (eofp)
8184 *eofp = 1;
8185 break;
8186 }
8187 /* If not traditional, then allow newlines inside strings. */
8188 if (count_newlines) {
8189 if (warn_white_space && is_hor_space[bp[-2]])
8190 warning ("white space at end of line in string");
8191 ++*count_newlines;
8192 }
8193 if (multiline_string_line == 0) {
8194 if (pedantic)
8195 pedwarn_with_line (line_for_error (start_line),
8196 "string constant runs past end of line");
8197 multiline_string_line = start_line;
8198 }
8199 } else if (c == match)
8200 break;
8201 #ifdef MULTIBYTE_CHARS
8202 {
8203 int length;
8204 --bp;
8205 length = local_mblen (bp, limit - bp);
8206 if (length <= 0)
8207 length = 1;
8208 bp += length;
8209 }
8210 #endif
8211 }
8212 return bp;
8213 }
8214
8215 /* Place into DST a quoted string representing the string SRC.
8216 SRCLEN is the length of SRC; SRC may contain null bytes.
8217 Return the address of DST's terminating null. */
8218
8219 static char *
8220 quote_string (dst, src, srclen)
8221 char *dst, *src;
8222 size_t srclen;
8223 {
8224 U_CHAR c;
8225 char *srclim = src + srclen;
8226
8227 *dst++ = '\"';
8228 while (src != srclim)
8229 switch ((c = *src++))
8230 {
8231 default:
8232 if (ISPRINT (c))
8233 *dst++ = c;
8234 else
8235 {
8236 sprintf (dst, "\\%03o", c);
8237 dst += 4;
8238 }
8239 break;
8240
8241 case '\"':
8242 case '\\':
8243 *dst++ = '\\';
8244 *dst++ = c;
8245 break;
8246 }
8247
8248 *dst++ = '\"';
8249 *dst = '\0';
8250 return dst;
8251 }
8252
8253 /* Skip across a group of balanced parens, starting from IP->bufp.
8254 IP->bufp is updated. Use this with IP->bufp pointing at an open-paren.
8255
8256 This does not handle newlines, because it's used for the arg of #if,
8257 where there aren't any newlines. Also, backslash-newline can't appear. */
8258
8259 static U_CHAR *
8260 skip_paren_group (ip)
8261 register FILE_BUF *ip;
8262 {
8263 U_CHAR *limit = ip->buf + ip->length;
8264 U_CHAR *p = ip->bufp;
8265 int depth = 0;
8266 int lines_dummy = 0;
8267
8268 while (p != limit) {
8269 int c = *p++;
8270 switch (c) {
8271 case '(':
8272 depth++;
8273 break;
8274
8275 case ')':
8276 depth--;
8277 if (depth == 0)
8278 return ip->bufp = p;
8279 break;
8280
8281 case '/':
8282 if (*p == '*') {
8283 ip->bufp = p;
8284 p = skip_to_end_of_comment (ip, &lines_dummy, 0);
8285 p = ip->bufp;
8286 }
8287
8288 case '"':
8289 case '\'':
8290 {
8291 int eofp = 0;
8292 p = skip_quoted_string (p - 1, limit, 0, NULL_PTR, NULL_PTR, &eofp);
8293 if (eofp)
8294 return ip->bufp = p;
8295 }
8296 break;
8297 }
8298 }
8299
8300 ip->bufp = p;
8301 return p;
8302 }
8303 \f
8304 /* Write out a #line directive, for instance, after an #include file.
8305 If CONDITIONAL is nonzero, we can omit the #line if it would
8306 appear to be a no-op, and we can output a few newlines instead
8307 if we want to increase the line number by a small amount.
8308 FILE_CHANGE says whether we are entering a file, leaving, or neither. */
8309
8310 static void
8311 output_line_directive (ip, op, conditional, file_change)
8312 FILE_BUF *ip, *op;
8313 int conditional;
8314 enum file_change_code file_change;
8315 {
8316 int len;
8317 char *line_directive_buf, *line_end;
8318
8319 if (no_line_directives
8320 || ip->fname == NULL
8321 || no_output) {
8322 op->lineno = ip->lineno;
8323 return;
8324 }
8325
8326 if (conditional) {
8327 if (ip->lineno == op->lineno)
8328 return;
8329
8330 /* If the inherited line number is a little too small,
8331 output some newlines instead of a #line directive. */
8332 if (ip->lineno > op->lineno && ip->lineno < op->lineno + 8) {
8333 check_expand (op, 10);
8334 while (ip->lineno > op->lineno) {
8335 *op->bufp++ = '\n';
8336 op->lineno++;
8337 }
8338 return;
8339 }
8340 }
8341
8342 /* Output a positive line number if possible. */
8343 while (ip->lineno <= 0 && ip->bufp - ip->buf < ip->length
8344 && *ip->bufp == '\n') {
8345 ip->lineno++;
8346 ip->bufp++;
8347 }
8348
8349 line_directive_buf = (char *) alloca (4 * ip->nominal_fname_len + 100);
8350 sprintf (line_directive_buf, "# %d ", ip->lineno);
8351 line_end = quote_string (line_directive_buf + strlen (line_directive_buf),
8352 ip->nominal_fname, ip->nominal_fname_len);
8353 if (file_change != same_file) {
8354 *line_end++ = ' ';
8355 *line_end++ = file_change == enter_file ? '1' : '2';
8356 }
8357 /* Tell cc1 if following text comes from a system header file. */
8358 if (ip->system_header_p) {
8359 *line_end++ = ' ';
8360 *line_end++ = '3';
8361 }
8362 #ifndef NO_IMPLICIT_EXTERN_C
8363 /* Tell cc1plus if following text should be treated as C. */
8364 if (ip->system_header_p == 2 && cplusplus) {
8365 *line_end++ = ' ';
8366 *line_end++ = '4';
8367 }
8368 #endif
8369 *line_end++ = '\n';
8370 len = line_end - line_directive_buf;
8371 check_expand (op, len + 1);
8372 if (op->bufp > op->buf && op->bufp[-1] != '\n')
8373 *op->bufp++ = '\n';
8374 bcopy ((char *) line_directive_buf, (char *) op->bufp, len);
8375 op->bufp += len;
8376 op->lineno = ip->lineno;
8377 }
8378 \f
8379 /* This structure represents one parsed argument in a macro call.
8380 `raw' points to the argument text as written (`raw_length' is its length).
8381 `expanded' points to the argument's macro-expansion
8382 (its length is `expand_length', and its allocated size is `expand_size').
8383 `stringified_length_bound' is an upper bound on the length
8384 the argument would have if stringified.
8385 `use_count' is the number of times this macro arg is substituted
8386 into the macro. If the actual use count exceeds 10,
8387 the value stored is 10.
8388 `free1' and `free2', if nonzero, point to blocks to be freed
8389 when the macro argument data is no longer needed. */
8390
8391 struct argdata {
8392 U_CHAR *raw, *expanded;
8393 int raw_length, expand_length, expand_size;
8394 int stringified_length_bound;
8395 U_CHAR *free1, *free2;
8396 char newlines;
8397 char use_count;
8398 };
8399
8400 /* Expand a macro call.
8401 HP points to the symbol that is the macro being called.
8402 Put the result of expansion onto the input stack
8403 so that subsequent input by our caller will use it.
8404
8405 If macro wants arguments, caller has already verified that
8406 an argument list follows; arguments come from the input stack. */
8407
8408 static void
8409 macroexpand (hp, op)
8410 HASHNODE *hp;
8411 FILE_BUF *op;
8412 {
8413 int nargs;
8414 DEFINITION *defn = hp->value.defn;
8415 register U_CHAR *xbuf;
8416 int xbuf_len;
8417 int start_line = instack[indepth].lineno;
8418 int rest_args, rest_zero;
8419
8420 CHECK_DEPTH (return;);
8421
8422 /* it might not actually be a macro. */
8423 if (hp->type != T_MACRO) {
8424 special_symbol (hp, op);
8425 return;
8426 }
8427
8428 /* This macro is being used inside a #if, which means it must be */
8429 /* recorded as a precondition. */
8430 if (pcp_inside_if && pcp_outfile && defn->predefined)
8431 dump_single_macro (hp, pcp_outfile);
8432
8433 nargs = defn->nargs;
8434
8435 if (nargs >= 0) {
8436 register int i;
8437 struct argdata *args;
8438 int parse_error = 0;
8439
8440 args = (struct argdata *) alloca ((nargs + 1) * sizeof (struct argdata));
8441
8442 for (i = 0; i < nargs; i++) {
8443 args[i].raw = (U_CHAR *) "";
8444 args[i].expanded = 0;
8445 args[i].raw_length = args[i].expand_length = args[i].expand_size
8446 = args[i].stringified_length_bound = 0;
8447 args[i].free1 = args[i].free2 = 0;
8448 args[i].use_count = 0;
8449 }
8450
8451 /* Parse all the macro args that are supplied. I counts them.
8452 The first NARGS args are stored in ARGS.
8453 The rest are discarded.
8454 If rest_args is set then we assume macarg absorbed the rest of the args.
8455 */
8456 i = 0;
8457 rest_args = 0;
8458 do {
8459 /* Discard the open-parenthesis or comma before the next arg. */
8460 ++instack[indepth].bufp;
8461 if (rest_args)
8462 continue;
8463 if (i < nargs || (nargs == 0 && i == 0)) {
8464 /* If we are working on last arg which absorbs rest of args... */
8465 if (i == nargs - 1 && defn->rest_args)
8466 rest_args = 1;
8467 parse_error = macarg (&args[i], rest_args);
8468 }
8469 else
8470 parse_error = macarg (NULL_PTR, 0);
8471 if (parse_error) {
8472 error_with_line (line_for_error (start_line),
8473 "unterminated macro call");
8474 break;
8475 }
8476 i++;
8477 } while (*instack[indepth].bufp != ')');
8478
8479 /* If we got one arg but it was just whitespace, call that 0 args. */
8480 if (i == 1) {
8481 register U_CHAR *bp = args[0].raw;
8482 register U_CHAR *lim = bp + args[0].raw_length;
8483 /* cpp.texi says for foo ( ) we provide one argument.
8484 However, if foo wants just 0 arguments, treat this as 0. */
8485 if (nargs == 0)
8486 while (bp != lim && is_space[*bp]) bp++;
8487 if (bp == lim)
8488 i = 0;
8489 }
8490
8491 /* Don't output an error message if we have already output one for
8492 a parse error above. */
8493 rest_zero = 0;
8494 if (nargs == 0 && i > 0) {
8495 if (! parse_error)
8496 error ("arguments given to macro `%s'", hp->name);
8497 } else if (i < nargs) {
8498 /* traditional C allows foo() if foo wants one argument. */
8499 if (nargs == 1 && i == 0 && traditional)
8500 ;
8501 /* the rest args token is allowed to absorb 0 tokens */
8502 else if (i == nargs - 1 && defn->rest_args)
8503 rest_zero = 1;
8504 else if (parse_error)
8505 ;
8506 else if (i == 0)
8507 error ("macro `%s' used without args", hp->name);
8508 else if (i == 1)
8509 error ("macro `%s' used with just one arg", hp->name);
8510 else
8511 error ("macro `%s' used with only %d args", hp->name, i);
8512 } else if (i > nargs) {
8513 if (! parse_error)
8514 error ("macro `%s' used with too many (%d) args", hp->name, i);
8515 }
8516
8517 /* Swallow the closeparen. */
8518 ++instack[indepth].bufp;
8519
8520 /* If macro wants zero args, we parsed the arglist for checking only.
8521 Read directly from the macro definition. */
8522 if (nargs == 0) {
8523 xbuf = defn->expansion;
8524 xbuf_len = defn->length;
8525 } else {
8526 register U_CHAR *exp = defn->expansion;
8527 register int offset; /* offset in expansion,
8528 copied a piece at a time */
8529 register int totlen; /* total amount of exp buffer filled so far */
8530
8531 register struct reflist *ap, *last_ap;
8532
8533 /* Macro really takes args. Compute the expansion of this call. */
8534
8535 /* Compute length in characters of the macro's expansion.
8536 Also count number of times each arg is used. */
8537 xbuf_len = defn->length;
8538 for (ap = defn->pattern; ap != NULL; ap = ap->next) {
8539 if (ap->stringify)
8540 xbuf_len += args[ap->argno].stringified_length_bound;
8541 else if (ap->raw_before != 0 || ap->raw_after != 0 || traditional)
8542 /* Add 4 for two newline-space markers to prevent
8543 token concatenation. */
8544 xbuf_len += args[ap->argno].raw_length + 4;
8545 else {
8546 /* We have an ordinary (expanded) occurrence of the arg.
8547 So compute its expansion, if we have not already. */
8548 if (args[ap->argno].expanded == 0) {
8549 FILE_BUF obuf;
8550 obuf = expand_to_temp_buffer (args[ap->argno].raw,
8551 args[ap->argno].raw + args[ap->argno].raw_length,
8552 1, 0);
8553
8554 args[ap->argno].expanded = obuf.buf;
8555 args[ap->argno].expand_length = obuf.bufp - obuf.buf;
8556 args[ap->argno].expand_size = obuf.length;
8557 args[ap->argno].free2 = obuf.buf;
8558
8559 xbuf_len += args[ap->argno].expand_length;
8560 } else {
8561 /* If the arg appears more than once, its later occurrences
8562 may have newline turned into backslash-'n', which is a
8563 factor of 2 expansion. */
8564 xbuf_len += 2 * args[ap->argno].expand_length;
8565 }
8566 /* Add 4 for two newline-space markers to prevent
8567 token concatenation. */
8568 xbuf_len += 4;
8569 }
8570 if (args[ap->argno].use_count < 10)
8571 args[ap->argno].use_count++;
8572 }
8573
8574 xbuf = (U_CHAR *) xmalloc (xbuf_len + 1);
8575
8576 /* Generate in XBUF the complete expansion
8577 with arguments substituted in.
8578 TOTLEN is the total size generated so far.
8579 OFFSET is the index in the definition
8580 of where we are copying from. */
8581 offset = totlen = 0;
8582 for (last_ap = NULL, ap = defn->pattern; ap != NULL;
8583 last_ap = ap, ap = ap->next) {
8584 register struct argdata *arg = &args[ap->argno];
8585 int count_before = totlen;
8586
8587 /* Add chars to XBUF. */
8588 for (i = 0; i < ap->nchars; i++, offset++)
8589 xbuf[totlen++] = exp[offset];
8590
8591 /* If followed by an empty rest arg with concatenation,
8592 delete the last run of nonwhite chars. */
8593 if (rest_zero && totlen > count_before
8594 && ((ap->rest_args && ap->raw_before != 0)
8595 || (last_ap != NULL && last_ap->rest_args
8596 && last_ap->raw_after != 0))) {
8597 /* Delete final whitespace. */
8598 while (totlen > count_before && is_space[xbuf[totlen - 1]]) {
8599 totlen--;
8600 }
8601
8602 /* Delete the nonwhites before them. */
8603 while (totlen > count_before && ! is_space[xbuf[totlen - 1]]) {
8604 totlen--;
8605 }
8606 }
8607
8608 if (ap->stringify != 0) {
8609 int arglen = arg->raw_length;
8610 int escaped = 0;
8611 int in_string = 0;
8612 int c;
8613 i = 0;
8614 while (i < arglen
8615 && (c = arg->raw[i], is_space[c]))
8616 i++;
8617 while (i < arglen
8618 && (c = arg->raw[arglen - 1], is_space[c]))
8619 arglen--;
8620 if (!traditional)
8621 xbuf[totlen++] = '\"'; /* insert beginning quote */
8622 for (; i < arglen; i++) {
8623 c = arg->raw[i];
8624
8625 if (in_string) {
8626 /* Generate nothing for backslash-newline in a string. */
8627 if (c == '\\' && arg->raw[i + 1] == '\n') {
8628 i++;
8629 continue;
8630 }
8631 } else {
8632 /* Special markers
8633 generate nothing for a stringified argument. */
8634 if (c == '\n') {
8635 i++;
8636 continue;
8637 }
8638
8639 /* Internal sequences of whitespace are replaced by one space
8640 except within a string or char token. */
8641 if (is_space[c]) {
8642 i++;
8643 while (is_space[(c = arg->raw[i])])
8644 /* Newline markers can occur within a whitespace sequence;
8645 consider them part of the sequence. */
8646 i += (c == '\n') + 1;
8647 i--;
8648 c = ' ';
8649 }
8650 }
8651
8652 if (escaped)
8653 escaped = 0;
8654 else {
8655 if (c == '\\')
8656 escaped = 1;
8657 else if (in_string) {
8658 if (c == in_string)
8659 in_string = 0;
8660 else
8661 {
8662 #ifdef MULTIBYTE_CHARS
8663 int length;
8664 length = local_mblen (arg->raw + i, arglen - i);
8665 if (length > 1)
8666 {
8667 bcopy (arg->raw + i, xbuf + totlen, length);
8668 i += length - 1;
8669 totlen += length;
8670 continue;
8671 }
8672 #endif
8673 }
8674 } else if (c == '\"' || c == '\'')
8675 in_string = c;
8676 }
8677
8678 /* Escape double-quote, and backslashes in strings.
8679 Newlines in strings are best escaped as \n, since
8680 otherwise backslash-backslash-newline-newline is
8681 mishandled. The C Standard doesn't allow newlines in
8682 strings, so we can escape newlines as we please. */
8683 if (c == '\"'
8684 || (in_string
8685 && (c == '\\'
8686 || (c == '\n' ? (c = 'n', 1) : 0))))
8687 xbuf[totlen++] = '\\';
8688 /* We used to output e.g. \008 for control characters here,
8689 but this doesn't conform to the C Standard.
8690 Just output the characters as-is. */
8691 xbuf[totlen++] = c;
8692 }
8693 if (!traditional)
8694 xbuf[totlen++] = '\"'; /* insert ending quote */
8695 } else if (ap->raw_before != 0 || ap->raw_after != 0 || traditional) {
8696 U_CHAR *p1 = arg->raw;
8697 U_CHAR *l1 = p1 + arg->raw_length;
8698 if (ap->raw_before != 0) {
8699 while (p1 != l1 && is_space[*p1]) p1++;
8700 while (p1 != l1 && is_idchar[*p1])
8701 xbuf[totlen++] = *p1++;
8702 /* Delete any no-reexpansion marker that follows
8703 an identifier at the beginning of the argument
8704 if the argument is concatenated with what precedes it. */
8705 if (p1[0] == '\n' && p1[1] == '-')
8706 p1 += 2;
8707 } else if (!traditional) {
8708 /* Ordinary expanded use of the argument.
8709 Put in newline-space markers to prevent token pasting. */
8710 xbuf[totlen++] = '\n';
8711 xbuf[totlen++] = ' ';
8712 }
8713 if (ap->raw_after != 0) {
8714 /* Arg is concatenated after: delete trailing whitespace,
8715 whitespace markers, and no-reexpansion markers. */
8716 while (p1 != l1) {
8717 if (is_space[l1[-1]]) l1--;
8718 else if (l1[-1] == '-') {
8719 U_CHAR *p2 = l1 - 1;
8720 /* If a `-' is preceded by an odd number of newlines then it
8721 and the last newline are a no-reexpansion marker. */
8722 while (p2 != p1 && p2[-1] == '\n') p2--;
8723 if ((l1 - 1 - p2) & 1) {
8724 l1 -= 2;
8725 }
8726 else break;
8727 }
8728 else break;
8729 }
8730 }
8731
8732 bcopy ((char *) p1, (char *) (xbuf + totlen), l1 - p1);
8733 totlen += l1 - p1;
8734 if (!traditional && ap->raw_after == 0) {
8735 /* Ordinary expanded use of the argument.
8736 Put in newline-space markers to prevent token pasting. */
8737 xbuf[totlen++] = '\n';
8738 xbuf[totlen++] = ' ';
8739 }
8740 } else {
8741 /* Ordinary expanded use of the argument.
8742 Put in newline-space markers to prevent token pasting. */
8743 if (!traditional) {
8744 xbuf[totlen++] = '\n';
8745 xbuf[totlen++] = ' ';
8746 }
8747 bcopy ((char *) arg->expanded, (char *) (xbuf + totlen),
8748 arg->expand_length);
8749 totlen += arg->expand_length;
8750 if (!traditional) {
8751 xbuf[totlen++] = '\n';
8752 xbuf[totlen++] = ' ';
8753 }
8754 /* If a macro argument with newlines is used multiple times,
8755 then only expand the newlines once. This avoids creating output
8756 lines which don't correspond to any input line, which confuses
8757 gdb and gcov. */
8758 if (arg->use_count > 1 && arg->newlines > 0) {
8759 /* Don't bother doing change_newlines for subsequent
8760 uses of arg. */
8761 arg->use_count = 1;
8762 change_newlines (arg);
8763 }
8764 }
8765
8766 if (totlen > xbuf_len)
8767 abort ();
8768 }
8769
8770 /* If there is anything left of the definition after handling
8771 the arg list, copy that in too. */
8772
8773 for (i = offset; i < defn->length; i++) {
8774 /* if we've reached the end of the macro */
8775 if (exp[i] == ')')
8776 rest_zero = 0;
8777 if (! (rest_zero && last_ap != NULL && last_ap->rest_args
8778 && last_ap->raw_after != 0))
8779 xbuf[totlen++] = exp[i];
8780 }
8781
8782 xbuf[totlen] = 0;
8783 xbuf_len = totlen;
8784
8785 for (i = 0; i < nargs; i++) {
8786 if (args[i].free1 != 0)
8787 free (args[i].free1);
8788 if (args[i].free2 != 0)
8789 free (args[i].free2);
8790 }
8791 }
8792 } else {
8793 xbuf = defn->expansion;
8794 xbuf_len = defn->length;
8795 }
8796
8797 /* Now put the expansion on the input stack
8798 so our caller will commence reading from it. */
8799 {
8800 register FILE_BUF *ip2;
8801
8802 ip2 = &instack[++indepth];
8803
8804 ip2->fname = 0;
8805 ip2->nominal_fname = 0;
8806 ip2->nominal_fname_len = 0;
8807 ip2->inc = 0;
8808 /* This may not be exactly correct, but will give much better error
8809 messages for nested macro calls than using a line number of zero. */
8810 ip2->lineno = start_line;
8811 ip2->buf = xbuf;
8812 ip2->length = xbuf_len;
8813 ip2->bufp = xbuf;
8814 ip2->free_ptr = (nargs > 0) ? xbuf : 0;
8815 ip2->macro = hp;
8816 ip2->if_stack = if_stack;
8817 ip2->system_header_p = 0;
8818
8819 /* Recursive macro use sometimes works traditionally.
8820 #define foo(x,y) bar (x (y,0), y)
8821 foo (foo, baz) */
8822
8823 if (!traditional)
8824 hp->type = T_DISABLED;
8825 }
8826 }
8827 \f
8828 /* Parse a macro argument and store the info on it into *ARGPTR.
8829 REST_ARGS is passed to macarg1 to make it absorb the rest of the args.
8830 Return nonzero to indicate a syntax error. */
8831
8832 static int
8833 macarg (argptr, rest_args)
8834 register struct argdata *argptr;
8835 int rest_args;
8836 {
8837 FILE_BUF *ip = &instack[indepth];
8838 int paren = 0;
8839 int lineno0 = ip->lineno;
8840 int comments = 0;
8841 int result = 0;
8842
8843 /* Try to parse as much of the argument as exists at this
8844 input stack level. */
8845 U_CHAR *bp = macarg1 (ip->bufp, ip->buf + ip->length, ip->macro,
8846 &paren, &ip->lineno, &comments, rest_args);
8847
8848 /* If we find the end of the argument at this level,
8849 set up *ARGPTR to point at it in the input stack. */
8850 if (!(ip->fname != 0 && (ip->lineno != lineno0 || comments != 0))
8851 && bp != ip->buf + ip->length) {
8852 if (argptr != 0) {
8853 argptr->raw = ip->bufp;
8854 argptr->raw_length = bp - ip->bufp;
8855 argptr->newlines = ip->lineno - lineno0;
8856 }
8857 ip->bufp = bp;
8858 } else {
8859 /* This input stack level ends before the macro argument does.
8860 We must pop levels and keep parsing.
8861 Therefore, we must allocate a temporary buffer and copy
8862 the macro argument into it. */
8863 int bufsize = bp - ip->bufp;
8864 int extra = ip->lineno - lineno0;
8865 U_CHAR *buffer = (U_CHAR *) xmalloc (bufsize + extra + 1);
8866 int final_start = 0;
8867
8868 bcopy ((char *) ip->bufp, (char *) buffer, bufsize);
8869 ip->bufp = bp;
8870
8871 while (bp == ip->buf + ip->length) {
8872 if (instack[indepth].macro == 0) {
8873 result = 1;
8874 break;
8875 }
8876 ip->macro->type = T_MACRO;
8877 if (ip->free_ptr)
8878 free (ip->free_ptr);
8879 ip = &instack[--indepth];
8880 lineno0 = ip->lineno;
8881 comments = 0;
8882 bp = macarg1 (ip->bufp, ip->buf + ip->length, ip->macro, &paren,
8883 &ip->lineno, &comments, rest_args);
8884 final_start = bufsize;
8885 bufsize += bp - ip->bufp;
8886 extra += ip->lineno - lineno0;
8887 buffer = (U_CHAR *) xrealloc (buffer, bufsize + extra + 1);
8888 bcopy ((char *) ip->bufp, (char *) (buffer + bufsize - (bp - ip->bufp)),
8889 bp - ip->bufp);
8890 ip->bufp = bp;
8891 }
8892
8893 /* Now, if arg is actually wanted, record its raw form,
8894 discarding comments and duplicating newlines in whatever
8895 part of it did not come from a macro expansion.
8896 EXTRA space has been preallocated for duplicating the newlines.
8897 FINAL_START is the index of the start of that part. */
8898 if (argptr != 0) {
8899 argptr->raw = buffer;
8900 argptr->raw_length = bufsize;
8901 argptr->free1 = buffer;
8902 argptr->newlines = ip->lineno - lineno0;
8903 if ((argptr->newlines || comments) && ip->fname != 0)
8904 argptr->raw_length
8905 = final_start +
8906 discard_comments (argptr->raw + final_start,
8907 argptr->raw_length - final_start,
8908 argptr->newlines);
8909 argptr->raw[argptr->raw_length] = 0;
8910 if (argptr->raw_length > bufsize + extra)
8911 abort ();
8912 }
8913 }
8914
8915 /* If we are not discarding this argument,
8916 macroexpand it and compute its length as stringified.
8917 All this info goes into *ARGPTR. */
8918
8919 if (argptr != 0) {
8920 register U_CHAR *buf, *lim;
8921 register int totlen;
8922
8923 buf = argptr->raw;
8924 lim = buf + argptr->raw_length;
8925
8926 while (buf != lim && is_space[*buf])
8927 buf++;
8928 while (buf != lim && is_space[lim[-1]])
8929 lim--;
8930 totlen = traditional ? 0 : 2; /* Count opening and closing quote. */
8931 while (buf != lim) {
8932 register U_CHAR c = *buf++;
8933 totlen++;
8934 /* Internal sequences of whitespace are replaced by one space
8935 in most cases, but not always. So count all the whitespace
8936 in case we need to keep it all. */
8937 #if 0
8938 if (is_space[c])
8939 SKIP_ALL_WHITE_SPACE (buf);
8940 else
8941 #endif
8942 if (c == '\"' || c == '\\' || c == '\n') /* escape these chars */
8943 totlen++;
8944 }
8945 argptr->stringified_length_bound = totlen;
8946 }
8947 return result;
8948 }
8949 \f
8950 /* Scan text from START (inclusive) up to LIMIT (exclusive),
8951 taken from the expansion of MACRO,
8952 counting parens in *DEPTHPTR,
8953 and return if reach LIMIT
8954 or before a `)' that would make *DEPTHPTR negative
8955 or before a comma when *DEPTHPTR is zero.
8956 Single and double quotes are matched and termination
8957 is inhibited within them. Comments also inhibit it.
8958 Value returned is pointer to stopping place.
8959
8960 Increment *NEWLINES each time a newline is passed.
8961 REST_ARGS notifies macarg1 that it should absorb the rest of the args.
8962 Set *COMMENTS to 1 if a comment is seen. */
8963
8964 static U_CHAR *
8965 macarg1 (start, limit, macro, depthptr, newlines, comments, rest_args)
8966 U_CHAR *start;
8967 register U_CHAR *limit;
8968 struct hashnode *macro;
8969 int *depthptr, *newlines, *comments;
8970 int rest_args;
8971 {
8972 register U_CHAR *bp = start;
8973
8974 while (bp < limit) {
8975 switch (*bp) {
8976 case '(':
8977 (*depthptr)++;
8978 break;
8979 case ')':
8980 if (--(*depthptr) < 0)
8981 return bp;
8982 break;
8983 case '\\':
8984 /* Traditionally, backslash makes following char not special. */
8985 if (traditional && bp + 1 < limit && bp[1] != '\n')
8986 bp++;
8987 break;
8988 case '\n':
8989 ++*newlines;
8990 break;
8991 case '/':
8992 if (macro)
8993 break;
8994 if (bp[1] == '\\')
8995 newline_fix (bp + 1);
8996 if (bp[1] == '*') {
8997 *comments = 1;
8998 for (bp += 2; bp < limit; bp++) {
8999 if (*bp == '\n')
9000 ++*newlines;
9001 else if (*bp == '*') {
9002 if (bp[-1] == '/' && warn_comments)
9003 warning ("`/*' within comment");
9004 if (bp[1] == '\\')
9005 newline_fix (bp + 1);
9006 if (bp[1] == '/') {
9007 bp++;
9008 break;
9009 }
9010 }
9011 else
9012 {
9013 #ifdef MULTIBYTE_CHARS
9014 int length;
9015 length = local_mblen (bp, limit - bp);
9016 if (length > 1)
9017 bp += (length - 1);
9018 #endif
9019 }
9020 }
9021 } else if (bp[1] == '/' && cplusplus_comments) {
9022 *comments = 1;
9023 for (bp += 2; bp < limit; bp++) {
9024 if (*bp == '\n') {
9025 ++*newlines;
9026 break;
9027 }
9028 if (*bp == '\\' && bp + 1 < limit && bp[1] == '\n')
9029 {
9030 ++*newlines;
9031 if (warn_comments)
9032 warning ("multiline `//' comment");
9033 ++bp;
9034 }
9035 else
9036 {
9037 #ifdef MULTIBYTE_CHARS
9038 int length;
9039 length = local_mblen (bp, limit - bp);
9040 if (length > 1)
9041 bp += (length - 1);
9042 #endif
9043 }
9044 }
9045 }
9046 break;
9047 case '\'':
9048 case '\"':
9049 {
9050 int quotec;
9051 for (quotec = *bp++; bp < limit && *bp != quotec; bp++) {
9052 if (*bp == '\\') {
9053 bp++;
9054 if (*bp == '\n')
9055 ++*newlines;
9056 while (*bp == '\\' && bp[1] == '\n') {
9057 bp += 2;
9058 ++*newlines;
9059 }
9060 } else if (*bp == '\n') {
9061 if (warn_white_space && is_hor_space[bp[-1]] && ! macro)
9062 warning ("white space at end of line in string");
9063 ++*newlines;
9064 if (quotec == '\'')
9065 break;
9066 }
9067 else
9068 {
9069 #ifdef MULTIBYTE_CHARS
9070 int length;
9071 length = local_mblen (bp, limit - bp);
9072 if (length > 1)
9073 bp += (length - 1);
9074 #endif
9075 }
9076 }
9077 }
9078 break;
9079 case ',':
9080 /* if we've returned to lowest level and we aren't absorbing all args */
9081 if ((*depthptr) == 0 && rest_args == 0)
9082 return bp;
9083 break;
9084 }
9085 bp++;
9086 }
9087
9088 return bp;
9089 }
9090 \f
9091 /* Discard comments and duplicate newlines
9092 in the string of length LENGTH at START,
9093 except inside of string constants.
9094 The string is copied into itself with its beginning staying fixed.
9095
9096 NEWLINES is the number of newlines that must be duplicated.
9097 We assume that that much extra space is available past the end
9098 of the string. */
9099
9100 static int
9101 discard_comments (start, length, newlines)
9102 U_CHAR *start;
9103 int length;
9104 int newlines;
9105 {
9106 register U_CHAR *ibp;
9107 register U_CHAR *obp;
9108 register U_CHAR *limit;
9109 register int c;
9110
9111 /* If we have newlines to duplicate, copy everything
9112 that many characters up. Then, in the second part,
9113 we will have room to insert the newlines
9114 while copying down.
9115 NEWLINES may actually be too large, because it counts
9116 newlines in string constants, and we don't duplicate those.
9117 But that does no harm. */
9118 if (newlines > 0) {
9119 ibp = start + length;
9120 obp = ibp + newlines;
9121 limit = start;
9122 while (limit != ibp)
9123 *--obp = *--ibp;
9124 }
9125
9126 ibp = start + newlines;
9127 limit = start + length + newlines;
9128 obp = start;
9129
9130 while (ibp < limit) {
9131 *obp++ = c = *ibp++;
9132 switch (c) {
9133 case '\n':
9134 /* Duplicate the newline. */
9135 *obp++ = '\n';
9136 break;
9137
9138 case '\\':
9139 if (*ibp == '\n') {
9140 obp--;
9141 ibp++;
9142 }
9143 break;
9144
9145 case '/':
9146 if (*ibp == '\\')
9147 newline_fix (ibp);
9148 /* Delete any comment. */
9149 if (cplusplus_comments && ibp[0] == '/') {
9150 /* Comments are equivalent to spaces. */
9151 obp[-1] = ' ';
9152 ibp++;
9153 while (ibp < limit)
9154 {
9155 if (*ibp == '\n')
9156 break;
9157 if (*ibp == '\\' && ibp + 1 < limit && ibp[1] == '\n')
9158 ibp++;
9159 else
9160 {
9161 #ifdef MULTIBYTE_CHARS
9162 int length = local_mblen (ibp, limit - ibp);
9163 if (length > 1)
9164 ibp += (length - 1);
9165 #endif
9166 }
9167 ibp++;
9168 }
9169 break;
9170 }
9171 if (ibp[0] != '*' || ibp + 1 >= limit)
9172 break;
9173 /* Comments are equivalent to spaces.
9174 For -traditional, a comment is equivalent to nothing. */
9175 if (traditional)
9176 obp--;
9177 else
9178 obp[-1] = ' ';
9179 while (++ibp < limit) {
9180 if (ibp[0] == '*') {
9181 if (ibp[1] == '\\')
9182 newline_fix (ibp + 1);
9183 if (ibp[1] == '/') {
9184 ibp += 2;
9185 break;
9186 }
9187 }
9188 else
9189 {
9190 #ifdef MULTIBYTE_CHARS
9191 int length = local_mblen (ibp, limit - ibp);
9192 if (length > 1)
9193 ibp += (length - 1);
9194 #endif
9195 }
9196 }
9197 break;
9198
9199 case '\'':
9200 case '\"':
9201 /* Notice and skip strings, so that we don't
9202 think that comments start inside them,
9203 and so we don't duplicate newlines in them. */
9204 {
9205 int quotec = c;
9206 while (ibp < limit) {
9207 *obp++ = c = *ibp++;
9208 if (c == quotec)
9209 break;
9210 if (c == '\n')
9211 {
9212 if (quotec == '\'')
9213 break;
9214 }
9215 else if (c == '\\') {
9216 if (ibp < limit && *ibp == '\n') {
9217 ibp++;
9218 obp--;
9219 } else {
9220 while (*ibp == '\\' && ibp[1] == '\n')
9221 ibp += 2;
9222 if (ibp < limit)
9223 *obp++ = *ibp++;
9224 }
9225 }
9226 else
9227 {
9228 #ifdef MULTIBYTE_CHARS
9229 int length;
9230 ibp--;
9231 length = local_mblen (ibp, limit - ibp);
9232 if (length > 1)
9233 {
9234 obp--;
9235 bcopy (ibp, obp, length);
9236 ibp += length;
9237 obp += length;
9238 }
9239 else
9240 ibp++;
9241 #endif
9242 }
9243 }
9244 }
9245 break;
9246 }
9247 }
9248
9249 return obp - start;
9250 }
9251 \f
9252 /* Turn newlines to spaces in the macro argument ARG.
9253 Remove backslash-newline from string constants,
9254 and turn other newlines in string constants to backslash-'n'. */
9255
9256 static void
9257 change_newlines (arg)
9258 struct argdata *arg;
9259 {
9260 U_CHAR *start = arg->expanded;
9261 int length = arg->expand_length;
9262 register U_CHAR *ibp;
9263 register U_CHAR *obp;
9264 register U_CHAR *limit;
9265 register int c;
9266
9267 ibp = start;
9268 limit = start + length;
9269 obp = start;
9270
9271 while (ibp < limit) {
9272 *obp++ = c = *ibp++;
9273 switch (c) {
9274 case '\n':
9275 /* If this is a NEWLINE NEWLINE, then this is a real newline in the
9276 string. Skip past the newline and its duplicate.
9277 Put a space in the output. */
9278 if (*ibp == '\n')
9279 {
9280 ibp++;
9281 obp--;
9282 *obp++ = ' ';
9283 }
9284 break;
9285
9286 case '\'':
9287 case '\"':
9288 /* Notice and skip strings, so that we don't delete newlines in them. */
9289 {
9290 int quotec = c;
9291 while (ibp < limit) {
9292 *obp++ = c = *ibp++;
9293 if (c == quotec)
9294 break;
9295 else if (c == '\\' && ibp < limit && *ibp == '\n')
9296 *obp++ = *ibp++;
9297 else if (c == '\n')
9298 {
9299 if (quotec == '\'')
9300 break;
9301 }
9302 else
9303 {
9304 #ifdef MULTIBYTE_CHARS
9305 int length;
9306 ibp--;
9307 length = local_mblen (ibp, limit - ibp);
9308 if (length > 1)
9309 {
9310 obp--;
9311 bcopy (ibp, obp, length);
9312 ibp += length;
9313 obp += length;
9314 }
9315 else
9316 ibp++;
9317 #endif
9318 }
9319 }
9320 }
9321 break;
9322 }
9323 }
9324
9325 arg->expand_length = obp - arg->expanded;
9326
9327 if (start != arg->expanded)
9328 free (start);
9329 }
9330 \f
9331 /* notice - output message to stderr */
9332
9333 static void
9334 notice VPROTO ((const char * msgid, ...))
9335 {
9336 #ifndef ANSI_PROTOTYPES
9337 const char * msgid;
9338 #endif
9339 va_list args;
9340
9341 VA_START (args, msgid);
9342
9343 #ifndef ANSI_PROTOTYPES
9344 msgid = va_arg (args, const char *);
9345 #endif
9346
9347 vnotice (msgid, args);
9348 va_end (args);
9349 }
9350
9351 static void
9352 vnotice (msgid, args)
9353 const char *msgid;
9354 va_list args;
9355 {
9356 vfprintf (stderr, _(msgid), args);
9357 }
9358
9359 /* error - print error message and increment count of errors. */
9360
9361 void
9362 error VPROTO ((const char * msgid, ...))
9363 {
9364 #ifndef ANSI_PROTOTYPES
9365 const char * msgid;
9366 #endif
9367 va_list args;
9368
9369 VA_START (args, msgid);
9370
9371 #ifndef ANSI_PROTOTYPES
9372 msgid = va_arg (args, const char *);
9373 #endif
9374
9375 verror (msgid, args);
9376 va_end (args);
9377 }
9378
9379 void
9380 verror (msgid, args)
9381 const char *msgid;
9382 va_list args;
9383 {
9384 int i;
9385 FILE_BUF *ip = NULL;
9386
9387 print_containing_files ();
9388
9389 for (i = indepth; i >= 0; i--)
9390 if (instack[i].fname != NULL) {
9391 ip = &instack[i];
9392 break;
9393 }
9394
9395 if (ip != NULL) {
9396 fwrite (ip->nominal_fname, sizeof ip->nominal_fname[0],
9397 ip->nominal_fname_len, stderr);
9398 fprintf (stderr, ":%d: ", ip->lineno);
9399 }
9400 vnotice (msgid, args);
9401 fprintf (stderr, "\n");
9402 errors++;
9403 }
9404
9405 /* Error including a message from `errno'. */
9406
9407 static void
9408 error_from_errno (name)
9409 char *name;
9410 {
9411 int e = errno;
9412 int i;
9413 FILE_BUF *ip = NULL;
9414
9415 print_containing_files ();
9416
9417 for (i = indepth; i >= 0; i--)
9418 if (instack[i].fname != NULL) {
9419 ip = &instack[i];
9420 break;
9421 }
9422
9423 if (ip != NULL) {
9424 fwrite (ip->nominal_fname, sizeof ip->nominal_fname[0],
9425 ip->nominal_fname_len, stderr);
9426 fprintf (stderr, ":%d: ", ip->lineno);
9427 }
9428
9429 fprintf (stderr, "%s: %s\n", name, xstrerror (e));
9430
9431 errors++;
9432 }
9433
9434 /* Print error message but don't count it. */
9435
9436 void
9437 warning VPROTO ((const char * msgid, ...))
9438 {
9439 #ifndef ANSI_PROTOTYPES
9440 const char * msgid;
9441 #endif
9442 va_list args;
9443
9444 VA_START (args, msgid);
9445
9446 #ifndef ANSI_PROTOTYPES
9447 msgid = va_arg (args, const char *);
9448 #endif
9449
9450 vwarning (msgid, args);
9451 va_end (args);
9452 }
9453
9454 static void
9455 vwarning (msgid, args)
9456 const char *msgid;
9457 va_list args;
9458 {
9459 int i;
9460 FILE_BUF *ip = NULL;
9461
9462 if (inhibit_warnings)
9463 return;
9464
9465 if (warnings_are_errors)
9466 errors++;
9467
9468 print_containing_files ();
9469
9470 for (i = indepth; i >= 0; i--)
9471 if (instack[i].fname != NULL) {
9472 ip = &instack[i];
9473 break;
9474 }
9475
9476 if (ip != NULL) {
9477 fwrite (ip->nominal_fname, sizeof ip->nominal_fname[0],
9478 ip->nominal_fname_len, stderr);
9479 fprintf (stderr, ":%d: ", ip->lineno);
9480 }
9481 notice ("warning: ");
9482 vnotice (msgid, args);
9483 fprintf (stderr, "\n");
9484 }
9485
9486 static void
9487 error_with_line VPROTO ((int line, const char * msgid, ...))
9488 {
9489 #ifndef ANSI_PROTOTYPES
9490 int line;
9491 const char * msgid;
9492 #endif
9493 va_list args;
9494
9495 VA_START (args, msgid);
9496
9497 #ifndef ANSI_PROTOTYPES
9498 line = va_arg (args, int);
9499 msgid = va_arg (args, const char *);
9500 #endif
9501
9502 verror_with_line (line, msgid, args);
9503 va_end (args);
9504 }
9505
9506
9507 static void
9508 verror_with_line (line, msgid, args)
9509 int line;
9510 const char *msgid;
9511 va_list args;
9512 {
9513 int i;
9514 FILE_BUF *ip = NULL;
9515
9516 print_containing_files ();
9517
9518 for (i = indepth; i >= 0; i--)
9519 if (instack[i].fname != NULL) {
9520 ip = &instack[i];
9521 break;
9522 }
9523
9524 if (ip != NULL) {
9525 fwrite (ip->nominal_fname, sizeof ip->nominal_fname[0],
9526 ip->nominal_fname_len, stderr);
9527 fprintf (stderr, ":%d: ", line);
9528 }
9529 vnotice (msgid, args);
9530 fprintf (stderr, "\n");
9531 errors++;
9532 }
9533
9534 static void
9535 warning_with_line VPROTO ((int line, const char * msgid, ...))
9536 {
9537 #ifndef ANSI_PROTOTYPES
9538 int line;
9539 const char * msgid;
9540 #endif
9541 va_list args;
9542
9543 VA_START (args, msgid);
9544
9545 #ifndef ANSI_PROTOTYPES
9546 line = va_arg (args, int);
9547 msgid = va_arg (args, const char *);
9548 #endif
9549
9550 vwarning_with_line (line, msgid, args);
9551 va_end (args);
9552 }
9553
9554 static void
9555 vwarning_with_line (line, msgid, args)
9556 int line;
9557 const char *msgid;
9558 va_list args;
9559 {
9560 int i;
9561 FILE_BUF *ip = NULL;
9562
9563 if (inhibit_warnings)
9564 return;
9565
9566 if (warnings_are_errors)
9567 errors++;
9568
9569 print_containing_files ();
9570
9571 for (i = indepth; i >= 0; i--)
9572 if (instack[i].fname != NULL) {
9573 ip = &instack[i];
9574 break;
9575 }
9576
9577 if (ip != NULL) {
9578 fwrite (ip->nominal_fname, sizeof ip->nominal_fname[0],
9579 ip->nominal_fname_len, stderr);
9580 fprintf (stderr, line ? ":%d: " : ": ", line);
9581 }
9582 notice ("warning: ");
9583 vnotice (msgid, args);
9584 fprintf (stderr, "\n");
9585 }
9586
9587 /* Print an error message and maybe count it. */
9588
9589 void
9590 pedwarn VPROTO ((const char * msgid, ...))
9591 {
9592 #ifndef ANSI_PROTOTYPES
9593 const char * msgid;
9594 #endif
9595 va_list args;
9596
9597 VA_START (args, msgid);
9598
9599 #ifndef ANSI_PROTOTYPES
9600 msgid = va_arg (args, const char *);
9601 #endif
9602
9603 if (pedantic_errors)
9604 verror (msgid, args);
9605 else
9606 vwarning (msgid, args);
9607 va_end (args);
9608 }
9609
9610 void
9611 pedwarn_with_line VPROTO ((int line, const char * msgid, ...))
9612 {
9613 #ifndef ANSI_PROTOTYPES
9614 int line;
9615 const char * msgid;
9616 #endif
9617 va_list args;
9618
9619 VA_START (args, msgid);
9620
9621 #ifndef ANSI_PROTOTYPES
9622 line = va_arg (args, int);
9623 msgid = va_arg (args, const char *);
9624 #endif
9625
9626 if (pedantic_errors)
9627 verror_with_line (line, msgid, args);
9628 else
9629 vwarning_with_line (line, msgid, args);
9630 va_end (args);
9631 }
9632
9633 /* Report a warning (or an error if pedantic_errors)
9634 giving specified file name and line number, not current. */
9635
9636 static void
9637 pedwarn_with_file_and_line VPROTO ((const char *file, size_t file_len, int line,
9638 const char * msgid, ...))
9639 {
9640 #ifndef ANSI_PROTOTYPES
9641 const char *file;
9642 size_t file_len;
9643 int line;
9644 const char * msgid;
9645 #endif
9646 va_list args;
9647
9648 if (!pedantic_errors && inhibit_warnings)
9649 return;
9650
9651 VA_START (args, msgid);
9652
9653 #ifndef ANSI_PROTOTYPES
9654 file = va_arg (args, const char *);
9655 file_len = va_arg (args, size_t);
9656 line = va_arg (args, int);
9657 msgid = va_arg (args, const char *);
9658 #endif
9659
9660 if (file) {
9661 fwrite (file, sizeof file[0], file_len, stderr);
9662 fprintf (stderr, ":%d: ", line);
9663 }
9664 if (pedantic_errors)
9665 errors++;
9666 if (!pedantic_errors)
9667 notice ("warning: ");
9668 vnotice (msgid, args);
9669 va_end (args);
9670 fprintf (stderr, "\n");
9671 }
9672
9673 static void
9674 pedwarn_strange_white_space (ch)
9675 int ch;
9676 {
9677 switch (ch)
9678 {
9679 case '\f': pedwarn ("formfeed in preprocessing directive"); break;
9680 case '\r': pedwarn ("carriage return in preprocessing directive"); break;
9681 case '\v': pedwarn ("vertical tab in preprocessing directive"); break;
9682 default: abort ();
9683 }
9684 }
9685 \f
9686 /* Print the file names and line numbers of the #include
9687 directives which led to the current file. */
9688
9689 static void
9690 print_containing_files ()
9691 {
9692 FILE_BUF *ip = NULL;
9693 int i;
9694 int first = 1;
9695
9696 /* If stack of files hasn't changed since we last printed
9697 this info, don't repeat it. */
9698 if (last_error_tick == input_file_stack_tick)
9699 return;
9700
9701 for (i = indepth; i >= 0; i--)
9702 if (instack[i].fname != NULL) {
9703 ip = &instack[i];
9704 break;
9705 }
9706
9707 /* Give up if we don't find a source file. */
9708 if (ip == NULL)
9709 return;
9710
9711 /* Find the other, outer source files. */
9712 for (i--; i >= 0; i--)
9713 if (instack[i].fname != NULL) {
9714 ip = &instack[i];
9715 if (first) {
9716 first = 0;
9717 notice ( "In file included from ");
9718 } else {
9719 notice (",\n from ");
9720 }
9721
9722 fwrite (ip->nominal_fname, sizeof ip->nominal_fname[0],
9723 ip->nominal_fname_len, stderr);
9724 fprintf (stderr, ":%d", ip->lineno);
9725 }
9726 if (! first)
9727 fprintf (stderr, ":\n");
9728
9729 /* Record we have printed the status as of this time. */
9730 last_error_tick = input_file_stack_tick;
9731 }
9732 \f
9733 /* Return the line at which an error occurred.
9734 The error is not necessarily associated with the current spot
9735 in the input stack, so LINE says where. LINE will have been
9736 copied from ip->lineno for the current input level.
9737 If the current level is for a file, we return LINE.
9738 But if the current level is not for a file, LINE is meaningless.
9739 In that case, we return the lineno of the innermost file. */
9740
9741 static int
9742 line_for_error (line)
9743 int line;
9744 {
9745 int i;
9746 int line1 = line;
9747
9748 for (i = indepth; i >= 0; ) {
9749 if (instack[i].fname != 0)
9750 return line1;
9751 i--;
9752 if (i < 0)
9753 return 0;
9754 line1 = instack[i].lineno;
9755 }
9756 abort ();
9757 /*NOTREACHED*/
9758 return 0;
9759 }
9760
9761 /*
9762 * If OBUF doesn't have NEEDED bytes after OPTR, make it bigger.
9763 *
9764 * As things stand, nothing is ever placed in the output buffer to be
9765 * removed again except when it's KNOWN to be part of an identifier,
9766 * so flushing and moving down everything left, instead of expanding,
9767 * should work ok.
9768 */
9769
9770 /* You might think void was cleaner for the return type,
9771 but that would get type mismatch in check_expand in strict ANSI. */
9772
9773 static int
9774 grow_outbuf (obuf, needed)
9775 register FILE_BUF *obuf;
9776 register int needed;
9777 {
9778 register U_CHAR *p;
9779 int minsize;
9780
9781 if (obuf->length - (obuf->bufp - obuf->buf) > needed)
9782 return 0;
9783
9784 /* Make it at least twice as big as it is now. */
9785 obuf->length *= 2;
9786 /* Make it have at least 150% of the free space we will need. */
9787 minsize = (3 * needed) / 2 + (obuf->bufp - obuf->buf);
9788 if (minsize > obuf->length)
9789 obuf->length = minsize;
9790
9791 p = (U_CHAR *) xrealloc (obuf->buf, obuf->length);
9792
9793 obuf->bufp = p + (obuf->bufp - obuf->buf);
9794 obuf->buf = p;
9795
9796 return 0;
9797 }
9798 \f
9799 /* Symbol table for macro names and special symbols */
9800
9801 /*
9802 * install a name in the main hash table, even if it is already there.
9803 * name stops with first non alphanumeric, except leading '#'.
9804 * caller must check against redefinition if that is desired.
9805 * delete_macro () removes things installed by install () in fifo order.
9806 * this is important because of the `defined' special symbol used
9807 * in #if, and also if pushdef/popdef directives are ever implemented.
9808 *
9809 * If LEN is >= 0, it is the length of the name.
9810 * Otherwise, compute the length by scanning the entire name.
9811 *
9812 * If HASH is >= 0, it is the precomputed hash code.
9813 * Otherwise, compute the hash code.
9814 */
9815
9816 static HASHNODE *
9817 install (name, len, type, value, hash)
9818 U_CHAR *name;
9819 int len;
9820 enum node_type type;
9821 char *value;
9822 int hash;
9823 {
9824 register HASHNODE *hp;
9825 register int i, bucket;
9826 register U_CHAR *p, *q;
9827
9828 if (len < 0) {
9829 p = name;
9830 while (is_idchar[*p])
9831 p++;
9832 len = p - name;
9833 }
9834
9835 if (hash < 0)
9836 hash = hashf (name, len, HASHSIZE);
9837
9838 i = sizeof (HASHNODE) + len + 1;
9839 hp = (HASHNODE *) xmalloc (i);
9840 bucket = hash;
9841 hp->bucket_hdr = &hashtab[bucket];
9842 hp->next = hashtab[bucket];
9843 hashtab[bucket] = hp;
9844 hp->prev = NULL;
9845 if (hp->next != NULL)
9846 hp->next->prev = hp;
9847 hp->type = type;
9848 hp->length = len;
9849 hp->value.cpval = value;
9850 hp->name = ((U_CHAR *) hp) + sizeof (HASHNODE);
9851 p = hp->name;
9852 q = name;
9853 for (i = 0; i < len; i++)
9854 *p++ = *q++;
9855 hp->name[len] = 0;
9856 return hp;
9857 }
9858
9859 /*
9860 * find the most recent hash node for name "name" (ending with first
9861 * non-identifier char) installed by install
9862 *
9863 * If LEN is >= 0, it is the length of the name.
9864 * Otherwise, compute the length by scanning the entire name.
9865 *
9866 * If HASH is >= 0, it is the precomputed hash code.
9867 * Otherwise, compute the hash code.
9868 */
9869
9870 HASHNODE *
9871 lookup (name, len, hash)
9872 U_CHAR *name;
9873 int len;
9874 int hash;
9875 {
9876 register U_CHAR *bp;
9877 register HASHNODE *bucket;
9878
9879 if (len < 0) {
9880 for (bp = name; is_idchar[*bp]; bp++) ;
9881 len = bp - name;
9882 }
9883
9884 if (hash < 0)
9885 hash = hashf (name, len, HASHSIZE);
9886
9887 bucket = hashtab[hash];
9888 while (bucket) {
9889 if (bucket->length == len && bcmp (bucket->name, name, len) == 0)
9890 return bucket;
9891 bucket = bucket->next;
9892 }
9893 return NULL;
9894 }
9895
9896 /*
9897 * Delete a hash node. Some weirdness to free junk from macros.
9898 * More such weirdness will have to be added if you define more hash
9899 * types that need it.
9900 */
9901
9902 /* Note that the DEFINITION of a macro is removed from the hash table
9903 but its storage is not freed. This would be a storage leak
9904 except that it is not reasonable to keep undefining and redefining
9905 large numbers of macros many times.
9906 In any case, this is necessary, because a macro can be #undef'd
9907 in the middle of reading the arguments to a call to it.
9908 If #undef freed the DEFINITION, that would crash. */
9909
9910 static void
9911 delete_macro (hp)
9912 HASHNODE *hp;
9913 {
9914
9915 if (hp->prev != NULL)
9916 hp->prev->next = hp->next;
9917 if (hp->next != NULL)
9918 hp->next->prev = hp->prev;
9919
9920 /* Make sure that the bucket chain header that the deleted guy was
9921 on points to the right thing afterwards. */
9922 if (hp == *hp->bucket_hdr)
9923 *hp->bucket_hdr = hp->next;
9924
9925 #if 0
9926 if (hp->type == T_MACRO) {
9927 DEFINITION *d = hp->value.defn;
9928 struct reflist *ap, *nextap;
9929
9930 for (ap = d->pattern; ap != NULL; ap = nextap) {
9931 nextap = ap->next;
9932 free (ap);
9933 }
9934 free (d);
9935 }
9936 #endif
9937 free (hp);
9938 }
9939
9940 /*
9941 * return hash function on name. must be compatible with the one
9942 * computed a step at a time, elsewhere
9943 */
9944
9945 static int
9946 hashf (name, len, hashsize)
9947 register U_CHAR *name;
9948 register int len;
9949 int hashsize;
9950 {
9951 register int r = 0;
9952
9953 while (len--)
9954 r = HASHSTEP (r, *name++);
9955
9956 return MAKE_POS (r) % hashsize;
9957 }
9958 \f
9959
9960 /* Dump the definition of a single macro HP to OF. */
9961
9962 static void
9963 dump_single_macro (hp, of)
9964 register HASHNODE *hp;
9965 FILE *of;
9966 {
9967 register DEFINITION *defn = hp->value.defn;
9968 struct reflist *ap;
9969 int offset;
9970 int concat;
9971
9972
9973 /* Print the definition of the macro HP. */
9974
9975 fprintf (of, "#define %s", hp->name);
9976
9977 if (defn->nargs >= 0) {
9978 int i;
9979
9980 fprintf (of, "(");
9981 for (i = 0; i < defn->nargs; i++) {
9982 dump_arg_n (defn, i, of);
9983 if (i + 1 < defn->nargs)
9984 fprintf (of, ", ");
9985 }
9986 fprintf (of, ")");
9987 }
9988
9989 fprintf (of, " ");
9990
9991 offset = 0;
9992 concat = 0;
9993 for (ap = defn->pattern; ap != NULL; ap = ap->next) {
9994 dump_defn_1 (defn->expansion, offset, ap->nchars, of);
9995 offset += ap->nchars;
9996 if (!traditional) {
9997 if (ap->nchars != 0)
9998 concat = 0;
9999 if (ap->stringify) {
10000 switch (ap->stringify) {
10001 case SHARP_TOKEN: fprintf (of, "#"); break;
10002 case WHITE_SHARP_TOKEN: fprintf (of, "# "); break;
10003 case PERCENT_COLON_TOKEN: fprintf (of, "%%:"); break;
10004 case WHITE_PERCENT_COLON_TOKEN: fprintf (of, "%%: "); break;
10005 default: abort ();
10006 }
10007 }
10008 if (ap->raw_before != 0) {
10009 if (concat) {
10010 switch (ap->raw_before) {
10011 case WHITE_SHARP_TOKEN:
10012 case WHITE_PERCENT_COLON_TOKEN:
10013 fprintf (of, " ");
10014 break;
10015 default:
10016 break;
10017 }
10018 } else {
10019 switch (ap->raw_before) {
10020 case SHARP_TOKEN: fprintf (of, "##"); break;
10021 case WHITE_SHARP_TOKEN: fprintf (of, "## "); break;
10022 case PERCENT_COLON_TOKEN: fprintf (of, "%%:%%:"); break;
10023 case WHITE_PERCENT_COLON_TOKEN: fprintf (of, "%%:%%: "); break;
10024 default: abort ();
10025 }
10026 }
10027 }
10028 concat = 0;
10029 }
10030 dump_arg_n (defn, ap->argno, of);
10031 if (!traditional && ap->raw_after != 0) {
10032 switch (ap->raw_after) {
10033 case SHARP_TOKEN: fprintf (of, "##"); break;
10034 case WHITE_SHARP_TOKEN: fprintf (of, " ##"); break;
10035 case PERCENT_COLON_TOKEN: fprintf (of, "%%:%%:"); break;
10036 case WHITE_PERCENT_COLON_TOKEN: fprintf (of, " %%:%%:"); break;
10037 default: abort ();
10038 }
10039 concat = 1;
10040 }
10041 }
10042 dump_defn_1 (defn->expansion, offset, defn->length - offset, of);
10043 fprintf (of, "\n");
10044 }
10045
10046 /* Dump all macro definitions as #defines to stdout. */
10047
10048 static void
10049 dump_all_macros ()
10050 {
10051 int bucket;
10052
10053 for (bucket = 0; bucket < HASHSIZE; bucket++) {
10054 register HASHNODE *hp;
10055
10056 for (hp = hashtab[bucket]; hp; hp= hp->next) {
10057 if (hp->type == T_MACRO)
10058 dump_single_macro (hp, stdout);
10059 }
10060 }
10061 }
10062
10063 /* Output to OF a substring of a macro definition.
10064 BASE is the beginning of the definition.
10065 Output characters START thru LENGTH.
10066 Unless traditional, discard newlines outside of strings, thus
10067 converting funny-space markers to ordinary spaces. */
10068
10069 static void
10070 dump_defn_1 (base, start, length, of)
10071 U_CHAR *base;
10072 int start;
10073 int length;
10074 FILE *of;
10075 {
10076 U_CHAR *p = base + start;
10077 U_CHAR *limit = base + start + length;
10078
10079 if (traditional)
10080 fwrite (p, sizeof (*p), length, of);
10081 else {
10082 while (p < limit) {
10083 if (*p == '\"' || *p =='\'') {
10084 U_CHAR *p1 = skip_quoted_string (p, limit, 0, NULL_PTR,
10085 NULL_PTR, NULL_PTR);
10086 fwrite (p, sizeof (*p), p1 - p, of);
10087 p = p1;
10088 } else {
10089 if (*p != '\n')
10090 putc (*p, of);
10091 p++;
10092 }
10093 }
10094 }
10095 }
10096
10097 /* Print the name of argument number ARGNUM of macro definition DEFN
10098 to OF.
10099 Recall that DEFN->args.argnames contains all the arg names
10100 concatenated in reverse order with comma-space in between. */
10101
10102 static void
10103 dump_arg_n (defn, argnum, of)
10104 DEFINITION *defn;
10105 int argnum;
10106 FILE *of;
10107 {
10108 register U_CHAR *p = defn->args.argnames;
10109 while (argnum + 1 < defn->nargs) {
10110 p = (U_CHAR *) index ((char *) p, ' ') + 1;
10111 argnum++;
10112 }
10113
10114 while (*p && *p != ',') {
10115 putc (*p, of);
10116 p++;
10117 }
10118 }
10119 \f
10120 /* Initialize syntactic classifications of characters. */
10121
10122 static void
10123 initialize_char_syntax ()
10124 {
10125 register int i;
10126
10127 /*
10128 * Set up is_idchar and is_idstart tables. These should be
10129 * faster than saying (is_alpha (c) || c == '_'), etc.
10130 * Set up these things before calling any routines tthat
10131 * refer to them.
10132 */
10133 for (i = 'a'; i <= 'z'; i++) {
10134 is_idchar[TOUPPER(i)] = 1;
10135 is_idchar[i] = 1;
10136 is_idstart[TOUPPER(i)] = 1;
10137 is_idstart[i] = 1;
10138 }
10139 for (i = '0'; i <= '9'; i++)
10140 is_idchar[i] = 1;
10141 is_idchar['_'] = 1;
10142 is_idstart['_'] = 1;
10143 is_idchar['$'] = 1;
10144 is_idstart['$'] = 1;
10145
10146 /* horizontal space table */
10147 is_hor_space[' '] = 1;
10148 is_hor_space['\t'] = 1;
10149 is_hor_space['\v'] = 1;
10150 is_hor_space['\f'] = 1;
10151 is_hor_space['\r'] = 1;
10152
10153 is_space[' '] = 1;
10154 is_space['\t'] = 1;
10155 is_space['\v'] = 1;
10156 is_space['\f'] = 1;
10157 is_space['\n'] = 1;
10158 is_space['\r'] = 1;
10159 }
10160
10161 /* Initialize the built-in macros. */
10162
10163 static void
10164 initialize_builtins (inp, outp)
10165 FILE_BUF *inp;
10166 FILE_BUF *outp;
10167 {
10168 install ((U_CHAR *) "__LINE__", -1, T_SPECLINE, NULL_PTR, -1);
10169 install ((U_CHAR *) "__DATE__", -1, T_DATE, NULL_PTR, -1);
10170 install ((U_CHAR *) "__FILE__", -1, T_FILE, NULL_PTR, -1);
10171 install ((U_CHAR *) "__BASE_FILE__", -1, T_BASE_FILE, NULL_PTR, -1);
10172 install ((U_CHAR *) "__INCLUDE_LEVEL__", -1, T_INCLUDE_LEVEL, NULL_PTR, -1);
10173 install ((U_CHAR *) "__VERSION__", -1, T_VERSION, NULL_PTR, -1);
10174 #ifndef NO_BUILTIN_SIZE_TYPE
10175 install ((U_CHAR *) "__SIZE_TYPE__", -1, T_SIZE_TYPE, NULL_PTR, -1);
10176 #endif
10177 #ifndef NO_BUILTIN_PTRDIFF_TYPE
10178 install ((U_CHAR *) "__PTRDIFF_TYPE__ ", -1, T_PTRDIFF_TYPE, NULL_PTR, -1);
10179 #endif
10180 install ((U_CHAR *) "__WCHAR_TYPE__", -1, T_WCHAR_TYPE, NULL_PTR, -1);
10181 install ((U_CHAR *) "__USER_LABEL_PREFIX__", -1, T_USER_LABEL_PREFIX_TYPE,
10182 NULL_PTR, -1);
10183 install ((U_CHAR *) "__REGISTER_PREFIX__", -1, T_REGISTER_PREFIX_TYPE,
10184 NULL_PTR, -1);
10185 install ((U_CHAR *) "__IMMEDIATE_PREFIX__", -1, T_IMMEDIATE_PREFIX_TYPE,
10186 NULL_PTR, -1);
10187 install ((U_CHAR *) "__TIME__", -1, T_TIME, NULL_PTR, -1);
10188 if (!traditional) {
10189 install ((U_CHAR *) "__STDC__", -1, T_CONST, "1", -1);
10190 install ((U_CHAR *) "__STDC_VERSION__", -1, T_CONST, "199409L", -1);
10191 }
10192 /* This is supplied using a -D by the compiler driver
10193 so that it is present only when truly compiling with GNU C. */
10194 /* install ((U_CHAR *) "__GNUC__", -1, T_CONST, "2", -1); */
10195 install ((U_CHAR *) "__HAVE_BUILTIN_SETJMP__", -1, T_CONST, "1", -1);
10196
10197 if (debug_output)
10198 {
10199 char directive[2048];
10200 U_CHAR *udirective = (U_CHAR *) directive;
10201 register struct directive *dp = &directive_table[0];
10202 struct tm *timebuf = timestamp ();
10203
10204 sprintf (directive, " __BASE_FILE__ \"%s\"\n",
10205 instack[0].nominal_fname);
10206 output_line_directive (inp, outp, 0, same_file);
10207 pass_thru_directive (udirective, &udirective[strlen (directive)],
10208 outp, dp);
10209
10210 sprintf (directive, " __VERSION__ \"%s\"\n", version_string);
10211 output_line_directive (inp, outp, 0, same_file);
10212 pass_thru_directive (udirective, &udirective[strlen (directive)],
10213 outp, dp);
10214
10215 #ifndef NO_BUILTIN_SIZE_TYPE
10216 sprintf (directive, " __SIZE_TYPE__ %s\n", SIZE_TYPE);
10217 output_line_directive (inp, outp, 0, same_file);
10218 pass_thru_directive (udirective, &udirective[strlen (directive)],
10219 outp, dp);
10220 #endif
10221
10222 #ifndef NO_BUILTIN_PTRDIFF_TYPE
10223 sprintf (directive, " __PTRDIFF_TYPE__ %s\n", PTRDIFF_TYPE);
10224 output_line_directive (inp, outp, 0, same_file);
10225 pass_thru_directive (udirective, &udirective[strlen (directive)],
10226 outp, dp);
10227 #endif
10228
10229 sprintf (directive, " __WCHAR_TYPE__ %s\n", wchar_type);
10230 output_line_directive (inp, outp, 0, same_file);
10231 pass_thru_directive (udirective, &udirective[strlen (directive)],
10232 outp, dp);
10233
10234 sprintf (directive, " __DATE__ \"%s %2d %4d\"\n",
10235 monthnames[timebuf->tm_mon],
10236 timebuf->tm_mday, timebuf->tm_year + 1900);
10237 output_line_directive (inp, outp, 0, same_file);
10238 pass_thru_directive (udirective, &udirective[strlen (directive)],
10239 outp, dp);
10240
10241 sprintf (directive, " __TIME__ \"%02d:%02d:%02d\"\n",
10242 timebuf->tm_hour, timebuf->tm_min, timebuf->tm_sec);
10243 output_line_directive (inp, outp, 0, same_file);
10244 pass_thru_directive (udirective, &udirective[strlen (directive)],
10245 outp, dp);
10246
10247 if (!traditional)
10248 {
10249 sprintf (directive, " __STDC__ 1");
10250 output_line_directive (inp, outp, 0, same_file);
10251 pass_thru_directive (udirective, &udirective[strlen (directive)],
10252 outp, dp);
10253 }
10254 if (objc)
10255 {
10256 sprintf (directive, " __OBJC__ 1");
10257 output_line_directive (inp, outp, 0, same_file);
10258 pass_thru_directive (udirective, &udirective[strlen (directive)],
10259 outp, dp);
10260 }
10261 }
10262 }
10263 \f
10264 /*
10265 * process a given definition string, for initialization
10266 * If STR is just an identifier, define it with value 1.
10267 * If STR has anything after the identifier, then it should
10268 * be identifier=definition.
10269 */
10270
10271 static void
10272 make_definition (str)
10273 char *str;
10274 {
10275 FILE_BUF *ip;
10276 struct directive *kt;
10277 U_CHAR *buf, *p;
10278
10279 p = buf = (U_CHAR *) str;
10280 if (!is_idstart[*p]) {
10281 error ("malformed option `-D %s'", str);
10282 return;
10283 }
10284 while (is_idchar[*++p])
10285 ;
10286 if (*p == '(') {
10287 while (is_idchar[*++p] || *p == ',' || is_hor_space[*p])
10288 ;
10289 if (*p++ != ')')
10290 p = (U_CHAR *) str; /* Error */
10291 }
10292 if (*p == 0) {
10293 buf = (U_CHAR *) alloca (p - buf + 4);
10294 strcpy ((char *)buf, str);
10295 strcat ((char *)buf, " 1");
10296 } else if (*p != '=') {
10297 error ("malformed option `-D %s'", str);
10298 return;
10299 } else {
10300 U_CHAR *q;
10301 /* Copy the entire option so we can modify it. */
10302 buf = (U_CHAR *) alloca (2 * strlen (str) + 1);
10303 strncpy ((char *) buf, str, p - (U_CHAR *) str);
10304 /* Change the = to a space. */
10305 buf[p - (U_CHAR *) str] = ' ';
10306 /* Scan for any backslash-newline and remove it. */
10307 p++;
10308 q = &buf[p - (U_CHAR *) str];
10309 while (*p) {
10310 if (*p == '\"' || *p == '\'') {
10311 int unterminated = 0;
10312 U_CHAR *p1 = skip_quoted_string (p, p + strlen ((char *) p), 0,
10313 NULL_PTR, NULL_PTR, &unterminated);
10314 if (unterminated)
10315 return;
10316 while (p != p1) {
10317 if (*p == '\\' && p[1] == '\n')
10318 p += 2;
10319 else if (*p == '\n')
10320 {
10321 *q++ = '\\';
10322 *q++ = 'n';
10323 p++;
10324 }
10325 else
10326 *q++ = *p++;
10327 }
10328 } else if (*p == '\\' && p[1] == '\n')
10329 p += 2;
10330 /* Change newline chars into newline-markers. */
10331 else if (*p == '\n')
10332 {
10333 *q++ = '\n';
10334 *q++ = '\n';
10335 p++;
10336 }
10337 else
10338 *q++ = *p++;
10339 }
10340 *q = 0;
10341 }
10342
10343 ip = &instack[++indepth];
10344 ip->nominal_fname = ip->fname = "*Initialization*";
10345 ip->nominal_fname_len = strlen (ip->nominal_fname);
10346
10347 ip->buf = ip->bufp = buf;
10348 ip->length = strlen ((char *) buf);
10349 ip->lineno = 1;
10350 ip->macro = 0;
10351 ip->free_ptr = 0;
10352 ip->if_stack = if_stack;
10353 ip->system_header_p = 0;
10354
10355 for (kt = directive_table; kt->type != T_DEFINE; kt++)
10356 ;
10357
10358 /* Pass NULL instead of OP, since this is a "predefined" macro. */
10359 do_define (buf, buf + strlen ((char *) buf), NULL_PTR, kt);
10360 --indepth;
10361 }
10362
10363 /* JF, this does the work for the -U option */
10364
10365 static void
10366 make_undef (str, op)
10367 char *str;
10368 FILE_BUF *op;
10369 {
10370 FILE_BUF *ip;
10371 struct directive *kt;
10372
10373 ip = &instack[++indepth];
10374 ip->nominal_fname = ip->fname = "*undef*";
10375 ip->nominal_fname_len = strlen (ip->nominal_fname);
10376
10377 ip->buf = ip->bufp = (U_CHAR *) str;
10378 ip->length = strlen (str);
10379 ip->lineno = 1;
10380 ip->macro = 0;
10381 ip->free_ptr = 0;
10382 ip->if_stack = if_stack;
10383 ip->system_header_p = 0;
10384
10385 for (kt = directive_table; kt->type != T_UNDEF; kt++)
10386 ;
10387
10388 do_undef ((U_CHAR *) str, (U_CHAR *) str + strlen (str), op, kt);
10389 --indepth;
10390 }
10391 \f
10392 /* Process the string STR as if it appeared as the body of a #assert.
10393 OPTION is the option name for which STR was the argument. */
10394
10395 static void
10396 make_assertion (option, str)
10397 const char *option;
10398 const char *str;
10399 {
10400 FILE_BUF *ip;
10401 struct directive *kt;
10402 U_CHAR *buf, *p, *q;
10403
10404 /* Copy the entire option so we can modify it. */
10405 buf = (U_CHAR *) alloca (strlen (str) + 1);
10406 strcpy ((char *) buf, str);
10407 /* Scan for any backslash-newline and remove it. */
10408 p = q = buf;
10409 while (*p) {
10410 if (*p == '\\' && p[1] == '\n')
10411 p += 2;
10412 else
10413 *q++ = *p++;
10414 }
10415 *q = 0;
10416
10417 p = buf;
10418 if (!is_idstart[*p]) {
10419 error ("malformed option `%s %s'", option, str);
10420 return;
10421 }
10422 while (is_idchar[*++p])
10423 ;
10424 SKIP_WHITE_SPACE (p);
10425 if (! (*p == 0 || *p == '(')) {
10426 error ("malformed option `%s %s'", option, str);
10427 return;
10428 }
10429
10430 ip = &instack[++indepth];
10431 ip->nominal_fname = ip->fname = "*Initialization*";
10432 ip->nominal_fname_len = strlen (ip->nominal_fname);
10433
10434 ip->buf = ip->bufp = buf;
10435 ip->length = strlen ((char *) buf);
10436 ip->lineno = 1;
10437 ip->macro = 0;
10438 ip->free_ptr = 0;
10439 ip->if_stack = if_stack;
10440 ip->system_header_p = 0;
10441
10442 for (kt = directive_table; kt->type != T_ASSERT; kt++)
10443 ;
10444
10445 /* Pass NULL as output ptr to do_define since we KNOW it never does
10446 any output.... */
10447 do_assert (buf, buf + strlen ((char *) buf) , NULL_PTR, kt);
10448 --indepth;
10449 }
10450 \f
10451 /* The previous include prefix, if any, is PREV_FILE_NAME.
10452 Translate any pathnames with COMPONENT.
10453 Allocate a new include prefix whose name is the
10454 simplified concatenation of PREFIX and NAME,
10455 with a trailing / added if needed.
10456 But return 0 if the include prefix should be ignored,
10457 e.g. because it is a duplicate of PREV_FILE_NAME. */
10458
10459 static struct file_name_list *
10460 new_include_prefix (prev_file_name, component, prefix, name)
10461 struct file_name_list *prev_file_name;
10462 const char *component;
10463 const char *prefix;
10464 const char *name;
10465 {
10466 if (name == 0)
10467 fatal ("Directory name missing after command line option");
10468
10469 if (*name == 0)
10470 /* Ignore the empty string. */
10471 return 0;
10472
10473 prefix = update_path (prefix, component);
10474 name = update_path (name, component);
10475
10476 {
10477 struct file_name_list *dir
10478 = ((struct file_name_list *)
10479 xmalloc (sizeof (struct file_name_list)
10480 + strlen (prefix) + strlen (name) + 2));
10481 size_t len;
10482 strcpy (dir->fname, prefix);
10483 strcat (dir->fname, name);
10484 len = simplify_filename (dir->fname);
10485
10486 /* Convert directory name to a prefix. */
10487 if (len && dir->fname[len - 1] != DIR_SEPARATOR) {
10488 if (len == 1 && dir->fname[len - 1] == '.')
10489 len = 0;
10490 else
10491 #ifdef VMS
10492 /* must be '/', hack_vms_include_specification triggers on it. */
10493 dir->fname[len++] = '/';
10494 #else
10495 dir->fname[len++] = DIR_SEPARATOR;
10496 #endif
10497 dir->fname[len] = 0;
10498 }
10499
10500 /* Ignore a directory whose name matches the previous one. */
10501 if (prev_file_name && !strcmp (prev_file_name->fname, dir->fname)) {
10502 /* But treat `-Idir -I- -Idir' as `-I- -Idir'. */
10503 if (!first_bracket_include)
10504 first_bracket_include = prev_file_name;
10505 free (dir);
10506 return 0;
10507 }
10508
10509 #ifndef VMS
10510 /* VMS can't stat dir prefixes, so skip these optimizations in VMS. */
10511
10512 /* Add a trailing "." if there is a filename. This increases the number
10513 of systems that can stat directories. We remove it below. */
10514 if (len != 0)
10515 {
10516 dir->fname[len] = '.';
10517 dir->fname[len + 1] = 0;
10518 }
10519
10520 /* Ignore a nonexistent directory. */
10521 if (stat (len ? dir->fname : ".", &dir->st) != 0) {
10522 if (errno != ENOENT && errno != ENOTDIR)
10523 error_from_errno (dir->fname);
10524 free (dir);
10525 return 0;
10526 }
10527
10528 if (len != 0)
10529 dir->fname[len] = 0;
10530
10531 /* Ignore a directory whose identity matches the previous one. */
10532 if (prev_file_name
10533 && INO_T_EQ (prev_file_name->st.st_ino, dir->st.st_ino)
10534 && prev_file_name->st.st_dev == dir->st.st_dev) {
10535 /* But treat `-Idir -I- -Idir' as `-I- -Idir'. */
10536 if (!first_bracket_include)
10537 first_bracket_include = prev_file_name;
10538 free (dir);
10539 return 0;
10540 }
10541 #endif /* ! VMS */
10542
10543 dir->next = 0;
10544 dir->c_system_include_path = 0;
10545 dir->got_name_map = 0;
10546
10547 return dir;
10548 }
10549 }
10550
10551 /* Append a chain of `struct file_name_list's
10552 to the end of the main include chain.
10553 FIRST is the beginning of the chain to append, and LAST is the end. */
10554
10555 static void
10556 append_include_chain (first, last)
10557 struct file_name_list *first, *last;
10558 {
10559 struct file_name_list *dir;
10560
10561 if (!first || !last)
10562 return;
10563
10564 if (include == 0)
10565 include = first;
10566 else
10567 last_include->next = first;
10568
10569 if (first_bracket_include == 0)
10570 first_bracket_include = first;
10571
10572 for (dir = first; ; dir = dir->next) {
10573 int len = strlen (dir->fname) + INCLUDE_LEN_FUDGE;
10574 if (len > max_include_len)
10575 max_include_len = len;
10576 if (dir == last)
10577 break;
10578 }
10579
10580 last->next = NULL;
10581 last_include = last;
10582 }
10583 \f
10584 /* Place into DST a representation of the file named SRC that is suitable
10585 for `make'. Do not null-terminate DST. Return its length. */
10586 static int
10587 quote_string_for_make (dst, src)
10588 char *dst;
10589 const char *src;
10590 {
10591 const char *p = src;
10592 int i = 0;
10593 for (;;)
10594 {
10595 char c = *p++;
10596 switch (c)
10597 {
10598 case '\0':
10599 case ' ':
10600 case '\t':
10601 {
10602 /* GNU make uses a weird quoting scheme for white space.
10603 A space or tab preceded by 2N+1 backslashes represents
10604 N backslashes followed by space; a space or tab
10605 preceded by 2N backslashes represents N backslashes at
10606 the end of a file name; and backslashes in other
10607 contexts should not be doubled. */
10608 const char *q;
10609 for (q = p - 1; src < q && q[-1] == '\\'; q--)
10610 {
10611 if (dst)
10612 dst[i] = '\\';
10613 i++;
10614 }
10615 }
10616 if (!c)
10617 return i;
10618 if (dst)
10619 dst[i] = '\\';
10620 i++;
10621 goto ordinary_char;
10622
10623 case '$':
10624 if (dst)
10625 dst[i] = c;
10626 i++;
10627 /* Fall through. This can mishandle things like "$(" but
10628 there's no easy fix. */
10629 default:
10630 ordinary_char:
10631 /* This can mishandle characters in the string "\0\n%*?[\\~";
10632 exactly which chars are mishandled depends on the `make' version.
10633 We know of no portable solution for this;
10634 even GNU make 3.76.1 doesn't solve the problem entirely.
10635 (Also, '\0' is mishandled due to our calling conventions.) */
10636 if (dst)
10637 dst[i] = c;
10638 i++;
10639 break;
10640 }
10641 }
10642 }
10643
10644
10645 /* Add output to `deps_buffer' for the -M switch.
10646 STRING points to the text to be output.
10647 SPACER is ':' for targets, ' ' for dependencies. */
10648
10649 static void
10650 deps_output (string, spacer)
10651 const char *string;
10652 int spacer;
10653 {
10654 int size = quote_string_for_make ((char *) 0, string);
10655
10656 if (size == 0)
10657 return;
10658
10659 #ifndef MAX_OUTPUT_COLUMNS
10660 #define MAX_OUTPUT_COLUMNS 72
10661 #endif
10662 if (MAX_OUTPUT_COLUMNS - 1 /*spacer*/ - 2 /*` \'*/ < deps_column + size
10663 && 1 < deps_column) {
10664 bcopy (" \\\n ", &deps_buffer[deps_size], 4);
10665 deps_size += 4;
10666 deps_column = 1;
10667 if (spacer == ' ')
10668 spacer = 0;
10669 }
10670
10671 if (deps_size + 2 * size + 8 > deps_allocated_size) {
10672 deps_allocated_size = (deps_size + 2 * size + 50) * 2;
10673 deps_buffer = xrealloc (deps_buffer, deps_allocated_size);
10674 }
10675 if (spacer == ' ') {
10676 deps_buffer[deps_size++] = ' ';
10677 deps_column++;
10678 }
10679 quote_string_for_make (&deps_buffer[deps_size], string);
10680 deps_size += size;
10681 deps_column += size;
10682 if (spacer == ':') {
10683 deps_buffer[deps_size++] = ':';
10684 deps_column++;
10685 }
10686 deps_buffer[deps_size] = 0;
10687 }
10688 \f
10689 void
10690 fatal VPROTO ((const char * msgid, ...))
10691 {
10692 #ifndef ANSI_PROTOTYPES
10693 const char * msgid;
10694 #endif
10695 va_list args;
10696
10697 fprintf (stderr, "%s: ", progname);
10698 VA_START (args, msgid);
10699
10700 #ifndef ANSI_PROTOTYPES
10701 msgid = va_arg (args, const char *);
10702 #endif
10703 vnotice (msgid, args);
10704 va_end (args);
10705 fprintf (stderr, "\n");
10706 exit (FATAL_EXIT_CODE);
10707 }
10708
10709 /* More 'friendly' abort that prints the line and file.
10710 config.h can #define abort fancy_abort if you like that sort of thing. */
10711
10712 void
10713 fancy_abort ()
10714 {
10715 fatal ("Internal gcc abort.");
10716 }
10717
10718 static void
10719 perror_with_name (name)
10720 char *name;
10721 {
10722 fprintf (stderr, "%s: %s: %s\n", progname, name, xstrerror (errno));
10723 errors++;
10724 }
10725
10726 static void
10727 pfatal_with_name (name)
10728 char *name;
10729 {
10730 perror_with_name (name);
10731 #ifdef VMS
10732 exit (vaxc$errno);
10733 #else
10734 exit (FATAL_EXIT_CODE);
10735 #endif
10736 }
10737
10738 /* Handler for SIGPIPE. */
10739
10740 static void
10741 pipe_closed (signo)
10742 /* If this is missing, some compilers complain. */
10743 int signo ATTRIBUTE_UNUSED;
10744 {
10745 fatal ("output pipe has been closed");
10746 }
10747 \f
10748 static void
10749 memory_full ()
10750 {
10751 fatal ("Memory exhausted.");
10752 }
10753 \f
10754 #ifdef VMS
10755
10756 /* Under VMS we need to fix up the "include" specification filename.
10757
10758 Rules for possible conversions
10759
10760 fullname tried paths
10761
10762 name name
10763 ./dir/name [.dir]name
10764 /dir/name dir:name
10765 /name [000000]name, name
10766 dir/name dir:[000000]name, dir:name, dir/name
10767 dir1/dir2/name dir1:[dir2]name, dir1:[000000.dir2]name
10768 path:/name path:[000000]name, path:name
10769 path:/dir/name path:[000000.dir]name, path:[dir]name
10770 path:dir/name path:[dir]name
10771 [path]:[dir]name [path.dir]name
10772 path/[dir]name [path.dir]name
10773
10774 The path:/name input is constructed when expanding <> includes.
10775
10776 return 1 if name was changed, 0 else. */
10777
10778 static int
10779 hack_vms_include_specification (fullname, vaxc_include)
10780 char *fullname;
10781 int vaxc_include;
10782 {
10783 register char *basename, *unixname, *local_ptr, *first_slash;
10784 int f, check_filename_before_returning, must_revert;
10785 char Local[512];
10786
10787 check_filename_before_returning = 0;
10788 must_revert = 0;
10789 /* See if we can find a 1st slash. If not, there's no path information. */
10790 first_slash = index (fullname, '/');
10791 if (first_slash == 0)
10792 return 0; /* Nothing to do!!! */
10793
10794 /* construct device spec if none given. */
10795
10796 if (index (fullname, ':') == 0)
10797 {
10798
10799 /* If fullname has a slash, take it as device spec. */
10800
10801 if (first_slash == fullname)
10802 {
10803 first_slash = index (fullname+1, '/'); /* 2nd slash ? */
10804 if (first_slash)
10805 *first_slash = ':'; /* make device spec */
10806 for (basename = fullname; *basename != 0; basename++)
10807 *basename = *(basename+1); /* remove leading slash */
10808 }
10809 else if ((first_slash[-1] != '.') /* keep ':/', './' */
10810 && (first_slash[-1] != ':')
10811 && (first_slash[-1] != ']')) /* or a vms path */
10812 {
10813 *first_slash = ':';
10814 }
10815 else if ((first_slash[1] == '[') /* skip './' in './[dir' */
10816 && (first_slash[-1] == '.'))
10817 fullname += 2;
10818 }
10819
10820 /* Get part after first ':' (basename[-1] == ':')
10821 or last '/' (basename[-1] == '/'). */
10822
10823 basename = base_name (fullname);
10824
10825 /*
10826 * Check if we have a vax-c style '#include filename'
10827 * and add the missing .h
10828 */
10829
10830 if (vaxc_include && !index (basename,'.'))
10831 strcat (basename, ".h");
10832
10833 local_ptr = Local; /* initialize */
10834
10835 /* We are trying to do a number of things here. First of all, we are
10836 trying to hammer the filenames into a standard format, such that later
10837 processing can handle them.
10838
10839 If the file name contains something like [dir.], then it recognizes this
10840 as a root, and strips the ".]". Later processing will add whatever is
10841 needed to get things working properly.
10842
10843 If no device is specified, then the first directory name is taken to be
10844 a device name (or a rooted logical). */
10845
10846 /* Point to the UNIX filename part (which needs to be fixed!)
10847 but skip vms path information.
10848 [basename != fullname since first_slash != 0]. */
10849
10850 if ((basename[-1] == ':') /* vms path spec. */
10851 || (basename[-1] == ']')
10852 || (basename[-1] == '>'))
10853 unixname = basename;
10854 else
10855 unixname = fullname;
10856
10857 if (*unixname == '/')
10858 unixname++;
10859
10860 /* If the directory spec is not rooted, we can just copy
10861 the UNIX filename part and we are done. */
10862
10863 if (((basename - fullname) > 1)
10864 && ( (basename[-1] == ']')
10865 || (basename[-1] == '>')))
10866 {
10867 if (basename[-2] != '.')
10868 {
10869
10870 /* The VMS part ends in a `]', and the preceding character is not a `.'.
10871 -> PATH]:/name (basename = '/name', unixname = 'name')
10872 We strip the `]', and then splice the two parts of the name in the
10873 usual way. Given the default locations for include files in cccp.c,
10874 we will only use this code if the user specifies alternate locations
10875 with the /include (-I) switch on the command line. */
10876
10877 basename -= 1; /* Strip "]" */
10878 unixname--; /* backspace */
10879 }
10880 else
10881 {
10882
10883 /* The VMS part has a ".]" at the end, and this will not do. Later
10884 processing will add a second directory spec, and this would be a syntax
10885 error. Thus we strip the ".]", and thus merge the directory specs.
10886 We also backspace unixname, so that it points to a '/'. This inhibits the
10887 generation of the 000000 root directory spec (which does not belong here
10888 in this case). */
10889
10890 basename -= 2; /* Strip ".]" */
10891 unixname--; /* backspace */
10892 }
10893 }
10894
10895 else
10896
10897 {
10898
10899 /* We drop in here if there is no VMS style directory specification yet.
10900 If there is no device specification either, we make the first dir a
10901 device and try that. If we do not do this, then we will be essentially
10902 searching the users default directory (as if they did a #include "asdf.h").
10903
10904 Then all we need to do is to push a '[' into the output string. Later
10905 processing will fill this in, and close the bracket. */
10906
10907 if ((unixname != fullname) /* vms path spec found. */
10908 && (basename[-1] != ':'))
10909 *local_ptr++ = ':'; /* dev not in spec. take first dir */
10910
10911 *local_ptr++ = '['; /* Open the directory specification */
10912 }
10913
10914 if (unixname == fullname) /* no vms dir spec. */
10915 {
10916 must_revert = 1;
10917 if ((first_slash != 0) /* unix dir spec. */
10918 && (*unixname != '/') /* not beginning with '/' */
10919 && (*unixname != '.')) /* or './' or '../' */
10920 *local_ptr++ = '.'; /* dir is local ! */
10921 }
10922
10923 /* at this point we assume that we have the device spec, and (at least
10924 the opening "[" for a directory specification. We may have directories
10925 specified already.
10926
10927 If there are no other slashes then the filename will be
10928 in the "root" directory. Otherwise, we need to add
10929 directory specifications. */
10930
10931 if (index (unixname, '/') == 0)
10932 {
10933 /* if no directories specified yet and none are following. */
10934 if (local_ptr[-1] == '[')
10935 {
10936 /* Just add "000000]" as the directory string */
10937 strcpy (local_ptr, "000000]");
10938 local_ptr += strlen (local_ptr);
10939 check_filename_before_returning = 1; /* we might need to fool with this later */
10940 }
10941 }
10942 else
10943 {
10944
10945 /* As long as there are still subdirectories to add, do them. */
10946 while (index (unixname, '/') != 0)
10947 {
10948 /* If this token is "." we can ignore it
10949 if it's not at the beginning of a path. */
10950 if ((unixname[0] == '.') && (unixname[1] == '/'))
10951 {
10952 /* remove it at beginning of path. */
10953 if ( ((unixname == fullname) /* no device spec */
10954 && (fullname+2 != basename)) /* starts with ./ */
10955 /* or */
10956 || ((basename[-1] == ':') /* device spec */
10957 && (unixname-1 == basename))) /* and ./ afterwards */
10958 *local_ptr++ = '.'; /* make '[.' start of path. */
10959 unixname += 2;
10960 continue;
10961 }
10962
10963 /* Add a subdirectory spec. Do not duplicate "." */
10964 if ( local_ptr[-1] != '.'
10965 && local_ptr[-1] != '['
10966 && local_ptr[-1] != '<')
10967 *local_ptr++ = '.';
10968
10969 /* If this is ".." then the spec becomes "-" */
10970 if ( (unixname[0] == '.')
10971 && (unixname[1] == '.')
10972 && (unixname[2] == '/'))
10973 {
10974 /* Add "-" and skip the ".." */
10975 if ((local_ptr[-1] == '.')
10976 && (local_ptr[-2] == '['))
10977 local_ptr--; /* prevent [.- */
10978 *local_ptr++ = '-';
10979 unixname += 3;
10980 continue;
10981 }
10982
10983 /* Copy the subdirectory */
10984 while (*unixname != '/')
10985 *local_ptr++= *unixname++;
10986
10987 unixname++; /* Skip the "/" */
10988 }
10989
10990 /* Close the directory specification */
10991 if (local_ptr[-1] == '.') /* no trailing periods */
10992 local_ptr--;
10993
10994 if (local_ptr[-1] == '[') /* no dir needed */
10995 local_ptr--;
10996 else
10997 *local_ptr++ = ']';
10998 }
10999
11000 /* Now add the filename. */
11001
11002 while (*unixname)
11003 *local_ptr++ = *unixname++;
11004 *local_ptr = 0;
11005
11006 /* Now append it to the original VMS spec. */
11007
11008 strcpy ((must_revert==1)?fullname:basename, Local);
11009
11010 /* If we put a [000000] in the filename, try to open it first. If this fails,
11011 remove the [000000], and return that name. This provides flexibility
11012 to the user in that they can use both rooted and non-rooted logical names
11013 to point to the location of the file. */
11014
11015 if (check_filename_before_returning)
11016 {
11017 f = open (fullname, O_RDONLY, 0666);
11018 if (f >= 0)
11019 {
11020 /* The file name is OK as it is, so return it as is. */
11021 close (f);
11022 return 1;
11023 }
11024
11025 /* The filename did not work. Try to remove the [000000] from the name,
11026 and return it. */
11027
11028 basename = index (fullname, '[');
11029 local_ptr = index (fullname, ']') + 1;
11030 strcpy (basename, local_ptr); /* this gets rid of it */
11031
11032 }
11033
11034 return 1;
11035 }
11036 #endif /* VMS */
11037 \f
11038 #ifdef VMS
11039
11040 /* The following wrapper functions supply additional arguments to the VMS
11041 I/O routines to optimize performance with file handling. The arguments
11042 are:
11043 "mbc=16" - Set multi-block count to 16 (use a 8192 byte buffer).
11044 "deq=64" - When extending the file, extend it in chunks of 32Kbytes.
11045 "fop=tef"- Truncate unused portions of file when closing file.
11046 "shr=nil"- Disallow file sharing while file is open. */
11047
11048 static FILE *
11049 VMS_freopen (fname, type, oldfile)
11050 char *fname;
11051 char *type;
11052 FILE *oldfile;
11053 {
11054 #undef freopen /* Get back the real freopen routine. */
11055 if (strcmp (type, "w") == 0)
11056 return freopen (fname, type, oldfile,
11057 "mbc=16", "deq=64", "fop=tef", "shr=nil");
11058 return freopen (fname, type, oldfile, "mbc=16");
11059 }
11060
11061 static FILE *
11062 VMS_fopen (fname, type)
11063 char *fname;
11064 char *type;
11065 {
11066 #undef fopen /* Get back the real fopen routine. */
11067 /* The gcc-vms-1.42 distribution's header files prototype fopen with two
11068 fixed arguments, which matches ANSI's specification but not VAXCRTL's
11069 pre-ANSI implementation. This hack circumvents the mismatch problem. */
11070 FILE *(*vmslib_fopen)() = (FILE *(*)()) fopen;
11071
11072 if (*type == 'w')
11073 return (*vmslib_fopen) (fname, type, "mbc=32",
11074 "deq=64", "fop=tef", "shr=nil");
11075 else
11076 return (*vmslib_fopen) (fname, type, "mbc=32");
11077 }
11078
11079 static int
11080 VMS_open (fname, flags, prot)
11081 char *fname;
11082 int flags;
11083 int prot;
11084 {
11085 #undef open /* Get back the real open routine. */
11086 return open (fname, flags, prot, "mbc=16", "deq=64", "fop=tef");
11087 }
11088 \f
11089 /* more VMS hackery */
11090 #include <fab.h>
11091 #include <nam.h>
11092
11093 extern unsigned long SYS$PARSE(), SYS$SEARCH();
11094
11095 /* Work around another library bug. If a file is located via a searchlist,
11096 and if the device it's on is not the same device as the one specified
11097 in the first element of that searchlist, then both stat() and fstat()
11098 will fail to return info about it. `errno' will be set to EVMSERR, and
11099 `vaxc$errno' will be set to SS$_NORMAL due yet another bug in stat()!
11100 We can get around this by fully parsing the filename and then passing
11101 that absolute name to stat().
11102
11103 Without this fix, we can end up failing to find header files, which is
11104 bad enough, but then compounding the problem by reporting the reason for
11105 failure as "normal successful completion." */
11106
11107 #undef fstat /* Get back to the library version. */
11108
11109 static int
11110 VMS_fstat (fd, statbuf)
11111 int fd;
11112 struct stat *statbuf;
11113 {
11114 int result = fstat (fd, statbuf);
11115
11116 if (result < 0)
11117 {
11118 FILE *fp;
11119 char nambuf[NAM$C_MAXRSS+1];
11120
11121 if ((fp = fdopen (fd, "r")) != 0 && fgetname (fp, nambuf) != 0)
11122 result = VMS_stat (nambuf, statbuf);
11123 /* No fclose(fp) here; that would close(fd) as well. */
11124 }
11125
11126 return result;
11127 }
11128
11129 static int
11130 VMS_stat (name, statbuf)
11131 const char *name;
11132 struct stat *statbuf;
11133 {
11134 int result = stat (name, statbuf);
11135
11136 if (result < 0)
11137 {
11138 struct FAB fab;
11139 struct NAM nam;
11140 char exp_nam[NAM$C_MAXRSS+1], /* expanded name buffer for SYS$PARSE */
11141 res_nam[NAM$C_MAXRSS+1]; /* resultant name buffer for SYS$SEARCH */
11142
11143 fab = cc$rms_fab;
11144 fab.fab$l_fna = (char *) name;
11145 fab.fab$b_fns = (unsigned char) strlen (name);
11146 fab.fab$l_nam = (void *) &nam;
11147 nam = cc$rms_nam;
11148 nam.nam$l_esa = exp_nam, nam.nam$b_ess = sizeof exp_nam - 1;
11149 nam.nam$l_rsa = res_nam, nam.nam$b_rss = sizeof res_nam - 1;
11150 nam.nam$b_nop = NAM$M_PWD | NAM$M_NOCONCEAL;
11151 if (SYS$PARSE (&fab) & 1)
11152 {
11153 if (SYS$SEARCH (&fab) & 1)
11154 {
11155 res_nam[nam.nam$b_rsl] = '\0';
11156 result = stat (res_nam, statbuf);
11157 }
11158 /* Clean up searchlist context cached by the system. */
11159 nam.nam$b_nop = NAM$M_SYNCHK;
11160 fab.fab$l_fna = 0, fab.fab$b_fns = 0;
11161 (void) SYS$PARSE (&fab);
11162 }
11163 }
11164
11165 return result;
11166 }
11167
11168 static size_t
11169 VMS_fwrite (ptr, size, nitems, stream)
11170 void const *ptr;
11171 size_t size;
11172 size_t nitems;
11173 FILE *stream;
11174 {
11175 /* VMS fwrite has undesirable results
11176 if STREAM happens to be a record oriented file.
11177 Work around this problem by writing each character individually. */
11178 char const *p = ptr;
11179 size_t bytes = size * nitems;
11180 char *lim = p + bytes;
11181
11182 while (p < lim)
11183 if (putc (*p++, stream) == EOF)
11184 return 0;
11185
11186 return bytes;
11187 }
11188 #endif /* VMS */