OSDN Git Service

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