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