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