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