chiark / gitweb /
Imported Upstream version 1.0.0
[e16] / epp / cpplib.c
1 /* CPP Library.
2  * Copyright (C) 1986, 87, 89, 92, 93, 94, 1995 Free Software Foundation, Inc.
3  * Written by Per Bothner, 1994-95.
4  * Based on CCCP program by by Paul Rubin, June 1986
5  * Adapted to ANSI C, Richard Stallman, Jan 1987
6  * 
7  * This program is free software; you can redistribute it and/or modify it
8  * under the terms of the GNU General Public License as published by the
9  * Free Software Foundation; either version 2, or (at your option) any
10  * later version.
11  * 
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
20  * 
21  * In other words, you are welcome to use, share and improve this program.
22  * You are forbidden to forbid anyone else to use, share and improve
23  * what you give them.   Help stamp out software-hoarding!  */
24
25 const char         *version_string = "0.0.0";
26
27 #include "config.h"
28
29 #ifdef __EMX__
30 #include <strings.h>
31 #endif
32
33 #ifndef STANDARD_INCLUDE_DIR
34 #define STANDARD_INCLUDE_DIR "/usr/include"
35 #endif
36
37 #ifndef LOCAL_INCLUDE_DIR
38 #define LOCAL_INCLUDE_DIR "/usr/local/include"
39 #endif
40
41 #include "cpplib.h"
42 #include "cpphash.h"
43
44 #ifndef STDC_VALUE
45 #define STDC_VALUE 1
46 #endif
47
48 /* By default, colon separates directories in a path.  */
49 #ifndef PATH_SEPARATOR
50 #define PATH_SEPARATOR ':'
51 #endif
52
53 #include <ctype.h>
54 #include <stdio.h>
55 #include <string.h>
56 #include <signal.h>
57 #ifdef __STDC__
58 #include <stdlib.h>
59 #endif
60 #ifdef HAVE_ALLOCA_H
61 #include <alloca.h>
62 #endif
63 #include <unistd.h>
64 #include <sys/types.h>
65 #include <sys/stat.h>
66 #include <fcntl.h>
67 #include <stdlib.h>
68
69 #ifndef VMS
70 #ifndef USG
71 #include <time.h>
72 #include <sys/time.h>           /* for __DATE__ and __TIME__ */
73 #include <sys/resource.h>
74 #else
75 #include <sys/param.h>          /* CYGNUS LOCAL: shebs -noquiet */
76 #include <sys/times.h>
77 #include <time.h>
78 #include <fcntl.h>
79 #endif /* USG */
80 #endif /* not VMS */
81
82 /* This defines "errno" properly for VMS, and gives us EACCES. */
83 #include <errno.h>
84
85 #ifndef O_RDONLY
86 #define O_RDONLY 0
87 #endif
88
89 #undef MIN
90 #undef MAX
91 #define MIN(X,Y) ((X) < (Y) ? (X) : (Y))
92 #define MAX(X,Y) ((X) > (Y) ? (X) : (Y))
93
94 #ifndef S_ISREG
95 #define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
96 #endif
97
98 #ifndef S_ISDIR
99 #define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
100 #endif
101
102 /* Define a generic NULL if one hasn't already been defined.  */
103
104 #ifndef GENERIC_PTR
105 #if defined (USE_PROTOTYPES) ? USE_PROTOTYPES : defined (__STDC__)
106 #define GENERIC_PTR void *
107 #else
108 #define GENERIC_PTR char *
109 #endif
110 #endif
111
112 #ifndef INCLUDE_LEN_FUDGE
113 #define INCLUDE_LEN_FUDGE 0
114 #endif
115
116 #define USE_FILE_NAME_MAPS 0
117
118 /* Symbols to predefine.  */
119
120 #ifdef CPP_PREDEFINES
121 static const char  *predefs = CPP_PREDEFINES;
122
123 #else
124 static const char  *predefs = "";
125
126 #endif
127
128 /* We let tm.h override the types used here, to handle trivial differences
129  * such as the choice of unsigned int or long unsigned int for size_t.
130  * When machines start needing nontrivial differences in the size type,
131  * it would be best to do something here to figure out automatically
132  * from other information what type to use.  */
133
134 /* The string value for __SIZE_TYPE__.  */
135
136 #ifndef SIZE_TYPE
137 #define SIZE_TYPE "long unsigned int"
138 #endif
139
140 /* The string value for __PTRDIFF_TYPE__.  */
141
142 #ifndef PTRDIFF_TYPE
143 #define PTRDIFF_TYPE "long int"
144 #endif
145
146 /* The string value for __WCHAR_TYPE__.  */
147
148 #ifndef WCHAR_TYPE
149 #define WCHAR_TYPE "int"
150 #endif
151 #define CPP_WCHAR_TYPE(PFILE) \
152         (CPP_OPTIONS (PFILE)->cplusplus ? "__wchar_t" : WCHAR_TYPE)
153
154 /* The string value for __USER_LABEL_PREFIX__ */
155
156 #ifndef USER_LABEL_PREFIX
157 #define USER_LABEL_PREFIX ""
158 #endif
159
160 /* The string value for __REGISTER_PREFIX__ */
161
162 #ifndef REGISTER_PREFIX
163 #define REGISTER_PREFIX ""
164 #endif
165
166 struct directive {
167    int                 length;
168    int                 (*func) (cpp_reader * pfile, struct directive * keyword,
169                                 unsigned char *buf, unsigned char *limit);
170    const char         *name;
171    enum node_type      type;
172    char                command_reads_line;
173    char                traditional_comments;
174    char                pass_thru;
175 };
176
177 /* In the definition of a #assert name, this structure forms
178  * a list of the individual values asserted.
179  * Each value is itself a list of "tokens".
180  * These are strings that are compared by name.  */
181
182 struct tokenlist_list {
183    struct tokenlist_list *next;
184    struct arglist     *tokens;
185 };
186
187 struct assertion_hashnode {
188    struct assertion_hashnode *next;     /* double links for easy deletion */
189    struct assertion_hashnode *prev;
190    /* also, a back pointer to this node's hash
191     * chain is kept, in case the node is the head
192     * of the chain and gets deleted. */
193    struct assertion_hashnode **bucket_hdr;
194    int                 length;  /* length of token, for quick comparison */
195    char               *name;    /* the actual name */
196    /* List of token-sequences.  */
197    struct tokenlist_list *value;
198 };
199
200 #define SKIP_WHITE_SPACE(p) do { while (is_hor_space[(unsigned char)(*p)]) p++; } while (0)
201 #define SKIP_ALL_WHITE_SPACE(p) do { while (is_space[(unsigned char)(*p)]) p++; } while (0)
202
203 #define PEEKN(N) (CPP_BUFFER (pfile)->rlimit - CPP_BUFFER (pfile)->cur >= (N) ? CPP_BUFFER (pfile)->cur[N] : EOF)
204 #define FORWARD(N) CPP_FORWARD (CPP_BUFFER (pfile), (N))
205 #define GETC() CPP_BUF_GET (CPP_BUFFER (pfile))
206 #define PEEKC() CPP_BUF_PEEK (CPP_BUFFER (pfile))
207 /* CPP_IS_MACRO_BUFFER is true if the buffer contains macro expansion.
208  * (Note that it is false while we're expanding marco *arguments*.) */
209 #define CPP_IS_MACRO_BUFFER(PBUF) ((PBUF)->cleanup == macro_cleanup)
210
211 /* Move all backslash-newline pairs out of embarrassing places.
212  * Exchange all such pairs following BP
213  * with any potentially-embarrassing characters that follow them.
214  * Potentially-embarrassing characters are / and *
215  * (because a backslash-newline inside a comment delimiter
216  * would cause it not to be recognized).  */
217
218 #define NEWLINE_FIX \
219   do {while (PEEKC() == '\\' && PEEKN(1) == '\n') FORWARD(2); } while(0)
220
221 /* Same, but assume we've already read the potential '\\' into C. */
222 #define NEWLINE_FIX1(C) do { \
223     while ((C) == '\\' && PEEKC() == '\n') { FORWARD(1); (C) = GETC(); }\
224   } while(0)
225
226 /* Name under which this program was invoked.  */
227
228 char               *progname;
229
230 struct cpp_pending {
231    struct cpp_pending *next;
232    const char         *cmd;
233    const char         *arg;
234 };
235
236 /* Structure returned by create_definition */
237 typedef struct {
238    struct definition  *defn;
239    char               *symnam;
240    int                 symlen;
241 } MACRODEF;
242
243 /* Forward declarations.  */
244
245 static void         add_import(cpp_reader * pfile, int fd, char *fname);
246 static int          finclude(cpp_reader * pfile, int f, const char *fname,
247                              int system_header_p,
248                              struct file_name_list *dirptr);
249 static void         validate_else(cpp_reader * pfile, const char *directive);
250 static int          comp_def_part(int first, unsigned char *beg1, int len1,
251                                   unsigned char *beg2, int len2, int last);
252 static int          lookup_import(cpp_reader * pfile, char *filename,
253                                   struct file_name_list *searchptr);
254 static int          redundant_include_p(cpp_reader * pfile, char *name);
255
256 static int          is_system_include(cpp_reader * pfile, char *filename);
257
258 static int          open_include_file(cpp_reader * pfile, char *filename,
259                                       struct file_name_list *searchptr);
260 static int          check_macro_name(cpp_reader * pfile, unsigned char *symname,
261                                      const char *usage);
262
263 static int          compare_token_lists(struct arglist *l1, struct arglist *l2);
264 static HOST_WIDE_INT eval_if_expression(cpp_reader * pfile, unsigned char *buf,
265                                         int length);
266
267 static int          file_size_and_mode(int fd, int *mode_pointer,
268                                        long int *size_pointer);
269 static struct arglist *read_token_list(cpp_reader * pfile, int *error_flag);
270 static void         free_token_list(struct arglist *tokens);
271 static int          safe_read(int desc, char *ptr, int len);
272 static void         push_macro_expansion(cpp_reader * pfile,
273                                          unsigned char *x,
274                                          int xbuf_len, HASHNODE * hp);
275
276 static struct cpp_pending *nreverse_pending(struct cpp_pending *list);
277 static char        *savestring(const char *input);
278
279 static void         conditional_skip(cpp_reader * pfile, int skip,
280                                      enum node_type type,
281                                      unsigned char *control_macro);
282 static void         skip_if_group(cpp_reader * pfile, int any);
283
284 static void         cpp_error_with_line(cpp_reader * pfile, int line,
285                                         int column, const char *msg);
286 static void         cpp_pedwarn_with_line(cpp_reader * pfile, int line,
287                                           int column, const char *msg);
288 static void         cpp_pedwarn_with_file_and_line(cpp_reader * pfile,
289                                                    const char *file, int line,
290                                                    const char *msg,
291                                                    const char *arg1,
292                                                    const char *arg2,
293                                                    const char *arg3);
294 static void         cpp_error_from_errno(cpp_reader * pfile, const char *name);
295
296 static cpp_buffer  *cpp_push_buffer(cpp_reader * pfile, unsigned char *buffer,
297                                     long length);
298 static cpp_buffer  *cpp_pop_buffer(cpp_reader * pfile);
299
300 /* Last arg to output_line_command.  */
301 enum file_change_code {
302    same_file, enter_file, leave_file
303 };
304
305 /* These functions are declared to return int instead of void since they
306  * are going to be placed in a table and some old compilers have trouble with
307  * pointers to functions returning void.  */
308
309 static int          do_define(cpp_reader * pfile, struct directive *keyword,
310                               unsigned char *buf, unsigned char *limit);
311
312 static int          do_line(cpp_reader * pfile, struct directive *keyword,
313                             unsigned char *unused1, unsigned char *unused2);
314
315 static int          do_include(cpp_reader * pfile, struct directive *keyword,
316                                unsigned char *unused1, unsigned char *unused2);
317
318 static int          do_undef(cpp_reader * pfile, struct directive *keyword,
319                              unsigned char *buf, unsigned char *limit);
320
321 static int          do_error(cpp_reader * pfile, struct directive *keyword,
322                              unsigned char *buf, unsigned char *limit);
323
324 static int          do_pragma(cpp_reader * pfile, struct directive *keyword,
325                               unsigned char *buf, unsigned char *limit);
326
327 static int          do_ident(cpp_reader * pfile, struct directive *keyword,
328                              unsigned char *buf, unsigned char *limit);
329
330 static int          do_if(cpp_reader * pfile, struct directive *keyword,
331                           unsigned char *buf, unsigned char *limit);
332
333 static int          do_xifdef(cpp_reader * pfile, struct directive *keyword,
334                               unsigned char *buf, unsigned char *limit);
335
336 static int          do_else(cpp_reader * pfile, struct directive *keyword,
337                             unsigned char *buf, unsigned char *limit);
338
339 static int          do_elif(cpp_reader * pfile, struct directive *keyword,
340                             unsigned char *buf, unsigned char *limit);
341
342 static int          do_endif(cpp_reader * pfile, struct directive *keyword,
343                              unsigned char *buf, unsigned char *limit);
344
345 static int          do_assert(cpp_reader * pfile, struct directive *keyword,
346                               unsigned char *buf, unsigned char *limit);
347
348 static int          do_unassert(cpp_reader * pfile, struct directive *keyword,
349                                 unsigned char *buf, unsigned char *limit);
350
351 static int          do_warning(cpp_reader * pfile, struct directive *keyword,
352                                unsigned char *buf, unsigned char *limit);
353
354 struct arglist     *reverse_token_list(struct arglist *tokens);
355
356 static int          parse_name(cpp_reader * pfile, int c);
357
358 static void         parse_set_mark(struct parse_marker *pmark,
359                                    cpp_reader * pfile);
360 static void         parse_clear_mark(struct parse_marker *pmark);
361 static void         parse_goto_mark(struct parse_marker *pmark,
362                                     cpp_reader * pfile);
363 static void         parse_move_mark(struct parse_marker *pmark,
364                                     cpp_reader * pfile);
365
366 struct file_name_list {
367    struct file_name_list *next;
368    char               *fname;
369    /* If the following is nonzero, it is a macro name.
370     * Don't include the file again if that macro is defined.  */
371    unsigned char      *control_macro;
372    /* If the following is nonzero, it is a C-language system include
373     * directory.  */
374    int                 c_system_include_path;
375    /* Mapping of file names for this directory.  */
376    struct file_name_map *name_map;
377    /* Non-zero if name_map is valid.  */
378    int                 got_name_map;
379 };
380
381 /* If a buffer's dir field is SELF_DIR_DUMMY, it means the file was found
382  * via the same directory as the file that #included it. */
383 #define SELF_DIR_DUMMY ((struct file_name_list*)(~0))
384
385 /* #include "file" looks in source file dir, then stack. */
386 /* #include <file> just looks in the stack. */
387 /* -I directories are added to the end, then the defaults are added. */
388 /* The */
389 static struct default_include {
390    const char         *fname;   /* The name of the directory.  */
391    int                 cplusplus;       /* Only look here if we're compiling C++.  */
392    int                 cxx_aware;       /* Includes in this directory don't need to
393                                          * be wrapped in extern "C" when compiling
394                                          * C++.  */
395 } include_defaults_array[]
396 #ifdef INCLUDE_DEFAULTS
397    = INCLUDE_DEFAULTS;
398
399 #else
400    =
401 {
402    /* Pick up GNU C++ specific include files.  */
403    {
404    GPLUSPLUS_INCLUDE_DIR, 1, 1}
405    ,
406 #ifdef CROSS_COMPILE
407       /* This is the dir for fixincludes.  Put it just before
408        * the files that we fix.  */
409    {
410    GCC_INCLUDE_DIR, 0, 0}
411    ,
412       /* For cross-compilation, this dir name is generated
413        * automatically in Makefile.in.  */
414    {
415    CROSS_INCLUDE_DIR, 0, 0}
416    ,
417       /* This is another place that the target system's headers might be.  */
418    {
419    TOOL_INCLUDE_DIR, 0, 1}
420    ,
421 #else /* not CROSS_COMPILE */
422       /* This should be /usr/local/include and should come before
423        * the fixincludes-fixed header files.  */
424    {
425    LOCAL_INCLUDE_DIR, 0, 1}
426    ,
427       /* This is here ahead of GCC_INCLUDE_DIR because assert.h goes here.
428        * Likewise, behind LOCAL_INCLUDE_DIR, where glibc puts its assert.h.  */
429    {
430    TOOL_INCLUDE_DIR, 0, 1}
431    ,
432       /* This is the dir for fixincludes.  Put it just before
433        * the files that we fix.  */
434    {
435    GCC_INCLUDE_DIR, 0, 0}
436    ,
437       /* Some systems have an extra dir of include files.  */
438 #ifdef SYSTEM_INCLUDE_DIR
439    {
440    SYSTEM_INCLUDE_DIR, 0, 0}
441    ,
442 #endif
443    {
444    STANDARD_INCLUDE_DIR, 0, 0}
445    ,
446 #endif /* not CROSS_COMPILE */
447    {
448    0, 0, 0}
449 };
450
451 #endif /* no INCLUDE_DEFAULTS */
452
453 /* Here is the actual list of #-directives, most-often-used first.
454  * The initialize_builtins function assumes #define is the very first.  */
455
456 static struct directive directive_table[] = {
457    {6, do_define, "define", T_DEFINE, 0, 1, 0},
458    {5, do_xifdef, "ifdef", T_IFDEF, 1, 0, 0},
459    {6, do_xifdef, "ifndef", T_IFNDEF, 1, 0, 0},
460    {7, do_include, "include", T_INCLUDE, 1, 0, 0},
461    {12, do_include, "include_next", T_INCLUDE_NEXT, 1, 0, 0},
462    {6, do_include, "import", T_IMPORT, 1, 0, 0},
463    {5, do_endif, "endif", T_ENDIF, 1, 0, 0},
464    {4, do_else, "else", T_ELSE, 1, 0, 0},
465    {2, do_if, "if", T_IF, 1, 0, 0},
466    {4, do_elif, "elif", T_ELIF, 1, 0, 0},
467    {5, do_undef, "undef", T_UNDEF, 0, 0, 0},
468    {5, do_error, "error", T_ERROR, 0, 0, 0},
469    {7, do_warning, "warning", T_WARNING, 0, 0, 0},
470    {6, do_pragma, "pragma", T_PRAGMA, 0, 0, 1},
471    {4, do_line, "line", T_LINE, 1, 0, 0},
472    {5, do_ident, "ident", T_IDENT, 1, 0, 1},
473 #ifdef SCCS_DIRECTIVE
474    {4, do_sccs, "sccs", T_SCCS, 0, 0, 0},
475 #endif
476    {6, do_assert, "assert", T_ASSERT, 1, 0, 0},
477    {8, do_unassert, "unassert", T_UNASSERT, 1, 0, 0},
478    {-1, 0, "", T_UNUSED, 0, 0, 0},
479 };
480
481 /* table to tell if char can be part of a C identifier. */
482 unsigned char       is_idchar[256];
483
484 /* table to tell if char can be first char of a c identifier. */
485 unsigned char       is_idstart[256];
486
487 /* table to tell if c is horizontal space.  */
488 unsigned char       is_hor_space[256];
489
490 /* table to tell if c is horizontal or vertical space.  */
491 static unsigned char is_space[256];
492
493 /* Initialize syntactic classifications of characters.  */
494
495 static void
496 initialize_char_syntax(struct cpp_options *opts)
497 {
498    int                 i;
499
500    /*
501     * Set up is_idchar and is_idstart tables.  These should be
502     * faster than saying (is_alpha (c) || c == '_'), etc.
503     * Set up these things before calling any routines tthat
504     * refer to them.
505     */
506    for (i = 'a'; i <= 'z'; i++)
507      {
508         is_idchar[i - 'a' + 'A'] = 1;
509         is_idchar[i] = 1;
510         is_idstart[i - 'a' + 'A'] = 1;
511         is_idstart[i] = 1;
512      }
513    for (i = '0'; i <= '9'; i++)
514       is_idchar[i] = 1;
515    is_idchar[(unsigned char)'_'] = 1;
516    is_idstart[(unsigned char)'_'] = 1;
517    is_idchar[(unsigned char)'$'] = opts->dollars_in_ident;
518    is_idstart[(unsigned char)'$'] = opts->dollars_in_ident;
519
520    /* horizontal space table */
521    is_hor_space[(unsigned char)' '] = 1;
522    is_hor_space[(unsigned char)'\t'] = 1;
523    is_hor_space[(unsigned char)'\v'] = 1;
524    is_hor_space[(unsigned char)'\f'] = 1;
525    is_hor_space[(unsigned char)'\r'] = 1;
526
527    is_space[(unsigned char)' '] = 1;
528    is_space[(unsigned char)'\t'] = 1;
529    is_space[(unsigned char)'\v'] = 1;
530    is_space[(unsigned char)'\f'] = 1;
531    is_space[(unsigned char)'\n'] = 1;
532    is_space[(unsigned char)'\r'] = 1;
533 }
534
535 /* Place into PFILE a quoted string representing the string SRC.
536  * Caller must reserve enough space in pfile->token_buffer. */
537 static void
538 quote_string(cpp_reader * pfile, const char *src)
539 {
540    unsigned char       c;
541
542    CPP_PUTC_Q(pfile, '\"');
543    for (;;)
544       switch ((c = *src++))
545         {
546         default:
547            if (isprint(c))
548               CPP_PUTC_Q(pfile, c);
549            else
550              {
551                 sprintf((char *)CPP_PWRITTEN(pfile), "\\%03o", c);
552                 CPP_ADJUST_WRITTEN(pfile, 4);
553              }
554            break;
555
556         case '\"':
557         case '\\':
558            CPP_PUTC_Q(pfile, '\\');
559            CPP_PUTC_Q(pfile, c);
560            break;
561
562         case '\0':
563            CPP_PUTC_Q(pfile, '\"');
564            CPP_NUL_TERMINATE_Q(pfile);
565            return;
566         }
567 }
568
569 /* Make sure PFILE->token_buffer will hold at least N more chars. */
570
571 void
572 cpp_grow_buffer(cpp_reader * pfile, long n)
573 {
574    long                old_written = CPP_WRITTEN(pfile);
575
576    pfile->token_buffer_size = n + 2 * pfile->token_buffer_size;
577    pfile->token_buffer =
578       (unsigned char *)xrealloc(pfile->token_buffer, pfile->token_buffer_size);
579    CPP_SET_WRITTEN(pfile, old_written);
580 }
581
582 /*
583  * process a given definition string, for initialization
584  * If STR is just an identifier, define it with value 1.
585  * If STR has anything after the identifier, then it should
586  * be identifier=definition.
587  */
588
589 void
590 cpp_define(cpp_reader * pfile, unsigned char *str)
591 {
592    unsigned char      *buf, *p;
593
594    buf = str;
595    p = str;
596    if (!is_idstart[*p])
597      {
598         cpp_error(pfile, "malformed option `-D %s'", str);
599         return;
600      }
601    while (is_idchar[*++p])
602       ;
603    if (*p == 0)
604      {
605         buf = (unsigned char *)alloca(p - buf + 4);
606         strcpy((char *)buf, (const char *)str);
607         strcat((char *)buf, " 1");
608      }
609    else if (*p != '=')
610      {
611         cpp_error(pfile, "malformed option `-D %s'", str);
612         return;
613      }
614    else
615      {
616         unsigned char      *q;
617
618         /* Copy the entire option so we can modify it.  */
619         buf = (unsigned char *)alloca(2 * strlen((char *)str) + 1);
620         strncpy((char *)buf, (const char *)str, p - str);
621         /* Change the = to a space.  */
622         buf[p - str] = ' ';
623         /* Scan for any backslash-newline and remove it.  */
624         p++;
625         q = &buf[p - str];
626         while (*p)
627           {
628              if (*p == '\\' && p[1] == '\n')
629                 p += 2;
630              else
631                 *q++ = *p++;
632           }
633         *q = 0;
634      }
635
636    do_define(pfile, NULL, buf, buf + strlen((char *)buf));
637 }
638
639 /* Process the string STR as if it appeared as the body of a #assert.
640  * OPTION is the option name for which STR was the argument.  */
641
642 static void
643 make_assertion(cpp_reader * pfile, const char *option, const char *str)
644 {
645    cpp_buffer         *ip;
646    unsigned char      *buf, *p, *q;
647
648    /* Copy the entire option so we can modify it.  */
649    buf = (unsigned char *)alloca(strlen((char *)str) + 1);
650    strcpy((char *)buf, (const char *)str);
651    /* Scan for any backslash-newline and remove it.  */
652    p = q = buf;
653    while (*p)
654      {
655         *q++ = *p++;
656      }
657    *q = 0;
658
659    p = buf;
660    if (!is_idstart[*p])
661      {
662         cpp_error(pfile, "malformed option `%s %s'", option, str);
663         return;
664      }
665    while (is_idchar[*++p])
666       ;
667    while (*p == ' ' || *p == '\t')
668       p++;
669    if (!(*p == 0 || *p == '('))
670      {
671         cpp_error(pfile, "malformed option `%s %s'", option, str);
672         return;
673      }
674    ip = cpp_push_buffer(pfile, buf, strlen((char *)buf));
675    do_assert(pfile, NULL, NULL, NULL);
676    cpp_pop_buffer(pfile);
677 }
678
679 /* Append a chain of `struct file_name_list's
680  * to the end of the main include chain.
681  * FIRST is the beginning of the chain to append, and LAST is the end.  */
682
683 static void
684 append_include_chain(cpp_reader * pfile, struct file_name_list *first,
685                      struct file_name_list *last)
686 {
687    struct cpp_options *opts = CPP_OPTIONS(pfile);
688    struct file_name_list *dir;
689
690    if (!first || !last)
691       return;
692
693    if (opts->include == 0)
694       opts->include = first;
695    else
696       opts->last_include->next = first;
697
698    if (opts->first_bracket_include == 0)
699       opts->first_bracket_include = first;
700
701    for (dir = first;; dir = dir->next)
702      {
703         int                 len = strlen(dir->fname) + INCLUDE_LEN_FUDGE;
704
705         if (len > pfile->max_include_len)
706            pfile->max_include_len = len;
707         if (dir == last)
708            break;
709      }
710
711    last->next = NULL;
712    opts->last_include = last;
713 }
714
715 /* Add output to `deps_buffer' for the -M switch.
716  * STRING points to the text to be output.
717  * SPACER is ':' for targets, ' ' for dependencies, zero for text
718  * to be inserted literally.  */
719
720 static void
721 deps_output(cpp_reader * pfile, const char *string, int spacer)
722 {
723    int                 size = strlen(string);
724
725    if (size == 0)
726       return;
727
728 #ifndef MAX_OUTPUT_COLUMNS
729 #define MAX_OUTPUT_COLUMNS 72
730 #endif
731    if (spacer
732        && pfile->deps_column > 0
733        && (pfile->deps_column + size) > MAX_OUTPUT_COLUMNS)
734      {
735         deps_output(pfile, " \\\n  ", 0);
736         pfile->deps_column = 0;
737      }
738    if (pfile->deps_size + size + 8 > pfile->deps_allocated_size)
739      {
740         pfile->deps_allocated_size = (pfile->deps_size + size + 50) * 2;
741         pfile->deps_buffer = (char *)xrealloc(pfile->deps_buffer,
742                                               pfile->deps_allocated_size);
743      }
744    if (spacer == ' ' && pfile->deps_column > 0)
745       pfile->deps_buffer[pfile->deps_size++] = ' ';
746    memcpy(&pfile->deps_buffer[pfile->deps_size], string, size);
747    pfile->deps_size += size;
748    pfile->deps_column += size;
749    if (spacer == ':')
750       pfile->deps_buffer[pfile->deps_size++] = ':';
751    pfile->deps_buffer[pfile->deps_size] = 0;
752 }
753
754 /* Given a colon-separated list of file names PATH,
755  * add all the names to the search path for include files.  */
756
757 static void
758 path_include(cpp_reader * pfile, char *path)
759 {
760    char               *p;
761
762    p = path;
763
764    if (*p)
765       while (1)
766         {
767            char               *q = p;
768            char               *name;
769            struct file_name_list *dirtmp;
770
771            /* Find the end of this name.  */
772            while (*q != 0 && *q != PATH_SEPARATOR)
773               q++;
774            if (p == q)
775              {
776                 /* An empty name in the path stands for the current directory.  */
777                 name = (char *)xmalloc(2);
778                 name[0] = '.';
779                 name[1] = 0;
780              }
781            else
782              {
783                 /* Otherwise use the directory that is named.  */
784                 name = (char *)xmalloc(q - p + 1);
785                 memcpy(name, p, q - p);
786                 name[q - p] = 0;
787              }
788
789            dirtmp =
790               (struct file_name_list *)xmalloc(sizeof(struct file_name_list));
791
792            dirtmp->next = 0;    /* New one goes on the end */
793            dirtmp->control_macro = 0;
794            dirtmp->c_system_include_path = 0;
795            dirtmp->fname = name;
796            dirtmp->got_name_map = 0;
797            append_include_chain(pfile, dirtmp, dirtmp);
798
799            /* Advance past this name.  */
800            p = q;
801            if (*p == 0)
802               break;
803            /* Skip the colon.  */
804            p++;
805         }
806 }
807
808 void
809 init_parse_options(struct cpp_options *opts)
810 {
811    memset((char *)opts, 0, sizeof *opts);
812    opts->in_fname = NULL;
813    opts->out_fname = NULL;
814
815    /* Initialize is_idchar to allow $.  */
816    opts->dollars_in_ident = 1;
817    initialize_char_syntax(opts);
818    opts->dollars_in_ident = DOLLARS_IN_IDENTIFIERS > 0;
819
820    opts->no_line_commands = 0;
821    opts->no_trigraphs = 1;
822    opts->put_out_comments = 0;
823    opts->print_include_names = 0;
824    opts->dump_macros = dump_none;
825    opts->no_output = 0;
826    opts->cplusplus = 0;
827    opts->cplusplus_comments = 1;
828
829    opts->verbose = 0;
830    opts->objc = 0;
831    opts->lang_asm = 0;
832    opts->for_lint = 0;
833    opts->chill = 0;
834    opts->pedantic_errors = 0;
835    opts->inhibit_warnings = 0;
836    opts->warn_comments = 0;
837    opts->warn_import = 1;
838    opts->warnings_are_errors = 0;
839 }
840
841 static enum cpp_token
842 null_underflow(cpp_reader * pfile)
843 {
844    pfile = NULL;
845    return CPP_EOF;
846 }
847
848 static int
849 null_cleanup(cpp_buffer * pbuf, cpp_reader * pfile)
850 {
851    pbuf = NULL;
852    pfile = NULL;
853    return 0;
854 }
855
856 static int
857 macro_cleanup(cpp_buffer * pbuf, cpp_reader * pfile)
858 {
859    HASHNODE           *macro = (HASHNODE *) pbuf->data;
860
861    pfile = NULL;
862    if (macro->type == T_DISABLED)
863       macro->type = T_MACRO;
864    if (macro->type != T_MACRO || pbuf->buf != macro->value.defn->expansion)
865       free(pbuf->buf);
866    return 0;
867 }
868
869 static int
870 file_cleanup(cpp_buffer * pbuf, cpp_reader * pfile)
871 {
872    pfile = NULL;
873    if (pbuf->buf)
874      {
875         free(pbuf->buf);
876         pbuf->buf = 0;
877      }
878    return 0;
879 }
880
881 /* Assuming we have read '/'.
882  * If this is the start of a comment (followed by '*' or '/'),
883  * skip to the end of the comment, and return ' '.
884  * Return EOF if we reached the end of file before the end of the comment.
885  * If not the start of a comment, return '/'. */
886
887 static int
888 skip_comment(cpp_reader * pfile, long *linep)
889 {
890    int                 c = 0;
891
892    while (PEEKC() == '\\' && PEEKN(1) == '\n')
893      {
894         if (linep)
895            (*linep)++;
896         FORWARD(2);
897      }
898    if (PEEKC() == '*')
899      {
900         FORWARD(1);
901         for (;;)
902           {
903              int                 prev_c = c;
904
905              c = GETC();
906              if (c == EOF)
907                 return EOF;
908              while (c == '\\' && PEEKC() == '\n')
909                {
910                   if (linep)
911                      (*linep)++;
912                   FORWARD(1), c = GETC();
913                }
914              if (prev_c == '*' && c == '/')
915                 return ' ';
916              if (c == '\n' && linep)
917                 (*linep)++;
918           }
919      }
920    else if (PEEKC() == '/' && CPP_OPTIONS(pfile)->cplusplus_comments)
921      {
922         FORWARD(1);
923         for (;;)
924           {
925              c = GETC();
926              if (c == EOF)
927                 return ' ';     /* Allow // to be terminated by EOF. */
928              while (c == '\\' && PEEKC() == '\n')
929                {
930                   FORWARD(1);
931                   c = GETC();
932                   if (linep)
933                      (*linep)++;
934                }
935              if (c == '\n')
936                {
937                   /* Don't consider final '\n' to be part of comment. */
938                   FORWARD(-1);
939                   return ' ';
940                }
941           }
942      }
943    else
944       return '/';
945 }
946
947 /* Skip whitespace \-newline and comments.  Does not macro-expand.  */
948 void
949 cpp_skip_hspace(cpp_reader * pfile)
950 {
951    while (1)
952      {
953         int                 c = PEEKC();
954
955         if (c == EOF)
956            return;              /* FIXME */
957         if (is_hor_space[c])
958           {
959              if ((c == '\f' || c == '\v') && CPP_PEDANTIC(pfile))
960                 cpp_pedwarn(pfile, "%s in preprocessing directive",
961                             c == '\f' ? "formfeed" : "vertical tab");
962              FORWARD(1);
963           }
964         else if (c == '/')
965           {
966              FORWARD(1);
967              c = skip_comment(pfile, NULL);
968              if (c == '/')
969                 FORWARD(-1);
970              if (c == EOF || c == '/')
971                 return;
972           }
973         else if (c == '\\' && PEEKN(1) == '\n')
974           {
975              FORWARD(2);
976           }
977         else if (c == '@' && CPP_BUFFER(pfile)->has_escapes
978                  && is_hor_space[PEEKN(1)])
979            FORWARD(2);
980         else
981            return;
982      }
983 }
984
985 /* Read the rest of the current line.
986  * The line is appended to PFILE's output buffer. */
987
988 static void
989 copy_rest_of_line(cpp_reader * pfile)
990 {
991    struct cpp_options *opts = CPP_OPTIONS(pfile);
992
993    for (;;)
994      {
995         int                 c = GETC();
996         int                 nextc;
997
998         switch (c)
999           {
1000           case EOF:
1001              goto end_directive;
1002           case '\\':
1003              if (PEEKC() == '\n')
1004                {
1005                   FORWARD(1);
1006                   continue;
1007                }
1008           case '\'':
1009           case '\"':
1010              goto scan_directive_token;
1011              break;
1012           case '/':
1013              nextc = PEEKC();
1014              if (nextc == '*' || (opts->cplusplus_comments && nextc == '*'))
1015                 goto scan_directive_token;
1016              break;
1017           case '\f':
1018           case '\v':
1019              if (CPP_PEDANTIC(pfile))
1020                 cpp_pedwarn(pfile, "%s in preprocessing directive",
1021                             c == '\f' ? "formfeed" : "vertical tab");
1022              break;
1023
1024           case '\n':
1025              FORWARD(-1);
1026              goto end_directive;
1027            scan_directive_token:
1028              FORWARD(-1);
1029              cpp_get_token(pfile);
1030              continue;
1031           }
1032         CPP_PUTC(pfile, c);
1033      }
1034  end_directive:;
1035    CPP_NUL_TERMINATE(pfile);
1036 }
1037
1038 void
1039 skip_rest_of_line(cpp_reader * pfile)
1040 {
1041    long                old = CPP_WRITTEN(pfile);
1042
1043    copy_rest_of_line(pfile);
1044    CPP_SET_WRITTEN(pfile, old);
1045 }
1046
1047 /* Handle a possible # directive.
1048  * '#' has already been read.  */
1049
1050 static int
1051 handle_directive(cpp_reader * pfile)
1052 {
1053    int                 c;
1054    struct directive   *kt;
1055    int                 ident_length;
1056    long                after_ident = 0;
1057    unsigned char      *ident, *line_end;
1058    long                old_written = CPP_WRITTEN(pfile);
1059
1060    cpp_skip_hspace(pfile);
1061
1062    c = PEEKC();
1063    if (c >= '0' && c <= '9')
1064      {
1065         /* Handle # followed by a line number.  */
1066         if (CPP_PEDANTIC(pfile))
1067            cpp_pedwarn(pfile, "`#' followed by integer");
1068         do_line(pfile, NULL, NULL, NULL);
1069         goto done_a_directive;
1070      }
1071    /* Now find the directive name. */
1072    CPP_PUTC(pfile, '#');
1073    parse_name(pfile, GETC());
1074    ident = pfile->token_buffer + old_written + 1;
1075    ident_length = CPP_PWRITTEN(pfile) - ident;
1076    if (ident_length == 0 && PEEKC() == '\n')
1077      {
1078         /* A line of just `#' becomes blank.  */
1079         goto done_a_directive;
1080      }
1081    /*
1082     * Decode the keyword and call the appropriate expansion
1083     * routine, after moving the input pointer up to the next line.
1084     */
1085    for (kt = directive_table;; kt++)
1086      {
1087         if (kt->length <= 0)
1088            goto not_a_directive;
1089         if (kt->length == ident_length
1090             && !strncmp(kt->name, (const char *)ident, ident_length))
1091            break;
1092      }
1093
1094    if (!kt->command_reads_line)
1095      {
1096         /* Nonzero means do not delete comments within the directive.
1097          * #define needs this when -traditional.  */
1098         int                 comments = CPP_TRADITIONAL(pfile)
1099            && kt->traditional_comments;
1100         int                 save_put_out_comments =
1101            CPP_OPTIONS(pfile)->put_out_comments;
1102
1103         CPP_OPTIONS(pfile)->put_out_comments = comments;
1104         after_ident = CPP_WRITTEN(pfile);
1105         copy_rest_of_line(pfile);
1106         CPP_OPTIONS(pfile)->put_out_comments = save_put_out_comments;
1107      }
1108    /* For #pragma and #define, we may want to pass through the directive.
1109     * Other directives may create output, but we don't want the directive
1110     * itself out, so we pop it now.  For example #include may write a #line
1111     * command (see comment in do_include), and conditionals may emit
1112     * #failed ... #endfailed stuff.  But note that popping the buffer
1113     * means the parameters to kt->func may point after pfile->limit
1114     * so these parameters are invalid as soon as something gets appended
1115     * to the token_buffer.  */
1116
1117    line_end = CPP_PWRITTEN(pfile);
1118    if (!kt->pass_thru && kt->type != T_DEFINE)
1119       CPP_SET_WRITTEN(pfile, old_written);
1120
1121    (*kt->func) (pfile, kt, pfile->token_buffer + after_ident, line_end);
1122    if (kt->pass_thru
1123        || (kt->type == T_DEFINE
1124            && CPP_OPTIONS(pfile)->dump_macros == dump_definitions))
1125      {
1126         /* Just leave the entire #define in the output stack. */
1127      }
1128    else if (kt->type == T_DEFINE
1129             && CPP_OPTIONS(pfile)->dump_macros == dump_names)
1130      {
1131         unsigned char      *p = pfile->token_buffer + old_written + 7;  /* Skip "#define". */
1132
1133         SKIP_WHITE_SPACE(p);
1134         while (is_idchar[*p])
1135            p++;
1136         pfile->limit = p;
1137         CPP_PUTC(pfile, '\n');
1138      }
1139    else if (kt->type == T_DEFINE)
1140       CPP_SET_WRITTEN(pfile, old_written);
1141  done_a_directive:
1142    return 1;
1143
1144  not_a_directive:
1145    return 0;
1146 }
1147
1148 /* Pass a directive through to the output file.
1149  * BUF points to the contents of the directive, as a contiguous string.
1150  * LIMIT points to the first character past the end of the directive.
1151  * KEYWORD is the keyword-table entry for the directive.  */
1152
1153 static void
1154 pass_thru_directive(char *buf, char *limit, cpp_reader * pfile,
1155                     struct directive *keyword)
1156 {
1157    unsigned            keyword_length = keyword->length;
1158
1159    CPP_RESERVE(pfile, 1 + keyword_length + (limit - buf));
1160    CPP_PUTC_Q(pfile, '#');
1161    CPP_PUTS_Q(pfile, keyword->name, keyword_length);
1162    if (limit != buf && buf[0] != ' ')
1163       CPP_PUTC_Q(pfile, ' ');
1164    CPP_PUTS_Q(pfile, buf, limit - buf);
1165 }
1166
1167 /* The arglist structure is built by do_define to tell
1168  * collect_definition where the argument names begin.  That
1169  * is, for a define like "#define f(x,y,z) foo+x-bar*y", the arglist
1170  * would contain pointers to the strings x, y, and z.
1171  * Collect_definition would then build a DEFINITION node,
1172  * with reflist nodes pointing to the places x, y, and z had
1173  * appeared.  So the arglist is just convenience data passed
1174  * between these two routines.  It is not kept around after
1175  * the current #define has been processed and entered into the
1176  * hash table. */
1177
1178 struct arglist {
1179    struct arglist     *next;
1180    char               *name;
1181    int                 length;
1182    int                 argno;
1183    char                rest_args;
1184 };
1185
1186 /* Read a replacement list for a macro with parameters.
1187  * Build the DEFINITION structure.
1188  * Reads characters of text starting at BUF until END.
1189  * ARGLIST specifies the formal parameters to look for
1190  * in the text of the definition; NARGS is the number of args
1191  * in that list, or -1 for a macro name that wants no argument list.
1192  * MACRONAME is the macro name itself (so we can avoid recursive expansion)
1193  * and NAMELEN is its length in characters.
1194  * 
1195  * Note that comments, backslash-newlines, and leading white space
1196  * have already been deleted from the argument.  */
1197
1198 static DEFINITION  *
1199 collect_expansion(cpp_reader * pfile, unsigned char *buf, unsigned char *limit,
1200                   int nargs, struct arglist *arglist)
1201 {
1202    DEFINITION         *defn;
1203    unsigned char      *p, *lastp, *exp_p;
1204    struct reflist     *endpat = NULL;
1205
1206    /* Pointer to first nonspace after last ## seen.  */
1207    unsigned char      *concat = 0;
1208
1209    /* Pointer to first nonspace after last single-# seen.  */
1210    unsigned char      *stringify = 0;
1211    int                 maxsize;
1212    int                 expected_delimiter = '\0';
1213
1214    /* Scan thru the replacement list, ignoring comments and quoted
1215     * strings, picking up on the macro calls.  It does a linear search
1216     * thru the arg list on every potential symbol.  Profiling might say
1217     * that something smarter should happen. */
1218
1219    if (limit < buf)
1220       abort();
1221
1222    /* Find the beginning of the trailing whitespace.  */
1223    p = buf;
1224    while (p < limit && is_space[limit[-1]])
1225       limit--;
1226
1227    /* Allocate space for the text in the macro definition.
1228     * Leading and trailing whitespace chars need 2 bytes each.
1229     * Each other input char may or may not need 1 byte,
1230     * so this is an upper bound.  The extra 5 are for invented
1231     * leading and trailing newline-marker and final null.  */
1232    maxsize = (sizeof(DEFINITION) + (limit - p) + 5);
1233    /* Occurrences of '@' get doubled, so allocate extra space for them. */
1234    while (p < limit)
1235       if (*p++ == '@')
1236          maxsize++;
1237    defn = (DEFINITION *) xcalloc(1, maxsize);
1238
1239    defn->nargs = nargs;
1240    exp_p = defn->expansion = (unsigned char *)defn + sizeof(DEFINITION);
1241    lastp = exp_p;
1242
1243    p = buf;
1244
1245    /* Add one initial space escape-marker to prevent accidental
1246     * token-pasting (often removed by macroexpand). */
1247    *exp_p++ = '@';
1248    *exp_p++ = ' ';
1249
1250    if (limit - p >= 2 && p[0] == '#' && p[1] == '#')
1251      {
1252         cpp_error(pfile, "`##' at start of macro definition");
1253         p += 2;
1254      }
1255    /* Process the main body of the definition.  */
1256    while (p < limit)
1257      {
1258         int                 skipped_arg = 0;
1259         unsigned char       c = *p++;
1260
1261         *exp_p++ = c;
1262
1263         if (!CPP_TRADITIONAL(pfile))
1264           {
1265              switch (c)
1266                {
1267                case '\'':
1268                case '\"':
1269                   if (expected_delimiter != '\0')
1270                     {
1271                        if (c == expected_delimiter)
1272                           expected_delimiter = '\0';
1273                     }
1274                   else
1275                      expected_delimiter = c;
1276                   break;
1277
1278                case '\\':
1279                   if (p < limit && expected_delimiter)
1280                     {
1281                        /* In a string, backslash goes through
1282                         * and makes next char ordinary.  */
1283                        *exp_p++ = *p++;
1284                     }
1285                   break;
1286
1287                case '@':
1288                   /* An '@' in a string or character constant stands for itself,
1289                    * and does not need to be escaped. */
1290                   if (!expected_delimiter)
1291                      *exp_p++ = c;
1292                   break;
1293
1294                case '#':
1295                   /* # is ordinary inside a string.  */
1296                   if (expected_delimiter)
1297                      break;
1298                   if (p < limit && *p == '#')
1299                     {
1300                        /* ##: concatenate preceding and following tokens.  */
1301                        /* Take out the first #, discard preceding whitespace.  */
1302                        exp_p--;
1303                        while (exp_p > lastp && is_hor_space[exp_p[-1]])
1304                           --exp_p;
1305                        /* Skip the second #.  */
1306                        p++;
1307                        /* Discard following whitespace.  */
1308                        SKIP_WHITE_SPACE(p);
1309                        concat = p;
1310                        if (p == limit)
1311                           cpp_error(pfile, "`##' at end of macro definition");
1312                     }
1313                   else if (nargs >= 0)
1314                     {
1315                        /* Single #: stringify following argument ref.
1316                         * Don't leave the # in the expansion.  */
1317                        exp_p--;
1318                        SKIP_WHITE_SPACE(p);
1319                        if (p == limit || !is_idstart[*p])
1320                           cpp_error(pfile,
1321                                     "`#' operator is not followed by a macro argument name");
1322                        else
1323                           stringify = p;
1324                     }
1325                   break;
1326                }
1327           }
1328         else
1329           {
1330              /* In -traditional mode, recognize arguments inside strings and
1331               * and character constants, and ignore special properties of #.
1332               * Arguments inside strings are considered "stringified", but no
1333               * extra quote marks are supplied.  */
1334              switch (c)
1335                {
1336                case '\'':
1337                case '\"':
1338                   if (expected_delimiter != '\0')
1339                     {
1340                        if (c == expected_delimiter)
1341                           expected_delimiter = '\0';
1342                     }
1343                   else
1344                      expected_delimiter = c;
1345                   break;
1346
1347                case '\\':
1348                   /* Backslash quotes delimiters and itself, but not macro args.  */
1349                   if (expected_delimiter != 0 && p < limit
1350                       && (*p == expected_delimiter || *p == '\\'))
1351                     {
1352                        *exp_p++ = *p++;
1353                        continue;
1354                     }
1355                   break;
1356
1357                case '/':
1358                   if (expected_delimiter != '\0')       /* No comments inside strings.  */
1359                      break;
1360                   if (*p == '*')
1361                     {
1362                        /* If we find a comment that wasn't removed by handle_directive,
1363                         * this must be -traditional.  So replace the comment with
1364                         * nothing at all.  */
1365                        exp_p--;
1366                        p += 1;
1367                        while (p < limit && !(p[-2] == '*' && p[-1] == '/'))
1368                           p++;
1369                     }
1370                   break;
1371                }
1372           }
1373
1374         /* Handle the start of a symbol.  */
1375         if (is_idchar[c] && nargs > 0)
1376           {
1377              unsigned char      *id_beg = p - 1;
1378              int                 id_len;
1379
1380              --exp_p;
1381              while (p != limit && is_idchar[*p])
1382                 p++;
1383              id_len = p - id_beg;
1384
1385              if (is_idstart[c])
1386                {
1387                   struct arglist     *arg;
1388
1389                   for (arg = arglist; arg != NULL; arg = arg->next)
1390                     {
1391                        struct reflist     *tpat;
1392
1393                        if (arg->name[0] == c
1394                            && arg->length == id_len
1395                            && strncmp((const char *)arg->name,
1396                                       (const char *)id_beg, id_len) == 0)
1397                          {
1398                             if (expected_delimiter
1399                                 && CPP_OPTIONS(pfile)->warn_stringify)
1400                               {
1401                                  if (CPP_TRADITIONAL(pfile))
1402                                    {
1403                                       cpp_warning(pfile,
1404                                                   "macro argument `%.*s' is stringified.",
1405                                                   id_len, arg->name);
1406                                    }
1407                                  else
1408                                    {
1409                                       cpp_warning(pfile,
1410                                                   "macro arg `%.*s' would be stringified with -traditional.",
1411                                                   id_len, arg->name);
1412                                    }
1413                               }
1414                             /* If ANSI, don't actually substitute inside a string.  */
1415                             if (!CPP_TRADITIONAL(pfile) && expected_delimiter)
1416                                break;
1417                             /* make a pat node for this arg and append it to the end of
1418                              * the pat list */
1419                             tpat =
1420                                (struct reflist *)
1421                                xmalloc(sizeof(struct reflist));
1422
1423                             tpat->next = NULL;
1424                             tpat->raw_before = concat == id_beg;
1425                             tpat->raw_after = 0;
1426                             tpat->rest_args = arg->rest_args;
1427                             tpat->stringify = (CPP_TRADITIONAL(pfile)
1428                                                ? expected_delimiter != '\0'
1429                                                : stringify == id_beg);
1430
1431                             if (endpat == NULL)
1432                                defn->pattern = tpat;
1433                             else
1434                                endpat->next = tpat;
1435                             endpat = tpat;
1436
1437                             tpat->argno = arg->argno;
1438                             tpat->nchars = exp_p - lastp;
1439                             {
1440                                unsigned char      *p1 = p;
1441
1442                                SKIP_WHITE_SPACE(p1);
1443                                if (p1 + 2 <= limit && p1[0] == '#'
1444                                    && p1[1] == '#')
1445                                   tpat->raw_after = 1;
1446                             }
1447                             lastp = exp_p;      /* place to start copying from next time */
1448                             skipped_arg = 1;
1449                             break;
1450                          }
1451                     }
1452                }
1453              /* If this was not a macro arg, copy it into the expansion.  */
1454              if (!skipped_arg)
1455                {
1456                   unsigned char      *lim1 = p;
1457
1458                   p = id_beg;
1459                   while (p != lim1)
1460                      *exp_p++ = *p++;
1461                   if (stringify == id_beg)
1462                      cpp_error(pfile,
1463                                "`#' operator should be followed by a macro argument name");
1464                }
1465           }
1466      }
1467
1468    if (!CPP_TRADITIONAL(pfile) && expected_delimiter == 0)
1469      {
1470         /* If ANSI, put in a "@ " marker to prevent token pasting.
1471          * But not if "inside a string" (which in ANSI mode
1472          * happens only for -D option).  */
1473         *exp_p++ = '@';
1474         *exp_p++ = ' ';
1475      }
1476    *exp_p = '\0';
1477
1478    defn->length = exp_p - defn->expansion;
1479
1480    /* Crash now if we overrun the allocated size.  */
1481    if (defn->length + 1 > maxsize)
1482       abort();
1483
1484    return defn;
1485 }
1486
1487 /*
1488  * special extension string that can be added to the last macro argument to 
1489  * allow it to absorb the "rest" of the arguments when expanded.  Ex:
1490  *              #define wow(a, b...)            process (b, a, b)
1491  *              { wow (1, 2, 3); }      ->      { process (2, 3, 1, 2, 3); }
1492  *              { wow (one, two); }     ->      { process (two, one, two); }
1493  * if this "rest_arg" is used with the concat token '##' and if it is not
1494  * supplied then the token attached to with ## will not be outputted.  Ex:
1495  *              #define wow (a, b...)           process (b ## , a, ## b)
1496  *              { wow (1, 2); }         ->      { process (2, 1, 2); }
1497  *              { wow (one); }          ->      { process (one); {
1498  */
1499 static char         rest_extension[] = "...";
1500
1501 #define REST_EXTENSION_LENGTH   (sizeof (rest_extension) - 1)
1502
1503 /* Create a DEFINITION node from a #define directive.  Arguments are 
1504  * as for do_define. */
1505 static void
1506 create_definition(MACRODEF * mdef, unsigned char *buf, unsigned char *limit,
1507                   cpp_reader * pfile, int predefinition)
1508 {
1509    unsigned char      *bp;      /* temp ptr into input buffer */
1510    unsigned char      *symname; /* remember where symbol name starts */
1511    int                 sym_length;      /* and how long it is */
1512    int                 rest_args = 0;
1513    long                line, col;
1514    const char         *file =
1515       CPP_BUFFER(pfile) ? CPP_BUFFER(pfile)->nominal_fname : "";
1516    DEFINITION         *defn;
1517    int                 arglengths = 0;  /* Accumulate lengths of arg names
1518                                          * plus number of args.  */
1519
1520    cpp_buf_line_and_col(CPP_BUFFER(pfile), &line, &col);
1521
1522    bp = buf;
1523
1524    while (is_hor_space[*bp])
1525       bp++;
1526
1527    symname = bp;                /* remember where it starts */
1528
1529    sym_length = check_macro_name(pfile, bp, "macro");
1530    bp += sym_length;
1531
1532    /* Lossage will occur if identifiers or control keywords are broken
1533     * across lines using backslash.  This is not the right place to take
1534     * care of that. */
1535
1536    if (*bp == '(')
1537      {
1538         struct arglist     *arg_ptrs = NULL;
1539         int                 argno = 0;
1540
1541         bp++;                   /* skip '(' */
1542         SKIP_WHITE_SPACE(bp);
1543
1544         /* Loop over macro argument names.  */
1545         while (*bp != ')')
1546           {
1547              struct arglist     *temp;
1548
1549              temp = (struct arglist *)alloca(sizeof(struct arglist));
1550
1551              temp->name = (char *)bp;
1552              temp->next = arg_ptrs;
1553              temp->argno = argno++;
1554              temp->rest_args = 0;
1555              arg_ptrs = temp;
1556
1557              if (rest_args)
1558                 cpp_pedwarn(pfile, "another parameter follows `%s'",
1559                             rest_extension);
1560
1561              if (!is_idstart[*bp])
1562                 cpp_pedwarn(pfile, "invalid character in macro parameter name");
1563
1564              /* Find the end of the arg name.  */
1565              while (is_idchar[*bp])
1566                {
1567                   bp++;
1568                   /* do we have a "special" rest-args extension here? */
1569                   if ((unsigned)(limit - bp) > REST_EXTENSION_LENGTH &&
1570                       strncmp(rest_extension, (const char *)bp,
1571                               REST_EXTENSION_LENGTH) == 0)
1572                     {
1573                        rest_args = 1;
1574                        temp->rest_args = 1;
1575                        break;
1576                     }
1577                }
1578              temp->length = (char *)bp - temp->name;
1579              if (rest_args == 1)
1580                 bp += REST_EXTENSION_LENGTH;
1581              arglengths += temp->length + 2;
1582              SKIP_WHITE_SPACE(bp);
1583              if (temp->length == 0 || (*bp != ',' && *bp != ')'))
1584                {
1585                   cpp_error(pfile,
1586                             "badly punctuated parameter list in `#define'");
1587                   goto nope;
1588                }
1589              if (*bp == ',')
1590                {
1591                   bp++;
1592                   SKIP_WHITE_SPACE(bp);
1593                }
1594              if (bp >= limit)
1595                {
1596                   cpp_error(pfile, "unterminated parameter list in `#define'");
1597                   goto nope;
1598                }
1599              {
1600                 struct arglist     *otemp;
1601
1602                 for (otemp = temp->next; otemp != NULL; otemp = otemp->next)
1603                    if (temp->length == otemp->length &&
1604                        strncmp((const char *)temp->name,
1605                                (const char *)otemp->name, temp->length) == 0)
1606                      {
1607                         char               *name;
1608
1609                         name = (char *)alloca(temp->length + 1);
1610                         strncpy(name, (const char *)temp->name, temp->length);
1611                         name[temp->length] = '\0';
1612                         cpp_error(pfile,
1613                                   "duplicate argument name `%s' in `#define'",
1614                                   name);
1615                         goto nope;
1616                      }
1617              }
1618           }
1619
1620         ++bp;                   /* skip paren */
1621         SKIP_WHITE_SPACE(bp);
1622         /* now everything from bp before limit is the definition. */
1623         defn = collect_expansion(pfile, bp, limit, argno, arg_ptrs);
1624         defn->rest_args = rest_args;
1625
1626         /* Now set defn->args.argnames to the result of concatenating
1627          * the argument names in reverse order
1628          * with comma-space between them.  */
1629         defn->args.argnames = (unsigned char *)xmalloc(arglengths + 1);
1630         {
1631            struct arglist     *temp;
1632            int                 i = 0;
1633
1634            for (temp = arg_ptrs; temp; temp = temp->next)
1635              {
1636                 memcpy(&defn->args.argnames[i], temp->name, temp->length);
1637                 i += temp->length;
1638                 if (temp->next != 0)
1639                   {
1640                      defn->args.argnames[i++] = ',';
1641                      defn->args.argnames[i++] = ' ';
1642                   }
1643              }
1644            defn->args.argnames[i] = 0;
1645         }
1646      }
1647    else
1648      {
1649         /* Simple expansion or empty definition.  */
1650
1651         if (bp < limit)
1652           {
1653              if (is_hor_space[*bp])
1654                {
1655                   bp++;
1656                   SKIP_WHITE_SPACE(bp);
1657                }
1658              else
1659                {
1660                   switch (*bp)
1661                     {
1662                     case '!':
1663                     case '"':
1664                     case '#':
1665                     case '%':
1666                     case '&':
1667                     case '\'':
1668                     case ')':
1669                     case '*':
1670                     case '+':
1671                     case ',':
1672                     case '-':
1673                     case '.':
1674                     case '/':
1675                     case ':':
1676                     case ';':
1677                     case '<':
1678                     case '=':
1679                     case '>':
1680                     case '?':
1681                     case '[':
1682                     case '\\':
1683                     case ']':
1684                     case '^':
1685                     case '{':
1686                     case '|':
1687                     case '}':
1688                     case '~':
1689                        cpp_warning(pfile,
1690                                    "missing white space after `#define %.*s'",
1691                                    sym_length, symname);
1692                        break;
1693
1694                     default:
1695                        cpp_pedwarn(pfile,
1696                                    "missing white space after `#define %.*s'",
1697                                    sym_length, symname);
1698                        break;
1699                     }
1700                }
1701           }
1702         /* now everything from bp before limit is the definition. */
1703         defn = collect_expansion(pfile, bp, limit, -1, NULL);
1704         defn->args.argnames = (unsigned char *)"";
1705      }
1706
1707    defn->line = line;
1708    defn->file = file;
1709
1710    /* OP is null if this is a predefinition */
1711    defn->predefined = predefinition;
1712    mdef->defn = defn;
1713    mdef->symnam = (char *)symname;
1714    mdef->symlen = sym_length;
1715
1716    return;
1717
1718  nope:
1719    mdef->defn = 0;
1720 }
1721
1722 /* Check a purported macro name SYMNAME, and yield its length.
1723  * USAGE is the kind of name this is intended for.  */
1724
1725 static int
1726 check_macro_name(cpp_reader * pfile, unsigned char *symname, const char *usage)
1727 {
1728    unsigned char      *p;
1729    int                 sym_length;
1730
1731    for (p = symname; is_idchar[*p]; p++)
1732       ;
1733    sym_length = p - symname;
1734    if (sym_length == 0)
1735      {
1736         cpp_error(pfile, "invalid %s name", usage);
1737      }
1738    else if (!is_idstart[*symname])
1739      {
1740         unsigned char      *msg;        /* what pain... */
1741
1742         msg = (unsigned char *)alloca(sym_length + 1);
1743         memcpy(msg, symname, sym_length);
1744         msg[sym_length] = 0;
1745         cpp_error(pfile, "invalid %s name `%s'", usage, msg);
1746      }
1747    else
1748      {
1749         if (!strncmp((const char *)symname, "defined", 7) && sym_length == 7)
1750            cpp_error(pfile, "invalid %s name `defined'", usage);
1751      }
1752    return sym_length;
1753 }
1754
1755 /*
1756  * return zero if two DEFINITIONs are isomorphic
1757  */
1758 static int
1759 compare_defs(DEFINITION * d1, DEFINITION * d2)
1760 {
1761    struct reflist     *a1, *a2;
1762    unsigned char      *p1 = d1->expansion;
1763    unsigned char      *p2 = d2->expansion;
1764    int                 first = 1;
1765
1766    if (d1->nargs != d2->nargs)
1767       return 1;
1768    if (strcmp((char *)d1->args.argnames, (char *)d2->args.argnames))
1769       return 1;
1770    for (a1 = d1->pattern, a2 = d2->pattern; a1 && a2;
1771         a1 = a1->next, a2 = a2->next)
1772      {
1773         if (!
1774             ((a1->nchars == a2->nchars
1775               && !strncmp((const char *)p1, (const char *)p2, a1->nchars))
1776              || !comp_def_part(first, p1, a1->nchars, p2, a2->nchars, 0))
1777             || a1->argno != a2->argno || a1->stringify != a2->stringify
1778             || a1->raw_before != a2->raw_before
1779             || a1->raw_after != a2->raw_after)
1780            return 1;
1781         first = 0;
1782         p1 += a1->nchars;
1783         p2 += a2->nchars;
1784      }
1785    if (a1 != a2)
1786       return 1;
1787    if (comp_def_part(first, p1, d1->length - (p1 - d1->expansion),
1788                      p2, d2->length - (p2 - d2->expansion), 1))
1789       return 1;
1790    return 0;
1791 }
1792
1793 /* Return 1 if two parts of two macro definitions are effectively different.
1794  * One of the parts starts at BEG1 and has LEN1 chars;
1795  * the other has LEN2 chars at BEG2.
1796  * Any sequence of whitespace matches any other sequence of whitespace.
1797  * FIRST means these parts are the first of a macro definition;
1798  * so ignore leading whitespace entirely.
1799  * LAST means these parts are the last of a macro definition;
1800  * so ignore trailing whitespace entirely.  */
1801
1802 static int
1803 comp_def_part(int first, unsigned char *beg1, int len1,
1804               unsigned char *beg2, int len2, int last)
1805 {
1806    unsigned char      *end1 = beg1 + len1;
1807    unsigned char      *end2 = beg2 + len2;
1808
1809    if (first)
1810      {
1811         while (beg1 != end1 && is_space[*beg1])
1812            beg1++;
1813         while (beg2 != end2 && is_space[*beg2])
1814            beg2++;
1815      }
1816    if (last)
1817      {
1818         while (beg1 != end1 && is_space[end1[-1]])
1819            end1--;
1820         while (beg2 != end2 && is_space[end2[-1]])
1821            end2--;
1822      }
1823    while (beg1 != end1 && beg2 != end2)
1824      {
1825         if (is_space[*beg1] && is_space[*beg2])
1826           {
1827              while (beg1 != end1 && is_space[*beg1])
1828                 beg1++;
1829              while (beg2 != end2 && is_space[*beg2])
1830                 beg2++;
1831           }
1832         else if (*beg1 == *beg2)
1833           {
1834              beg1++;
1835              beg2++;
1836           }
1837         else
1838            break;
1839      }
1840    return (beg1 != end1) || (beg2 != end2);
1841 }
1842
1843 /* Process a #define command.
1844  * BUF points to the contents of the #define command, as a contiguous string.
1845  * LIMIT points to the first character past the end of the definition.
1846  * KEYWORD is the keyword-table entry for #define,
1847  * or NULL for a "predefined" macro.  */
1848
1849 static int
1850 do_define(cpp_reader * pfile, struct directive *keyword,
1851           unsigned char *buf, unsigned char *limit)
1852 {
1853    int                 hashcode;
1854    MACRODEF            mdef;
1855    HASHNODE           *hp;
1856
1857    create_definition(&mdef, buf, limit, pfile, keyword == NULL);
1858    if (mdef.defn == 0)
1859       return 1;
1860
1861    hashcode = hashf(mdef.symnam, mdef.symlen, HASHSIZE);
1862
1863    if ((hp = cpp_lookup(mdef.symnam, mdef.symlen, hashcode)) != NULL)
1864      {
1865         int                 ok = 0;
1866
1867         /* Redefining a precompiled key is ok.  */
1868         if (hp->type == T_PCSTRING)
1869            ok = 1;
1870         /* Redefining a macro is ok if the definitions are the same.  */
1871         else if (hp->type == T_MACRO)
1872            ok = !compare_defs(mdef.defn, hp->value.defn);
1873         /* Redefining a constant is ok with -D.  */
1874         else if (hp->type == T_CONST)
1875            ok = !CPP_OPTIONS(pfile)->done_initializing;
1876         /* Print the warning if it's not ok.  */
1877         if (!ok)
1878           {
1879              char               *msg;   /* what pain... */
1880
1881              /* If we are passing through #define and #undef directives, do
1882               * that for this re-definition now.  */
1883              if (CPP_OPTIONS(pfile)->debug_output && keyword)
1884                 pass_thru_directive((char *)buf, (char *)limit, pfile, keyword);
1885
1886              msg = (char *)alloca(mdef.symlen + 22);
1887              *msg = '`';
1888              memcpy(msg + 1, mdef.symnam, mdef.symlen);
1889              strcpy((msg + mdef.symlen + 1), "' redefined");
1890              cpp_pedwarn(pfile, msg);
1891              if (hp->type == T_MACRO)
1892                 cpp_pedwarn_with_file_and_line(pfile, hp->value.defn->file,
1893                                                hp->value.defn->line,
1894                                                "this is the location of the previous definition",
1895                                                NULL, NULL, NULL);
1896           }
1897         /* Replace the old definition.  */
1898         hp->type = T_MACRO;
1899         hp->value.defn = mdef.defn;
1900      }
1901    else
1902      {
1903         /* If we are passing through #define and #undef directives, do
1904          * that for this new definition now.  */
1905         if (CPP_OPTIONS(pfile)->debug_output && keyword)
1906            pass_thru_directive((char *)buf, (char *)limit, pfile, keyword);
1907         install(mdef.symnam, mdef.symlen, T_MACRO, 0,
1908                 (char *)mdef.defn, hashcode);
1909      }
1910
1911    return 0;
1912 }
1913
1914 /* This structure represents one parsed argument in a macro call.
1915  * `raw' points to the argument text as written (`raw_length' is its length).
1916  * `expanded' points to the argument's macro-expansion
1917  * (its length is `expand_length').
1918  * `stringified_length' is the length the argument would have
1919  * if stringified.
1920  * `use_count' is the number of times this macro arg is substituted
1921  * into the macro.  If the actual use count exceeds 10, 
1922  * the value stored is 10. */
1923
1924 /* raw and expanded are relative to ARG_BASE */
1925 #define ARG_BASE ((pfile)->token_buffer)
1926
1927 struct argdata {
1928    /* Strings relative to pfile->token_buffer */
1929    long                raw, expanded, stringified;
1930    int                 raw_length, expand_length;
1931    int                 stringified_length;
1932    char                newlines;
1933    char                use_count;
1934 };
1935
1936 cpp_buffer         *
1937 cpp_push_buffer(cpp_reader * pfile, unsigned char *buffer, long length)
1938 {
1939 #ifdef STATIC_BUFFERS
1940    cpp_buffer         *buf = CPP_BUFFER(pfile);
1941
1942    if (buf == pfile->buffer_stack)
1943       cpp_fatal("macro or `#include' recursion too deep");
1944    buf--;
1945    memset((char *)buf, 0, sizeof(cpp_buffer));
1946    CPP_BUFFER(pfile) = buf;
1947 #else
1948    cpp_buffer         *buf = (cpp_buffer *) xmalloc(sizeof(cpp_buffer));
1949
1950    memset((char *)buf, 0, sizeof(cpp_buffer));
1951    CPP_PREV_BUFFER(buf) = CPP_BUFFER(pfile);
1952    CPP_BUFFER(pfile) = buf;
1953 #endif
1954    buf->if_stack = pfile->if_stack;
1955    buf->cleanup = null_cleanup;
1956    buf->underflow = null_underflow;
1957    buf->buf = buf->cur = buffer;
1958    buf->alimit = buf->rlimit = buffer + length;
1959
1960    return buf;
1961 }
1962
1963 static cpp_buffer  *
1964 cpp_pop_buffer(cpp_reader * pfile)
1965 {
1966    cpp_buffer         *buf = CPP_BUFFER(pfile);
1967
1968 #ifdef STATIC_BUFFERS
1969    (*buf->cleanup) (buf, pfile);
1970    return ++CPP_BUFFER(pfile);
1971 #else
1972    cpp_buffer         *next_buf = CPP_PREV_BUFFER(buf);
1973
1974    (*buf->cleanup) (buf, pfile);
1975    CPP_BUFFER(pfile) = next_buf;
1976    free(buf);
1977    return next_buf;
1978 #endif
1979 }
1980
1981 /* Scan until CPP_BUFFER (PFILE) is exhausted into PFILE->token_buffer.
1982  * Pop the buffer when done. */
1983
1984 static void
1985 cpp_scan_buffer(cpp_reader * pfile)
1986 {
1987    cpp_buffer         *buffer = CPP_BUFFER(pfile);
1988
1989    for (;;)
1990      {
1991         enum cpp_token      token = cpp_get_token(pfile);
1992
1993         if (token == CPP_EOF)   /* Should not happen ... */
1994            break;
1995         if (token == CPP_POP && CPP_BUFFER(pfile) == buffer)
1996           {
1997              cpp_pop_buffer(pfile);
1998              break;
1999           }
2000      }
2001 }
2002
2003 /*
2004  * Rescan a string (which may have escape marks) into pfile's buffer.
2005  * Place the result in pfile->token_buffer.
2006  *
2007  * The input is copied before it is scanned, so it is safe to pass
2008  * it something from the token_buffer that will get overwritten
2009  * (because it follows CPP_WRITTEN).  This is used by do_include.
2010  */
2011
2012 static void
2013 cpp_expand_to_buffer(cpp_reader * pfile, unsigned char *buf, int length)
2014 {
2015    cpp_buffer         *ip;
2016    unsigned char      *limit = buf + length;
2017    unsigned char      *buf1;
2018
2019    if (length < 0)
2020       abort();
2021
2022    /* Set up the input on the input stack.  */
2023
2024    buf1 = (unsigned char *)alloca(length + 1);
2025    {
2026       unsigned char      *p1 = buf;
2027       unsigned char      *p2 = buf1;
2028
2029       while (p1 != limit)
2030          *p2++ = *p1++;
2031    }
2032    buf1[length] = 0;
2033
2034    ip = cpp_push_buffer(pfile, buf1, length);
2035    ip->has_escapes = 1;
2036
2037    /* Scan the input, create the output.  */
2038    cpp_scan_buffer(pfile);
2039
2040    CPP_NUL_TERMINATE(pfile);
2041 }
2042
2043 static void
2044 adjust_position(unsigned char *buf, unsigned char *limit, long *linep,
2045                 long *colp)
2046 {
2047    while (buf < limit)
2048      {
2049         unsigned char       ch = *buf++;
2050
2051         if (ch == '\n')
2052            (*linep)++, (*colp) = 1;
2053         else
2054            (*colp)++;
2055      }
2056 }
2057
2058 /* Move line_base forward, updating lineno and colno. */
2059
2060 static void
2061 update_position(cpp_buffer * pbuf)
2062 {
2063    unsigned char      *old_pos = pbuf->buf + pbuf->line_base;
2064    unsigned char      *new_pos = pbuf->cur;
2065    struct parse_marker *mark;
2066
2067    for (mark = pbuf->marks; mark != NULL; mark = mark->next)
2068      {
2069         if (pbuf->buf + mark->position < new_pos)
2070            new_pos = pbuf->buf + mark->position;
2071      }
2072    pbuf->line_base += new_pos - old_pos;
2073    adjust_position(old_pos, new_pos, &pbuf->lineno, &pbuf->colno);
2074 }
2075
2076 void
2077 cpp_buf_line_and_col(cpp_buffer * pbuf, long *linep, long *colp)
2078 {
2079    long                dummy;
2080
2081    if (colp == NULL)
2082       colp = &dummy;
2083    if (pbuf)
2084      {
2085         *linep = pbuf->lineno;
2086         *colp = pbuf->colno;
2087         adjust_position(pbuf->buf + pbuf->line_base, pbuf->cur, linep, colp);
2088      }
2089    else
2090      {
2091         *linep = 0;
2092         *colp = 0;
2093      }
2094 }
2095
2096 /* Return the cpp_buffer that corresponds to a file (not a macro). */
2097
2098 cpp_buffer         *
2099 cpp_file_buffer(cpp_reader * pfile)
2100 {
2101    cpp_buffer         *ip = CPP_BUFFER(pfile);
2102
2103    for (; ip != CPP_NULL_BUFFER(pfile); ip = CPP_PREV_BUFFER(ip))
2104       if (ip->fname != NULL)
2105          return ip;
2106    return NULL;
2107 }
2108
2109 static long
2110 count_newlines(unsigned char *buf, unsigned char *limit)
2111 {
2112    long                count = 0;
2113
2114    while (buf < limit)
2115      {
2116         unsigned char       ch = *buf++;
2117
2118         if (ch == '\n')
2119            count++;
2120      }
2121    return count;
2122 }
2123
2124 /*
2125  * write out a #line command, for instance, after an #include file.
2126  * If CONDITIONAL is nonzero, we can omit the #line if it would
2127  * appear to be a no-op, and we can output a few newlines instead
2128  * if we want to increase the line number by a small amount.
2129  * FILE_CHANGE says whether we are entering a file, leaving, or neither.
2130  */
2131
2132 static void
2133 output_line_command(cpp_reader * pfile, int conditional,
2134                     enum file_change_code file_change)
2135 {
2136    long                line, col;
2137    cpp_buffer         *ip = CPP_BUFFER(pfile);
2138
2139    if (CPP_OPTIONS(pfile)->no_line_commands
2140        || ip->fname == NULL || CPP_OPTIONS(pfile)->no_output)
2141      {
2142         return;
2143      }
2144    update_position(ip);
2145    line = CPP_BUFFER(pfile)->lineno;
2146    col = CPP_BUFFER(pfile)->colno;
2147    adjust_position(CPP_LINE_BASE(ip), ip->cur, &line, &col);
2148
2149    if (conditional)
2150      {
2151         if (line == pfile->lineno)
2152            return;
2153
2154         /* If the inherited line number is a little too small,
2155          * output some newlines instead of a #line command.  */
2156         if (line > pfile->lineno && line < pfile->lineno + 8)
2157           {
2158              CPP_RESERVE(pfile, 20);
2159              while (line > pfile->lineno)
2160                {
2161                   CPP_PUTC_Q(pfile, '\n');
2162                   pfile->lineno++;
2163                }
2164              return;
2165           }
2166      }
2167
2168    CPP_RESERVE(pfile, 4 * strlen(ip->nominal_fname) + 50);
2169    {
2170 #ifdef OUTPUT_LINE_COMMANDS
2171       static char         sharp_line[] = "#line ";
2172
2173 #else
2174       static char         sharp_line[] = "# ";
2175
2176 #endif
2177       CPP_PUTS_Q(pfile, sharp_line, sizeof(sharp_line) - 1);
2178    }
2179
2180    sprintf((char *)CPP_PWRITTEN(pfile), "%d ", (int)line);
2181    CPP_ADJUST_WRITTEN(pfile, strlen((char *)CPP_PWRITTEN(pfile)));
2182
2183    quote_string(pfile, ip->nominal_fname);
2184    if (file_change != same_file)
2185      {
2186         CPP_PUTC_Q(pfile, ' ');
2187         CPP_PUTC_Q(pfile, file_change == enter_file ? '1' : '2');
2188      }
2189    /* Tell cc1 if following text comes from a system header file.  */
2190    if (ip->system_header_p)
2191      {
2192         CPP_PUTC_Q(pfile, ' ');
2193         CPP_PUTC_Q(pfile, '3');
2194      }
2195 #ifndef NO_IMPLICIT_EXTERN_C
2196    /* Tell cc1plus if following text should be treated as C.  */
2197    if (ip->system_header_p == 2 && CPP_OPTIONS(pfile)->cplusplus)
2198      {
2199         CPP_PUTC_Q(pfile, ' ');
2200         CPP_PUTC_Q(pfile, '4');
2201      }
2202 #endif
2203    CPP_PUTC_Q(pfile, '\n');
2204    pfile->lineno = line;
2205 }
2206
2207 /*
2208  * Parse a macro argument and append the info on PFILE's token_buffer.
2209  * REST_ARGS means to absorb the rest of the args.
2210  * Return nonzero to indicate a syntax error.
2211  */
2212
2213 static enum cpp_token
2214 macarg(cpp_reader * pfile, int rest_args)
2215 {
2216    int                 paren = 0;
2217    enum cpp_token      token;
2218    char                save_put_out_comments =
2219       CPP_OPTIONS(pfile)->put_out_comments;
2220
2221    CPP_OPTIONS(pfile)->put_out_comments = 0;
2222
2223    token = CPP_OTHER;
2224    /* Try to parse as much of the argument as exists at this
2225     * input stack level.  */
2226    pfile->no_macro_expand++;
2227    for (;;)
2228      {
2229         token = cpp_get_token(pfile);
2230         switch (token)
2231           {
2232           case CPP_EOF:
2233              goto done;
2234           case CPP_POP:
2235              /* If we've hit end of file, it's an error (reported by caller).
2236               * Ditto if it's the end of cpp_expand_to_buffer text.
2237               * If we've hit end of macro, just continue.  */
2238              if (!CPP_IS_MACRO_BUFFER(CPP_BUFFER(pfile)))
2239                 goto done;
2240              break;
2241           case CPP_LPAREN:
2242              paren++;
2243              break;
2244           case CPP_RPAREN:
2245              if (--paren < 0)
2246                 goto found;
2247              break;
2248           case CPP_COMMA:
2249              /* if we've returned to lowest level and
2250               * we aren't absorbing all args */
2251              if (paren == 0 && rest_args == 0)
2252                 goto found;
2253              break;
2254            found:
2255              /* Remove ',' or ')' from argument buffer. */
2256              CPP_ADJUST_WRITTEN(pfile, -1);
2257              goto done;
2258           default:;
2259           }
2260      }
2261
2262  done:
2263    CPP_OPTIONS(pfile)->put_out_comments = save_put_out_comments;
2264    pfile->no_macro_expand--;
2265
2266    return token;
2267 }
2268
2269 /* Turn newlines to spaces in the string of length LENGTH at START,
2270  * except inside of string constants.
2271  * The string is copied into itself with its beginning staying fixed.  */
2272
2273 static int
2274 change_newlines(unsigned char *start, int length)
2275 {
2276    unsigned char      *ibp;
2277    unsigned char      *obp;
2278    unsigned char      *limit;
2279    int                 c;
2280
2281    ibp = start;
2282    limit = start + length;
2283    obp = start;
2284
2285    while (ibp < limit)
2286      {
2287         *obp++ = c = *ibp++;
2288         switch (c)
2289           {
2290
2291           case '\'':
2292           case '\"':
2293              /* Notice and skip strings, so that we don't delete newlines in them.  */
2294              {
2295                 int                 quotec = c;
2296
2297                 while (ibp < limit)
2298                   {
2299                      *obp++ = c = *ibp++;
2300                      if (c == quotec)
2301                         break;
2302                      if (c == '\n' && quotec == '\'')
2303                         break;
2304                   }
2305              }
2306              break;
2307           }
2308      }
2309
2310    return obp - start;
2311 }
2312
2313 static struct tm   *
2314 timestamp(cpp_reader * pfile)
2315 {
2316    if (!pfile->timebuf)
2317      {
2318         time_t              t = time((time_t *) 0);
2319
2320         pfile->timebuf = localtime(&t);
2321      }
2322    return pfile->timebuf;
2323 }
2324
2325 static const char  *monthnames[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2326    "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
2327 };
2328
2329 /*
2330  * expand things like __FILE__.  Place the expansion into the output
2331  * buffer *without* rescanning.
2332  */
2333
2334 static void
2335 special_symbol(HASHNODE * hp, cpp_reader * pfile)
2336 {
2337    const char         *buf;
2338    char               *bufx;
2339    int                 len;
2340    int                 true_indepth;
2341    cpp_buffer         *ip = NULL;
2342    struct tm          *timebuf;
2343
2344    int                 paren = 0;       /* For special `defined' keyword */
2345
2346    for (ip = CPP_BUFFER(pfile);; ip = CPP_PREV_BUFFER(ip))
2347      {
2348         if (ip == NULL)
2349           {
2350              cpp_error(pfile, "cccp error: not in any file?!");
2351              return;            /* the show must go on */
2352           }
2353         if (ip->fname != NULL)
2354            break;
2355      }
2356
2357    switch (hp->type)
2358      {
2359      case T_FILE:
2360      case T_BASE_FILE:
2361         {
2362            const char         *string;
2363
2364            if (hp->type == T_BASE_FILE)
2365              {
2366                 while (CPP_PREV_BUFFER(ip))
2367                    ip = CPP_PREV_BUFFER(ip);
2368              }
2369            string = ip->nominal_fname;
2370
2371            if (!string)
2372               string = "";
2373            CPP_RESERVE(pfile, 3 + 4 * strlen(string));
2374            quote_string(pfile, string);
2375            return;
2376         }
2377
2378      case T_INCLUDE_LEVEL:
2379         true_indepth = 0;
2380         for (ip = CPP_BUFFER(pfile); ip != NULL; ip = CPP_PREV_BUFFER(ip))
2381            if (ip->fname != NULL)
2382               true_indepth++;
2383
2384         bufx = (char *)alloca(8);       /* Eight bytes ought to be more than enough */
2385         sprintf(bufx, "%d", true_indepth - 1);
2386         buf = bufx;
2387         break;
2388
2389      case T_VERSION:
2390         bufx = (char *)alloca(3 + strlen(version_string));
2391         sprintf(bufx, "\"%s\"", version_string);
2392         buf = bufx;
2393         break;
2394
2395 #ifndef NO_BUILTIN_SIZE_TYPE
2396      case T_SIZE_TYPE:
2397         buf = SIZE_TYPE;
2398         break;
2399 #endif
2400
2401 #ifndef NO_BUILTIN_PTRDIFF_TYPE
2402      case T_PTRDIFF_TYPE:
2403         buf = PTRDIFF_TYPE;
2404         break;
2405 #endif
2406
2407      case T_WCHAR_TYPE:
2408         buf = CPP_WCHAR_TYPE(pfile);
2409         break;
2410
2411      case T_USER_LABEL_PREFIX_TYPE:
2412         buf = USER_LABEL_PREFIX;
2413         break;
2414
2415      case T_REGISTER_PREFIX_TYPE:
2416         buf = REGISTER_PREFIX;
2417         break;
2418
2419      case T_CONST:
2420         bufx = (char *)alloca(4 * sizeof(int));
2421         sprintf(bufx, "%d", hp->value.ival);
2422         buf = bufx;
2423         break;
2424
2425      case T_SPECLINE:
2426         {
2427            long                line = ip->lineno;
2428            long                col = ip->colno;
2429
2430            adjust_position(CPP_LINE_BASE(ip), ip->cur, &line, &col);
2431
2432            bufx = (char *)alloca(10);
2433            sprintf(bufx, "%d", (int)line);
2434            buf = bufx;
2435         }
2436         break;
2437
2438      case T_DATE:
2439      case T_TIME:
2440         bufx = (char *)alloca(20);
2441         timebuf = timestamp(pfile);
2442         if (hp->type == T_DATE)
2443            sprintf(bufx, "\"%s %2d %4d\"", monthnames[timebuf->tm_mon],
2444                    timebuf->tm_mday, timebuf->tm_year + 1900);
2445         else
2446            sprintf(bufx, "\"%02d:%02d:%02d\"", timebuf->tm_hour,
2447                    timebuf->tm_min, timebuf->tm_sec);
2448         buf = bufx;
2449         break;
2450
2451      case T_SPEC_DEFINED:
2452         buf = " 0 ";            /* Assume symbol is not defined */
2453         ip = CPP_BUFFER(pfile);
2454         SKIP_WHITE_SPACE(ip->cur);
2455         if (*ip->cur == '(')
2456           {
2457              paren++;
2458              ip->cur++;         /* Skip over the paren */
2459              SKIP_WHITE_SPACE(ip->cur);
2460           }
2461         if (!is_idstart[*ip->cur])
2462            goto oops;
2463         if ((hp = cpp_lookup((const char *)ip->cur, -1, -1)))
2464           {
2465              buf = " 1 ";
2466           }
2467         while (is_idchar[*ip->cur])
2468            ++ip->cur;
2469         SKIP_WHITE_SPACE(ip->cur);
2470         if (paren)
2471           {
2472              if (*ip->cur != ')')
2473                 goto oops;
2474              ++ip->cur;
2475           }
2476         break;
2477
2478       oops:
2479
2480         cpp_error(pfile, "`defined' without an identifier");
2481         break;
2482
2483      default:
2484         cpp_error(pfile, "cccp error: invalid special hash type");      /* time for gdb */
2485         abort();
2486      }
2487    len = strlen(buf);
2488    CPP_RESERVE(pfile, len + 1);
2489    CPP_PUTS_Q(pfile, buf, len);
2490    CPP_NUL_TERMINATE_Q(pfile);
2491
2492    return;
2493 }
2494
2495 /* Initialize the built-in macros.  */
2496
2497 static void
2498 initialize_builtins(cpp_reader * pfile)
2499 {
2500    install("__LINE__", -1, T_SPECLINE, 0, 0, -1);
2501    install("__DATE__", -1, T_DATE, 0, 0, -1);
2502    install("__FILE__", -1, T_FILE, 0, 0, -1);
2503    install("__BASE_FILE__", -1, T_BASE_FILE, 0, 0, -1);
2504    install("__INCLUDE_LEVEL__", -1, T_INCLUDE_LEVEL, 0, 0, -1);
2505    install("__VERSION__", -1, T_VERSION, 0, 0, -1);
2506 #ifndef NO_BUILTIN_SIZE_TYPE
2507    install("__SIZE_TYPE__", -1, T_SIZE_TYPE, 0, 0, -1);
2508 #endif
2509 #ifndef NO_BUILTIN_PTRDIFF_TYPE
2510    install("__PTRDIFF_TYPE__ ", -1, T_PTRDIFF_TYPE, 0, 0, -1);
2511 #endif
2512    install("__WCHAR_TYPE__", -1, T_WCHAR_TYPE, 0, 0, -1);
2513    install("__USER_LABEL_PREFIX__", -1, T_USER_LABEL_PREFIX_TYPE, 0, 0, -1);
2514    install("__REGISTER_PREFIX__", -1, T_REGISTER_PREFIX_TYPE, 0, 0, -1);
2515    install("__TIME__", -1, T_TIME, 0, 0, -1);
2516    if (!CPP_TRADITIONAL(pfile))
2517       install("__STDC__", -1, T_CONST, STDC_VALUE, 0, -1);
2518    if (CPP_OPTIONS(pfile)->objc)
2519       install("__OBJC__", -1, T_CONST, 1, 0, -1);
2520 /*  This is supplied using a -D by the compiler driver
2521  * so that it is present only when truly compiling with GNU C.  */
2522 /*  install ("__GNUC__", -1, T_CONST, 2, 0, -1);  */
2523
2524    if (CPP_OPTIONS(pfile)->debug_output)
2525      {
2526         char                directive[2048];
2527         struct directive   *dp = &directive_table[0];
2528         struct tm          *timebuf = timestamp(pfile);
2529         cpp_buffer         *pbuffer = CPP_BUFFER(pfile);
2530
2531         while (CPP_PREV_BUFFER(pbuffer))
2532            pbuffer = CPP_PREV_BUFFER(pbuffer);
2533         sprintf(directive, " __BASE_FILE__ \"%s\"\n", pbuffer->nominal_fname);
2534         output_line_command(pfile, 0, same_file);
2535         pass_thru_directive(directive, &directive[strlen(directive)], pfile,
2536                             dp);
2537
2538         sprintf(directive, " __VERSION__ \"%s\"\n", version_string);
2539         output_line_command(pfile, 0, same_file);
2540         pass_thru_directive(directive, &directive[strlen(directive)], pfile,
2541                             dp);
2542
2543 #ifndef NO_BUILTIN_SIZE_TYPE
2544         sprintf(directive, " __SIZE_TYPE__ %s\n", SIZE_TYPE);
2545         output_line_command(pfile, 0, same_file);
2546         pass_thru_directive(directive, &directive[strlen(directive)], pfile,
2547                             dp);
2548 #endif
2549
2550 #ifndef NO_BUILTIN_PTRDIFF_TYPE
2551         sprintf(directive, " __PTRDIFF_TYPE__ %s\n", PTRDIFF_TYPE);
2552         output_line_command(pfile, 0, same_file);
2553         pass_thru_directive(directive, &directive[strlen(directive)], pfile,
2554                             dp);
2555 #endif
2556
2557         sprintf(directive, " __WCHAR_TYPE__ %s\n", CPP_WCHAR_TYPE(pfile));
2558         output_line_command(pfile, 0, same_file);
2559         pass_thru_directive(directive, &directive[strlen(directive)], pfile,
2560                             dp);
2561
2562         sprintf(directive, " __DATE__ \"%s %2d %4d\"\n",
2563                 monthnames[timebuf->tm_mon],
2564                 timebuf->tm_mday, timebuf->tm_year + 1900);
2565         output_line_command(pfile, 0, same_file);
2566         pass_thru_directive(directive, &directive[strlen(directive)], pfile,
2567                             dp);
2568
2569         sprintf(directive, " __TIME__ \"%02d:%02d:%02d\"\n",
2570                 timebuf->tm_hour, timebuf->tm_min, timebuf->tm_sec);
2571         output_line_command(pfile, 0, same_file);
2572         pass_thru_directive(directive, &directive[strlen(directive)], pfile,
2573                             dp);
2574
2575         if (!CPP_TRADITIONAL(pfile))
2576           {
2577              sprintf(directive, " __STDC__ 1");
2578              output_line_command(pfile, 0, same_file);
2579              pass_thru_directive(directive, &directive[strlen(directive)],
2580                                  pfile, dp);
2581           }
2582         if (CPP_OPTIONS(pfile)->objc)
2583           {
2584              sprintf(directive, " __OBJC__ 1");
2585              output_line_command(pfile, 0, same_file);
2586              pass_thru_directive(directive, &directive[strlen(directive)],
2587                                  pfile, dp);
2588           }
2589      }
2590 }
2591
2592 /* Return 1 iff a token ending in C1 followed directly by a token C2
2593  * could cause mis-tokenization. */
2594
2595 static int
2596 unsafe_chars(int c1, int c2)
2597 {
2598    switch (c1)
2599      {
2600      case '+':
2601      case '-':
2602         if (c2 == c1 || c2 == '=')
2603            return 1;
2604         goto letter;
2605      case '.':
2606      case '0':
2607      case '1':
2608      case '2':
2609      case '3':
2610      case '4':
2611      case '5':
2612      case '6':
2613      case '7':
2614      case '8':
2615      case '9':
2616      case 'e':
2617      case 'E':
2618         if (c2 == '-' || c2 == '+')
2619            return 1;            /* could extend a pre-processing number */
2620         goto letter;
2621      case 'L':
2622         if (c2 == '\'' || c2 == '\"')
2623            return 1;            /* Could turn into L"xxx" or L'xxx'. */
2624         goto letter;
2625       letter:
2626      case '_':
2627      case 'a':
2628      case 'b':
2629      case 'c':
2630      case 'd':
2631      case 'f':
2632      case 'g':
2633      case 'h':
2634      case 'i':
2635      case 'j':
2636      case 'k':
2637      case 'l':
2638      case 'm':
2639      case 'n':
2640      case 'o':
2641      case 'p':
2642      case 'q':
2643      case 'r':
2644      case 's':
2645      case 't':
2646      case 'u':
2647      case 'v':
2648      case 'w':
2649      case 'x':
2650      case 'y':
2651      case 'z':
2652      case 'A':
2653      case 'B':
2654      case 'C':
2655      case 'D':
2656      case 'F':
2657      case 'G':
2658      case 'H':
2659      case 'I':
2660      case 'J':
2661      case 'K':
2662      case 'M':
2663      case 'N':
2664      case 'O':
2665      case 'P':
2666      case 'Q':
2667      case 'R':
2668      case 'S':
2669      case 'T':
2670      case 'U':
2671      case 'V':
2672      case 'W':
2673      case 'X':
2674      case 'Y':
2675      case 'Z':
2676         /* We're in the middle of either a name or a pre-processing number. */
2677         return (is_idchar[c2] || c2 == '.');
2678      case '<':
2679      case '>':
2680      case '!':
2681      case '%':
2682      case '#':
2683      case ':':
2684      case '^':
2685      case '&':
2686      case '|':
2687      case '*':
2688      case '/':
2689      case '=':
2690         return (c2 == c1 || c2 == '=');
2691      }
2692    return 0;
2693 }
2694
2695 /* Expand a macro call.
2696  * HP points to the symbol that is the macro being called.
2697  * Put the result of expansion onto the input stack
2698  * so that subsequent input by our caller will use it.
2699  * 
2700  * If macro wants arguments, caller has already verified that
2701  * an argument list follows; arguments come from the input stack.  */
2702
2703 static void
2704 macroexpand(cpp_reader * pfile, HASHNODE * hp)
2705 {
2706    int                 nargs;
2707    DEFINITION         *defn = hp->value.defn;
2708    unsigned char      *xbuf;
2709    long                start_line, start_column;
2710    int                 xbuf_len;
2711    struct argdata     *args;
2712    long                old_written = CPP_WRITTEN(pfile);
2713
2714    int                 rest_args, rest_zero;
2715    int                 i;
2716
2717    pfile->output_escapes++;
2718    cpp_buf_line_and_col(cpp_file_buffer(pfile), &start_line, &start_column);
2719
2720    rest_zero = 0;
2721    args = NULL;
2722    nargs = defn->nargs;
2723
2724    if (nargs >= 0)
2725      {
2726         enum cpp_token      token;
2727
2728         token = CPP_OTHER;
2729
2730         args = (struct argdata *)alloca((nargs + 1) * sizeof(struct argdata));
2731
2732         for (i = 0; i < nargs; i++)
2733           {
2734              args[i].raw = args[i].expanded = 0;
2735              args[i].raw_length = 0;
2736              args[i].expand_length = args[i].stringified_length = -1;
2737              args[i].use_count = 0;
2738           }
2739
2740         /* Parse all the macro args that are supplied.  I counts them.
2741          * The first NARGS args are stored in ARGS.
2742          * The rest are discarded.  If rest_args is set then we assume
2743          * macarg absorbed the rest of the args. */
2744         i = 0;
2745         rest_args = 0;
2746         rest_args = 0;
2747         FORWARD(1);             /* Discard the open-parenthesis before the first arg.  */
2748         do
2749           {
2750              if (rest_args)
2751                 continue;
2752              if (i < nargs || (nargs == 0 && i == 0))
2753                {
2754                   /* if we are working on last arg which absorbs rest of args... */
2755                   if (i == nargs - 1 && defn->rest_args)
2756                      rest_args = 1;
2757                   args[i].raw = CPP_WRITTEN(pfile);
2758                   token = macarg(pfile, rest_args);
2759                   args[i].raw_length = CPP_WRITTEN(pfile) - args[i].raw;
2760                   args[i].newlines = 0; /* FIXME */
2761                }
2762              else
2763                 token = macarg(pfile, 0);
2764              if (token == CPP_EOF || token == CPP_POP)
2765                {
2766                   cpp_error_with_line(pfile, start_line, start_column,
2767                                       "unterminated macro call");
2768                   return;
2769                }
2770              i++;
2771           }
2772         while (token == CPP_COMMA);
2773
2774         /* If we got one arg but it was just whitespace, call that 0 args.  */
2775         if (i == 1)
2776           {
2777              unsigned char      *bp = ARG_BASE + args[0].raw;
2778              unsigned char      *lim = bp + args[0].raw_length;
2779
2780              /* cpp.texi says for foo ( ) we provide one argument.
2781               * However, if foo wants just 0 arguments, treat this as 0.  */
2782              if (nargs == 0)
2783                 while (bp != lim && is_space[*bp])
2784                    bp++;
2785              if (bp == lim)
2786                 i = 0;
2787           }
2788         /* Don't output an error message if we have already output one for
2789          * a parse error above.  */
2790         if (nargs == 0 && i > 0)
2791           {
2792              cpp_error(pfile, "arguments given to macro `%s'", hp->name);
2793           }
2794         else if (i < nargs)
2795           {
2796              /* traditional C allows foo() if foo wants one argument.  */
2797              if (nargs == 1 && i == 0 && CPP_TRADITIONAL(pfile));
2798              /* the rest args token is allowed to absorb 0 tokens */
2799              else if (i == nargs - 1 && defn->rest_args)
2800                 rest_zero = 1;
2801              else if (i == 0)
2802                 cpp_error(pfile, "macro `%s' used without args", hp->name);
2803              else if (i == 1)
2804                 cpp_error(pfile, "macro `%s' used with just one arg", hp->name);
2805              else
2806                 cpp_error(pfile, "macro `%s' used with only %d args",
2807                           hp->name, i);
2808           }
2809         else if (i > nargs)
2810           {
2811              cpp_error(pfile,
2812                        "macro `%s' used with too many (%d) args", hp->name, i);
2813           }
2814      }
2815    /* If macro wants zero args, we parsed the arglist for checking only.
2816     * Read directly from the macro definition.  */
2817    if (nargs <= 0)
2818      {
2819         xbuf = defn->expansion;
2820         xbuf_len = defn->length;
2821      }
2822    else
2823      {
2824         unsigned char      *exp = defn->expansion;
2825         int                 offset;     /* offset in expansion,
2826                                          * copied a piece at a time */
2827         int                 totlen;     /* total amount of exp buffer filled so far */
2828
2829         struct reflist     *ap, *last_ap;
2830
2831         /* Macro really takes args.  Compute the expansion of this call.  */
2832
2833         /* Compute length in characters of the macro's expansion.
2834          * Also count number of times each arg is used.  */
2835         xbuf_len = defn->length;
2836         for (ap = defn->pattern; ap != NULL; ap = ap->next)
2837           {
2838              if (ap->stringify)
2839                {
2840                   struct argdata     *arg = &args[ap->argno];
2841
2842                   /* Stringify it it hasn't already been */
2843                   if (arg->stringified_length < 0)
2844                     {
2845                        int                 arglen = arg->raw_length;
2846                        int                 escaped = 0;
2847                        int                 in_string = 0;
2848                        int                 c;
2849
2850                        /* Initially need_space is -1.  Otherwise, 1 means the
2851                         * previous character was a space, but we suppressed it;
2852                         * 0 means the previous character was a non-space. */
2853                        int                 need_space = -1;
2854
2855                        i = 0;
2856                        arg->stringified = CPP_WRITTEN(pfile);
2857                        if (!CPP_TRADITIONAL(pfile))
2858                           CPP_PUTC(pfile, '\"');        /* insert beginning quote */
2859                        for (; i < arglen; i++)
2860                          {
2861                             c = (ARG_BASE + arg->raw)[i];
2862
2863                             if (!in_string)
2864                               {
2865                                  /* Internal sequences of whitespace are replaced by
2866                                   * one space except within an string or char token. */
2867                                  if (is_space[c])
2868                                    {
2869                                       if (CPP_WRITTEN(pfile) > arg->stringified
2870                                           && (CPP_PWRITTEN(pfile))[-1] == '@')
2871                                         {
2872                                            /* "@ " escape markers are removed */
2873                                            CPP_ADJUST_WRITTEN(pfile, -1);
2874                                            continue;
2875                                         }
2876                                       if (need_space == 0)
2877                                          need_space = 1;
2878                                       continue;
2879                                    }
2880                                  else if (need_space > 0)
2881                                     CPP_PUTC(pfile, ' ');
2882                                  need_space = 0;
2883                               }
2884                             if (escaped)
2885                                escaped = 0;
2886                             else
2887                               {
2888                                  if (c == '\\')
2889                                     escaped = 1;
2890                                  if (in_string)
2891                                    {
2892                                       if (c == in_string)
2893                                          in_string = 0;
2894                                    }
2895                                  else if (c == '\"' || c == '\'')
2896                                     in_string = c;
2897                               }
2898
2899                             /* Escape these chars */
2900                             if (c == '\"' || (in_string && c == '\\'))
2901                                CPP_PUTC(pfile, '\\');
2902                             if (isprint(c))
2903                                CPP_PUTC(pfile, c);
2904                             else
2905                               {
2906                                  CPP_RESERVE(pfile, 4);
2907                                  sprintf((char *)CPP_PWRITTEN(pfile), "\\%03o",
2908                                          (unsigned int)c);
2909                                  CPP_ADJUST_WRITTEN(pfile, 4);
2910                               }
2911                          }
2912                        if (!CPP_TRADITIONAL(pfile))
2913                           CPP_PUTC(pfile, '\"');        /* insert ending quote */
2914                        arg->stringified_length
2915                           = CPP_WRITTEN(pfile) - arg->stringified;
2916                     }
2917                   xbuf_len += args[ap->argno].stringified_length;
2918                }
2919              else if (ap->raw_before || ap->raw_after || CPP_TRADITIONAL(pfile))
2920                 /* Add 4 for two newline-space markers to prevent
2921                  * token concatenation.  */
2922                 xbuf_len += args[ap->argno].raw_length + 4;
2923              else
2924                {
2925                   /* We have an ordinary (expanded) occurrence of the arg.
2926                    * So compute its expansion, if we have not already.  */
2927                   if (args[ap->argno].expand_length < 0)
2928                     {
2929                        args[ap->argno].expanded = CPP_WRITTEN(pfile);
2930                        cpp_expand_to_buffer(pfile,
2931                                             ARG_BASE + args[ap->argno].raw,
2932                                             args[ap->argno].raw_length);
2933
2934                        args[ap->argno].expand_length
2935                           = CPP_WRITTEN(pfile) - args[ap->argno].expanded;
2936                     }
2937                   /* Add 4 for two newline-space markers to prevent
2938                    * token concatenation.  */
2939                   xbuf_len += args[ap->argno].expand_length + 4;
2940                }
2941              if (args[ap->argno].use_count < 10)
2942                 args[ap->argno].use_count++;
2943           }
2944
2945         xbuf = (unsigned char *)xmalloc(xbuf_len + 1);
2946
2947         /* Generate in XBUF the complete expansion
2948          * with arguments substituted in.
2949          * TOTLEN is the total size generated so far.
2950          * OFFSET is the index in the definition
2951          * of where we are copying from.  */
2952         offset = totlen = 0;
2953         for (last_ap = NULL, ap = defn->pattern; ap != NULL;
2954              last_ap = ap, ap = ap->next)
2955           {
2956              struct argdata     *arg = &args[ap->argno];
2957              int                 count_before = totlen;
2958
2959              /* Add chars to XBUF.  */
2960              for (i = 0; i < ap->nchars; i++, offset++)
2961                 xbuf[totlen++] = exp[offset];
2962
2963              /* If followed by an empty rest arg with concatenation,
2964               * delete the last run of nonwhite chars.  */
2965              if (rest_zero && totlen > count_before
2966                  && ((ap->rest_args && ap->raw_before)
2967                      || (last_ap != NULL && last_ap->rest_args
2968                          && last_ap->raw_after)))
2969                {
2970                   /* Delete final whitespace.  */
2971                   while (totlen > count_before && is_space[xbuf[totlen - 1]])
2972                      totlen--;
2973
2974                   /* Delete the nonwhites before them.  */
2975                   while (totlen > count_before && !is_space[xbuf[totlen - 1]])
2976                      totlen--;
2977                }
2978              if (ap->stringify != 0)
2979                {
2980                   memcpy(xbuf + totlen, ARG_BASE + arg->stringified,
2981                          arg->stringified_length);
2982                   totlen += arg->stringified_length;
2983                }
2984              else if (ap->raw_before || ap->raw_after || CPP_TRADITIONAL(pfile))
2985                {
2986                   unsigned char      *p1 = ARG_BASE + arg->raw;
2987                   unsigned char      *l1 = p1 + arg->raw_length;
2988
2989                   if (ap->raw_before)
2990                     {
2991                        while (p1 != l1 && is_space[*p1])
2992                           p1++;
2993                        while (p1 != l1 && is_idchar[*p1])
2994                           xbuf[totlen++] = *p1++;
2995                     }
2996                   if (ap->raw_after)
2997                     {
2998                        /* Arg is concatenated after: delete trailing whitespace,
2999                         * whitespace markers, and no-reexpansion markers.  */
3000                        while (p1 != l1)
3001                          {
3002                             if (is_space[l1[-1]])
3003                                l1--;
3004                             else if (l1[-1] == '-')
3005                               {
3006                                  unsigned char      *p2 = l1 - 1;
3007
3008                                  /* If a `-' is preceded by an odd number of newlines then it
3009                                   * and the last newline are a no-reexpansion marker.  */
3010                                  while (p2 != p1 && p2[-1] == '\n')
3011                                     p2--;
3012                                  if ((l1 - 1 - p2) & 1)
3013                                    {
3014                                       l1 -= 2;
3015                                    }
3016                                  else
3017                                     break;
3018                               }
3019                             else
3020                                break;
3021                          }
3022                     }
3023                   memcpy(xbuf + totlen, p1, l1 - p1);
3024                   totlen += l1 - p1;
3025                }
3026              else
3027                {
3028                   unsigned char      *expanded = ARG_BASE + arg->expanded;
3029
3030                   if (!ap->raw_before && totlen > 0 && arg->expand_length
3031                       && !CPP_TRADITIONAL(pfile)
3032                       && unsafe_chars(xbuf[totlen - 1], expanded[0]))
3033                     {
3034                        xbuf[totlen++] = '@';
3035                        xbuf[totlen++] = ' ';
3036                     }
3037                   memcpy(xbuf + totlen, expanded, arg->expand_length);
3038                   totlen += arg->expand_length;
3039
3040                   if (!ap->raw_after && totlen > 0 && offset < defn->length
3041                       && !CPP_TRADITIONAL(pfile)
3042                       && unsafe_chars(xbuf[totlen - 1], exp[offset]))
3043                     {
3044                        xbuf[totlen++] = '@';
3045                        xbuf[totlen++] = ' ';
3046                     }
3047                   /* If a macro argument with newlines is used multiple times,
3048                    * then only expand the newlines once.  This avoids creating
3049                    * output lines which don't correspond to any input line,
3050                    * which confuses gdb and gcov.  */
3051                   if (arg->use_count > 1 && arg->newlines > 0)
3052                     {
3053                        /* Don't bother doing change_newlines for subsequent
3054                         * uses of arg.  */
3055                        arg->use_count = 1;
3056                        arg->expand_length
3057                           = change_newlines(expanded, arg->expand_length);
3058                     }
3059                }
3060
3061              if (totlen > xbuf_len)
3062                 abort();
3063           }
3064
3065         /* if there is anything left of the definition
3066          * after handling the arg list, copy that in too. */
3067
3068         for (i = offset; i < defn->length; i++)
3069           {
3070              /* if we've reached the end of the macro */
3071              if (exp[i] == ')')
3072                 rest_zero = 0;
3073              if (!(rest_zero && last_ap != NULL && last_ap->rest_args
3074                    && last_ap->raw_after))
3075                 xbuf[totlen++] = exp[i];
3076           }
3077
3078         xbuf[totlen] = 0;
3079         xbuf_len = totlen;
3080
3081      }
3082
3083    pfile->output_escapes--;
3084
3085    /* Now put the expansion on the input stack
3086     * so our caller will commence reading from it.  */
3087    push_macro_expansion(pfile, xbuf, xbuf_len, hp);
3088    CPP_BUFFER(pfile)->has_escapes = 1;
3089
3090    /* Pop the space we've used in the token_buffer for argument expansion. */
3091    CPP_SET_WRITTEN(pfile, old_written);
3092
3093    /* Recursive macro use sometimes works traditionally.
3094     * #define foo(x,y) bar (x (y,0), y)
3095     * foo (foo, baz)  */
3096
3097    if (!CPP_TRADITIONAL(pfile))
3098       hp->type = T_DISABLED;
3099 }
3100
3101 static void
3102 push_macro_expansion(cpp_reader * pfile, unsigned char *xbuf, int xbuf_len,
3103                      HASHNODE * hp)
3104 {
3105    cpp_buffer         *mbuf = cpp_push_buffer(pfile, xbuf, xbuf_len);
3106
3107    mbuf->cleanup = macro_cleanup;
3108    mbuf->data = hp;
3109
3110    /* The first chars of the expansion should be a "@ " added by
3111     * collect_expansion.  This is to prevent accidental token-pasting
3112     * between the text preceding the macro invocation, and the macro
3113     * expansion text.
3114     * 
3115     * We would like to avoid adding unneeded spaces (for the sake of
3116     * tools that use cpp, such as imake).  In some common cases we can
3117     * tell that it is safe to omit the space.
3118     * 
3119     * The character before the macro invocation cannot have been an
3120     * idchar (or else it would have been pasted with the idchars of
3121     * the macro name).  Therefore, if the first non-space character
3122     * of the expansion is an idchar, we do not need the extra space
3123     * to prevent token pasting.
3124     * 
3125     * Also, we don't need the extra space if the first char is '(',
3126     * or some other (less common) characters.  */
3127
3128    if (xbuf[0] == '@' && xbuf[1] == ' '
3129        && (is_idchar[xbuf[2]] || xbuf[2] == '(' || xbuf[2] == '\''
3130            || xbuf[2] == '\"'))
3131       mbuf->cur += 2;
3132 }
3133
3134 /* Like cpp_get_token, except that it does not read past end-of-line.
3135  * Also, horizontal space is skipped, and macros are popped.  */
3136
3137 static enum cpp_token
3138 get_directive_token(cpp_reader * pfile)
3139 {
3140    for (;;)
3141      {
3142         long                old_written = CPP_WRITTEN(pfile);
3143         enum cpp_token      token;
3144
3145         cpp_skip_hspace(pfile);
3146         if (PEEKC() == '\n')
3147            return CPP_VSPACE;
3148         token = cpp_get_token(pfile);
3149         switch (token)
3150           {
3151           case CPP_POP:
3152              if (!CPP_IS_MACRO_BUFFER(CPP_BUFFER(pfile)))
3153                 return token;
3154              /* ... else fall though ... */
3155           case CPP_HSPACE:
3156           case CPP_COMMENT:
3157              CPP_SET_WRITTEN(pfile, old_written);
3158              break;
3159           default:
3160              return token;
3161           }
3162      }
3163 }
3164
3165 /* Handle #include and #import.
3166  * This function expects to see "fname" or <fname> on the input.
3167  * 
3168  * The input is normally in part of the output_buffer following
3169  * CPP_WRITTEN, and will get overwritten by output_line_command.
3170  * I.e. in input file specification has been popped by handle_directive.
3171  * This is safe. */
3172
3173 static int
3174 do_include(cpp_reader * pfile, struct directive *keyword,
3175            unsigned char *unused1, unsigned char *unused2)
3176 {
3177    int                 importing = (keyword->type == T_IMPORT);
3178    int                 skip_dirs = (keyword->type == T_INCLUDE_NEXT);
3179    char               *fname;   /* Dynamically allocated fname buffer */
3180    char               *pcftry;
3181    unsigned char      *fbeg, *fend;     /* Beginning and end of fname */
3182    enum cpp_token      token;
3183
3184    /* Chain of dirs to search */
3185    struct file_name_list *search_start = CPP_OPTIONS(pfile)->include;
3186    struct file_name_list dsp[1];        /* First in chain, if #include "..." */
3187    struct file_name_list *searchptr = 0;
3188    long                old_written = CPP_WRITTEN(pfile);
3189
3190    int                 flen;
3191
3192    int                 f;       /* file number */
3193
3194    int                 angle_brackets = 0;      /* 0 for "...", 1 for <...> */
3195    char               *pcfbuf;
3196    int                 pcfnum;
3197
3198    f = -1;                      /* JF we iz paranoid! */
3199
3200    unused1 = NULL;
3201    unused2 = NULL;
3202    if (importing && CPP_OPTIONS(pfile)->warn_import
3203        && !CPP_OPTIONS(pfile)->inhibit_warnings
3204        && !CPP_BUFFER(pfile)->system_header_p && !pfile->import_warning)
3205      {
3206         pfile->import_warning = 1;
3207         cpp_warning(pfile, "using `#import' is not recommended");
3208         fprintf(stderr,
3209                 "The fact that a certain header file need not be processed more than once\n");
3210         fprintf(stderr,
3211                 "should be indicated in the header file, not where it is used.\n");
3212         fprintf(stderr,
3213                 "The best way to do this is with a conditional of this form:\n\n");
3214         fprintf(stderr, "  #ifndef _FOO_H_INCLUDED\n");
3215         fprintf(stderr, "  #define _FOO_H_INCLUDED\n");
3216         fprintf(stderr, "  ... <real contents of file> ...\n");
3217         fprintf(stderr, "  #endif /* Not _FOO_H_INCLUDED */\n\n");
3218         fprintf(stderr, "Then users can use `#include' any number of times.\n");
3219         fprintf(stderr,
3220                 "GNU C automatically avoids processing the file more than once\n");
3221         fprintf(stderr, "when it is equipped with such a conditional.\n");
3222      }
3223    pfile->parsing_include_directive++;
3224    token = get_directive_token(pfile);
3225    pfile->parsing_include_directive--;
3226
3227    if (token == CPP_STRING)
3228      {
3229         /* FIXME - check no trailing garbage */
3230         fbeg = pfile->token_buffer + old_written + 1;
3231         fend = CPP_PWRITTEN(pfile) - 1;
3232         if (fbeg[-1] == '<')
3233           {
3234              angle_brackets = 1;
3235              /* If -I-, start with the first -I dir after the -I-.  */
3236              if (CPP_OPTIONS(pfile)->first_bracket_include)
3237                 search_start = CPP_OPTIONS(pfile)->first_bracket_include;
3238           }
3239         /* If -I- was specified, don't search current dir, only spec'd ones. */
3240         else if (!CPP_OPTIONS(pfile)->ignore_srcdir)
3241           {
3242              cpp_buffer         *fp;
3243
3244              /* We have "filename".  Figure out directory this source
3245               * file is coming from and put it on the front of the list. */
3246
3247              for (fp = CPP_BUFFER(pfile); fp != NULL; fp = CPP_PREV_BUFFER(fp))
3248                {
3249                   int                 n;
3250                   const char         *ep, *nam;
3251
3252                   if ((nam = fp->nominal_fname) != NULL)
3253                     {
3254                        /* Found a named file.  Figure out dir of the file,
3255                         * and put it in front of the search list.  */
3256                        dsp[0].next = search_start;
3257                        search_start = dsp;
3258 #ifndef VMS
3259                        ep = strrchr(nam, '/');
3260 #else /* VMS */
3261                        ep = strrchr(nam, ']');
3262                        if (ep == NULL)
3263                           ep = strrchr(nam, '>');
3264                        if (ep == NULL)
3265                           ep = strrchr(nam, ':');
3266                        if (ep != NULL)
3267                           ep++;
3268 #endif /* VMS */
3269                        if (ep != NULL)
3270                          {
3271                             n = ep - nam;
3272                             dsp[0].fname = (char *)alloca(n + 1);
3273                             strncpy(dsp[0].fname, nam, n);
3274                             dsp[0].fname[n] = '\0';
3275                             if (n + INCLUDE_LEN_FUDGE > pfile->max_include_len)
3276                                pfile->max_include_len = n + INCLUDE_LEN_FUDGE;
3277                          }
3278                        else
3279                          {
3280                             dsp[0].fname = 0;   /* Current directory */
3281                          }
3282                        dsp[0].got_name_map = 0;
3283                        break;
3284                     }
3285                }
3286           }
3287      }
3288    else
3289      {
3290         cpp_error(pfile,
3291                   "`#%s' expects \"FILENAME\" or <FILENAME>", keyword->name);
3292         CPP_SET_WRITTEN(pfile, old_written);
3293         skip_rest_of_line(pfile);
3294         return 0;
3295      }
3296
3297    *fend = 0;
3298
3299    token = get_directive_token(pfile);
3300    if (token != CPP_VSPACE)
3301      {
3302         cpp_error(pfile, "junk at end of `#include'");
3303         while (token != CPP_VSPACE && token != CPP_EOF && token != CPP_POP)
3304            token = get_directive_token(pfile);
3305      }
3306    /* For #include_next, skip in the search path
3307     * past the dir in which the containing file was found.  */
3308    if (skip_dirs)
3309      {
3310         cpp_buffer         *fp;
3311
3312         for (fp = CPP_BUFFER(pfile); fp != NULL; fp = CPP_PREV_BUFFER(fp))
3313            if (fp->fname != NULL)
3314              {
3315                 /* fp->dir is null if the containing file was specified with
3316                  * an absolute file name.  In that case, don't skip anything.  */
3317                 if (fp->dir == SELF_DIR_DUMMY)
3318                    search_start = CPP_OPTIONS(pfile)->include;
3319                 else if (fp->dir)
3320                    search_start = fp->dir->next;
3321                 break;
3322              }
3323      }
3324    CPP_SET_WRITTEN(pfile, old_written);
3325
3326    flen = fend - fbeg;
3327
3328    if (flen == 0)
3329      {
3330         cpp_error(pfile, "empty file name in `#%s'", keyword->name);
3331         return 0;
3332      }
3333    /* Allocate this permanently, because it gets stored in the definitions
3334     * of macros.  */
3335    fname = (char *)xmalloc(pfile->max_include_len + flen + 4);
3336    /* + 2 above for slash and terminating null.  */
3337    /* + 2 added for '.h' on VMS (to support '#include filename') */
3338
3339    /* If specified file name is absolute, just open it.  */
3340
3341 #ifndef __EMX__
3342    if (*fbeg == '/')
3343 #else
3344    if (_fnisabs(fbeg))
3345 #endif
3346      {
3347         strncpy(fname, (const char *)fbeg, flen);
3348         fname[flen] = 0;
3349         if (redundant_include_p(pfile, fname))
3350            return 0;
3351         if (importing)
3352            f = lookup_import(pfile, fname, NULL);
3353         else
3354            f = open_include_file(pfile, fname, NULL);
3355         if (f == -2)
3356            return 0;            /* Already included this file */
3357      }
3358    else
3359      {
3360         /* Search directory path, trying to open the file.
3361          * Copy each filename tried into FNAME.  */
3362
3363         for (searchptr = search_start; searchptr; searchptr = searchptr->next)
3364           {
3365              if (searchptr->fname)
3366                {
3367                   /* The empty string in a search path is ignored.
3368                    * This makes it possible to turn off entirely
3369                    * a standard piece of the list.  */
3370                   if (searchptr->fname[0] == 0)
3371                      continue;
3372                   strcpy(fname, searchptr->fname);
3373                   strcat(fname, "/");
3374                   fname[strlen(fname) + flen] = 0;
3375                }
3376              else
3377                {
3378                   fname[0] = 0;
3379                }
3380              strncat(fname, (const char *)fbeg, flen);
3381 #ifdef VMS
3382              /* Change this 1/2 Unix 1/2 VMS file specification into a
3383               * full VMS file specification */
3384              if (searchptr->fname && (searchptr->fname[0] != 0))
3385                {
3386                   /* Fix up the filename */
3387                   hack_vms_include_specification(fname);
3388                }
3389              else
3390                {
3391                   /* This is a normal VMS filespec, so use it unchanged.  */
3392                   strncpy(fname, fbeg, flen);
3393                   fname[flen] = 0;
3394                   /* if it's '#include filename', add the missing .h */
3395                   if (strchr(fname, '.') == NULL)
3396                     {
3397                        strcat(fname, ".h");
3398                     }
3399                }
3400 #endif /* VMS */
3401              /* ??? There are currently 3 separate mechanisms for avoiding processing
3402               * of redundant include files: #import, #pragma once, and
3403               * redundant_include_p.  It would be nice if they were unified.  */
3404              if (redundant_include_p(pfile, fname))
3405                 return 0;
3406              if (importing)
3407                 f = lookup_import(pfile, fname, searchptr);
3408              else
3409                 f = open_include_file(pfile, fname, searchptr);
3410              if (f == -2)
3411                 return 0;       /* Already included this file */
3412 #ifdef EACCES
3413              else if (f == -1 && errno == EACCES)
3414                 cpp_warning(pfile, "Header file %s exists, but is not readable",
3415                             fname);
3416 #endif
3417              if (f >= 0)
3418                 break;
3419           }
3420      }
3421
3422    if (f < 0)
3423      {
3424         /* A file that was not found.  */
3425         strncpy(fname, (const char *)fbeg, flen);
3426         fname[flen] = 0;
3427         /* If generating dependencies and -MG was specified, we assume missing
3428          * files are leaf files, living in the same directory as the source file
3429          * or other similar place; these missing files may be generated from
3430          * other files and may not exist yet (eg: y.tab.h).  */
3431
3432         if (CPP_OPTIONS(pfile)->print_deps_missing_files
3433             && CPP_PRINT_DEPS(pfile)
3434             > (angle_brackets || (pfile->system_include_depth > 0)))
3435           {
3436              /* If it was requested as a system header file,
3437               * then assume it belongs in the first place to look for such.  */
3438              if (angle_brackets)
3439                {
3440                   for (searchptr = search_start; searchptr;
3441                        searchptr = searchptr->next)
3442                     {
3443                        if (searchptr->fname)
3444                          {
3445                             char               *p;
3446
3447                             if (searchptr->fname[0] == 0)
3448                                continue;
3449                             p = (char *)alloca(strlen(searchptr->fname)
3450                                                + strlen(fname) + 2);
3451                             strcpy(p, searchptr->fname);
3452                             strcat(p, "/");
3453                             strcat(p, fname);
3454                             deps_output(pfile, p, ' ');
3455                             break;
3456                          }
3457                     }
3458                }
3459              else
3460                {
3461                   /* Otherwise, omit the directory, as if the file existed
3462                    * in the directory with the source.  */
3463                   deps_output(pfile, fname, ' ');
3464                }
3465           }
3466         /* If -M was specified, and this header file won't be added to the
3467          * dependency list, then don't count this as an error, because we can
3468          * still produce correct output.  Otherwise, we can't produce correct
3469          * output, because there may be dependencies we need inside the missing
3470          * file, and we don't know what directory this missing file exists in. */
3471         else if (CPP_PRINT_DEPS(pfile)
3472                  && (CPP_PRINT_DEPS(pfile)
3473                      <= (angle_brackets || (pfile->system_include_depth > 0))))
3474            cpp_warning(pfile, "No include path in which to find %s", fname);
3475         else if (search_start)
3476            cpp_error_from_errno(pfile, fname);
3477         else
3478            cpp_error(pfile, "No include path in which to find %s", fname);
3479      }
3480    else
3481      {
3482         /* Check to see if this include file is a once-only include file.
3483          * If so, give up.  */
3484
3485         struct file_name_list *ptr;
3486
3487         for (ptr = pfile->dont_repeat_files; ptr; ptr = ptr->next)
3488           {
3489              if (!strcmp(ptr->fname, fname))
3490                {
3491                   close(f);
3492                   return 0;     /* This file was once'd. */
3493                }
3494           }
3495
3496         for (ptr = pfile->all_include_files; ptr; ptr = ptr->next)
3497           {
3498              if (!strcmp(ptr->fname, fname))
3499                 break;          /* This file was included before. */
3500           }
3501
3502         if (ptr == 0)
3503           {
3504              /* This is the first time for this file.  */
3505              /* Add it to list of files included.  */
3506
3507              ptr =
3508                 (struct file_name_list *)xmalloc(sizeof(struct file_name_list));
3509
3510              ptr->control_macro = 0;
3511              ptr->c_system_include_path = 0;
3512              ptr->next = pfile->all_include_files;
3513              pfile->all_include_files = ptr;
3514              ptr->fname = savestring(fname);
3515              ptr->got_name_map = 0;
3516
3517              /* For -M, add this file to the dependencies.  */
3518              if (CPP_PRINT_DEPS(pfile)
3519                  > (angle_brackets || (pfile->system_include_depth > 0)))
3520                 deps_output(pfile, fname, ' ');
3521           }
3522         /* Handle -H option.  */
3523         if (CPP_OPTIONS(pfile)->print_include_names)
3524           {
3525              cpp_buffer         *buf = CPP_BUFFER(pfile);
3526
3527              while ((buf = CPP_PREV_BUFFER(buf)) != NULL)
3528                 putc('.', stderr);
3529              fprintf(stderr, "%s\n", fname);
3530           }
3531         if (angle_brackets)
3532            pfile->system_include_depth++;
3533
3534         /* Actually process the file.  */
3535
3536         /* Record file on "seen" list for #import. */
3537         add_import(pfile, f, fname);
3538
3539         pcftry = (char *)alloca(strlen(fname) + 30);
3540         pcfbuf = 0;
3541         pcfnum = 0;
3542
3543         /* Actually process the file */
3544         cpp_push_buffer(pfile, NULL, 0);
3545         if (finclude(pfile, f, fname, is_system_include(pfile, fname),
3546                      searchptr != dsp ? searchptr : SELF_DIR_DUMMY))
3547           {
3548              output_line_command(pfile, 0, enter_file);
3549              pfile->only_seen_white = 2;
3550           }
3551         if (angle_brackets)
3552            pfile->system_include_depth--;
3553      }
3554    return 0;
3555 }
3556
3557 /* Return nonzero if there is no need to include file NAME
3558  * because it has already been included and it contains a conditional
3559  * to make a repeated include do nothing.  */
3560
3561 static int
3562 redundant_include_p(cpp_reader * pfile, char *name)
3563 {
3564    struct file_name_list *l = pfile->all_include_files;
3565
3566    for (; l; l = l->next)
3567       if (!strcmp(name, l->fname)
3568           && l->control_macro
3569           && cpp_lookup((const char *)l->control_macro, -1, -1))
3570          return 1;
3571    return 0;
3572 }
3573
3574 /* Return nonzero if the given FILENAME is an absolute pathname which
3575  * designates a file within one of the known "system" include file
3576  * directories.  We assume here that if the given FILENAME looks like
3577  * it is the name of a file which resides either directly in a "system"
3578  * include file directory, or within any subdirectory thereof, then the
3579  * given file must be a "system" include file.  This function tells us
3580  * if we should suppress pedantic errors/warnings for the given FILENAME.
3581  * 
3582  * The value is 2 if the file is a C-language system header file
3583  * for which C++ should (on most systems) assume `extern "C"'.  */
3584
3585 static int
3586 is_system_include(cpp_reader * pfile, char *filename)
3587 {
3588    struct file_name_list *searchptr;
3589
3590    for (searchptr = CPP_OPTIONS(pfile)->first_system_include; searchptr;
3591         searchptr = searchptr->next)
3592       if (searchptr->fname)
3593         {
3594            char               *sys_dir = searchptr->fname;
3595            unsigned            length = strlen(sys_dir);
3596
3597            if (!strncmp(sys_dir, filename, length) && filename[length] == '/')
3598              {
3599                 if (searchptr->c_system_include_path)
3600                    return 2;
3601                 else
3602                    return 1;
3603              }
3604         }
3605    return 0;
3606 }
3607
3608 /*
3609  * Install a name in the assertion hash table.
3610  *
3611  * If LEN is >= 0, it is the length of the name.
3612  * Otherwise, compute the length by scanning the entire name.
3613  *
3614  * If HASH is >= 0, it is the precomputed hash code.
3615  * Otherwise, compute the hash code.
3616  */
3617 static ASSERTION_HASHNODE *
3618 assertion_install(cpp_reader * pfile, const char *name, int len, int hash)
3619 {
3620    ASSERTION_HASHNODE *hp;
3621    int                 i, bucket;
3622
3623    i = sizeof(ASSERTION_HASHNODE) + len + 1;
3624    hp = (ASSERTION_HASHNODE *) xmalloc(i);
3625    bucket = hash;
3626    hp->bucket_hdr = &pfile->assertion_hashtab[bucket];
3627    hp->next = pfile->assertion_hashtab[bucket];
3628    pfile->assertion_hashtab[bucket] = hp;
3629    hp->prev = NULL;
3630    if (hp->next != NULL)
3631       hp->next->prev = hp;
3632    hp->length = len;
3633    hp->value = 0;
3634    hp->name = ((char *)hp) + sizeof(ASSERTION_HASHNODE);
3635    memcpy(hp->name, name, len);
3636    hp->name[len] = 0;
3637    return hp;
3638 }
3639 /*
3640  * find the most recent hash node for name name (ending with first
3641  * non-identifier char) installed by install
3642  *
3643  * If LEN is >= 0, it is the length of the name.
3644  * Otherwise, compute the length by scanning the entire name.
3645  *
3646  * If HASH is >= 0, it is the precomputed hash code.
3647  * Otherwise, compute the hash code.
3648  */
3649
3650 static ASSERTION_HASHNODE *
3651 assertion_lookup(cpp_reader * pfile, const char *name, int len, int hash)
3652 {
3653    ASSERTION_HASHNODE *bucket;
3654
3655    bucket = pfile->assertion_hashtab[hash];
3656    while (bucket)
3657      {
3658         if (bucket->length == len && strncmp(bucket->name, name, len) == 0)
3659            return bucket;
3660         bucket = bucket->next;
3661      }
3662    return NULL;
3663 }
3664
3665 static void
3666 delete_assertion(ASSERTION_HASHNODE * hp)
3667 {
3668    struct tokenlist_list *tail;
3669
3670    if (hp->prev != NULL)
3671       hp->prev->next = hp->next;
3672    if (hp->next != NULL)
3673       hp->next->prev = hp->prev;
3674
3675    for (tail = hp->value; tail;)
3676      {
3677         struct tokenlist_list *next = tail->next;
3678
3679         free_token_list(tail->tokens);
3680         free(tail);
3681         tail = next;
3682      }
3683
3684    /* make sure that the bucket chain header that
3685     * the deleted guy was on points to the right thing afterwards. */
3686    if (hp == *hp->bucket_hdr)
3687       *hp->bucket_hdr = hp->next;
3688
3689    free(hp);
3690 }
3691
3692 /* Convert a character string literal into a nul-terminated string.
3693  * The input string is [IN ... LIMIT).
3694  * The result is placed in RESULT.  RESULT can be the same as IN.
3695  * The value returned in the end of the string written to RESULT,
3696  * or NULL on error.  */
3697
3698 static char        *
3699 convert_string(cpp_reader * pfile, char *result, char *in, char *limit,
3700                int handle_escapes)
3701 {
3702    unsigned char       c;
3703
3704    c = *in++;
3705    if (c != '\"')
3706       return NULL;
3707    while (in < limit)
3708      {
3709         c = *in++;
3710
3711         switch (c)
3712           {
3713           case '\0':
3714              return NULL;
3715           case '\"':
3716              limit = in;
3717              break;
3718           case '\\':
3719              if (handle_escapes)
3720                {
3721                   char               *bpc = in;
3722                   int                 i =
3723                      (unsigned char)cpp_parse_escape(pfile, &bpc);
3724
3725                   in = bpc;
3726                   if (i >= 0)
3727                      *result++ = (unsigned char)c;
3728                   break;
3729                }
3730              /* else fall through */
3731           default:
3732              *result++ = c;
3733           }
3734      }
3735    *result = 0;
3736    return result;
3737 }
3738
3739 /*
3740  * interpret #line command.  Remembers previously seen fnames
3741  * in its very own hash table.
3742  */
3743 #define FNAME_HASHSIZE 37
3744
3745 static int
3746 do_line(cpp_reader * pfile, struct directive *keyword,
3747         unsigned char *unused1, unsigned char *unused2)
3748 {
3749    cpp_buffer         *ip = CPP_BUFFER(pfile);
3750    int                 new_lineno;
3751    long                old_written = CPP_WRITTEN(pfile);
3752    enum file_change_code file_change = same_file;
3753    enum cpp_token      token;
3754
3755    token = get_directive_token(pfile);
3756
3757    keyword = NULL;
3758    unused1 = unused2 = NULL;
3759
3760    if (token != CPP_NUMBER || !isdigit(pfile->token_buffer[old_written]))
3761      {
3762         cpp_error(pfile, "invalid format `#line' command");
3763         goto bad_line_directive;
3764      }
3765    /* The Newline at the end of this line remains to be processed.
3766     * To put the next line at the specified line number,
3767     * we must store a line number now that is one less.  */
3768    new_lineno = atoi((char *)(pfile->token_buffer + old_written)) - 1;
3769    CPP_SET_WRITTEN(pfile, old_written);
3770
3771    /* NEW_LINENO is one less than the actual line number here.  */
3772    if (CPP_PEDANTIC(pfile) && new_lineno < 0)
3773       cpp_pedwarn(pfile, "line number out of range in `#line' command");
3774
3775    token = get_directive_token(pfile);
3776
3777    if (token == CPP_STRING)
3778      {
3779         char               *fname = (char *)pfile->token_buffer + old_written;
3780         char               *end_name;
3781         static HASHNODE    *fname_table[FNAME_HASHSIZE];
3782         HASHNODE           *hp, **hash_bucket;
3783         unsigned char      *p;
3784         long                num_start;
3785         int                 fname_length;
3786
3787         /* Turn the file name, which is a character string literal,
3788          * into a null-terminated string.  Do this in place.  */
3789         end_name =
3790            convert_string(pfile, fname, fname, (char *)CPP_PWRITTEN(pfile), 1);
3791         if (end_name == NULL)
3792           {
3793              cpp_error(pfile, "invalid format `#line' command");
3794              goto bad_line_directive;
3795           }
3796         fname_length = end_name - fname;
3797
3798         num_start = CPP_WRITTEN(pfile);
3799         token = get_directive_token(pfile);
3800         if (token != CPP_VSPACE && token != CPP_EOF && token != CPP_POP)
3801           {
3802              p = pfile->token_buffer + num_start;
3803              if (CPP_PEDANTIC(pfile))
3804                 cpp_pedwarn(pfile, "garbage at end of `#line' command");
3805
3806              if (token != CPP_NUMBER || *p < '0' || *p > '4' || p[1] != '\0')
3807                {
3808                   cpp_error(pfile, "invalid format `#line' command");
3809                   goto bad_line_directive;
3810                }
3811              if (*p == '1')
3812                 file_change = enter_file;
3813              else if (*p == 2)
3814                 file_change = leave_file;
3815              else if (*p == 3)
3816                 ip->system_header_p = 1;
3817              else               /* if (*p == 4) */
3818                 ip->system_header_p = 2;
3819
3820              CPP_SET_WRITTEN(pfile, num_start);
3821              token = get_directive_token(pfile);
3822              p = pfile->token_buffer + num_start;
3823              if (token == CPP_NUMBER && p[1] == '\0'
3824                  && (*p == '3' || *p == '4'))
3825                {
3826                   ip->system_header_p = *p == 3 ? 1 : 2;
3827                   token = get_directive_token(pfile);
3828                }
3829              if (token != CPP_VSPACE)
3830                {
3831                   cpp_error(pfile, "invalid format `#line' command");
3832                   goto bad_line_directive;
3833                }
3834           }
3835         hash_bucket = &fname_table[hashf(fname, fname_length, FNAME_HASHSIZE)];
3836         for (hp = *hash_bucket; hp != NULL; hp = hp->next)
3837            if (hp->length == fname_length &&
3838                strncmp(hp->value.cpval, fname, fname_length) == 0)
3839              {
3840                 ip->nominal_fname = hp->value.cpval;
3841                 break;
3842              }
3843         if (hp == 0)
3844           {
3845              /* Didn't find it; cons up a new one.  */
3846              hp = (HASHNODE *) xcalloc(1, sizeof(HASHNODE) + fname_length + 1);
3847              hp->next = *hash_bucket;
3848              *hash_bucket = hp;
3849
3850              hp->length = fname_length;
3851              ip->nominal_fname = hp->value.cpval =
3852                 ((char *)hp) + sizeof(HASHNODE);
3853              memcpy(hp->value.cpval, fname, fname_length);
3854           }
3855      }
3856    else if (token != CPP_VSPACE && token != CPP_EOF)
3857      {
3858         cpp_error(pfile, "invalid format `#line' command");
3859         goto bad_line_directive;
3860      }
3861    ip->lineno = new_lineno;
3862  bad_line_directive:
3863    skip_rest_of_line(pfile);
3864    CPP_SET_WRITTEN(pfile, old_written);
3865    output_line_command(pfile, 0, file_change);
3866    return 0;
3867 }
3868
3869 /*
3870  * remove the definition of a symbol from the symbol table.
3871  * according to un*x /lib/cpp, it is not an error to undef
3872  * something that has no definitions, so it isn't one here either.
3873  */
3874
3875 static int
3876 do_undef(cpp_reader * pfile, struct directive *keyword, unsigned char *buf,
3877          unsigned char *limit)
3878 {
3879    int                 sym_length;
3880    HASHNODE           *hp;
3881    unsigned char      *orig_buf = buf;
3882
3883    SKIP_WHITE_SPACE(buf);
3884    sym_length = check_macro_name(pfile, buf, "macro");
3885
3886    while ((hp = cpp_lookup((const char *)buf, sym_length, -1)) != NULL)
3887      {
3888         /* If we are generating additional info for debugging (with -g) we
3889          * need to pass through all effective #undef commands.  */
3890         if (CPP_OPTIONS(pfile)->debug_output && keyword)
3891            pass_thru_directive((char *)orig_buf, (char *)limit, pfile, keyword);
3892         if (hp->type != T_MACRO)
3893            cpp_warning(pfile, "undefining `%s'", hp->name);
3894         delete_macro(hp);
3895      }
3896
3897    if (CPP_PEDANTIC(pfile))
3898      {
3899         buf += sym_length;
3900         SKIP_WHITE_SPACE(buf);
3901         if (buf != limit)
3902            cpp_pedwarn(pfile, "garbage after `#undef' directive");
3903      }
3904    return 0;
3905 }
3906
3907 /*
3908  * Report an error detected by the program we are processing.
3909  * Use the text of the line in the error message.
3910  * (We use error because it prints the filename & line#.)
3911  */
3912
3913 static int
3914 do_error(cpp_reader * pfile, struct directive *keyword, unsigned char *buf,
3915          unsigned char *limit)
3916 {
3917    int                 length = limit - buf;
3918    unsigned char      *copy = (unsigned char *)xmalloc(length + 1);
3919
3920    keyword = NULL;
3921    memcpy(copy, buf, length);
3922    copy[length] = 0;
3923    SKIP_WHITE_SPACE(copy);
3924    cpp_error(pfile, "#error %s", copy);
3925    return 0;
3926 }
3927
3928 /*
3929  * Report a warning detected by the program we are processing.
3930  * Use the text of the line in the warning message, then continue.
3931  * (We use error because it prints the filename & line#.)
3932  */
3933
3934 static int
3935 do_warning(cpp_reader * pfile, struct directive *keyword, unsigned char *buf,
3936            unsigned char *limit)
3937 {
3938    int                 length = limit - buf;
3939    unsigned char      *copy = (unsigned char *)xmalloc(length + 1);
3940
3941    keyword = NULL;
3942    memcpy(copy, buf, length);
3943    copy[length] = 0;
3944    SKIP_WHITE_SPACE(copy);
3945    cpp_warning(pfile, "#warning %s", copy);
3946    return 0;
3947 }
3948
3949 /* Remember the name of the current file being read from so that we can
3950  * avoid ever including it again.  */
3951
3952 static int
3953 do_once(cpp_reader * pfile)
3954 {
3955    cpp_buffer         *ip = NULL;
3956    struct file_name_list *new_;
3957
3958    for (ip = CPP_BUFFER(pfile);; ip = CPP_PREV_BUFFER(ip))
3959      {
3960         if (ip == NULL)
3961            return 0;
3962         if (ip->fname != NULL)
3963            break;
3964      }
3965
3966    new_ = (struct file_name_list *)xmalloc(sizeof(struct file_name_list));
3967
3968    new_->next = pfile->dont_repeat_files;
3969    pfile->dont_repeat_files = new_;
3970    new_->fname = savestring(ip->fname);
3971    new_->control_macro = 0;
3972    new_->got_name_map = 0;
3973    new_->c_system_include_path = 0;
3974
3975    return 0;
3976 }
3977
3978 /* #ident has already been copied to the output file, so just ignore it.  */
3979
3980 static int
3981 do_ident(cpp_reader * pfile, struct directive *keyword, unsigned char *buf,
3982          unsigned char *limit)
3983 {
3984 /*  long old_written = CPP_WRITTEN (pfile); */
3985
3986    /* Allow #ident in system headers, since that's not user's fault.  */
3987    if (CPP_PEDANTIC(pfile) && !CPP_BUFFER(pfile)->system_header_p)
3988       cpp_pedwarn(pfile, "ANSI C does not allow `#ident'");
3989
3990    keyword = NULL;
3991    buf = NULL;
3992    limit = NULL;
3993    /* Leave rest of line to be read by later calls to cpp_get_token. */
3994
3995    return 0;
3996 }
3997
3998 /* #pragma and its argument line have already been copied to the output file.
3999  * Just check for some recognized pragmas that need validation here.  */
4000
4001 static int
4002 do_pragma(cpp_reader * pfile, struct directive *keyword, unsigned char *buf,
4003           unsigned char *limit)
4004 {
4005    while (*buf == ' ' || *buf == '\t')
4006       buf++;
4007
4008    keyword = NULL;
4009    limit = NULL;
4010    if (!strncmp((const char *)buf, "once", 4))
4011      {
4012         /* Allow #pragma once in system headers, since that's not the user's
4013          * fault.  */
4014         if (!CPP_BUFFER(pfile)->system_header_p)
4015            cpp_warning(pfile, "`#pragma once' is obsolete");
4016         do_once(pfile);
4017      }
4018    if (!strncmp((const char *)buf, "implementation", 14))
4019      {
4020         /* Be quiet about `#pragma implementation' for a file only if it hasn't
4021          * been included yet.  */
4022         struct file_name_list *ptr;
4023         char               *p = (char *)buf + 14, *fname, *inc_fname;
4024         int                 fname_len;
4025
4026         SKIP_WHITE_SPACE(p);
4027         if (*p == '\n' || *p != '\"')
4028            return 0;
4029
4030         fname = p + 1;
4031         p = strchr(fname, '\"');
4032         fname_len =
4033            (int)(((int)(p != NULL)) ? ((int)(p - fname))
4034                  : ((int)(strlen(fname))));
4035
4036         for (ptr = pfile->all_include_files; ptr; ptr = ptr->next)
4037           {
4038              inc_fname = strrchr(ptr->fname, '/');
4039              inc_fname = inc_fname ? inc_fname + 1 : (char *)ptr->fname;
4040              if (inc_fname && !strncmp(inc_fname, fname, fname_len))
4041                 cpp_warning(pfile,
4042                             "`#pragma implementation' for `%s' appears after file is included",
4043                             fname);
4044           }
4045      }
4046    return 0;
4047 }
4048
4049 /* Just ignore #sccs, on systems where we define it at all.  */
4050
4051 /*
4052  * handle #if command by
4053  *   1) inserting special `defined' keyword into the hash table
4054  *      that gets turned into 0 or 1 by special_symbol (thus,
4055  *      if the luser has a symbol called `defined' already, it won't
4056  *      work inside the #if command)
4057  *   2) rescan the input into a temporary output buffer
4058  *   3) pass the output buffer to the yacc parser and collect a value
4059  *   4) clean up the mess left from steps 1 and 2.
4060  *   5) call conditional_skip to skip til the next #endif (etc.),
4061  *      or not, depending on the value from step 3.
4062  */
4063
4064 static int
4065 do_if(cpp_reader * pfile, struct directive *keyword, unsigned char *buf,
4066       unsigned char *limit)
4067 {
4068    HOST_WIDE_INT       value = eval_if_expression(pfile, buf, limit - buf);
4069
4070    keyword = NULL;
4071    conditional_skip(pfile, value == 0, T_IF, NULL);
4072    return 0;
4073 }
4074
4075 /*
4076  * handle a #elif directive by not changing  if_stack  either.
4077  * see the comment above do_else.
4078  */
4079
4080 static int
4081 do_elif(cpp_reader * pfile, struct directive *keyword, unsigned char *buf,
4082         unsigned char *limit)
4083 {
4084
4085    keyword = NULL;
4086
4087    if (pfile->if_stack == CPP_BUFFER(pfile)->if_stack)
4088      {
4089         cpp_error(pfile, "`#elif' not within a conditional");
4090         return 0;
4091      }
4092    else
4093      {
4094         if (pfile->if_stack->type != T_IF && pfile->if_stack->type != T_ELIF)
4095           {
4096              cpp_error(pfile, "`#elif' after `#else'");
4097              if (pfile->if_stack->fname != NULL
4098                  && CPP_BUFFER(pfile)->fname != NULL
4099                  && strcmp(pfile->if_stack->fname,
4100                            CPP_BUFFER(pfile)->nominal_fname) != 0)
4101                 fprintf(stderr, ", file %s", pfile->if_stack->fname);
4102              fprintf(stderr, ")\n");
4103           }
4104         pfile->if_stack->type = T_ELIF;
4105      }
4106
4107    if (pfile->if_stack->if_succeeded)
4108       skip_if_group(pfile, 0);
4109    else
4110      {
4111         HOST_WIDE_INT       value = eval_if_expression(pfile, buf, limit - buf);
4112
4113         if (value == 0)
4114            skip_if_group(pfile, 0);
4115         else
4116           {
4117              ++pfile->if_stack->if_succeeded;   /* continue processing input */
4118              output_line_command(pfile, 1, same_file);
4119           }
4120      }
4121    return 0;
4122 }
4123
4124 /*
4125  * evaluate a #if expression in BUF, of length LENGTH,
4126  * then parse the result as a C expression and return the value as an int.
4127  */
4128 static              HOST_WIDE_INT
4129 eval_if_expression(cpp_reader * pfile, unsigned char *buf, int length)
4130 {
4131    HASHNODE           *save_defined;
4132    HOST_WIDE_INT       value;
4133    long                old_written = CPP_WRITTEN(pfile);
4134
4135    buf = NULL;
4136    length = 0;
4137    save_defined = install("defined", -1, T_SPEC_DEFINED, 0, 0, -1);
4138    pfile->pcp_inside_if = 1;
4139
4140    value = cpp_parse_expr(pfile);
4141    pfile->pcp_inside_if = 0;
4142    delete_macro(save_defined);  /* clean up special symbol */
4143
4144    CPP_SET_WRITTEN(pfile, old_written); /* Pop */
4145
4146    return value;
4147 }
4148
4149 /*
4150  * routine to handle ifdef/ifndef.  Try to look up the symbol,
4151  * then do or don't skip to the #endif/#else/#elif depending
4152  * on what directive is actually being processed.
4153  */
4154
4155 static int
4156 do_xifdef(cpp_reader * pfile, struct directive *keyword, unsigned char *unused1,
4157           unsigned char *unused2)
4158 {
4159    int                 skip;
4160    cpp_buffer         *ip = CPP_BUFFER(pfile);
4161    char               *ident;
4162    int                 ident_length;
4163    enum cpp_token      token;
4164    int                 start_of_file = 0;
4165    unsigned char      *control_macro = 0;
4166    int                 old_written = CPP_WRITTEN(pfile);
4167
4168    unused1 = NULL;
4169    unused2 = NULL;
4170    /* Detect a #ifndef at start of file (not counting comments).  */
4171    if (ip->fname != 0 && keyword->type == T_IFNDEF)
4172       start_of_file = pfile->only_seen_white == 2;
4173
4174    pfile->no_macro_expand++;
4175    token = get_directive_token(pfile);
4176    pfile->no_macro_expand--;
4177
4178    ident = (char *)pfile->token_buffer + old_written;
4179    ident_length = CPP_WRITTEN(pfile) - old_written;
4180    CPP_SET_WRITTEN(pfile, old_written); /* Pop */
4181
4182    if (token == CPP_VSPACE || token == CPP_POP || token == CPP_EOF)
4183      {
4184         skip = (keyword->type == T_IFDEF);
4185         if (!CPP_TRADITIONAL(pfile))
4186            cpp_pedwarn(pfile, "`#%s' with no argument", keyword->name);
4187      }
4188    else if (token == CPP_NAME)
4189      {
4190         HASHNODE           *hp = cpp_lookup(ident, ident_length, -1);
4191
4192         skip = (hp == NULL) ^ (keyword->type == T_IFNDEF);
4193         if (start_of_file && !skip)
4194           {
4195              control_macro = (unsigned char *)xmalloc(ident_length + 1);
4196              memcpy(control_macro, ident, ident_length + 1);
4197           }
4198      }
4199    else
4200      {
4201         skip = (keyword->type == T_IFDEF);
4202         if (!CPP_TRADITIONAL(pfile))
4203            cpp_error(pfile, "`#%s' with invalid argument", keyword->name);
4204      }
4205
4206    if (!CPP_TRADITIONAL(pfile))
4207      {
4208         int                 c;
4209
4210         cpp_skip_hspace(pfile);
4211         c = PEEKC();
4212         if (c != EOF && c != '\n')
4213            cpp_pedwarn(pfile, "garbage at end of `#%s' argument",
4214                        keyword->name);
4215      }
4216    skip_rest_of_line(pfile);
4217
4218    conditional_skip(pfile, skip, T_IF, control_macro);
4219    return 0;
4220 }
4221
4222 /* Push TYPE on stack; then, if SKIP is nonzero, skip ahead.
4223  * If this is a #ifndef starting at the beginning of a file,
4224  * CONTROL_MACRO is the macro name tested by the #ifndef.
4225  * Otherwise, CONTROL_MACRO is 0.  */
4226
4227 static void
4228 conditional_skip(cpp_reader * pfile, int skip, enum node_type type,
4229                  unsigned char *control_macro)
4230 {
4231    IF_STACK_FRAME     *temp;
4232
4233    temp = (IF_STACK_FRAME *) xcalloc(1, sizeof(IF_STACK_FRAME));
4234    temp->fname = CPP_BUFFER(pfile)->nominal_fname;
4235    temp->next = pfile->if_stack;
4236    temp->control_macro = control_macro;
4237    pfile->if_stack = temp;
4238
4239    pfile->if_stack->type = type;
4240
4241    if (skip != 0)
4242      {
4243         skip_if_group(pfile, 0);
4244         return;
4245      }
4246    else
4247      {
4248         ++pfile->if_stack->if_succeeded;
4249         output_line_command(pfile, 1, same_file);
4250      }
4251 }
4252
4253 /*
4254  * skip to #endif, #else, or #elif.  adjust line numbers, etc.
4255  * leaves input ptr at the sharp sign found.
4256  * If ANY is nonzero, return at next directive of any sort.
4257  */
4258
4259 static void
4260 skip_if_group(cpp_reader * pfile, int any)
4261 {
4262    int                 c;
4263    struct directive   *kt;
4264    IF_STACK_FRAME     *save_if_stack = pfile->if_stack; /* don't pop past here */
4265
4266    int                 ident_length;
4267    char               *ident;
4268    struct parse_marker line_start_mark;
4269
4270    parse_set_mark(&line_start_mark, pfile);
4271
4272    if (CPP_OPTIONS(pfile)->output_conditionals)
4273      {
4274         static char         failed[] = "#failed\n";
4275
4276         CPP_PUTS(pfile, failed, sizeof(failed) - 1);
4277         pfile->lineno++;
4278         output_line_command(pfile, 1, same_file);
4279      }
4280  beg_of_line:
4281    if (CPP_OPTIONS(pfile)->output_conditionals)
4282      {
4283         cpp_buffer         *pbuf = CPP_BUFFER(pfile);
4284         unsigned char      *start_line = pbuf->buf + line_start_mark.position;
4285
4286         CPP_PUTS(pfile, start_line, pbuf->cur - start_line);
4287      }
4288    parse_move_mark(&line_start_mark, pfile);
4289    if (!CPP_TRADITIONAL(pfile))
4290       cpp_skip_hspace(pfile);
4291    c = GETC();
4292    if (c == '#')
4293      {
4294         int                 old_written = CPP_WRITTEN(pfile);
4295
4296         cpp_skip_hspace(pfile);
4297
4298         parse_name(pfile, GETC());
4299         ident_length = CPP_WRITTEN(pfile) - old_written;
4300         ident = (char *)pfile->token_buffer + old_written;
4301         pfile->limit = (unsigned char *)ident;
4302
4303         for (kt = directive_table; kt->length >= 0; kt++)
4304           {
4305              IF_STACK_FRAME     *temp;
4306
4307              if (ident_length == kt->length
4308                  && strncmp(ident, kt->name, kt->length) == 0)
4309                {
4310                   /* If we are asked to return on next directive, do so now.  */
4311                   if (any)
4312                      goto done;
4313
4314                   switch (kt->type)
4315                     {
4316                     case T_IF:
4317                     case T_IFDEF:
4318                     case T_IFNDEF:
4319                        temp
4320                           =
4321                           (IF_STACK_FRAME *) xcalloc(1, sizeof(IF_STACK_FRAME));
4322                        temp->next = pfile->if_stack;
4323                        pfile->if_stack = temp;
4324                        temp->fname = CPP_BUFFER(pfile)->nominal_fname;
4325                        temp->type = kt->type;
4326                        break;
4327                     case T_ELSE:
4328                     case T_ENDIF:
4329                        if (CPP_PEDANTIC(pfile)
4330                            && pfile->if_stack != save_if_stack)
4331                           validate_else(pfile,
4332                                         kt->type ==
4333                                         T_ELSE ? "#else" : "#endif");
4334                     case T_ELIF:
4335                        if (pfile->if_stack == CPP_BUFFER(pfile)->if_stack)
4336                          {
4337                             cpp_error(pfile,
4338                                       "`#%s' not within a conditional",
4339                                       kt->name);
4340                             break;
4341                          }
4342                        else if (pfile->if_stack == save_if_stack)
4343                           goto done;    /* found what we came for */
4344
4345                        if (kt->type != T_ENDIF)
4346                          {
4347                             if (pfile->if_stack->type == T_ELSE)
4348                                cpp_error(pfile,
4349                                          "`#else' or `#elif' after `#else'");
4350                             pfile->if_stack->type = kt->type;
4351                             break;
4352                          }
4353                        temp = pfile->if_stack;
4354                        pfile->if_stack = temp->next;
4355                        free(temp);
4356                        break;
4357                     default:;
4358                     }
4359                   break;
4360                }
4361              /* Don't let erroneous code go by.  */
4362              if (kt->length < 0 && !CPP_OPTIONS(pfile)->lang_asm
4363                  && CPP_PEDANTIC(pfile))
4364                 cpp_pedwarn(pfile, "invalid preprocessor directive name");
4365           }
4366         c = GETC();
4367      }
4368    /* We're in the middle of a line.  Skip the rest of it. */
4369    for (;;)
4370      {
4371         switch (c)
4372           {
4373              long                old;
4374
4375           case EOF:
4376              goto done;
4377           case '/':             /* possible comment */
4378              c = skip_comment(pfile, NULL);
4379              if (c == EOF)
4380                 goto done;
4381              break;
4382           case '\"':
4383           case '\'':
4384              FORWARD(-1);
4385              old = CPP_WRITTEN(pfile);
4386              cpp_get_token(pfile);
4387              CPP_SET_WRITTEN(pfile, old);
4388              break;
4389           case '\\':
4390              /* Char after backslash loses its special meaning.  */
4391              if (PEEKC() == '\n')
4392                 FORWARD(1);
4393              break;
4394           case '\n':
4395              goto beg_of_line;
4396              break;
4397           }
4398         c = GETC();
4399      }
4400  done:
4401    if (CPP_OPTIONS(pfile)->output_conditionals)
4402      {
4403         static char         end_failed[] = "#endfailed\n";
4404
4405         CPP_PUTS(pfile, end_failed, sizeof(end_failed) - 1);
4406         pfile->lineno++;
4407      }
4408    pfile->only_seen_white = 1;
4409    parse_goto_mark(&line_start_mark, pfile);
4410    parse_clear_mark(&line_start_mark);
4411 }
4412
4413 /*
4414  * handle a #else directive.  Do this by just continuing processing
4415  * without changing  if_stack ;  this is so that the error message
4416  * for missing #endif's etc. will point to the original #if.  It
4417  * is possible that something different would be better.
4418  */
4419
4420 static int
4421 do_else(cpp_reader * pfile, struct directive *keyword, unsigned char *buf,
4422         unsigned char *limit)
4423 {
4424    cpp_buffer         *ip = CPP_BUFFER(pfile);
4425
4426    keyword = NULL;
4427    buf = NULL;
4428    limit = NULL;
4429
4430    if (CPP_PEDANTIC(pfile))
4431       validate_else(pfile, "#else");
4432    skip_rest_of_line(pfile);
4433
4434    if (pfile->if_stack == CPP_BUFFER(pfile)->if_stack)
4435      {
4436         cpp_error(pfile, "`#else' not within a conditional");
4437         return 0;
4438      }
4439    else
4440      {
4441         /* #ifndef can't have its special treatment for containing the whole file
4442          * if it has a #else clause.  */
4443         pfile->if_stack->control_macro = 0;
4444
4445         if (pfile->if_stack->type != T_IF && pfile->if_stack->type != T_ELIF)
4446           {
4447              cpp_error(pfile, "`#else' after `#else'");
4448              fprintf(stderr, " (matches line %d", pfile->if_stack->lineno);
4449              if (strcmp(pfile->if_stack->fname, ip->nominal_fname) != 0)
4450                 fprintf(stderr, ", file %s", pfile->if_stack->fname);
4451              fprintf(stderr, ")\n");
4452           }
4453         pfile->if_stack->type = T_ELSE;
4454      }
4455
4456    if (pfile->if_stack->if_succeeded)
4457       skip_if_group(pfile, 0);
4458    else
4459      {
4460         ++pfile->if_stack->if_succeeded;        /* continue processing input */
4461         output_line_command(pfile, 1, same_file);
4462      }
4463    return 0;
4464 }
4465
4466 /*
4467  * unstack after #endif command
4468  */
4469
4470 static int
4471 do_endif(cpp_reader * pfile, struct directive *keyword, unsigned char *buf,
4472          unsigned char *limit)
4473 {
4474    if (CPP_PEDANTIC(pfile))
4475       validate_else(pfile, "#endif");
4476    skip_rest_of_line(pfile);
4477
4478    keyword = NULL;
4479    buf = NULL;
4480    limit = NULL;
4481
4482    if (pfile->if_stack == CPP_BUFFER(pfile)->if_stack)
4483      {
4484         cpp_error(pfile, "unbalanced `#endif'");
4485      }
4486    else
4487      {
4488         IF_STACK_FRAME     *temp = pfile->if_stack;
4489
4490         pfile->if_stack = temp->next;
4491         if (temp->control_macro != 0)
4492           {
4493              /* This #endif matched a #ifndef at the start of the file.
4494               * See if it is at the end of the file.  */
4495              struct parse_marker start_mark;
4496              int                 c;
4497
4498              parse_set_mark(&start_mark, pfile);
4499
4500              for (;;)
4501                {
4502                   cpp_skip_hspace(pfile);
4503                   c = GETC();
4504                   if (c != '\n')
4505                      break;
4506                }
4507              parse_goto_mark(&start_mark, pfile);
4508              parse_clear_mark(&start_mark);
4509
4510              if (c == EOF)
4511                {
4512                   /* If we get here, this #endif ends a #ifndef
4513                    * that contains all of the file (aside from whitespace).
4514                    * Arrange not to include the file again
4515                    * if the macro that was tested is defined.
4516                    * 
4517                    * Do not do this for the top-level file in a -include or any
4518                    * file in a -imacros.  */
4519                   {
4520                      struct file_name_list *ifile = pfile->all_include_files;
4521
4522                      for (; ifile != NULL; ifile = ifile->next)
4523                        {
4524                           if (!strcmp(ifile->fname, CPP_BUFFER(pfile)->fname))
4525                             {
4526                                ifile->control_macro = temp->control_macro;
4527                                break;
4528                             }
4529                        }
4530                   }
4531                }
4532           }
4533         free(temp);
4534         output_line_command(pfile, 1, same_file);
4535      }
4536    return 0;
4537 }
4538
4539 /* When an #else or #endif is found while skipping failed conditional,
4540  * if -pedantic was specified, this is called to warn about text after
4541  * the command name.  P points to the first char after the command name.  */
4542
4543 static void
4544 validate_else(cpp_reader * pfile, const char *directive)
4545 {
4546    int                 c;
4547
4548    cpp_skip_hspace(pfile);
4549    c = PEEKC();
4550    if (c != EOF && c != '\n')
4551       cpp_pedwarn(pfile,
4552                   "text following `%s' violates ANSI standard", directive);
4553 }
4554
4555 /* Get the next token, and add it to the text in pfile->token_buffer.
4556  * Return the kind of token we got. */
4557
4558 enum cpp_token
4559 cpp_get_token(cpp_reader * pfile)
4560 {
4561    int                 c, c2, c3;
4562    long                old_written = 0;
4563    long                start_line, start_column;
4564    enum cpp_token      token;
4565    struct cpp_options *opts = CPP_OPTIONS(pfile);
4566
4567    CPP_BUFFER(pfile)->prev = CPP_BUFFER(pfile)->cur;
4568  get_next:
4569    c = GETC();
4570    if (c == EOF)
4571      {
4572       handle_eof:
4573         if (CPP_BUFFER(pfile)->seen_eof)
4574           {
4575              if (cpp_pop_buffer(pfile) != CPP_NULL_BUFFER(pfile))
4576                 goto get_next;
4577              else
4578                 return CPP_EOF;
4579           }
4580         else
4581           {
4582              cpp_buffer         *next_buf = CPP_PREV_BUFFER(CPP_BUFFER(pfile));
4583
4584              CPP_BUFFER(pfile)->seen_eof = 1;
4585              if (CPP_BUFFER(pfile)->nominal_fname && next_buf != 0)
4586                {
4587                   /* We're about to return from an #include file.
4588                    * Emit #line information now (as part of the CPP_POP) result.
4589                    * But the #line refers to the file we will pop to. */
4590                   cpp_buffer         *cur_buffer = CPP_BUFFER(pfile);
4591
4592                   CPP_BUFFER(pfile) = next_buf;
4593                   pfile->input_stack_listing_current = 0;
4594                   output_line_command(pfile, 0, leave_file);
4595                   CPP_BUFFER(pfile) = cur_buffer;
4596                }
4597              return CPP_POP;
4598           }
4599      }
4600    else
4601      {
4602         switch (c)
4603           {
4604              long                newlines;
4605              struct parse_marker start_mark;
4606
4607           case '/':
4608              if (PEEKC() == '=')
4609                 goto op2;
4610              if (opts->put_out_comments)
4611                 parse_set_mark(&start_mark, pfile);
4612              newlines = 0;
4613              cpp_buf_line_and_col(cpp_file_buffer(pfile),
4614                                   &start_line, &start_column);
4615              c = skip_comment(pfile, &newlines);
4616              if (opts->put_out_comments && (c == '/' || c == EOF))
4617                 parse_clear_mark(&start_mark);
4618              if (c == '/')
4619                 goto randomchar;
4620              if (c == EOF)
4621                {
4622                   cpp_error_with_line(pfile, start_line, start_column,
4623                                       "unterminated comment");
4624                   goto handle_eof;
4625                }
4626              c = '/';           /* Initial letter of comment. */
4627            return_comment:
4628              /* Comments are equivalent to spaces.
4629               * For -traditional, a comment is equivalent to nothing.  */
4630              if (opts->put_out_comments)
4631                {
4632                   cpp_buffer         *pbuf = CPP_BUFFER(pfile);
4633                   unsigned char      *start = pbuf->buf + start_mark.position;
4634                   int                 len = pbuf->cur - start;
4635
4636                   CPP_RESERVE(pfile, 1 + len);
4637                   CPP_PUTC_Q(pfile, c);
4638                   CPP_PUTS_Q(pfile, start, len);
4639                   pfile->lineno += newlines;
4640                   parse_clear_mark(&start_mark);
4641                   return CPP_COMMENT;
4642                }
4643              else if (CPP_TRADITIONAL(pfile))
4644                {
4645                   return CPP_COMMENT;
4646                }
4647              else
4648                {
4649                   CPP_RESERVE(pfile, 1);
4650                   CPP_PUTC_Q(pfile, ' ');
4651                   return CPP_HSPACE;
4652                }
4653
4654           case '#':
4655              if (!pfile->only_seen_white)
4656                 goto randomchar;
4657              if (handle_directive(pfile))
4658                 return CPP_DIRECTIVE;
4659              pfile->only_seen_white = 0;
4660              return CPP_OTHER;
4661
4662           case '\"':
4663           case '\'':
4664              /* A single quoted string is treated like a double -- some
4665               * programs (e.g., troff) are perverse this way */
4666              cpp_buf_line_and_col(cpp_file_buffer(pfile),
4667                                   &start_line, &start_column);
4668              old_written = CPP_WRITTEN(pfile);
4669            string:
4670              CPP_PUTC(pfile, c);
4671              while (1)
4672                {
4673                   int                 cc = GETC();
4674
4675                   if (cc == EOF)
4676                     {
4677                        if (CPP_IS_MACRO_BUFFER(CPP_BUFFER(pfile)))
4678                          {
4679                             /* try harder: this string crosses a macro expansion
4680                              * boundary.  This can happen naturally if -traditional.
4681                              * Otherwise, only -D can make a macro with an unmatched
4682                              * quote.  */
4683                             cpp_buffer         *next_buf
4684                                = CPP_PREV_BUFFER(CPP_BUFFER(pfile));
4685
4686                             (*CPP_BUFFER(pfile)->cleanup)
4687                                (CPP_BUFFER(pfile), pfile);
4688                             CPP_BUFFER(pfile) = next_buf;
4689                             continue;
4690                          }
4691                        if (!CPP_TRADITIONAL(pfile))
4692                          {
4693                             cpp_error_with_line(pfile, start_line, start_column,
4694                                                 "unterminated string or character constant");
4695                             if (pfile->multiline_string_line != start_line
4696                                 && pfile->multiline_string_line != 0)
4697                                cpp_error_with_line(pfile,
4698                                                    pfile->multiline_string_line,
4699                                                    -1,
4700                                                    "possible real start of unterminated constant");
4701                             pfile->multiline_string_line = 0;
4702                          }
4703                        break;
4704                     }
4705                   CPP_PUTC(pfile, cc);
4706                   switch (cc)
4707                     {
4708                     case '\n':
4709                        /* Traditionally, end of line ends a string constant with
4710                         * no error.  So exit the loop and record the new line.  */
4711                        if (CPP_TRADITIONAL(pfile))
4712                           goto while2end;
4713                        if (c == '\'')
4714                          {
4715                             cpp_error_with_line(pfile, start_line, start_column,
4716                                                 "unterminated character constant");
4717                             goto while2end;
4718                          }
4719                        if (CPP_PEDANTIC(pfile)
4720                            && pfile->multiline_string_line == 0)
4721                          {
4722                             cpp_pedwarn_with_line(pfile, start_line,
4723                                                   start_column,
4724                                                   "string constant runs past end of line");
4725                          }
4726                        if (pfile->multiline_string_line == 0)
4727                           pfile->multiline_string_line = start_line;
4728                        break;
4729
4730                     case '\\':
4731                        cc = GETC();
4732                        if (cc == '\n')
4733                          {
4734                             /* Backslash newline is replaced by nothing at all. */
4735                             CPP_ADJUST_WRITTEN(pfile, -1);
4736                             pfile->lineno++;
4737                          }
4738                        else
4739                          {
4740                             /* ANSI stupidly requires that in \\ the second \
4741                              * is *not* prevented from combining with a newline.  */
4742                             NEWLINE_FIX1(cc);
4743                             if (cc != EOF)
4744                                CPP_PUTC(pfile, cc);
4745                          }
4746                        break;
4747
4748                     case '\"':
4749                     case '\'':
4750                        if (cc == c)
4751                           goto while2end;
4752                        break;
4753                     }
4754                }
4755            while2end:
4756              pfile->lineno += count_newlines(pfile->token_buffer + old_written,
4757                                              CPP_PWRITTEN(pfile));
4758              pfile->only_seen_white = 0;
4759              return c == '\'' ? CPP_CHAR : CPP_STRING;
4760
4761           case '$':
4762              if (!opts->dollars_in_ident)
4763                 goto randomchar;
4764              goto letter;
4765
4766           case ':':
4767              if (opts->cplusplus && PEEKC() == ':')
4768                 goto op2;
4769              goto randomchar;
4770
4771           case '&':
4772           case '+':
4773           case '|':
4774              NEWLINE_FIX;
4775              c2 = PEEKC();
4776              if (c2 == c || c2 == '=')
4777                 goto op2;
4778              goto randomchar;
4779
4780           case '*':
4781           case '!':
4782           case '%':
4783           case '=':
4784           case '^':
4785              NEWLINE_FIX;
4786              if (PEEKC() == '=')
4787                 goto op2;
4788              goto randomchar;
4789
4790           case '-':
4791              NEWLINE_FIX;
4792              c2 = PEEKC();
4793              if (c2 == '-' && opts->chill)
4794                {
4795                   /* Chill style comment */
4796                   if (opts->put_out_comments)
4797                      parse_set_mark(&start_mark, pfile);
4798                   FORWARD(1);   /* Skip second '-'. */
4799                   for (;;)
4800                     {
4801                        c = GETC();
4802                        if (c == EOF)
4803                           break;
4804                        if (c == '\n')
4805                          {
4806                             /* Don't consider final '\n' to be part of comment. */
4807                             FORWARD(-1);
4808                             break;
4809                          }
4810                     }
4811                   c = '-';
4812                   goto return_comment;
4813                }
4814              if (c2 == '-' || c2 == '=' || c2 == '>')
4815                 goto op2;
4816              goto randomchar;
4817
4818           case '<':
4819              if (pfile->parsing_include_directive)
4820                {
4821                   for (;;)
4822                     {
4823                        CPP_PUTC(pfile, c);
4824                        if (c == '>')
4825                           break;
4826                        c = GETC();
4827                        NEWLINE_FIX1(c);
4828                        if (c == '\n' || c == EOF)
4829                          {
4830                             cpp_error(pfile,
4831                                       "missing '>' in `#include <FILENAME>'");
4832                             break;
4833                          }
4834                     }
4835                   return CPP_STRING;
4836                }
4837              /* else fall through */
4838           case '>':
4839              NEWLINE_FIX;
4840              c2 = PEEKC();
4841              if (c2 == '=')
4842                 goto op2;
4843              if (c2 != c)
4844                 goto randomchar;
4845              FORWARD(1);
4846              CPP_RESERVE(pfile, 4);
4847              CPP_PUTC(pfile, c);
4848              CPP_PUTC(pfile, c2);
4849              NEWLINE_FIX;
4850              c3 = PEEKC();
4851              if (c3 == '=')
4852                 CPP_PUTC_Q(pfile, GETC());
4853              CPP_NUL_TERMINATE_Q(pfile);
4854              pfile->only_seen_white = 0;
4855              return CPP_OTHER;
4856
4857           case '@':
4858              if (CPP_BUFFER(pfile)->has_escapes)
4859                {
4860                   c = GETC();
4861                   if (c == '-')
4862                     {
4863                        if (pfile->output_escapes)
4864                           CPP_PUTS(pfile, "@-", 2);
4865                        parse_name(pfile, GETC());
4866                        return CPP_NAME;
4867                     }
4868                   else if (is_space[c])
4869                     {
4870                        CPP_RESERVE(pfile, 2);
4871                        if (pfile->output_escapes)
4872                           CPP_PUTC_Q(pfile, '@');
4873                        CPP_PUTC_Q(pfile, c);
4874                        return CPP_HSPACE;
4875                     }
4876                }
4877              if (pfile->output_escapes)
4878                {
4879                   CPP_PUTS(pfile, "@@", 2);
4880                   return CPP_OTHER;
4881                }
4882              goto randomchar;
4883
4884           case '.':
4885              NEWLINE_FIX;
4886              c2 = PEEKC();
4887              if (isdigit(c2))
4888                {
4889                   CPP_RESERVE(pfile, 2);
4890                   CPP_PUTC_Q(pfile, '.');
4891                   c = GETC();
4892                   goto number;
4893                }
4894              /* FIXME - misses the case "..\\\n." */
4895              if (c2 == '.' && PEEKN(1) == '.')
4896                {
4897                   CPP_RESERVE(pfile, 4);
4898                   CPP_PUTC_Q(pfile, '.');
4899                   CPP_PUTC_Q(pfile, '.');
4900                   CPP_PUTC_Q(pfile, '.');
4901                   FORWARD(2);
4902                   CPP_NUL_TERMINATE_Q(pfile);
4903                   pfile->only_seen_white = 0;
4904                   return CPP_3DOTS;
4905                }
4906              goto randomchar;
4907
4908            op2:
4909              token = CPP_OTHER;
4910              pfile->only_seen_white = 0;
4911            op2any:
4912              CPP_RESERVE(pfile, 3);
4913              CPP_PUTC_Q(pfile, c);
4914              CPP_PUTC_Q(pfile, GETC());
4915              CPP_NUL_TERMINATE_Q(pfile);
4916              return token;
4917
4918           case 'L':
4919              NEWLINE_FIX;
4920              c2 = PEEKC();
4921              if ((c2 == '\'' || c2 == '\"') && !CPP_TRADITIONAL(pfile))
4922                {
4923                   CPP_PUTC(pfile, c);
4924                   c = GETC();
4925                   goto string;
4926                }
4927              goto letter;
4928
4929           case '0':
4930           case '1':
4931           case '2':
4932           case '3':
4933           case '4':
4934           case '5':
4935           case '6':
4936           case '7':
4937           case '8':
4938           case '9':
4939            number:
4940              c2 = '.';
4941              for (;;)
4942                {
4943                   CPP_RESERVE(pfile, 2);
4944                   CPP_PUTC_Q(pfile, c);
4945                   NEWLINE_FIX;
4946                   c = PEEKC();
4947                   if (c == EOF)
4948                      break;
4949                   if (!is_idchar[c] && c != '.'
4950                       && ((c2 != 'e' && c2 != 'E') || (c != '+' && c != '-')))
4951                      break;
4952                   FORWARD(1);
4953                   c2 = c;
4954                }
4955              CPP_NUL_TERMINATE_Q(pfile);
4956              pfile->only_seen_white = 0;
4957              return CPP_NUMBER;
4958           case 'b':
4959           case 'c':
4960           case 'd':
4961           case 'h':
4962           case 'o':
4963           case 'B':
4964           case 'C':
4965           case 'D':
4966           case 'H':
4967           case 'O':
4968              if (opts->chill && PEEKC() == '\'')
4969                {
4970                   pfile->only_seen_white = 0;
4971                   CPP_RESERVE(pfile, 2);
4972                   CPP_PUTC_Q(pfile, c);
4973                   CPP_PUTC_Q(pfile, '\'');
4974                   FORWARD(1);
4975                   for (;;)
4976                     {
4977                        c = GETC();
4978                        if (c == EOF)
4979                           goto chill_number_eof;
4980                        if (!is_idchar[c])
4981                          {
4982                             if (c == '\\' && PEEKC() == '\n')
4983                               {
4984                                  FORWARD(2);
4985                                  continue;
4986                               }
4987                             break;
4988                          }
4989                        CPP_PUTC(pfile, c);
4990                     }
4991                   if (c == '\'')
4992                     {
4993                        CPP_RESERVE(pfile, 2);
4994                        CPP_PUTC_Q(pfile, c);
4995                        CPP_NUL_TERMINATE_Q(pfile);
4996                        return CPP_STRING;
4997                     }
4998                   else
4999                     {
5000                        FORWARD(-1);
5001                      chill_number_eof:
5002                        CPP_NUL_TERMINATE(pfile);
5003                        return CPP_NUMBER;
5004                     }
5005                }
5006              else
5007                 goto letter;
5008           case '_':
5009           case 'a':
5010           case 'e':
5011           case 'f':
5012           case 'g':
5013           case 'i':
5014           case 'j':
5015           case 'k':
5016           case 'l':
5017           case 'm':
5018           case 'n':
5019           case 'p':
5020           case 'q':
5021           case 'r':
5022           case 's':
5023           case 't':
5024           case 'u':
5025           case 'v':
5026           case 'w':
5027           case 'x':
5028           case 'y':
5029           case 'z':
5030           case 'A':
5031           case 'E':
5032           case 'F':
5033           case 'G':
5034           case 'I':
5035           case 'J':
5036           case 'K':
5037           case 'M':
5038           case 'N':
5039           case 'P':
5040           case 'Q':
5041           case 'R':
5042           case 'S':
5043           case 'T':
5044           case 'U':
5045           case 'V':
5046           case 'W':
5047           case 'X':
5048           case 'Y':
5049           case 'Z':
5050            letter:
5051              {
5052                 HASHNODE           *hp;
5053                 char               *ident;
5054                 int                 before_name_written = CPP_WRITTEN(pfile);
5055                 int                 ident_len;
5056
5057                 parse_name(pfile, c);
5058                 pfile->only_seen_white = 0;
5059                 if (pfile->no_macro_expand)
5060                    return CPP_NAME;
5061                 ident = (char *)pfile->token_buffer + before_name_written;
5062                 ident_len = CPP_PWRITTEN(pfile) - (unsigned char *)ident;
5063                 hp = cpp_lookup(ident, ident_len, -1);
5064                 if (!hp)
5065                    return CPP_NAME;
5066                 if (hp->type == T_DISABLED)
5067                   {
5068                      if (pfile->output_escapes)
5069                        {        /* Return "@-IDENT", followed by '\0'. */
5070                           int                 i;
5071
5072                           CPP_RESERVE(pfile, 3);
5073                           ident =
5074                              (char *)pfile->token_buffer + before_name_written;
5075                           CPP_ADJUST_WRITTEN(pfile, 2);
5076                           for (i = ident_len; i >= 0; i--)
5077                              ident[i + 2] = ident[i];
5078                           ident[0] = '@';
5079                           ident[1] = '-';
5080                        }
5081                      return CPP_NAME;
5082                   }
5083                 /* If macro wants an arglist, verify that a '(' follows.
5084                  * first skip all whitespace, copying it to the output
5085                  * after the macro name.  Then, if there is no '(',
5086                  * decide this is not a macro call and leave things that way.  */
5087                 if (hp->type == T_MACRO && hp->value.defn->nargs >= 0)
5088                   {
5089                      struct parse_marker macro_mark;
5090                      int                 is_macro_call;
5091
5092                      while (CPP_IS_MACRO_BUFFER(CPP_BUFFER(pfile)))
5093                        {
5094                           cpp_buffer         *next_buf;
5095
5096                           cpp_skip_hspace(pfile);
5097                           if (PEEKC() != EOF)
5098                              break;
5099                           next_buf = CPP_PREV_BUFFER(CPP_BUFFER(pfile));
5100                           (*CPP_BUFFER(pfile)->cleanup) (CPP_BUFFER(pfile),
5101                                                          pfile);
5102                           CPP_BUFFER(pfile) = next_buf;
5103                        }
5104                      parse_set_mark(&macro_mark, pfile);
5105                      for (;;)
5106                        {
5107                           cpp_skip_hspace(pfile);
5108                           c = PEEKC();
5109                           is_macro_call = c == '(';
5110                           if (c != '\n')
5111                              break;
5112                           FORWARD(1);
5113                        }
5114                      if (!is_macro_call)
5115                         parse_goto_mark(&macro_mark, pfile);
5116                      parse_clear_mark(&macro_mark);
5117                      if (!is_macro_call)
5118                         return CPP_NAME;
5119                   }
5120                 /* This is now known to be a macro call. */
5121
5122                 /* it might not actually be a macro.  */
5123                 if (hp->type != T_MACRO)
5124                   {
5125                      int                 xbuf_len;
5126                      unsigned char      *xbuf;
5127
5128                      CPP_SET_WRITTEN(pfile, before_name_written);
5129                      special_symbol(hp, pfile);
5130                      xbuf_len = CPP_WRITTEN(pfile) - before_name_written;
5131                      xbuf = (unsigned char *)xmalloc(xbuf_len + 1);
5132                      CPP_SET_WRITTEN(pfile, before_name_written);
5133                      memcpy(xbuf, CPP_PWRITTEN(pfile), xbuf_len + 1);
5134                      push_macro_expansion(pfile, xbuf, xbuf_len, hp);
5135                   }
5136                 else
5137                   {
5138                      /* Expand the macro, reading arguments as needed,
5139                       * and push the expansion on the input stack.  */
5140                      macroexpand(pfile, hp);
5141                      CPP_SET_WRITTEN(pfile, before_name_written);
5142                   }
5143
5144                 /* An extra "@ " is added to the end of a macro expansion
5145                  * to prevent accidental token pasting.  We prefer to avoid
5146                  * unneeded extra spaces (for the sake of cpp-using tools like
5147                  * imake).  Here we remove the space if it is safe to do so. */
5148                 if (pfile->buffer->rlimit - pfile->buffer->cur >= 3
5149                     && pfile->buffer->rlimit[-2] == '@'
5150                     && pfile->buffer->rlimit[-1] == ' ')
5151                   {
5152                      int                 c1 = pfile->buffer->rlimit[-3];
5153
5154                      c2 = CPP_BUF_PEEK(CPP_PREV_BUFFER(CPP_BUFFER(pfile)));
5155
5156                      if (c2 == EOF || !unsafe_chars(c1, c2))
5157                         pfile->buffer->rlimit -= 2;
5158                   }
5159              }
5160              goto get_next;
5161
5162           case ' ':
5163           case '\t':
5164           case '\v':
5165           case '\r':
5166              for (;;)
5167                {
5168                   CPP_PUTC(pfile, c);
5169                   c = PEEKC();
5170                   if (c == EOF || !is_hor_space[c])
5171                      break;
5172                   FORWARD(1);
5173                }
5174              return CPP_HSPACE;
5175
5176           case '\\':
5177              c2 = PEEKC();
5178              if (c2 != '\n')
5179                 goto randomchar;
5180              token = CPP_HSPACE;
5181              goto op2any;
5182
5183           case '\n':
5184              CPP_PUTC(pfile, c);
5185              if (pfile->only_seen_white == 0)
5186                 pfile->only_seen_white = 1;
5187              pfile->lineno++;
5188              output_line_command(pfile, 1, same_file);
5189              return CPP_VSPACE;
5190
5191           case '(':
5192              token = CPP_LPAREN;
5193              goto char1;
5194           case ')':
5195              token = CPP_RPAREN;
5196              goto char1;
5197           case '{':
5198              token = CPP_LBRACE;
5199              goto char1;
5200           case '}':
5201              token = CPP_RBRACE;
5202              goto char1;
5203           case ',':
5204              token = CPP_COMMA;
5205              goto char1;
5206           case ';':
5207              token = CPP_SEMICOLON;
5208              goto char1;
5209
5210            randomchar:
5211           default:
5212              token = CPP_OTHER;
5213            char1:
5214              pfile->only_seen_white = 0;
5215              CPP_PUTC(pfile, c);
5216              return token;
5217           }
5218      }
5219 }
5220
5221 #if 0                           /* Unused */
5222 /* Like cpp_get_token, but skip spaces and comments. */
5223 enum cpp_token
5224 cpp_get_non_space_token(cpp_reader * pfile)
5225 {
5226    int                 old_written = CPP_WRITTEN(pfile);
5227
5228    for (;;)
5229      {
5230         enum cpp_token      token = cpp_get_token(pfile);
5231
5232         if (token != CPP_COMMENT && token != CPP_POP
5233             && token != CPP_HSPACE && token != CPP_VSPACE)
5234            return token;
5235         CPP_SET_WRITTEN(pfile, old_written);
5236      }
5237 }
5238 #endif
5239
5240 /* Parse an identifier starting with C. */
5241
5242 int
5243 parse_name(cpp_reader * pfile, int c)
5244 {
5245    for (;;)
5246      {
5247         if (!is_idchar[c])
5248           {
5249              if (c == '\\' && PEEKC() == '\n')
5250                {
5251                   FORWARD(2);
5252                   continue;
5253                }
5254              FORWARD(-1);
5255              break;
5256           }
5257         CPP_RESERVE(pfile, 2);  /* One more for final NUL. */
5258         CPP_PUTC_Q(pfile, c);
5259         c = GETC();
5260         if (c == EOF)
5261            break;
5262      }
5263    CPP_NUL_TERMINATE_Q(pfile);
5264    return 1;
5265 }
5266
5267 /* Maintain and search list of included files, for #import.  */
5268
5269 /* Hash a file name for import_hash_table.  */
5270
5271 static int
5272 import_hash(char *f)
5273 {
5274    int                 val = 0;
5275
5276    while (*f)
5277       val += *f++;
5278    return (val % IMPORT_HASH_SIZE);
5279 }
5280
5281 /* Search for file FILENAME in import_hash_table.
5282  * Return -2 if found, either a matching name or a matching inode.
5283  * Otherwise, open the file and return a file descriptor if successful
5284  * or -1 if unsuccessful.  */
5285
5286 static int
5287 lookup_import(cpp_reader * pfile, char *filename,
5288               struct file_name_list *searchptr)
5289 {
5290    struct import_file *i;
5291    int                 h;
5292    int                 hashval;
5293    struct stat         sb;
5294    int                 fd;
5295
5296    hashval = import_hash(filename);
5297
5298    /* Attempt to find file in list of already included files */
5299    i = pfile->import_hash_table[hashval];
5300
5301    while (i)
5302      {
5303         if (!strcmp(filename, i->name))
5304            return -2;           /* return found */
5305         i = i->next;
5306      }
5307    /* Open it and try a match on inode/dev */
5308    fd = open_include_file(pfile, filename, searchptr);
5309    if (fd < 0)
5310       return fd;
5311    fstat(fd, &sb);
5312    for (h = 0; h < IMPORT_HASH_SIZE; h++)
5313      {
5314         i = pfile->import_hash_table[h];
5315         while (i)
5316           {
5317              /* Compare the inode and the device.
5318               * Supposedly on some systems the inode is not a scalar.  */
5319              if (!memcmp
5320                  ((char *)&i->inode, (char *)&sb.st_ino, sizeof(sb.st_ino))
5321                  && i->dev == sb.st_dev)
5322                {
5323                   close(fd);
5324                   return -2;    /* return found */
5325                }
5326              i = i->next;
5327           }
5328      }
5329    return fd;                   /* Not found, return open file */
5330 }
5331
5332 /* Add the file FNAME, open on descriptor FD, to import_hash_table.  */
5333
5334 static void
5335 add_import(cpp_reader * pfile, int fd, char *fname)
5336 {
5337    struct import_file *i;
5338    int                 hashval;
5339    struct stat         sb;
5340
5341    hashval = import_hash(fname);
5342    fstat(fd, &sb);
5343    i = (struct import_file *)xmalloc(sizeof(struct import_file));
5344
5345    i->name = (char *)xmalloc(strlen(fname) + 1);
5346    strcpy(i->name, fname);
5347    memcpy((char *)&i->inode, (char *)&sb.st_ino, sizeof(sb.st_ino));
5348    i->dev = sb.st_dev;
5349    i->next = pfile->import_hash_table[hashval];
5350    pfile->import_hash_table[hashval] = i;
5351 }
5352
5353 /* The file_name_map structure holds a mapping of file names for a
5354  * particular directory.  This mapping is read from the file named
5355  * FILE_NAME_MAP_FILE in that directory.  Such a file can be used to
5356  * map filenames on a file system with severe filename restrictions,
5357  * such as DOS.  The format of the file name map file is just a series
5358  * of lines with two tokens on each line.  The first token is the name
5359  * to map, and the second token is the actual name to use.  */
5360
5361 struct file_name_map {
5362    struct file_name_map *map_next;
5363    char               *map_from;
5364    char               *map_to;
5365 };
5366
5367 #if USE_FILE_NAME_MAPS
5368
5369 #define FILE_NAME_MAP_FILE "header.gcc"
5370
5371 /* Read a space delimited string of unlimited length from a stdio
5372  * file.  */
5373
5374 static char        *
5375 read_filename_string(int ch, FILE * f)
5376 {
5377    char               *alloc, *set;
5378    int                 len;
5379
5380    len = 20;
5381    set = alloc = (char *)xmalloc(len + 1);
5382    if (!is_space[ch])
5383      {
5384         *set++ = ch;
5385         while ((ch = getc(f)) != EOF && !is_space[ch])
5386           {
5387              if (set - alloc == len)
5388                {
5389                   len *= 2;
5390                   alloc = (char *)xrealloc(alloc, len + 1);
5391                   set = alloc + len / 2;
5392                }
5393              *set++ = ch;
5394           }
5395      }
5396    *set = '\0';
5397    ungetc(ch, f);
5398    return alloc;
5399 }
5400
5401 /* This structure holds a linked list of file name maps, one per directory. */
5402 struct file_name_map_list {
5403    struct file_name_map_list *map_list_next;
5404    char               *map_list_name;
5405    struct file_name_map *map_list_map;
5406 };
5407
5408 /* Read the file name map file for DIRNAME.  */
5409
5410 static struct file_name_map *
5411 read_name_map(cpp_reader * pfile, const char *dirname)
5412 {
5413    struct file_name_map_list *map_list_ptr;
5414    char               *name;
5415    FILE               *f;
5416
5417    for (map_list_ptr = CPP_OPTIONS(pfile)->map_list; map_list_ptr;
5418         map_list_ptr = map_list_ptr->map_list_next)
5419       if (!strcmp(map_list_ptr->map_list_name, dirname))
5420          return map_list_ptr->map_list_map;
5421
5422    map_list_ptr =
5423       ((struct file_name_map_list *)xmalloc(sizeof(struct file_name_map_list)));
5424
5425    map_list_ptr->map_list_name = savestring(dirname);
5426    map_list_ptr->map_list_map = NULL;
5427
5428    name = (char *)alloca(strlen(dirname) + strlen(FILE_NAME_MAP_FILE) + 2);
5429    strcpy(name, dirname);
5430    if (*dirname)
5431       strcat(name, "/");
5432    strcat(name, FILE_NAME_MAP_FILE);
5433 #ifndef __EMX__
5434    f = fopen(name, "r");
5435 #else
5436    f = fopen(name, "rt");
5437 #endif
5438    if (!f)
5439       map_list_ptr->map_list_map = NULL;
5440    else
5441      {
5442         int                 ch;
5443         int                 dirlen = strlen(dirname);
5444
5445         while ((ch = getc(f)) != EOF)
5446           {
5447              char               *from, *to;
5448              struct file_name_map *ptr;
5449
5450              if (is_space[ch])
5451                 continue;
5452              from = read_filename_string(ch, f);
5453              while ((ch = getc(f)) != EOF && is_hor_space[ch]);
5454              to = read_filename_string(ch, f);
5455
5456              ptr =
5457                 ((struct file_name_map *)xmalloc(sizeof(struct file_name_map)));
5458
5459              ptr->map_from = from;
5460
5461              /* Make the real filename absolute.  */
5462              if (*to == '/')
5463                 ptr->map_to = to;
5464              else
5465                {
5466                   ptr->map_to = (char *)xmalloc(dirlen + strlen(to) + 2);
5467                   strcpy(ptr->map_to, dirname);
5468                   ptr->map_to[dirlen] = '/';
5469                   strcpy(ptr->map_to + dirlen + 1, to);
5470                   free(to);
5471                }
5472
5473              ptr->map_next = map_list_ptr->map_list_map;
5474              map_list_ptr->map_list_map = ptr;
5475
5476              while ((ch = getc(f)) != '\n')
5477                 if (ch == EOF)
5478                    break;
5479           }
5480         fclose(f);
5481      }
5482
5483    map_list_ptr->map_list_next = CPP_OPTIONS(pfile)->map_list;
5484    CPP_OPTIONS(pfile)->map_list = map_list_ptr;
5485
5486    return map_list_ptr->map_list_map;
5487 }
5488
5489 /* Try to open include file FILENAME.  SEARCHPTR is the directory
5490  * being tried from the include file search path.  This function maps
5491  * filenames on file systems based on information read by
5492  * read_name_map.  */
5493
5494 static int
5495 open_include_file(cpp_reader * pfile, char *filename,
5496                   struct file_name_list *searchptr)
5497 {
5498    struct file_name_map *map;
5499    const char         *from;
5500    const char         *p, *dir;
5501
5502    if (searchptr && !searchptr->got_name_map)
5503      {
5504         searchptr->name_map = read_name_map(pfile,
5505                                             searchptr->fname
5506                                             ? searchptr->fname : ".");
5507         searchptr->got_name_map = 1;
5508      }
5509    /* First check the mapping for the directory we are using.  */
5510    if (searchptr && searchptr->name_map)
5511      {
5512         from = filename;
5513         if (searchptr->fname)
5514            from += strlen(searchptr->fname) + 1;
5515         for (map = searchptr->name_map; map; map = map->map_next)
5516           {
5517              if (!strcmp(map->map_from, from))
5518                {
5519                   /* Found a match.  */
5520                   return open(map->map_to, O_RDONLY, 0666);
5521                }
5522           }
5523      }
5524    /* Try to find a mapping file for the particular directory we are
5525     * looking in.  Thus #include <sys/types.h> will look up sys/types.h
5526     * in /usr/include/header.gcc and look up types.h in
5527     * /usr/include/sys/header.gcc.  */
5528    p = strrchr(filename, '/');
5529    if (!p)
5530       p = filename;
5531    if (searchptr
5532        && searchptr->fname
5533        && strlen(searchptr->fname) == (unsigned)(p - filename)
5534        && !strncmp(searchptr->fname, filename, p - filename))
5535      {
5536         /* FILENAME is in SEARCHPTR, which we've already checked.  */
5537         return open(filename, O_RDONLY, 0666);
5538      }
5539    if (p == filename)
5540      {
5541         dir = ".";
5542         from = filename;
5543      }
5544    else
5545      {
5546         char               *s;
5547
5548         s = (char *)alloca(p - filename + 1);
5549         memcpy(s, filename, p - filename);
5550         s[p - filename] = '\0';
5551         from = p + 1;
5552         dir = s;
5553      }
5554    for (map = read_name_map(pfile, dir); map; map = map->map_next)
5555       if (!strcmp(map->map_from, from))
5556          return open(map->map_to, O_RDONLY, 0666);
5557
5558    return open(filename, O_RDONLY, 0666);
5559 }
5560
5561 #else
5562
5563 static int
5564 open_include_file(cpp_reader * pfile, char *filename,
5565                   struct file_name_list *searchptr)
5566 {
5567    pfile = NULL;
5568    searchptr = NULL;
5569    return open(filename, O_RDONLY, 0666);
5570 }
5571
5572 #endif /* USE_FILE_NAME_MAPS */
5573
5574 /* Process the contents of include file FNAME, already open on descriptor F,
5575  * with output to OP.
5576  * SYSTEM_HEADER_P is 1 if this file resides in any one of the known
5577  * "system" include directories (as decided by the `is_system_include'
5578  * function above).
5579  * DIRPTR is the link in the dir path through which this file was found,
5580  * or 0 if the file name was absolute or via the current directory.
5581  * Return 1 on success, 0 on failure.
5582  * 
5583  * The caller is responsible for the cpp_push_buffer.  */
5584
5585 static int
5586 finclude(cpp_reader * pfile, int f, const char *fname, int system_header_p,
5587          struct file_name_list *dirptr)
5588 {
5589    int                 st_mode;
5590    long                st_size;
5591    long                i;
5592    int                 length;
5593    cpp_buffer         *fp;      /* For input stack frame */
5594
5595    if (file_size_and_mode(f, &st_mode, &st_size) < 0)
5596      {
5597         cpp_perror_with_name(pfile, fname);
5598         close(f);
5599         cpp_pop_buffer(pfile);
5600         return 0;
5601      }
5602    fp = CPP_BUFFER(pfile);
5603    fp->nominal_fname = fp->fname = fname;
5604    fp->dir = dirptr;
5605    fp->system_header_p = system_header_p;
5606    fp->lineno = 1;
5607    fp->colno = 1;
5608    fp->cleanup = file_cleanup;
5609
5610    if (S_ISREG(st_mode))
5611      {
5612         fp->buf = (unsigned char *)xmalloc(st_size + 2);
5613         fp->alimit = fp->buf + st_size + 2;
5614         fp->cur = fp->buf;
5615
5616         /* Read the file contents, knowing that st_size is an upper bound
5617          * on the number of bytes we can read.  */
5618         length = safe_read(f, (char *)fp->buf, st_size);
5619         fp->rlimit = fp->buf + length;
5620         if (length < 0)
5621            goto nope;
5622      }
5623    else if (S_ISDIR(st_mode))
5624      {
5625         cpp_error(pfile, "directory `%s' specified in #include", fname);
5626         close(f);
5627         return 0;
5628      }
5629    else
5630      {
5631         /* Cannot count its file size before reading.
5632          * First read the entire file into heap and
5633          * copy them into buffer on stack. */
5634
5635         int                 bsize = 2000;
5636
5637         st_size = 0;
5638         fp->buf = (unsigned char *)xmalloc(bsize + 2);
5639
5640         for (;;)
5641           {
5642              i = safe_read(f, (char *)(fp->buf + st_size), bsize - st_size);
5643              if (i < 0)
5644                 goto nope;      /* error! */
5645              st_size += i;
5646              if (st_size != bsize)
5647                 break;          /* End of file */
5648              bsize *= 2;
5649              fp->buf = (unsigned char *)xrealloc(fp->buf, bsize + 2);
5650           }
5651         length = st_size;
5652      }
5653
5654    if ((length > 0 && fp->buf[length - 1] != '\n')
5655        /* Backslash-newline at end is not good enough.  */
5656        || (length > 1 && fp->buf[length - 2] == '\\'))
5657      {
5658         fp->buf[length++] = '\n';
5659      }
5660    fp->buf[length] = '\0';
5661    fp->rlimit = fp->buf + length;
5662
5663    /* Close descriptor now, so nesting does not use lots of descriptors.  */
5664    close(f);
5665
5666    /* Must do this before calling trigraph_pcp, so that the correct file name
5667     * will be printed in warning messages.  */
5668
5669    pfile->input_stack_listing_current = 0;
5670
5671    return 1;
5672
5673  nope:
5674
5675    cpp_perror_with_name(pfile, fname);
5676    close(f);
5677    free(fp->buf);
5678    return 1;
5679 }
5680
5681 int
5682 push_parse_file(cpp_reader * pfile, const char *fname)
5683 {
5684    struct cpp_options *opts = CPP_OPTIONS(pfile);
5685    struct cpp_pending *pend;
5686    char               *p;
5687    int                 f;
5688    cpp_buffer         *fp;
5689
5690    /* The code looks at the defaults through this pointer, rather than through
5691     * the constant structure above.  This pointer gets changed if an environment
5692     * variable specifies other defaults.  */
5693    struct default_include *include_defaults = include_defaults_array;
5694
5695    /* Add dirs from CPATH after dirs from -I.  */
5696    /* There seems to be confusion about what CPATH should do,
5697     * so for the moment it is not documented.  */
5698    /* Some people say that CPATH should replace the standard include dirs,
5699     * but that seems pointless: it comes before them, so it overrides them
5700     * anyway.  */
5701    p = (char *)getenv("CPATH");
5702    if (p != 0 && !opts->no_standard_includes)
5703       path_include(pfile, p);
5704
5705    /* Now that dollars_in_ident is known, initialize is_idchar.  */
5706    initialize_char_syntax(opts);
5707
5708    /* Do partial setup of input buffer for the sake of generating
5709     * early #line directives (when -g is in effect).  */
5710    fp = cpp_push_buffer(pfile, NULL, 0);
5711    if (opts->in_fname == NULL)
5712       opts->in_fname = "";
5713    fp->nominal_fname = fp->fname = opts->in_fname;
5714    fp->lineno = 0;
5715
5716    /* Install __LINE__, etc.  Must follow initialize_char_syntax
5717     * and option processing.  */
5718    initialize_builtins(pfile);
5719
5720    /* Do standard #defines and assertions
5721     * that identify system and machine type.  */
5722
5723    if (!opts->inhibit_predefs)
5724      {
5725         p = (char *)alloca(strlen(predefs) + 1);
5726
5727         strcpy(p, predefs);
5728         while (*p)
5729           {
5730              char               *q;
5731
5732              while (*p == ' ' || *p == '\t')
5733                 p++;
5734              /* Handle -D options.  */
5735              if (p[0] == '-' && p[1] == 'D')
5736                {
5737                   q = &p[2];
5738                   while (*p && *p != ' ' && *p != '\t')
5739                      p++;
5740                   if (*p != 0)
5741                      *p++ = 0;
5742                   if (opts->debug_output)
5743                      output_line_command(pfile, 0, same_file);
5744                   cpp_define(pfile, (unsigned char *)q);
5745                   while (*p == ' ' || *p == '\t')
5746                      p++;
5747                }
5748              else if (p[0] == '-' && p[1] == 'A')
5749                {
5750                   /* Handle -A options (assertions).  */
5751                   char               *assertion;
5752                   char               *past_name;
5753                   char               *value;
5754                   char               *past_value;
5755                   char               *termination;
5756                   int                 save_char;
5757
5758                   assertion = &p[2];
5759                   past_name = assertion;
5760                   /* Locate end of name.  */
5761                   while (*past_name && *past_name != ' '
5762                          && *past_name != '\t' && *past_name != '(')
5763                      past_name++;
5764                   /* Locate `(' at start of value.  */
5765                   value = past_name;
5766                   while (*value && (*value == ' ' || *value == '\t'))
5767                      value++;
5768                   if (*value++ != '(')
5769                      abort();
5770                   while (*value && (*value == ' ' || *value == '\t'))
5771                      value++;
5772                   past_value = value;
5773                   /* Locate end of value.  */
5774                   while (*past_value && *past_value != ' '
5775                          && *past_value != '\t' && *past_value != ')')
5776                      past_value++;
5777                   termination = past_value;
5778                   while (*termination
5779                          && (*termination == ' ' || *termination == '\t'))
5780                      termination++;
5781                   if (*termination++ != ')')
5782                      abort();
5783                   if (*termination && *termination != ' '
5784                       && *termination != '\t')
5785                      abort();
5786                   /* Temporarily null-terminate the value.  */
5787                   save_char = *termination;
5788                   *termination = '\0';
5789                   /* Install the assertion.  */
5790                   make_assertion(pfile, "-A", assertion);
5791                   *termination = (char)save_char;
5792                   p = termination;
5793                   while (*p == ' ' || *p == '\t')
5794                      p++;
5795                }
5796              else
5797                {
5798                   abort();
5799                }
5800           }
5801      }
5802    /* Now handle the command line options.  */
5803
5804    /* Do -U's, -D's and -A's in the order they were seen.  */
5805    /* First reverse the list. */
5806    opts->pending = nreverse_pending(opts->pending);
5807
5808    for (pend = opts->pending; pend; pend = pend->next)
5809      {
5810         if (pend->cmd != NULL && pend->cmd[0] == '-')
5811           {
5812              switch (pend->cmd[1])
5813                {
5814                case 'U':
5815                   if (opts->debug_output)
5816                      output_line_command(pfile, 0, same_file);
5817                   do_undef(pfile, NULL, (unsigned char *)pend->arg,
5818                            (unsigned char *)pend->arg + strlen(pend->arg));
5819                   break;
5820                case 'D':
5821                   if (opts->debug_output)
5822                      output_line_command(pfile, 0, same_file);
5823                   cpp_define(pfile, (unsigned char *)pend->arg);
5824                   break;
5825                case 'A':
5826                   make_assertion(pfile, "-A", pend->arg);
5827                   break;
5828                }
5829           }
5830      }
5831
5832    opts->done_initializing = 1;
5833
5834    {                            /* read the appropriate environment variable and if it exists
5835                                  * replace include_defaults with the listed path. */
5836       char               *epath = 0;
5837
5838       switch ((opts->objc << 1) + opts->cplusplus)
5839         {
5840         case 0:
5841            epath = getenv("C_INCLUDE_PATH");
5842            break;
5843         case 1:
5844            epath = getenv("CPLUS_INCLUDE_PATH");
5845            break;
5846         case 2:
5847            epath = getenv("OBJC_INCLUDE_PATH");
5848            break;
5849         case 3:
5850            epath = getenv("OBJCPLUS_INCLUDE_PATH");
5851            break;
5852         }
5853       /* If the environment var for this language is set,
5854        * add to the default list of include directories.  */
5855       if (epath)
5856         {
5857            char               *nstore = (char *)alloca(strlen(epath) + 2);
5858            int                 num_dirs;
5859            char               *startp, *endp;
5860
5861            for (num_dirs = 1, startp = epath; *startp; startp++)
5862               if (*startp == PATH_SEPARATOR)
5863                  num_dirs++;
5864            include_defaults
5865               = (struct default_include *)xmalloc((num_dirs
5866                                                    *
5867                                                    sizeof(struct
5868                                                           default_include)) +
5869                                                   sizeof
5870                                                   (include_defaults_array));
5871
5872            startp = endp = epath;
5873            num_dirs = 0;
5874            while (1)
5875              {
5876                 /* Handle cases like c:/usr/lib:d:/gcc/lib */
5877                 if ((*endp == PATH_SEPARATOR) || *endp == 0)
5878                   {
5879                      strncpy(nstore, startp, endp - startp);
5880                      if (endp == startp)
5881                         strcpy(nstore, ".");
5882                      else
5883                         nstore[endp - startp] = '\0';
5884
5885                      include_defaults[num_dirs].fname = savestring(nstore);
5886                      include_defaults[num_dirs].cplusplus = opts->cplusplus;
5887                      include_defaults[num_dirs].cxx_aware = 1;
5888                      num_dirs++;
5889                      if (*endp == '\0')
5890                         break;
5891                      endp = startp = endp + 1;
5892                   }
5893                 else
5894                    endp++;
5895              }
5896            /* Put the usual defaults back in at the end.  */
5897            memcpy((char *)&include_defaults[num_dirs],
5898                   (char *)include_defaults_array,
5899                   sizeof(include_defaults_array));
5900         }
5901    }
5902
5903    append_include_chain(pfile, opts->before_system, opts->last_before_system);
5904    opts->first_system_include = opts->before_system;
5905
5906    /* Unless -fnostdinc,
5907     * tack on the standard include file dirs to the specified list */
5908    if (!opts->no_standard_includes)
5909      {
5910         struct default_include *di = include_defaults;
5911         char               *specd_prefix = opts->include_prefix;
5912         char               *default_prefix = savestring(GCC_INCLUDE_DIR);
5913         int                 default_len = 0;
5914
5915         /* Remove the `include' from /usr/local/lib/gcc.../include.  */
5916         if (!strcmp(default_prefix + strlen(default_prefix) - 8, "/include"))
5917           {
5918              default_len = strlen(default_prefix) - 7;
5919              default_prefix[default_len] = 0;
5920           }
5921         /* Search "translated" versions of GNU directories.
5922          * These have /usr/local/lib/gcc... replaced by specd_prefix.  */
5923         if (specd_prefix != 0 && default_len != 0)
5924            for (di = include_defaults; di->fname; di++)
5925              {
5926                 /* Some standard dirs are only for C++.  */
5927                 if (!di->cplusplus
5928                     || (opts->cplusplus
5929                         && !opts->no_standard_cplusplus_includes))
5930                   {
5931                      /* Does this dir start with the prefix?  */
5932                      if (!strncmp(di->fname, default_prefix, default_len))
5933                        {
5934                           /* Yes; change prefix and add to search list.  */
5935                           struct file_name_list *new_
5936                              =
5937                              (struct file_name_list *)
5938                              xmalloc(sizeof(struct file_name_list));
5939                           int                 this_len =
5940                              strlen(specd_prefix) + strlen(di->fname) -
5941                              default_len;
5942                           char               *str =
5943                              (char *)xmalloc(this_len + 1);
5944
5945                           strcpy(str, specd_prefix);
5946                           strcat(str, di->fname + default_len);
5947                           new_->fname = str;
5948                           new_->control_macro = 0;
5949                           new_->c_system_include_path = !di->cxx_aware;
5950                           new_->got_name_map = 0;
5951                           append_include_chain(pfile, new_, new_);
5952                           if (opts->first_system_include == 0)
5953                              opts->first_system_include = new_;
5954                        }
5955                   }
5956              }
5957         /* Search ordinary names for GNU include directories.  */
5958         for (di = include_defaults; di->fname; di++)
5959           {
5960              /* Some standard dirs are only for C++.  */
5961              if (!di->cplusplus
5962                  || (opts->cplusplus && !opts->no_standard_cplusplus_includes))
5963                {
5964                   struct file_name_list *new_
5965                      = (struct file_name_list *)
5966                      xmalloc(sizeof(struct file_name_list));
5967
5968                   new_->control_macro = 0;
5969                   new_->c_system_include_path = !di->cxx_aware;
5970                   new_->fname = (char *)di->fname;
5971                   new_->got_name_map = 0;
5972                   append_include_chain(pfile, new_, new_);
5973                   if (opts->first_system_include == 0)
5974                      opts->first_system_include = new_;
5975                }
5976           }
5977      }
5978    /* Tack the after_include chain at the end of the include chain.  */
5979    append_include_chain(pfile, opts->after_include, opts->last_after_include);
5980    if (opts->first_system_include == 0)
5981       opts->first_system_include = opts->after_include;
5982
5983    /* With -v, print the list of dirs to search.  */
5984    if (opts->verbose)
5985      {
5986         struct file_name_list *fl;
5987
5988         fprintf(stderr, "#include \"...\" search starts here:\n");
5989         for (fl = opts->include; fl; fl = fl->next)
5990           {
5991              if (fl == opts->first_bracket_include)
5992                 fprintf(stderr, "#include <...> search starts here:\n");
5993              fprintf(stderr, " %s\n", fl->fname);
5994           }
5995         fprintf(stderr, "End of search list.\n");
5996      }
5997    /* Scan the -imacros files before the main input.
5998     * Much like #including them, but with no_output set
5999     * so that only their macro definitions matter.  */
6000
6001    opts->no_output++;
6002    pfile->no_record_file++;
6003    for (pend = opts->pending; pend; pend = pend->next)
6004      {
6005         if (pend->cmd != NULL && strcmp(pend->cmd, "-imacros") == 0)
6006           {
6007              int                 fd = open(pend->arg, O_RDONLY, 0666);
6008
6009              if (fd < 0)
6010                {
6011                   cpp_perror_with_name(pfile, pend->arg);
6012                   return FATAL_EXIT_CODE;
6013                }
6014              cpp_push_buffer(pfile, NULL, 0);
6015              finclude(pfile, fd, pend->arg, 0, NULL);
6016              cpp_scan_buffer(pfile);
6017           }
6018      }
6019    opts->no_output--;
6020    pfile->no_record_file--;
6021
6022    /* Copy the entire contents of the main input file into
6023     * the stacked input buffer previously allocated for it.  */
6024    if (fname == NULL || *fname == 0)
6025      {
6026         fname = "";
6027         f = 0;
6028      }
6029    else if ((f = open(fname, O_RDONLY, 0666)) < 0)
6030       cpp_pfatal_with_name(pfile, fname);
6031
6032    /* -MG doesn't select the form of output and must be specified with one of
6033     * -M or -MM.  -MG doesn't make sense with -MD or -MMD since they don't
6034     * inhibit compilation.  */
6035    if (opts->print_deps_missing_files
6036        && (opts->print_deps == 0 || !opts->no_output))
6037       cpp_fatal("-MG must be specified with one of -M or -MM");
6038
6039    /* Either of two environment variables can specify output of deps.
6040     * Its value is either "OUTPUT_FILE" or "OUTPUT_FILE DEPS_TARGET",
6041     * where OUTPUT_FILE is the file to write deps info to
6042     * and DEPS_TARGET is the target to mention in the deps.  */
6043
6044    if (opts->print_deps == 0
6045        && (getenv("SUNPRO_DEPENDENCIES") != 0
6046            || getenv("DEPENDENCIES_OUTPUT") != 0))
6047      {
6048         char               *spec = getenv("DEPENDENCIES_OUTPUT");
6049         char               *s;
6050         char               *output_file;
6051
6052         if (spec == 0)
6053           {
6054              spec = getenv("SUNPRO_DEPENDENCIES");
6055              opts->print_deps = 2;
6056           }
6057         else
6058            opts->print_deps = 1;
6059
6060         s = spec;
6061         /* Find the space before the DEPS_TARGET, if there is one.  */
6062         /* This should use index.  (mrs) */
6063         while (*s != 0 && *s != ' ')
6064            s++;
6065         if (*s != 0)
6066           {
6067              opts->deps_target = s + 1;
6068              output_file = (char *)xmalloc(s - spec + 1);
6069              memcpy(output_file, spec, s - spec);
6070              output_file[s - spec] = 0;
6071           }
6072         else
6073           {
6074              opts->deps_target = 0;
6075              output_file = spec;
6076           }
6077
6078         opts->deps_file = output_file;
6079         opts->print_deps_append = 1;
6080      }
6081    /* For -M, print the expected object file name
6082     * as the target of this Make-rule.  */
6083    if (opts->print_deps)
6084      {
6085         pfile->deps_allocated_size = 200;
6086         pfile->deps_buffer = (char *)xmalloc(pfile->deps_allocated_size);
6087         pfile->deps_buffer[0] = 0;
6088         pfile->deps_size = 0;
6089         pfile->deps_column = 0;
6090
6091         if (opts->deps_target)
6092            deps_output(pfile, opts->deps_target, ':');
6093         else if (*opts->in_fname == 0)
6094            deps_output(pfile, "-", ':');
6095         else
6096           {
6097              char               *q;
6098              int                 len;
6099
6100              /* Discard all directory prefixes from filename.  */
6101              if ((q = (char *)strrchr(opts->in_fname, '/')) != NULL
6102 #ifdef DIR_SEPARATOR
6103                  && (q = strrchr(opts->in_fname, DIR_SEPARATOR)) != NULL
6104 #endif
6105                 )
6106                 ++q;
6107              else
6108                 q = (char *)opts->in_fname;
6109
6110              /* Copy remainder to mungable area.  */
6111              p = (char *)alloca(strlen(q) + 8);
6112              strcpy(p, q);
6113
6114              /* Output P, but remove known suffixes.  */
6115              len = strlen(p);
6116              q = p + len;
6117              if (len >= 2 && p[len - 2] == '.' && strchr("cCsSm", p[len - 1]))
6118                 q = p + (len - 2);
6119              else if (len >= 3
6120                       && p[len - 3] == '.'
6121                       && p[len - 2] == 'c' && p[len - 1] == 'c')
6122                 q = p + (len - 3);
6123              else if (len >= 4
6124                       && p[len - 4] == '.'
6125                       && p[len - 3] == 'c'
6126                       && p[len - 2] == 'x' && p[len - 1] == 'x')
6127                 q = p + (len - 4);
6128              else if (len >= 4
6129                       && p[len - 4] == '.'
6130                       && p[len - 3] == 'c'
6131                       && p[len - 2] == 'p' && p[len - 1] == 'p')
6132                 q = p + (len - 4);
6133
6134              /* Supply our own suffix.  */
6135              strcpy(q, ".o");
6136
6137              deps_output(pfile, p, ':');
6138              deps_output(pfile, opts->in_fname, ' ');
6139           }
6140      }
6141
6142    /* Scan the -include files before the main input.
6143     * We push these in reverse order, so that the first one is handled first.  */
6144
6145    pfile->no_record_file++;
6146    opts->pending = nreverse_pending(opts->pending);
6147    for (pend = opts->pending; pend; pend = pend->next)
6148      {
6149         if (pend->cmd != NULL && strcmp(pend->cmd, "-include") == 0)
6150           {
6151              int                 fd = open(pend->arg, O_RDONLY, 0666);
6152
6153              if (fd < 0)
6154                {
6155                   cpp_perror_with_name(pfile, pend->arg);
6156                   return FATAL_EXIT_CODE;
6157                }
6158              cpp_push_buffer(pfile, NULL, 0);
6159              finclude(pfile, fd, pend->arg, 0, NULL);
6160           }
6161      }
6162    pfile->no_record_file--;
6163
6164    /* Free the pending list. */
6165    for (pend = opts->pending; pend;)
6166      {
6167         struct cpp_pending *next = pend->next;
6168
6169         free(pend);
6170         pend = next;
6171      }
6172    opts->pending = NULL;
6173
6174    if (finclude(pfile, f, fname, 0, NULL))
6175       output_line_command(pfile, 0, same_file);
6176    return SUCCESS_EXIT_CODE;
6177 }
6178
6179 void
6180 init_parse_file(cpp_reader * pfile)
6181 {
6182    memset((char *)pfile, 0, sizeof(cpp_reader));
6183    pfile->get_token = cpp_get_token;
6184
6185    pfile->token_buffer_size = 200;
6186    pfile->token_buffer = (unsigned char *)xmalloc(pfile->token_buffer_size);
6187    CPP_SET_WRITTEN(pfile, 0);
6188
6189    pfile->system_include_depth = 0;
6190    pfile->dont_repeat_files = 0;
6191    pfile->all_include_files = 0;
6192    pfile->max_include_len = 0;
6193    pfile->timebuf = NULL;
6194    pfile->only_seen_white = 1;
6195    pfile->buffer = CPP_NULL_BUFFER(pfile);
6196 }
6197
6198 static struct cpp_pending *
6199 nreverse_pending(struct cpp_pending *list)
6200 {
6201    struct cpp_pending *prev = 0, *next, *pend;
6202
6203    for (pend = list; pend; pend = next)
6204      {
6205         next = pend->next;
6206         pend->next = prev;
6207         prev = pend;
6208      }
6209    return prev;
6210 }
6211
6212 static void
6213 push_pending(cpp_reader * pfile, const char *cmd, const char *arg)
6214 {
6215    struct cpp_pending *pend
6216       = (struct cpp_pending *)xmalloc(sizeof(struct cpp_pending));
6217
6218    pend->cmd = cmd;
6219    pend->arg = arg;
6220    pend->next = CPP_OPTIONS(pfile)->pending;
6221    CPP_OPTIONS(pfile)->pending = pend;
6222 }
6223
6224 /* Handle command-line options in (argc, argv).
6225  * Can be called multiple times, to handle multiple sets of options.
6226  * Returns if an unrecognized option is seen.
6227  * Returns number of handled arguments.  */
6228
6229 int
6230 cpp_handle_options(cpp_reader * pfile, int argc, char **argv)
6231 {
6232    int                 i;
6233    struct cpp_options *opts = CPP_OPTIONS(pfile);
6234
6235    for (i = 0; i < argc; i++)
6236      {
6237         if (argv[i][0] != '-')
6238           {
6239              if (opts->out_fname != NULL)
6240                 cpp_fatal("Usage: %s [switches] input output", argv[0]);
6241              else if (opts->in_fname != NULL)
6242                 opts->out_fname = argv[i];
6243              else
6244                 opts->in_fname = argv[i];
6245           }
6246         else
6247           {
6248              switch (argv[i][1])
6249                {
6250
6251                case 'i':
6252                   if (!strcmp(argv[i], "-include")
6253                       || !strcmp(argv[i], "-imacros"))
6254                     {
6255                        if (i + 1 == argc)
6256                           cpp_fatal("Filename missing after `%s' option",
6257                                     argv[i]);
6258                        else
6259                           push_pending(pfile, argv[i], argv[i + 1]), i++;
6260                     }
6261                   if (!strcmp(argv[i], "-iprefix"))
6262                     {
6263                        if (i + 1 == argc)
6264                           cpp_fatal("Filename missing after `-iprefix' option");
6265                        else
6266                           opts->include_prefix = argv[++i];
6267                     }
6268                   if (!strcmp(argv[i], "-ifoutput"))
6269                     {
6270                        opts->output_conditionals = 1;
6271                     }
6272                   if (!strcmp(argv[i], "-isystem"))
6273                     {
6274                        struct file_name_list *dirtmp;
6275
6276                        if (i + 1 == argc)
6277                           cpp_fatal("Filename missing after `-isystem' option");
6278
6279                        dirtmp =
6280                           (struct file_name_list
6281                            *)xmalloc(sizeof(struct file_name_list));
6282
6283                        dirtmp->next = 0;
6284                        dirtmp->control_macro = 0;
6285                        dirtmp->c_system_include_path = 1;
6286                        dirtmp->fname = (char *)xmalloc(strlen(argv[i + 1]) + 1);
6287                        strcpy(dirtmp->fname, argv[++i]);
6288                        dirtmp->got_name_map = 0;
6289
6290                        if (opts->before_system == 0)
6291                           opts->before_system = dirtmp;
6292                        else
6293                           opts->last_before_system->next = dirtmp;
6294                        opts->last_before_system = dirtmp;       /* Tail follows the last one */
6295                     }
6296                   /* Add directory to end of path for includes,
6297                    * with the default prefix at the front of its name.  */
6298                   if (!strcmp(argv[i], "-iwithprefix"))
6299                     {
6300                        struct file_name_list *dirtmp;
6301                        char               *prefix;
6302
6303                        if (opts->include_prefix != 0)
6304                           prefix = opts->include_prefix;
6305                        else
6306                          {
6307                             prefix = savestring(GCC_INCLUDE_DIR);
6308                             /* Remove the `include' from /usr/local/lib/gcc.../include.  */
6309                             if (!strcmp
6310                                 (prefix + strlen(prefix) - 8, "/include"))
6311                                prefix[strlen(prefix) - 7] = 0;
6312                          }
6313
6314                        dirtmp =
6315                           (struct file_name_list
6316                            *)xmalloc(sizeof(struct file_name_list));
6317
6318                        dirtmp->next = 0;        /* New one goes on the end */
6319                        dirtmp->control_macro = 0;
6320                        dirtmp->c_system_include_path = 0;
6321                        if (i + 1 == argc)
6322                           cpp_fatal
6323                              ("Directory name missing after `-iwithprefix' option");
6324
6325                        dirtmp->fname = (char *)xmalloc(strlen(argv[i + 1])
6326                                                        + strlen(prefix) + 1);
6327                        strcpy(dirtmp->fname, prefix);
6328                        strcat(dirtmp->fname, argv[++i]);
6329                        dirtmp->got_name_map = 0;
6330
6331                        if (opts->after_include == 0)
6332                           opts->after_include = dirtmp;
6333                        else
6334                           opts->last_after_include->next = dirtmp;
6335                        opts->last_after_include = dirtmp;       /* Tail follows the last one */
6336                     }
6337                   /* Add directory to main path for includes,
6338                    * with the default prefix at the front of its name.  */
6339                   if (!strcmp(argv[i], "-iwithprefixbefore"))
6340                     {
6341                        struct file_name_list *dirtmp;
6342                        char               *prefix;
6343
6344                        if (opts->include_prefix != 0)
6345                           prefix = opts->include_prefix;
6346                        else
6347                          {
6348                             prefix = savestring(GCC_INCLUDE_DIR);
6349                             /* Remove the `include' from /usr/local/lib/gcc.../include.  */
6350                             if (!strcmp
6351                                 (prefix + strlen(prefix) - 8, "/include"))
6352                                prefix[strlen(prefix) - 7] = 0;
6353                          }
6354
6355                        dirtmp =
6356                           (struct file_name_list
6357                            *)xmalloc(sizeof(struct file_name_list));
6358
6359                        dirtmp->next = 0;        /* New one goes on the end */
6360                        dirtmp->control_macro = 0;
6361                        dirtmp->c_system_include_path = 0;
6362                        if (i + 1 == argc)
6363                           cpp_fatal
6364                              ("Directory name missing after `-iwithprefixbefore' option");
6365
6366                        dirtmp->fname = (char *)xmalloc(strlen(argv[i + 1])
6367                                                        + strlen(prefix) + 1);
6368                        strcpy(dirtmp->fname, prefix);
6369                        strcat(dirtmp->fname, argv[++i]);
6370                        dirtmp->got_name_map = 0;
6371
6372                        append_include_chain(pfile, dirtmp, dirtmp);
6373                     }
6374                   /* Add directory to end of path for includes.  */
6375                   if (!strcmp(argv[i], "-idirafter"))
6376                     {
6377                        struct file_name_list *dirtmp;
6378
6379                        dirtmp =
6380                           (struct file_name_list
6381                            *)xmalloc(sizeof(struct file_name_list));
6382
6383                        dirtmp->next = 0;        /* New one goes on the end */
6384                        dirtmp->control_macro = 0;
6385                        dirtmp->c_system_include_path = 0;
6386                        if (i + 1 == argc)
6387                           cpp_fatal
6388                              ("Directory name missing after `-idirafter' option");
6389                        else
6390                           dirtmp->fname = argv[++i];
6391                        dirtmp->got_name_map = 0;
6392
6393                        if (opts->after_include == 0)
6394                           opts->after_include = dirtmp;
6395                        else
6396                           opts->last_after_include->next = dirtmp;
6397                        opts->last_after_include = dirtmp;       /* Tail follows the last one */
6398                     }
6399                   break;
6400
6401                case 'o':
6402                   if (opts->out_fname != NULL)
6403                      cpp_fatal("Output filename specified twice");
6404                   if (i + 1 == argc)
6405                      cpp_fatal("Filename missing after -o option");
6406                   opts->out_fname = argv[++i];
6407                   if (!strcmp(opts->out_fname, "-"))
6408                      opts->out_fname = "";
6409                   break;
6410
6411                case 'p':
6412                   if (!strcmp(argv[i], "-pedantic"))
6413                      CPP_PEDANTIC(pfile) = 1;
6414                   else if (!strcmp(argv[i], "-pedantic-errors"))
6415                     {
6416                        CPP_PEDANTIC(pfile) = 1;
6417                        opts->pedantic_errors = 1;
6418                     }
6419                   break;
6420
6421                case 't':
6422                   if (!strcmp(argv[i], "-traditional"))
6423                     {
6424                        opts->traditional = 1;
6425                        if (opts->dollars_in_ident > 0)
6426                           opts->dollars_in_ident = 1;
6427                     }
6428                   else if (!strcmp(argv[i], "-trigraphs"))
6429                     {
6430                        if (!opts->chill)
6431                           opts->no_trigraphs = 0;
6432                     }
6433                   break;
6434
6435                case 'l':
6436                   if (!strcmp(argv[i], "-lang-c"))
6437                      opts->cplusplus = 0, opts->cplusplus_comments =
6438                         0, opts->objc = 0;
6439                   if (!strcmp(argv[i], "-lang-c++"))
6440                      opts->cplusplus = 1, opts->cplusplus_comments =
6441                         1, opts->objc = 0;
6442                   if (!strcmp(argv[i], "-lang-c-c++-comments"))
6443                      opts->cplusplus = 0, opts->cplusplus_comments =
6444                         1, opts->objc = 0;
6445                   if (!strcmp(argv[i], "-lang-objc"))
6446                      opts->objc = 1, opts->cplusplus =
6447                         0, opts->cplusplus_comments = 1;
6448                   if (!strcmp(argv[i], "-lang-objc++"))
6449                      opts->objc = 1, opts->cplusplus =
6450                         1, opts->cplusplus_comments = 1;
6451                   if (!strcmp(argv[i], "-lang-asm"))
6452                      opts->lang_asm = 1;
6453                   if (!strcmp(argv[i], "-lint"))
6454                      opts->for_lint = 1;
6455                   if (!strcmp(argv[i], "-lang-chill"))
6456                      opts->objc = 0, opts->cplusplus = 0, opts->chill = 1,
6457                         opts->traditional = 1, opts->no_trigraphs = 1;
6458                   break;
6459
6460                case '+':
6461                   opts->cplusplus = 1, opts->cplusplus_comments = 1;
6462                   break;
6463
6464                case 'w':
6465                   opts->inhibit_warnings = 1;
6466                   break;
6467
6468                case 'W':
6469                   if (!strcmp(argv[i], "-Wtrigraphs"))
6470                      opts->warn_trigraphs = 1;
6471                   else if (!strcmp(argv[i], "-Wno-trigraphs"))
6472                      opts->warn_trigraphs = 0;
6473                   else if (!strcmp(argv[i], "-Wcomment"))
6474                      opts->warn_comments = 1;
6475                   else if (!strcmp(argv[i], "-Wno-comment"))
6476                      opts->warn_comments = 0;
6477                   else if (!strcmp(argv[i], "-Wcomments"))
6478                      opts->warn_comments = 1;
6479                   else if (!strcmp(argv[i], "-Wno-comments"))
6480                      opts->warn_comments = 0;
6481                   else if (!strcmp(argv[i], "-Wtraditional"))
6482                      opts->warn_stringify = 1;
6483                   else if (!strcmp(argv[i], "-Wno-traditional"))
6484                      opts->warn_stringify = 0;
6485                   else if (!strcmp(argv[i], "-Wimport"))
6486                      opts->warn_import = 1;
6487                   else if (!strcmp(argv[i], "-Wno-import"))
6488                      opts->warn_import = 0;
6489                   else if (!strcmp(argv[i], "-Werror"))
6490                      opts->warnings_are_errors = 1;
6491                   else if (!strcmp(argv[i], "-Wno-error"))
6492                      opts->warnings_are_errors = 0;
6493                   else if (!strcmp(argv[i], "-Wall"))
6494                     {
6495                        opts->warn_trigraphs = 1;
6496                        opts->warn_comments = 1;
6497                     }
6498                   break;
6499
6500                case 'M':
6501                   /* The style of the choices here is a bit mixed.
6502                    * The chosen scheme is a hybrid of keeping all options in one string
6503                    * and specifying each option in a separate argument:
6504                    * -M|-MM|-MD file|-MMD file [-MG].  An alternative is:
6505                    * -M|-MM|-MD file|-MMD file|-MG|-MMG; or more concisely:
6506                    * -M[M][G][D file].  This is awkward to handle in specs, and is not
6507                    * as extensible.  */
6508                   /* ??? -MG must be specified in addition to one of -M or -MM.
6509                    * This can be relaxed in the future without breaking anything.
6510                    * The converse isn't true.  */
6511
6512                   /* -MG isn't valid with -MD or -MMD.  This is checked for later.  */
6513                   if (!strcmp(argv[i], "-MG"))
6514                     {
6515                        opts->print_deps_missing_files = 1;
6516                        break;
6517                     }
6518                   if (!strcmp(argv[i], "-M"))
6519                      opts->print_deps = 2;
6520                   else if (!strcmp(argv[i], "-MM"))
6521                      opts->print_deps = 1;
6522                   else if (!strcmp(argv[i], "-MD"))
6523                      opts->print_deps = 2;
6524                   else if (!strcmp(argv[i], "-MMD"))
6525                      opts->print_deps = 1;
6526                   /* For -MD and -MMD options, write deps on file named by next arg.  */
6527                   if (!strcmp(argv[i], "-MD") || !strcmp(argv[i], "-MMD"))
6528                     {
6529                        if (i + 1 == argc)
6530                           cpp_fatal("Filename missing after %s option",
6531                                     argv[i]);
6532                        opts->deps_file = argv[++i];
6533                     }
6534                   else
6535                     {
6536                        /* For -M and -MM, write deps on standard output
6537                         * and suppress the usual output.  */
6538                        opts->no_output = 1;
6539                     }
6540                   break;
6541
6542                case 'd':
6543                   {
6544                      char               *p = argv[i] + 2;
6545                      char                c;
6546
6547                      while ((c = *p++) != 0)
6548                        {
6549                           /* Arg to -d specifies what parts of macros to dump */
6550                           switch (c)
6551                             {
6552                             case 'M':
6553                                opts->dump_macros = dump_only;
6554                                opts->no_output = 1;
6555                                break;
6556                             case 'N':
6557                                opts->dump_macros = dump_names;
6558                                break;
6559                             case 'D':
6560                                opts->dump_macros = dump_definitions;
6561                                break;
6562                             }
6563                        }
6564                   }
6565                   break;
6566
6567                case 'g':
6568                   if (argv[i][2] == '3')
6569                      opts->debug_output = 1;
6570                   break;
6571
6572                case 'v':
6573                   fprintf(stderr, "GNU CPP version %s", version_string);
6574 #ifdef TARGET_VERSION
6575                   TARGET_VERSION;
6576 #endif
6577                   fprintf(stderr, "\n");
6578                   opts->verbose = 1;
6579                   break;
6580
6581                case 'H':
6582                   opts->print_include_names = 1;
6583                   break;
6584
6585                case 'D':
6586                   if (argv[i][2] != 0)
6587                      push_pending(pfile, "-D", argv[i] + 2);
6588                   else if (i + 1 == argc)
6589                      cpp_fatal("Macro name missing after -D option");
6590                   else
6591                      i++, push_pending(pfile, "-D", argv[i]);
6592                   break;
6593
6594                case 'A':
6595                   {
6596                      char               *p = NULL;
6597
6598                      if (argv[i][2] != 0)
6599                         p = argv[i] + 2;
6600                      else if (i + 1 == argc)
6601                         cpp_fatal("Assertion missing after -A option");
6602                      else
6603                         p = argv[++i];
6604
6605                      if (!strcmp(p, "-"))
6606                        {
6607                           struct cpp_pending **ptr;
6608
6609                           /* -A- eliminates all predefined macros and assertions.
6610                            * Let's include also any that were specified earlier
6611                            * on the command line.  That way we can get rid of any
6612                            * that were passed automatically in from GCC.  */
6613
6614                           opts->inhibit_predefs = 1;
6615                           for (ptr = &opts->pending; *ptr != NULL;)
6616                             {
6617                                struct cpp_pending *pend = *ptr;
6618
6619                                if (pend->cmd && pend->cmd[0] == '-'
6620                                    && (pend->cmd[1] == 'D'
6621                                        || pend->cmd[1] == 'A'))
6622                                  {
6623                                     *ptr = pend->next;
6624                                     free(pend);
6625                                  }
6626                                else
6627                                   ptr = &pend->next;
6628                             }
6629                        }
6630                      else
6631                        {
6632                           push_pending(pfile, "-A", p);
6633                        }
6634                   }
6635                   break;
6636
6637                case 'U':        /* JF #undef something */
6638                   if (argv[i][2] != 0)
6639                      push_pending(pfile, "-U", argv[i] + 2);
6640                   else if (i + 1 == argc)
6641                      cpp_fatal("Macro name missing after -U option");
6642                   else
6643                      push_pending(pfile, "-U", argv[i + 1]), i++;
6644                   break;
6645
6646                case 'C':
6647                   opts->put_out_comments = 1;
6648                   break;
6649
6650                case 'E':        /* -E comes from cc -E; ignore it.  */
6651                   break;
6652
6653                case 'P':
6654                   opts->no_line_commands = 1;
6655                   break;
6656
6657                case '$':        /* Don't include $ in identifiers.  */
6658                   opts->dollars_in_ident = 0;
6659                   break;
6660
6661                case 'I':        /* Add directory to path for includes.  */
6662                   {
6663                      struct file_name_list *dirtmp;
6664
6665                      if (!CPP_OPTIONS(pfile)->ignore_srcdir
6666                          && !strcmp(argv[i] + 2, "-"))
6667                        {
6668                           CPP_OPTIONS(pfile)->ignore_srcdir = 1;
6669                           /* Don't use any preceding -I directories for #include <...>.  */
6670                           CPP_OPTIONS(pfile)->first_bracket_include = 0;
6671                        }
6672                      else
6673                        {
6674                           dirtmp =
6675                              (struct file_name_list
6676                               *)xmalloc(sizeof(struct file_name_list));
6677
6678                           dirtmp->next = 0;     /* New one goes on the end */
6679                           dirtmp->control_macro = 0;
6680                           dirtmp->c_system_include_path = 0;
6681                           if (argv[i][2] != 0)
6682                              dirtmp->fname = argv[i] + 2;
6683                           else if (i + 1 == argc)
6684                              cpp_fatal
6685                                 ("Directory name missing after -I option");
6686                           else
6687                              dirtmp->fname = argv[++i];
6688                           dirtmp->got_name_map = 0;
6689                           append_include_chain(pfile, dirtmp, dirtmp);
6690                        }
6691                   }
6692                   break;
6693
6694                case 'n':
6695                   if (!strcmp(argv[i], "-nostdinc"))
6696                      /* -nostdinc causes no default include directories.
6697                       * You must specify all include-file directories with -I.  */
6698                      opts->no_standard_includes = 1;
6699                   else if (!strcmp(argv[i], "-nostdinc++"))
6700                      /* -nostdinc++ causes no default C++-specific include directories. */
6701                      opts->no_standard_cplusplus_includes = 1;
6702                   break;
6703
6704                case 'u':
6705                   /* Sun compiler passes undocumented switch "-undef".
6706                    * Let's assume it means to inhibit the predefined symbols.  */
6707                   opts->inhibit_predefs = 1;
6708                   break;
6709
6710                case '\0':       /* JF handle '-' as file name meaning stdin or stdout */
6711                   if (opts->in_fname == NULL)
6712                     {
6713                        opts->in_fname = "";
6714                        break;
6715                     }
6716                   else if (opts->out_fname == NULL)
6717                     {
6718                        opts->out_fname = "";
6719                        break;
6720                     }           /* else fall through into error */
6721                default:
6722                   return i;
6723                }
6724           }
6725      }
6726    return i;
6727 }
6728
6729 void
6730 cpp_finish(cpp_reader * pfile)
6731 {
6732    struct cpp_options *opts = CPP_OPTIONS(pfile);
6733
6734    if (opts->print_deps)
6735      {
6736         /* Stream on which to print the dependency information.  */
6737         FILE               *deps_stream;
6738
6739         /* Don't actually write the deps file if compilation has failed.  */
6740         if (pfile->errors == 0)
6741           {
6742              const char         *deps_mode =
6743                 opts->print_deps_append ? "a" : "w";
6744
6745              if (opts->deps_file == 0)
6746                 deps_stream = stdout;
6747              else if ((deps_stream = fopen(opts->deps_file, deps_mode)) == 0)
6748                 cpp_pfatal_with_name(pfile, opts->deps_file);
6749              fputs(pfile->deps_buffer, deps_stream);
6750              putc('\n', deps_stream);
6751              if (opts->deps_file)
6752                {
6753                   if (ferror(deps_stream) || fclose(deps_stream) != 0)
6754                      cpp_fatal("I/O error on output");
6755                }
6756           }
6757      }
6758 }
6759
6760 static int
6761 do_assert(cpp_reader * pfile, struct directive *keyword, unsigned char *buf,
6762           unsigned char *limit)
6763 {
6764    long                symstart;        /* remember where symbol name starts */
6765    int                 c;
6766    int                 sym_length;      /* and how long it is */
6767    struct arglist     *tokens = NULL;
6768
6769    if (CPP_PEDANTIC(pfile) && CPP_OPTIONS(pfile)->done_initializing
6770        && !CPP_BUFFER(pfile)->system_header_p)
6771       cpp_pedwarn(pfile, "ANSI C does not allow `#assert'");
6772
6773    keyword = NULL;
6774    buf = NULL;
6775    limit = NULL;
6776
6777    cpp_skip_hspace(pfile);
6778    symstart = CPP_WRITTEN(pfile);       /* remember where it starts */
6779    parse_name(pfile, GETC());
6780    sym_length = check_macro_name(pfile, pfile->token_buffer + symstart,
6781                                  "assertion");
6782
6783    cpp_skip_hspace(pfile);
6784    if (PEEKC() != '(')
6785      {
6786         cpp_error(pfile, "missing token-sequence in `#assert'");
6787         goto error;
6788      }
6789    {
6790       int                 error_flag = 0;
6791
6792       tokens = read_token_list(pfile, &error_flag);
6793       if (error_flag)
6794          goto error;
6795       if (tokens == 0)
6796         {
6797            cpp_error(pfile, "empty token-sequence in `#assert'");
6798            goto error;
6799         }
6800       cpp_skip_hspace(pfile);
6801       c = PEEKC();
6802       if (c != EOF && c != '\n')
6803          cpp_pedwarn(pfile, "junk at end of `#assert'");
6804       skip_rest_of_line(pfile);
6805    }
6806
6807    /* If this name isn't already an assertion name, make it one.
6808     * Error if it was already in use in some other way.  */
6809
6810    {
6811       ASSERTION_HASHNODE *hp;
6812       const char         *symname = (char *)pfile->token_buffer + symstart;
6813       int                 hashcode =
6814          hashf(symname, sym_length, ASSERTION_HASHSIZE);
6815       struct tokenlist_list *value =
6816          (struct tokenlist_list *)xmalloc(sizeof(struct tokenlist_list));
6817
6818       hp = assertion_lookup(pfile, symname, sym_length, hashcode);
6819       if (hp == NULL)
6820         {
6821            if (sym_length == 7 && !strncmp(symname, "defined", sym_length))
6822               cpp_error(pfile, "`defined' redefined as assertion");
6823            hp = assertion_install(pfile, symname, sym_length, hashcode);
6824         }
6825       /* Add the spec'd token-sequence to the list of such.  */
6826       value->tokens = tokens;
6827       value->next = hp->value;
6828       hp->value = value;
6829    }
6830    CPP_SET_WRITTEN(pfile, symstart);    /* Pop */
6831    return 0;
6832  error:
6833    CPP_SET_WRITTEN(pfile, symstart);    /* Pop */
6834    skip_rest_of_line(pfile);
6835    return 1;
6836 }
6837
6838 static int
6839 do_unassert(cpp_reader * pfile, struct directive *keyword, unsigned char *buf,
6840             unsigned char *limit)
6841 {
6842    long                symstart;        /* remember where symbol name starts */
6843    int                 sym_length;      /* and how long it is */
6844    int                 c;
6845
6846    struct arglist     *tokens = NULL;
6847    int                 tokens_specified = 0;
6848
6849    keyword = NULL;
6850    buf = NULL;
6851    limit = NULL;
6852
6853    if (CPP_PEDANTIC(pfile) && CPP_OPTIONS(pfile)->done_initializing
6854        && !CPP_BUFFER(pfile)->system_header_p)
6855       cpp_pedwarn(pfile, "ANSI C does not allow `#unassert'");
6856
6857    cpp_skip_hspace(pfile);
6858
6859    symstart = CPP_WRITTEN(pfile);       /* remember where it starts */
6860    parse_name(pfile, GETC());
6861    sym_length = check_macro_name(pfile, pfile->token_buffer + symstart,
6862                                  "assertion");
6863
6864    cpp_skip_hspace(pfile);
6865    if (PEEKC() == '(')
6866      {
6867         int                 error_flag = 0;
6868
6869         tokens = read_token_list(pfile, &error_flag);
6870         if (error_flag)
6871            goto error;
6872         if (tokens == 0)
6873           {
6874              cpp_error(pfile, "empty token list in `#unassert'");
6875              goto error;
6876           }
6877         tokens_specified = 1;
6878      }
6879    cpp_skip_hspace(pfile);
6880    c = PEEKC();
6881    if (c != EOF && c != '\n')
6882       cpp_error(pfile, "junk at end of `#unassert'");
6883    skip_rest_of_line(pfile);
6884
6885    {
6886       ASSERTION_HASHNODE *hp;
6887       const char         *symname = (char *)pfile->token_buffer + symstart;
6888       int                 hashcode =
6889          hashf(symname, sym_length, ASSERTION_HASHSIZE);
6890       struct tokenlist_list *tail, *prev;
6891
6892       hp = assertion_lookup(pfile, symname, sym_length, hashcode);
6893       if (hp == NULL)
6894          return 1;
6895
6896       /* If no token list was specified, then eliminate this assertion
6897        * entirely.  */
6898       if (!tokens_specified)
6899          delete_assertion(hp);
6900       else
6901         {
6902            /* If a list of tokens was given, then delete any matching list.  */
6903
6904            tail = hp->value;
6905            prev = 0;
6906            while (tail)
6907              {
6908                 struct tokenlist_list *next = tail->next;
6909
6910                 if (compare_token_lists(tail->tokens, tokens))
6911                   {
6912                      if (prev)
6913                         prev->next = next;
6914                      else
6915                         hp->value = tail->next;
6916                      free_token_list(tail->tokens);
6917                      free(tail);
6918                   }
6919                 else
6920                   {
6921                      prev = tail;
6922                   }
6923                 tail = next;
6924              }
6925         }
6926    }
6927
6928    CPP_SET_WRITTEN(pfile, symstart);    /* Pop */
6929    return 0;
6930  error:
6931    CPP_SET_WRITTEN(pfile, symstart);    /* Pop */
6932    skip_rest_of_line(pfile);
6933    return 1;
6934 }
6935
6936 /* Test whether there is an assertion named NAME
6937  * and optionally whether it has an asserted token list TOKENS.
6938  * NAME is not null terminated; its length is SYM_LENGTH.
6939  * If TOKENS_SPECIFIED is 0, then don't check for any token list.  */
6940
6941 static int
6942 check_assertion(cpp_reader * pfile, const char *name, int sym_length,
6943                 int tokens_specified, struct arglist *tokens)
6944 {
6945    ASSERTION_HASHNODE *hp;
6946    int                 hashcode = hashf(name, sym_length, ASSERTION_HASHSIZE);
6947
6948    if (CPP_PEDANTIC(pfile) && !CPP_BUFFER(pfile)->system_header_p)
6949       cpp_pedwarn(pfile, "ANSI C does not allow testing assertions");
6950
6951    hp = assertion_lookup(pfile, name, sym_length, hashcode);
6952    if (hp == NULL)
6953       /* It is not an assertion; just return false.  */
6954       return 0;
6955
6956    /* If no token list was specified, then value is 1.  */
6957    if (!tokens_specified)
6958       return 1;
6959
6960    {
6961       struct tokenlist_list *tail;
6962
6963       tail = hp->value;
6964
6965       /* If a list of tokens was given,
6966        * then succeed if the assertion records a matching list.  */
6967
6968       while (tail)
6969         {
6970            if (compare_token_lists(tail->tokens, tokens))
6971               return 1;
6972            tail = tail->next;
6973         }
6974
6975       /* Fail if the assertion has no matching list.  */
6976       return 0;
6977    }
6978 }
6979
6980 /* Compare two lists of tokens for equality including order of tokens.  */
6981
6982 static int
6983 compare_token_lists(struct arglist *l1, struct arglist *l2)
6984 {
6985    while (l1 && l2)
6986      {
6987         if (l1->length != l2->length)
6988            return 0;
6989         if (strncmp(l1->name, l2->name, l1->length))
6990            return 0;
6991         l1 = l1->next;
6992         l2 = l2->next;
6993      }
6994
6995    /* Succeed if both lists end at the same time.  */
6996    return l1 == l2;
6997 }
6998
6999 struct arglist     *
7000 reverse_token_list(struct arglist *tokens)
7001 {
7002    struct arglist     *prev = 0, *cur, *next;
7003
7004    for (cur = tokens; cur; cur = next)
7005      {
7006         next = cur->next;
7007         cur->next = prev;
7008         prev = cur;
7009      }
7010    return prev;
7011 }
7012
7013 /* Read a space-separated list of tokens ending in a close parenthesis.
7014  * Return a list of strings, in the order they were written.
7015  * (In case of error, return 0 and store -1 in *ERROR_FLAG.) */
7016
7017 static struct arglist *
7018 read_token_list(cpp_reader * pfile, int *error_flag)
7019 {
7020    struct arglist     *token_ptrs = 0;
7021    int                 depth = 1;
7022    int                 length;
7023
7024    *error_flag = 0;
7025    FORWARD(1);                  /* Skip '(' */
7026
7027    /* Loop over the assertion value tokens.  */
7028    while (depth > 0)
7029      {
7030         struct arglist     *temp;
7031         long                name_written = CPP_WRITTEN(pfile);
7032         int                 c;
7033
7034         cpp_skip_hspace(pfile);
7035
7036         c = GETC();
7037
7038         /* Find the end of the token.  */
7039         if (c == '(')
7040           {
7041              CPP_PUTC(pfile, c);
7042              depth++;
7043           }
7044         else if (c == ')')
7045           {
7046              depth--;
7047              if (depth == 0)
7048                 break;
7049              CPP_PUTC(pfile, c);
7050           }
7051         else if (c == '"' || c == '\'')
7052           {
7053              FORWARD(-1);
7054              cpp_get_token(pfile);
7055           }
7056         else if (c == '\n')
7057            break;
7058         else
7059           {
7060              while (c != EOF && !is_space[c] && c != '(' && c != ')'
7061                     && c != '"' && c != '\'')
7062                {
7063                   CPP_PUTC(pfile, c);
7064                   c = GETC();
7065                }
7066              if (c != EOF)
7067                 FORWARD(-1);
7068           }
7069
7070         length = CPP_WRITTEN(pfile) - name_written;
7071         temp = (struct arglist *)xmalloc(sizeof(struct arglist) + length + 1);
7072
7073         temp->name = (char *)(temp + 1);
7074         memcpy(temp->name, (char *)(pfile->token_buffer + name_written),
7075                length);
7076         temp->name[length] = 0;
7077         temp->next = token_ptrs;
7078         token_ptrs = temp;
7079         temp->length = length;
7080
7081         CPP_ADJUST_WRITTEN(pfile, -length);     /* pop */
7082
7083         if (c == EOF || c == '\n')
7084           {                     /* FIXME */
7085              cpp_error(pfile,
7086                        "unterminated token sequence following  `#' operator");
7087              return 0;
7088           }
7089      }
7090
7091    /* We accumulated the names in reverse order.
7092     * Now reverse them to get the proper order.  */
7093    return reverse_token_list(token_ptrs);
7094 }
7095
7096 static void
7097 free_token_list(struct arglist *tokens)
7098 {
7099    while (tokens)
7100      {
7101         struct arglist     *next = tokens->next;
7102
7103         free(tokens->name);
7104         free(tokens);
7105         tokens = next;
7106      }
7107 }
7108
7109 /* Get the file-mode and data size of the file open on FD
7110  * and store them in *MODE_POINTER and *SIZE_POINTER.  */
7111
7112 static int
7113 file_size_and_mode(int fd, int *mode_pointer, long int *size_pointer)
7114 {
7115    struct stat         sbuf;
7116
7117    if (fstat(fd, &sbuf) < 0)
7118       return (-1);
7119    if (mode_pointer)
7120       *mode_pointer = sbuf.st_mode;
7121    if (size_pointer)
7122       *size_pointer = sbuf.st_size;
7123    return 0;
7124 }
7125
7126 /* Read LEN bytes at PTR from descriptor DESC, for file FILENAME,
7127  * retrying if necessary.  Return a negative value if an error occurs,
7128  * otherwise return the actual number of bytes read,
7129  * which must be LEN unless end-of-file was reached.  */
7130
7131 static int
7132 safe_read(int desc, char *ptr, int len)
7133 {
7134    int                 left = len;
7135
7136    while (left > 0)
7137      {
7138         int                 nchars = read(desc, ptr, left);
7139
7140         if (nchars < 0)
7141           {
7142 #ifdef EINTR
7143              if (errno == EINTR)
7144                 continue;
7145 #endif
7146              return nchars;
7147           }
7148         if (nchars == 0)
7149            break;
7150         ptr += nchars;
7151         left -= nchars;
7152      }
7153    return len - left;
7154 }
7155
7156 static char        *
7157 savestring(const char *input)
7158 {
7159    unsigned            size = strlen(input);
7160    char               *output = (char *)xmalloc(size + 1);
7161
7162    strcpy(output, input);
7163    return output;
7164 }
7165
7166 /* Initialize PMARK to remember the current position of PFILE. */
7167 void
7168 parse_set_mark(struct parse_marker *pmark, cpp_reader * pfile)
7169 {
7170    cpp_buffer         *pbuf = CPP_BUFFER(pfile);
7171
7172    pmark->next = pbuf->marks;
7173    pbuf->marks = pmark;
7174    pmark->buf = pbuf;
7175    pmark->position = pbuf->cur - pbuf->buf;
7176 }
7177
7178 /* Cleanup PMARK - we no longer need it. */
7179 static void
7180 parse_clear_mark(struct parse_marker *pmark)
7181 {
7182    struct parse_marker **pp = &pmark->buf->marks;
7183
7184    for (;; pp = &(*pp)->next)
7185      {
7186         if (*pp == NULL)
7187            cpp_fatal("internal error", "in parse_set_mark");
7188         if (*pp == pmark)
7189            break;
7190      }
7191    *pp = pmark->next;
7192 }
7193
7194 /* Backup the current position of PFILE to that saved in PMARK. */
7195
7196 static void
7197 parse_goto_mark(struct parse_marker *pmark, cpp_reader * pfile)
7198 {
7199    cpp_buffer         *pbuf = CPP_BUFFER(pfile);
7200
7201    if (pbuf != pmark->buf)
7202       cpp_fatal("internal error %s", "parse_goto_mark");
7203    pbuf->cur = pbuf->buf + pmark->position;
7204 }
7205
7206 /* Reset PMARK to point to the current position of PFILE.  (Same
7207  * as parse_clear_mark (PMARK), parse_set_mark (PMARK, PFILE) but faster. */
7208
7209 static void
7210 parse_move_mark(struct parse_marker *pmark, cpp_reader * pfile)
7211 {
7212    cpp_buffer         *pbuf = CPP_BUFFER(pfile);
7213
7214    if (pbuf != pmark->buf)
7215       cpp_fatal("internal error %s", "parse_move_mark");
7216    pmark->position = pbuf->cur - pbuf->buf;
7217 }
7218
7219 int
7220 cpp_read_check_assertion(cpp_reader * pfile)
7221 {
7222    int                 name_start = CPP_WRITTEN(pfile);
7223    int                 name_length, name_written;
7224    int                 result;
7225
7226    FORWARD(1);                  /* Skip '#' */
7227    cpp_skip_hspace(pfile);
7228    parse_name(pfile, GETC());
7229    name_written = CPP_WRITTEN(pfile);
7230    name_length = name_written - name_start;
7231    cpp_skip_hspace(pfile);
7232    if (CPP_BUF_PEEK(CPP_BUFFER(pfile)) == '(')
7233      {
7234         int                 error_flag;
7235         struct arglist     *token_ptrs = read_token_list(pfile, &error_flag);
7236
7237         result = check_assertion(pfile,
7238                                  (char *)pfile->token_buffer + name_start,
7239                                  name_length, 1, token_ptrs);
7240      }
7241    else
7242       result = check_assertion(pfile,
7243                                (char *)pfile->token_buffer + name_start,
7244                                name_length, 0, NULL);
7245    CPP_ADJUST_WRITTEN(pfile, -name_length);     /* pop */
7246    return result;
7247 }
7248
7249 static void
7250 cpp_print_file_and_line(cpp_reader * pfile)
7251 {
7252    cpp_buffer         *ip = cpp_file_buffer(pfile);
7253
7254    if (ip != NULL)
7255      {
7256         long                line, col;
7257
7258         cpp_buf_line_and_col(ip, &line, &col);
7259         cpp_file_line_for_message(pfile, ip->nominal_fname,
7260                                   line, pfile->show_column ? col : -1);
7261      }
7262 }
7263
7264 static void
7265 cpp_error_v(cpp_reader * pfile, const char *msg, va_list args)
7266 {
7267    cpp_print_containing_files(pfile);
7268    cpp_print_file_and_line(pfile);
7269    cpp_message_v(pfile, 1, msg, args);
7270 }
7271
7272 void
7273 cpp_error(cpp_reader * pfile, const char *msg, ...)
7274 {
7275    va_list             args;
7276
7277    va_start(args, msg);
7278
7279    cpp_error_v(pfile, msg, args);
7280
7281    va_end(args);
7282 }
7283
7284 /* Print error message but don't count it.  */
7285
7286 static void
7287 cpp_warning_v(cpp_reader * pfile, const char *msg, va_list args)
7288 {
7289    if (CPP_OPTIONS(pfile)->inhibit_warnings)
7290       return;
7291
7292    if (CPP_OPTIONS(pfile)->warnings_are_errors)
7293       pfile->errors++;
7294
7295    cpp_print_containing_files(pfile);
7296    cpp_print_file_and_line(pfile);
7297    cpp_message_v(pfile, 0, msg, args);
7298 }
7299
7300 void
7301 cpp_warning(cpp_reader * pfile, const char *msg, ...)
7302 {
7303    va_list             args;
7304
7305    va_start(args, msg);
7306
7307    cpp_warning_v(pfile, msg, args);
7308
7309    va_end(args);
7310 }
7311
7312 /* Print an error message and maybe count it.  */
7313
7314 void
7315 cpp_pedwarn(cpp_reader * pfile, const char *msg, ...)
7316 {
7317    va_list             args;
7318
7319    va_start(args, msg);
7320
7321    if (CPP_OPTIONS(pfile)->pedantic_errors)
7322       cpp_error_v(pfile, msg, args);
7323    else
7324       cpp_warning_v(pfile, msg, args);
7325
7326    va_end(args);
7327 }
7328
7329 static void
7330 cpp_error_with_line(cpp_reader * pfile, int line, int column, const char *msg)
7331 {
7332    cpp_buffer         *ip = cpp_file_buffer(pfile);
7333
7334    cpp_print_containing_files(pfile);
7335
7336    if (ip != NULL)
7337       cpp_file_line_for_message(pfile, ip->nominal_fname, line, column);
7338
7339    cpp_message(pfile, 1, msg, NULL, NULL, NULL);
7340 }
7341
7342 static void
7343 cpp_warning_with_line(cpp_reader * pfile, int line, int column, const char *msg)
7344 {
7345    cpp_buffer         *ip;
7346
7347    if (CPP_OPTIONS(pfile)->inhibit_warnings)
7348       return;
7349
7350    if (CPP_OPTIONS(pfile)->warnings_are_errors)
7351       pfile->errors++;
7352
7353    cpp_print_containing_files(pfile);
7354
7355    ip = cpp_file_buffer(pfile);
7356
7357    if (ip != NULL)
7358       cpp_file_line_for_message(pfile, ip->nominal_fname, line, column);
7359
7360    cpp_message(pfile, 0, msg, NULL, NULL, NULL);
7361 }
7362
7363 static void
7364 cpp_pedwarn_with_line(cpp_reader * pfile, int line, int column, const char *msg)
7365 {
7366    if (CPP_OPTIONS(pfile)->pedantic_errors)
7367       cpp_error_with_line(pfile, column, line, msg);
7368    else
7369       cpp_warning_with_line(pfile, line, column, msg);
7370 }
7371
7372 /* Report a warning (or an error if pedantic_errors)
7373  * giving specified file name and line number, not current.  */
7374
7375 void
7376 cpp_pedwarn_with_file_and_line(cpp_reader * pfile,
7377                                const char *file, int line,
7378                                const char *msg, const char *arg1,
7379                                const char *arg2, const char *arg3)
7380 {
7381    if (!CPP_OPTIONS(pfile)->pedantic_errors
7382        && CPP_OPTIONS(pfile)->inhibit_warnings)
7383       return;
7384    if (file != NULL)
7385       cpp_file_line_for_message(pfile, file, line, -1);
7386    cpp_message(pfile, CPP_OPTIONS(pfile)->pedantic_errors,
7387                msg, arg1, arg2, arg3);
7388 }
7389
7390 /* This defines "errno" properly for VMS, and gives us EACCES. */
7391 #include <errno.h>
7392 #ifndef errno
7393 extern int          errno;
7394
7395 #endif
7396
7397 #ifndef HAVE_STRERROR
7398 extern int          sys_nerr;
7399
7400 #if defined(bsd4_4)
7401 extern const char  *const sys_errlist[];
7402
7403 #else
7404 extern char        *sys_errlist[];
7405
7406 #endif
7407 #endif /* HAVE_STRERROR */
7408
7409 /*
7410  * my_strerror - return the descriptive text associated with an `errno' code.
7411  */
7412
7413 static const char  *
7414 my_strerror(int errnum)
7415 {
7416    const char         *result;
7417
7418 #ifndef HAVE_STRERROR
7419    result = ((errnum < sys_nerr) ? sys_errlist[errnum] : 0);
7420 #else
7421    result = strerror(errnum);
7422 #endif
7423
7424    if (!result)
7425       result = "undocumented I/O error";
7426
7427    return result;
7428 }
7429
7430 /* Error including a message from `errno'.  */
7431
7432 static void
7433 cpp_error_from_errno(cpp_reader * pfile, const char *name)
7434 {
7435    cpp_buffer         *ip = cpp_file_buffer(pfile);
7436
7437    cpp_print_containing_files(pfile);
7438
7439    if (ip != NULL)
7440       cpp_file_line_for_message(pfile, ip->nominal_fname, ip->lineno, -1);
7441
7442    cpp_message(pfile, 1, "%s: %s", name, my_strerror(errno), NULL);
7443 }
7444
7445 void
7446 cpp_perror_with_name(cpp_reader * pfile, const char *name)
7447 {
7448    cpp_message(pfile, 1, "%s: %s: %s", progname, name, my_strerror(errno));
7449 }
7450
7451 /* TODO:
7452  * No pre-compiled header file support.
7453  *
7454  * Possibly different enum token codes for each C/C++ token.
7455  *
7456  * Should clean up remaining directives to that do_XXX functions
7457  *   only take two arguments and all have command_reads_line.
7458  *
7459  * Find and cleanup remaining uses of static variables,
7460  *
7461  * Support for trigraphs.
7462  *
7463  * Support -dM flag (dump_all_macros).
7464  *
7465  * Support for_lint flag.
7466  */