xref: /netbsd-src/external/gpl3/gcc.old/dist/libcpp/files.c (revision 76c7fc5f6b13ed0b1508e6b313e88e59977ed78e)
1 /* Part of CPP library.  File handling.
2    Copyright (C) 1986-2017 Free Software Foundation, Inc.
3    Written by Per Bothner, 1994.
4    Based on CCCP program by Paul Rubin, June 1986
5    Adapted to ANSI C, Richard Stallman, Jan 1987
6    Split out of cpplib.c, Zack Weinberg, Oct 1998
7    Reimplemented, Neil Booth, Jul 2003
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 3, 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; see the file COPYING3.  If not see
21 <http://www.gnu.org/licenses/>.  */
22 
23 #include "config.h"
24 #include "system.h"
25 #include "cpplib.h"
26 #include "internal.h"
27 #include "mkdeps.h"
28 #include "obstack.h"
29 #include "hashtab.h"
30 #include "md5.h"
31 #include <dirent.h>
32 
33 /* Variable length record files on VMS will have a stat size that includes
34    record control characters that won't be included in the read size.  */
35 #ifdef VMS
36 # define FAB_C_VAR 2 /* variable length records (see Starlet fabdef.h) */
37 # define STAT_SIZE_RELIABLE(ST) ((ST).st_fab_rfm != FAB_C_VAR)
38 #else
39 # define STAT_SIZE_RELIABLE(ST) true
40 #endif
41 
42 #ifdef __DJGPP__
43 #include <io.h>
44   /* For DJGPP redirected input is opened in text mode.  */
45 #  define set_stdin_to_binary_mode() \
46      if (! isatty (0)) setmode (0, O_BINARY)
47 #else
48 #  define set_stdin_to_binary_mode() /* Nothing */
49 #endif
50 
51 /* This structure represents a file searched for by CPP, whether it
52    exists or not.  An instance may be pointed to by more than one
53    cpp_file_hash_entry; at present no reference count is kept.  */
54 struct _cpp_file
55 {
56   /* Filename as given to #include or command line switch.  */
57   const char *name;
58 
59   /* The full path used to find the file.  */
60   const char *path;
61 
62   /* The full path of the pch file.  */
63   const char *pchname;
64 
65   /* The file's path with the basename stripped.  NULL if it hasn't
66      been calculated yet.  */
67   const char *dir_name;
68 
69   /* Chain through all files.  */
70   struct _cpp_file *next_file;
71 
72   /* The contents of NAME after calling read_file().  */
73   const uchar *buffer;
74 
75   /* Pointer to the real start of BUFFER.  read_file() might increment
76      BUFFER; when freeing, this this pointer must be used instead.  */
77   const uchar *buffer_start;
78 
79   /* The macro, if any, preventing re-inclusion.  */
80   const cpp_hashnode *cmacro;
81 
82   /* The directory in the search path where FILE was found.  Used for
83      #include_next and determining whether a header is a system
84      header.  */
85   cpp_dir *dir;
86 
87   /* As filled in by stat(2) for the file.  */
88   struct stat st;
89 
90   /* File descriptor.  Invalid if -1, otherwise open.  */
91   int fd;
92 
93   /* Zero if this file was successfully opened and stat()-ed,
94      otherwise errno obtained from failure.  */
95   int err_no;
96 
97   /* Number of times the file has been stacked for preprocessing.  */
98   unsigned short stack_count;
99 
100   /* If opened with #import or contains #pragma once.  */
101   bool once_only;
102 
103   /* If read() failed before.  */
104   bool dont_read;
105 
106   /* If this file is the main file.  */
107   bool main_file;
108 
109   /* If BUFFER above contains the true contents of the file.  */
110   bool buffer_valid;
111 
112   /* If this file is implicitly preincluded.  */
113   bool implicit_preinclude;
114 };
115 
116 /* A singly-linked list for all searches for a given file name, with
117    its head pointed to by a slot in FILE_HASH.  The file name is what
118    appeared between the quotes in a #include directive; it can be
119    determined implicitly from the hash table location or explicitly
120    from FILE->name.
121 
122    FILE is a structure containing details about the file that was
123    found with that search, or details of how the search failed.
124 
125    START_DIR is the starting location of the search in the include
126    chain.  The current directories for "" includes are also hashed in
127    the hash table and therefore unique.  Files that are looked up
128    without using a search path, such as absolute filenames and file
129    names from the command line share a special starting directory so
130    they don't cause cache hits with normal include-chain lookups.
131 
132    If START_DIR is NULL then the entry is for a directory, not a file,
133    and the directory is in DIR.  Since the starting point in a file
134    lookup chain is never NULL, this means that simple pointer
135    comparisons against START_DIR can be made to determine cache hits
136    in file lookups.
137 
138    If a cache lookup fails because of e.g. an extra "./" in the path,
139    then nothing will break.  It is just less efficient as CPP will
140    have to do more work re-preprocessing the file, and/or comparing
141    its contents against earlier once-only files.
142 */
143 struct cpp_file_hash_entry
144 {
145   struct cpp_file_hash_entry *next;
146   cpp_dir *start_dir;
147   source_location location;
148   union
149   {
150     _cpp_file *file;
151     cpp_dir *dir;
152   } u;
153 };
154 
155 /* Number of entries to put in a cpp_file_hash_entry pool.  */
156 #define FILE_HASH_POOL_SIZE 127
157 
158 /* A file hash entry pool.  We allocate cpp_file_hash_entry object from
159    one of these.  */
160 struct file_hash_entry_pool
161 {
162   /* Number of entries used from this pool.  */
163   unsigned int file_hash_entries_used;
164   /* Next pool in the chain; used when freeing.  */
165   struct file_hash_entry_pool *next;
166   /* The memory pool.  */
167   struct cpp_file_hash_entry pool[FILE_HASH_POOL_SIZE];
168 };
169 
170 static bool open_file (_cpp_file *file);
171 static bool pch_open_file (cpp_reader *pfile, _cpp_file *file,
172 			   bool *invalid_pch);
173 static bool find_file_in_dir (cpp_reader *pfile, _cpp_file *file,
174 			      bool *invalid_pch, source_location loc);
175 static bool read_file_guts (cpp_reader *pfile, _cpp_file *file,
176 			    source_location loc);
177 static bool read_file (cpp_reader *pfile, _cpp_file *file,
178 		       source_location loc);
179 static bool should_stack_file (cpp_reader *, _cpp_file *file, bool import,
180 			       source_location loc);
181 static struct cpp_dir *search_path_head (cpp_reader *, const char *fname,
182 				 int angle_brackets, enum include_type);
183 static const char *dir_name_of_file (_cpp_file *file);
184 static void open_file_failed (cpp_reader *pfile, _cpp_file *file, int,
185 			      source_location);
186 static struct cpp_file_hash_entry *search_cache (struct cpp_file_hash_entry *head,
187 					     const cpp_dir *start_dir);
188 static _cpp_file *make_cpp_file (cpp_reader *, cpp_dir *, const char *fname);
189 static void destroy_cpp_file (_cpp_file *);
190 static cpp_dir *make_cpp_dir (cpp_reader *, const char *dir_name, int sysp);
191 static void allocate_file_hash_entries (cpp_reader *pfile);
192 static struct cpp_file_hash_entry *new_file_hash_entry (cpp_reader *pfile);
193 static int report_missing_guard (void **slot, void *b);
194 static hashval_t file_hash_hash (const void *p);
195 static int file_hash_eq (const void *p, const void *q);
196 static char *read_filename_string (int ch, FILE *f);
197 static void read_name_map (cpp_dir *dir);
198 static char *remap_filename (cpp_reader *pfile, _cpp_file *file);
199 static char *append_file_to_dir (const char *fname, cpp_dir *dir);
200 static bool validate_pch (cpp_reader *, _cpp_file *file, const char *pchname);
201 static int pchf_save_compare (const void *e1, const void *e2);
202 static int pchf_compare (const void *d_p, const void *e_p);
203 static bool check_file_against_entries (cpp_reader *, _cpp_file *, bool);
204 
205 /* Given a filename in FILE->PATH, with the empty string interpreted
206    as <stdin>, open it.
207 
208    On success FILE contains an open file descriptor and stat
209    information for the file.  On failure the file descriptor is -1 and
210    the appropriate errno is also stored in FILE.  Returns TRUE iff
211    successful.
212 
213    We used to open files in nonblocking mode, but that caused more
214    problems than it solved.  Do take care not to acquire a controlling
215    terminal by mistake (this can't happen on sane systems, but
216    paranoia is a virtue).
217 
218    Use the three-argument form of open even though we aren't
219    specifying O_CREAT, to defend against broken system headers.
220 
221    O_BINARY tells some runtime libraries (notably DJGPP) not to do
222    newline translation; we can handle DOS line breaks just fine
223    ourselves.  */
224 static bool
225 open_file (_cpp_file *file)
226 {
227   const char *cpp_restricted;
228 
229   cpp_restricted = getenv ("CPP_RESTRICTED");
230 
231   if (file->path[0] == '\0')
232     {
233       file->fd = 0;
234       set_stdin_to_binary_mode ();
235     }
236   else
237     file->fd = open (file->path, O_RDONLY | O_NOCTTY | O_BINARY
238 		     | (cpp_restricted != NULL) ? O_NONBLOCK : 0, 0666);
239 
240 
241   if (file->fd != -1)
242     {
243       if (fstat (file->fd, &file->st) == 0)
244 	{
245 	  if (!S_ISDIR (file->st.st_mode))
246 	  if (cpp_restricted != NULL
247 	      ? S_ISREG (file->st.st_mode) : !S_ISDIR (file->st.st_mode))
248 
249 	    {
250 	      if (cpp_restricted)
251 		fcntl(file->fd, F_SETFL,
252 		      fcntl(file->fd, F_GETFL, 0) & ~O_NONBLOCK);
253 	      file->err_no = 0;
254 	      return true;
255 	    }
256 
257 	  /* Ignore a directory and continue the search.  The file we're
258 	     looking for may be elsewhere in the search path.  */
259 	  errno = ENOENT;
260 	}
261 
262       close (file->fd);
263       file->fd = -1;
264     }
265 #if defined(_WIN32) && !defined(__CYGWIN__)
266   else if (errno == EACCES)
267     {
268       /* On most UNIX systems, open succeeds on a directory.  Above,
269          we check if we have opened a directory and if so, set errno
270          to ENOENT.  However, on Windows, opening a directory
271          fails with EACCES.  We want to return ENOENT in that
272          case too.  */
273       if (stat (file->path, &file->st) == 0
274           && S_ISDIR (file->st.st_mode))
275         errno = ENOENT;
276       else
277 	/* The call to stat may have reset errno.  */
278 	errno = EACCES;
279     }
280 #endif
281   else if (errno == ENOTDIR)
282     errno = ENOENT;
283 
284   file->err_no = errno;
285 
286   return false;
287 }
288 
289 /* Temporary PCH intercept of opening a file.  Try to find a PCH file
290    based on FILE->name and FILE->dir, and test those found for
291    validity using PFILE->cb.valid_pch.  Return true iff a valid file is
292    found.  Set *INVALID_PCH if a PCH file is found but wasn't valid.  */
293 
294 static bool
295 pch_open_file (cpp_reader *pfile, _cpp_file *file, bool *invalid_pch)
296 {
297   static const char extension[] = ".gch";
298   const char *path = file->path;
299   size_t len, flen;
300   char *pchname;
301   struct stat st;
302   bool valid = false;
303 
304   /* No PCH on <stdin> or if not requested.  */
305   if (file->name[0] == '\0' || !pfile->cb.valid_pch)
306     return false;
307 
308   /* If the file is not included as first include from either the toplevel
309      file or the command-line it is not a valid use of PCH.  */
310   for (_cpp_file *f = pfile->all_files; f; f = f->next_file)
311     if (f->implicit_preinclude)
312       continue;
313     else if (f->main_file)
314       break;
315     else
316       return false;
317 
318   flen = strlen (path);
319   len = flen + sizeof (extension);
320   pchname = XNEWVEC (char, len);
321   memcpy (pchname, path, flen);
322   memcpy (pchname + flen, extension, sizeof (extension));
323 
324   if (stat (pchname, &st) == 0)
325     {
326       DIR *pchdir;
327       struct dirent *d;
328       size_t dlen, plen = len;
329 
330       if (!S_ISDIR (st.st_mode))
331 	valid = validate_pch (pfile, file, pchname);
332       else if ((pchdir = opendir (pchname)) != NULL)
333 	{
334 	  pchname[plen - 1] = '/';
335 	  while ((d = readdir (pchdir)) != NULL)
336 	    {
337 	      dlen = strlen (d->d_name) + 1;
338 	      if ((strcmp (d->d_name, ".") == 0)
339 		  || (strcmp (d->d_name, "..") == 0))
340 		continue;
341 	      if (dlen + plen > len)
342 		{
343 		  len += dlen + 64;
344 		  pchname = XRESIZEVEC (char, pchname, len);
345 		}
346 	      memcpy (pchname + plen, d->d_name, dlen);
347 	      valid = validate_pch (pfile, file, pchname);
348 	      if (valid)
349 		break;
350 	    }
351 	  closedir (pchdir);
352 	}
353       if (!valid)
354 	*invalid_pch = true;
355     }
356 
357   if (valid)
358     file->pchname = pchname;
359   else
360     free (pchname);
361 
362   return valid;
363 }
364 
365 /* Canonicalize the path to FILE.  Return the canonical form if it is
366    shorter, otherwise return NULL.  This function does NOT free the
367    memory pointed by FILE.  */
368 
369 static char *
370 maybe_shorter_path (const char * file)
371 {
372   char * file2 = lrealpath (file);
373   if (file2 && strlen (file2) < strlen (file))
374     {
375       return file2;
376     }
377   else
378     {
379       free (file2);
380       return NULL;
381     }
382 }
383 
384 /* Try to open the path FILE->name appended to FILE->dir.  This is
385    where remap and PCH intercept the file lookup process.  Return true
386    if the file was found, whether or not the open was successful.
387    Set *INVALID_PCH to true if a PCH file is found but wasn't valid.
388    Use LOC when emitting any diagnostics.  */
389 
390 static bool
391 find_file_in_dir (cpp_reader *pfile, _cpp_file *file, bool *invalid_pch,
392 		  source_location loc)
393 {
394   char *path;
395 
396   if (CPP_OPTION (pfile, remap) && (path = remap_filename (pfile, file)))
397     ;
398   else
399     if (file->dir->construct)
400       path = file->dir->construct (file->name, file->dir);
401     else
402       path = append_file_to_dir (file->name, file->dir);
403 
404   if (path)
405     {
406       hashval_t hv;
407       char *copy;
408       void **pp;
409 
410       /* We try to canonicalize system headers.  For DOS based file
411        * system, we always try to shorten non-system headers, as DOS
412        * has a tighter constraint on max path length.  */
413       if ((CPP_OPTION (pfile, canonical_system_headers) && file->dir->sysp)
414 #ifdef HAVE_DOS_BASED_FILE_SYSTEM
415 	  || !file->dir->sysp
416 #endif
417 	 )
418 	{
419 	  char * canonical_path = maybe_shorter_path (path);
420 	  if (canonical_path)
421 	    {
422 	      /* The canonical path was newly allocated.  Let's free the
423 		 non-canonical one.  */
424 	      free (path);
425 	      path = canonical_path;
426 	    }
427 	}
428 
429       hv = htab_hash_string (path);
430       if (htab_find_with_hash (pfile->nonexistent_file_hash, path, hv) != NULL)
431 	{
432 	  file->err_no = ENOENT;
433 	  return false;
434 	}
435 
436       file->path = path;
437       if (pch_open_file (pfile, file, invalid_pch))
438 	return true;
439 
440       if (open_file (file))
441 	return true;
442 
443       if (file->err_no != ENOENT)
444 	{
445 	  open_file_failed (pfile, file, 0, loc);
446 	  return true;
447 	}
448 
449       /* We copy the path name onto an obstack partly so that we don't
450 	 leak the memory, but mostly so that we don't fragment the
451 	 heap.  */
452       copy = (char *) obstack_copy0 (&pfile->nonexistent_file_ob, path,
453 				     strlen (path));
454       free (path);
455       pp = htab_find_slot_with_hash (pfile->nonexistent_file_hash,
456 				     copy, hv, INSERT);
457       *pp = copy;
458 
459       file->path = file->name;
460     }
461   else
462     {
463       file->err_no = ENOENT;
464       file->path = NULL;
465     }
466 
467   return false;
468 }
469 
470 /* Return tue iff the missing_header callback found the given HEADER.  */
471 static bool
472 search_path_exhausted (cpp_reader *pfile, const char *header, _cpp_file *file)
473 {
474   missing_header_cb func = pfile->cb.missing_header;
475 
476   /* When the regular search path doesn't work, try context dependent
477      headers search paths.  */
478   if (func
479       && file->dir == NULL)
480     {
481       if ((file->path = func (pfile, header, &file->dir)) != NULL)
482 	{
483 	  if (open_file (file))
484 	    return true;
485 	  free ((void *)file->path);
486 	}
487       file->path = file->name;
488     }
489 
490   return false;
491 }
492 
493 bool
494 _cpp_find_failed (_cpp_file *file)
495 {
496   return file->err_no != 0;
497 }
498 
499 /* Given a filename FNAME search for such a file in the include path
500    starting from START_DIR.  If FNAME is the empty string it is
501    interpreted as STDIN if START_DIR is PFILE->no_search_path.
502 
503    If the file is not found in the file cache fall back to the O/S and
504    add the result to our cache.
505 
506    If the file was not found in the filesystem, or there was an error
507    opening it, then ERR_NO is nonzero and FD is -1.  If the file was
508    found, then ERR_NO is zero and FD could be -1 or an open file
509    descriptor.  FD can be -1 if the file was found in the cache and
510    had previously been closed.  To open it again pass the return value
511    to open_file().
512 
513    If IMPLICIT_PREINCLUDE then it is OK for the file to be missing.
514    If present, it is OK for a precompiled header to be included after
515    it.
516 
517    Use LOC as the location for any errors.  */
518 
519 _cpp_file *
520 _cpp_find_file (cpp_reader *pfile, const char *fname, cpp_dir *start_dir,
521 		bool fake, int angle_brackets, bool implicit_preinclude,
522 		source_location loc)
523 {
524   struct cpp_file_hash_entry *entry;
525   void **hash_slot;
526   _cpp_file *file;
527   bool invalid_pch = false;
528   bool saw_bracket_include = false;
529   bool saw_quote_include = false;
530   struct cpp_dir *found_in_cache = NULL;
531 
532   /* Ensure we get no confusion between cached files and directories.  */
533   if (start_dir == NULL)
534     cpp_error_at (pfile, CPP_DL_ICE, loc, "NULL directory in find_file");
535 
536   hash_slot
537     = htab_find_slot_with_hash (pfile->file_hash, fname,
538 				htab_hash_string (fname), INSERT);
539 
540   /* First check the cache before we resort to memory allocation.  */
541   entry = search_cache ((struct cpp_file_hash_entry *) *hash_slot, start_dir);
542   if (entry)
543     return entry->u.file;
544 
545   file = make_cpp_file (pfile, start_dir, fname);
546   file->implicit_preinclude
547     = (implicit_preinclude
548        || (pfile->buffer
549 	   && pfile->buffer->file->implicit_preinclude));
550 
551   /* Try each path in the include chain.  */
552   for (; !fake ;)
553     {
554       if (find_file_in_dir (pfile, file, &invalid_pch, loc))
555 	break;
556 
557       file->dir = file->dir->next;
558       if (file->dir == NULL)
559 	{
560 	  if (search_path_exhausted (pfile, fname, file))
561 	    {
562 	      /* Although this file must not go in the cache, because
563 		 the file found might depend on things (like the current file)
564 		 that aren't represented in the cache, it still has to go in
565 		 the list of all files so that #import works.  */
566 	      file->next_file = pfile->all_files;
567 	      pfile->all_files = file;
568 	      if (*hash_slot == NULL)
569 		{
570 		  /* If *hash_slot is NULL, the above htab_find_slot_with_hash
571 		     call just created the slot, but we aren't going to store
572 		     there anything, so need to remove the newly created entry.
573 		     htab_clear_slot requires that it is non-NULL, so store
574 		     there some non-NULL pointer, htab_clear_slot will
575 		     overwrite it immediately.  */
576 		  *hash_slot = file;
577 		  htab_clear_slot (pfile->file_hash, hash_slot);
578 		}
579 	      return file;
580 	    }
581 
582 	  if (invalid_pch)
583 	    {
584 	      cpp_error (pfile, CPP_DL_ERROR,
585 	       "one or more PCH files were found, but they were invalid");
586 	      if (!cpp_get_options (pfile)->warn_invalid_pch)
587 		cpp_error (pfile, CPP_DL_ERROR,
588 			   "use -Winvalid-pch for more information");
589 	    }
590 	  if (implicit_preinclude)
591 	    {
592 	      free ((char *) file->name);
593 	      free (file);
594 	      if (*hash_slot == NULL)
595 		{
596 		  /* See comment on the above htab_clear_slot call.  */
597 		  *hash_slot = file;
598 		  htab_clear_slot (pfile->file_hash, hash_slot);
599 		}
600 	      return NULL;
601 	    }
602 	  else
603 	    open_file_failed (pfile, file, angle_brackets, loc);
604 	  break;
605 	}
606 
607       /* Only check the cache for the starting location (done above)
608 	 and the quote and bracket chain heads because there are no
609 	 other possible starting points for searches.  */
610       if (file->dir == pfile->bracket_include)
611 	saw_bracket_include = true;
612       else if (file->dir == pfile->quote_include)
613 	saw_quote_include = true;
614       else
615 	continue;
616 
617       entry = search_cache ((struct cpp_file_hash_entry *) *hash_slot, file->dir);
618       if (entry)
619 	{
620 	  found_in_cache = file->dir;
621 	  break;
622 	}
623     }
624 
625   if (entry)
626     {
627       /* Cache for START_DIR too, sharing the _cpp_file structure.  */
628       free ((char *) file->name);
629       free (file);
630       file = entry->u.file;
631     }
632   else
633     {
634       /* This is a new file; put it in the list.  */
635       file->next_file = pfile->all_files;
636       pfile->all_files = file;
637     }
638 
639   /* Store this new result in the hash table.  */
640   entry = new_file_hash_entry (pfile);
641   entry->next = (struct cpp_file_hash_entry *) *hash_slot;
642   entry->start_dir = start_dir;
643   entry->location = pfile->line_table->highest_location;
644   entry->u.file = file;
645   *hash_slot = (void *) entry;
646 
647   /* If we passed the quote or bracket chain heads, cache them also.
648      This speeds up processing if there are lots of -I options.  */
649   if (saw_bracket_include
650       && pfile->bracket_include != start_dir
651       && found_in_cache != pfile->bracket_include)
652     {
653       entry = new_file_hash_entry (pfile);
654       entry->next = (struct cpp_file_hash_entry *) *hash_slot;
655       entry->start_dir = pfile->bracket_include;
656       entry->location = pfile->line_table->highest_location;
657       entry->u.file = file;
658       *hash_slot = (void *) entry;
659     }
660   if (saw_quote_include
661       && pfile->quote_include != start_dir
662       && found_in_cache != pfile->quote_include)
663     {
664       entry = new_file_hash_entry (pfile);
665       entry->next = (struct cpp_file_hash_entry *) *hash_slot;
666       entry->start_dir = pfile->quote_include;
667       entry->location = pfile->line_table->highest_location;
668       entry->u.file = file;
669       *hash_slot = (void *) entry;
670     }
671 
672   return file;
673 }
674 
675 /* Read a file into FILE->buffer, returning true on success.
676 
677    If FILE->fd is something weird, like a block device, we don't want
678    to read it at all.  Don't even try to figure out what something is,
679    except for plain files and block devices, since there is no
680    reliable portable way of doing this.
681 
682    Use LOC for any diagnostics.
683 
684    FIXME: Flush file cache and try again if we run out of memory.  */
685 static bool
686 read_file_guts (cpp_reader *pfile, _cpp_file *file, source_location loc)
687 {
688   ssize_t size, total, count;
689   uchar *buf;
690   bool regular;
691 
692   if (S_ISBLK (file->st.st_mode))
693     {
694       cpp_error_at (pfile, CPP_DL_ERROR, loc,
695 		    "%s is a block device", file->path);
696       return false;
697     }
698 
699   regular = S_ISREG (file->st.st_mode) != 0;
700   if (regular)
701     {
702       /* off_t might have a wider range than ssize_t - in other words,
703 	 the max size of a file might be bigger than the address
704 	 space.  We can't handle a file that large.  (Anyone with
705 	 a single source file bigger than 2GB needs to rethink
706 	 their coding style.)  Some systems (e.g. AIX 4.1) define
707 	 SSIZE_MAX to be much smaller than the actual range of the
708 	 type.  Use INTTYPE_MAXIMUM unconditionally to ensure this
709 	 does not bite us.  */
710       if (file->st.st_size > INTTYPE_MAXIMUM (ssize_t))
711 	{
712 	  cpp_error_at (pfile, CPP_DL_ERROR, loc,
713 			"%s is too large", file->path);
714 	  return false;
715 	}
716 
717       size = file->st.st_size;
718     }
719   else
720     /* 8 kilobytes is a sensible starting size.  It ought to be bigger
721        than the kernel pipe buffer, and it's definitely bigger than
722        the majority of C source files.  */
723     size = 8 * 1024;
724 
725   /* The + 16 here is space for the final '\n' and 15 bytes of padding,
726      used to quiet warnings from valgrind or Address Sanitizer, when the
727      optimized lexer accesses aligned 16-byte memory chunks, including
728      the bytes after the malloced, area, and stops lexing on '\n'.  */
729   buf = XNEWVEC (uchar, size + 16);
730   total = 0;
731   while ((count = read (file->fd, buf + total, size - total)) > 0)
732     {
733       total += count;
734 
735       if (total == size)
736 	{
737 	  if (regular)
738 	    break;
739 	  size *= 2;
740 	  buf = XRESIZEVEC (uchar, buf, size + 16);
741 	}
742     }
743 
744   if (count < 0)
745     {
746       cpp_errno_filename (pfile, CPP_DL_ERROR, file->path, loc);
747       free (buf);
748       return false;
749     }
750 
751   if (regular && total != size && STAT_SIZE_RELIABLE (file->st))
752     cpp_error_at (pfile, CPP_DL_WARNING, loc,
753 	       "%s is shorter than expected", file->path);
754 
755   file->buffer = _cpp_convert_input (pfile,
756 				     CPP_OPTION (pfile, input_charset),
757 				     buf, size + 16, total,
758 				     &file->buffer_start,
759 				     &file->st.st_size);
760   file->buffer_valid = true;
761 
762   return true;
763 }
764 
765 /* Convenience wrapper around read_file_guts that opens the file if
766    necessary and closes the file descriptor after reading.  FILE must
767    have been passed through find_file() at some stage.  Use LOC for
768    any diagnostics.  */
769 static bool
770 read_file (cpp_reader *pfile, _cpp_file *file, source_location loc)
771 {
772   /* If we already have its contents in memory, succeed immediately.  */
773   if (file->buffer_valid)
774     return true;
775 
776   /* If an earlier read failed for some reason don't try again.  */
777   if (file->dont_read || file->err_no)
778     return false;
779 
780   if (file->fd == -1 && !open_file (file))
781     {
782       open_file_failed (pfile, file, 0, loc);
783       return false;
784     }
785 
786   file->dont_read = !read_file_guts (pfile, file, loc);
787   close (file->fd);
788   file->fd = -1;
789 
790   return !file->dont_read;
791 }
792 
793 /* Returns TRUE if FILE's contents have been successfully placed in
794    FILE->buffer and the file should be stacked, otherwise false.
795    Use LOC for any diagnostics.  */
796 static bool
797 should_stack_file (cpp_reader *pfile, _cpp_file *file, bool import,
798 		   source_location loc)
799 {
800   _cpp_file *f;
801 
802   /* Skip once-only files.  */
803   if (file->once_only)
804     return false;
805 
806   /* We must mark the file once-only if #import now, before header
807      guard checks.  Otherwise, undefining the header guard might
808      cause the file to be re-stacked.  */
809   if (import)
810     {
811       _cpp_mark_file_once_only (pfile, file);
812 
813       /* Don't stack files that have been stacked before.  */
814       if (file->stack_count)
815 	return false;
816     }
817 
818   /* Skip if the file had a header guard and the macro is defined.
819      PCH relies on this appearing before the PCH handler below.  */
820   if (file->cmacro && file->cmacro->type == NT_MACRO)
821     return false;
822 
823   /* Handle PCH files immediately; don't stack them.  */
824   if (file->pchname)
825     {
826       pfile->cb.read_pch (pfile, file->pchname, file->fd, file->path);
827       file->fd = -1;
828       free ((void *) file->pchname);
829       file->pchname = NULL;
830       return false;
831     }
832 
833   if (!read_file (pfile, file, loc))
834     return false;
835 
836   /* Check the file against the PCH file.  This is done before
837      checking against files we've already seen, since it may save on
838      I/O.  */
839   if (check_file_against_entries (pfile, file, import))
840     {
841       /* If this isn't a #import, but yet we can't include the file,
842 	 that means that it was #import-ed in the PCH file,
843 	 so we can never include it again.  */
844       if (! import)
845 	_cpp_mark_file_once_only (pfile, file);
846       return false;
847     }
848 
849   /* Now we've read the file's contents, we can stack it if there
850      are no once-only files.  */
851   if (!pfile->seen_once_only)
852     return true;
853 
854   /* We may have read the file under a different name.  Look
855      for likely candidates and compare file contents to be sure.  */
856   for (f = pfile->all_files; f; f = f->next_file)
857     {
858       if (f == file)
859 	continue;
860 
861       if ((import || f->once_only)
862 	  && f->err_no == 0
863 	  && f->st.st_mtime == file->st.st_mtime
864 	  && f->st.st_size == file->st.st_size)
865 	{
866 	  _cpp_file *ref_file;
867 	  bool same_file_p = false;
868 
869 	  if (f->buffer && !f->buffer_valid)
870 	    {
871 	      /* We already have a buffer but it is not valid, because
872 		 the file is still stacked.  Make a new one.  */
873 	      ref_file = make_cpp_file (pfile, f->dir, f->name);
874 	      ref_file->path = f->path;
875 	    }
876 	  else
877 	    /* The file is not stacked anymore.  We can reuse it.  */
878 	    ref_file = f;
879 
880 	  same_file_p = read_file (pfile, ref_file, loc)
881 			/* Size might have changed in read_file().  */
882 			&& ref_file->st.st_size == file->st.st_size
883 			&& !memcmp (ref_file->buffer,
884 				    file->buffer,
885 				    file->st.st_size);
886 
887 	  if (f->buffer && !f->buffer_valid)
888 	    {
889 	      ref_file->path = 0;
890 	      destroy_cpp_file (ref_file);
891 	    }
892 
893 	  if (same_file_p)
894 	    break;
895 	}
896     }
897 
898   return f == NULL;
899 }
900 
901 /* Place the file referenced by FILE into a new buffer on the buffer
902    stack if possible.  IMPORT is true if this stacking attempt is
903    because of a #import directive.  Returns true if a buffer is
904    stacked.  Use LOC for any diagnostics.  */
905 bool
906 _cpp_stack_file (cpp_reader *pfile, _cpp_file *file, bool import,
907 		 source_location loc)
908 {
909   cpp_buffer *buffer;
910   int sysp;
911 
912   if (!should_stack_file (pfile, file, import, loc))
913       return false;
914 
915   if (pfile->buffer == NULL || file->dir == NULL)
916     sysp = 0;
917   else
918     sysp = MAX (pfile->buffer->sysp,  file->dir->sysp);
919 
920   /* Add the file to the dependencies on its first inclusion.  */
921   if (CPP_OPTION (pfile, deps.style) > !!sysp && !file->stack_count)
922     {
923       if (!file->main_file || !CPP_OPTION (pfile, deps.ignore_main_file))
924 	deps_add_dep (pfile->deps, file->path);
925     }
926 
927   /* Clear buffer_valid since _cpp_clean_line messes it up.  */
928   file->buffer_valid = false;
929   file->stack_count++;
930 
931   /* Stack the buffer.  */
932   buffer = cpp_push_buffer (pfile, file->buffer, file->st.st_size,
933 			    CPP_OPTION (pfile, preprocessed)
934 			    && !CPP_OPTION (pfile, directives_only));
935   buffer->file = file;
936   buffer->sysp = sysp;
937   buffer->to_free = file->buffer_start;
938 
939   /* Initialize controlling macro state.  */
940   pfile->mi_valid = true;
941   pfile->mi_cmacro = 0;
942 
943   /* Generate the call back.  */
944   _cpp_do_file_change (pfile, LC_ENTER, file->path, 1, sysp);
945 
946   return true;
947 }
948 
949 /* Mark FILE to be included once only.  */
950 void
951 _cpp_mark_file_once_only (cpp_reader *pfile, _cpp_file *file)
952 {
953   pfile->seen_once_only = true;
954   file->once_only = true;
955 }
956 
957 /* Return the directory from which searching for FNAME should start,
958    considering the directive TYPE and ANGLE_BRACKETS.  If there is
959    nothing left in the path, returns NULL.  */
960 static struct cpp_dir *
961 search_path_head (cpp_reader *pfile, const char *fname, int angle_brackets,
962 		  enum include_type type)
963 {
964   cpp_dir *dir;
965   _cpp_file *file;
966 
967   if (IS_ABSOLUTE_PATH (fname))
968     return &pfile->no_search_path;
969 
970   /* pfile->buffer is NULL when processing an -include command-line flag.  */
971   file = pfile->buffer == NULL ? pfile->main_file : pfile->buffer->file;
972 
973   /* For #include_next, skip in the search path past the dir in which
974      the current file was found, but if it was found via an absolute
975      path use the normal search logic.  */
976   if (type == IT_INCLUDE_NEXT && file->dir
977       && file->dir != &pfile->no_search_path)
978     dir = file->dir->next;
979   else if (angle_brackets)
980     dir = pfile->bracket_include;
981   else if (type == IT_CMDLINE)
982     /* -include and -imacros use the #include "" chain with the
983        preprocessor's cwd prepended.  */
984     return make_cpp_dir (pfile, "./", false);
985   else if (pfile->quote_ignores_source_dir)
986     dir = pfile->quote_include;
987   else
988     return make_cpp_dir (pfile, dir_name_of_file (file),
989 			 pfile->buffer ? pfile->buffer->sysp : 0);
990 
991   if (dir == NULL)
992     cpp_error (pfile, CPP_DL_ERROR,
993 	       "no include path in which to search for %s", fname);
994 
995   return dir;
996 }
997 
998 /* Strip the basename from the file's path.  It ends with a slash if
999    of nonzero length.  Note that this procedure also works for
1000    <stdin>, which is represented by the empty string.  */
1001 static const char *
1002 dir_name_of_file (_cpp_file *file)
1003 {
1004   if (!file->dir_name)
1005     {
1006       size_t len = lbasename (file->path) - file->path;
1007       char *dir_name = XNEWVEC (char, len + 1);
1008 
1009       memcpy (dir_name, file->path, len);
1010       dir_name[len] = '\0';
1011       file->dir_name = dir_name;
1012     }
1013 
1014   return file->dir_name;
1015 }
1016 
1017 /* Handles #include-family directives (distinguished by TYPE),
1018    including HEADER, and the command line -imacros and -include.
1019    Returns true if a buffer was stacked.  */
1020 bool
1021 _cpp_stack_include (cpp_reader *pfile, const char *fname, int angle_brackets,
1022 		    enum include_type type, source_location loc)
1023 {
1024   struct cpp_dir *dir;
1025   _cpp_file *file;
1026   bool stacked;
1027 
1028   /* For -include command-line flags we have type == IT_CMDLINE.
1029      When the first -include file is processed we have the case, where
1030      pfile->cur_token == pfile->cur_run->base, we are directly called up
1031      by the front end.  However in the case of the second -include file,
1032      we are called from _cpp_lex_token -> _cpp_get_fresh_line ->
1033      cpp_push_include, with pfile->cur_token != pfile->cur_run->base,
1034      and pfile->cur_token[-1].src_loc not (yet) initialized.
1035      However, when the include file cannot be found, we need src_loc to
1036      be initialized to some safe value: 0 means UNKNOWN_LOCATION.  */
1037   if (type == IT_CMDLINE && pfile->cur_token != pfile->cur_run->base)
1038     pfile->cur_token[-1].src_loc = 0;
1039 
1040   dir = search_path_head (pfile, fname, angle_brackets, type);
1041   if (!dir)
1042     return false;
1043 
1044   file = _cpp_find_file (pfile, fname, dir, false, angle_brackets,
1045 			 type == IT_DEFAULT, loc);
1046   if (type == IT_DEFAULT && file == NULL)
1047     return false;
1048 
1049   /* Compensate for the increment in linemap_add that occurs if
1050       _cpp_stack_file actually stacks the file.  In the case of a
1051      normal #include, we're currently at the start of the line
1052      *following* the #include.  A separate source_location for this
1053      location makes no sense (until we do the LC_LEAVE), and
1054      complicates LAST_SOURCE_LINE_LOCATION.  This does not apply if we
1055      found a PCH file (in which case linemap_add is not called) or we
1056      were included from the command-line.  */
1057   if (file->pchname == NULL && file->err_no == 0
1058       && type != IT_CMDLINE && type != IT_DEFAULT)
1059     pfile->line_table->highest_location--;
1060 
1061   stacked = _cpp_stack_file (pfile, file, type == IT_IMPORT, loc);
1062 
1063   if (!stacked)
1064     /* _cpp_stack_file didn't stack the file, so let's rollback the
1065        compensation dance we performed above.  */
1066     pfile->line_table->highest_location++;
1067 
1068   return stacked;
1069 }
1070 
1071 /* Could not open FILE.  The complication is dependency output.  */
1072 static void
1073 open_file_failed (cpp_reader *pfile, _cpp_file *file, int angle_brackets,
1074 		  source_location loc)
1075 {
1076   int sysp = pfile->line_table->highest_line > 1 && pfile->buffer ? pfile->buffer->sysp : 0;
1077   bool print_dep = CPP_OPTION (pfile, deps.style) > (angle_brackets || !!sysp);
1078 
1079   if (pfile->state.in__has_include__)
1080     return;
1081 
1082   errno = file->err_no;
1083   if (print_dep && CPP_OPTION (pfile, deps.missing_files) && errno == ENOENT)
1084     {
1085       deps_add_dep (pfile->deps, file->name);
1086       /* If the preprocessor output (other than dependency information) is
1087          being used, we must also flag an error.  */
1088       if (CPP_OPTION (pfile, deps.need_preprocessor_output))
1089 	cpp_errno_filename (pfile, CPP_DL_FATAL,
1090 			    file->path ? file->path : file->name,
1091 			    loc);
1092     }
1093   else
1094     {
1095       /* If we are not outputting dependencies, or if we are and dependencies
1096          were requested for this file, or if preprocessor output is needed
1097          in addition to dependency information, this is an error.
1098 
1099          Otherwise (outputting dependencies but not for this file, and not
1100          using the preprocessor output), we can still produce correct output
1101          so it's only a warning.  */
1102       if (CPP_OPTION (pfile, deps.style) == DEPS_NONE
1103           || print_dep
1104           || CPP_OPTION (pfile, deps.need_preprocessor_output))
1105 	cpp_errno_filename (pfile, CPP_DL_FATAL,
1106 			    file->path ? file->path : file->name,
1107 			    loc);
1108       else
1109 	cpp_errno_filename (pfile, CPP_DL_WARNING,
1110 			    file->path ? file->path : file->name,
1111 			    loc);
1112     }
1113 }
1114 
1115 /* Search in the chain beginning at HEAD for a file whose search path
1116    started at START_DIR != NULL.  */
1117 static struct cpp_file_hash_entry *
1118 search_cache (struct cpp_file_hash_entry *head, const cpp_dir *start_dir)
1119 {
1120   while (head && head->start_dir != start_dir)
1121     head = head->next;
1122 
1123   return head;
1124 }
1125 
1126 /* Allocate a new _cpp_file structure.  */
1127 static _cpp_file *
1128 make_cpp_file (cpp_reader *pfile, cpp_dir *dir, const char *fname)
1129 {
1130   _cpp_file *file;
1131 
1132   file = XCNEW (_cpp_file);
1133   file->main_file = !pfile->buffer;
1134   file->fd = -1;
1135   file->dir = dir;
1136   file->name = xstrdup (fname);
1137 
1138   return file;
1139 }
1140 
1141 /* Release a _cpp_file structure.  */
1142 static void
1143 destroy_cpp_file (_cpp_file *file)
1144 {
1145   free ((void *) file->buffer_start);
1146   free ((void *) file->name);
1147   free ((void *) file->path);
1148   free (file);
1149 }
1150 
1151 /* Release all the files allocated by this reader.  */
1152 static void
1153 destroy_all_cpp_files (cpp_reader *pfile)
1154 {
1155   _cpp_file *iter = pfile->all_files;
1156   while (iter)
1157     {
1158       _cpp_file *next = iter->next_file;
1159       destroy_cpp_file (iter);
1160       iter = next;
1161     }
1162 }
1163 
1164 /* A hash of directory names.  The directory names are the path names
1165    of files which contain a #include "", the included file name is
1166    appended to this directories.
1167 
1168    To avoid duplicate entries we follow the convention that all
1169    non-empty directory names should end in a '/'.  DIR_NAME must be
1170    stored in permanently allocated memory.  */
1171 static cpp_dir *
1172 make_cpp_dir (cpp_reader *pfile, const char *dir_name, int sysp)
1173 {
1174   struct cpp_file_hash_entry *entry, **hash_slot;
1175   cpp_dir *dir;
1176 
1177   hash_slot = (struct cpp_file_hash_entry **)
1178     htab_find_slot_with_hash (pfile->dir_hash, dir_name,
1179 			      htab_hash_string (dir_name),
1180 			      INSERT);
1181 
1182   /* Have we already hashed this directory?  */
1183   for (entry = *hash_slot; entry; entry = entry->next)
1184     if (entry->start_dir == NULL)
1185       return entry->u.dir;
1186 
1187   dir = XCNEW (cpp_dir);
1188   dir->next = pfile->quote_include;
1189   dir->name = (char *) dir_name;
1190   dir->len = strlen (dir_name);
1191   dir->sysp = sysp;
1192   dir->construct = 0;
1193 
1194   /* Store this new result in the hash table.  */
1195   entry = new_file_hash_entry (pfile);
1196   entry->next = *hash_slot;
1197   entry->start_dir = NULL;
1198   entry->location = pfile->line_table->highest_location;
1199   entry->u.dir = dir;
1200   *hash_slot = entry;
1201 
1202   return dir;
1203 }
1204 
1205 /* Create a new block of memory for file hash entries.  */
1206 static void
1207 allocate_file_hash_entries (cpp_reader *pfile)
1208 {
1209   struct file_hash_entry_pool *pool = XNEW (struct file_hash_entry_pool);
1210   pool->file_hash_entries_used = 0;
1211   pool->next = pfile->file_hash_entries;
1212   pfile->file_hash_entries = pool;
1213 }
1214 
1215 /* Return a new file hash entry.  */
1216 static struct cpp_file_hash_entry *
1217 new_file_hash_entry (cpp_reader *pfile)
1218 {
1219   unsigned int idx;
1220   if (pfile->file_hash_entries->file_hash_entries_used == FILE_HASH_POOL_SIZE)
1221     allocate_file_hash_entries (pfile);
1222 
1223   idx = pfile->file_hash_entries->file_hash_entries_used++;
1224   return &pfile->file_hash_entries->pool[idx];
1225 }
1226 
1227 /* Free the file hash entry pools.  */
1228 static void
1229 free_file_hash_entries (cpp_reader *pfile)
1230 {
1231   struct file_hash_entry_pool *iter = pfile->file_hash_entries;
1232   while (iter)
1233     {
1234       struct file_hash_entry_pool *next = iter->next;
1235       free (iter);
1236       iter = next;
1237     }
1238 }
1239 
1240 /* Returns TRUE if a file FNAME has ever been successfully opened.
1241    This routine is not intended to correctly handle filenames aliased
1242    by links or redundant . or .. traversals etc.  */
1243 bool
1244 cpp_included (cpp_reader *pfile, const char *fname)
1245 {
1246   struct cpp_file_hash_entry *entry;
1247 
1248   entry = (struct cpp_file_hash_entry *)
1249      htab_find_with_hash (pfile->file_hash, fname, htab_hash_string (fname));
1250 
1251   while (entry && (entry->start_dir == NULL || entry->u.file->err_no))
1252     entry = entry->next;
1253 
1254   return entry != NULL;
1255 }
1256 
1257 /* Returns TRUE if a file FNAME has ever been successfully opened
1258    before LOCATION.  This routine is not intended to correctly handle
1259    filenames aliased by links or redundant . or .. traversals etc.  */
1260 bool
1261 cpp_included_before (cpp_reader *pfile, const char *fname,
1262 		     source_location location)
1263 {
1264   struct cpp_file_hash_entry *entry
1265     = (struct cpp_file_hash_entry *)
1266       htab_find_with_hash (pfile->file_hash, fname, htab_hash_string (fname));
1267 
1268   if (IS_ADHOC_LOC (location))
1269     location = get_location_from_adhoc_loc (pfile->line_table, location);
1270 
1271   while (entry && (entry->start_dir == NULL || entry->u.file->err_no
1272 		   || entry->location > location))
1273     entry = entry->next;
1274 
1275   return entry != NULL;
1276 }
1277 
1278 /* Calculate the hash value of a file hash entry P.  */
1279 
1280 static hashval_t
1281 file_hash_hash (const void *p)
1282 {
1283   struct cpp_file_hash_entry *entry = (struct cpp_file_hash_entry *) p;
1284   const char *hname;
1285   if (entry->start_dir)
1286     hname = entry->u.file->name;
1287   else
1288     hname = entry->u.dir->name;
1289 
1290   return htab_hash_string (hname);
1291 }
1292 
1293 /* Compare a string Q against a file hash entry P.  */
1294 static int
1295 file_hash_eq (const void *p, const void *q)
1296 {
1297   struct cpp_file_hash_entry *entry = (struct cpp_file_hash_entry *) p;
1298   const char *fname = (const char *) q;
1299   const char *hname;
1300 
1301   if (entry->start_dir)
1302     hname = entry->u.file->name;
1303   else
1304     hname = entry->u.dir->name;
1305 
1306   return filename_cmp (hname, fname) == 0;
1307 }
1308 
1309 /* Compare entries in the nonexistent file hash table.  These are just
1310    strings.  */
1311 static int
1312 nonexistent_file_hash_eq (const void *p, const void *q)
1313 {
1314   return filename_cmp ((const char *) p, (const char *) q) == 0;
1315 }
1316 
1317 /* Initialize everything in this source file.  */
1318 void
1319 _cpp_init_files (cpp_reader *pfile)
1320 {
1321   pfile->file_hash = htab_create_alloc (127, file_hash_hash, file_hash_eq,
1322 					NULL, xcalloc, free);
1323   pfile->dir_hash = htab_create_alloc (127, file_hash_hash, file_hash_eq,
1324 					NULL, xcalloc, free);
1325   allocate_file_hash_entries (pfile);
1326   pfile->nonexistent_file_hash = htab_create_alloc (127, htab_hash_string,
1327 						    nonexistent_file_hash_eq,
1328 						    NULL, xcalloc, free);
1329   obstack_specify_allocation (&pfile->nonexistent_file_ob, 0, 0,
1330 			      xmalloc, free);
1331 }
1332 
1333 /* Finalize everything in this source file.  */
1334 void
1335 _cpp_cleanup_files (cpp_reader *pfile)
1336 {
1337   htab_delete (pfile->file_hash);
1338   htab_delete (pfile->dir_hash);
1339   htab_delete (pfile->nonexistent_file_hash);
1340   obstack_free (&pfile->nonexistent_file_ob, 0);
1341   free_file_hash_entries (pfile);
1342   destroy_all_cpp_files (pfile);
1343 }
1344 
1345 /* Make the parser forget about files it has seen.  This can be useful
1346    for resetting the parser to start another run.  */
1347 void
1348 cpp_clear_file_cache (cpp_reader *pfile)
1349 {
1350   _cpp_cleanup_files (pfile);
1351   pfile->file_hash_entries = NULL;
1352   pfile->all_files = NULL;
1353   _cpp_init_files (pfile);
1354 }
1355 
1356 /* Enter a file name in the hash for the sake of cpp_included.  */
1357 void
1358 _cpp_fake_include (cpp_reader *pfile, const char *fname)
1359 {
1360   _cpp_find_file (pfile, fname, pfile->buffer->file->dir, true, 0, false, 0);
1361 }
1362 
1363 /* Not everyone who wants to set system-header-ness on a buffer can
1364    see the details of a buffer.  This is an exported interface because
1365    fix-header needs it.  */
1366 void
1367 cpp_make_system_header (cpp_reader *pfile, int syshdr, int externc)
1368 {
1369   int flags = 0;
1370   const struct line_maps *line_table = pfile->line_table;
1371   const line_map_ordinary *map = LINEMAPS_LAST_ORDINARY_MAP (line_table);
1372   /* 1 = system header, 2 = system header to be treated as C.  */
1373   if (syshdr)
1374     flags = 1 + (externc != 0);
1375   pfile->buffer->sysp = flags;
1376   _cpp_do_file_change (pfile, LC_RENAME, ORDINARY_MAP_FILE_NAME (map),
1377 		       SOURCE_LINE (map, pfile->line_table->highest_line), flags);
1378 }
1379 
1380 /* Allow the client to change the current file.  Used by the front end
1381    to achieve pseudo-file names like <built-in>.
1382    If REASON is LC_LEAVE, then NEW_NAME must be NULL.  */
1383 void
1384 cpp_change_file (cpp_reader *pfile, enum lc_reason reason,
1385 		 const char *new_name)
1386 {
1387   _cpp_do_file_change (pfile, reason, new_name, 1, 0);
1388 }
1389 
1390 struct report_missing_guard_data
1391 {
1392   const char **paths;
1393   size_t count;
1394 };
1395 
1396 /* Callback function for htab_traverse.  */
1397 static int
1398 report_missing_guard (void **slot, void *d)
1399 {
1400   struct cpp_file_hash_entry *entry = (struct cpp_file_hash_entry *) *slot;
1401   struct report_missing_guard_data *data
1402     = (struct report_missing_guard_data *) d;
1403 
1404   /* Skip directories.  */
1405   if (entry->start_dir != NULL)
1406     {
1407       _cpp_file *file = entry->u.file;
1408 
1409       /* We don't want MI guard advice for the main file.  */
1410       if (!file->once_only && file->cmacro == NULL
1411 	  && file->stack_count == 1 && !file->main_file)
1412 	{
1413 	  if (data->paths == NULL)
1414 	    {
1415 	      data->paths = XCNEWVEC (const char *, data->count);
1416 	      data->count = 0;
1417 	    }
1418 
1419 	  data->paths[data->count++] = file->path;
1420 	}
1421     }
1422 
1423   /* Keep traversing the hash table.  */
1424   return 1;
1425 }
1426 
1427 /* Comparison function for qsort.  */
1428 static int
1429 report_missing_guard_cmp (const void *p1, const void *p2)
1430 {
1431   return strcmp (*(const char *const *) p1, *(const char *const *) p2);
1432 }
1433 
1434 /* Report on all files that might benefit from a multiple include guard.
1435    Triggered by -H.  */
1436 void
1437 _cpp_report_missing_guards (cpp_reader *pfile)
1438 {
1439   struct report_missing_guard_data data;
1440 
1441   data.paths = NULL;
1442   data.count = htab_elements (pfile->file_hash);
1443   htab_traverse (pfile->file_hash, report_missing_guard, &data);
1444 
1445   if (data.paths != NULL)
1446     {
1447       size_t i;
1448 
1449       /* Sort the paths to avoid outputting them in hash table
1450 	 order.  */
1451       qsort (data.paths, data.count, sizeof (const char *),
1452 	     report_missing_guard_cmp);
1453       fputs (_("Multiple include guards may be useful for:\n"),
1454 	     stderr);
1455       for (i = 0; i < data.count; i++)
1456 	{
1457 	  fputs (data.paths[i], stderr);
1458 	  putc ('\n', stderr);
1459 	}
1460       free (data.paths);
1461     }
1462 }
1463 
1464 /* Locate HEADER, and determine whether it is newer than the current
1465    file.  If it cannot be located or dated, return -1, if it is
1466    newer, return 1, otherwise 0.  */
1467 int
1468 _cpp_compare_file_date (cpp_reader *pfile, const char *fname,
1469 			int angle_brackets)
1470 {
1471   _cpp_file *file;
1472   struct cpp_dir *dir;
1473 
1474   dir = search_path_head (pfile, fname, angle_brackets, IT_INCLUDE);
1475   if (!dir)
1476     return -1;
1477 
1478   file = _cpp_find_file (pfile, fname, dir, false, angle_brackets, false, 0);
1479   if (file->err_no)
1480     return -1;
1481 
1482   if (file->fd != -1)
1483     {
1484       close (file->fd);
1485       file->fd = -1;
1486     }
1487 
1488   return file->st.st_mtime > pfile->buffer->file->st.st_mtime;
1489 }
1490 
1491 /* Pushes the given file onto the buffer stack.  Returns nonzero if
1492    successful.  */
1493 bool
1494 cpp_push_include (cpp_reader *pfile, const char *fname)
1495 {
1496   return _cpp_stack_include (pfile, fname, false, IT_CMDLINE, 0);
1497 }
1498 
1499 /* Pushes the given file, implicitly included at the start of a
1500    compilation, onto the buffer stack but without any errors if the
1501    file is not found.  Returns nonzero if successful.  */
1502 bool
1503 cpp_push_default_include (cpp_reader *pfile, const char *fname)
1504 {
1505   return _cpp_stack_include (pfile, fname, true, IT_DEFAULT, 0);
1506 }
1507 
1508 /* Do appropriate cleanup when a file INC's buffer is popped off the
1509    input stack.  */
1510 void
1511 _cpp_pop_file_buffer (cpp_reader *pfile, _cpp_file *file,
1512 		      const unsigned char *to_free)
1513 {
1514   /* Record the inclusion-preventing macro, which could be NULL
1515      meaning no controlling macro.  */
1516   if (pfile->mi_valid && file->cmacro == NULL)
1517     file->cmacro = pfile->mi_cmacro;
1518 
1519   /* Invalidate control macros in the #including file.  */
1520   pfile->mi_valid = false;
1521 
1522   if (to_free)
1523     {
1524       if (to_free == file->buffer_start)
1525 	{
1526 	  file->buffer_start = NULL;
1527 	  file->buffer = NULL;
1528 	  file->buffer_valid = false;
1529 	}
1530       free ((void *) to_free);
1531     }
1532 }
1533 
1534 /* Return the file name associated with FILE.  */
1535 const char *
1536 _cpp_get_file_name (_cpp_file *file)
1537 {
1538   return file->name;
1539 }
1540 
1541 /* Inteface to file statistics record in _cpp_file structure. */
1542 struct stat *
1543 _cpp_get_file_stat (_cpp_file *file)
1544 {
1545     return &file->st;
1546 }
1547 
1548 /* Set the include chain for "" to QUOTE, for <> to BRACKET.  If
1549    QUOTE_IGNORES_SOURCE_DIR, then "" includes do not look in the
1550    directory of the including file.
1551 
1552    If BRACKET does not lie in the QUOTE chain, it is set to QUOTE.  */
1553 void
1554 cpp_set_include_chains (cpp_reader *pfile, cpp_dir *quote, cpp_dir *bracket,
1555 			int quote_ignores_source_dir)
1556 {
1557   pfile->quote_include = quote;
1558   pfile->bracket_include = quote;
1559   pfile->quote_ignores_source_dir = quote_ignores_source_dir;
1560 
1561   for (; quote; quote = quote->next)
1562     {
1563       quote->name_map = NULL;
1564       quote->len = strlen (quote->name);
1565       if (quote == bracket)
1566 	pfile->bracket_include = bracket;
1567     }
1568 }
1569 
1570 /* Append the file name to the directory to create the path, but don't
1571    turn / into // or // into ///; // may be a namespace escape.  */
1572 static char *
1573 append_file_to_dir (const char *fname, cpp_dir *dir)
1574 {
1575   size_t dlen, flen;
1576   char *path;
1577 
1578   dlen = dir->len;
1579   flen = strlen (fname);
1580   path = XNEWVEC (char, dlen + 1 + flen + 1);
1581   memcpy (path, dir->name, dlen);
1582   if (dlen && !IS_DIR_SEPARATOR (path[dlen - 1]))
1583     path[dlen++] = '/';
1584   memcpy (&path[dlen], fname, flen + 1);
1585 
1586   return path;
1587 }
1588 
1589 /* Read a space delimited string of unlimited length from a stdio
1590    file F.  */
1591 static char *
1592 read_filename_string (int ch, FILE *f)
1593 {
1594   char *alloc, *set;
1595   int len;
1596 
1597   len = 20;
1598   set = alloc = XNEWVEC (char, len + 1);
1599   if (! is_space (ch))
1600     {
1601       *set++ = ch;
1602       while ((ch = getc (f)) != EOF && ! is_space (ch))
1603 	{
1604 	  if (set - alloc == len)
1605 	    {
1606 	      len *= 2;
1607 	      alloc = XRESIZEVEC (char, alloc, len + 1);
1608 	      set = alloc + len / 2;
1609 	    }
1610 	  *set++ = ch;
1611 	}
1612     }
1613   *set = '\0';
1614   ungetc (ch, f);
1615   return alloc;
1616 }
1617 
1618 /* Read the file name map file for DIR.  */
1619 static void
1620 read_name_map (cpp_dir *dir)
1621 {
1622   static const char FILE_NAME_MAP_FILE[] = "header.gcc";
1623   char *name;
1624   FILE *f;
1625   size_t len, count = 0, room = 9;
1626 
1627   len = dir->len;
1628   name = (char *) alloca (len + sizeof (FILE_NAME_MAP_FILE) + 1);
1629   memcpy (name, dir->name, len);
1630   if (len && !IS_DIR_SEPARATOR (name[len - 1]))
1631     name[len++] = '/';
1632   strcpy (name + len, FILE_NAME_MAP_FILE);
1633   f = fopen (name, "r");
1634 
1635   dir->name_map = XNEWVEC (const char *, room);
1636 
1637   /* Silently return NULL if we cannot open.  */
1638   if (f)
1639     {
1640       int ch;
1641 
1642       while ((ch = getc (f)) != EOF)
1643 	{
1644 	  char *to;
1645 
1646 	  if (is_space (ch))
1647 	    continue;
1648 
1649 	  if (count + 2 > room)
1650 	    {
1651 	      room += 8;
1652 	      dir->name_map = XRESIZEVEC (const char *, dir->name_map, room);
1653 	    }
1654 
1655 	  dir->name_map[count] = read_filename_string (ch, f);
1656 	  while ((ch = getc (f)) != EOF && is_hspace (ch))
1657 	    ;
1658 
1659 	  to = read_filename_string (ch, f);
1660 	  if (IS_ABSOLUTE_PATH (to))
1661 	    dir->name_map[count + 1] = to;
1662 	  else
1663 	    {
1664 	      dir->name_map[count + 1] = append_file_to_dir (to, dir);
1665 	      free (to);
1666 	    }
1667 
1668 	  count += 2;
1669 	  while ((ch = getc (f)) != '\n')
1670 	    if (ch == EOF)
1671 	      break;
1672 	}
1673 
1674       fclose (f);
1675     }
1676 
1677   /* Terminate the list of maps.  */
1678   dir->name_map[count] = NULL;
1679 }
1680 
1681 /* Remap a FILE's name based on the file_name_map, if any, for
1682    FILE->dir.  If the file name has any directory separators,
1683    recursively check those directories too.  */
1684 static char *
1685 remap_filename (cpp_reader *pfile, _cpp_file *file)
1686 {
1687   const char *fname, *p;
1688   char *new_dir, *p3;
1689   cpp_dir *dir;
1690   size_t index, len;
1691 
1692   dir = file->dir;
1693   fname = file->name;
1694 
1695   for (;;)
1696     {
1697       if (!dir->name_map)
1698 	read_name_map (dir);
1699 
1700       for (index = 0; dir->name_map[index]; index += 2)
1701 	if (!filename_cmp (dir->name_map[index], fname))
1702 	    return xstrdup (dir->name_map[index + 1]);
1703       if (IS_ABSOLUTE_PATH (fname))
1704 	return NULL;
1705       p = strchr (fname, '/');
1706 #ifdef HAVE_DOS_BASED_FILE_SYSTEM
1707       {
1708 	char *p2 = strchr (fname, '\\');
1709 	if (!p || (p > p2))
1710 	  p = p2;
1711       }
1712 #endif
1713       if (!p || p == fname)
1714 	return NULL;
1715 
1716       len = dir->len + (p - fname + 1);
1717       new_dir = XNEWVEC (char, len + 2);
1718       p3 = new_dir + dir->len;
1719       memcpy (new_dir, dir->name, dir->len);
1720       if (dir->len && !IS_DIR_SEPARATOR (dir->name[dir->len - 1]))
1721 	{
1722 	  *p3++ = '/';
1723 	  len++;
1724 	}
1725       memcpy (p3, fname, p - fname + 1);
1726       new_dir[len] = '\0';
1727 
1728       dir = make_cpp_dir (pfile, new_dir, dir->sysp);
1729       fname = p + 1;
1730     }
1731 }
1732 
1733 /* Returns true if PCHNAME is a valid PCH file for FILE.  */
1734 static bool
1735 validate_pch (cpp_reader *pfile, _cpp_file *file, const char *pchname)
1736 {
1737   const char *saved_path = file->path;
1738   bool valid = false;
1739 
1740   file->path = pchname;
1741   if (open_file (file))
1742     {
1743       valid = 1 & pfile->cb.valid_pch (pfile, pchname, file->fd);
1744 
1745       if (!valid)
1746 	{
1747 	  close (file->fd);
1748 	  file->fd = -1;
1749 	}
1750 
1751       if (CPP_OPTION (pfile, print_include_names))
1752 	{
1753 	  unsigned int i;
1754 	  for (i = 1; i < pfile->line_table->depth; i++)
1755 	    putc ('.', stderr);
1756 	  fprintf (stderr, "%c %s\n",
1757 		   valid ? '!' : 'x', pchname);
1758 	}
1759     }
1760 
1761   file->path = saved_path;
1762   return valid;
1763 }
1764 
1765 /* Get the path associated with the _cpp_file F.  The path includes
1766    the base name from the include directive and the directory it was
1767    found in via the search path.  */
1768 
1769 const char *
1770 cpp_get_path (struct _cpp_file *f)
1771 {
1772   return f->path;
1773 }
1774 
1775 /* Get the directory associated with the _cpp_file F.  */
1776 
1777 cpp_dir *
1778 cpp_get_dir (struct _cpp_file *f)
1779 {
1780   return f->dir;
1781 }
1782 
1783 /* Get the cpp_buffer currently associated with the cpp_reader
1784    PFILE.  */
1785 
1786 cpp_buffer *
1787 cpp_get_buffer (cpp_reader *pfile)
1788 {
1789   return pfile->buffer;
1790 }
1791 
1792 /* Get the _cpp_file associated with the cpp_buffer B.  */
1793 
1794 _cpp_file *
1795 cpp_get_file (cpp_buffer *b)
1796 {
1797   return b->file;
1798 }
1799 
1800 /* Get the previous cpp_buffer given a cpp_buffer B.  The previous
1801    buffer is the buffer that included the given buffer.  */
1802 
1803 cpp_buffer *
1804 cpp_get_prev (cpp_buffer *b)
1805 {
1806   return b->prev;
1807 }
1808 
1809 /* This data structure holds the list of header files that were seen
1810    while the PCH was being built.  The 'entries' field is kept sorted
1811    in memcmp() order; yes, this means that on little-endian systems,
1812    it's sorted initially by the least-significant byte of 'size', but
1813    that's OK.  The code does rely on having entries with the same size
1814    next to each other.  */
1815 
1816 struct pchf_entry {
1817   /* The size of this file.  This is used to save running a MD5 checksum
1818      if the sizes don't match.  */
1819   off_t size;
1820   /* The MD5 checksum of this file.  */
1821   unsigned char sum[16];
1822   /* Is this file to be included only once?  */
1823   bool once_only;
1824 };
1825 
1826 struct pchf_data {
1827   /* Number of pchf_entry structures.  */
1828   size_t count;
1829 
1830   /* Are there any values with once_only set?
1831      This is used as an optimisation, it means we don't have to search
1832      the structure if we're processing a regular #include.  */
1833   bool have_once_only;
1834 
1835   struct pchf_entry entries[1];
1836 };
1837 
1838 static struct pchf_data *pchf;
1839 
1840 /* A qsort ordering function for pchf_entry structures.  */
1841 
1842 static int
1843 pchf_save_compare (const void *e1, const void *e2)
1844 {
1845   return memcmp (e1, e2, sizeof (struct pchf_entry));
1846 }
1847 
1848 /* Create and write to F a pchf_data structure.  */
1849 
1850 bool
1851 _cpp_save_file_entries (cpp_reader *pfile, FILE *fp)
1852 {
1853   size_t count = 0;
1854   struct pchf_data *result;
1855   size_t result_size;
1856   _cpp_file *f;
1857   bool ret;
1858 
1859   for (f = pfile->all_files; f; f = f->next_file)
1860     ++count;
1861 
1862   result_size = (sizeof (struct pchf_data)
1863 		 + sizeof (struct pchf_entry) * (count - 1));
1864   result = XCNEWVAR (struct pchf_data, result_size);
1865 
1866   result->count = 0;
1867   result->have_once_only = false;
1868 
1869   for (f = pfile->all_files; f; f = f->next_file)
1870     {
1871       size_t count;
1872 
1873       /* This should probably never happen, since if a read error occurred
1874 	 the PCH file shouldn't be written...  */
1875       if (f->dont_read || f->err_no)
1876 	continue;
1877 
1878       if (f->stack_count == 0)
1879 	continue;
1880 
1881       count = result->count++;
1882 
1883       result->entries[count].once_only = f->once_only;
1884       /* |= is avoided in the next line because of an HP C compiler bug */
1885       result->have_once_only = result->have_once_only | f->once_only;
1886       if (f->buffer_valid)
1887 	md5_buffer ((const char *)f->buffer,
1888 		    f->st.st_size, result->entries[count].sum);
1889       else
1890 	{
1891 	  FILE *ff;
1892 	  int oldfd = f->fd;
1893 
1894 	  if (!open_file (f))
1895 	    {
1896 	      open_file_failed (pfile, f, 0, 0);
1897 	      free (result);
1898 	      return false;
1899 	    }
1900 	  ff = fdopen (f->fd, "rb");
1901 	  md5_stream (ff, result->entries[count].sum);
1902 	  fclose (ff);
1903 	  f->fd = oldfd;
1904 	}
1905       result->entries[count].size = f->st.st_size;
1906     }
1907 
1908   result_size = (sizeof (struct pchf_data)
1909                  + sizeof (struct pchf_entry) * (result->count - 1));
1910 
1911   qsort (result->entries, result->count, sizeof (struct pchf_entry),
1912 	 pchf_save_compare);
1913 
1914   ret = fwrite (result, result_size, 1, fp) == 1;
1915   free (result);
1916   return ret;
1917 }
1918 
1919 /* Read the pchf_data structure from F.  */
1920 
1921 bool
1922 _cpp_read_file_entries (cpp_reader *pfile ATTRIBUTE_UNUSED, FILE *f)
1923 {
1924   struct pchf_data d;
1925 
1926   if (fread (&d, sizeof (struct pchf_data) - sizeof (struct pchf_entry), 1, f)
1927        != 1)
1928     return false;
1929 
1930   pchf = XNEWVAR (struct pchf_data, sizeof (struct pchf_data)
1931 		  + sizeof (struct pchf_entry) * (d.count - 1));
1932   memcpy (pchf, &d, sizeof (struct pchf_data) - sizeof (struct pchf_entry));
1933   if (fread (pchf->entries, sizeof (struct pchf_entry), d.count, f)
1934       != d.count)
1935     return false;
1936   return true;
1937 }
1938 
1939 /* The parameters for pchf_compare.  */
1940 
1941 struct pchf_compare_data
1942 {
1943   /* The size of the file we're looking for.  */
1944   off_t size;
1945 
1946   /* The MD5 checksum of the file, if it's been computed.  */
1947   unsigned char sum[16];
1948 
1949   /* Is SUM valid?  */
1950   bool sum_computed;
1951 
1952   /* Do we need to worry about entries that don't have ONCE_ONLY set?  */
1953   bool check_included;
1954 
1955   /* The file that we're searching for.  */
1956   _cpp_file *f;
1957 };
1958 
1959 /* bsearch comparison function; look for D_P in E_P.  */
1960 
1961 static int
1962 pchf_compare (const void *d_p, const void *e_p)
1963 {
1964   const struct pchf_entry *e = (const struct pchf_entry *)e_p;
1965   struct pchf_compare_data *d = (struct pchf_compare_data *)d_p;
1966   int result;
1967 
1968   result = memcmp (&d->size, &e->size, sizeof (off_t));
1969   if (result != 0)
1970     return result;
1971 
1972   if (! d->sum_computed)
1973     {
1974       _cpp_file *const f = d->f;
1975 
1976       md5_buffer ((const char *)f->buffer, f->st.st_size, d->sum);
1977       d->sum_computed = true;
1978     }
1979 
1980   result = memcmp (d->sum, e->sum, 16);
1981   if (result != 0)
1982     return result;
1983 
1984   if (d->check_included || e->once_only)
1985     return 0;
1986   else
1987     return 1;
1988 }
1989 
1990 /* Check that F is not in a list read from a PCH file (if any).
1991    Assumes that f->buffer_valid is true.  Return TRUE if the file
1992    should not be read.  */
1993 
1994 static bool
1995 check_file_against_entries (cpp_reader *pfile ATTRIBUTE_UNUSED,
1996 			    _cpp_file *f,
1997 			    bool check_included)
1998 {
1999   struct pchf_compare_data d;
2000 
2001   if (pchf == NULL
2002       || (! check_included && ! pchf->have_once_only))
2003     return false;
2004 
2005   d.size = f->st.st_size;
2006   d.sum_computed = false;
2007   d.f = f;
2008   d.check_included = check_included;
2009   return bsearch (&d, pchf->entries, pchf->count, sizeof (struct pchf_entry),
2010 		  pchf_compare) != NULL;
2011 }
2012 
2013 /* Return true if the file FNAME is found in the appropriate include file path
2014    as indicated by ANGLE_BRACKETS.  */
2015 
2016 bool
2017 _cpp_has_header (cpp_reader *pfile, const char *fname, int angle_brackets,
2018 		 enum include_type type)
2019 {
2020   cpp_dir *start_dir = search_path_head (pfile, fname, angle_brackets, type);
2021   _cpp_file *file = _cpp_find_file (pfile, fname, start_dir,
2022 				    /*fake=*/false, angle_brackets,
2023 				    /*implicit_preinclude=*/false, 0);
2024   return file->err_no != ENOENT;
2025 }
2026 
2027