1 /* Part of CPP library. (include file handling)
2 Copyright (C) 1986, 1987, 1989, 1992, 1993, 1994, 1995, 1998,
3 1999, 2000, 2001, 2002, 2003 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
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. */
26 #include "coretypes.h"
32 #include "splay-tree.h"
33 #ifdef ENABLE_VALGRIND_CHECKING
36 /* Avoid #ifdef:s when we can help it. */
37 #define VALGRIND_DISCARD(x)
41 # include <sys/mman.h>
42 # ifndef MMAP_THRESHOLD
43 # define MMAP_THRESHOLD 3 /* Minimum page count to mmap the file. */
46 # define TEST_THRESHOLD(size, pagesize) \
47 (size / pagesize >= MMAP_THRESHOLD && (size % pagesize) != 0)
48 /* Use mmap if the file is big enough to be worth it (controlled
49 by MMAP_THRESHOLD) and if we can safely count on there being
50 at least one readable NUL byte after the end of the file's
51 contents. This is true for all tested operating systems when
52 the file size is not an exact multiple of the page size. */
54 # define SHOULD_MMAP(size, pagesize) TEST_THRESHOLD (size, pagesize)
56 # define WIN32_LEAN_AND_MEAN
58 /* Cygwin can't correctly emulate mmap under Windows 9x style systems so
59 disallow use of mmap on those systems. Windows 9x does not zero fill
60 memory at EOF and beyond, as required. */
61 # define SHOULD_MMAP(size, pagesize) ((GetVersion() & 0x80000000) \
62 ? 0 : TEST_THRESHOLD (size, pagesize))
66 #else /* No MMAP_FILE */
67 # undef MMAP_THRESHOLD
68 # define MMAP_THRESHOLD 0
75 /* If errno is inspected immediately after a system call fails, it will be
76 nonzero, and no error number will ever be zero. */
84 /* Suppress warning about function macros used w/o arguments in traditional
85 C. It is unlikely that glibc's strcmp macro helps this file at all. */
88 /* This structure is used for the table of all includes. */
90 const char *name; /* actual path name of file */
91 const char *header_name; /* the original header found */
92 const cpp_hashnode *cmacro; /* macro, if any, preventing reinclusion. */
93 const struct cpp_path *foundhere;
94 /* location in search path where file was
95 found, for #include_next and sysp. */
96 const unsigned char *buffer; /* pointer to cached file contents */
97 struct stat st; /* copy of stat(2) data for file */
98 int fd; /* fd open on file (short term storage only) */
99 int err_no; /* errno obtained if opening a file failed */
100 unsigned short include_count; /* number of times file has been read */
101 unsigned short refcnt; /* number of stacked buffers using this file */
102 unsigned char mapped; /* file buffer is mmapped */
103 unsigned char pch; /* 0: file not known to be a PCH.
105 (on return from find_include_file).
106 2: file is not and never will be a valid
108 3: file is always a valid precompiled
112 /* Variable length record files on VMS will have a stat size that includes
113 record control characters that won't be included in the read size. */
115 # define FAB_C_VAR 2 /* variable length records (see Starlet fabdef.h) */
116 # define STAT_SIZE_TOO_BIG(ST) ((ST).st_fab_rfm == FAB_C_VAR)
118 # define STAT_SIZE_TOO_BIG(ST) 0
121 /* The cmacro works like this: If it's NULL, the file is to be
122 included again. If it's NEVER_REREAD, the file is never to be
123 included again. Otherwise it is a macro hashnode, and the file is
124 to be included again if the macro is defined. */
125 #define NEVER_REREAD ((const cpp_hashnode *) -1)
126 #define DO_NOT_REREAD(inc) \
127 ((inc)->cmacro && ((inc)->cmacro == NEVER_REREAD \
128 || (inc)->cmacro->type == NT_MACRO))
129 #define NO_INCLUDE_PATH ((struct include_file *) -1)
130 #define INCLUDE_PCH_P(F) (((F)->pch & 1) != 0)
132 static struct file_name_map *read_name_map
133 PARAMS ((cpp_reader *, const char *));
134 static char *read_filename_string PARAMS ((int, FILE *));
135 static char *remap_filename PARAMS ((cpp_reader *, char *,
137 static struct cpp_path *search_from PARAMS ((cpp_reader *,
139 static struct include_file *
140 find_include_file PARAMS ((cpp_reader *, const cpp_token *,
142 static struct include_file *open_file PARAMS ((cpp_reader *, const char *));
143 static struct include_file *validate_pch PARAMS ((cpp_reader *,
146 static struct include_file *open_file_pch PARAMS ((cpp_reader *,
148 static int read_include_file PARAMS ((cpp_reader *, struct include_file *));
149 static bool stack_include_file PARAMS ((cpp_reader *, struct include_file *));
150 static void purge_cache PARAMS ((struct include_file *));
151 static void destroy_node PARAMS ((splay_tree_value));
152 static int report_missing_guard PARAMS ((splay_tree_node, void *));
153 static splay_tree_node find_or_create_entry PARAMS ((cpp_reader *,
155 static void handle_missing_header PARAMS ((cpp_reader *, const char *, int));
156 static int remove_component_p PARAMS ((const char *));
158 /* Set up the splay tree we use to store information about all the
159 file names seen in this compilation. We also have entries for each
160 file we tried to open but failed; this saves system calls since we
161 don't try to open it again in future.
163 The key of each node is the file name, after processing by
164 cpp_simplify_path. The path name may or may not be absolute.
165 The path string has been malloced, as is automatically freed by
166 registering free () as the splay tree key deletion function.
168 A node's value is a pointer to a struct include_file, and is never
171 _cpp_init_includes (pfile)
174 pfile->all_include_files
175 = splay_tree_new ((splay_tree_compare_fn) strcmp,
176 (splay_tree_delete_key_fn) free,
180 /* Tear down the splay tree. */
182 _cpp_cleanup_includes (pfile)
185 splay_tree_delete (pfile->all_include_files);
188 /* Free a node. The path string is automatically freed. */
193 struct include_file *f = (struct include_file *) v;
202 /* Mark a file to not be reread (e.g. #import, read failure). */
204 _cpp_never_reread (file)
205 struct include_file *file;
207 file->cmacro = NEVER_REREAD;
210 /* Lookup a filename, which is simplified after making a copy, and
211 create an entry if none exists. */
212 static splay_tree_node
213 find_or_create_entry (pfile, fname)
217 splay_tree_node node;
218 struct include_file *file;
219 char *name = xstrdup (fname);
221 cpp_simplify_path (name);
222 node = splay_tree_lookup (pfile->all_include_files, (splay_tree_key) name);
227 file = xcnew (struct include_file);
229 file->header_name = name;
230 file->err_no = errno;
231 node = splay_tree_insert (pfile->all_include_files,
232 (splay_tree_key) file->name,
233 (splay_tree_value) file);
239 /* Enter a file name in the splay tree, for the sake of cpp_included. */
241 _cpp_fake_include (pfile, fname)
245 find_or_create_entry (pfile, fname);
248 /* Given a file name, look it up in the cache; if there is no entry,
249 create one with a non-NULL value (regardless of success in opening
250 the file). If the file doesn't exist or is inaccessible, this
251 entry is flagged so we don't attempt to open it again in the
252 future. If the file isn't open, open it. The empty string is
253 interpreted as stdin.
255 Returns an include_file structure with an open file descriptor on
256 success, or NULL on failure. */
257 static struct include_file *
258 open_file (pfile, filename)
260 const char *filename;
262 splay_tree_node nd = find_or_create_entry (pfile, filename);
263 struct include_file *file = (struct include_file *) nd->value;
267 /* Ugh. handle_missing_header () needs errno to be set. */
268 errno = file->err_no;
272 /* Don't reopen an idempotent file. */
273 if (DO_NOT_REREAD (file))
276 /* Don't reopen one which is already loaded. */
277 if (file->buffer != NULL)
280 /* We used to open files in nonblocking mode, but that caused more
281 problems than it solved. Do take care not to acquire a
282 controlling terminal by mistake (this can't happen on sane
283 systems, but paranoia is a virtue).
285 Use the three-argument form of open even though we aren't
286 specifying O_CREAT, to defend against broken system headers.
288 O_BINARY tells some runtime libraries (notably DJGPP) not to do
289 newline translation; we can handle DOS line breaks just fine
292 Special case: the empty string is translated to stdin. */
294 if (filename[0] == '\0')
298 /* For DJGPP redirected input is opened in text mode. Change it
300 if (! isatty (file->fd))
301 setmode (file->fd, O_BINARY);
305 file->fd = open (file->name, O_RDONLY | O_NOCTTY | O_BINARY, 0666);
307 if (file->fd != -1 && fstat (file->fd, &file->st) == 0)
309 if (!S_ISDIR (file->st.st_mode))
312 /* If it's a directory, we return null and continue the search
313 as the file we're looking for may appear elsewhere in the
320 file->err_no = errno;
324 static struct include_file *
325 validate_pch (pfile, filename, pchname)
327 const char *filename;
330 struct include_file * file;
332 file = open_file (pfile, pchname);
335 if ((file->pch & 2) == 0)
336 file->pch = pfile->cb.valid_pch (pfile, pchname, file->fd);
337 if (INCLUDE_PCH_P (file))
339 char *f = xstrdup (filename);
340 cpp_simplify_path (f);
341 file->header_name = f;
350 /* Like open_file, but also look for a precompiled header if (a) one exists
351 and (b) it is valid. */
352 static struct include_file *
353 open_file_pch (pfile, filename)
355 const char *filename;
357 if (filename[0] != '\0'
358 && pfile->cb.valid_pch != NULL)
360 size_t namelen = strlen (filename);
361 char *pchname = alloca (namelen + 5);
362 struct include_file * file;
365 memcpy (pchname, filename, namelen);
366 memcpy (pchname + namelen, ".gch", 5);
368 nd = find_or_create_entry (pfile, pchname);
369 file = (struct include_file *) nd->value;
373 if (stat (file->name, &file->st) == 0 && S_ISDIR (file->st.st_mode))
377 size_t subname_len = namelen + 64;
378 char *subname = xmalloc (subname_len);
380 thedir = opendir (pchname);
383 memcpy (subname, pchname, namelen + 4);
384 subname[namelen+4] = '/';
385 while ((d = readdir (thedir)) != NULL)
387 if (strlen (d->d_name) + namelen + 7 > subname_len)
389 subname_len = strlen (d->d_name) + namelen + 64;
390 subname = xrealloc (subname, subname_len);
392 strcpy (subname + namelen + 5, d->d_name);
393 file = validate_pch (pfile, filename, subname);
401 file = validate_pch (pfile, filename, pchname);
406 return open_file (pfile, filename);
409 /* Place the file referenced by INC into a new buffer on the buffer
410 stack, unless there are errors, or the file is not re-included
411 because of e.g. multiple-include guards. Returns true if a buffer
414 stack_include_file (pfile, inc)
416 struct include_file *inc;
420 const char *filename;
422 if (DO_NOT_REREAD (inc))
425 sysp = MAX ((pfile->map ? pfile->map->sysp : 0),
426 (inc->foundhere ? inc->foundhere->sysp : 0));
428 /* Add the file to the dependencies on its first inclusion. */
429 if (CPP_OPTION (pfile, deps.style) > !!sysp && !inc->include_count)
431 if (pfile->buffer || CPP_OPTION (pfile, deps.ignore_main_file) == 0)
432 deps_add_dep (pfile->deps, inc->name);
435 /* PCH files get dealt with immediately. */
436 if (INCLUDE_PCH_P (inc))
438 pfile->cb.read_pch (pfile, inc->name, inc->fd, inc->header_name);
447 if (read_include_file (pfile, inc))
449 /* If an error occurs, do not try to read this file again. */
450 _cpp_never_reread (inc);
453 /* Mark a regular, zero-length file never-reread. We read it,
454 NUL-terminate it, and stack it once, so preprocessing a main
455 file of zero length does not raise an error. */
456 if (S_ISREG (inc->st.st_mode) && inc->st.st_size == 0)
457 _cpp_never_reread (inc);
463 /* We don't want MI guard advice for the main file. */
464 inc->include_count++;
467 fp = cpp_push_buffer (pfile, inc->buffer, inc->st.st_size,
468 /* from_stage3 */ CPP_OPTION (pfile, preprocessed), 0);
472 /* Initialize controlling macro state. */
473 pfile->mi_valid = true;
474 pfile->mi_cmacro = 0;
476 /* Generate the call back. */
477 filename = inc->name;
478 if (*filename == '\0')
479 filename = "<stdin>";
480 _cpp_do_file_change (pfile, LC_ENTER, filename, 1, sysp);
485 /* Read the file referenced by INC into the file cache.
487 If fd points to a plain file, we might be able to mmap it; we can
488 definitely allocate the buffer all at once. If fd is a pipe or
489 terminal, we can't do either. If fd is something weird, like a
490 block device, we don't want to read it at all.
492 Unfortunately, different systems use different st.st_mode values
493 for pipes: some have S_ISFIFO, some S_ISSOCK, some are buggy and
494 zero the entire struct stat except a couple fields. Hence we don't
495 even try to figure out what something is, except for plain files
498 FIXME: Flush file cache and try again if we run out of memory. */
500 read_include_file (pfile, inc)
502 struct include_file *inc;
504 ssize_t size, offset, count;
507 static int pagesize = -1;
510 if (S_ISREG (inc->st.st_mode))
512 /* off_t might have a wider range than ssize_t - in other words,
513 the max size of a file might be bigger than the address
514 space. We can't handle a file that large. (Anyone with
515 a single source file bigger than 2GB needs to rethink
516 their coding style.) Some systems (e.g. AIX 4.1) define
517 SSIZE_MAX to be much smaller than the actual range of the
518 type. Use INTTYPE_MAXIMUM unconditionally to ensure this
520 if (inc->st.st_size > INTTYPE_MAXIMUM (ssize_t))
522 cpp_error (pfile, DL_ERROR, "%s is too large", inc->name);
525 size = inc->st.st_size;
530 pagesize = getpagesize ();
532 if (SHOULD_MMAP (size, pagesize))
534 buf = (uchar *) mmap (0, size, PROT_READ, MAP_PRIVATE, inc->fd, 0);
535 if (buf == (uchar *) -1)
538 /* We must tell Valgrind that the byte at buf[size] is actually
539 readable. Discard the handle to avoid handle leak. */
540 VALGRIND_DISCARD (VALGRIND_MAKE_READABLE (buf + size, 1));
547 buf = (uchar *) xmalloc (size + 1);
549 while (offset < size)
551 count = read (inc->fd, buf + offset, size - offset);
556 if (!STAT_SIZE_TOO_BIG (inc->st))
557 cpp_error (pfile, DL_WARNING,
558 "%s is shorter than expected", inc->name);
560 buf = xrealloc (buf, size + 1);
561 inc->st.st_size = size;
566 /* The lexer requires that the buffer be NUL-terminated. */
570 else if (S_ISBLK (inc->st.st_mode))
572 cpp_error (pfile, DL_ERROR, "%s is a block device", inc->name);
577 /* 8 kilobytes is a sensible starting size. It ought to be
578 bigger than the kernel pipe buffer, and it's definitely
579 bigger than the majority of C source files. */
582 buf = (uchar *) xmalloc (size + 1);
584 while ((count = read (inc->fd, buf + offset, size - offset)) > 0)
590 buf = xrealloc (buf, size + 1);
596 if (offset + 1 < size)
597 buf = xrealloc (buf, offset + 1);
599 /* The lexer requires that the buffer be NUL-terminated. */
601 inc->st.st_size = offset;
608 cpp_errno (pfile, DL_ERROR, inc->name);
613 /* Drop INC's buffer from memory, if we are unlikely to need it again. */
616 struct include_file *inc;
623 /* Undo the previous annotation for the
624 known-zero-byte-after-mmap. Discard the handle to avoid
626 VALGRIND_DISCARD (VALGRIND_MAKE_NOACCESS (inc->buffer
627 + inc->st.st_size, 1));
628 munmap ((PTR) inc->buffer, inc->st.st_size);
632 free ((PTR) inc->buffer);
637 /* Return 1 if the file named by FNAME has been included before in
638 any context, 0 otherwise. */
640 cpp_included (pfile, fname)
644 struct cpp_path *path;
648 if (IS_ABSOLUTE_PATHNAME (fname))
650 /* Just look it up. */
651 nd = splay_tree_lookup (pfile->all_include_files, (splay_tree_key) fname);
652 return (nd && nd->value);
655 /* Search directory path for the file. */
656 name = (char *) alloca (strlen (fname) + pfile->max_include_len + 2);
657 for (path = pfile->quote_include; path; path = path->next)
659 memcpy (name, path->name, path->len);
660 name[path->len] = '/';
661 strcpy (&name[path->len + 1], fname);
662 if (CPP_OPTION (pfile, remap))
663 n = remap_filename (pfile, name, path);
667 nd = splay_tree_lookup (pfile->all_include_files, (splay_tree_key) n);
674 /* Search for HEADER. Return 0 if there is no such file (or it's
675 un-openable), in which case an error code will be in errno. If
676 there is no include path to use it returns NO_INCLUDE_PATH,
677 otherwise an include_file structure. If this request originates
678 from a directive of TYPE #include_next, set INCLUDE_NEXT to true. */
679 static struct include_file *
680 find_include_file (pfile, header, type)
682 const cpp_token *header;
683 enum include_type type;
685 const char *fname = (const char *) header->val.str.text;
686 struct cpp_path *path;
687 struct include_file *file;
690 if (IS_ABSOLUTE_PATHNAME (fname))
691 return open_file_pch (pfile, fname);
693 /* For #include_next, skip in the search path past the dir in which
694 the current file was found, but if it was found via an absolute
695 path use the normal search logic. */
696 if (type == IT_INCLUDE_NEXT && pfile->buffer->inc->foundhere)
697 path = pfile->buffer->inc->foundhere->next;
698 else if (header->type == CPP_HEADER_NAME)
699 path = pfile->bracket_include;
701 path = search_from (pfile, type);
705 cpp_error (pfile, DL_ERROR, "no include path in which to find %s",
707 return NO_INCLUDE_PATH;
710 /* Search directory path for the file. */
711 name = (char *) alloca (strlen (fname) + pfile->max_include_len + 2);
712 for (; path; path = path->next)
715 memcpy (name, path->name, len);
716 /* Don't turn / into // or // into ///; // may be a namespace
718 if (name[len-1] == '/')
721 strcpy (&name[len + 1], fname);
722 if (CPP_OPTION (pfile, remap))
723 n = remap_filename (pfile, name, path);
727 file = open_file_pch (pfile, n);
730 file->foundhere = path;
738 /* Not everyone who wants to set system-header-ness on a buffer can
739 see the details of a buffer. This is an exported interface because
740 fix-header needs it. */
742 cpp_make_system_header (pfile, syshdr, externc)
748 /* 1 = system header, 2 = system header to be treated as C. */
750 flags = 1 + (externc != 0);
751 _cpp_do_file_change (pfile, LC_RENAME, pfile->map->to_file,
752 SOURCE_LINE (pfile->map, pfile->line), flags);
755 /* Report on all files that might benefit from a multiple include guard.
758 _cpp_report_missing_guards (pfile)
762 splay_tree_foreach (pfile->all_include_files, report_missing_guard,
766 /* Callback function for splay_tree_foreach(). */
768 report_missing_guard (n, b)
772 struct include_file *f = (struct include_file *) n->value;
773 int *bannerp = (int *) b;
775 if (f && f->cmacro == 0 && f->include_count == 1)
779 fputs (_("Multiple include guards may be useful for:\n"), stderr);
782 fputs (f->name, stderr);
788 /* Create a dependency for file FNAME, or issue an error message as
789 appropriate. ANGLE_BRACKETS is nonzero if the file was bracketed
792 handle_missing_header (pfile, fname, angle_brackets)
798 = CPP_OPTION (pfile, deps.style) > (angle_brackets || pfile->map->sysp);
800 if (CPP_OPTION (pfile, deps.missing_files) && print_dep)
801 deps_add_dep (pfile->deps, fname);
802 /* If -M was specified, then don't count this as an error, because
803 we can still produce correct output. Otherwise, we can't produce
804 correct output, because there may be dependencies we need inside
805 the missing file, and we don't know what directory this missing
808 cpp_errno (pfile, CPP_OPTION (pfile, deps.style) && ! print_dep
809 ? DL_WARNING: DL_ERROR, fname);
812 /* Handles #include-family directives (distinguished by TYPE),
813 including HEADER, and the command line -imacros and -include.
814 Returns true if a buffer was stacked. */
816 _cpp_execute_include (pfile, header, type)
818 const cpp_token *header;
819 enum include_type type;
821 bool stacked = false;
822 struct include_file *inc = find_include_file (pfile, header, type);
825 handle_missing_header (pfile, (const char *) header->val.str.text,
826 header->type == CPP_HEADER_NAME);
827 else if (inc != NO_INCLUDE_PATH)
829 stacked = stack_include_file (pfile, inc);
831 if (type == IT_IMPORT)
832 _cpp_never_reread (inc);
838 /* Locate HEADER, and determine whether it is newer than the current
839 file. If it cannot be located or dated, return -1, if it is newer
840 newer, return 1, otherwise 0. */
842 _cpp_compare_file_date (pfile, header)
844 const cpp_token *header;
846 struct include_file *inc = find_include_file (pfile, header, 0);
848 if (inc == NULL || inc == NO_INCLUDE_PATH)
857 return inc->st.st_mtime > pfile->buffer->inc->st.st_mtime;
861 /* Push an input buffer and load it up with the contents of FNAME. If
862 FNAME is "", read standard input. Return true if a buffer was
865 _cpp_read_file (pfile, fname)
869 /* This uses open_file, because we don't allow a PCH to be used as
870 the toplevel compilation (that would prevent re-compiling an
871 existing PCH without deleting it first). */
872 struct include_file *f = open_file (pfile, fname);
876 cpp_errno (pfile, DL_ERROR, fname);
880 return stack_include_file (pfile, f);
883 /* Do appropriate cleanup when a file INC's buffer is popped off the
886 _cpp_pop_file_buffer (pfile, inc)
888 struct include_file *inc;
890 /* Record the inclusion-preventing macro, which could be NULL
891 meaning no controlling macro. */
892 if (pfile->mi_valid && inc->cmacro == NULL)
893 inc->cmacro = pfile->mi_cmacro;
895 /* Invalidate control macros in the #including file. */
896 pfile->mi_valid = false;
899 if (inc->refcnt == 0 && DO_NOT_REREAD (inc))
903 /* Returns the first place in the include chain to start searching for
904 "" includes. This involves stripping away the basename of the
905 current file, unless -I- was specified.
907 If we're handling -include or -imacros, use the "" chain, but with
908 the preprocessor's cwd prepended. */
909 static struct cpp_path *
910 search_from (pfile, type)
912 enum include_type type;
914 cpp_buffer *buffer = pfile->buffer;
917 /* Command line uses the cwd, and does not cache the result. */
918 if (type == IT_CMDLINE)
921 /* Ignore the current file's directory? */
922 if (pfile->quote_ignores_source_dir)
923 return pfile->quote_include;
925 if (! buffer->search_cached)
927 buffer->search_cached = 1;
929 dlen = lbasename (buffer->inc->name) - buffer->inc->name;
933 /* We don't guarantee NAME is null-terminated. This saves
934 allocating and freeing memory. Drop a trailing '/'. */
935 buffer->dir.name = (char *) buffer->inc->name;
942 buffer->dir.name = (char *) ".";
946 if (dlen > pfile->max_include_len)
947 pfile->max_include_len = dlen;
949 buffer->dir.len = dlen;
950 buffer->dir.next = pfile->quote_include;
951 buffer->dir.sysp = pfile->map->sysp;
957 /* The file_name_map structure holds a mapping of file names for a
958 particular directory. This mapping is read from the file named
959 FILE_NAME_MAP_FILE in that directory. Such a file can be used to
960 map filenames on a file system with severe filename restrictions,
961 such as DOS. The format of the file name map file is just a series
962 of lines with two tokens on each line. The first token is the name
963 to map, and the second token is the actual name to use. */
964 struct file_name_map {
965 struct file_name_map *map_next;
970 #define FILE_NAME_MAP_FILE "header.gcc"
972 /* Read a space delimited string of unlimited length from a stdio
975 read_filename_string (ch, f)
983 set = alloc = xmalloc (len + 1);
987 while ((ch = getc (f)) != EOF && ! is_space (ch))
989 if (set - alloc == len)
992 alloc = xrealloc (alloc, len + 1);
993 set = alloc + len / 2;
1003 /* This structure holds a linked list of file name maps, one per directory. */
1004 struct file_name_map_list {
1005 struct file_name_map_list *map_list_next;
1006 char *map_list_name;
1007 struct file_name_map *map_list_map;
1010 /* Read the file name map file for DIRNAME. */
1011 static struct file_name_map *
1012 read_name_map (pfile, dirname)
1014 const char *dirname;
1016 struct file_name_map_list *map_list_ptr;
1020 /* Check the cache of directories, and mappings in their remap file. */
1021 for (map_list_ptr = CPP_OPTION (pfile, map_list); map_list_ptr;
1022 map_list_ptr = map_list_ptr->map_list_next)
1023 if (! strcmp (map_list_ptr->map_list_name, dirname))
1024 return map_list_ptr->map_list_map;
1026 map_list_ptr = ((struct file_name_map_list *)
1027 xmalloc (sizeof (struct file_name_map_list)));
1028 map_list_ptr->map_list_name = xstrdup (dirname);
1030 /* The end of the list ends in NULL. */
1031 map_list_ptr->map_list_map = NULL;
1033 name = (char *) alloca (strlen (dirname) + strlen (FILE_NAME_MAP_FILE) + 2);
1034 strcpy (name, dirname);
1037 strcat (name, FILE_NAME_MAP_FILE);
1038 f = fopen (name, "r");
1040 /* Silently return NULL if we cannot open. */
1045 while ((ch = getc (f)) != EOF)
1048 struct file_name_map *ptr;
1052 from = read_filename_string (ch, f);
1053 while ((ch = getc (f)) != EOF && is_hspace (ch))
1055 to = read_filename_string (ch, f);
1057 ptr = ((struct file_name_map *)
1058 xmalloc (sizeof (struct file_name_map)));
1059 ptr->map_from = from;
1061 /* Make the real filename absolute. */
1062 if (IS_ABSOLUTE_PATHNAME (to))
1066 ptr->map_to = concat (dirname, "/", to, NULL);
1070 ptr->map_next = map_list_ptr->map_list_map;
1071 map_list_ptr->map_list_map = ptr;
1073 while ((ch = getc (f)) != '\n')
1080 /* Add this information to the cache. */
1081 map_list_ptr->map_list_next = CPP_OPTION (pfile, map_list);
1082 CPP_OPTION (pfile, map_list) = map_list_ptr;
1084 return map_list_ptr->map_list_map;
1087 /* Remap an unsimplified path NAME based on the file_name_map (if any)
1090 remap_filename (pfile, name, loc)
1093 struct cpp_path *loc;
1095 struct file_name_map *map;
1096 const char *from, *p;
1099 if (! loc->name_map)
1101 /* Get a null-terminated path. */
1102 char *dname = alloca (loc->len + 1);
1103 memcpy (dname, loc->name, loc->len);
1104 dname[loc->len] = '\0';
1106 loc->name_map = read_name_map (pfile, dname);
1107 if (! loc->name_map)
1111 /* This works since NAME has not been simplified yet. */
1112 from = name + loc->len + 1;
1114 for (map = loc->name_map; map; map = map->map_next)
1115 if (!strcmp (map->map_from, from))
1118 /* Try to find a mapping file for the particular directory we are
1119 looking in. Thus #include <sys/types.h> will look up sys/types.h
1120 in /usr/include/header.gcc and look up types.h in
1121 /usr/include/sys/header.gcc. */
1122 p = strrchr (name, '/');
1126 /* We know p != name as absolute paths don't call remap_filename. */
1128 cpp_error (pfile, DL_ICE, "absolute file name in remap_filename");
1130 dir = (char *) alloca (p - name + 1);
1131 memcpy (dir, name, p - name);
1132 dir[p - name] = '\0';
1135 for (map = read_name_map (pfile, dir); map; map = map->map_next)
1136 if (! strcmp (map->map_from, from))
1142 /* Set the include chain for "" to QUOTE, for <> to BRACKET. If
1143 QUOTE_IGNORES_SOURCE_DIR, then "" includes do not look in the
1144 directory of the including file.
1146 If BRACKET does not lie in the QUOTE chain, it is set to QUOTE. */
1148 cpp_set_include_chains (pfile, quote, bracket, quote_ignores_source_dir)
1150 cpp_path *quote, *bracket;
1151 int quote_ignores_source_dir;
1153 pfile->quote_include = quote;
1154 pfile->bracket_include = quote;
1155 pfile->quote_ignores_source_dir = quote_ignores_source_dir;
1156 pfile->max_include_len = 0;
1158 for (; quote; quote = quote->next)
1160 quote->name_map = NULL;
1161 quote->len = strlen (quote->name);
1162 if (quote->len > pfile->max_include_len)
1163 pfile->max_include_len = quote->len;
1164 if (quote == bracket)
1165 pfile->bracket_include = bracket;
1169 /* Returns true if it is safe to remove the final component of path,
1170 when it is followed by a ".." component. We use lstat to avoid
1171 symlinks if we have it. If not, we can still catch errors with
1174 remove_component_p (path)
1181 result = lstat (path, &s);
1183 result = stat (path, &s);
1186 /* There's no guarantee that errno will be unchanged, even on
1187 success. Cygwin's lstat(), for example, will often set errno to
1188 ENOSYS. In case of success, reset errno to zero. */
1192 return result == 0 && S_ISDIR (s.st_mode);
1195 /* Simplify a path name in place, deleting redundant components. This
1196 reduces OS overhead and guarantees that equivalent paths compare
1197 the same (modulo symlinks).
1200 foo/bar/../quux foo/quux
1204 //quux //quux (POSIX allows leading // as a namespace escape)
1206 Guarantees no trailing slashes. All transforms reduce the length
1207 of the string. Returns PATH. errno is 0 if no error occurred;
1208 nonzero if an error occurred when using stat () or lstat (). */
1210 cpp_simplify_path (path)
1211 char *path ATTRIBUTE_UNUSED;
1215 char *base, *orig_base;
1219 /* Don't overflow the empty path by putting a '.' in it below. */
1223 #if defined (HAVE_DOS_BASED_FILE_SYSTEM)
1224 /* Convert all backslashes to slashes. */
1225 for (from = path; *from; from++)
1226 if (*from == '\\') *from = '/';
1228 /* Skip over leading drive letter if present. */
1229 if (ISALPHA (path[0]) && path[1] == ':')
1230 from = to = &path[2];
1237 /* Remove redundant leading /s. */
1246 /* 3 or more initial /s are equivalent to 1 /. */
1247 while (*++from == '/');
1249 /* On some hosts // differs from /; Posix allows this. */
1254 base = orig_base = to;
1259 while (*from == '/')
1267 if (from[1] == '\0')
1274 else if (from[1] == '.' && (from[2] == '/' || from[2] == '\0'))
1276 /* Don't simplify if there was no previous component. */
1277 if (absolute && orig_base == to)
1282 /* Don't simplify if the previous component was "../",
1283 or if an error has already occurred with (l)stat. */
1284 if (base != to && errno == 0)
1286 /* We don't back up if it's a symlink. */
1288 if (remove_component_p (path))
1290 while (to > base && *to != '/')
1300 /* Add the component separator. */
1304 /* Copy this component until the trailing null or '/'. */
1305 while (*from != '\0' && *from != '/')
1312 /* Change the empty string to "." so that it is not treated as stdin.