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