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