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