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