OSDN Git Service

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