OSDN Git Service

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