cppfiles.c 30.9 KB
Newer Older
Zack Weinberg committed
1
/* Part of CPP library.  (include file handling)
Jeff Law committed
2
   Copyright (C) 1986, 1987, 1989, 1992, 1993, 1994, 1995, 1998,
3
   1999, 2000, 2001 Free Software Foundation, Inc.
Zack Weinberg committed
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
   Written by Per Bothner, 1994.
   Based on CCCP program by Paul Rubin, June 1986
   Adapted to ANSI C, Richard Stallman, Jan 1987
   Split out of cpplib.c, Zack Weinberg, Oct 1998

This program is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 2, or (at your option) any
later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
21
Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
Zack Weinberg committed
22 23 24 25

#include "config.h"
#include "system.h"
#include "cpplib.h"
26
#include "cpphash.h"
27
#include "intl.h"
28
#include "mkdeps.h"
29
#include "splay-tree.h"
Zack Weinberg committed
30

31 32 33 34 35 36 37 38 39 40 41
#ifdef HAVE_MMAP_FILE
# include <sys/mman.h>
# ifndef MMAP_THRESHOLD
#  define MMAP_THRESHOLD 3 /* Minimum page count to mmap the file.  */
# endif

#else  /* No MMAP_FILE */
#  undef MMAP_THRESHOLD
#  define MMAP_THRESHOLD 0
#endif

Zack Weinberg committed
42 43 44 45
#ifndef O_BINARY
# define O_BINARY 0
#endif

46 47 48 49 50 51 52 53 54
/* If errno is inspected immediately after a system call fails, it will be
   nonzero, and no error number will ever be zero.  */
#ifndef ENOENT
# define ENOENT 0
#endif
#ifndef ENOTDIR
# define ENOTDIR 0
#endif

55 56 57 58
/* Suppress warning about function macros used w/o arguments in traditional
   C.  It is unlikely that glibc's strcmp macro helps this file at all.  */
#undef strcmp

59 60 61 62 63
/* This structure is used for the table of all includes.  */
struct include_file
{
  const char *name;		/* actual path name of file */
  const cpp_hashnode *cmacro;	/* macro, if any, preventing reinclusion.  */
64
  const struct search_path *foundhere;
65 66 67 68 69 70 71 72 73 74
				/* location in search path where file was
				   found, for #include_next and sysp.  */
  const unsigned char *buffer;	/* pointer to cached file contents */
  struct stat st;		/* copy of stat(2) data for file */
  int fd;			/* fd open on file (short term storage only) */
  unsigned short include_count;	/* number of times file has been read */
  unsigned short refcnt;	/* number of stacked buffers using this file */
  unsigned char mapped;		/* file buffer is mmapped */
};

75 76 77
/* The cmacro works like this: If it's NULL, the file is to be
   included again.  If it's NEVER_REREAD, the file is never to be
   included again.  Otherwise it is a macro hashnode, and the file is
78
   to be included again if the macro is defined.  */
79 80 81
#define NEVER_REREAD ((const cpp_hashnode *)-1)
#define DO_NOT_REREAD(inc) \
((inc)->cmacro && ((inc)->cmacro == NEVER_REREAD \
82
		   || (inc)->cmacro->type == NT_MACRO))
83
#define NO_INCLUDE_PATH ((struct include_file *) -1)
84

85
static struct file_name_map *read_name_map
86 87 88
				PARAMS ((cpp_reader *, const char *));
static char *read_filename_string PARAMS ((int, FILE *));
static char *remap_filename 	PARAMS ((cpp_reader *, char *,
89 90
					 struct search_path *));
static struct search_path *search_from PARAMS ((cpp_reader *,
91
						enum include_type));
92
static struct include_file *
93 94
	find_include_file PARAMS ((cpp_reader *, const cpp_token *,
				   enum include_type));
95
static struct include_file *open_file PARAMS ((cpp_reader *, const char *));
96
static int read_include_file	PARAMS ((cpp_reader *, struct include_file *));
97
static void stack_include_file	PARAMS ((cpp_reader *, struct include_file *));
98
static void purge_cache 	PARAMS ((struct include_file *));
99
static void destroy_node	PARAMS ((splay_tree_value));
100
static int report_missing_guard		PARAMS ((splay_tree_node, void *));
101 102 103
static splay_tree_node find_or_create_entry PARAMS ((cpp_reader *,
						     const char *));
static void handle_missing_header PARAMS ((cpp_reader *, const char *, int));
104
static int remove_component_p	PARAMS ((const char *));
105 106 107 108 109 110 111 112 113 114 115 116 117

/* Set up the splay tree we use to store information about all the
   file names seen in this compilation.  We also have entries for each
   file we tried to open but failed; this saves system calls since we
   don't try to open it again in future.

   The key of each node is the file name, after processing by
   _cpp_simplify_pathname.  The path name may or may not be absolute.
   The path string has been malloced, as is automatically freed by
   registering free () as the splay tree key deletion function.

   A node's value is a pointer to a struct include_file, and is never
   NULL.  */
118
void
119
_cpp_init_includes (pfile)
120 121 122
     cpp_reader *pfile;
{
  pfile->all_include_files
123 124
    = splay_tree_new ((splay_tree_compare_fn) strcmp,
		      (splay_tree_delete_key_fn) free,
125
		      destroy_node);
126
}
Zack Weinberg committed
127

128
/* Tear down the splay tree.  */
129 130 131 132 133 134 135
void
_cpp_cleanup_includes (pfile)
     cpp_reader *pfile;
{
  splay_tree_delete (pfile->all_include_files);
}

136 137 138 139 140 141 142 143 144 145 146 147 148 149
/* Free a node.  The path string is automatically freed.  */
static void
destroy_node (v)
     splay_tree_value v;
{
  struct include_file *f = (struct include_file *)v;

  if (f)
    {
      purge_cache (f);
      free (f);
    }
}

150 151 152 153 154 155 156 157
/* Mark a file to not be reread (e.g. #import, read failure).  */
void
_cpp_never_reread (file)
     struct include_file *file;
{
  file->cmacro = NEVER_REREAD;
}

158
/* Lookup a filename, which is simplified after making a copy, and
159 160
   create an entry if none exists.  errno is nonzero iff a (reported)
   stat() error occurred during simplification.  */
161 162
static splay_tree_node
find_or_create_entry (pfile, fname)
163 164 165
     cpp_reader *pfile;
     const char *fname;
{
166 167
  splay_tree_node node;
  struct include_file *file;
168
  char *name = xstrdup (fname);
169

170 171 172 173 174
  _cpp_simplify_pathname (name);
  node = splay_tree_lookup (pfile->all_include_files, (splay_tree_key) name);
  if (node)
    free (name);
  else
175
    {
176
      file = xcnew (struct include_file);
177
      file->name = name;
178 179 180
      node = splay_tree_insert (pfile->all_include_files,
				(splay_tree_key) file->name,
				(splay_tree_value) file);
181
    }
182 183 184 185

  return node;
}

186
/* Enter a file name in the splay tree, for the sake of cpp_included.  */
187 188 189 190 191 192
void
_cpp_fake_include (pfile, fname)
     cpp_reader *pfile;
     const char *fname;
{
  find_or_create_entry (pfile, fname);
193 194
}

195
/* Given a file name, look it up in the cache; if there is no entry,
196 197 198
   create one with a non-NULL value (regardless of success in opening
   the file).  If the file doesn't exist or is inaccessible, this
   entry is flagged so we don't attempt to open it again in the
199 200
   future.  If the file isn't open, open it.  The empty string is
   interpreted as stdin.
201 202 203

   Returns an include_file structure with an open file descriptor on
   success, or NULL on failure.  */
Zack Weinberg committed
204

205
static struct include_file *
206
open_file (pfile, filename)
207 208
     cpp_reader *pfile;
     const char *filename;
209
{
210 211
  splay_tree_node nd = find_or_create_entry (pfile, filename);
  struct include_file *file = (struct include_file *) nd->value;
Zack Weinberg committed
212

213 214 215
  if (errno)
    file->fd = -2;

216 217 218
  /* Don't retry opening if we failed previously.  */
  if (file->fd == -2)
    return 0;
219

220 221 222
  /* Don't reopen an idempotent file. */
  if (DO_NOT_REREAD (file))
    return file;
223
      
224 225 226
  /* Don't reopen one which is already loaded. */
  if (file->buffer != NULL)
    return file;
Zack Weinberg committed
227

228 229 230 231
  /* We used to open files in nonblocking mode, but that caused more
     problems than it solved.  Do take care not to acquire a
     controlling terminal by mistake (this can't happen on sane
     systems, but paranoia is a virtue).
Zack Weinberg committed
232

233 234
     Use the three-argument form of open even though we aren't
     specifying O_CREAT, to defend against broken system headers.
Zack Weinberg committed
235

236 237 238
     O_BINARY tells some runtime libraries (notably DJGPP) not to do
     newline translation; we can handle DOS line breaks just fine
     ourselves.
239

240
     Special case: the empty string is translated to stdin.  */
241

242
  if (filename[0] == '\0')
243
    file->fd = 0;
244
  else
245
    file->fd = open (file->name, O_RDONLY | O_NOCTTY | O_BINARY, 0666);
246

247 248
  if (file->fd != -1 && fstat (file->fd, &file->st) == 0)
    {
249 250 251 252 253 254 255 256 257 258 259 260 261 262
      /* If it's a directory, we return null and continue the search
	 as the file we're looking for may appear elsewhere in the
	 search path.  */
      if (S_ISDIR (file->st.st_mode))
	errno = ENOENT;
      else
	{
	  /* Mark a regular, zero-length file never-reread now.  */
	  if (S_ISREG (file->st.st_mode) && file->st.st_size == 0)
	    {
	      _cpp_never_reread (file);
	      close (file->fd);
	      file->fd = -1;
	    }
263

264 265
	  return file;
	}
266
    }
267 268 269

  /* Don't issue an error message if the file doesn't exist.  */
  if (errno != ENOENT && errno != ENOTDIR)
270
    cpp_error_from_errno (pfile, file->name);
271

272 273 274
  /* Create a negative node for this path, and return null.  */
  file->fd = -2;

275 276 277
  return 0;
}

278 279
/* Place the file referenced by INC into a new buffer on PFILE's
   stack.  If there are errors, or the file should not be re-included,
280
   a null (zero-length) buffer is pushed.  */
281

282
static void
283 284 285 286
stack_include_file (pfile, inc)
     cpp_reader *pfile;
     struct include_file *inc;
{
287
  size_t len = 0;
288
  cpp_buffer *fp;
289 290 291 292
  int sysp, deps_sysp;

  /* We'll try removing deps_sysp after the release of 3.0.  */
  deps_sysp = pfile->system_include_depth != 0;
293 294
  sysp = MAX ((pfile->buffer ? pfile->buffer->sysp : 0),
	      (inc->foundhere ? inc->foundhere->sysp : 0));
295 296 297 298 299

  /* For -M, add the file to the dependencies on its first inclusion.  */
  if (CPP_OPTION (pfile, print_deps) > deps_sysp && !inc->include_count)
    deps_add_dep (pfile->deps, inc->name);

300 301 302 303 304 305 306 307 308 309
  /* Not in cache?  */
  if (! DO_NOT_REREAD (inc) && ! inc->buffer)
    {
      /* If an error occurs, do not try to read this file again.  */
      if (read_include_file (pfile, inc))
	_cpp_never_reread (inc);
      close (inc->fd);
      inc->fd = -1;
    }

310 311 312 313 314 315 316
  if (! DO_NOT_REREAD (inc))
    {
      len = inc->st.st_size;
      if (pfile->buffer)
	{
	  /* We don't want MI guard advice for the main file.  */
	  inc->include_count++;
317

318 319 320 321 322 323 324 325 326
	  /* Handle -H option.  */
	  if (CPP_OPTION (pfile, print_include_names))
	    {
	      for (fp = pfile->buffer; fp; fp = fp->prev)
		putc ('.', stderr);
	      fprintf (stderr, " %s\n", inc->name);
	    }
	}
    }
327 328 329 330

  /* Push a buffer.  */
  fp = cpp_push_buffer (pfile, inc->buffer, len, BUF_FILE, inc->name);
  fp->inc = inc;
331
  fp->inc->refcnt++;
332
  fp->sysp = sysp;
333

334 335 336
  /* Initialise controlling macro state.  */
  pfile->mi_state = MI_OUTSIDE;
  pfile->mi_cmacro = 0;
337
  pfile->include_depth++;
338 339 340 341 342

  /* Generate the call back.  */
  fp->lineno = 0;
  _cpp_do_file_change (pfile, FC_ENTER, 0, 0);
  fp->lineno = 1;
343 344 345 346 347 348 349
}

/* Read the file referenced by INC into the file cache.

   If fd points to a plain file, we might be able to mmap it; we can
   definitely allocate the buffer all at once.  If fd is a pipe or
   terminal, we can't do either.  If fd is something weird, like a
350
   block device, we don't want to read it at all.
351 352 353 354

   Unfortunately, different systems use different st.st_mode values
   for pipes: some have S_ISFIFO, some S_ISSOCK, some are buggy and
   zero the entire struct stat except a couple fields.  Hence we don't
355 356
   even try to figure out what something is, except for plain files
   and block devices.
357 358 359

   FIXME: Flush file cache and try again if we run out of memory.  */

360
static int
361 362 363 364 365 366 367 368 369 370 371
read_include_file (pfile, inc)
     cpp_reader *pfile;
     struct include_file *inc;
{
  ssize_t size, offset, count;
  U_CHAR *buf;
#if MMAP_THRESHOLD
  static int pagesize = -1;
#endif

  if (S_ISREG (inc->st.st_mode))
372
    {
373 374 375 376 377 378 379 380 381
      /* off_t might have a wider range than ssize_t - in other words,
	 the max size of a file might be bigger than the address
	 space.  We can't handle a file that large.  (Anyone with
	 a single source file bigger than 2GB needs to rethink
	 their coding style.)  Some systems (e.g. AIX 4.1) define
	 SSIZE_MAX to be much smaller than the actual range of the
	 type.  Use INTTYPE_MAXIMUM unconditionally to ensure this
	 does not bite us.  */
      if (inc->st.st_size > INTTYPE_MAXIMUM (ssize_t))
382
	{
383 384
	  cpp_error (pfile, "%s is too large", inc->name);
	  goto fail;
385
	}
386 387
      size = inc->st.st_size;

388
      inc->mapped = 0;
389 390 391 392 393 394 395 396 397 398 399 400
#if MMAP_THRESHOLD
      if (pagesize == -1)
	pagesize = getpagesize ();

      if (size / pagesize >= MMAP_THRESHOLD)
	{
	  buf = (U_CHAR *) mmap (0, size, PROT_READ, MAP_PRIVATE, inc->fd, 0);
	  if (buf == (U_CHAR *)-1)
	    goto perror_fail;
	  inc->mapped = 1;
	}
      else
401
#endif
402
	{
403 404 405 406 407 408 409 410 411 412 413 414 415 416
	  buf = (U_CHAR *) xmalloc (size);
	  offset = 0;
	  while (offset < size)
	    {
	      count = read (inc->fd, buf + offset, size - offset);
	      if (count < 0)
		goto perror_fail;
	      if (count == 0)
		{
		  cpp_warning (pfile, "%s is shorter than expected", inc->name);
		  break;
		}
	      offset += count;
	    }
417
	}
418 419 420 421 422 423 424 425 426 427 428 429
    }
  else if (S_ISBLK (inc->st.st_mode))
    {
      cpp_error (pfile, "%s is a block device", inc->name);
      goto fail;
    }
  else
    {
      /* 8 kilobytes is a sensible starting size.  It ought to be
	 bigger than the kernel pipe buffer, and it's definitely
	 bigger than the majority of C source files.  */
      size = 8 * 1024;
430

431 432 433
      buf = (U_CHAR *) xmalloc (size);
      offset = 0;
      while ((count = read (inc->fd, buf + offset, size - offset)) > 0)
434
	{
435 436 437
	  offset += count;
	  if (offset == size)
	    buf = xrealloc (buf, (size *= 2));
438
	}
439 440 441 442 443 444
      if (count < 0)
	goto perror_fail;

      if (offset < size)
	buf = xrealloc (buf, offset);
      inc->st.st_size = offset;
445
    }
Zack Weinberg committed
446

447
  inc->buffer = buf;
448
  return 0;
449 450 451 452

 perror_fail:
  cpp_error_from_errno (pfile, inc->name);
 fail:
453
  return 1;
454 455 456 457 458 459 460
}

static void
purge_cache (inc)
     struct include_file *inc;
{
  if (inc->buffer)
461
    {
462
#if MMAP_THRESHOLD
463
      if (inc->mapped)
464
	munmap ((PTR) inc->buffer, inc->st.st_size);
465
      else
466
#endif
467 468
	free ((PTR) inc->buffer);
      inc->buffer = NULL;
469
    }
470 471
}

472 473 474 475
/* Return 1 if the file named by FNAME has been included before in
   any context, 0 otherwise.  */
int
cpp_included (pfile, fname)
Zack Weinberg committed
476
     cpp_reader *pfile;
477
     const char *fname;
Zack Weinberg committed
478
{
479
  struct search_path *path;
480
  char *name, *n;
481
  splay_tree_node nd;
482

Neil Booth committed
483
  if (IS_ABSOLUTE_PATHNAME (fname))
484
    {
485 486 487
      /* Just look it up.  */
      nd = splay_tree_lookup (pfile->all_include_files, (splay_tree_key) fname);
      return (nd && nd->value);
488
    }
489 490
      
  /* Search directory path for the file.  */
491
  name = (char *) alloca (strlen (fname) + pfile->max_include_len + 2);
492
  for (path = CPP_OPTION (pfile, quote_include); path; path = path->next)
493
    {
494 495 496
      memcpy (name, path->name, path->len);
      name[path->len] = '/';
      strcpy (&name[path->len + 1], fname);
497
      if (CPP_OPTION (pfile, remap))
498 499
	n = remap_filename (pfile, name, path);
      else
500
	n = name;
501

502
      nd = splay_tree_lookup (pfile->all_include_files, (splay_tree_key) n);
503 504
      if (nd && nd->value)
	return 1;
505
    }
506
  return 0;
Zack Weinberg committed
507 508
}

509 510 511 512 513
/* Search for HEADER.  Return 0 if there is no such file (or it's
   un-openable), in which case an error code will be in errno.  If
   there is no include path to use it returns NO_INCLUDE_PATH,
   otherwise an include_file structure.  If this request originates
   from a #include_next directive, set INCLUDE_NEXT to true.  */
514 515

static struct include_file *
516
find_include_file (pfile, header, type)
517
     cpp_reader *pfile;
518
     const cpp_token *header;
519
     enum include_type type;
520
{
521
  const char *fname = (const char *) header->val.str.text;
522
  struct search_path *path;
523
  struct include_file *file;
524
  char *name, *n;
Zack Weinberg committed
525

Neil Booth committed
526
  if (IS_ABSOLUTE_PATHNAME (fname))
527
    return open_file (pfile, fname);
528 529

  /* For #include_next, skip in the search path past the dir in which
530 531
     the current file was found, but if it was found via an absolute
     path use the normal search logic.  */
532
  if (type == IT_INCLUDE_NEXT && pfile->buffer->inc->foundhere)
533 534 535 536
    path = pfile->buffer->inc->foundhere->next;
  else if (header->type == CPP_HEADER_NAME)
    path = CPP_OPTION (pfile, bracket_include);
  else
537
    path = search_from (pfile, type);
538 539 540 541 542 543 544

  if (path == NULL)
    {
      cpp_error (pfile, "No include path in which to find %s", fname);
      return NO_INCLUDE_PATH;
    }

545
  /* Search directory path for the file.  */
546
  name = (char *) alloca (strlen (fname) + pfile->max_include_len + 2);
547
  for (; path; path = path->next)
Zack Weinberg committed
548
    {
549 550 551
      memcpy (name, path->name, path->len);
      name[path->len] = '/';
      strcpy (&name[path->len + 1], fname);
552
      if (CPP_OPTION (pfile, remap))
553 554
	n = remap_filename (pfile, name, path);
      else
555
	n = name;
556

557
      file = open_file (pfile, n);
558
      if (file)
Zack Weinberg committed
559
	{
560 561
	  file->foundhere = path;
	  return file;
Zack Weinberg committed
562 563
	}
    }
564

565
  return 0;
Zack Weinberg committed
566 567
}

568
/* Not everyone who wants to set system-header-ness on a buffer can
569 570
   see the details of a buffer.  This is an exported interface because
   fix-header needs it.  */
571
void
572
cpp_make_system_header (pfile, syshdr, externc)
573
     cpp_reader *pfile;
574
     int syshdr, externc;
575
{
576 577 578 579 580
  int flags = 0;

  /* 1 = system header, 2 = system header to be treated as C.  */
  if (syshdr)
    flags = 1 + (externc != 0);
581
  pfile->buffer->sysp = flags;
582 583
  _cpp_do_file_change (pfile, FC_RENAME, pfile->buffer->nominal_fname,
		       pfile->buffer->lineno);
584 585
}

586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617
/* Report on all files that might benefit from a multiple include guard.
   Triggered by -H.  */
void
_cpp_report_missing_guards (pfile)
     cpp_reader *pfile;
{
  int banner = 0;
  splay_tree_foreach (pfile->all_include_files, report_missing_guard,
		      (PTR) &banner);
}

static int
report_missing_guard (n, b)
     splay_tree_node n;
     void *b;
{
  struct include_file *f = (struct include_file *) n->value;
  int *bannerp = (int *)b;

  if (f && f->cmacro == 0 && f->include_count == 1)
    {
      if (*bannerp == 0)
	{
	  fputs (_("Multiple include guards may be useful for:\n"), stderr);
	  *bannerp = 1;
	}
      fputs (f->name, stderr);
      putc ('\n', stderr);
    }
  return 0;
}

618 619 620 621 622 623 624 625 626 627
/* Create a dependency, or issue an error message as appropriate.   */
static void
handle_missing_header (pfile, fname, angle_brackets)
     cpp_reader *pfile;
     const char *fname;
     int angle_brackets;
{
  /* We will try making the RHS pfile->buffer->sysp after 3.0.  */
  int print_dep = CPP_PRINT_DEPS(pfile) > (angle_brackets
					   || pfile->system_include_depth);
628

629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653
  if (CPP_OPTION (pfile, print_deps_missing_files) && print_dep)
    {
      if (!angle_brackets || IS_ABSOLUTE_PATHNAME (fname))
	deps_add_dep (pfile->deps, fname);
      else
	{
	  /* If requested as a system header, assume it belongs in
	     the first system header directory.  */
	  struct search_path *ptr = CPP_OPTION (pfile, bracket_include);
	  char *p;
	  int len = 0, fname_len = strlen (fname);

	  if (ptr)
	    len = ptr->len;

	  p = (char *) alloca (len + fname_len + 2);
	  if (len)
	    {
	      memcpy (p, ptr->name, len);
	      p[len++] = '/';
	    }
	  memcpy (p + len, fname, fname_len + 1);
	  deps_add_dep (pfile->deps, p);
	}
    }
654 655 656 657 658 659
  /* If -M was specified, then don't count this as an error, because
     we can still produce correct output.  Otherwise, we can't produce
     correct output, because there may be dependencies we need inside
     the missing file, and we don't know what directory this missing
     file exists in.  FIXME: Use a future cpp_diagnotic_with_errno ()
     for both of these cases.  */
660
  else if (CPP_PRINT_DEPS (pfile) && ! print_dep)
661
    cpp_warning (pfile, "%s: %s", fname, xstrerror (errno));
662 663 664 665
  else
    cpp_error_from_errno (pfile, fname);
}

666 667 668
/* Returns non-zero if a buffer was stacked.  */
int
_cpp_execute_include (pfile, header, type)
669
     cpp_reader *pfile;
Neil Booth committed
670
     const cpp_token *header;
671
     enum include_type type;
672
{
673
  struct include_file *inc = find_include_file (pfile, header, type);
674

675 676 677 678
  if (inc == 0)
    handle_missing_header (pfile, (const char *) header->val.str.text,
			   header->type == CPP_HEADER_NAME);
  else if (inc != NO_INCLUDE_PATH)
679
    {
680
      if (header->type == CPP_HEADER_NAME)
681
	pfile->system_include_depth++;
682

683 684
      stack_include_file (pfile, inc);

685
      if (type == IT_IMPORT)
686
	_cpp_never_reread (inc);
687 688

      return 1;
689
    }
690 691

  return 0;
692 693
}

694 695 696
/* Locate HEADER, and determine whether it is newer than the current
   file.  If it cannot be located or dated, return -1, if it is newer
   newer, return 1, otherwise 0.  */
697
int
698
_cpp_compare_file_date (pfile, header)
699
     cpp_reader *pfile;
700
     const cpp_token *header;
701
{
702
  struct include_file *inc = find_include_file (pfile, header, 0);
703
  
704
  if (inc == NULL || inc == NO_INCLUDE_PATH)
705
    return -1;
706

707
  if (inc->fd > 0)
708 709 710 711
    {
      close (inc->fd);
      inc->fd = -1;
    }
712
    
713
  return inc->st.st_mtime > pfile->buffer->inc->st.st_mtime;
714 715 716
}


717
/* Push an input buffer and load it up with the contents of FNAME.
718
   If FNAME is "", read standard input.  */
719
int
720
_cpp_read_file (pfile, fname)
721 722 723
     cpp_reader *pfile;
     const char *fname;
{
724
  struct include_file *f = open_file (pfile, fname);
725

Zack Weinberg committed
726 727 728 729 730 731
  if (f == NULL)
    {
      cpp_error_from_errno (pfile, fname);
      return 0;
    }

732 733
  stack_include_file (pfile, f);
  return 1;
734 735
}

736 737 738 739 740 741 742 743 744 745 746 747 748
/* Do appropriate cleanup when a file buffer is popped off the input
   stack.  */
void
_cpp_pop_file_buffer (pfile, buf)
     cpp_reader *pfile;
     cpp_buffer *buf;
{
  struct include_file *inc = buf->inc;

  if (pfile->system_include_depth)
    pfile->system_include_depth--;
  if (pfile->include_depth)
    pfile->include_depth--;
Neil Booth committed
749

750 751
  /* Record the inclusion-preventing macro, which could be NULL
     meaning no controlling macro, if we haven't got it already.  */
752
  if (pfile->mi_state == MI_OUTSIDE && inc->cmacro == NULL)
753
    inc->cmacro = pfile->mi_cmacro;
Neil Booth committed
754 755 756

  /* Invalidate control macros in the #including file.  */
  pfile->mi_state = MI_FAILED;
757

758 759 760
  inc->refcnt--;
  if (inc->refcnt == 0 && DO_NOT_REREAD (inc))
    purge_cache (inc);
761 762
}

763 764
/* Returns the first place in the include chain to start searching for
   "" includes.  This involves stripping away the basename of the
765 766 767 768
   current file, unless -I- was specified.

   If we're handling -include or -imacros, use the "" chain, but with
   the preprocessor's cwd prepended.  */
769
static struct search_path *
770
search_from (pfile, type)
771
     cpp_reader *pfile;
772
     enum include_type type;
773 774 775 776
{
  cpp_buffer *buffer = pfile->buffer;
  unsigned int dlen;

777 778 779 780
  /* Command line uses the cwd, and does not cache the result.  */
  if (type == IT_CMDLINE)
    goto use_cwd;

781 782 783 784
  /* Ignore the current file's directory if -I- was given.  */
  if (CPP_OPTION (pfile, ignore_srcdir))
    return CPP_OPTION (pfile, quote_include);

785
  if (! buffer->search_cached)
786
    {
787
      buffer->search_cached = 1;
788

789
      dlen = lbasename (buffer->inc->name) - buffer->inc->name;
790

791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813
      if (dlen)
	{
	  /* We don't guarantee NAME is null-terminated.  This saves
	     allocating and freeing memory, and duplicating it when faking
	     buffers in cpp_push_buffer.  Drop a trailing '/'.  */
	  buffer->dir.name = buffer->inc->name;
	  if (dlen > 1)
	    dlen--;
	}
      else
	{
	use_cwd:
	  buffer->dir.name = ".";
	  dlen = 1;
	}

      if (dlen > pfile->max_include_len)
	pfile->max_include_len = dlen;

      buffer->dir.len = dlen;
      buffer->dir.next = CPP_OPTION (pfile, quote_include);
      buffer->dir.sysp = buffer->sysp;
    }
814 815 816 817

  return &buffer->dir;
}

818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886
/* The file_name_map structure holds a mapping of file names for a
   particular directory.  This mapping is read from the file named
   FILE_NAME_MAP_FILE in that directory.  Such a file can be used to
   map filenames on a file system with severe filename restrictions,
   such as DOS.  The format of the file name map file is just a series
   of lines with two tokens on each line.  The first token is the name
   to map, and the second token is the actual name to use.  */

struct file_name_map
{
  struct file_name_map *map_next;
  char *map_from;
  char *map_to;
};

#define FILE_NAME_MAP_FILE "header.gcc"

/* Read a space delimited string of unlimited length from a stdio
   file.  */

static char *
read_filename_string (ch, f)
     int ch;
     FILE *f;
{
  char *alloc, *set;
  int len;

  len = 20;
  set = alloc = xmalloc (len + 1);
  if (! is_space(ch))
    {
      *set++ = ch;
      while ((ch = getc (f)) != EOF && ! is_space(ch))
	{
	  if (set - alloc == len)
	    {
	      len *= 2;
	      alloc = xrealloc (alloc, len + 1);
	      set = alloc + len / 2;
	    }
	  *set++ = ch;
	}
    }
  *set = '\0';
  ungetc (ch, f);
  return alloc;
}

/* This structure holds a linked list of file name maps, one per directory.  */

struct file_name_map_list
{
  struct file_name_map_list *map_list_next;
  char *map_list_name;
  struct file_name_map *map_list_map;
};

/* Read the file name map file for DIRNAME.  */

static struct file_name_map *
read_name_map (pfile, dirname)
     cpp_reader *pfile;
     const char *dirname;
{
  register struct file_name_map_list *map_list_ptr;
  char *name;
  FILE *f;

887
  /* Check the cache of directories, and mappings in their remap file.  */
888 889 890 891 892 893 894 895
  for (map_list_ptr = CPP_OPTION (pfile, map_list); map_list_ptr;
       map_list_ptr = map_list_ptr->map_list_next)
    if (! strcmp (map_list_ptr->map_list_name, dirname))
      return map_list_ptr->map_list_map;

  map_list_ptr = ((struct file_name_map_list *)
		  xmalloc (sizeof (struct file_name_map_list)));
  map_list_ptr->map_list_name = xstrdup (dirname);
896 897

  /* The end of the list ends in NULL.  */
898
  map_list_ptr->map_list_map = NULL;
899 900 901 902 903 904 905

  name = (char *) alloca (strlen (dirname) + strlen (FILE_NAME_MAP_FILE) + 2);
  strcpy (name, dirname);
  if (*dirname)
    strcat (name, "/");
  strcat (name, FILE_NAME_MAP_FILE);
  f = fopen (name, "r");
906 907 908

  /* Silently return NULL if we cannot open.  */
  if (f)
909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929
    {
      int ch;
      int dirlen = strlen (dirname);

      while ((ch = getc (f)) != EOF)
	{
	  char *from, *to;
	  struct file_name_map *ptr;

	  if (is_space(ch))
	    continue;
	  from = read_filename_string (ch, f);
	  while ((ch = getc (f)) != EOF && is_hspace(ch))
	    ;
	  to = read_filename_string (ch, f);

	  ptr = ((struct file_name_map *)
		 xmalloc (sizeof (struct file_name_map)));
	  ptr->map_from = from;

	  /* Make the real filename absolute.  */
Neil Booth committed
930
	  if (IS_ABSOLUTE_PATHNAME (to))
931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950
	    ptr->map_to = to;
	  else
	    {
	      ptr->map_to = xmalloc (dirlen + strlen (to) + 2);
	      strcpy (ptr->map_to, dirname);
	      ptr->map_to[dirlen] = '/';
	      strcpy (ptr->map_to + dirlen + 1, to);
	      free (to);
	    }	      

	  ptr->map_next = map_list_ptr->map_list_map;
	  map_list_ptr->map_list_map = ptr;

	  while ((ch = getc (f)) != '\n')
	    if (ch == EOF)
	      break;
	}
      fclose (f);
    }
  
951
  /* Add this information to the cache.  */
952 953 954 955 956 957
  map_list_ptr->map_list_next = CPP_OPTION (pfile, map_list);
  CPP_OPTION (pfile, map_list) = map_list_ptr;

  return map_list_ptr->map_list_map;
}  

958 959
/* Remap an unsimplified path NAME based on the file_name_map (if any)
   for LOC.  */
960 961 962 963
static char *
remap_filename (pfile, name, loc)
     cpp_reader *pfile;
     char *name;
964
     struct search_path *loc;
965 966
{
  struct file_name_map *map;
967
  const char *from, *p;
968
  char *dir;
969 970

  if (! loc->name_map)
971
    {
972 973 974 975 976
      /* Get a null-terminated path.  */
      char *dname = alloca (loc->len + 1);
      memcpy (dname, loc->name, loc->len);
      dname[loc->len] = '\0';

977
      loc->name_map = read_name_map (pfile, dname);
978 979 980
      if (! loc->name_map)
	return name;
    }
981
  
982
  /* This works since NAME has not been simplified yet.  */
983
  from = name + loc->len + 1;
984 985 986 987 988 989 990 991 992 993 994 995 996
  
  for (map = loc->name_map; map; map = map->map_next)
    if (!strcmp (map->map_from, from))
      return map->map_to;

  /* Try to find a mapping file for the particular directory we are
     looking in.  Thus #include <sys/types.h> will look up sys/types.h
     in /usr/include/header.gcc and look up types.h in
     /usr/include/sys/header.gcc.  */
  p = strrchr (name, '/');
  if (!p)
    return name;

997
  /* We know p != name as absolute paths don't call remap_filename.  */
998
  if (p == name)
999 1000 1001 1002 1003 1004
    cpp_ice (pfile, "absolute file name in remap_filename");

  dir = (char *) alloca (p - name + 1);
  memcpy (dir, name, p - name);
  dir[p - name] = '\0';
  from = p + 1;
1005 1006
  
  for (map = read_name_map (pfile, dir); map; map = map->map_next)
1007
    if (! strcmp (map->map_from, from))
1008 1009 1010 1011 1012
      return map->map_to;

  return name;
}

1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032
/* Returns true if it is safe to remove the final component of path,
   when it is followed by a ".." component.  We use lstat to avoid
   symlinks if we have it.  If not, we can still catch errors with
   stat ().  */
static int
remove_component_p (path)
     const char *path;
{
  struct stat s;
  int result;

#ifdef HAVE_LSTAT
  result = lstat (path, &s);
#else
  result = stat (path, &s);
#endif

  return result == 0 && S_ISDIR (s.st_mode);
}

1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043
/* Simplify a path name in place, deleting redundant components.  This
   reduces OS overhead and guarantees that equivalent paths compare
   the same (modulo symlinks).

   Transforms made:
   foo/bar/../quux	foo/quux
   foo/./bar		foo/bar
   foo//bar		foo/bar
   /../quux		/quux
   //quux		//quux  (POSIX allows leading // as a namespace escape)

1044 1045 1046 1047
   Guarantees no trailing slashes.  All transforms reduce the length
   of the string.  Returns PATH.  errno is 0 if no error occurred;
   nonzero if an error occurred when using stat () or lstat ().  */

1048
char *
1049
_cpp_simplify_pathname (path)
1050
    char *path;
1051
{
1052 1053 1054 1055 1056 1057 1058 1059 1060
#ifndef VMS
  char *from, *to;
  char *base, *orig_base;
  int absolute = 0;

  errno = 0;
  /* Don't overflow the empty path by putting a '.' in it below.  */
  if (*path == '\0')
    return path;
1061

1062
#if defined (HAVE_DOS_BASED_FILE_SYSTEM)
1063 1064 1065
  /* Convert all backslashes to slashes. */
  for (from = path; *from; from++)
    if (*from == '\\') *from = '/';
1066
    
1067 1068 1069 1070
  /* Skip over leading drive letter if present. */
  if (ISALPHA (path[0]) && path[1] == ':')
    from = to = &path[2];
  else
1071
    from = to = path;
1072 1073
#else
  from = to = path;
1074 1075
#endif
    
1076 1077
  /* Remove redundant leading /s.  */
  if (*from == '/')
1078
    {
1079 1080 1081 1082
      absolute = 1;
      to++;
      from++;
      if (*from == '/')
1083
	{
1084 1085 1086 1087 1088 1089
	  if (*++from == '/')
	    /* 3 or more initial /s are equivalent to 1 /.  */
	    while (*++from == '/');
	  else
	    /* On some hosts // differs from /; Posix allows this.  */
	    to++;
1090 1091
	}
    }
1092 1093 1094

  base = orig_base = to;
  for (;;)
1095
    {
1096 1097 1098 1099 1100 1101 1102 1103 1104
      int move_base = 0;

      while (*from == '/')
	from++;

      if (*from == '\0')
	break;

      if (*from == '.')
1105
	{
1106 1107 1108
	  if (from[1] == '\0')
	    break;
	  if (from[1] == '/')
1109
	    {
1110 1111
	      from += 2;
	      continue;
1112
	    }
1113
	  else if (from[1] == '.' && (from[2] == '/' || from[2] == '\0'))
1114
	    {
1115 1116
	      /* Don't simplify if there was no previous component.  */
	      if (absolute && orig_base == to)
1117
		{
1118 1119
		  from += 2;
		  continue;
1120
		}
1121 1122 1123
	      /* Don't simplify if the previous component was "../",
		 or if an error has already occurred with (l)stat.  */
	      if (base != to && errno == 0)
1124
		{
1125 1126 1127 1128 1129 1130 1131 1132 1133
		  /* We don't back up if it's a symlink.  */
		  *to = '\0';
		  if (remove_component_p (path))
		    {
		      while (to > base && *to != '/')
			to--;
		      from += 2;
		      continue;
		    }
1134
		}
1135
	      move_base = 1;
1136
	    }
1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148
	}

      /* Add the component separator.  */
      if (to > orig_base)
	*to++ = '/';

      /* Copy this component until the trailing null or '/'.  */
      while (*from != '\0' && *from != '/')
	*to++ = *from++;

      if (move_base)
	base = to;
1149 1150
    }
    
1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161
  /* Change the empty string to "." so that it is not treated as stdin.
     Null terminate.  */
  if (to == path)
    *to++ = '.';
  *to = '\0';

  return path;
#else /* VMS  */
  errno = 0;
  return path;
#endif /* !VMS  */
1162
}