OSDN Git Service

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