OSDN Git Service

* toplev.c (rest_of_compilation): Avoid cfg_cleanup calls when not
[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, 2002, 2003 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 <dirent.h>
26 #include "coretypes.h"
27 #include "tm.h"
28 #include "cpplib.h"
29 #include "cpphash.h"
30 #include "intl.h"
31 #include "mkdeps.h"
32 #include "splay-tree.h"
33 #ifdef ENABLE_VALGRIND_CHECKING
34 #include <valgrind.h>
35 #else
36 /* Avoid #ifdef:s when we can help it.  */
37 #define VALGRIND_DISCARD(x)
38 #endif
39
40 #ifdef HAVE_MMAP_FILE
41 # include <sys/mman.h>
42 # ifndef MMAP_THRESHOLD
43 #  define MMAP_THRESHOLD 3 /* Minimum page count to mmap the file.  */
44 # endif
45 # if MMAP_THRESHOLD
46 #  define TEST_THRESHOLD(size, pagesize) \
47      (size / pagesize >= MMAP_THRESHOLD && (size % pagesize) != 0)
48    /* Use mmap if the file is big enough to be worth it (controlled
49       by MMAP_THRESHOLD) and if we can safely count on there being
50       at least one readable NUL byte after the end of the file's
51       contents.  This is true for all tested operating systems when
52       the file size is not an exact multiple of the page size.  */
53 #  ifndef __CYGWIN__
54 #   define SHOULD_MMAP(size, pagesize) TEST_THRESHOLD (size, pagesize)
55 #  else
56 #   define WIN32_LEAN_AND_MEAN
57 #   include <windows.h>
58     /* Cygwin can't correctly emulate mmap under Windows 9x style systems so
59        disallow use of mmap on those systems.  Windows 9x does not zero fill
60        memory at EOF and beyond, as required.  */
61 #   define SHOULD_MMAP(size, pagesize) ((GetVersion() & 0x80000000) \
62                                         ? 0 : TEST_THRESHOLD (size, pagesize))
63 #  endif
64 # endif
65
66 #else  /* No MMAP_FILE */
67 #  undef MMAP_THRESHOLD
68 #  define MMAP_THRESHOLD 0
69 #endif
70
71 #ifndef O_BINARY
72 # define O_BINARY 0
73 #endif
74
75 /* If errno is inspected immediately after a system call fails, it will be
76    nonzero, and no error number will ever be zero.  */
77 #ifndef ENOENT
78 # define ENOENT 0
79 #endif
80 #ifndef ENOTDIR
81 # define ENOTDIR 0
82 #endif
83
84 /* Suppress warning about function macros used w/o arguments in traditional
85    C.  It is unlikely that glibc's strcmp macro helps this file at all.  */
86 #undef strcmp
87
88 /* This structure is used for the table of all includes.  */
89 struct include_file {
90   const char *name;             /* actual path name of file */
91   const char *header_name;      /* the original header found */
92   const cpp_hashnode *cmacro;   /* macro, if any, preventing reinclusion.  */
93   const struct cpp_path *foundhere;
94                                 /* location in search path where file was
95                                    found, for #include_next and sysp.  */
96   const unsigned char *buffer;  /* pointer to cached file contents */
97   struct stat st;               /* copy of stat(2) data for file */
98   int fd;                       /* fd open on file (short term storage only) */
99   int err_no;                   /* errno obtained if opening a file failed */
100   unsigned short include_count; /* number of times file has been read */
101   unsigned short refcnt;        /* number of stacked buffers using this file */
102   unsigned char mapped;         /* file buffer is mmapped */
103   unsigned char pch;            /* 0: file not known to be a PCH.
104                                    1: file is a PCH 
105                                       (on return from find_include_file).
106                                    2: file is not and never will be a valid
107                                       precompiled header.
108                                    3: file is always a valid precompiled
109                                       header.  */
110 };
111
112 /* Variable length record files on VMS will have a stat size that includes
113    record control characters that won't be included in the read size.  */
114 #ifdef VMS
115 # define FAB_C_VAR 2 /* variable length records (see Starlet fabdef.h) */
116 # define STAT_SIZE_TOO_BIG(ST) ((ST).st_fab_rfm == FAB_C_VAR)
117 #else
118 # define STAT_SIZE_TOO_BIG(ST) 0
119 #endif
120
121 /* The cmacro works like this: If it's NULL, the file is to be
122    included again.  If it's NEVER_REREAD, the file is never to be
123    included again.  Otherwise it is a macro hashnode, and the file is
124    to be included again if the macro is defined.  */
125 #define NEVER_REREAD ((const cpp_hashnode *) -1)
126 #define DO_NOT_REREAD(inc) \
127 ((inc)->cmacro && ((inc)->cmacro == NEVER_REREAD \
128                    || (inc)->cmacro->type == NT_MACRO))
129 #define NO_INCLUDE_PATH ((struct include_file *) -1)
130 #define INCLUDE_PCH_P(F) (((F)->pch & 1) != 0)
131
132 static struct file_name_map *read_name_map
133                                 PARAMS ((cpp_reader *, const char *));
134 static char *read_filename_string PARAMS ((int, FILE *));
135 static char *remap_filename     PARAMS ((cpp_reader *, char *,
136                                          struct cpp_path *));
137 static struct cpp_path *search_from PARAMS ((cpp_reader *,
138                                                 enum include_type));
139 static struct include_file *
140         find_include_file PARAMS ((cpp_reader *, const cpp_token *,
141                                    enum include_type));
142 static struct include_file *open_file PARAMS ((cpp_reader *, const char *));
143 static struct include_file *validate_pch PARAMS ((cpp_reader *,
144                                                   const char *,
145                                                   const char *));
146 static struct include_file *open_file_pch PARAMS ((cpp_reader *, 
147                                                    const char *));
148 static int read_include_file    PARAMS ((cpp_reader *, struct include_file *));
149 static bool stack_include_file  PARAMS ((cpp_reader *, struct include_file *));
150 static void purge_cache         PARAMS ((struct include_file *));
151 static void destroy_node        PARAMS ((splay_tree_value));
152 static int report_missing_guard         PARAMS ((splay_tree_node, void *));
153 static splay_tree_node find_or_create_entry PARAMS ((cpp_reader *,
154                                                      const char *));
155 static void handle_missing_header PARAMS ((cpp_reader *, const char *, int));
156 static int remove_component_p PARAMS ((const char *));
157
158 /* Set up the splay tree we use to store information about all the
159    file names seen in this compilation.  We also have entries for each
160    file we tried to open but failed; this saves system calls since we
161    don't try to open it again in future.
162
163    The key of each node is the file name, after processing by
164    cpp_simplify_path.  The path name may or may not be absolute.
165    The path string has been malloced, as is automatically freed by
166    registering free () as the splay tree key deletion function.
167
168    A node's value is a pointer to a struct include_file, and is never
169    NULL.  */
170 void
171 _cpp_init_includes (pfile)
172      cpp_reader *pfile;
173 {
174   pfile->all_include_files
175     = splay_tree_new ((splay_tree_compare_fn) strcmp,
176                       (splay_tree_delete_key_fn) free,
177                       destroy_node);
178 }
179
180 /* Tear down the splay tree.  */
181 void
182 _cpp_cleanup_includes (pfile)
183      cpp_reader *pfile;
184 {
185   splay_tree_delete (pfile->all_include_files);
186 }
187
188 /* Free a node.  The path string is automatically freed.  */
189 static void
190 destroy_node (v)
191      splay_tree_value v;
192 {
193   struct include_file *f = (struct include_file *) v;
194
195   if (f)
196     {
197       purge_cache (f);
198       free (f);
199     }
200 }
201
202 /* Mark a file to not be reread (e.g. #import, read failure).  */
203 void
204 _cpp_never_reread (file)
205      struct include_file *file;
206 {
207   file->cmacro = NEVER_REREAD;
208 }
209
210 /* Lookup a filename, which is simplified after making a copy, and
211    create an entry if none exists.  */
212 static splay_tree_node
213 find_or_create_entry (pfile, fname)
214      cpp_reader *pfile;
215      const char *fname;
216 {
217   splay_tree_node node;
218   struct include_file *file;
219   char *name = xstrdup (fname);
220
221   cpp_simplify_path (name);
222   node = splay_tree_lookup (pfile->all_include_files, (splay_tree_key) name);
223   if (node)
224     free (name);
225   else
226     {
227       file = xcnew (struct include_file);
228       file->name = name;
229       file->header_name = name;
230       file->err_no = errno;
231       node = splay_tree_insert (pfile->all_include_files,
232                                 (splay_tree_key) file->name,
233                                 (splay_tree_value) file);
234     }
235
236   return node;
237 }
238
239 /* Enter a file name in the splay tree, for the sake of cpp_included.  */
240 void
241 _cpp_fake_include (pfile, fname)
242      cpp_reader *pfile;
243      const char *fname;
244 {
245   find_or_create_entry (pfile, fname);
246 }
247
248 /* Given a file name, look it up in the cache; if there is no entry,
249    create one with a non-NULL value (regardless of success in opening
250    the file).  If the file doesn't exist or is inaccessible, this
251    entry is flagged so we don't attempt to open it again in the
252    future.  If the file isn't open, open it.  The empty string is
253    interpreted as stdin.
254
255    Returns an include_file structure with an open file descriptor on
256    success, or NULL on failure.  */
257 static struct include_file *
258 open_file (pfile, filename)
259      cpp_reader *pfile;
260      const char *filename;
261 {
262   splay_tree_node nd = find_or_create_entry (pfile, filename);
263   struct include_file *file = (struct include_file *) nd->value;
264
265   if (file->err_no)
266     {
267       /* Ugh.  handle_missing_header () needs errno to be set.  */
268       errno = file->err_no;
269       return 0;
270     }
271
272   /* Don't reopen an idempotent file.  */
273   if (DO_NOT_REREAD (file))
274     return file;
275
276   /* Don't reopen one which is already loaded.  */
277   if (file->buffer != NULL)
278     return file;
279
280   /* We used to open files in nonblocking mode, but that caused more
281      problems than it solved.  Do take care not to acquire a
282      controlling terminal by mistake (this can't happen on sane
283      systems, but paranoia is a virtue).
284
285      Use the three-argument form of open even though we aren't
286      specifying O_CREAT, to defend against broken system headers.
287
288      O_BINARY tells some runtime libraries (notably DJGPP) not to do
289      newline translation; we can handle DOS line breaks just fine
290      ourselves.
291
292      Special case: the empty string is translated to stdin.  */
293
294   if (filename[0] == '\0')
295     {
296       file->fd = 0;
297 #ifdef __DJGPP__
298       /* For DJGPP redirected input is opened in text mode. Change it
299          to binary mode.  */
300       if (! isatty (file->fd))
301         setmode (file->fd, O_BINARY);
302 #endif
303     }
304   else
305     file->fd = open (file->name, O_RDONLY | O_NOCTTY | O_BINARY, 0666);
306
307   if (file->fd != -1 && fstat (file->fd, &file->st) == 0)
308     {
309       if (!S_ISDIR (file->st.st_mode))
310         return file;
311
312       /* If it's a directory, we return null and continue the search
313          as the file we're looking for may appear elsewhere in the
314          search path.  */
315       errno = ENOENT;
316       close (file->fd);
317       file->fd = -1;
318     }
319
320   file->err_no = errno;
321   return 0;
322 }
323
324 static struct include_file *
325 validate_pch (pfile, filename, pchname)
326      cpp_reader *pfile;
327      const char *filename;
328      const char *pchname;
329 {
330   struct include_file * file;
331   
332   file = open_file (pfile, pchname);
333   if (file == NULL)
334     return NULL;
335   if ((file->pch & 2) == 0)
336     file->pch = pfile->cb.valid_pch (pfile, pchname, file->fd);
337   if (INCLUDE_PCH_P (file))
338     {
339       char *f = xstrdup (filename);
340       cpp_simplify_path (f);
341       file->header_name = f;
342       return file;
343     }
344   close (file->fd);
345   file->fd = -1;
346   return NULL;
347 }
348
349
350 /* Like open_file, but also look for a precompiled header if (a) one exists
351    and (b) it is valid.  */
352 static struct include_file *
353 open_file_pch (pfile, filename)
354      cpp_reader *pfile;
355      const char *filename;
356 {
357   if (filename[0] != '\0'
358       && pfile->cb.valid_pch != NULL)
359     {
360       size_t namelen = strlen (filename);
361       char *pchname = alloca (namelen + 5);
362       struct include_file * file;
363       splay_tree_node nd;
364       
365       memcpy (pchname, filename, namelen);
366       memcpy (pchname + namelen, ".gch", 5);
367
368       nd = find_or_create_entry (pfile, pchname);
369       file = (struct include_file *) nd->value;
370
371       if (file != NULL)
372         {
373           if (stat (file->name, &file->st) == 0 && S_ISDIR (file->st.st_mode))
374             {
375               DIR * thedir;
376               struct dirent *d;
377               size_t subname_len = namelen + 64;
378               char *subname = xmalloc (subname_len);
379               
380               thedir = opendir (pchname);
381               if (thedir == NULL)
382                 return NULL;
383               memcpy (subname, pchname, namelen + 4);
384               subname[namelen+4] = '/';
385               while ((d = readdir (thedir)) != NULL)
386                 {
387                   if (strlen (d->d_name) + namelen + 7 > subname_len)
388                     {
389                       subname_len = strlen (d->d_name) + namelen + 64;
390                       subname = xrealloc (subname, subname_len);
391                     }
392                   strcpy (subname + namelen + 5, d->d_name);
393                   file = validate_pch (pfile, filename, subname);
394                   if (file)
395                     break;
396                 }
397               closedir (thedir);
398               free (subname);
399             }
400           else
401             file = validate_pch (pfile, filename, pchname);
402           if (file)
403             return file;
404         }
405     }
406   return open_file (pfile, filename);
407 }
408
409 /* Place the file referenced by INC into a new buffer on the buffer
410    stack, unless there are errors, or the file is not re-included
411    because of e.g. multiple-include guards.  Returns true if a buffer
412    is stacked.  */
413 static bool
414 stack_include_file (pfile, inc)
415      cpp_reader *pfile;
416      struct include_file *inc;
417 {
418   cpp_buffer *fp;
419   int sysp;
420   const char *filename;
421
422   if (DO_NOT_REREAD (inc))
423     return false;
424
425   sysp = MAX ((pfile->map ? pfile->map->sysp : 0),
426               (inc->foundhere ? inc->foundhere->sysp : 0));
427
428   /* Add the file to the dependencies on its first inclusion.  */
429   if (CPP_OPTION (pfile, deps.style) > !!sysp && !inc->include_count)
430     {
431       if (pfile->buffer || CPP_OPTION (pfile, deps.ignore_main_file) == 0)
432         deps_add_dep (pfile->deps, inc->name);
433     }
434
435   /* PCH files get dealt with immediately.  */
436   if (INCLUDE_PCH_P (inc))
437     {
438       pfile->cb.read_pch (pfile, inc->name, inc->fd, inc->header_name);
439       close (inc->fd);
440       inc->fd = -1;
441       return false;
442     }
443
444   /* Not in cache?  */
445   if (! inc->buffer)
446     {
447       if (read_include_file (pfile, inc))
448         {
449           /* If an error occurs, do not try to read this file again.  */
450           _cpp_never_reread (inc);
451           return false;
452         }
453       /* Mark a regular, zero-length file never-reread.  We read it,
454          NUL-terminate it, and stack it once, so preprocessing a main
455          file of zero length does not raise an error.  */
456       if (S_ISREG (inc->st.st_mode) && inc->st.st_size == 0)
457         _cpp_never_reread (inc);
458       close (inc->fd);
459       inc->fd = -1;
460     }
461
462   if (pfile->buffer)
463     /* We don't want MI guard advice for the main file.  */
464     inc->include_count++;
465
466   /* Push a buffer.  */
467   fp = cpp_push_buffer (pfile, inc->buffer, inc->st.st_size,
468                         /* from_stage3 */ CPP_OPTION (pfile, preprocessed), 0);
469   fp->inc = inc;
470   fp->inc->refcnt++;
471
472   /* Initialize controlling macro state.  */
473   pfile->mi_valid = true;
474   pfile->mi_cmacro = 0;
475
476   /* Generate the call back.  */
477   filename = inc->name;
478   if (*filename == '\0')
479     filename = "<stdin>";
480   _cpp_do_file_change (pfile, LC_ENTER, filename, 1, sysp);
481
482   return true;
483 }
484
485 /* Read the file referenced by INC into the file cache.
486
487    If fd points to a plain file, we might be able to mmap it; we can
488    definitely allocate the buffer all at once.  If fd is a pipe or
489    terminal, we can't do either.  If fd is something weird, like a
490    block device, we don't want to read it at all.
491
492    Unfortunately, different systems use different st.st_mode values
493    for pipes: some have S_ISFIFO, some S_ISSOCK, some are buggy and
494    zero the entire struct stat except a couple fields.  Hence we don't
495    even try to figure out what something is, except for plain files
496    and block devices.
497
498    FIXME: Flush file cache and try again if we run out of memory.  */
499 static int
500 read_include_file (pfile, inc)
501      cpp_reader *pfile;
502      struct include_file *inc;
503 {
504   ssize_t size, offset, count;
505   uchar *buf;
506 #if MMAP_THRESHOLD
507   static int pagesize = -1;
508 #endif
509
510   if (S_ISREG (inc->st.st_mode))
511     {
512       /* off_t might have a wider range than ssize_t - in other words,
513          the max size of a file might be bigger than the address
514          space.  We can't handle a file that large.  (Anyone with
515          a single source file bigger than 2GB needs to rethink
516          their coding style.)  Some systems (e.g. AIX 4.1) define
517          SSIZE_MAX to be much smaller than the actual range of the
518          type.  Use INTTYPE_MAXIMUM unconditionally to ensure this
519          does not bite us.  */
520       if (inc->st.st_size > INTTYPE_MAXIMUM (ssize_t))
521         {
522           cpp_error (pfile, DL_ERROR, "%s is too large", inc->name);
523           goto fail;
524         }
525       size = inc->st.st_size;
526
527       inc->mapped = 0;
528 #if MMAP_THRESHOLD
529       if (pagesize == -1)
530         pagesize = getpagesize ();
531
532       if (SHOULD_MMAP (size, pagesize))
533         {
534           buf = (uchar *) mmap (0, size, PROT_READ, MAP_PRIVATE, inc->fd, 0);
535           if (buf == (uchar *) -1)
536             goto perror_fail;
537
538           /* We must tell Valgrind that the byte at buf[size] is actually
539              readable.  Discard the handle to avoid handle leak.  */
540           VALGRIND_DISCARD (VALGRIND_MAKE_READABLE (buf + size, 1));
541
542           inc->mapped = 1;
543         }
544       else
545 #endif
546         {
547           buf = (uchar *) xmalloc (size + 1);
548           offset = 0;
549           while (offset < size)
550             {
551               count = read (inc->fd, buf + offset, size - offset);
552               if (count < 0)
553                 goto perror_fail;
554               if (count == 0)
555                 {
556                   if (!STAT_SIZE_TOO_BIG (inc->st))
557                     cpp_error (pfile, DL_WARNING,
558                                "%s is shorter than expected", inc->name);
559                   size = offset;
560                   buf = xrealloc (buf, size + 1);
561                   inc->st.st_size = size;
562                   break;
563                 }
564               offset += count;
565             }
566           /* The lexer requires that the buffer be NUL-terminated.  */
567           buf[size] = '\0';
568         }
569     }
570   else if (S_ISBLK (inc->st.st_mode))
571     {
572       cpp_error (pfile, DL_ERROR, "%s is a block device", inc->name);
573       goto fail;
574     }
575   else
576     {
577       /* 8 kilobytes is a sensible starting size.  It ought to be
578          bigger than the kernel pipe buffer, and it's definitely
579          bigger than the majority of C source files.  */
580       size = 8 * 1024;
581
582       buf = (uchar *) xmalloc (size + 1);
583       offset = 0;
584       while ((count = read (inc->fd, buf + offset, size - offset)) > 0)
585         {
586           offset += count;
587           if (offset == size)
588             {
589               size *= 2;
590               buf = xrealloc (buf, size + 1);
591             }
592         }
593       if (count < 0)
594         goto perror_fail;
595
596       if (offset + 1 < size)
597         buf = xrealloc (buf, offset + 1);
598
599       /* The lexer requires that the buffer be NUL-terminated.  */
600       buf[offset] = '\0';
601       inc->st.st_size = offset;
602     }
603
604   inc->buffer = buf;
605   return 0;
606
607  perror_fail:
608   cpp_errno (pfile, DL_ERROR, inc->name);
609  fail:
610   return 1;
611 }
612
613 /* Drop INC's buffer from memory, if we are unlikely to need it again.  */
614 static void
615 purge_cache (inc)
616      struct include_file *inc;
617 {
618   if (inc->buffer)
619     {
620 #if MMAP_THRESHOLD
621       if (inc->mapped)
622         {
623           /* Undo the previous annotation for the
624              known-zero-byte-after-mmap.  Discard the handle to avoid
625              handle leak.  */
626           VALGRIND_DISCARD (VALGRIND_MAKE_NOACCESS (inc->buffer
627                                                     + inc->st.st_size, 1));
628           munmap ((PTR) inc->buffer, inc->st.st_size);
629         }
630       else
631 #endif
632         free ((PTR) inc->buffer);
633       inc->buffer = NULL;
634     }
635 }
636
637 /* Return 1 if the file named by FNAME has been included before in
638    any context, 0 otherwise.  */
639 int
640 cpp_included (pfile, fname)
641      cpp_reader *pfile;
642      const char *fname;
643 {
644   struct cpp_path *path;
645   char *name, *n;
646   splay_tree_node nd;
647
648   if (IS_ABSOLUTE_PATHNAME (fname))
649     {
650       /* Just look it up.  */
651       nd = splay_tree_lookup (pfile->all_include_files, (splay_tree_key) fname);
652       return (nd && nd->value);
653     }
654
655   /* Search directory path for the file.  */
656   name = (char *) alloca (strlen (fname) + pfile->max_include_len + 2);
657   for (path = pfile->quote_include; path; path = path->next)
658     {
659       memcpy (name, path->name, path->len);
660       name[path->len] = '/';
661       strcpy (&name[path->len + 1], fname);
662       if (CPP_OPTION (pfile, remap))
663         n = remap_filename (pfile, name, path);
664       else
665         n = name;
666
667       nd = splay_tree_lookup (pfile->all_include_files, (splay_tree_key) n);
668       if (nd && nd->value)
669         return 1;
670     }
671   return 0;
672 }
673
674 /* Search for HEADER.  Return 0 if there is no such file (or it's
675    un-openable), in which case an error code will be in errno.  If
676    there is no include path to use it returns NO_INCLUDE_PATH,
677    otherwise an include_file structure.  If this request originates
678    from a directive of TYPE #include_next, set INCLUDE_NEXT to true.  */
679 static struct include_file *
680 find_include_file (pfile, header, type)
681      cpp_reader *pfile;
682      const cpp_token *header;
683      enum include_type type;
684 {
685   const char *fname = (const char *) header->val.str.text;
686   struct cpp_path *path;
687   struct include_file *file;
688   char *name, *n;
689
690   if (IS_ABSOLUTE_PATHNAME (fname))
691     return open_file_pch (pfile, fname);
692
693   /* For #include_next, skip in the search path past the dir in which
694      the current file was found, but if it was found via an absolute
695      path use the normal search logic.  */
696   if (type == IT_INCLUDE_NEXT && pfile->buffer->inc->foundhere)
697     path = pfile->buffer->inc->foundhere->next;
698   else if (header->type == CPP_HEADER_NAME)
699     path = pfile->bracket_include;
700   else
701     path = search_from (pfile, type);
702
703   if (path == NULL)
704     {
705       cpp_error (pfile, DL_ERROR, "no include path in which to find %s",
706                  fname);
707       return NO_INCLUDE_PATH;
708     }
709
710   /* Search directory path for the file.  */
711   name = (char *) alloca (strlen (fname) + pfile->max_include_len + 2);
712   for (; path; path = path->next)
713     {
714       int len = path->len;
715       memcpy (name, path->name, len);
716       /* Don't turn / into // or // into ///; // may be a namespace
717          escape.  */
718       if (name[len-1] == '/')
719         len--;
720       name[len] = '/';
721       strcpy (&name[len + 1], fname);
722       if (CPP_OPTION (pfile, remap))
723         n = remap_filename (pfile, name, path);
724       else
725         n = name;
726
727       file = open_file_pch (pfile, n);
728       if (file)
729         {
730           file->foundhere = path;
731           return file;
732         }
733     }
734
735   return 0;
736 }
737
738 /* Not everyone who wants to set system-header-ness on a buffer can
739    see the details of a buffer.  This is an exported interface because
740    fix-header needs it.  */
741 void
742 cpp_make_system_header (pfile, syshdr, externc)
743      cpp_reader *pfile;
744      int syshdr, externc;
745 {
746   int flags = 0;
747
748   /* 1 = system header, 2 = system header to be treated as C.  */
749   if (syshdr)
750     flags = 1 + (externc != 0);
751   _cpp_do_file_change (pfile, LC_RENAME, pfile->map->to_file,
752                        SOURCE_LINE (pfile->map, pfile->line), flags);
753 }
754
755 /* Report on all files that might benefit from a multiple include guard.
756    Triggered by -H.  */
757 void
758 _cpp_report_missing_guards (pfile)
759      cpp_reader *pfile;
760 {
761   int banner = 0;
762   splay_tree_foreach (pfile->all_include_files, report_missing_guard,
763                       (PTR) &banner);
764 }
765
766 /* Callback function for splay_tree_foreach().  */
767 static int
768 report_missing_guard (n, b)
769      splay_tree_node n;
770      void *b;
771 {
772   struct include_file *f = (struct include_file *) n->value;
773   int *bannerp = (int *) b;
774
775   if (f && f->cmacro == 0 && f->include_count == 1)
776     {
777       if (*bannerp == 0)
778         {
779           fputs (_("Multiple include guards may be useful for:\n"), stderr);
780           *bannerp = 1;
781         }
782       fputs (f->name, stderr);
783       putc ('\n', stderr);
784     }
785   return 0;
786 }
787
788 /* Create a dependency for file FNAME, or issue an error message as
789    appropriate.  ANGLE_BRACKETS is nonzero if the file was bracketed
790    like <..>.  */
791 static void
792 handle_missing_header (pfile, fname, angle_brackets)
793      cpp_reader *pfile;
794      const char *fname;
795      int angle_brackets;
796 {
797   bool print_dep
798     = CPP_OPTION (pfile, deps.style) > (angle_brackets || pfile->map->sysp);
799
800   if (CPP_OPTION (pfile, deps.missing_files) && print_dep)
801     deps_add_dep (pfile->deps, fname);
802   /* If -M was specified, then don't count this as an error, because
803      we can still produce correct output.  Otherwise, we can't produce
804      correct output, because there may be dependencies we need inside
805      the missing file, and we don't know what directory this missing
806      file exists in.  */
807   else
808     cpp_errno (pfile, CPP_OPTION (pfile, deps.style) && ! print_dep
809                ? DL_WARNING: DL_ERROR, fname);
810 }
811
812 /* Handles #include-family directives (distinguished by TYPE),
813    including HEADER, and the command line -imacros and -include.
814    Returns true if a buffer was stacked.  */
815 bool
816 _cpp_execute_include (pfile, header, type)
817      cpp_reader *pfile;
818      const cpp_token *header;
819      enum include_type type;
820 {
821   bool stacked = false;
822   struct include_file *inc = find_include_file (pfile, header, type);
823
824   if (inc == 0)
825     handle_missing_header (pfile, (const char *) header->val.str.text,
826                            header->type == CPP_HEADER_NAME);
827   else if (inc != NO_INCLUDE_PATH)
828     {
829       stacked = stack_include_file (pfile, inc);
830
831       if (type == IT_IMPORT)
832         _cpp_never_reread (inc);
833     }
834
835   return stacked;
836 }
837
838 /* Locate HEADER, and determine whether it is newer than the current
839    file.  If it cannot be located or dated, return -1, if it is newer
840    newer, return 1, otherwise 0.  */
841 int
842 _cpp_compare_file_date (pfile, header)
843      cpp_reader *pfile;
844      const cpp_token *header;
845 {
846   struct include_file *inc = find_include_file (pfile, header, 0);
847
848   if (inc == NULL || inc == NO_INCLUDE_PATH)
849     return -1;
850
851   if (inc->fd > 0)
852     {
853       close (inc->fd);
854       inc->fd = -1;
855     }
856
857   return inc->st.st_mtime > pfile->buffer->inc->st.st_mtime;
858 }
859
860
861 /* Push an input buffer and load it up with the contents of FNAME.  If
862    FNAME is "", read standard input.  Return true if a buffer was
863    stacked.  */
864 bool
865 _cpp_read_file (pfile, fname)
866      cpp_reader *pfile;
867      const char *fname;
868 {
869   /* This uses open_file, because we don't allow a PCH to be used as
870      the toplevel compilation (that would prevent re-compiling an
871      existing PCH without deleting it first).  */
872   struct include_file *f = open_file (pfile, fname);
873
874   if (f == NULL)
875     {
876       cpp_errno (pfile, DL_ERROR, fname);
877       return false;
878     }
879
880   return stack_include_file (pfile, f);
881 }
882
883 /* Do appropriate cleanup when a file INC's buffer is popped off the
884    input stack.  */
885 void
886 _cpp_pop_file_buffer (pfile, inc)
887      cpp_reader *pfile;
888      struct include_file *inc;
889 {
890   /* Record the inclusion-preventing macro, which could be NULL
891      meaning no controlling macro.  */
892   if (pfile->mi_valid && inc->cmacro == NULL)
893     inc->cmacro = pfile->mi_cmacro;
894
895   /* Invalidate control macros in the #including file.  */
896   pfile->mi_valid = false;
897
898   inc->refcnt--;
899   if (inc->refcnt == 0 && DO_NOT_REREAD (inc))
900     purge_cache (inc);
901 }
902
903 /* Returns the first place in the include chain to start searching for
904    "" includes.  This involves stripping away the basename of the
905    current file, unless -I- was specified.
906
907    If we're handling -include or -imacros, use the "" chain, but with
908    the preprocessor's cwd prepended.  */
909 static struct cpp_path *
910 search_from (pfile, type)
911      cpp_reader *pfile;
912      enum include_type type;
913 {
914   cpp_buffer *buffer = pfile->buffer;
915   unsigned int dlen;
916
917   /* Command line uses the cwd, and does not cache the result.  */
918   if (type == IT_CMDLINE)
919     goto use_cwd;
920
921   /* Ignore the current file's directory?  */
922   if (pfile->quote_ignores_source_dir)
923     return pfile->quote_include;
924
925   if (! buffer->search_cached)
926     {
927       buffer->search_cached = 1;
928
929       dlen = lbasename (buffer->inc->name) - buffer->inc->name;
930
931       if (dlen)
932         {
933           /* We don't guarantee NAME is null-terminated.  This saves
934              allocating and freeing memory.  Drop a trailing '/'.  */
935           buffer->dir.name = (char *) buffer->inc->name;
936           if (dlen > 1)
937             dlen--;
938         }
939       else
940         {
941         use_cwd:
942           buffer->dir.name = (char *) ".";
943           dlen = 1;
944         }
945
946       if (dlen > pfile->max_include_len)
947         pfile->max_include_len = dlen;
948
949       buffer->dir.len = dlen;
950       buffer->dir.next = pfile->quote_include;
951       buffer->dir.sysp = pfile->map->sysp;
952     }
953
954   return &buffer->dir;
955 }
956
957 /* The file_name_map structure holds a mapping of file names for a
958    particular directory.  This mapping is read from the file named
959    FILE_NAME_MAP_FILE in that directory.  Such a file can be used to
960    map filenames on a file system with severe filename restrictions,
961    such as DOS.  The format of the file name map file is just a series
962    of lines with two tokens on each line.  The first token is the name
963    to map, and the second token is the actual name to use.  */
964 struct file_name_map {
965   struct file_name_map *map_next;
966   char *map_from;
967   char *map_to;
968 };
969
970 #define FILE_NAME_MAP_FILE "header.gcc"
971
972 /* Read a space delimited string of unlimited length from a stdio
973    file F.  */
974 static char *
975 read_filename_string (ch, f)
976      int ch;
977      FILE *f;
978 {
979   char *alloc, *set;
980   int len;
981
982   len = 20;
983   set = alloc = xmalloc (len + 1);
984   if (! is_space (ch))
985     {
986       *set++ = ch;
987       while ((ch = getc (f)) != EOF && ! is_space (ch))
988         {
989           if (set - alloc == len)
990             {
991               len *= 2;
992               alloc = xrealloc (alloc, len + 1);
993               set = alloc + len / 2;
994             }
995           *set++ = ch;
996         }
997     }
998   *set = '\0';
999   ungetc (ch, f);
1000   return alloc;
1001 }
1002
1003 /* This structure holds a linked list of file name maps, one per directory.  */
1004 struct file_name_map_list {
1005   struct file_name_map_list *map_list_next;
1006   char *map_list_name;
1007   struct file_name_map *map_list_map;
1008 };
1009
1010 /* Read the file name map file for DIRNAME.  */
1011 static struct file_name_map *
1012 read_name_map (pfile, dirname)
1013      cpp_reader *pfile;
1014      const char *dirname;
1015 {
1016   struct file_name_map_list *map_list_ptr;
1017   char *name;
1018   FILE *f;
1019
1020   /* Check the cache of directories, and mappings in their remap file.  */
1021   for (map_list_ptr = CPP_OPTION (pfile, map_list); map_list_ptr;
1022        map_list_ptr = map_list_ptr->map_list_next)
1023     if (! strcmp (map_list_ptr->map_list_name, dirname))
1024       return map_list_ptr->map_list_map;
1025
1026   map_list_ptr = ((struct file_name_map_list *)
1027                   xmalloc (sizeof (struct file_name_map_list)));
1028   map_list_ptr->map_list_name = xstrdup (dirname);
1029
1030   /* The end of the list ends in NULL.  */
1031   map_list_ptr->map_list_map = NULL;
1032
1033   name = (char *) alloca (strlen (dirname) + strlen (FILE_NAME_MAP_FILE) + 2);
1034   strcpy (name, dirname);
1035   if (*dirname)
1036     strcat (name, "/");
1037   strcat (name, FILE_NAME_MAP_FILE);
1038   f = fopen (name, "r");
1039
1040   /* Silently return NULL if we cannot open.  */
1041   if (f)
1042     {
1043       int ch;
1044
1045       while ((ch = getc (f)) != EOF)
1046         {
1047           char *from, *to;
1048           struct file_name_map *ptr;
1049
1050           if (is_space (ch))
1051             continue;
1052           from = read_filename_string (ch, f);
1053           while ((ch = getc (f)) != EOF && is_hspace (ch))
1054             ;
1055           to = read_filename_string (ch, f);
1056
1057           ptr = ((struct file_name_map *)
1058                  xmalloc (sizeof (struct file_name_map)));
1059           ptr->map_from = from;
1060
1061           /* Make the real filename absolute.  */
1062           if (IS_ABSOLUTE_PATHNAME (to))
1063             ptr->map_to = to;
1064           else
1065             {
1066               ptr->map_to = concat (dirname, "/", to, NULL);
1067               free (to);
1068             }
1069
1070           ptr->map_next = map_list_ptr->map_list_map;
1071           map_list_ptr->map_list_map = ptr;
1072
1073           while ((ch = getc (f)) != '\n')
1074             if (ch == EOF)
1075               break;
1076         }
1077       fclose (f);
1078     }
1079
1080   /* Add this information to the cache.  */
1081   map_list_ptr->map_list_next = CPP_OPTION (pfile, map_list);
1082   CPP_OPTION (pfile, map_list) = map_list_ptr;
1083
1084   return map_list_ptr->map_list_map;
1085 }
1086
1087 /* Remap an unsimplified path NAME based on the file_name_map (if any)
1088    for LOC.  */
1089 static char *
1090 remap_filename (pfile, name, loc)
1091      cpp_reader *pfile;
1092      char *name;
1093      struct cpp_path *loc;
1094 {
1095   struct file_name_map *map;
1096   const char *from, *p;
1097   char *dir;
1098
1099   if (! loc->name_map)
1100     {
1101       /* Get a null-terminated path.  */
1102       char *dname = alloca (loc->len + 1);
1103       memcpy (dname, loc->name, loc->len);
1104       dname[loc->len] = '\0';
1105
1106       loc->name_map = read_name_map (pfile, dname);
1107       if (! loc->name_map)
1108         return name;
1109     }
1110
1111   /* This works since NAME has not been simplified yet.  */
1112   from = name + loc->len + 1;
1113
1114   for (map = loc->name_map; map; map = map->map_next)
1115     if (!strcmp (map->map_from, from))
1116       return map->map_to;
1117
1118   /* Try to find a mapping file for the particular directory we are
1119      looking in.  Thus #include <sys/types.h> will look up sys/types.h
1120      in /usr/include/header.gcc and look up types.h in
1121      /usr/include/sys/header.gcc.  */
1122   p = strrchr (name, '/');
1123   if (!p)
1124     return name;
1125
1126   /* We know p != name as absolute paths don't call remap_filename.  */
1127   if (p == name)
1128     cpp_error (pfile, DL_ICE, "absolute file name in remap_filename");
1129
1130   dir = (char *) alloca (p - name + 1);
1131   memcpy (dir, name, p - name);
1132   dir[p - name] = '\0';
1133   from = p + 1;
1134
1135   for (map = read_name_map (pfile, dir); map; map = map->map_next)
1136     if (! strcmp (map->map_from, from))
1137       return map->map_to;
1138
1139   return name;
1140 }
1141
1142 /* Set the include chain for "" to QUOTE, for <> to BRACKET.  If
1143    QUOTE_IGNORES_SOURCE_DIR, then "" includes do not look in the
1144    directory of the including file.
1145
1146    If BRACKET does not lie in the QUOTE chain, it is set to QUOTE.  */
1147 void
1148 cpp_set_include_chains (pfile, quote, bracket, quote_ignores_source_dir)
1149      cpp_reader *pfile;
1150      cpp_path *quote, *bracket;
1151      int quote_ignores_source_dir;
1152 {
1153   pfile->quote_include = quote;
1154   pfile->bracket_include = quote;
1155   pfile->quote_ignores_source_dir = quote_ignores_source_dir;
1156   pfile->max_include_len = 0;
1157
1158   for (; quote; quote = quote->next)
1159     {
1160       quote->name_map = NULL;
1161       quote->len = strlen (quote->name);
1162       if (quote->len > pfile->max_include_len)
1163         pfile->max_include_len = quote->len;
1164       if (quote == bracket)
1165         pfile->bracket_include = bracket;
1166     }
1167 }
1168
1169 /* Returns true if it is safe to remove the final component of path,
1170    when it is followed by a ".." component.  We use lstat to avoid
1171    symlinks if we have it.  If not, we can still catch errors with
1172    stat ().  */
1173 static int
1174 remove_component_p (path)
1175      const char *path;
1176 {
1177   struct stat s;
1178   int result;
1179
1180 #ifdef HAVE_LSTAT
1181   result = lstat (path, &s);
1182 #else
1183   result = stat (path, &s);
1184 #endif
1185
1186   /* There's no guarantee that errno will be unchanged, even on
1187      success.  Cygwin's lstat(), for example, will often set errno to
1188      ENOSYS.  In case of success, reset errno to zero.  */
1189   if (result == 0)
1190     errno = 0;
1191
1192   return result == 0 && S_ISDIR (s.st_mode);
1193 }
1194
1195 /* Simplify a path name in place, deleting redundant components.  This
1196    reduces OS overhead and guarantees that equivalent paths compare
1197    the same (modulo symlinks).
1198
1199    Transforms made:
1200    foo/bar/../quux      foo/quux
1201    foo/./bar            foo/bar
1202    foo//bar             foo/bar
1203    /../quux             /quux
1204    //quux               //quux  (POSIX allows leading // as a namespace escape)
1205
1206    Guarantees no trailing slashes.  All transforms reduce the length
1207    of the string.  Returns PATH.  errno is 0 if no error occurred;
1208    nonzero if an error occurred when using stat () or lstat ().  */
1209 void
1210 cpp_simplify_path (path)
1211      char *path ATTRIBUTE_UNUSED;
1212 {
1213 #ifndef VMS
1214   char *from, *to;
1215   char *base, *orig_base;
1216   int absolute = 0;
1217
1218   errno = 0;
1219   /* Don't overflow the empty path by putting a '.' in it below.  */
1220   if (*path == '\0')
1221     return;
1222
1223 #if defined (HAVE_DOS_BASED_FILE_SYSTEM)
1224   /* Convert all backslashes to slashes.  */
1225   for (from = path; *from; from++)
1226     if (*from == '\\') *from = '/';
1227
1228   /* Skip over leading drive letter if present.  */
1229   if (ISALPHA (path[0]) && path[1] == ':')
1230     from = to = &path[2];
1231   else
1232     from = to = path;
1233 #else
1234   from = to = path;
1235 #endif
1236
1237   /* Remove redundant leading /s.  */
1238   if (*from == '/')
1239     {
1240       absolute = 1;
1241       to++;
1242       from++;
1243       if (*from == '/')
1244         {
1245           if (*++from == '/')
1246             /* 3 or more initial /s are equivalent to 1 /.  */
1247             while (*++from == '/');
1248           else
1249             /* On some hosts // differs from /; Posix allows this.  */
1250             to++;
1251         }
1252     }
1253
1254   base = orig_base = to;
1255   for (;;)
1256     {
1257       int move_base = 0;
1258
1259       while (*from == '/')
1260         from++;
1261
1262       if (*from == '\0')
1263         break;
1264
1265       if (*from == '.')
1266         {
1267           if (from[1] == '\0')
1268             break;
1269           if (from[1] == '/')
1270             {
1271               from += 2;
1272               continue;
1273             }
1274           else if (from[1] == '.' && (from[2] == '/' || from[2] == '\0'))
1275             {
1276               /* Don't simplify if there was no previous component.  */
1277               if (absolute && orig_base == to)
1278                 {
1279                   from += 2;
1280                   continue;
1281                 }
1282               /* Don't simplify if the previous component was "../",
1283                  or if an error has already occurred with (l)stat.  */
1284               if (base != to && errno == 0)
1285                 {
1286                   /* We don't back up if it's a symlink.  */
1287                   *to = '\0';
1288                   if (remove_component_p (path))
1289                     {
1290                       while (to > base && *to != '/')
1291                         to--;
1292                       from += 2;
1293                       continue;
1294                     }
1295                 }
1296               move_base = 1;
1297             }
1298         }
1299
1300       /* Add the component separator.  */
1301       if (to > orig_base)
1302         *to++ = '/';
1303
1304       /* Copy this component until the trailing null or '/'.  */
1305       while (*from != '\0' && *from != '/')
1306         *to++ = *from++;
1307
1308       if (move_base)
1309         base = to;
1310     }
1311
1312   /* Change the empty string to "." so that it is not treated as stdin.
1313      Null terminate.  */
1314   if (to == path)
1315     *to++ = '.';
1316   *to = '\0';
1317 #else  /* VMS */
1318   errno = 0;
1319 #endif /* !VMS  */
1320 }