1/* CPP Library.
2   Copyright (C) 1986, 1987, 1989, 1992, 1993, 1994, 1995, 1996, 1997, 1998,
3   1999, 2000 Free Software Foundation, Inc.
4   Contributed by Per Bothner, 1994-95.
5   Based on CCCP program by Paul Rubin, June 1986
6   Adapted to ANSI C, Richard Stallman, Jan 1987
7
8This program is free software; you can redistribute it and/or modify it
9under the terms of the GNU General Public License as published by the
10Free Software Foundation; either version 2, or (at your option) any
11later version.
12
13This program is distributed in the hope that it will be useful,
14but WITHOUT ANY WARRANTY; without even the implied warranty of
15MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16GNU General Public License for more details.
17
18You should have received a copy of the GNU General Public License
19along with this program; if not, write to the Free Software
20Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
21
22#include "config.h"
23#include "system.h"
24
25#define FAKE_CONST
26#include "cpplib.h"
27#include "cpphash.h"
28#include "output.h"
29#include "prefix.h"
30#include "intl.h"
31
32/* XXX Should be in a header file. */
33extern char *version_string;
34
35/* Predefined symbols, built-in macros, and the default include path. */
36
37#ifndef GET_ENV_PATH_LIST
38#define GET_ENV_PATH_LIST(VAR,NAME)	do { (VAR) = getenv (NAME); } while (0)
39#endif
40
41/* By default, colon separates directories in a path.  */
42#ifndef PATH_SEPARATOR
43#define PATH_SEPARATOR ':'
44#endif
45
46#ifndef STANDARD_INCLUDE_DIR
47#define STANDARD_INCLUDE_DIR "/usr/include"
48#endif
49
50/* We let tm.h override the types used here, to handle trivial differences
51   such as the choice of unsigned int or long unsigned int for size_t.
52   When machines start needing nontrivial differences in the size type,
53   it would be best to do something here to figure out automatically
54   from other information what type to use.  */
55
56/* The string value for __SIZE_TYPE__.  */
57
58#ifndef SIZE_TYPE
59#define SIZE_TYPE "long unsigned int"
60#endif
61
62/* The string value for __PTRDIFF_TYPE__.  */
63
64#ifndef PTRDIFF_TYPE
65#define PTRDIFF_TYPE "long int"
66#endif
67
68/* The string value for __WCHAR_TYPE__.  */
69
70#ifndef WCHAR_TYPE
71#define WCHAR_TYPE "int"
72#endif
73#define CPP_WCHAR_TYPE(PFILE) \
74	(CPP_OPTIONS (PFILE)->cplusplus ? "__wchar_t" : WCHAR_TYPE)
75
76/* The string value for __USER_LABEL_PREFIX__ */
77
78#ifndef USER_LABEL_PREFIX
79#define USER_LABEL_PREFIX ""
80#endif
81
82/* The string value for __REGISTER_PREFIX__ */
83
84#ifndef REGISTER_PREFIX
85#define REGISTER_PREFIX ""
86#endif
87
88/* Suffix for object files, and known input-file extensions. */
89static char *known_suffixes[] =
90{
91  ".c",  ".C",   ".s",   ".S",   ".m",
92  ".cc", ".cxx", ".cpp", ".cp",  ".c++",
93  NULL
94};
95
96#ifndef OBJECT_SUFFIX
97# ifdef VMS
98#  define OBJECT_SUFFIX ".obj"
99# else
100#  define OBJECT_SUFFIX ".o"
101# endif
102#endif
103
104
105#if defined(__BEOS__) || defined(__HAIKU__)
106#include <OS.h>
107/* the thread priority used for all gcc-tools */
108static int priority = B_LOW_PRIORITY;
109#endif
110
111/* This is the default list of directories to search for include files.
112   It may be overridden by the various -I and -ixxx options.
113
114   #include "file" looks in the same directory as the current file,
115   then this list.
116   #include <file> just looks in this list.
117
118   All these directories are treated as `system' include directories
119   (they are not subject to pedantic warnings in some cases).  */
120
121static struct default_include
122{
123  char *fname;			/* The name of the directory.  */
124  char *component;		/* The component containing the directory
125				   (see update_path in prefix.c) */
126  int cplusplus;		/* Only look here if we're compiling C++.  */
127  int cxx_aware;		/* Includes in this directory don't need to
128				   be wrapped in extern "C" when compiling
129				   C++.  This is not used anymore.  */
130}
131include_defaults_array[]
132#ifdef INCLUDE_DEFAULTS
133= INCLUDE_DEFAULTS;
134#else
135= {
136    /* Pick up GNU C++ specific include files.  */
137    { GPLUSPLUS_INCLUDE_DIR, "G++", 1, 1 },
138#ifdef CROSS_COMPILE
139    /* This is the dir for fixincludes.  Put it just before
140       the files that we fix.  */
141    { GCC_INCLUDE_DIR, "GCC", 0, 0 },
142    /* For cross-compilation, this dir name is generated
143       automatically in Makefile.in.  */
144    { CROSS_INCLUDE_DIR, "GCC", 0, 0 },
145#ifdef TOOL_INCLUDE_DIR
146    /* This is another place that the target system's headers might be.  */
147    { TOOL_INCLUDE_DIR, "BINUTILS", 0, 1 },
148#endif
149#else /* not CROSS_COMPILE */
150#ifdef LOCAL_INCLUDE_DIR
151    /* This should be /usr/local/include and should come before
152       the fixincludes-fixed header files.  */
153    { LOCAL_INCLUDE_DIR, 0, 0, 1 },
154#endif
155#ifdef TOOL_INCLUDE_DIR
156    /* This is here ahead of GCC_INCLUDE_DIR because assert.h goes here.
157       Likewise, behind LOCAL_INCLUDE_DIR, where glibc puts its assert.h.  */
158    { TOOL_INCLUDE_DIR, "BINUTILS", 0, 1 },
159#endif
160    /* This is the dir for fixincludes.  Put it just before
161       the files that we fix.  */
162    { GCC_INCLUDE_DIR, "GCC", 0, 0 },
163    /* Some systems have an extra dir of include files.  */
164#ifdef SYSTEM_INCLUDE_DIR
165    { SYSTEM_INCLUDE_DIR, 0, 0, 0 },
166#endif
167#ifndef STANDARD_INCLUDE_COMPONENT
168#define STANDARD_INCLUDE_COMPONENT 0
169#endif
170    { STANDARD_INCLUDE_DIR, STANDARD_INCLUDE_COMPONENT, 0, 0 },
171#endif /* not CROSS_COMPILE */
172    { 0, 0, 0, 0 }
173  };
174#endif /* no INCLUDE_DEFAULTS */
175
176/* Internal structures and prototypes. */
177
178/* A `struct pending_option' remembers one -D, -A, -U, -include, or -imacros
179   switch.  There are four lists: one for -D and -U, one for -A, one
180   for -include, one for -imacros.  `undef' is set for -U, clear for
181   -D, ignored for the others.
182   (Future: add an equivalent of -U for -A) */
183struct pending_option
184{
185  struct pending_option *next;
186  char *arg;
187  int undef;
188};
189
190#ifdef __STDC__
191#define APPEND(pend, list, elt) \
192  do {  if (!(pend)->list##_head) (pend)->list##_head = (elt); \
193	else (pend)->list##_tail->next = (elt); \
194	(pend)->list##_tail = (elt); \
195  } while (0)
196#else
197#define APPEND(pend, list, elt) \
198  do {  if (!(pend)->list/**/_head) (pend)->list/**/_head = (elt); \
199	else (pend)->list/**/_tail->next = (elt); \
200	(pend)->list/**/_tail = (elt); \
201  } while (0)
202#endif
203
204static void initialize_char_syntax	PARAMS ((int));
205static void print_help                  PARAMS ((void));
206static void path_include		PARAMS ((cpp_reader *,
207						 struct cpp_pending *,
208						 char *, int));
209static void initialize_builtins		PARAMS ((cpp_reader *));
210static void append_include_chain	PARAMS ((cpp_reader *,
211						 struct cpp_pending *,
212						 char *, int));
213
214/* Last argument to append_include_chain: chain to use */
215enum { QUOTE = 0, BRACKET, SYSTEM, AFTER };
216
217/* If gcc is in use (stage2/stage3) we can make these tables initialized
218   data. */
219#if defined __GNUC__ && (__GNUC__ > 2 \
220			 || (__GNUC__ == 2 && __GNUC_MINOR__ > 8))
221/* Table to tell if a character is legal as the second or later character
222   of a C identifier. */
223U_CHAR is_idchar[256] =
224{
225  ['a'] = 1, ['b'] = 1, ['c'] = 1,  ['d'] = 1, ['e'] = 1, ['f'] = 1,
226  ['g'] = 1, ['h'] = 1, ['i'] = 1,  ['j'] = 1, ['k'] = 1, ['l'] = 1,
227  ['m'] = 1, ['n'] = 1, ['o'] = 1,  ['p'] = 1, ['q'] = 1, ['r'] = 1,
228  ['s'] = 1, ['t'] = 1, ['u'] = 1,  ['v'] = 1, ['w'] = 1, ['x'] = 1,
229  ['y'] = 1, ['z'] = 1,
230
231  ['A'] = 1, ['B'] = 1, ['C'] = 1,  ['D'] = 1, ['E'] = 1, ['F'] = 1,
232  ['G'] = 1, ['H'] = 1, ['I'] = 1,  ['J'] = 1, ['K'] = 1, ['L'] = 1,
233  ['M'] = 1, ['N'] = 1, ['O'] = 1,  ['P'] = 1, ['Q'] = 1, ['R'] = 1,
234  ['S'] = 1, ['T'] = 1, ['U'] = 1,  ['V'] = 1, ['W'] = 1, ['X'] = 1,
235  ['Y'] = 1, ['Z'] = 1,
236
237  ['1'] = 1, ['2'] = 1, ['3'] = 1,  ['4'] = 1, ['5'] = 1, ['6'] = 1,
238  ['7'] = 1, ['8'] = 1, ['9'] = 1,  ['0'] = 1,
239
240  ['_']  = 1,
241};
242
243/* Table to tell if a character is legal as the first character of
244   a C identifier. */
245U_CHAR is_idstart[256] =
246{
247  ['a'] = 1, ['b'] = 1, ['c'] = 1,  ['d'] = 1, ['e'] = 1, ['f'] = 1,
248  ['g'] = 1, ['h'] = 1, ['i'] = 1,  ['j'] = 1, ['k'] = 1, ['l'] = 1,
249  ['m'] = 1, ['n'] = 1, ['o'] = 1,  ['p'] = 1, ['q'] = 1, ['r'] = 1,
250  ['s'] = 1, ['t'] = 1, ['u'] = 1,  ['v'] = 1, ['w'] = 1, ['x'] = 1,
251  ['y'] = 1, ['z'] = 1,
252
253  ['A'] = 1, ['B'] = 1, ['C'] = 1,  ['D'] = 1, ['E'] = 1, ['F'] = 1,
254  ['G'] = 1, ['H'] = 1, ['I'] = 1,  ['J'] = 1, ['K'] = 1, ['L'] = 1,
255  ['M'] = 1, ['N'] = 1, ['O'] = 1,  ['P'] = 1, ['Q'] = 1, ['R'] = 1,
256  ['S'] = 1, ['T'] = 1, ['U'] = 1,  ['V'] = 1, ['W'] = 1, ['X'] = 1,
257  ['Y'] = 1, ['Z'] = 1,
258
259  ['_']  = 1,
260};
261
262/* Table to tell if a character is horizontal space.
263   \r is magical, so it is not in here.  */
264U_CHAR is_hor_space[256] =
265{
266  [' '] = 1, ['\t'] = 1, ['\v'] = 1, ['\f'] = 1,
267};
268/* table to tell if a character is horizontal or vertical space.  */
269U_CHAR is_space[256] =
270{
271  [' '] = 1, ['\t'] = 1, ['\v'] = 1, ['\f'] = 1, ['\n'] = 1,
272};
273/* Table to handle trigraph conversion, which occurs before all other
274   processing, everywhere in the file.  (This is necessary since one
275   of the trigraphs encodes backslash.)  Note it's off by default.
276
277	from	to	from	to	from	to
278	?? =	#	?? )	]	?? !	|
279	?? (	[	?? '	^	?? >	}
280	?? /	\	?? <	{	?? -	~
281
282   There is not a space between the ?? and the third char.  I put spaces
283   there to avoid warnings when compiling this file. */
284U_CHAR trigraph_table[256] =
285{
286  ['='] = '#',  [')'] = ']',  ['!'] = '|',
287  ['('] = '[',  ['\''] = '^', ['>'] = '}',
288  ['/'] = '\\', ['<'] = '{',  ['-'] = '~',
289};
290
291/* This function will be entirely removed soon. */
292static inline void
293initialize_char_syntax (dollar_in_ident)
294     int dollar_in_ident;
295{
296  is_idchar['$'] = dollar_in_ident;
297  is_idstart['$'] = dollar_in_ident;
298}
299
300#else /* Not GCC. */
301
302U_CHAR is_idchar[256] = { 0 };
303U_CHAR is_idstart[256] = { 0 };
304U_CHAR is_hor_space[256] = { 0 };
305U_CHAR is_space[256] = { 0 };
306U_CHAR trigraph_table[256] = { 0 };
307
308/* Initialize syntactic classifications of characters. */
309static void
310initialize_char_syntax (dollar_in_ident)
311     int dollar_in_ident;
312{
313  is_idstart['a'] = 1; is_idstart['b'] = 1; is_idstart['c'] = 1;
314  is_idstart['d'] = 1; is_idstart['e'] = 1; is_idstart['f'] = 1;
315  is_idstart['g'] = 1; is_idstart['h'] = 1; is_idstart['i'] = 1;
316  is_idstart['j'] = 1; is_idstart['k'] = 1; is_idstart['l'] = 1;
317  is_idstart['m'] = 1; is_idstart['n'] = 1; is_idstart['o'] = 1;
318  is_idstart['p'] = 1; is_idstart['q'] = 1; is_idstart['r'] = 1;
319  is_idstart['s'] = 1; is_idstart['t'] = 1; is_idstart['u'] = 1;
320  is_idstart['v'] = 1; is_idstart['w'] = 1; is_idstart['x'] = 1;
321  is_idstart['y'] = 1; is_idstart['z'] = 1;
322
323  is_idstart['A'] = 1; is_idstart['B'] = 1; is_idstart['C'] = 1;
324  is_idstart['D'] = 1; is_idstart['E'] = 1; is_idstart['F'] = 1;
325  is_idstart['G'] = 1; is_idstart['H'] = 1; is_idstart['I'] = 1;
326  is_idstart['J'] = 1; is_idstart['K'] = 1; is_idstart['L'] = 1;
327  is_idstart['M'] = 1; is_idstart['N'] = 1; is_idstart['O'] = 1;
328  is_idstart['P'] = 1; is_idstart['Q'] = 1; is_idstart['R'] = 1;
329  is_idstart['S'] = 1; is_idstart['T'] = 1; is_idstart['U'] = 1;
330  is_idstart['V'] = 1; is_idstart['W'] = 1; is_idstart['X'] = 1;
331  is_idstart['Y'] = 1; is_idstart['Z'] = 1;
332
333  is_idstart['_'] = 1;
334
335  is_idchar['a'] = 1; is_idchar['b'] = 1; is_idchar['c'] = 1;
336  is_idchar['d'] = 1; is_idchar['e'] = 1; is_idchar['f'] = 1;
337  is_idchar['g'] = 1; is_idchar['h'] = 1; is_idchar['i'] = 1;
338  is_idchar['j'] = 1; is_idchar['k'] = 1; is_idchar['l'] = 1;
339  is_idchar['m'] = 1; is_idchar['n'] = 1; is_idchar['o'] = 1;
340  is_idchar['p'] = 1;  is_idchar['q'] = 1; is_idchar['r'] = 1;
341  is_idchar['s'] = 1; is_idchar['t'] = 1;  is_idchar['u'] = 1;
342  is_idchar['v'] = 1; is_idchar['w'] = 1; is_idchar['x'] = 1;
343  is_idchar['y'] = 1; is_idchar['z'] = 1;
344
345  is_idchar['A'] = 1; is_idchar['B'] = 1; is_idchar['C'] = 1;
346  is_idchar['D'] = 1; is_idchar['E'] = 1; is_idchar['F'] = 1;
347  is_idchar['G'] = 1; is_idchar['H'] = 1; is_idchar['I'] = 1;
348  is_idchar['J'] = 1; is_idchar['K'] = 1; is_idchar['L'] = 1;
349  is_idchar['M'] = 1; is_idchar['N'] = 1; is_idchar['O'] = 1;
350  is_idchar['P'] = 1; is_idchar['Q'] = 1; is_idchar['R'] = 1;
351  is_idchar['S'] = 1; is_idchar['T'] = 1;  is_idchar['U'] = 1;
352  is_idchar['V'] = 1; is_idchar['W'] = 1; is_idchar['X'] = 1;
353  is_idchar['Y'] = 1; is_idchar['Z'] = 1;
354
355  is_idchar['1'] = 1; is_idchar['2'] = 1; is_idchar['3'] = 1;
356  is_idchar['4'] = 1; is_idchar['5'] = 1; is_idchar['6'] = 1;
357  is_idchar['7'] = 1; is_idchar['8'] = 1; is_idchar['9'] = 1;
358  is_idchar['0'] = 1;
359
360  is_idchar['_']  = 1;
361
362  is_idchar['$']  = dollar_in_ident;
363  is_idstart['$'] = dollar_in_ident;
364
365  /* white space tables */
366  is_hor_space[' '] = 1;
367  is_hor_space['\t'] = 1;
368  is_hor_space['\v'] = 1;
369  is_hor_space['\f'] = 1;
370
371  is_space[' '] = 1;
372  is_space['\t'] = 1;
373  is_space['\v'] = 1;
374  is_space['\f'] = 1;
375  is_space['\n'] = 1;
376
377  /* trigraph conversion */
378  trigraph_table['='] = '#';  trigraph_table[')'] = ']';
379  trigraph_table['!'] = '|';  trigraph_table['('] = '[';
380  trigraph_table['\''] = '^'; trigraph_table['>'] = '}';
381  trigraph_table['/'] = '\\'; trigraph_table['<'] = '{';
382  trigraph_table['-'] = '~';
383}
384
385#endif /* Not GCC. */
386
387/* Given a colon-separated list of file names PATH,
388   add all the names to the search path for include files.  */
389
390static void
391path_include (pfile, pend, list, path)
392     cpp_reader *pfile;
393     struct cpp_pending *pend;
394     char *list;
395     int path;
396{
397  char *p, *q, *name;
398
399  p = list;
400
401  do
402    {
403      /* Find the end of this name.  */
404      q = p;
405      while (*q != 0 && *q != PATH_SEPARATOR) q++;
406      if (q == p)
407	{
408	  /* An empty name in the path stands for the current directory.  */
409	  name = (char *) xmalloc (2);
410	  name[0] = '.';
411	  name[1] = 0;
412	}
413      else
414	{
415	  /* Otherwise use the directory that is named.  */
416	  name = (char *) xmalloc (q - p + 1);
417	  memcpy (name, p, q - p);
418	  name[q - p] = 0;
419	}
420
421      append_include_chain (pfile, pend, name, path);
422
423      /* Advance past this name.  */
424      if (*q == 0)
425	break;
426      p = q + 1;
427    }
428  while (1);
429}
430
431/* Find the base name of a (partial) pathname FNAME.
432   Returns a pointer into the string passed in.
433   Accepts Unix (/-separated) paths on all systems,
434   DOS and VMS paths on those systems.  */
435static char *
436base_name (fname)
437     const char *fname;
438{
439  char *s = (char *)fname;
440  char *p;
441#if defined (HAVE_DOS_BASED_FILE_SYSTEM)
442  if (ISALPHA (s[0]) && s[1] == ':') s += 2;
443  if ((p = rindex (s, '\\'))) s = p + 1;
444#elif defined VMS
445  if ((p = rindex (s, ':'))) s = p + 1; /* Skip device.  */
446  if ((p = rindex (s, ']'))) s = p + 1; /* Skip directory.  */
447  if ((p = rindex (s, '>'))) s = p + 1; /* Skip alternate (int'n'l) dir.  */
448#endif
449  if ((p = rindex (s, '/'))) s = p + 1;
450  return s;
451}
452
453
454/* Append DIR to include path PATH.  DIR must be permanently allocated
455   and writable. */
456static void
457append_include_chain (pfile, pend, dir, path)
458     cpp_reader *pfile;
459     struct cpp_pending *pend;
460     char *dir;
461     int path;
462{
463  struct file_name_list *new;
464  struct stat st;
465  unsigned int len;
466
467  simplify_pathname (dir);
468  if (stat (dir, &st))
469    {
470      /* Dirs that don't exist are silently ignored. */
471      if (errno != ENOENT)
472	cpp_perror_with_name (pfile, dir);
473      else if (CPP_OPTIONS (pfile)->verbose)
474	cpp_notice ("ignoring nonexistent directory `%s'\n", dir);
475      return;
476    }
477
478  if (!S_ISDIR (st.st_mode))
479    {
480      cpp_message (pfile, 1, "%s: %s: Not a directory", progname, dir);
481      return;
482    }
483
484  len = strlen (dir);
485  if (len > pfile->max_include_len)
486    pfile->max_include_len = len;
487
488  new = (struct file_name_list *)xmalloc (sizeof (struct file_name_list));
489  new->name = dir;
490  new->nlen = len;
491  new->ino  = st.st_ino;
492  new->dev  = st.st_dev;
493  new->sysp = (path == SYSTEM);
494  new->name_map = NULL;
495
496  switch (path)
497    {
498    case QUOTE:		APPEND (pend, quote, new); break;
499    case BRACKET:	APPEND (pend, brack, new); break;
500    case SYSTEM:	APPEND (pend, systm, new); break;
501    case AFTER:		APPEND (pend, after, new); break;
502    }
503}
504
505
506/* Write out a #define command for the special named MACRO_NAME
507   to PFILE's token_buffer.  */
508
509static void
510dump_special_to_buffer (pfile, macro_name)
511     cpp_reader *pfile;
512     char *macro_name;
513{
514  static char define_directive[] = "#define ";
515  int macro_name_length = strlen (macro_name);
516  output_line_command (pfile, same_file);
517  CPP_RESERVE (pfile, sizeof(define_directive) + macro_name_length);
518  CPP_PUTS_Q (pfile, define_directive, sizeof(define_directive)-1);
519  CPP_PUTS_Q (pfile, macro_name, macro_name_length);
520  CPP_PUTC_Q (pfile, ' ');
521  cpp_expand_to_buffer (pfile, macro_name, macro_name_length);
522  CPP_PUTC (pfile, '\n');
523}
524
525/* Initialize a cpp_options structure. */
526void
527cpp_options_init (opts)
528     cpp_options *opts;
529{
530  bzero ((char *) opts, sizeof (struct cpp_options));
531
532  opts->dollars_in_ident = 1;
533  opts->cplusplus_comments = 1;
534  opts->warn_import = 1;
535
536  opts->pending = (struct cpp_pending *) xmalloc (sizeof (struct cpp_pending));
537  bzero ((char *) opts->pending, sizeof (struct cpp_pending));
538}
539
540/* Initialize a cpp_reader structure. */
541void
542cpp_reader_init (pfile)
543     cpp_reader *pfile;
544{
545  bzero ((char *) pfile, sizeof (cpp_reader));
546#if 0
547  pfile->get_token = cpp_get_token;
548#endif
549
550  pfile->token_buffer_size = 200;
551  pfile->token_buffer = (U_CHAR *) xmalloc (pfile->token_buffer_size);
552  CPP_SET_WRITTEN (pfile, 0);
553
554  pfile->hashtab = (HASHNODE **) xcalloc (HASHSIZE, sizeof (HASHNODE *));
555}
556
557/* Free resources used by PFILE.
558   This is the cpp_reader 'finalizer' or 'destructor' (in C++ terminology).  */
559void
560cpp_cleanup (pfile)
561     cpp_reader *pfile;
562{
563  int i;
564  while (CPP_BUFFER (pfile) != CPP_NULL_BUFFER (pfile))
565    cpp_pop_buffer (pfile);
566
567  if (pfile->token_buffer)
568    {
569      free (pfile->token_buffer);
570      pfile->token_buffer = NULL;
571    }
572
573  if (pfile->deps_buffer)
574    {
575      free (pfile->deps_buffer);
576      pfile->deps_buffer = NULL;
577      pfile->deps_allocated_size = 0;
578    }
579
580  if (pfile->input_buffer)
581    {
582      free (pfile->input_buffer);
583      free (pfile->input_speccase);
584      pfile->input_buffer = pfile->input_speccase = NULL;
585      pfile->input_buffer_len = 0;
586    }
587
588  while (pfile->if_stack)
589    {
590      IF_STACK_FRAME *temp = pfile->if_stack;
591      pfile->if_stack = temp->next;
592      free (temp);
593    }
594
595  for (i = ALL_INCLUDE_HASHSIZE; --i >= 0; )
596    {
597      struct include_hash *imp = pfile->all_include_files[i];
598      while (imp)
599	{
600	  struct include_hash *next = imp->next;
601#if 0
602	  /* This gets freed elsewhere - I think. */
603	  free (imp->name);
604#endif
605	  free (imp);
606	  imp = next;
607	}
608      pfile->all_include_files[i] = 0;
609    }
610
611  for (i = HASHSIZE; --i >= 0;)
612    {
613      while (pfile->hashtab[i])
614	delete_macro (pfile->hashtab[i]);
615    }
616  free (pfile->hashtab);
617}
618
619
620/* Initialize the built-in macros.  */
621static void
622initialize_builtins (pfile)
623     cpp_reader *pfile;
624{
625#define NAME(str) (U_CHAR *)str, sizeof str - 1
626  cpp_install (pfile, NAME("__TIME__"),		  T_TIME,	0, -1);
627  cpp_install (pfile, NAME("__DATE__"),		  T_DATE,	0, -1);
628  cpp_install (pfile, NAME("__FILE__"),		  T_FILE,	0, -1);
629  cpp_install (pfile, NAME("__BASE_FILE__"),	  T_BASE_FILE,	0, -1);
630  cpp_install (pfile, NAME("__LINE__"),		  T_SPECLINE,	0, -1);
631  cpp_install (pfile, NAME("__INCLUDE_LEVEL__"),  T_INCLUDE_LEVEL, 0, -1);
632  cpp_install (pfile, NAME("__VERSION__"),	  T_VERSION,	0, -1);
633#ifndef NO_BUILTIN_SIZE_TYPE
634  cpp_install (pfile, NAME("__SIZE_TYPE__"),	  T_CONST, SIZE_TYPE, -1);
635#endif
636#ifndef NO_BUILTIN_PTRDIFF_TYPE
637  cpp_install (pfile, NAME("__PTRDIFF_TYPE__ "),  T_CONST, PTRDIFF_TYPE, -1);
638#endif
639  cpp_install (pfile, NAME("__WCHAR_TYPE__"),	  T_CONST, WCHAR_TYPE, -1);
640  cpp_install (pfile, NAME("__USER_LABEL_PREFIX__"), T_CONST, user_label_prefix, -1);
641  cpp_install (pfile, NAME("__REGISTER_PREFIX__"),  T_CONST, REGISTER_PREFIX, -1);
642  cpp_install (pfile, NAME("__HAVE_BUILTIN_SETJMP__"), T_CONST, "1", -1);
643  if (!CPP_TRADITIONAL (pfile))
644    {
645      cpp_install (pfile, NAME("__STDC__"),	  T_STDC,  0, -1);
646#if 0
647      if (CPP_OPTIONS (pfile)->c9x)
648	cpp_install (pfile, NAME("__STDC_VERSION__"),T_CONST, "199909L", -1);
649      else
650#endif
651	cpp_install (pfile, NAME("__STDC_VERSION__"),T_CONST, "199409L", -1);
652    }
653#undef NAME
654
655  if (CPP_OPTIONS (pfile)->debug_output)
656    {
657      dump_special_to_buffer (pfile, "__BASE_FILE__");
658      dump_special_to_buffer (pfile, "__VERSION__");
659#ifndef NO_BUILTIN_SIZE_TYPE
660      dump_special_to_buffer (pfile, "__SIZE_TYPE__");
661#endif
662#ifndef NO_BUILTIN_PTRDIFF_TYPE
663      dump_special_to_buffer (pfile, "__PTRDIFF_TYPE__");
664#endif
665      dump_special_to_buffer (pfile, "__WCHAR_TYPE__");
666      dump_special_to_buffer (pfile, "__DATE__");
667      dump_special_to_buffer (pfile, "__TIME__");
668      if (!CPP_TRADITIONAL (pfile))
669	dump_special_to_buffer (pfile, "__STDC__");
670    }
671}
672
673/* Another subroutine of cpp_start_read.  This one sets up to do
674   dependency-file output. */
675static void
676initialize_dependency_output (pfile)
677     cpp_reader *pfile;
678{
679  cpp_options *opts = CPP_OPTIONS (pfile);
680  char *spec, *s, *output_file;
681
682  /* Either of two environment variables can specify output of deps.
683     Its value is either "OUTPUT_FILE" or "OUTPUT_FILE DEPS_TARGET",
684     where OUTPUT_FILE is the file to write deps info to
685     and DEPS_TARGET is the target to mention in the deps.  */
686
687  if (opts->print_deps == 0)
688    {
689      spec = getenv ("DEPENDENCIES_OUTPUT");
690      if (spec)
691	opts->print_deps = 1;
692      else
693	{
694	  spec = getenv ("SUNPRO_DEPENDENCIES");
695	  if (spec)
696	    opts->print_deps = 2;
697	  else
698	    return;
699	}
700
701      /* Find the space before the DEPS_TARGET, if there is one.  */
702      s = strchr (spec, ' ');
703      if (s)
704	{
705	  opts->deps_target = s + 1;
706	  output_file = (char *) xmalloc (s - spec + 1);
707	  memcpy (output_file, spec, s - spec);
708	  output_file[s - spec] = 0;
709	}
710      else
711	{
712	  opts->deps_target = 0;
713	  output_file = spec;
714	}
715
716      opts->deps_file = output_file;
717      opts->print_deps_append = 1;
718    }
719
720  /* Print the expected object file name as the target of this Make-rule.  */
721  pfile->deps_allocated_size = 200;
722  pfile->deps_buffer = (char *) xmalloc (pfile->deps_allocated_size);
723  pfile->deps_buffer[0] = 0;
724  pfile->deps_size = 0;
725  pfile->deps_column = 0;
726
727  if (opts->deps_target)
728    deps_output (pfile, opts->deps_target, ':');
729  else if (*opts->in_fname == 0)
730    deps_output (pfile, "-", ':');
731  else
732    {
733      char *p, *q, *r;
734      int len, x;
735
736      /* Discard all directory prefixes from filename.  */
737      q = base_name (opts->in_fname);
738
739      /* Copy remainder to mungable area.  */
740      len = strlen (q);
741      p = (char *) alloca (len + 8);
742      strcpy (p, q);
743
744      /* Output P, but remove known suffixes.  */
745      q = p + len;
746      /* Point to the filename suffix.  */
747      r = rindex (p, '.');
748      /* Compare against the known suffixes.  */
749      for (x = 0; known_suffixes[x]; x++)
750	{
751	  if (strncmp (known_suffixes[x], r, q - r) == 0)
752	    {
753	      /* Make q point to the bit we're going to overwrite
754		 with an object suffix.  */
755	      q = r;
756	      break;
757	    }
758	}
759
760      /* Supply our own suffix.  */
761      strcpy (q, OBJECT_SUFFIX);
762
763      deps_output (pfile, p, ':');
764      deps_output (pfile, opts->in_fname, ' ');
765    }
766}
767
768/* This is called after options have been processed.
769 * Check options for consistency, and setup for processing input
770 * from the file named FNAME.  (Use standard input if FNAME==NULL.)
771 * Return 1 on success, 0 on failure.
772 */
773
774int
775cpp_start_read (pfile, fname)
776     cpp_reader *pfile;
777     char *fname;
778{
779  struct cpp_options *opts = CPP_OPTIONS (pfile);
780  struct pending_option *p, *q;
781  int f;
782  cpp_buffer *fp;
783  struct include_hash *ih_fake;
784
785  /* -MG doesn't select the form of output and must be specified with one of
786     -M or -MM.  -MG doesn't make sense with -MD or -MMD since they don't
787     inhibit compilation.  */
788  if (opts->print_deps_missing_files
789      && (opts->print_deps == 0 || !opts->no_output))
790    {
791      cpp_fatal (pfile, "-MG must be specified with one of -M or -MM");
792      return 0;
793    }
794
795  /* Chill should not be used with -trigraphs. */
796  if (opts->chill && opts->trigraphs)
797    {
798      cpp_warning (pfile, "-lang-chill and -trigraphs are mutually exclusive");
799      opts->trigraphs = 0;
800    }
801
802  /* Set this if it hasn't been set already. */
803  if (user_label_prefix == NULL)
804    user_label_prefix = USER_LABEL_PREFIX;
805
806  /* Now that we know dollars_in_ident, we can initialize the syntax
807     tables. */
808  initialize_char_syntax (opts->dollars_in_ident);
809
810  /* Do partial setup of input buffer for the sake of generating
811     early #line directives (when -g is in effect).  */
812  fp = cpp_push_buffer (pfile, NULL, 0);
813  if (!fp)
814    return 0;
815  if (opts->in_fname == NULL || *opts->in_fname == 0)
816    {
817      opts->in_fname = fname;
818      if (opts->in_fname == NULL)
819	opts->in_fname = "";
820    }
821  fp->nominal_fname = fp->fname = opts->in_fname;
822  fp->lineno = 0;
823
824  /* Install __LINE__, etc.  Must follow initialize_char_syntax
825     and option processing.  */
826  initialize_builtins (pfile);
827
828  /* Do -U's, -D's and -A's in the order they were seen.  */
829  p = opts->pending->define_head;
830  while (p)
831    {
832      if (opts->debug_output)
833	output_line_command (pfile, same_file);
834      if (p->undef)
835	cpp_undef (pfile, p->arg);
836      else
837	cpp_define (pfile, p->arg);
838
839      q = p->next;
840      free (p);
841      p = q;
842    }
843
844  p = opts->pending->assert_head;
845  while (p)
846    {
847      if (opts->debug_output)
848	output_line_command (pfile, same_file);
849      if (p->undef)
850	cpp_unassert (pfile, p->arg);
851      else
852	cpp_assert (pfile, p->arg);
853
854      q = p->next;
855      free (p);
856      p = q;
857    }
858
859  opts->done_initializing = 1;
860
861  /* Several environment variables may add to the include search path.
862     CPATH specifies an additional list of directories to be searched
863     as if specified with -I, while C_INCLUDE_PATH, CPLUS_INCLUDE_PATH,
864     etc. specify an additional list of directories to be searched as
865     if specified with -isystem, for the language indicated.
866
867     These variables are ignored if -nostdinc is on.  */
868  if (! opts->no_standard_includes)
869    {
870      char *path;
871      GET_ENV_PATH_LIST (path, "CPATH");
872      if (path != 0 && *path != 0)
873	path_include (pfile, opts->pending, path, BRACKET);
874
875      switch ((opts->objc << 1) + opts->cplusplus)
876	{
877	case 0:
878	  GET_ENV_PATH_LIST (path, "C_INCLUDE_PATH");
879	  break;
880	case 1:
881	  GET_ENV_PATH_LIST (path, "CPLUS_INCLUDE_PATH");
882	  break;
883	case 2:
884	  GET_ENV_PATH_LIST (path, "OBJC_INCLUDE_PATH");
885	  break;
886	case 3:
887	  GET_ENV_PATH_LIST (path, "OBJCPLUS_INCLUDE_PATH");
888	  break;
889	}
890      if (path != 0 && *path != 0)
891	path_include (pfile, opts->pending, path, SYSTEM);
892    }
893
894  /* Unless -nostdinc, add the compiled-in include path to the list,
895     translating prefixes. */
896  if (!opts->no_standard_includes)
897    {
898      struct default_include *p = include_defaults_array;
899      char *specd_prefix = opts->include_prefix;
900
901      /* Search "translated" versions of GNU directories.
902	 These have /usr/local/lib/gcc... replaced by specd_prefix.  */
903      if (specd_prefix != 0)
904	{
905	  char *default_prefix = alloca (sizeof GCC_INCLUDE_DIR - 7);
906	  /* Remove the `include' from /usr/local/lib/gcc.../include.
907	     GCC_INCLUDE_DIR will always end in /include. */
908	  int default_len = sizeof GCC_INCLUDE_DIR - 8;
909	  int specd_len = strlen (specd_prefix);
910
911	  default_len = sizeof GCC_INCLUDE_DIR - 8;
912	  memcpy (default_prefix, GCC_INCLUDE_DIR, default_len);
913	  default_prefix[default_len] = '\0';
914
915	  for (p = include_defaults_array; p->fname; p++)
916	    {
917	      /* Some standard dirs are only for C++.  */
918	      if (!p->cplusplus
919		  || (opts->cplusplus
920		      && !opts->no_standard_cplusplus_includes))
921		{
922		  /* Does this dir start with the prefix?  */
923		  if (!strncmp (p->fname, default_prefix, default_len))
924		    {
925		      /* Yes; change prefix and add to search list.  */
926		      int flen = strlen (p->fname);
927		      int this_len = specd_len + flen - default_len;
928		      char *str = (char *) xmalloc (this_len + 1);
929		      memcpy (str, specd_prefix, specd_len);
930		      memcpy (str + specd_len,
931			      p->fname + default_len,
932			      flen - default_len + 1);
933
934		      append_include_chain (pfile, opts->pending,
935					    str, SYSTEM);
936		    }
937		}
938	    }
939	}
940
941      /* Search ordinary names for GNU include directories.  */
942      for (p = include_defaults_array; p->fname; p++)
943	{
944	  /* Some standard dirs are only for C++.  */
945	  if (!p->cplusplus
946	      || (opts->cplusplus
947		  && !opts->no_standard_cplusplus_includes))
948	    {
949	      char *str = (char *) update_path (p->fname, p->component);
950	      str = xstrdup (str);  /* XXX Potential memory leak! */
951	      append_include_chain (pfile, opts->pending, str, SYSTEM);
952	    }
953	}
954    }
955
956  merge_include_chains (opts);
957
958  /* With -v, print the list of dirs to search.  */
959  if (opts->verbose)
960    {
961      struct file_name_list *p;
962      cpp_message (pfile, -1, "#include \"...\" search starts here:\n");
963      for (p = opts->quote_include; p; p = p->next)
964	{
965	  if (p == opts->bracket_include)
966	    cpp_message (pfile, -1, "#include <...> search starts here:\n");
967	  fprintf (stderr, " %s\n", p->name);
968	}
969      cpp_message (pfile, -1, "End of search list.\n");
970    }
971
972  /* Open the main input file.
973     We do this in nonblocking mode so we don't get stuck here if
974     someone clever has asked cpp to process /dev/rmt0;
975     finclude() will check that we have a real file to work with.  */
976  if (fname == NULL || *fname == 0)
977    {
978      fname = "";
979      f = 0;
980    }
981  else if ((f = open (fname, O_RDONLY|O_NONBLOCK|O_NOCTTY, 0666)) < 0)
982    cpp_pfatal_with_name (pfile, fname);
983
984  initialize_dependency_output (pfile);
985
986  /* Must call finclude() on the main input before processing
987     -include switches; otherwise the -included text winds up
988     after the main input. */
989  ih_fake = (struct include_hash *) xmalloc (sizeof (struct include_hash));
990  ih_fake->next = 0;
991  ih_fake->next_this_file = 0;
992  ih_fake->foundhere = ABSOLUTE_PATH;  /* well sort of ... */
993  ih_fake->name = fname;
994  ih_fake->control_macro = 0;
995  ih_fake->buf = (char *)-1;
996  ih_fake->limit = 0;
997  if (!finclude (pfile, f, ih_fake))
998    return 0;
999  output_line_command (pfile, same_file);
1000  pfile->only_seen_white = 2;
1001
1002  /* The -imacros files can be scanned now, but the -include files
1003     have to be pushed onto the include stack and processed later,
1004     in the main loop calling cpp_get_token.  */
1005
1006  pfile->no_record_file++;
1007  opts->no_output++;
1008  p = opts->pending->imacros_head;
1009  while (p)
1010    {
1011      int fd = open (p->arg, O_RDONLY|O_NONBLOCK|O_NOCTTY, 0666);
1012      if (fd < 0)
1013	{
1014	  cpp_perror_with_name (pfile, p->arg);
1015	  return 0;
1016	}
1017      if (!cpp_push_buffer (pfile, NULL, 0))
1018	return 0;
1019
1020      ih_fake = (struct include_hash *)
1021	xmalloc (sizeof (struct include_hash));
1022      ih_fake->next = 0;
1023      ih_fake->next_this_file = 0;
1024      ih_fake->foundhere = ABSOLUTE_PATH;  /* well sort of ... */
1025      ih_fake->name = p->arg;
1026      ih_fake->control_macro = 0;
1027      ih_fake->buf = (char *)-1;
1028      ih_fake->limit = 0;
1029      if (!finclude (pfile, fd, ih_fake))
1030	cpp_scan_buffer (pfile);
1031      free (ih_fake);
1032
1033      q = p->next;
1034      free (p);
1035      p = q;
1036    }
1037
1038  opts->no_output--;
1039
1040  p = opts->pending->include_head;
1041  while (p)
1042    {
1043      int fd = open (p->arg, O_RDONLY|O_NONBLOCK|O_NOCTTY, 0666);
1044      if (fd < 0)
1045	{
1046	  cpp_perror_with_name (pfile, p->arg);
1047	  return 0;
1048	}
1049      if (!cpp_push_buffer (pfile, NULL, 0))
1050	return 0;
1051
1052      ih_fake = (struct include_hash *)
1053	xmalloc (sizeof (struct include_hash));
1054      ih_fake->next = 0;
1055      ih_fake->next_this_file = 0;
1056      ih_fake->foundhere = ABSOLUTE_PATH;  /* well sort of ... */
1057      ih_fake->name = p->arg;
1058      ih_fake->control_macro = 0;
1059      ih_fake->buf = (char *)-1;
1060      ih_fake->limit = 0;
1061      if (finclude (pfile, fd, ih_fake))
1062	output_line_command (pfile, enter_file);
1063
1064      q = p->next;
1065      free (p);
1066      p = q;
1067    }
1068  pfile->no_record_file--;
1069
1070  free (opts->pending);
1071  opts->pending = NULL;
1072
1073  return 1;
1074}
1075
1076/* This is called at the end of preprocessing.  It pops the
1077   last buffer and writes dependency output.  It should also
1078   clear macro definitions, such that you could call cpp_start_read
1079   with a new filename to restart processing. */
1080void
1081cpp_finish (pfile)
1082     cpp_reader *pfile;
1083{
1084  struct cpp_options *opts = CPP_OPTIONS (pfile);
1085
1086  if (CPP_PREV_BUFFER (CPP_BUFFER (pfile)) != CPP_NULL_BUFFER (pfile))
1087    cpp_fatal (pfile,
1088	       "cpplib internal error: buffers still stacked in cpp_finish");
1089  cpp_pop_buffer (pfile);
1090
1091  if (opts->print_deps)
1092    {
1093      /* Stream on which to print the dependency information.  */
1094      FILE *deps_stream;
1095
1096      /* Don't actually write the deps file if compilation has failed.  */
1097      if (pfile->errors == 0)
1098	{
1099	  char *deps_mode = opts->print_deps_append ? "a" : "w";
1100	  if (opts->deps_file == 0)
1101	    deps_stream = stdout;
1102	  else if ((deps_stream = fopen (opts->deps_file, deps_mode)) == 0)
1103	    cpp_pfatal_with_name (pfile, opts->deps_file);
1104	  fputs (pfile->deps_buffer, deps_stream);
1105	  putc ('\n', deps_stream);
1106	  if (opts->deps_file)
1107	    {
1108	      if (ferror (deps_stream) || fclose (deps_stream) != 0)
1109		cpp_fatal (pfile, "I/O error on output");
1110	    }
1111	}
1112    }
1113
1114  if (opts->dump_macros == dump_only)
1115    {
1116      int i;
1117      HASHNODE *h;
1118      MACRODEF m;
1119      for (i = HASHSIZE; --i >= 0;)
1120	{
1121	  for (h = pfile->hashtab[i]; h; h = h->next)
1122	    if (h->type == T_MACRO)
1123	      {
1124		m.defn = h->value.defn;
1125		m.symnam = h->name;
1126		m.symlen = h->length;
1127		dump_definition (pfile, m);
1128		CPP_PUTC (pfile, '\n');
1129	      }
1130	}
1131    }
1132}
1133
1134/* Handle one command-line option in (argc, argv).
1135   Can be called multiple times, to handle multiple sets of options.
1136   Returns number of strings consumed.  */
1137int
1138cpp_handle_option (pfile, argc, argv)
1139     cpp_reader *pfile;
1140     int argc;
1141     char **argv;
1142{
1143  struct cpp_options *opts = CPP_OPTIONS (pfile);
1144  int i = 0;
1145
1146  if (argv[i][0] != '-')
1147    {
1148      if (opts->out_fname != NULL)
1149	{
1150	  print_help ();
1151	  cpp_fatal (pfile, "Too many arguments");
1152	}
1153      else if (opts->in_fname != NULL)
1154	opts->out_fname = argv[i];
1155      else
1156	opts->in_fname = argv[i];
1157    }
1158  else
1159    switch (argv[i][1])
1160      {
1161      case 'f':
1162	if (!strcmp (argv[i], "-fleading-underscore"))
1163	  user_label_prefix = "_";
1164	else if (!strcmp (argv[i], "-fno-leading-underscore"))
1165	  user_label_prefix = "";
1166	break;
1167
1168      case 'I':			/* Add directory to path for includes.  */
1169	if (!strcmp (argv[i] + 2, "-"))
1170	  {
1171	    /* -I- means:
1172	       Use the preceding -I directories for #include "..."
1173	       but not #include <...>.
1174	       Don't search the directory of the present file
1175	       for #include "...".  (Note that -I. -I- is not the same as
1176	       the default setup; -I. uses the compiler's working dir.)  */
1177	    if (! opts->ignore_srcdir)
1178	      {
1179		opts->ignore_srcdir = 1;
1180		opts->pending->quote_head = opts->pending->brack_head;
1181		opts->pending->quote_tail = opts->pending->brack_tail;
1182		opts->pending->brack_head = 0;
1183		opts->pending->brack_tail = 0;
1184	      }
1185	    else
1186	      {
1187		cpp_fatal (pfile, "-I- specified twice");
1188		return argc;
1189	      }
1190	  }
1191	else
1192	  {
1193	    char *fname;
1194	    if (argv[i][2] != 0)
1195	      fname = argv[i] + 2;
1196	    else if (i + 1 == argc)
1197	      goto missing_dirname;
1198	    else
1199	      fname = argv[++i];
1200	    append_include_chain (pfile, opts->pending,
1201				  xstrdup (fname), BRACKET);
1202	  }
1203	break;
1204
1205      case 'i':
1206	/* Add directory to beginning of system include path, as a system
1207	   include directory. */
1208	if (!strcmp (argv[i], "-isystem"))
1209	  {
1210	    if (i + 1 == argc)
1211	      goto missing_filename;
1212	    append_include_chain (pfile, opts->pending,
1213				  xstrdup (argv[++i]), SYSTEM);
1214	  }
1215	else if (!strcmp (argv[i], "-include"))
1216	  {
1217	    if (i + 1 == argc)
1218	      goto missing_filename;
1219	    else
1220	      {
1221		struct pending_option *o = (struct pending_option *)
1222		  xmalloc (sizeof (struct pending_option));
1223		o->arg = argv[++i];
1224
1225		/* This list has to be built in reverse order so that
1226		   when cpp_start_read pushes all the -include files onto
1227		   the buffer stack, they will be scanned in forward order.  */
1228		o->next = opts->pending->include_head;
1229		opts->pending->include_head = o;
1230	      }
1231	  }
1232	else if (!strcmp (argv[i], "-imacros"))
1233	  {
1234	    if (i + 1 == argc)
1235	      goto missing_filename;
1236	    else
1237	      {
1238		struct pending_option *o = (struct pending_option *)
1239		  xmalloc (sizeof (struct pending_option));
1240		o->arg = argv[++i];
1241		o->next = NULL;
1242
1243		APPEND (opts->pending, imacros, o);
1244	      }
1245	  }
1246	/* Add directory to end of path for includes,
1247	   with the default prefix at the front of its name.  */
1248	else if (!strcmp (argv[i], "-iwithprefix"))
1249	  {
1250	    char *fname;
1251	    int len;
1252	    if (i + 1 == argc)
1253	      goto missing_dirname;
1254	    ++i;
1255	    len = strlen (argv[i]);
1256
1257	    if (opts->include_prefix != 0)
1258	      {
1259		fname = xmalloc (opts->include_prefix_len + len + 1);
1260		memcpy (fname, opts->include_prefix, opts->include_prefix_len);
1261		memcpy (fname + opts->include_prefix_len, argv[i], len + 1);
1262	      }
1263	    else
1264	      {
1265		fname = xmalloc (sizeof GCC_INCLUDE_DIR - 8 + len);
1266		memcpy (fname, GCC_INCLUDE_DIR, sizeof GCC_INCLUDE_DIR - 9);
1267		memcpy (fname + sizeof GCC_INCLUDE_DIR - 9, argv[i], len + 1);
1268	      }
1269
1270	    append_include_chain (pfile, opts->pending, fname, SYSTEM);
1271	  }
1272	/* Add directory to main path for includes,
1273	   with the default prefix at the front of its name.  */
1274	else if (!strcmp (argv[i], "-iwithprefixbefore"))
1275	  {
1276	    char *fname;
1277	    int len;
1278	    if (i + 1 == argc)
1279	      goto missing_dirname;
1280	    ++i;
1281	    len = strlen (argv[i]);
1282
1283	    if (opts->include_prefix != 0)
1284	      {
1285		fname = xmalloc (opts->include_prefix_len + len + 1);
1286		memcpy (fname, opts->include_prefix, opts->include_prefix_len);
1287		memcpy (fname + opts->include_prefix_len, argv[i], len + 1);
1288	      }
1289	    else
1290	      {
1291		fname = xmalloc (sizeof GCC_INCLUDE_DIR - 8 + len);
1292		memcpy (fname, GCC_INCLUDE_DIR, sizeof GCC_INCLUDE_DIR - 9);
1293		memcpy (fname + sizeof GCC_INCLUDE_DIR - 9, argv[i], len + 1);
1294	      }
1295
1296	    append_include_chain (pfile, opts->pending, fname, BRACKET);
1297	  }
1298	/* Add directory to end of path for includes.  */
1299	else if (!strcmp (argv[i], "-idirafter"))
1300	  {
1301	    if (i + 1 == argc)
1302	      goto missing_dirname;
1303	    append_include_chain (pfile, opts->pending,
1304				  xstrdup (argv[++i]), AFTER);
1305	  }
1306	else if (!strcmp (argv[i], "-iprefix"))
1307	  {
1308	    if (i + 1 == argc)
1309	      goto missing_filename;
1310	    else
1311	      {
1312		opts->include_prefix = argv[++i];
1313		opts->include_prefix_len = strlen (argv[i]);
1314	      }
1315	  }
1316	else if (!strcmp (argv[i], "-ifoutput"))
1317	  opts->output_conditionals = 1;
1318
1319	break;
1320
1321      case 'o':
1322	if (opts->out_fname != NULL)
1323	  {
1324	    cpp_fatal (pfile, "Output filename specified twice");
1325	    return argc;
1326	  }
1327	if (i + 1 == argc)
1328	  goto missing_filename;
1329	opts->out_fname = argv[++i];
1330	if (!strcmp (opts->out_fname, "-"))
1331	  opts->out_fname = "";
1332	break;
1333
1334      case 'p':
1335	if (!strcmp (argv[i], "-pedantic"))
1336	  CPP_PEDANTIC (pfile) = 1;
1337	else if (!strcmp (argv[i], "-pedantic-errors"))
1338	  {
1339	    CPP_PEDANTIC (pfile) = 1;
1340	    opts->pedantic_errors = 1;
1341	  }
1342#if 0
1343	else if (!strcmp (argv[i], "-pcp")) {
1344	  char *pcp_fname = argv[++i];
1345	  pcp_outfile = ((pcp_fname[0] != '-' || pcp_fname[1] != '\0')
1346			 ? fopen (pcp_fname, "w")
1347			 : fdopen (dup (fileno (stdout)), "w"));
1348	  if (pcp_outfile == 0)
1349	    cpp_pfatal_with_name (pfile, pcp_fname);
1350	  no_precomp = 1;
1351	}
1352#endif
1353#if defined(__BEOS__) || defined(__HAIKU__)
1354        else if (!strncmp (argv[i], "-priority=", 10))
1355	  priority = atol (argv[i] + 10);
1356#endif
1357	break;
1358
1359      case 't':
1360	if (!strcmp (argv[i], "-traditional"))
1361	  {
1362	    opts->traditional = 1;
1363	    opts->cplusplus_comments = 0;
1364	  }
1365	else if (!strcmp (argv[i], "-trigraphs"))
1366	  opts->trigraphs = 1;
1367	break;
1368
1369      case 'l':
1370	if (! strcmp (argv[i], "-lang-c"))
1371	  opts->cplusplus = 0, opts->cplusplus_comments = 1, opts->c89 = 0,
1372	    opts->c9x = 1, opts->objc = 0;
1373	if (! strcmp (argv[i], "-lang-c89"))
1374	  opts->cplusplus = 0, opts->cplusplus_comments = 0, opts->c89 = 1,
1375	    opts->c9x = 0, opts->objc = 0;
1376	if (! strcmp (argv[i], "-lang-c++"))
1377	  opts->cplusplus = 1, opts->cplusplus_comments = 1, opts->c89 = 0,
1378	    opts->c9x = 0, opts->objc = 0;
1379	if (! strcmp (argv[i], "-lang-objc"))
1380	  opts->cplusplus = 0, opts->cplusplus_comments = 1, opts->c89 = 0,
1381	    opts->c9x = 0, opts->objc = 1;
1382	if (! strcmp (argv[i], "-lang-objc++"))
1383	  opts->cplusplus = 1, opts->cplusplus_comments = 1, opts->c89 = 0,
1384	    opts->c9x = 0, opts->objc = 1;
1385	if (! strcmp (argv[i], "-lang-asm"))
1386	  opts->lang_asm = 1;
1387	if (! strcmp (argv[i], "-lint"))
1388	  opts->for_lint = 1;
1389	if (! strcmp (argv[i], "-lang-chill"))
1390	  opts->objc = 0, opts->cplusplus = 0, opts->chill = 1,
1391	    opts->traditional = 1;
1392	break;
1393
1394      case '+':
1395	opts->cplusplus = 1, opts->cplusplus_comments = 1;
1396	break;
1397
1398      case 's':
1399	if (!strcmp (argv[i], "-std=iso9899:1990")
1400	    || !strcmp (argv[i], "-std=iso9899:199409")
1401	    || !strcmp (argv[i], "-std=c89")
1402	    || !strcmp (argv[i], "-std=gnu89"))
1403	  opts->cplusplus = 0, opts->cplusplus_comments = 0,
1404	    opts->c89 = 1, opts->c9x = 0, opts->objc = 0;
1405	else if (!strcmp (argv[i], "-std=iso9899:199x")
1406		 || !strcmp (argv[i], "-std=c9x")
1407		 || !strcmp (argv[i], "-std=gnu9x"))
1408	  opts->cplusplus = 0, opts->cplusplus_comments = 1, opts->c89 = 0,
1409	    opts->c9x = 1, opts->objc = 0;
1410	break;
1411
1412      case 'w':
1413	opts->inhibit_warnings = 1;
1414	break;
1415
1416      case 'W':
1417	if (!strcmp (argv[i], "-Wtrigraphs"))
1418	  opts->warn_trigraphs = 1;
1419	else if (!strcmp (argv[i], "-Wno-trigraphs"))
1420	  opts->warn_trigraphs = 0;
1421	else if (!strcmp (argv[i], "-Wcomment"))
1422	  opts->warn_comments = 1;
1423	else if (!strcmp (argv[i], "-Wno-comment"))
1424	  opts->warn_comments = 0;
1425	else if (!strcmp (argv[i], "-Wcomments"))
1426	  opts->warn_comments = 1;
1427	else if (!strcmp (argv[i], "-Wno-comments"))
1428	  opts->warn_comments = 0;
1429	else if (!strcmp (argv[i], "-Wtraditional"))
1430	  opts->warn_stringify = 1;
1431	else if (!strcmp (argv[i], "-Wno-traditional"))
1432	  opts->warn_stringify = 0;
1433	else if (!strcmp (argv[i], "-Wundef"))
1434	  opts->warn_undef = 1;
1435	else if (!strcmp (argv[i], "-Wno-undef"))
1436	  opts->warn_undef = 0;
1437	else if (!strcmp (argv[i], "-Wimport"))
1438	  opts->warn_import = 1;
1439	else if (!strcmp (argv[i], "-Wno-import"))
1440	  opts->warn_import = 0;
1441	else if (!strcmp (argv[i], "-Werror"))
1442	  opts->warnings_are_errors = 1;
1443	else if (!strcmp (argv[i], "-Wno-error"))
1444	  opts->warnings_are_errors = 0;
1445	else if (!strcmp (argv[i], "-Wall"))
1446	  {
1447	    opts->warn_trigraphs = 1;
1448	    opts->warn_comments = 1;
1449	  }
1450	break;
1451
1452      case 'M':
1453	/* The style of the choices here is a bit mixed.
1454	   The chosen scheme is a hybrid of keeping all options in one string
1455	   and specifying each option in a separate argument:
1456	   -M|-MM|-MD file|-MMD file [-MG].  An alternative is:
1457	   -M|-MM|-MD file|-MMD file|-MG|-MMG; or more concisely:
1458	   -M[M][G][D file].  This is awkward to handle in specs, and is not
1459	   as extensible.  */
1460	/* ??? -MG must be specified in addition to one of -M or -MM.
1461	   This can be relaxed in the future without breaking anything.
1462	   The converse isn't true.  */
1463
1464	/* -MG isn't valid with -MD or -MMD.  This is checked for later.  */
1465	if (!strcmp (argv[i], "-MG"))
1466	  {
1467	    opts->print_deps_missing_files = 1;
1468	    break;
1469	  }
1470	if (!strcmp (argv[i], "-M"))
1471	  opts->print_deps = 2;
1472	else if (!strcmp (argv[i], "-MM"))
1473	  opts->print_deps = 1;
1474	else if (!strcmp (argv[i], "-MD"))
1475	  opts->print_deps = 2;
1476	else if (!strcmp (argv[i], "-MMD"))
1477	  opts->print_deps = 1;
1478	/* For -MD and -MMD options, write deps on file named by next arg.  */
1479	if (!strcmp (argv[i], "-MD") || !strcmp (argv[i], "-MMD"))
1480	  {
1481	    if (i+1 == argc)
1482	      goto missing_filename;
1483	    opts->deps_file = argv[++i];
1484	  }
1485	else
1486	  {
1487	    /* For -M and -MM, write deps on standard output
1488	       and suppress the usual output.  */
1489	    opts->no_output = 1;
1490	  }
1491	break;
1492
1493      case 'd':
1494	{
1495	  char *p = argv[i] + 2;
1496	  char c;
1497	  while ((c = *p++) != 0)
1498	    {
1499	      /* Arg to -d specifies what parts of macros to dump */
1500	      switch (c)
1501		{
1502		case 'M':
1503		  opts->dump_macros = dump_only;
1504		  opts->no_output = 1;
1505		  break;
1506		case 'N':
1507		  opts->dump_macros = dump_names;
1508		  break;
1509		case 'D':
1510		  opts->dump_macros = dump_definitions;
1511		  break;
1512		case 'I':
1513		  opts->dump_includes = 1;
1514		  break;
1515		}
1516	    }
1517	}
1518	break;
1519
1520      case 'g':
1521	if (argv[i][2] == '3')
1522	  opts->debug_output = 1;
1523	break;
1524
1525      case '-':
1526	if (!strcmp (argv[i], "--help"))
1527	  print_help ();
1528	else if (!strcmp (argv[i], "--version"))
1529	  cpp_notice ("GNU CPP version %s\n", version_string);
1530	exit (0);  /* XXX */
1531	break;
1532
1533      case 'v':
1534	cpp_notice ("GNU CPP version %s", version_string);
1535#ifdef TARGET_VERSION
1536	TARGET_VERSION;
1537#endif
1538	fputc ('\n', stderr);
1539	opts->verbose = 1;
1540	break;
1541
1542      case 'H':
1543	opts->print_include_names = 1;
1544	break;
1545
1546      case 'D':
1547	{
1548	  struct pending_option *o = (struct pending_option *)
1549	    xmalloc (sizeof (struct pending_option));
1550	  if (argv[i][2] != 0)
1551	    o->arg = argv[i] + 2;
1552	  else if (i + 1 == argc)
1553	    {
1554	      cpp_fatal (pfile, "Macro name missing after -D option");
1555	      return argc;
1556	    }
1557	  else
1558	    o->arg = argv[++i];
1559
1560	  o->next = NULL;
1561	  o->undef = 0;
1562	  APPEND (opts->pending, define, o);
1563	}
1564	break;
1565
1566      case 'A':
1567	{
1568	  char *p;
1569
1570	  if (argv[i][2] != 0)
1571	    p = argv[i] + 2;
1572	  else if (i + 1 == argc)
1573	    {
1574	      cpp_fatal (pfile, "Assertion missing after -A option");
1575	      return argc;
1576	    }
1577	  else
1578	    p = argv[++i];
1579
1580	  if (strcmp (p, "-"))
1581	    {
1582	      struct pending_option *o = (struct pending_option *)
1583		xmalloc (sizeof (struct pending_option));
1584
1585	      o->arg = p;
1586	      o->next = NULL;
1587	      o->undef = 0;
1588	      APPEND (opts->pending, assert, o);
1589	    }
1590	  else
1591	    {
1592	      /* -A- eliminates all predefined macros and assertions.
1593		 Let's include also any that were specified earlier
1594		 on the command line.  That way we can get rid of any
1595		 that were passed automatically in from GCC.  */
1596	      struct pending_option *o1, *o2;
1597
1598	      o1 = opts->pending->define_head;
1599	      while (o1)
1600		{
1601		  o2 = o1->next;
1602		  free (o1);
1603		  o1 = o2;
1604		}
1605	      o1 = opts->pending->assert_head;
1606	      while (o1)
1607		{
1608		  o2 = o1->next;
1609		  free (o1);
1610		  o1 = o2;
1611		}
1612	      opts->pending->assert_head = NULL;
1613	      opts->pending->assert_tail = NULL;
1614	      opts->pending->define_head = NULL;
1615	      opts->pending->define_tail = NULL;
1616	    }
1617	}
1618	break;
1619
1620      case 'U':
1621	{
1622	  struct pending_option *o = (struct pending_option *)
1623	    xmalloc (sizeof (struct pending_option));
1624
1625	  if (argv[i][2] != 0)
1626	    o->arg = argv[i] + 2;
1627	  else if (i + 1 == argc)
1628	    {
1629	      cpp_fatal (pfile, "Macro name missing after -U option");
1630	      return argc;
1631	    }
1632	  else
1633	    o->arg = argv[++i];
1634
1635	  o->next = NULL;
1636	  o->undef = 1;
1637	  APPEND (opts->pending, define, o);
1638	}
1639	break;
1640
1641      case 'C':
1642	opts->put_out_comments = 1;
1643	break;
1644
1645      case 'E':			/* -E comes from cc -E; ignore it.  */
1646	break;
1647
1648      case 'P':
1649	opts->no_line_commands = 1;
1650	break;
1651
1652      case '$':			/* Don't include $ in identifiers.  */
1653	opts->dollars_in_ident = 0;
1654	break;
1655
1656      case 'n':
1657	if (!strcmp (argv[i], "-nostdinc"))
1658	  /* -nostdinc causes no default include directories.
1659	     You must specify all include-file directories with -I.  */
1660	  opts->no_standard_includes = 1;
1661	else if (!strcmp (argv[i], "-nostdinc++"))
1662	  /* -nostdinc++ causes no default C++-specific include directories. */
1663	  opts->no_standard_cplusplus_includes = 1;
1664#if 0
1665	else if (!strcmp (argv[i], "-noprecomp"))
1666	  no_precomp = 1;
1667#endif
1668	break;
1669
1670      case 'r':
1671	if (!strcmp (argv[i], "-remap"))
1672	  opts->remap = 1;
1673	break;
1674
1675      case '\0': /* JF handle '-' as file name meaning stdin or stdout */
1676	if (opts->in_fname == NULL)
1677	  opts->in_fname = "";
1678	else if (opts->out_fname == NULL)
1679	  opts->out_fname = "";
1680	else
1681	  return i;  /* error */
1682	break;
1683
1684      default:
1685	return i;
1686      }
1687
1688#if defined(__BEOS__) || defined(__HAIKU__)
1689  set_thread_priority (find_thread(NULL), priority);
1690  {
1691    char priobuf[20];
1692    sprintf (priobuf, "-priority=%d", priority);
1693    if (opts->verbose)
1694      cpp_notice ("using priority %d\n", priority);
1695  }
1696#endif
1697
1698  return i + 1;
1699
1700 missing_filename:
1701  cpp_fatal (pfile, "Filename missing after `%s' option", argv[i]);
1702  return argc;
1703 missing_dirname:
1704  cpp_fatal (pfile, "Directory name missing after `%s' option", argv[i]);
1705  return argc;
1706}
1707
1708/* Handle command-line options in (argc, argv).
1709   Can be called multiple times, to handle multiple sets of options.
1710   Returns if an unrecognized option is seen.
1711   Returns number of strings consumed.  */
1712
1713int
1714cpp_handle_options (pfile, argc, argv)
1715     cpp_reader *pfile;
1716     int argc;
1717     char **argv;
1718{
1719  int i;
1720  int strings_processed;
1721  for (i = 0; i < argc; i += strings_processed)
1722    {
1723      strings_processed = cpp_handle_option (pfile, argc - i, argv + i);
1724      if (strings_processed == 0)
1725	break;
1726    }
1727  return i;
1728}
1729
1730static void
1731print_help ()
1732{
1733  cpp_notice ("Usage: %s [switches] input output\n", progname);
1734  fputs (_("\
1735Switches:\n\
1736  -include <file>           Include the contents of <file> before other files\n\
1737  -imacros <file>           Accept definition of macros in <file>\n\
1738  -iprefix <path>           Specify <path> as a prefix for next two options\n\
1739  -iwithprefix <dir>        Add <dir> to the end of the system include path\n\
1740  -iwithprefixbefore <dir>  Add <dir> to the end of the main include path\n\
1741  -isystem <dir>            Add <dir> to the start of the system include path\n\
1742  -idirafter <dir>          Add <dir> to the end of the system include path\n\
1743  -I <dir>                  Add <dir> to the end of the main include path\n\
1744  -nostdinc                 Do not search system include directories\n\
1745                             (dirs specified with -isystem will still be used)\n\
1746  -nostdinc++               Do not search system include directories for C++\n\
1747  -o <file>                 Put output into <file>\n\
1748  -pedantic                 Issue all warnings demanded by strict ANSI C\n\
1749  -traditional              Follow K&R pre-processor behaviour\n\
1750  -trigraphs                Support ANSI C trigraphs\n\
1751  -lang-c                   Assume that the input sources are in C\n\
1752  -lang-c89                 Assume that the input sources are in C89\n\
1753  -lang-c++                 Assume that the input sources are in C++\n\
1754  -lang-objc                Assume that the input sources are in ObjectiveC\n\
1755  -lang-objc++              Assume that the input sources are in ObjectiveC++\n\
1756  -lang-asm                 Assume that the input sources are in assembler\n\
1757  -lang-chill               Assume that the input sources are in Chill\n\
1758  -std=<std name>           Specify the conformance standard; one of:\n\
1759                            gnu89, gnu9x, c89, c9x, iso9899:1990,\n\
1760                            iso9899:199409, iso9899:199x\n\
1761  -+                        Allow parsing of C++ style features\n\
1762  -w                        Inhibit warning messages\n\
1763  -Wtrigraphs               Warn if trigraphs are encountered\n\
1764  -Wno-trigraphs            Do not warn about trigraphs\n\
1765  -Wcomment{s}              Warn if one comment starts inside another\n\
1766  -Wno-comment{s}           Do not warn about comments\n\
1767  -Wtraditional             Warn if a macro argument is/would be turned into\n\
1768                             a string if -traditional is specified\n\
1769  -Wno-traditional          Do not warn about stringification\n\
1770  -Wundef                   Warn if an undefined macro is used by #if\n\
1771  -Wno-undef                Do not warn about testing undefined macros\n\
1772  -Wimport                  Warn about the use of the #import directive\n\
1773  -Wno-import               Do not warn about the use of #import\n\
1774  -Werror                   Treat all warnings as errors\n\
1775  -Wno-error                Do not treat warnings as errors\n\
1776  -Wall                     Enable all preprocessor warnings\n\
1777  -M                        Generate make dependencies\n\
1778  -MM                       As -M, but ignore system header files\n\
1779  -MD                       As -M, but put output in a .d file\n\
1780  -MMD                      As -MD, but ignore system header files\n\
1781  -MG                       Treat missing header file as generated files\n\
1782  -g                        Include #define and #undef directives in the output\n\
1783  -D<macro>                 Define a <macro> with string '1' as its value\n\
1784  -D<macro>=<val>           Define a <macro> with <val> as its value\n\
1785  -A<question> (<answer>)   Assert the <answer> to <question>\n\
1786  -U<macro>                 Undefine <macro> \n\
1787  -v                        Display the version number\n\
1788  -H                        Print the name of header files as they are used\n\
1789  -C                        Do not discard comments\n\
1790  -dM                       Display a list of macro definitions active at end\n\
1791  -dD                       Preserve macro definitions in output\n\
1792  -dN                       As -dD except that only the names are preserved\n\
1793  -dI                       Include #include directives in the output\n\
1794  -ifoutput                 Describe skipped code blocks in output \n\
1795  -P                        Do not generate #line directives\n\
1796  -$                        Do not allow '$' in identifiers\n\
1797  -remap                    Remap file names when including files.\n\
1798  -priority=<prio>          Specify thread-priority to use (1-10, default is 5)\n\
1799  -h or --help              Display this information\n\
1800"), stdout);
1801}
1802