OSDN Git Service

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