OSDN Git Service

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