OSDN Git Service

* jcf-parse.c (init_jcf_parse): Register current_file_list root.
[pf3gnuchains/gcc-fork.git] / gcc / cppfiles.c
1 /* Part of CPP library.  (include file handling)
2    Copyright (C) 1986, 1987, 1989, 1992, 1993, 1994, 1995, 1998,
3    1999, 2000 Free Software Foundation, Inc.
4    Written by Per Bothner, 1994.
5    Based on CCCP program by Paul Rubin, June 1986
6    Adapted to ANSI C, Richard Stallman, Jan 1987
7    Split out of cpplib.c, Zack Weinberg, Oct 1998
8
9 This program is free software; you can redistribute it and/or modify it
10 under the terms of the GNU General Public License as published by the
11 Free Software Foundation; either version 2, or (at your option) any
12 later version.
13
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 GNU General Public License for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with this program; if not, write to the Free Software
21 Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
22
23 #include "config.h"
24 #include "system.h"
25 #include "cpplib.h"
26 #include "cpphash.h"
27 #include "intl.h"
28 #include "mkdeps.h"
29 #include "splay-tree.h"
30
31 #ifdef HAVE_MMAP_FILE
32 # include <sys/mman.h>
33 # ifndef MMAP_THRESHOLD
34 #  define MMAP_THRESHOLD 3 /* Minimum page count to mmap the file.  */
35 # endif
36
37 #else  /* No MMAP_FILE */
38 #  undef MMAP_THRESHOLD
39 #  define MMAP_THRESHOLD 0
40 #endif
41
42 #ifndef O_BINARY
43 # define O_BINARY 0
44 #endif
45
46 #ifndef INCLUDE_LEN_FUDGE
47 # define INCLUDE_LEN_FUDGE 0
48 #endif
49
50 /* If errno is inspected immediately after a system call fails, it will be
51    nonzero, and no error number will ever be zero.  */
52 #ifndef ENOENT
53 # define ENOENT 0
54 #endif
55 #ifndef ENOTDIR
56 # define ENOTDIR 0
57 #endif
58 #ifndef ENOMEM
59 # define ENOMEM 0
60 #endif
61
62 /* Suppress warning about function macros used w/o arguments in traditional
63    C.  It is unlikely that glibc's strcmp macro helps this file at all.  */
64 #undef strcmp
65
66 static struct file_name_map *read_name_map
67                                 PARAMS ((cpp_reader *, const char *));
68 static char *read_filename_string PARAMS ((int, FILE *));
69 static char *remap_filename     PARAMS ((cpp_reader *, char *,
70                                          struct file_name_list *));
71 static struct file_name_list *actual_directory
72                                 PARAMS ((cpp_reader *, const char *));
73 static struct include_file *find_include_file
74                                 PARAMS ((cpp_reader *, const char *,
75                                          struct file_name_list *));
76 static struct include_file *open_file PARAMS ((cpp_reader *, const char *));
77 static int read_include_file    PARAMS ((cpp_reader *, struct include_file *));
78 static int stack_include_file   PARAMS ((cpp_reader *, struct include_file *));
79 static void purge_cache         PARAMS ((struct include_file *));
80 static void destroy_include_file_node   PARAMS ((splay_tree_value));
81 static int report_missing_guard         PARAMS ((splay_tree_node, void *));
82
83 #if 0
84 static void hack_vms_include_specification PARAMS ((char *));
85 #endif
86
87 /* We use a splay tree to store information about all the include
88    files seen in this compilation.  The key of each tree node is the
89    physical path to the file.  The value is 0 if the file does not
90    exist, or a struct include_file pointer.  */
91
92 static void
93 destroy_include_file_node (v)
94      splay_tree_value v;
95 {
96   struct include_file *f = (struct include_file *)v;
97   if (f)
98     {
99       purge_cache (f);
100       free (f);  /* The tree is registered with free to free f->name.  */
101     }
102 }
103
104 void
105 _cpp_init_includes (pfile)
106      cpp_reader *pfile;
107 {
108   pfile->all_include_files
109     = splay_tree_new ((splay_tree_compare_fn) strcmp,
110                       (splay_tree_delete_key_fn) free,
111                       destroy_include_file_node);
112 }
113
114 void
115 _cpp_cleanup_includes (pfile)
116      cpp_reader *pfile;
117 {
118   splay_tree_delete (pfile->all_include_files);
119 }
120
121 /* Given a file name, look it up in the cache; if there is no entry,
122    create one with a non-NULL value (regardless of success in opening
123    the file).  If the file doesn't exist or is inaccessible, this
124    entry is flagged so we don't attempt to open it again in the
125    future.  If the file isn't open, open it.
126
127    Returns an include_file structure with an open file descriptor on
128    success, or NULL on failure.  */
129
130 static struct include_file *
131 open_file (pfile, filename)
132      cpp_reader *pfile;
133      const char *filename;
134 {
135   splay_tree_node nd;
136   struct include_file *file;
137
138   nd = splay_tree_lookup (pfile->all_include_files, (splay_tree_key) filename);
139
140   if (nd)
141     {
142       file = (struct include_file *) nd->value;
143
144       /* Don't retry opening if we failed previously.  */
145       if (file->fd == -2)
146         return 0;
147
148       /* Don't reopen an idempotent file. */
149       if (DO_NOT_REREAD (file))
150         return file;
151       
152       /* Don't reopen one which is already loaded. */
153       if (file->buffer != NULL)
154         return file;
155     }
156   else
157     {
158       file = xcnew (struct include_file);
159       file->name = xstrdup (filename);
160       splay_tree_insert (pfile->all_include_files,
161                          (splay_tree_key) file->name,
162                          (splay_tree_value) file);
163     }
164
165   /* We used to open files in nonblocking mode, but that caused more
166      problems than it solved.  Do take care not to acquire a
167      controlling terminal by mistake (this can't happen on sane
168      systems, but paranoia is a virtue).
169
170      Use the three-argument form of open even though we aren't
171      specifying O_CREAT, to defend against broken system headers.
172
173      O_BINARY tells some runtime libraries (notably DJGPP) not to do
174      newline translation; we can handle DOS line breaks just fine
175      ourselves.
176
177      Special case: the empty string is translated to stdin.  */
178
179   if (filename[0] == '\0')
180     file->fd = 0;
181   else
182     file->fd = open (filename, O_RDONLY | O_NOCTTY | O_BINARY, 0666);
183
184   if (file->fd != -1 && fstat (file->fd, &file->st) == 0)
185     {
186       /* Mark a regular, zero-length file never-reread now.  */
187       if (S_ISREG (file->st.st_mode) && file->st.st_size == 0)
188         {
189           file->cmacro = NEVER_REREAD;
190           close (file->fd);
191           file->fd = -1;
192         }
193
194       return file;
195     }
196
197   /* Don't issue an error message if the file doesn't exist.  */
198   if (errno != ENOENT && errno != ENOTDIR)
199     cpp_error_from_errno (pfile, filename);
200
201   /* Create a negative node for this path, and return null.  */
202   file->fd = -2;
203
204   return 0;
205 }
206
207 /* Place the file referenced by INC into a new buffer on PFILE's stack.
208    Return 1 if successful, 0 if not.  */
209
210 static int
211 stack_include_file (pfile, inc)
212      cpp_reader *pfile;
213      struct include_file *inc;
214 {
215   cpp_buffer *fp;
216
217   if (pfile->context->prev)
218     cpp_ice (pfile, "attempt to push file buffer with contexts stacked");
219
220   if (DO_NOT_REREAD (inc))
221     return 0;
222
223   if (inc->buffer == NULL)
224     if (read_include_file (pfile, inc) == 0)
225       return 0;
226
227   fp = cpp_push_buffer (pfile, NULL, 0);
228   if (fp == 0)
229     return 0;
230
231   /* Initialise controlling macro state.  */
232   pfile->mi_state = MI_OUTSIDE;
233   pfile->mi_cmacro = 0;
234
235   fp->inc = inc;
236   fp->nominal_fname = inc->name;
237   fp->buf = inc->buffer;
238   fp->rlimit = fp->buf + inc->st.st_size;
239   fp->cur = fp->buf;
240   fp->lineno = 1;
241   fp->line_base = fp->buf;
242
243   /* The ->actual_dir field is only used when ignore_srcdir is not in effect;
244      see do_include */
245   if (!CPP_OPTION (pfile, ignore_srcdir))
246     fp->actual_dir = actual_directory (pfile, inc->name);
247
248   fp->inc->refcnt++;
249   pfile->include_depth++;
250   pfile->input_stack_listing_current = 0;
251
252   if (pfile->cb.enter_file)
253     (*pfile->cb.enter_file) (pfile);
254
255   return 1;
256 }
257
258 /* Read the file referenced by INC into the file cache.
259
260    If fd points to a plain file, we might be able to mmap it; we can
261    definitely allocate the buffer all at once.  If fd is a pipe or
262    terminal, we can't do either.  If fd is something weird, like a
263    block device or a directory, we don't want to read it at all.
264
265    Unfortunately, different systems use different st.st_mode values
266    for pipes: some have S_ISFIFO, some S_ISSOCK, some are buggy and
267    zero the entire struct stat except a couple fields.  Hence we don't
268    even try to figure out what something is, except for plain files,
269    directories, and block devices.
270
271    FIXME: Flush file cache and try again if we run out of memory.  */
272
273 static int
274 read_include_file (pfile, inc)
275      cpp_reader *pfile;
276      struct include_file *inc;
277 {
278   ssize_t size, offset, count;
279   U_CHAR *buf;
280 #if MMAP_THRESHOLD
281   static int pagesize = -1;
282 #endif
283
284   if (S_ISREG (inc->st.st_mode))
285     {
286       /* off_t might have a wider range than ssize_t - in other words,
287          the max size of a file might be bigger than the address
288          space.  We can't handle a file that large.  (Anyone with
289          a single source file bigger than 2GB needs to rethink
290          their coding style.)  Some systems (e.g. AIX 4.1) define
291          SSIZE_MAX to be much smaller than the actual range of the
292          type.  Use INTTYPE_MAXIMUM unconditionally to ensure this
293          does not bite us.  */
294       if (inc->st.st_size > INTTYPE_MAXIMUM (ssize_t))
295         {
296           cpp_error (pfile, "%s is too large", inc->name);
297           goto fail;
298         }
299       size = inc->st.st_size;
300
301       inc->mapped = 0;
302 #if MMAP_THRESHOLD
303       if (pagesize == -1)
304         pagesize = getpagesize ();
305
306       if (size / pagesize >= MMAP_THRESHOLD)
307         {
308           buf = (U_CHAR *) mmap (0, size, PROT_READ, MAP_PRIVATE, inc->fd, 0);
309           if (buf == (U_CHAR *)-1)
310             goto perror_fail;
311           inc->mapped = 1;
312         }
313       else
314 #endif
315         {
316           buf = (U_CHAR *) xmalloc (size);
317           offset = 0;
318           while (offset < size)
319             {
320               count = read (inc->fd, buf + offset, size - offset);
321               if (count < 0)
322                 goto perror_fail;
323               if (count == 0)
324                 {
325                   cpp_warning (pfile, "%s is shorter than expected", inc->name);
326                   break;
327                 }
328               offset += count;
329             }
330         }
331     }
332   else if (S_ISBLK (inc->st.st_mode))
333     {
334       cpp_error (pfile, "%s is a block device", inc->name);
335       goto fail;
336     }
337   else if (S_ISDIR (inc->st.st_mode))
338     {
339       cpp_error (pfile, "%s is a directory", inc->name);
340       goto fail;
341     }
342   else
343     {
344       /* 8 kilobytes is a sensible starting size.  It ought to be
345          bigger than the kernel pipe buffer, and it's definitely
346          bigger than the majority of C source files.  */
347       size = 8 * 1024;
348
349       buf = (U_CHAR *) xmalloc (size);
350       offset = 0;
351       while ((count = read (inc->fd, buf + offset, size - offset)) > 0)
352         {
353           offset += count;
354           if (offset == size)
355             buf = xrealloc (buf, (size *= 2));
356         }
357       if (count < 0)
358         goto perror_fail;
359
360       if (offset < size)
361         buf = xrealloc (buf, offset);
362       inc->st.st_size = offset;
363     }
364
365   close (inc->fd);
366   inc->buffer = buf;
367   inc->fd = -1;
368   return 1;
369
370  perror_fail:
371   cpp_error_from_errno (pfile, inc->name);
372  fail:
373   /* Do not try to read this file again.  */
374   close (inc->fd);
375   inc->fd = -1;
376   inc->cmacro = NEVER_REREAD;
377   return 0;
378 }
379
380 static void
381 purge_cache (inc)
382      struct include_file *inc;
383 {
384   if (inc->buffer)
385     {
386 #if MMAP_THRESHOLD
387       if (inc->mapped)
388         munmap ((PTR) inc->buffer, inc->st.st_size);
389       else
390 #endif
391         free ((PTR) inc->buffer);
392       inc->buffer = NULL;
393     }
394 }
395
396 /* Return 1 if the file named by FNAME has been included before in
397    any context, 0 otherwise.  */
398 int
399 cpp_included (pfile, fname)
400      cpp_reader *pfile;
401      const char *fname;
402 {
403   struct file_name_list *path;
404   char *name;
405   splay_tree_node nd;
406
407   if (fname[0] == '/')
408     {
409       /* Just look it up.  */
410       nd = splay_tree_lookup (pfile->all_include_files, (splay_tree_key) fname);
411       return (nd && nd->value);
412     }
413       
414   /* Search directory path for the file.  */
415   name = (char *) alloca (strlen (fname) + pfile->max_include_len
416                           + 2 + INCLUDE_LEN_FUDGE);
417   for (path = CPP_OPTION (pfile, quote_include); path; path = path->next)
418     {
419       memcpy (name, path->name, path->nlen);
420       name[path->nlen] = '/';
421       strcpy (&name[path->nlen+1], fname);
422       _cpp_simplify_pathname (name);
423       if (CPP_OPTION (pfile, remap))
424         name = remap_filename (pfile, name, path);
425
426       nd = splay_tree_lookup (pfile->all_include_files, (splay_tree_key) name);
427       if (nd && nd->value)
428         return 1;
429     }
430   return 0;
431 }
432
433 /* Search for include file FNAME in the include chain starting at
434    SEARCH_START.  Return 0 if there is no such file (or it's un-openable),
435    otherwise an include_file structure.  */
436
437 static struct include_file *
438 find_include_file (pfile, fname, search_start)
439      cpp_reader *pfile;
440      const char *fname;
441      struct file_name_list *search_start;
442 {
443   struct file_name_list *path;
444   char *name;
445   struct include_file *file;
446
447   if (fname[0] == '/')
448     return open_file (pfile, fname);
449       
450   /* Search directory path for the file.  */
451   name = (char *) alloca (strlen (fname) + pfile->max_include_len
452                           + 2 + INCLUDE_LEN_FUDGE);
453   for (path = search_start; path; path = path->next)
454     {
455       memcpy (name, path->name, path->nlen);
456       name[path->nlen] = '/';
457       strcpy (&name[path->nlen+1], fname);
458       _cpp_simplify_pathname (name);
459       if (CPP_OPTION (pfile, remap))
460         name = remap_filename (pfile, name, path);
461
462       file = open_file (pfile, name);
463       if (file)
464         {
465           file->sysp = path->sysp;
466           file->foundhere = path;
467           return file;
468         }
469     }
470   return 0;
471 }
472
473 /* #line uses this to save artificial file names.  We have to stat the
474    file because an all_include_files entry is always either + or -,
475    there's no 'I don't know' value.  */
476 const char *
477 _cpp_fake_include (pfile, fname)
478      cpp_reader *pfile;
479      const char *fname;
480 {
481   splay_tree_node nd;
482   struct include_file *file;
483   char *name;
484
485   file = find_include_file (pfile, fname, CPP_OPTION (pfile, quote_include));
486   if (file)
487     {
488       if (file->fd > 0)
489         {
490           close (file->fd);
491           file->fd = -1;
492         }
493       return file->name;
494     }
495
496   name = xstrdup (fname);
497   _cpp_simplify_pathname (name);
498
499   /* We cannot just blindly insert a node, because there's still the
500      chance that the node already exists but isn't on the search path.  */
501   nd = splay_tree_lookup (pfile->all_include_files, (splay_tree_key) name);
502   if (nd)
503     {
504       free (name);
505       return (const char *) nd->key;
506     }
507
508   file = xcnew (struct include_file);
509   file->name = name;
510   file->fd = -2;
511   splay_tree_insert (pfile->all_include_files, (splay_tree_key) name,
512                      (splay_tree_value) file);
513
514   return file->name;
515 }
516
517 /* Not everyone who wants to set system-header-ness on a buffer can
518    see the details of struct include_file.  This is an exported interface
519    because fix-header needs it.  */
520 void
521 cpp_make_system_header (pfile, pbuf, flag)
522      cpp_reader *pfile;
523      cpp_buffer *pbuf;
524      int flag;
525 {
526   if (flag < 0 || flag > 2)
527     cpp_ice (pfile, "cpp_make_system_header: bad flag %d\n", flag);
528   else if (!pbuf->inc)
529     cpp_ice (pfile, "cpp_make_system_header called on non-file buffer");
530   else
531     pbuf->inc->sysp = flag;
532 }
533
534 const char *
535 cpp_syshdr_flags (pfile, pbuf)
536      cpp_reader *pfile ATTRIBUTE_UNUSED;
537      cpp_buffer *pbuf;
538 {
539 #ifndef NO_IMPLICIT_EXTERN_C
540   if (CPP_OPTION (pfile, cplusplus) && pbuf->inc->sysp == 2)
541     return " 3 4";
542 #endif
543   if (pbuf->inc->sysp)
544     return " 3";
545   return "";
546 }
547
548 /* Report on all files that might benefit from a multiple include guard.
549    Triggered by -H.  */
550 void
551 _cpp_report_missing_guards (pfile)
552      cpp_reader *pfile;
553 {
554   int banner = 0;
555   splay_tree_foreach (pfile->all_include_files, report_missing_guard,
556                       (PTR) &banner);
557 }
558
559 static int
560 report_missing_guard (n, b)
561      splay_tree_node n;
562      void *b;
563 {
564   struct include_file *f = (struct include_file *) n->value;
565   int *bannerp = (int *)b;
566
567   if (f && f->cmacro == 0 && f->include_count == 1)
568     {
569       if (*bannerp == 0)
570         {
571           fputs (_("Multiple include guards may be useful for:\n"), stderr);
572           *bannerp = 1;
573         }
574       fputs (f->name, stderr);
575       putc ('\n', stderr);
576     }
577   return 0;
578 }
579
580 #define PRINT_THIS_DEP(p, b) (CPP_PRINT_DEPS(p) > (b||p->system_include_depth))
581 void
582 _cpp_execute_include (pfile, header, no_reinclude, search_start)
583      cpp_reader *pfile;
584      const cpp_token *header;
585      int no_reinclude;
586      struct file_name_list *search_start;
587 {
588   unsigned int len = header->val.str.len;
589   unsigned int angle_brackets = header->type == CPP_HEADER_NAME;
590   struct include_file *inc;
591   char *fname;
592
593   fname = alloca (len + 1);
594   memcpy (fname, header->val.str.text, len);
595   fname[len] = '\0';
596
597   if (!search_start)
598     {
599       if (angle_brackets)
600         search_start = CPP_OPTION (pfile, bracket_include);
601       else if (CPP_OPTION (pfile, ignore_srcdir))
602         search_start = CPP_OPTION (pfile, quote_include);
603       else
604         search_start = CPP_BUFFER (pfile)->actual_dir;
605
606       if (!search_start)
607         {
608           cpp_error (pfile, "No include path in which to find %s", fname);
609           return;
610         }
611     }
612
613   inc = find_include_file (pfile, fname, search_start);
614
615   if (inc)
616     {
617       /* For -M, add the file to the dependencies on its first inclusion. */
618       if (!inc->include_count && PRINT_THIS_DEP (pfile, angle_brackets))
619         deps_add_dep (pfile->deps, inc->name);
620       inc->include_count++;
621
622       /* Actually process the file.  */
623       if (stack_include_file (pfile, inc))
624         {
625           if (angle_brackets)
626             pfile->system_include_depth++;
627
628           if (no_reinclude)
629             inc->cmacro = NEVER_REREAD;
630
631           /* Handle -H option.  */
632           if (CPP_OPTION (pfile, print_include_names))
633             {
634               cpp_buffer *fp = CPP_BUFFER (pfile);
635               while ((fp = CPP_PREV_BUFFER (fp)) != NULL)
636                 putc ('.', stderr);
637               fprintf (stderr, " %s\n", inc->name);
638             }
639         }
640       return;
641     }
642       
643   if (CPP_OPTION (pfile, print_deps_missing_files)
644       && PRINT_THIS_DEP (pfile, angle_brackets))
645     {
646       if (!angle_brackets)
647         deps_add_dep (pfile->deps, fname);
648       else
649         {
650           char *p;
651           struct file_name_list *ptr;
652           /* If requested as a system header, assume it belongs in
653              the first system header directory. */
654           if (CPP_OPTION (pfile, bracket_include))
655             ptr = CPP_OPTION (pfile, bracket_include);
656           else
657             ptr = CPP_OPTION (pfile, quote_include);
658
659           p = (char *) alloca (strlen (ptr->name)
660                                + strlen (fname) + 2);
661           if (*ptr->name != '\0')
662             {
663               strcpy (p, ptr->name);
664               strcat (p, "/");
665             }
666           strcat (p, fname);
667           _cpp_simplify_pathname (p);
668           deps_add_dep (pfile->deps, p);
669         }
670     }
671   /* If -M was specified, and this header file won't be added to
672      the dependency list, then don't count this as an error,
673      because we can still produce correct output.  Otherwise, we
674      can't produce correct output, because there may be
675      dependencies we need inside the missing file, and we don't
676      know what directory this missing file exists in. */
677   else if (CPP_PRINT_DEPS (pfile)
678            && ! PRINT_THIS_DEP (pfile, angle_brackets))
679     cpp_warning (pfile, "No include path in which to find %s", fname);
680   else
681     cpp_error_from_errno (pfile, fname);
682 }
683
684 /* Locate file F, and determine whether it is newer than PFILE. Return -1,
685    if F cannot be located or dated, 1, if it is newer and 0 if older.  */
686 int
687 _cpp_compare_file_date (pfile, f)
688      cpp_reader *pfile;
689      const cpp_token *f;
690 {
691   unsigned int len = f->val.str.len;
692   char *fname;
693   struct file_name_list *search_start;
694   struct include_file *inc;
695
696   if (f->type == CPP_HEADER_NAME)
697     search_start = CPP_OPTION (pfile, bracket_include);
698   else if (CPP_OPTION (pfile, ignore_srcdir))
699     search_start = CPP_OPTION (pfile, quote_include);
700   else
701     search_start = CPP_BUFFER (pfile)->actual_dir;
702
703   fname = alloca (len + 1);
704   memcpy (fname, f->val.str.text, len);
705   fname[len] = '\0';
706   inc = find_include_file (pfile, fname, search_start);
707   
708   if (!inc)
709     return -1;
710   if (inc->fd > 0)
711     {
712       close (inc->fd);
713       inc->fd = -1;
714     }
715     
716   return inc->st.st_mtime > CPP_BUFFER (pfile)->inc->st.st_mtime;
717 }
718
719
720 /* Push an input buffer and load it up with the contents of FNAME.
721    If FNAME is "" or NULL, read standard input.  */
722 int
723 cpp_read_file (pfile, fname)
724      cpp_reader *pfile;
725      const char *fname;
726 {
727   struct include_file *f;
728
729   if (fname == NULL)
730     fname = "";
731
732   f = open_file (pfile, fname);
733
734   if (f == NULL)
735     {
736       cpp_error_from_errno (pfile, fname);
737       return 0;
738     }
739
740   /* Return success for zero-length files.  */
741   if (DO_NOT_REREAD (f))
742     return 1;
743
744   return stack_include_file (pfile, f);
745 }
746
747 /* Do appropriate cleanup when a file buffer is popped off the input
748    stack.  */
749 void
750 _cpp_pop_file_buffer (pfile, buf)
751      cpp_reader *pfile;
752      cpp_buffer *buf;
753 {
754   struct include_file *inc = buf->inc;
755
756   if (pfile->system_include_depth)
757     pfile->system_include_depth--;
758   if (pfile->include_depth)
759     pfile->include_depth--;
760   pfile->input_stack_listing_current = 0;
761
762   /* Record the inclusion-preventing macro and its definedness.  */
763   if (pfile->mi_state == MI_OUTSIDE && inc->cmacro != NEVER_REREAD)
764     {
765       /* This could be NULL meaning no controlling macro.  */
766       inc->cmacro = pfile->mi_cmacro;
767       inc->defined = 1;
768     }
769
770   /* Invalidate control macros in the #including file.  */
771   pfile->mi_state = MI_FAILED;
772
773   inc->refcnt--;
774   if (inc->refcnt == 0 && DO_NOT_REREAD (inc))
775     purge_cache (inc);
776 }
777
778 /* The file_name_map structure holds a mapping of file names for a
779    particular directory.  This mapping is read from the file named
780    FILE_NAME_MAP_FILE in that directory.  Such a file can be used to
781    map filenames on a file system with severe filename restrictions,
782    such as DOS.  The format of the file name map file is just a series
783    of lines with two tokens on each line.  The first token is the name
784    to map, and the second token is the actual name to use.  */
785
786 struct file_name_map
787 {
788   struct file_name_map *map_next;
789   char *map_from;
790   char *map_to;
791 };
792
793 #define FILE_NAME_MAP_FILE "header.gcc"
794
795 /* Read a space delimited string of unlimited length from a stdio
796    file.  */
797
798 static char *
799 read_filename_string (ch, f)
800      int ch;
801      FILE *f;
802 {
803   char *alloc, *set;
804   int len;
805
806   len = 20;
807   set = alloc = xmalloc (len + 1);
808   if (! is_space(ch))
809     {
810       *set++ = ch;
811       while ((ch = getc (f)) != EOF && ! is_space(ch))
812         {
813           if (set - alloc == len)
814             {
815               len *= 2;
816               alloc = xrealloc (alloc, len + 1);
817               set = alloc + len / 2;
818             }
819           *set++ = ch;
820         }
821     }
822   *set = '\0';
823   ungetc (ch, f);
824   return alloc;
825 }
826
827 /* This structure holds a linked list of file name maps, one per directory.  */
828
829 struct file_name_map_list
830 {
831   struct file_name_map_list *map_list_next;
832   char *map_list_name;
833   struct file_name_map *map_list_map;
834 };
835
836 /* Read the file name map file for DIRNAME.  */
837
838 static struct file_name_map *
839 read_name_map (pfile, dirname)
840      cpp_reader *pfile;
841      const char *dirname;
842 {
843   register struct file_name_map_list *map_list_ptr;
844   char *name;
845   FILE *f;
846
847   for (map_list_ptr = CPP_OPTION (pfile, map_list); map_list_ptr;
848        map_list_ptr = map_list_ptr->map_list_next)
849     if (! strcmp (map_list_ptr->map_list_name, dirname))
850       return map_list_ptr->map_list_map;
851
852   map_list_ptr = ((struct file_name_map_list *)
853                   xmalloc (sizeof (struct file_name_map_list)));
854   map_list_ptr->map_list_name = xstrdup (dirname);
855   map_list_ptr->map_list_map = NULL;
856
857   name = (char *) alloca (strlen (dirname) + strlen (FILE_NAME_MAP_FILE) + 2);
858   strcpy (name, dirname);
859   if (*dirname)
860     strcat (name, "/");
861   strcat (name, FILE_NAME_MAP_FILE);
862   f = fopen (name, "r");
863   if (!f)
864     map_list_ptr->map_list_map = (struct file_name_map *)-1;
865   else
866     {
867       int ch;
868       int dirlen = strlen (dirname);
869
870       while ((ch = getc (f)) != EOF)
871         {
872           char *from, *to;
873           struct file_name_map *ptr;
874
875           if (is_space(ch))
876             continue;
877           from = read_filename_string (ch, f);
878           while ((ch = getc (f)) != EOF && is_hspace(ch))
879             ;
880           to = read_filename_string (ch, f);
881
882           ptr = ((struct file_name_map *)
883                  xmalloc (sizeof (struct file_name_map)));
884           ptr->map_from = from;
885
886           /* Make the real filename absolute.  */
887           if (*to == '/')
888             ptr->map_to = to;
889           else
890             {
891               ptr->map_to = xmalloc (dirlen + strlen (to) + 2);
892               strcpy (ptr->map_to, dirname);
893               ptr->map_to[dirlen] = '/';
894               strcpy (ptr->map_to + dirlen + 1, to);
895               free (to);
896             }         
897
898           ptr->map_next = map_list_ptr->map_list_map;
899           map_list_ptr->map_list_map = ptr;
900
901           while ((ch = getc (f)) != '\n')
902             if (ch == EOF)
903               break;
904         }
905       fclose (f);
906     }
907   
908   map_list_ptr->map_list_next = CPP_OPTION (pfile, map_list);
909   CPP_OPTION (pfile, map_list) = map_list_ptr;
910
911   return map_list_ptr->map_list_map;
912 }  
913
914 /* Remap NAME based on the file_name_map (if any) for LOC. */
915
916 static char *
917 remap_filename (pfile, name, loc)
918      cpp_reader *pfile;
919      char *name;
920      struct file_name_list *loc;
921 {
922   struct file_name_map *map;
923   const char *from, *p, *dir;
924
925   if (! loc->name_map)
926     loc->name_map = read_name_map (pfile,
927                                    loc->name
928                                    ? loc->name : ".");
929
930   if (loc->name_map == (struct file_name_map *)-1)
931     return name;
932   
933   from = name + strlen (loc->name) + 1;
934   
935   for (map = loc->name_map; map; map = map->map_next)
936     if (!strcmp (map->map_from, from))
937       return map->map_to;
938
939   /* Try to find a mapping file for the particular directory we are
940      looking in.  Thus #include <sys/types.h> will look up sys/types.h
941      in /usr/include/header.gcc and look up types.h in
942      /usr/include/sys/header.gcc.  */
943   p = strrchr (name, '/');
944   if (!p)
945     p = name;
946   if (loc && loc->name
947       && strlen (loc->name) == (size_t) (p - name)
948       && !strncmp (loc->name, name, p - name))
949     /* FILENAME is in SEARCHPTR, which we've already checked.  */
950     return name;
951
952   if (p == name)
953     {
954       dir = ".";
955       from = name;
956     }
957   else
958     {
959       char * newdir = (char *) alloca (p - name + 1);
960       memcpy (newdir, name, p - name);
961       newdir[p - name] = '\0';
962       dir = newdir;
963       from = p + 1;
964     }
965   
966   for (map = read_name_map (pfile, dir); map; map = map->map_next)
967     if (! strcmp (map->map_from, name))
968       return map->map_to;
969
970   return name;
971 }
972
973 /* Given a path FNAME, extract the directory component and place it
974    onto the actual_dirs list.  Return a pointer to the allocated
975    file_name_list structure.  These structures are used to implement
976    current-directory "" include searching. */
977
978 static struct file_name_list *
979 actual_directory (pfile, fname)
980      cpp_reader *pfile;
981      const char *fname;
982 {
983   char *last_slash, *dir;
984   size_t dlen;
985   struct file_name_list *x;
986   
987   dir = xstrdup (fname);
988   last_slash = strrchr (dir, '/');
989   if (last_slash)
990     {
991       if (last_slash == dir)
992         {
993           dlen = 1;
994           last_slash[1] = '\0';
995         }
996       else
997         {
998           dlen = last_slash - dir;
999           *last_slash = '\0';
1000         }
1001     }
1002   else
1003     {
1004       free (dir);
1005       dir = xstrdup (".");
1006       dlen = 1;
1007     }
1008
1009   if (dlen > pfile->max_include_len)
1010     pfile->max_include_len = dlen;
1011
1012   for (x = pfile->actual_dirs; x; x = x->alloc)
1013     if (!strcmp (x->name, dir))
1014       {
1015         free (dir);
1016         return x;
1017       }
1018
1019   /* Not found, make a new one. */
1020   x = (struct file_name_list *) xmalloc (sizeof (struct file_name_list));
1021   x->name = dir;
1022   x->nlen = dlen;
1023   x->next = CPP_OPTION (pfile, quote_include);
1024   x->alloc = pfile->actual_dirs;
1025   x->sysp = CPP_BUFFER (pfile)->inc->sysp;
1026   x->name_map = NULL;
1027
1028   pfile->actual_dirs = x;
1029   return x;
1030 }
1031
1032 /* Simplify a path name in place, deleting redundant components.  This
1033    reduces OS overhead and guarantees that equivalent paths compare
1034    the same (modulo symlinks).
1035
1036    Transforms made:
1037    foo/bar/../quux      foo/quux
1038    foo/./bar            foo/bar
1039    foo//bar             foo/bar
1040    /../quux             /quux
1041    //quux               //quux  (POSIX allows leading // as a namespace escape)
1042
1043    Guarantees no trailing slashes. All transforms reduce the length
1044    of the string.
1045  */
1046 void
1047 _cpp_simplify_pathname (path)
1048     char *path;
1049 {
1050     char *from, *to;
1051     char *base;
1052     int absolute = 0;
1053
1054 #if defined (HAVE_DOS_BASED_FILE_SYSTEM)
1055     /* Convert all backslashes to slashes. */
1056     for (from = path; *from; from++)
1057         if (*from == '\\') *from = '/';
1058     
1059     /* Skip over leading drive letter if present. */
1060     if (ISALPHA (path[0]) && path[1] == ':')
1061         from = to = &path[2];
1062     else
1063         from = to = path;
1064 #else
1065     from = to = path;
1066 #endif
1067     
1068     /* Remove redundant initial /s.  */
1069     if (*from == '/')
1070     {
1071         absolute = 1;
1072         to++;
1073         from++;
1074         if (*from == '/')
1075         {
1076             if (*++from == '/')
1077                 /* 3 or more initial /s are equivalent to 1 /.  */
1078                 while (*++from == '/');
1079             else
1080                 /* On some hosts // differs from /; Posix allows this.  */
1081                 to++;
1082         }
1083     }
1084     base = to;
1085     
1086     for (;;)
1087     {
1088         while (*from == '/')
1089             from++;
1090
1091         if (from[0] == '.' && from[1] == '/')
1092             from += 2;
1093         else if (from[0] == '.' && from[1] == '\0')
1094             goto done;
1095         else if (from[0] == '.' && from[1] == '.' && from[2] == '/')
1096         {
1097             if (base == to)
1098             {
1099                 if (absolute)
1100                     from += 3;
1101                 else
1102                 {
1103                     *to++ = *from++;
1104                     *to++ = *from++;
1105                     *to++ = *from++;
1106                     base = to;
1107                 }
1108             }
1109             else
1110             {
1111                 to -= 2;
1112                 while (to > base && *to != '/') to--;
1113                 if (*to == '/')
1114                     to++;
1115                 from += 3;
1116             }
1117         }
1118         else if (from[0] == '.' && from[1] == '.' && from[2] == '\0')
1119         {
1120             if (base == to)
1121             {
1122                 if (!absolute)
1123                 {
1124                     *to++ = *from++;
1125                     *to++ = *from++;
1126                 }
1127             }
1128             else
1129             {
1130                 to -= 2;
1131                 while (to > base && *to != '/') to--;
1132                 if (*to == '/')
1133                     to++;
1134             }
1135             goto done;
1136         }
1137         else
1138             /* Copy this component and trailing /, if any.  */
1139             while ((*to++ = *from++) != '/')
1140             {
1141                 if (!to[-1])
1142                 {
1143                     to--;
1144                     goto done;
1145                 }
1146             }
1147         
1148     }
1149     
1150  done:
1151     /* Trim trailing slash */
1152     if (to[0] == '/' && (!absolute || to > path+1))
1153         to--;
1154
1155     /* Change the empty string to "." so that stat() on the result
1156        will always work. */
1157     if (to == path)
1158       *to++ = '.';
1159     
1160     *to = '\0';
1161
1162     return;
1163 }
1164
1165 /* It is not clear when this should be used if at all, so I've
1166    disabled it until someone who understands VMS can look at it. */
1167 #if 0
1168
1169 /* Under VMS we need to fix up the "include" specification filename.
1170
1171    Rules for possible conversions
1172
1173         fullname                tried paths
1174
1175         name                    name
1176         ./dir/name              [.dir]name
1177         /dir/name               dir:name
1178         /name                   [000000]name, name
1179         dir/name                dir:[000000]name, dir:name, dir/name
1180         dir1/dir2/name          dir1:[dir2]name, dir1:[000000.dir2]name
1181         path:/name              path:[000000]name, path:name
1182         path:/dir/name          path:[000000.dir]name, path:[dir]name
1183         path:dir/name           path:[dir]name
1184         [path]:[dir]name        [path.dir]name
1185         path/[dir]name          [path.dir]name
1186
1187    The path:/name input is constructed when expanding <> includes. */
1188
1189
1190 static void
1191 hack_vms_include_specification (fullname)
1192      char *fullname;
1193 {
1194   register char *basename, *unixname, *local_ptr, *first_slash;
1195   int f, check_filename_before_returning, must_revert;
1196   char Local[512];
1197
1198   check_filename_before_returning = 0;
1199   must_revert = 0;
1200   /* See if we can find a 1st slash. If not, there's no path information.  */
1201   first_slash = strchr (fullname, '/');
1202   if (first_slash == 0)
1203     return 0;                           /* Nothing to do!!! */
1204
1205   /* construct device spec if none given.  */
1206
1207   if (strchr (fullname, ':') == 0)
1208     {
1209
1210       /* If fullname has a slash, take it as device spec.  */
1211
1212       if (first_slash == fullname)
1213         {
1214           first_slash = strchr (fullname + 1, '/');     /* 2nd slash ? */
1215           if (first_slash)
1216             *first_slash = ':';                         /* make device spec  */
1217           for (basename = fullname; *basename != 0; basename++)
1218             *basename = *(basename+1);                  /* remove leading slash  */
1219         }
1220       else if ((first_slash[-1] != '.')         /* keep ':/', './' */
1221             && (first_slash[-1] != ':')
1222             && (first_slash[-1] != ']'))        /* or a vms path  */
1223         {
1224           *first_slash = ':';
1225         }
1226       else if ((first_slash[1] == '[')          /* skip './' in './[dir'  */
1227             && (first_slash[-1] == '.'))
1228         fullname += 2;
1229     }
1230
1231   /* Get part after first ':' (basename[-1] == ':')
1232      or last '/' (basename[-1] == '/').  */
1233
1234   basename = base_name (fullname);
1235
1236   local_ptr = Local;                    /* initialize */
1237
1238   /* We are trying to do a number of things here.  First of all, we are
1239      trying to hammer the filenames into a standard format, such that later
1240      processing can handle them.
1241      
1242      If the file name contains something like [dir.], then it recognizes this
1243      as a root, and strips the ".]".  Later processing will add whatever is
1244      needed to get things working properly.
1245      
1246      If no device is specified, then the first directory name is taken to be
1247      a device name (or a rooted logical).  */
1248
1249   /* Point to the UNIX filename part (which needs to be fixed!)
1250      but skip vms path information.
1251      [basename != fullname since first_slash != 0].  */
1252
1253   if ((basename[-1] == ':')             /* vms path spec.  */
1254       || (basename[-1] == ']')
1255       || (basename[-1] == '>'))
1256     unixname = basename;
1257   else
1258     unixname = fullname;
1259
1260   if (*unixname == '/')
1261     unixname++;
1262
1263   /* If the directory spec is not rooted, we can just copy
1264      the UNIX filename part and we are done.  */
1265
1266   if (((basename - fullname) > 1)
1267      && (  (basename[-1] == ']')
1268         || (basename[-1] == '>')))
1269     {
1270       if (basename[-2] != '.')
1271         {
1272
1273         /* The VMS part ends in a `]', and the preceding character is not a `.'.
1274            -> PATH]:/name (basename = '/name', unixname = 'name')
1275            We strip the `]', and then splice the two parts of the name in the
1276            usual way.  Given the default locations for include files,
1277            we will only use this code if the user specifies alternate locations
1278            with the /include (-I) switch on the command line.  */
1279
1280           basename -= 1;        /* Strip "]" */
1281           unixname--;           /* backspace */
1282         }
1283       else
1284         {
1285
1286         /* The VMS part has a ".]" at the end, and this will not do.  Later
1287            processing will add a second directory spec, and this would be a syntax
1288            error.  Thus we strip the ".]", and thus merge the directory specs.
1289            We also backspace unixname, so that it points to a '/'.  This inhibits the
1290            generation of the 000000 root directory spec (which does not belong here
1291            in this case).  */
1292
1293           basename -= 2;        /* Strip ".]" */
1294           unixname--;           /* backspace */
1295         }
1296     }
1297
1298   else
1299
1300     {
1301
1302       /* We drop in here if there is no VMS style directory specification yet.
1303          If there is no device specification either, we make the first dir a
1304          device and try that.  If we do not do this, then we will be essentially
1305          searching the users default directory (as if they did a #include "asdf.h").
1306         
1307          Then all we need to do is to push a '[' into the output string. Later
1308          processing will fill this in, and close the bracket.  */
1309
1310       if ((unixname != fullname)        /* vms path spec found.  */
1311          && (basename[-1] != ':'))
1312         *local_ptr++ = ':';             /* dev not in spec.  take first dir */
1313
1314       *local_ptr++ = '[';               /* Open the directory specification */
1315     }
1316
1317     if (unixname == fullname)           /* no vms dir spec.  */
1318       {
1319         must_revert = 1;
1320         if ((first_slash != 0)          /* unix dir spec.  */
1321             && (*unixname != '/')       /* not beginning with '/'  */
1322             && (*unixname != '.'))      /* or './' or '../'  */
1323           *local_ptr++ = '.';           /* dir is local !  */
1324       }
1325
1326   /* at this point we assume that we have the device spec, and (at least
1327      the opening "[" for a directory specification.  We may have directories
1328      specified already.
1329
1330      If there are no other slashes then the filename will be
1331      in the "root" directory.  Otherwise, we need to add
1332      directory specifications.  */
1333
1334   if (strchr (unixname, '/') == 0)
1335     {
1336       /* if no directories specified yet and none are following.  */
1337       if (local_ptr[-1] == '[')
1338         {
1339           /* Just add "000000]" as the directory string */
1340           strcpy (local_ptr, "000000]");
1341           local_ptr += strlen (local_ptr);
1342           check_filename_before_returning = 1; /* we might need to fool with this later */
1343         }
1344     }
1345   else
1346     {
1347
1348       /* As long as there are still subdirectories to add, do them.  */
1349       while (strchr (unixname, '/') != 0)
1350         {
1351           /* If this token is "." we can ignore it
1352                if it's not at the beginning of a path.  */
1353           if ((unixname[0] == '.') && (unixname[1] == '/'))
1354             {
1355               /* remove it at beginning of path.  */
1356               if (  ((unixname == fullname)             /* no device spec  */
1357                     && (fullname+2 != basename))        /* starts with ./ */
1358                                                         /* or  */
1359                  || ((basename[-1] == ':')              /* device spec  */
1360                     && (unixname-1 == basename)))       /* and ./ afterwards  */
1361                 *local_ptr++ = '.';                     /* make '[.' start of path.  */
1362               unixname += 2;
1363               continue;
1364             }
1365
1366           /* Add a subdirectory spec. Do not duplicate "." */
1367           if (  local_ptr[-1] != '.'
1368              && local_ptr[-1] != '['
1369              && local_ptr[-1] != '<')
1370             *local_ptr++ = '.';
1371
1372           /* If this is ".." then the spec becomes "-" */
1373           if (  (unixname[0] == '.')
1374              && (unixname[1] == '.')
1375              && (unixname[2] == '/'))
1376             {
1377               /* Add "-" and skip the ".." */
1378               if ((local_ptr[-1] == '.')
1379                   && (local_ptr[-2] == '['))
1380                 local_ptr--;                    /* prevent [.-  */
1381               *local_ptr++ = '-';
1382               unixname += 3;
1383               continue;
1384             }
1385
1386           /* Copy the subdirectory */
1387           while (*unixname != '/')
1388             *local_ptr++= *unixname++;
1389
1390           unixname++;                   /* Skip the "/" */
1391         }
1392
1393       /* Close the directory specification */
1394       if (local_ptr[-1] == '.')         /* no trailing periods */
1395         local_ptr--;
1396
1397       if (local_ptr[-1] == '[')         /* no dir needed */
1398         local_ptr--;
1399       else
1400         *local_ptr++ = ']';
1401     }
1402
1403   /* Now add the filename.  */
1404
1405   while (*unixname)
1406     *local_ptr++ = *unixname++;
1407   *local_ptr = 0;
1408
1409   /* Now append it to the original VMS spec.  */
1410
1411   strcpy ((must_revert==1)?fullname:basename, Local);
1412
1413   /* If we put a [000000] in the filename, try to open it first. If this fails,
1414      remove the [000000], and return that name.  This provides flexibility
1415      to the user in that they can use both rooted and non-rooted logical names
1416      to point to the location of the file.  */
1417
1418   if (check_filename_before_returning)
1419     {
1420       f = open (fullname, O_RDONLY|O_NONBLOCK);
1421       if (f >= 0)
1422         {
1423           /* The file name is OK as it is, so return it as is.  */
1424           close (f);
1425           return 1;
1426         }
1427
1428       /* The filename did not work.  Try to remove the [000000] from the name,
1429          and return it.  */
1430
1431       basename = strchr (fullname, '[');
1432       local_ptr = strchr (fullname, ']') + 1;
1433       strcpy (basename, local_ptr);             /* this gets rid of it */
1434
1435     }
1436
1437   return 1;
1438 }
1439 #endif  /* VMS */