OSDN Git Service

* cppfiles.c (struct include_file): Update.
[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, 2001 Free Software Foundation, Inc.
4    Written by Per Bothner, 1994.
5    Based on CCCP program by Paul Rubin, June 1986
6    Adapted to ANSI C, Richard Stallman, Jan 1987
7    Split out of cpplib.c, Zack Weinberg, Oct 1998
8
9 This program is free software; you can redistribute it and/or modify it
10 under the terms of the GNU General Public License as published by the
11 Free Software Foundation; either version 2, or (at your option) any
12 later version.
13
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 GNU General Public License for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with this program; if not, write to the Free Software
21 Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
22
23 #include "config.h"
24 #include "system.h"
25 #include "cpplib.h"
26 #include "cpphash.h"
27 #include "intl.h"
28 #include "mkdeps.h"
29 #include "splay-tree.h"
30
31 #ifdef HAVE_MMAP_FILE
32 # include <sys/mman.h>
33 # ifndef MMAP_THRESHOLD
34 #  define MMAP_THRESHOLD 3 /* Minimum page count to mmap the file.  */
35 # endif
36
37 #else  /* No MMAP_FILE */
38 #  undef MMAP_THRESHOLD
39 #  define MMAP_THRESHOLD 0
40 #endif
41
42 #ifndef O_BINARY
43 # define O_BINARY 0
44 #endif
45
46 #ifndef INCLUDE_LEN_FUDGE
47 # define INCLUDE_LEN_FUDGE 0
48 #endif
49
50 /* If errno is inspected immediately after a system call fails, it will be
51    nonzero, and no error number will ever be zero.  */
52 #ifndef ENOENT
53 # define ENOENT 0
54 #endif
55 #ifndef ENOTDIR
56 # define ENOTDIR 0
57 #endif
58 #ifndef ENOMEM
59 # define ENOMEM 0
60 #endif
61
62 /* Suppress warning about function macros used w/o arguments in traditional
63    C.  It is unlikely that glibc's strcmp macro helps this file at all.  */
64 #undef strcmp
65
66 /* This structure is used for the table of all includes.  */
67 struct include_file
68 {
69   const char *name;             /* actual path name of file */
70   const cpp_hashnode *cmacro;   /* macro, if any, preventing reinclusion.  */
71   const struct search_path *foundhere;
72                                 /* location in search path where file was
73                                    found, for #include_next and sysp.  */
74   const unsigned char *buffer;  /* pointer to cached file contents */
75   struct stat st;               /* copy of stat(2) data for file */
76   int fd;                       /* fd open on file (short term storage only) */
77   unsigned short include_count; /* number of times file has been read */
78   unsigned short refcnt;        /* number of stacked buffers using this file */
79   unsigned char mapped;         /* file buffer is mmapped */
80   unsigned char defined;        /* cmacro prevents inclusion in this state */
81 };
82
83 /* The cmacro works like this: If it's NULL, the file is to be
84    included again.  If it's NEVER_REREAD, the file is never to be
85    included again.  Otherwise it is a macro hashnode, and the file is
86    to be included again if the macro is defined or not as specified by
87    DEFINED.  */
88 #define NEVER_REREAD ((const cpp_hashnode *)-1)
89 #define DO_NOT_REREAD(inc) \
90 ((inc)->cmacro && ((inc)->cmacro == NEVER_REREAD \
91                    || ((inc)->cmacro->type == NT_MACRO) == (inc)->defined))
92
93 static struct file_name_map *read_name_map
94                                 PARAMS ((cpp_reader *, const char *));
95 static char *read_filename_string PARAMS ((int, FILE *));
96 static char *remap_filename     PARAMS ((cpp_reader *, char *,
97                                          struct search_path *));
98 static struct search_path *search_from PARAMS ((cpp_reader *,
99                                                 struct include_file *));
100 static struct include_file *find_include_file
101                                 PARAMS ((cpp_reader *, const char *,
102                                          struct search_path *));
103 static struct include_file *open_file PARAMS ((cpp_reader *, const char *));
104 static void read_include_file   PARAMS ((cpp_reader *, struct include_file *));
105 static void stack_include_file  PARAMS ((cpp_reader *, struct include_file *));
106 static void purge_cache         PARAMS ((struct include_file *));
107 static void destroy_include_file_node   PARAMS ((splay_tree_value));
108 static int report_missing_guard         PARAMS ((splay_tree_node, void *));
109
110 /* We use a splay tree to store information about all the include
111    files seen in this compilation.  The key of each tree node is the
112    physical path to the file.  The value is 0 if the file does not
113    exist, or a struct include_file pointer.  */
114
115 static void
116 destroy_include_file_node (v)
117      splay_tree_value v;
118 {
119   struct include_file *f = (struct include_file *)v;
120
121   if (f)
122     {
123       purge_cache (f);
124       free (f);  /* The tree is registered with free to free f->name.  */
125     }
126 }
127
128 void
129 _cpp_init_includes (pfile)
130      cpp_reader *pfile;
131 {
132   pfile->all_include_files
133     = splay_tree_new ((splay_tree_compare_fn) strcmp,
134                       (splay_tree_delete_key_fn) free,
135                       destroy_include_file_node);
136 }
137
138 void
139 _cpp_cleanup_includes (pfile)
140      cpp_reader *pfile;
141 {
142   splay_tree_delete (pfile->all_include_files);
143 }
144
145 /* Mark a file to not be reread (e.g. #import, read failure).  */
146 void
147 _cpp_never_reread (file)
148      struct include_file *file;
149 {
150   file->cmacro = NEVER_REREAD;
151 }
152
153 /* Put a file name in the splay tree, for the sake of cpp_included ().
154    Assume that FNAME has already had its path simplified.  */
155 void
156 _cpp_fake_include (pfile, fname)
157      cpp_reader *pfile;
158      const char *fname;
159 {
160   splay_tree_node nd;
161
162   nd = splay_tree_lookup (pfile->all_include_files, (splay_tree_key) fname);
163   if (! nd)
164     {
165       struct include_file *file = xcnew (struct include_file);
166       file->name = xstrdup (fname);
167       splay_tree_insert (pfile->all_include_files,
168                          (splay_tree_key) file->name,
169                          (splay_tree_value) file);
170     }
171 }
172
173 /* Given a file name, look it up in the cache; if there is no entry,
174    create one with a non-NULL value (regardless of success in opening
175    the file).  If the file doesn't exist or is inaccessible, this
176    entry is flagged so we don't attempt to open it again in the
177    future.  If the file isn't open, open it.  The empty string is
178    interpreted as stdin.
179
180    Returns an include_file structure with an open file descriptor on
181    success, or NULL on failure.  */
182
183 static struct include_file *
184 open_file (pfile, filename)
185      cpp_reader *pfile;
186      const char *filename;
187 {
188   splay_tree_node nd;
189   struct include_file *file;
190
191   nd = splay_tree_lookup (pfile->all_include_files, (splay_tree_key) filename);
192
193   if (nd)
194     {
195       file = (struct include_file *) nd->value;
196
197       /* Don't retry opening if we failed previously.  */
198       if (file->fd == -2)
199         return 0;
200
201       /* Don't reopen an idempotent file. */
202       if (DO_NOT_REREAD (file))
203         return file;
204       
205       /* Don't reopen one which is already loaded. */
206       if (file->buffer != NULL)
207         return file;
208     }
209   else
210     {
211       /* In particular, this clears foundhere.  */
212       file = xcnew (struct include_file);
213       file->name = xstrdup (filename);
214       splay_tree_insert (pfile->all_include_files,
215                          (splay_tree_key) file->name,
216                          (splay_tree_value) file);
217     }
218
219   /* We used to open files in nonblocking mode, but that caused more
220      problems than it solved.  Do take care not to acquire a
221      controlling terminal by mistake (this can't happen on sane
222      systems, but paranoia is a virtue).
223
224      Use the three-argument form of open even though we aren't
225      specifying O_CREAT, to defend against broken system headers.
226
227      O_BINARY tells some runtime libraries (notably DJGPP) not to do
228      newline translation; we can handle DOS line breaks just fine
229      ourselves.
230
231      Special case: the empty string is translated to stdin.  */
232
233   if (filename[0] == '\0')
234     file->fd = 0;
235   else
236     file->fd = open (filename, O_RDONLY | O_NOCTTY | O_BINARY, 0666);
237
238   if (file->fd != -1 && fstat (file->fd, &file->st) == 0)
239     {
240       /* Mark a regular, zero-length file never-reread now.  */
241       if (S_ISREG (file->st.st_mode) && file->st.st_size == 0)
242         {
243           _cpp_never_reread (file);
244           close (file->fd);
245           file->fd = -1;
246         }
247
248       return file;
249     }
250
251   /* Don't issue an error message if the file doesn't exist.  */
252   if (errno != ENOENT && errno != ENOTDIR)
253     cpp_error_from_errno (pfile, filename);
254
255   /* Create a negative node for this path, and return null.  */
256   file->fd = -2;
257
258   return 0;
259 }
260
261 /* Place the file referenced by INC into a new buffer on PFILE's
262    stack.  If there are errors, or the file should not be re-included,
263    a null buffer is pushed.  */
264
265 static void
266 stack_include_file (pfile, inc)
267      cpp_reader *pfile;
268      struct include_file *inc;
269 {
270   size_t len = 0;
271   cpp_buffer *fp;
272   int sysp, deps_sysp;
273
274   /* We'll try removing deps_sysp after the release of 3.0.  */
275   deps_sysp = pfile->system_include_depth != 0;
276   sysp = ((pfile->buffer && pfile->buffer->sysp)
277           || (inc->foundhere && inc->foundhere->sysp));
278
279   /* For -M, add the file to the dependencies on its first inclusion.  */
280   if (CPP_OPTION (pfile, print_deps) > deps_sysp && !inc->include_count)
281     deps_add_dep (pfile->deps, inc->name);
282
283   /* We don't want multiple include guard advice for the main file.  */
284   if (pfile->buffer)
285     inc->include_count++;
286
287   /* Not in cache?  */
288   if (! inc->buffer)
289     read_include_file (pfile, inc);
290
291   if (! DO_NOT_REREAD (inc))
292     len = inc->st.st_size;
293
294   /* Push a buffer.  */
295   fp = cpp_push_buffer (pfile, inc->buffer, len, BUF_FILE, inc->name);
296   fp->inc = inc;
297   fp->inc->refcnt++;
298   fp->sysp = sysp;
299   fp->search_from = search_from (pfile, inc);
300
301   /* Initialise controlling macro state.  */
302   pfile->mi_state = MI_OUTSIDE;
303   pfile->mi_cmacro = 0;
304   pfile->include_depth++;
305
306   /* Generate the call back.  */
307   fp->lineno = 0;
308   _cpp_do_file_change (pfile, FC_ENTER, 0, 0);
309   fp->lineno = 1;
310 }
311
312 /* Read the file referenced by INC into the file cache.
313
314    If fd points to a plain file, we might be able to mmap it; we can
315    definitely allocate the buffer all at once.  If fd is a pipe or
316    terminal, we can't do either.  If fd is something weird, like a
317    block device or a directory, we don't want to read it at all.
318
319    Unfortunately, different systems use different st.st_mode values
320    for pipes: some have S_ISFIFO, some S_ISSOCK, some are buggy and
321    zero the entire struct stat except a couple fields.  Hence we don't
322    even try to figure out what something is, except for plain files,
323    directories, and block devices.
324
325    FIXME: Flush file cache and try again if we run out of memory.  */
326
327 static void
328 read_include_file (pfile, inc)
329      cpp_reader *pfile;
330      struct include_file *inc;
331 {
332   ssize_t size, offset, count;
333   U_CHAR *buf;
334 #if MMAP_THRESHOLD
335   static int pagesize = -1;
336 #endif
337
338   if (DO_NOT_REREAD (inc))
339     return;
340
341   if (S_ISREG (inc->st.st_mode))
342     {
343       /* off_t might have a wider range than ssize_t - in other words,
344          the max size of a file might be bigger than the address
345          space.  We can't handle a file that large.  (Anyone with
346          a single source file bigger than 2GB needs to rethink
347          their coding style.)  Some systems (e.g. AIX 4.1) define
348          SSIZE_MAX to be much smaller than the actual range of the
349          type.  Use INTTYPE_MAXIMUM unconditionally to ensure this
350          does not bite us.  */
351       if (inc->st.st_size > INTTYPE_MAXIMUM (ssize_t))
352         {
353           cpp_error (pfile, "%s is too large", inc->name);
354           goto fail;
355         }
356       size = inc->st.st_size;
357
358       inc->mapped = 0;
359 #if MMAP_THRESHOLD
360       if (pagesize == -1)
361         pagesize = getpagesize ();
362
363       if (size / pagesize >= MMAP_THRESHOLD)
364         {
365           buf = (U_CHAR *) mmap (0, size, PROT_READ, MAP_PRIVATE, inc->fd, 0);
366           if (buf == (U_CHAR *)-1)
367             goto perror_fail;
368           inc->mapped = 1;
369         }
370       else
371 #endif
372         {
373           buf = (U_CHAR *) xmalloc (size);
374           offset = 0;
375           while (offset < size)
376             {
377               count = read (inc->fd, buf + offset, size - offset);
378               if (count < 0)
379                 goto perror_fail;
380               if (count == 0)
381                 {
382                   cpp_warning (pfile, "%s is shorter than expected", inc->name);
383                   break;
384                 }
385               offset += count;
386             }
387         }
388     }
389   else if (S_ISBLK (inc->st.st_mode))
390     {
391       cpp_error (pfile, "%s is a block device", inc->name);
392       goto fail;
393     }
394   else if (S_ISDIR (inc->st.st_mode))
395     {
396       cpp_error (pfile, "%s is a directory", inc->name);
397       goto fail;
398     }
399   else
400     {
401       /* 8 kilobytes is a sensible starting size.  It ought to be
402          bigger than the kernel pipe buffer, and it's definitely
403          bigger than the majority of C source files.  */
404       size = 8 * 1024;
405
406       buf = (U_CHAR *) xmalloc (size);
407       offset = 0;
408       while ((count = read (inc->fd, buf + offset, size - offset)) > 0)
409         {
410           offset += count;
411           if (offset == size)
412             buf = xrealloc (buf, (size *= 2));
413         }
414       if (count < 0)
415         goto perror_fail;
416
417       if (offset < size)
418         buf = xrealloc (buf, offset);
419       inc->st.st_size = offset;
420     }
421
422   close (inc->fd);
423   inc->buffer = buf;
424   inc->fd = -1;
425   return;
426
427  perror_fail:
428   cpp_error_from_errno (pfile, inc->name);
429  fail:
430   /* Do not try to read this file again.  */
431   close (inc->fd);
432   inc->fd = -1;
433   _cpp_never_reread (inc);
434   return;
435 }
436
437 static void
438 purge_cache (inc)
439      struct include_file *inc;
440 {
441   if (inc->buffer)
442     {
443 #if MMAP_THRESHOLD
444       if (inc->mapped)
445         munmap ((PTR) inc->buffer, inc->st.st_size);
446       else
447 #endif
448         free ((PTR) inc->buffer);
449       inc->buffer = NULL;
450     }
451 }
452
453 /* Return 1 if the file named by FNAME has been included before in
454    any context, 0 otherwise.  */
455 int
456 cpp_included (pfile, fname)
457      cpp_reader *pfile;
458      const char *fname;
459 {
460   struct search_path *path;
461   char *name;
462   splay_tree_node nd;
463
464   if (IS_ABSOLUTE_PATHNAME (fname))
465     {
466       /* Just look it up.  */
467       nd = splay_tree_lookup (pfile->all_include_files, (splay_tree_key) fname);
468       return (nd && nd->value);
469     }
470       
471   /* Search directory path for the file.  */
472   name = (char *) alloca (strlen (fname) + pfile->max_include_len
473                           + 2 + INCLUDE_LEN_FUDGE);
474   for (path = CPP_OPTION (pfile, quote_include); path; path = path->next)
475     {
476       memcpy (name, path->name, path->len);
477       name[path->len] = '/';
478       strcpy (&name[path->len + 1], fname);
479       _cpp_simplify_pathname (name);
480       if (CPP_OPTION (pfile, remap))
481         name = remap_filename (pfile, name, path);
482
483       nd = splay_tree_lookup (pfile->all_include_files, (splay_tree_key) name);
484       if (nd && nd->value)
485         return 1;
486     }
487   return 0;
488 }
489
490 /* Search for include file FNAME in the include chain starting at
491    SEARCH_START.  Return 0 if there is no such file (or it's un-openable),
492    otherwise an include_file structure.  */
493
494 static struct include_file *
495 find_include_file (pfile, fname, search_start)
496      cpp_reader *pfile;
497      const char *fname;
498      struct search_path *search_start;
499 {
500   struct search_path *path;
501   char *name;
502   struct include_file *file;
503
504   if (IS_ABSOLUTE_PATHNAME (fname))
505     return open_file (pfile, fname);
506       
507   /* Search directory path for the file.  */
508   name = (char *) alloca (strlen (fname) + pfile->max_include_len
509                           + 2 + INCLUDE_LEN_FUDGE);
510   for (path = search_start; path; path = path->next)
511     {
512       memcpy (name, path->name, path->len);
513       name[path->len] = '/';
514       strcpy (&name[path->len + 1], fname);
515       _cpp_simplify_pathname (name);
516       if (CPP_OPTION (pfile, remap))
517         name = remap_filename (pfile, name, path);
518
519       file = open_file (pfile, name);
520       if (file)
521         {
522           file->foundhere = path;
523           return file;
524         }
525     }
526
527   return 0;
528 }
529
530 /* Not everyone who wants to set system-header-ness on a buffer can
531    see the details of a buffer.  This is an exported interface because
532    fix-header needs it.  */
533 void
534 cpp_make_system_header (pfile, syshdr, externc)
535      cpp_reader *pfile;
536      int syshdr, externc;
537 {
538   int flags = 0;
539
540   /* 1 = system header, 2 = system header to be treated as C.  */
541   if (syshdr)
542     flags = 1 + (externc != 0);
543   pfile->buffer->sysp = flags;
544   _cpp_do_file_change (pfile, FC_RENAME, pfile->buffer->nominal_fname,
545                        pfile->buffer->lineno);
546 }
547
548 /* Report on all files that might benefit from a multiple include guard.
549    Triggered by -H.  */
550 void
551 _cpp_report_missing_guards (pfile)
552      cpp_reader *pfile;
553 {
554   int banner = 0;
555   splay_tree_foreach (pfile->all_include_files, report_missing_guard,
556                       (PTR) &banner);
557 }
558
559 static int
560 report_missing_guard (n, b)
561      splay_tree_node n;
562      void *b;
563 {
564   struct include_file *f = (struct include_file *) n->value;
565   int *bannerp = (int *)b;
566
567   if (f && f->cmacro == 0 && f->include_count == 1)
568     {
569       if (*bannerp == 0)
570         {
571           fputs (_("Multiple include guards may be useful for:\n"), stderr);
572           *bannerp = 1;
573         }
574       fputs (f->name, stderr);
575       putc ('\n', stderr);
576     }
577   return 0;
578 }
579
580 void
581 _cpp_execute_include (pfile, header, no_reinclude, include_next)
582      cpp_reader *pfile;
583      const cpp_token *header;
584      int no_reinclude;
585      int include_next;
586 {
587   struct search_path *search_start = 0;
588   unsigned int len = header->val.str.len;
589   unsigned int angle_brackets = header->type == CPP_HEADER_NAME;
590   struct include_file *inc;
591   char *fname;
592   int print_dep;
593
594   /* Help protect #include or similar from recursion.  */
595   if (pfile->buffer_stack_depth >= CPP_STACK_MAX)
596     {
597       cpp_fatal (pfile, "#include nested too deeply");
598       return;
599     }
600
601   /* Check we've tidied up #include before entering the buffer.  */
602   if (pfile->context->prev)
603     {
604       cpp_ice (pfile, "attempt to push file buffer with contexts stacked");
605       return;
606     }
607
608   /* For #include_next, skip in the search path past the dir in which
609      the current file was found.  If this is the last directory in the
610      search path, don't include anything.  If the current file was
611      specified with an absolute path, use the normal search logic.  If
612      this is the primary source file, use the normal search logic and
613      generate a warning.  */
614   if (include_next)
615     {
616       if (! pfile->buffer->prev)
617         cpp_warning (pfile, "#include_next in primary source file");
618       else
619         {
620           if (pfile->buffer->inc->foundhere)
621             {
622               search_start = pfile->buffer->inc->foundhere->next;
623               if (! search_start)
624                 return;
625             }
626         }
627     }
628
629   fname = alloca (len + 1);
630   memcpy (fname, header->val.str.text, len);
631   fname[len] = '\0';
632
633   if (!search_start)
634     {
635       if (angle_brackets)
636         search_start = CPP_OPTION (pfile, bracket_include);
637       else
638         search_start = pfile->buffer->search_from;
639
640       if (!search_start)
641         {
642           cpp_error (pfile, "No include path in which to find %s", fname);
643           return;
644         }
645     }
646
647   inc = find_include_file (pfile, fname, search_start);
648   if (inc)
649     {
650       if (angle_brackets)
651         pfile->system_include_depth++;
652
653       stack_include_file (pfile, inc);
654
655       if (! DO_NOT_REREAD (inc))
656         {
657           if (no_reinclude)
658             _cpp_never_reread (inc);
659
660           /* Handle -H option.  */
661           if (CPP_OPTION (pfile, print_include_names))
662             {
663               cpp_buffer *fp = CPP_BUFFER (pfile);
664               while ((fp = CPP_PREV_BUFFER (fp)) != NULL)
665                 putc ('.', stderr);
666               fprintf (stderr, " %s\n", inc->name);
667             }
668         }
669
670       return;
671     }
672       
673   /* We will try making the RHS pfile->buffer->sysp after 3.0.  */
674   print_dep = CPP_PRINT_DEPS(pfile) > (angle_brackets
675                                        || pfile->system_include_depth);
676   if (CPP_OPTION (pfile, print_deps_missing_files) && print_dep)
677     {
678       if (!angle_brackets || IS_ABSOLUTE_PATHNAME (fname))
679         deps_add_dep (pfile->deps, fname);
680       else
681         {
682           char *p;
683           struct search_path *ptr;
684           int len;
685
686           /* If requested as a system header, assume it belongs in
687              the first system header directory.  */
688           if (CPP_OPTION (pfile, bracket_include))
689             ptr = CPP_OPTION (pfile, bracket_include);
690           else
691             ptr = CPP_OPTION (pfile, quote_include);
692
693           /* FIXME: ptr can be null, no?  */
694           len = ptr->len;
695           p = (char *) alloca (len + strlen (fname) + 2);
696           if (len)
697             {
698               memcpy (p, ptr->name, len);
699               p[len++] = '/';
700             }
701           strcpy (p + len, fname);
702           _cpp_simplify_pathname (p);
703           deps_add_dep (pfile->deps, p);
704         }
705     }
706   /* If -M was specified, and this header file won't be added to
707      the dependency list, then don't count this as an error,
708      because we can still produce correct output.  Otherwise, we
709      can't produce correct output, because there may be
710      dependencies we need inside the missing file, and we don't
711      know what directory this missing file exists in. */
712   else if (CPP_PRINT_DEPS (pfile) && ! print_dep)
713     cpp_warning (pfile, "No include path in which to find %s", fname);
714   else
715     cpp_error_from_errno (pfile, fname);
716 }
717
718 /* Locate file F, and determine whether it is newer than PFILE. Return -1,
719    if F cannot be located or dated, 1, if it is newer and 0 if older.  */
720 int
721 _cpp_compare_file_date (pfile, f)
722      cpp_reader *pfile;
723      const cpp_token *f;
724 {
725   unsigned int len = f->val.str.len;
726   char *fname;
727   struct search_path *search_start;
728   struct include_file *inc;
729
730   if (f->type == CPP_HEADER_NAME)
731     search_start = CPP_OPTION (pfile, bracket_include);
732   else if (CPP_OPTION (pfile, ignore_srcdir))
733     search_start = pfile->buffer->search_from;
734
735   fname = alloca (len + 1);
736   memcpy (fname, f->val.str.text, len);
737   fname[len] = '\0';
738   inc = find_include_file (pfile, fname, search_start);
739   
740   if (!inc)
741     return -1;
742   if (inc->fd > 0)
743     {
744       close (inc->fd);
745       inc->fd = -1;
746     }
747     
748   return inc->st.st_mtime > CPP_BUFFER (pfile)->inc->st.st_mtime;
749 }
750
751
752 /* Push an input buffer and load it up with the contents of FNAME.
753    If FNAME is "", read standard input.  */
754 int
755 _cpp_read_file (pfile, fname)
756      cpp_reader *pfile;
757      const char *fname;
758 {
759   struct include_file *f = open_file (pfile, fname);
760
761   if (f == NULL)
762     {
763       cpp_error_from_errno (pfile, fname);
764       return 0;
765     }
766
767   stack_include_file (pfile, f);
768   return 1;
769 }
770
771 /* Do appropriate cleanup when a file buffer is popped off the input
772    stack.  */
773 void
774 _cpp_pop_file_buffer (pfile, buf)
775      cpp_reader *pfile;
776      cpp_buffer *buf;
777 {
778   struct include_file *inc = buf->inc;
779
780   if (pfile->system_include_depth)
781     pfile->system_include_depth--;
782   if (pfile->include_depth)
783     pfile->include_depth--;
784
785   /* Record the inclusion-preventing macro and its definedness.  */
786   if (pfile->mi_state == MI_OUTSIDE && inc->cmacro != NEVER_REREAD)
787     {
788       /* This could be NULL meaning no controlling macro.  */
789       inc->cmacro = pfile->mi_cmacro;
790       inc->defined = 1;
791     }
792
793   /* Invalidate control macros in the #including file.  */
794   pfile->mi_state = MI_FAILED;
795
796   inc->refcnt--;
797   if (inc->refcnt == 0 && DO_NOT_REREAD (inc))
798     purge_cache (inc);
799 }
800
801 /* Returns the first place in the include chain to start searching for
802    "" includes.  This involves stripping away the basename of the
803    current file, unless -I- was specified.  */
804 static struct search_path *
805 search_from (pfile, inc)
806      cpp_reader *pfile;
807      struct include_file *inc;
808 {
809   cpp_buffer *buffer = pfile->buffer;
810   unsigned int dlen;
811
812   /* Ignore the current file's directory if -I- was given.  */
813   if (CPP_OPTION (pfile, ignore_srcdir))
814     return CPP_OPTION (pfile, quote_include);
815
816   dlen = basename (inc->name) - inc->name;
817   if (dlen)
818     {
819       /* We don't guarantee NAME is null-terminated.  This saves
820          allocating and freeing memory, and duplicating it when faking
821          buffers in cpp_push_buffer.  Drop a trailing '/'.  */
822       buffer->dir.name = inc->name;
823       if (dlen > 1)
824         dlen--;
825     }
826   else
827     {
828       buffer->dir.name = ".";
829       dlen = 1;
830     }
831
832   if (dlen > pfile->max_include_len)
833     pfile->max_include_len = dlen;
834
835   buffer->dir.len = dlen;
836   buffer->dir.next = CPP_OPTION (pfile, quote_include);
837   buffer->dir.sysp = buffer->sysp;
838
839   return &buffer->dir;
840 }
841
842 /* The file_name_map structure holds a mapping of file names for a
843    particular directory.  This mapping is read from the file named
844    FILE_NAME_MAP_FILE in that directory.  Such a file can be used to
845    map filenames on a file system with severe filename restrictions,
846    such as DOS.  The format of the file name map file is just a series
847    of lines with two tokens on each line.  The first token is the name
848    to map, and the second token is the actual name to use.  */
849
850 struct file_name_map
851 {
852   struct file_name_map *map_next;
853   char *map_from;
854   char *map_to;
855 };
856
857 #define FILE_NAME_MAP_FILE "header.gcc"
858
859 /* Read a space delimited string of unlimited length from a stdio
860    file.  */
861
862 static char *
863 read_filename_string (ch, f)
864      int ch;
865      FILE *f;
866 {
867   char *alloc, *set;
868   int len;
869
870   len = 20;
871   set = alloc = xmalloc (len + 1);
872   if (! is_space(ch))
873     {
874       *set++ = ch;
875       while ((ch = getc (f)) != EOF && ! is_space(ch))
876         {
877           if (set - alloc == len)
878             {
879               len *= 2;
880               alloc = xrealloc (alloc, len + 1);
881               set = alloc + len / 2;
882             }
883           *set++ = ch;
884         }
885     }
886   *set = '\0';
887   ungetc (ch, f);
888   return alloc;
889 }
890
891 /* This structure holds a linked list of file name maps, one per directory.  */
892
893 struct file_name_map_list
894 {
895   struct file_name_map_list *map_list_next;
896   char *map_list_name;
897   struct file_name_map *map_list_map;
898 };
899
900 /* Read the file name map file for DIRNAME.  */
901
902 static struct file_name_map *
903 read_name_map (pfile, dirname)
904      cpp_reader *pfile;
905      const char *dirname;
906 {
907   register struct file_name_map_list *map_list_ptr;
908   char *name;
909   FILE *f;
910
911   /* Check the cache of directories, and mappings in their remap file.  */
912   for (map_list_ptr = CPP_OPTION (pfile, map_list); map_list_ptr;
913        map_list_ptr = map_list_ptr->map_list_next)
914     if (! strcmp (map_list_ptr->map_list_name, dirname))
915       return map_list_ptr->map_list_map;
916
917   map_list_ptr = ((struct file_name_map_list *)
918                   xmalloc (sizeof (struct file_name_map_list)));
919   map_list_ptr->map_list_name = xstrdup (dirname);
920
921   /* The end of the list ends in NULL.  */
922   map_list_ptr->map_list_map = NULL;
923
924   name = (char *) alloca (strlen (dirname) + strlen (FILE_NAME_MAP_FILE) + 2);
925   strcpy (name, dirname);
926   if (*dirname)
927     strcat (name, "/");
928   strcat (name, FILE_NAME_MAP_FILE);
929   f = fopen (name, "r");
930
931   /* Silently return NULL if we cannot open.  */
932   if (f)
933     {
934       int ch;
935       int dirlen = strlen (dirname);
936
937       while ((ch = getc (f)) != EOF)
938         {
939           char *from, *to;
940           struct file_name_map *ptr;
941
942           if (is_space(ch))
943             continue;
944           from = read_filename_string (ch, f);
945           while ((ch = getc (f)) != EOF && is_hspace(ch))
946             ;
947           to = read_filename_string (ch, f);
948
949           ptr = ((struct file_name_map *)
950                  xmalloc (sizeof (struct file_name_map)));
951           ptr->map_from = from;
952
953           /* Make the real filename absolute.  */
954           if (IS_ABSOLUTE_PATHNAME (to))
955             ptr->map_to = to;
956           else
957             {
958               ptr->map_to = xmalloc (dirlen + strlen (to) + 2);
959               strcpy (ptr->map_to, dirname);
960               ptr->map_to[dirlen] = '/';
961               strcpy (ptr->map_to + dirlen + 1, to);
962               free (to);
963             }         
964
965           ptr->map_next = map_list_ptr->map_list_map;
966           map_list_ptr->map_list_map = ptr;
967
968           while ((ch = getc (f)) != '\n')
969             if (ch == EOF)
970               break;
971         }
972       fclose (f);
973     }
974   
975   /* Add this information to the cache.  */
976   map_list_ptr->map_list_next = CPP_OPTION (pfile, map_list);
977   CPP_OPTION (pfile, map_list) = map_list_ptr;
978
979   return map_list_ptr->map_list_map;
980 }  
981
982 /* Remap NAME based on the file_name_map (if any) for LOC. */
983
984 static char *
985 remap_filename (pfile, name, loc)
986      cpp_reader *pfile;
987      char *name;
988      struct search_path *loc;
989 {
990   struct file_name_map *map;
991   const char *from, *p;
992   char *dir, *dname;
993
994   /* Get a null-terminated path.  */
995   dname = alloca (loc->len + 1);
996   memcpy (dname, loc->name, loc->len);
997   dname[loc->len] = '\0';
998
999   if (! loc->name_map)
1000     {
1001       loc->name_map = read_name_map (pfile, dname);
1002       if (! loc->name_map)
1003         return name;
1004     }
1005   
1006   /* FIXME: this doesn't look right - NAME has been simplified.  */
1007   from = name + loc->len + 1;
1008   
1009   for (map = loc->name_map; map; map = map->map_next)
1010     if (!strcmp (map->map_from, from))
1011       return map->map_to;
1012
1013   /* Try to find a mapping file for the particular directory we are
1014      looking in.  Thus #include <sys/types.h> will look up sys/types.h
1015      in /usr/include/header.gcc and look up types.h in
1016      /usr/include/sys/header.gcc.  */
1017   p = strrchr (name, '/');
1018   if (!p)
1019     return name;
1020
1021   /* We know p != name as absolute paths don't call remap_filename.  */
1022   if (p == name)
1023     cpp_ice (pfile, "absolute file name in remap_filename");
1024
1025   dir = (char *) alloca (p - name + 1);
1026   memcpy (dir, name, p - name);
1027   dir[p - name] = '\0';
1028   from = p + 1;
1029   
1030   for (map = read_name_map (pfile, dir); map; map = map->map_next)
1031     if (! strcmp (map->map_from, from))
1032       return map->map_to;
1033
1034   return name;
1035 }
1036
1037 /* Simplify a path name in place, deleting redundant components.  This
1038    reduces OS overhead and guarantees that equivalent paths compare
1039    the same (modulo symlinks).
1040
1041    Transforms made:
1042    foo/bar/../quux      foo/quux
1043    foo/./bar            foo/bar
1044    foo//bar             foo/bar
1045    /../quux             /quux
1046    //quux               //quux  (POSIX allows leading // as a namespace escape)
1047
1048    Guarantees no trailing slashes. All transforms reduce the length
1049    of the string.
1050  */
1051 void
1052 _cpp_simplify_pathname (path)
1053     char *path;
1054 {
1055     char *from, *to;
1056     char *base;
1057     int absolute = 0;
1058
1059 #if defined (HAVE_DOS_BASED_FILE_SYSTEM)
1060     /* Convert all backslashes to slashes. */
1061     for (from = path; *from; from++)
1062         if (*from == '\\') *from = '/';
1063     
1064     /* Skip over leading drive letter if present. */
1065     if (ISALPHA (path[0]) && path[1] == ':')
1066         from = to = &path[2];
1067     else
1068         from = to = path;
1069 #else
1070     from = to = path;
1071 #endif
1072     
1073     /* Remove redundant initial /s.  */
1074     if (*from == '/')
1075     {
1076         absolute = 1;
1077         to++;
1078         from++;
1079         if (*from == '/')
1080         {
1081             if (*++from == '/')
1082                 /* 3 or more initial /s are equivalent to 1 /.  */
1083                 while (*++from == '/');
1084             else
1085                 /* On some hosts // differs from /; Posix allows this.  */
1086                 to++;
1087         }
1088     }
1089     base = to;
1090     
1091     for (;;)
1092     {
1093         while (*from == '/')
1094             from++;
1095
1096         if (from[0] == '.' && from[1] == '/')
1097             from += 2;
1098         else if (from[0] == '.' && from[1] == '\0')
1099             goto done;
1100         else if (from[0] == '.' && from[1] == '.' && from[2] == '/')
1101         {
1102             if (base == to)
1103             {
1104                 if (absolute)
1105                     from += 3;
1106                 else
1107                 {
1108                     *to++ = *from++;
1109                     *to++ = *from++;
1110                     *to++ = *from++;
1111                     base = to;
1112                 }
1113             }
1114             else
1115             {
1116                 to -= 2;
1117                 while (to > base && *to != '/') to--;
1118                 if (*to == '/')
1119                     to++;
1120                 from += 3;
1121             }
1122         }
1123         else if (from[0] == '.' && from[1] == '.' && from[2] == '\0')
1124         {
1125             if (base == to)
1126             {
1127                 if (!absolute)
1128                 {
1129                     *to++ = *from++;
1130                     *to++ = *from++;
1131                 }
1132             }
1133             else
1134             {
1135                 to -= 2;
1136                 while (to > base && *to != '/') to--;
1137                 if (*to == '/')
1138                     to++;
1139             }
1140             goto done;
1141         }
1142         else
1143             /* Copy this component and trailing /, if any.  */
1144             while ((*to++ = *from++) != '/')
1145             {
1146                 if (!to[-1])
1147                 {
1148                     to--;
1149                     goto done;
1150                 }
1151             }
1152         
1153     }
1154     
1155  done:
1156     /* Trim trailing slash */
1157     if (to[0] == '/' && (!absolute || to > path+1))
1158         to--;
1159
1160     /* Change the empty string to "." so that stat() on the result
1161        will always work. */
1162     if (to == path)
1163       *to++ = '.';
1164     
1165     *to = '\0';
1166
1167     return;
1168 }